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

app.bundle.js 1.2MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275
  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":161}],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":152}],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":152,"../../service/RTC/StreamEventTypes.js":154,"./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":151}],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":151,"../../service/RTC/RTCEvents.js":152,"../../service/RTC/StreamEventTypes.js":154,"../../service/UI/UIEvents":155,"../../service/desktopsharing/DesktopSharingEventTypes":158,"../../service/xmpp/XMPPEvents":161,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCBrowserType":8,"./RTCUtils.js":9,"events":162}],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. return constraints;
  1124. }
  1125. function RTCUtils(RTCService, onTemasysPluginReady)
  1126. {
  1127. var self = this;
  1128. this.service = RTCService;
  1129. if (RTCBrowserType.isFirefox()) {
  1130. var FFversion = RTCBrowserType.getFirefoxVersion();
  1131. if (FFversion >= 40) {
  1132. this.peerconnection = mozRTCPeerConnection;
  1133. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1134. this.pc_constraints = {};
  1135. this.attachMediaStream = function (element, stream) {
  1136. // srcObject is being standardized and FF will eventually
  1137. // support that unprefixed. FF also supports the
  1138. // "element.src = URL.createObjectURL(...)" combo, but that
  1139. // will be deprecated in favour of srcObject.
  1140. //
  1141. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1142. // https://github.com/webrtc/samples/issues/302
  1143. if(!element[0])
  1144. return;
  1145. element[0].mozSrcObject = stream;
  1146. element[0].play();
  1147. };
  1148. this.getStreamID = function (stream) {
  1149. var id = stream.id;
  1150. if (!id) {
  1151. var tracks = stream.getVideoTracks();
  1152. if (!tracks || tracks.length === 0) {
  1153. tracks = stream.getAudioTracks();
  1154. }
  1155. id = tracks[0].id;
  1156. }
  1157. return SDPUtil.filter_special_chars(id);
  1158. };
  1159. this.getVideoSrc = function (element) {
  1160. if(!element)
  1161. return null;
  1162. return element.mozSrcObject;
  1163. };
  1164. this.setVideoSrc = function (element, src) {
  1165. if(element)
  1166. element.mozSrcObject = src;
  1167. };
  1168. RTCSessionDescription = mozRTCSessionDescription;
  1169. RTCIceCandidate = mozRTCIceCandidate;
  1170. } else {
  1171. console.error(
  1172. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1173. window.location.href = 'unsupported_browser.html';
  1174. return;
  1175. }
  1176. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1177. this.peerconnection = webkitRTCPeerConnection;
  1178. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1179. this.attachMediaStream = function (element, stream) {
  1180. element.attr('src', webkitURL.createObjectURL(stream));
  1181. };
  1182. this.getStreamID = function (stream) {
  1183. // streams from FF endpoints have the characters '{' and '}'
  1184. // that make jQuery choke.
  1185. return SDPUtil.filter_special_chars(stream.id);
  1186. };
  1187. this.getVideoSrc = function (element) {
  1188. if(!element)
  1189. return null;
  1190. return element.getAttribute("src");
  1191. };
  1192. this.setVideoSrc = function (element, src) {
  1193. if(element)
  1194. element.setAttribute("src", src);
  1195. };
  1196. // DTLS should now be enabled by default but..
  1197. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1198. if (RTCBrowserType.isAndroid()) {
  1199. this.pc_constraints = {}; // disable DTLS on Android
  1200. }
  1201. if (!webkitMediaStream.prototype.getVideoTracks) {
  1202. webkitMediaStream.prototype.getVideoTracks = function () {
  1203. return this.videoTracks;
  1204. };
  1205. }
  1206. if (!webkitMediaStream.prototype.getAudioTracks) {
  1207. webkitMediaStream.prototype.getAudioTracks = function () {
  1208. return this.audioTracks;
  1209. };
  1210. }
  1211. }
  1212. // Detect IE/Safari
  1213. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1214. //AdapterJS.WebRTCPlugin.setLogLevel(
  1215. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1216. AdapterJS.webRTCReady(function (isPlugin) {
  1217. self.peerconnection = RTCPeerConnection;
  1218. self.getUserMedia = getUserMedia;
  1219. self.attachMediaStream = function (elSel, stream) {
  1220. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1221. return;
  1222. }
  1223. attachMediaStream(elSel[0], stream);
  1224. };
  1225. self.getStreamID = function (stream) {
  1226. var id = SDPUtil.filter_special_chars(stream.label);
  1227. return id;
  1228. };
  1229. self.getVideoSrc = function (element) {
  1230. if (!element) {
  1231. console.warn("Attempt to get video SRC of null element");
  1232. return null;
  1233. }
  1234. var children = element.children;
  1235. for (var i = 0; i !== children.length; ++i) {
  1236. if (children[i].name === 'streamId') {
  1237. return children[i].value;
  1238. }
  1239. }
  1240. //console.info(element.id + " SRC: " + src);
  1241. return null;
  1242. };
  1243. self.setVideoSrc = function (element, src) {
  1244. //console.info("Set video src: ", element, src);
  1245. if (!src) {
  1246. console.warn("Not attaching video stream, 'src' is null");
  1247. return;
  1248. }
  1249. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1250. var stream = AdapterJS.WebRTCPlugin.plugin
  1251. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1252. attachMediaStream(element, stream);
  1253. };
  1254. onTemasysPluginReady(isPlugin);
  1255. });
  1256. } else {
  1257. try {
  1258. console.log('Browser does not appear to be WebRTC-capable');
  1259. } catch (e) { }
  1260. window.location.href = 'unsupported_browser.html';
  1261. }
  1262. }
  1263. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1264. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1265. desktopStream) {
  1266. currentResolution = resolution;
  1267. var constraints = getConstraints(
  1268. um, resolution, bandwidth, fps, desktopStream);
  1269. console.info("Get media constraints", constraints);
  1270. var self = this;
  1271. try {
  1272. this.getUserMedia(constraints,
  1273. function (stream) {
  1274. console.log('onUserMediaSuccess');
  1275. self.setAvailableDevices(um, true);
  1276. success_callback(stream);
  1277. },
  1278. function (error) {
  1279. self.setAvailableDevices(um, false);
  1280. console.warn('Failed to get access to local media. Error ',
  1281. error, constraints);
  1282. if (failure_callback) {
  1283. failure_callback(error);
  1284. }
  1285. });
  1286. } catch (e) {
  1287. console.error('GUM failed: ', e);
  1288. if(failure_callback) {
  1289. failure_callback(e);
  1290. }
  1291. }
  1292. };
  1293. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1294. var devices = {};
  1295. if(um.indexOf("video") != -1) {
  1296. devices.video = available;
  1297. }
  1298. if(um.indexOf("audio") != -1) {
  1299. devices.audio = available;
  1300. }
  1301. this.service.setDeviceAvailability(devices);
  1302. };
  1303. /**
  1304. * We ask for audio and video combined stream in order to get permissions and
  1305. * not to ask twice.
  1306. */
  1307. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1308. function(devices, callback, usageOptions)
  1309. {
  1310. var self = this;
  1311. // Get AV
  1312. var successCallback = function (stream) {
  1313. if(callback)
  1314. callback(stream, usageOptions);
  1315. else
  1316. self.successCallback(stream, usageOptions);
  1317. };
  1318. if(!devices)
  1319. devices = ['audio', 'video'];
  1320. var newDevices = [];
  1321. if(usageOptions)
  1322. for(var i = 0; i < devices.length; i++) {
  1323. var device = devices[i];
  1324. if(usageOptions[device] === true)
  1325. newDevices.push(device);
  1326. }
  1327. else
  1328. newDevices = devices;
  1329. if(newDevices.length === 0) {
  1330. successCallback();
  1331. return;
  1332. }
  1333. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1334. // With FF/IE we can't split the stream into audio and video because FF
  1335. // doesn't support media stream constructors. So, we need to get the
  1336. // audio stream separately from the video stream using two distinct GUM
  1337. // calls. Not very user friendly :-( but we don't have many other
  1338. // options neither.
  1339. //
  1340. // Note that we pack those 2 streams in a single object and pass it to
  1341. // the successCallback method.
  1342. var obtainVideo = function (audioStream) {
  1343. self.getUserMediaWithConstraints(
  1344. ['video'],
  1345. function (videoStream) {
  1346. return successCallback({
  1347. audioStream: audioStream,
  1348. videoStream: videoStream
  1349. });
  1350. },
  1351. function (error) {
  1352. console.error(
  1353. 'failed to obtain video stream - stop', error);
  1354. self.errorCallback(error);
  1355. },
  1356. config.resolution || '360');
  1357. };
  1358. var obtainAudio = function () {
  1359. self.getUserMediaWithConstraints(
  1360. ['audio'],
  1361. function (audioStream) {
  1362. if (newDevices.indexOf('video') !== -1)
  1363. obtainVideo(audioStream);
  1364. },
  1365. function (error) {
  1366. console.error(
  1367. 'failed to obtain audio stream - stop', error);
  1368. self.errorCallback(error);
  1369. }
  1370. );
  1371. };
  1372. if (newDevices.indexOf('audio') !== -1) {
  1373. obtainAudio();
  1374. } else {
  1375. obtainVideo(null);
  1376. }
  1377. } else {
  1378. this.getUserMediaWithConstraints(
  1379. newDevices,
  1380. function (stream) {
  1381. successCallback(stream);
  1382. },
  1383. function (error) {
  1384. self.errorCallback(error);
  1385. },
  1386. config.resolution || '360');
  1387. }
  1388. };
  1389. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1390. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1391. // it's an object with two properties: audioStream, videoStream.
  1392. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1393. console.log('got', stream, stream.getAudioTracks().length,
  1394. stream.getVideoTracks().length);
  1395. this.handleLocalStream(stream, usageOptions);
  1396. };
  1397. RTCUtils.prototype.errorCallback = function (error) {
  1398. var self = this;
  1399. console.error('failed to obtain audio/video stream - trying audio only', error);
  1400. var resolution = getPreviousResolution(currentResolution);
  1401. if(typeof error == "object" && error.constraintName && error.name
  1402. && (error.name == "ConstraintNotSatisfiedError" ||
  1403. error.name == "OverconstrainedError") &&
  1404. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1405. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1406. && resolution != null)
  1407. {
  1408. self.getUserMediaWithConstraints(['audio', 'video'],
  1409. function (stream) {
  1410. return self.successCallback(stream);
  1411. }, function (error) {
  1412. return self.errorCallback(error);
  1413. }, resolution);
  1414. }
  1415. else {
  1416. self.getUserMediaWithConstraints(
  1417. ['audio'],
  1418. function (stream) {
  1419. return self.successCallback(stream);
  1420. },
  1421. function (error) {
  1422. console.error('failed to obtain audio/video stream - stop',
  1423. error);
  1424. return self.successCallback(null);
  1425. }
  1426. );
  1427. }
  1428. };
  1429. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions) {
  1430. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1431. // an object with two properties: audioStream, videoStream.
  1432. var audioStream, videoStream;
  1433. if(window.webkitMediaStream)
  1434. {
  1435. audioStream = new webkitMediaStream();
  1436. videoStream = new webkitMediaStream();
  1437. if(stream) {
  1438. var audioTracks = stream.getAudioTracks();
  1439. for (var i = 0; i < audioTracks.length; i++) {
  1440. audioStream.addTrack(audioTracks[i]);
  1441. }
  1442. var videoTracks = stream.getVideoTracks();
  1443. for (i = 0; i < videoTracks.length; i++) {
  1444. videoStream.addTrack(videoTracks[i]);
  1445. }
  1446. }
  1447. }
  1448. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1449. { // Firefox and Temasys plugin
  1450. if (stream && stream.audioStream)
  1451. audioStream = stream.audioStream;
  1452. else
  1453. audioStream = new DummyMediaStream("dummyAudio");
  1454. if (stream && stream.videoStream)
  1455. videoStream = stream.videoStream;
  1456. else
  1457. videoStream = new DummyMediaStream("dummyVideo");
  1458. }
  1459. var audioMuted = (usageOptions && usageOptions.audio === false),
  1460. videoMuted = (usageOptions && usageOptions.video === false);
  1461. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1462. videoGUM = (!usageOptions || usageOptions.video !== false);
  1463. this.service.createLocalStream(audioStream, "audio", null, null,
  1464. audioMuted, audioGUM);
  1465. this.service.createLocalStream(videoStream, "video", null, 'camera',
  1466. videoMuted, videoGUM);
  1467. };
  1468. function DummyMediaStream(id) {
  1469. this.id = id;
  1470. this.label = id;
  1471. this.stop = function() { };
  1472. this.getAudioTracks = function() { return []; };
  1473. this.getVideoTracks = function() { return []; };
  1474. }
  1475. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1476. var newStream = null;
  1477. if (window.webkitMediaStream) {
  1478. newStream = new webkitMediaStream();
  1479. if (newStream) {
  1480. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1481. for (var i = 0; i < tracks.length; i++) {
  1482. newStream.addTrack(tracks[i]);
  1483. }
  1484. }
  1485. }
  1486. else {
  1487. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1488. if (stream) {
  1489. newStream = stream;
  1490. } else {
  1491. newStream =
  1492. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1493. }
  1494. }
  1495. return newStream;
  1496. };
  1497. module.exports = RTCUtils;
  1498. },{"../../service/RTC/Resolutions":153,"../xmpp/SDPUtil":58,"./RTCBrowserType":8,"./adapter.screenshare":10}],10:[function(require,module,exports){
  1499. /*! adapterjs - custom version from - 2015-08-12 */
  1500. // Adapter's interface.
  1501. var AdapterJS = AdapterJS || {};
  1502. // Browserify compatibility
  1503. if(typeof exports !== 'undefined') {
  1504. module.exports = AdapterJS;
  1505. }
  1506. AdapterJS.options = AdapterJS.options || {};
  1507. // uncomment to get virtual webcams
  1508. // AdapterJS.options.getAllCams = true;
  1509. // uncomment to prevent the install prompt when the plugin in not yet installed
  1510. // AdapterJS.options.hidePluginInstallPrompt = true;
  1511. // AdapterJS version
  1512. AdapterJS.VERSION = '0.11.1';
  1513. // This function will be called when the WebRTC API is ready to be used
  1514. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1515. // the plugin
  1516. // You may Override this function to synchronise the start of your application
  1517. // with the WebRTC API being ready.
  1518. // If you decide not to override use this synchronisation, it may result in
  1519. // an extensive CPU usage on the plugin start (once per tab loaded)
  1520. // Params:
  1521. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1522. //
  1523. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1524. // The WebRTC API is ready.
  1525. // Override me and do whatever you want here
  1526. };
  1527. // Sets a callback function to be called when the WebRTC interface is ready.
  1528. // The first argument is the function to callback.\
  1529. // Throws an error if the first argument is not a function
  1530. AdapterJS.webRTCReady = function (callback) {
  1531. if (typeof callback !== 'function') {
  1532. throw new Error('Callback provided is not a function');
  1533. }
  1534. if (true === AdapterJS.onwebrtcreadyDone) {
  1535. // All WebRTC interfaces are ready, just call the callback
  1536. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1537. } else {
  1538. // will be triggered automatically when your browser/plugin is ready.
  1539. AdapterJS.onwebrtcready = callback;
  1540. }
  1541. };
  1542. // Plugin namespace
  1543. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1544. // The object to store plugin information
  1545. AdapterJS.WebRTCPlugin.pluginInfo = {
  1546. prefix : 'Tem',
  1547. plugName : 'TemWebRTCPlugin',
  1548. pluginId : 'plugin0',
  1549. type : 'application/x-temwebrtcplugin',
  1550. onload : '__TemWebRTCReady0',
  1551. portalLink : 'http://skylink.io/plugin/',
  1552. downloadLink : null, //set below
  1553. companyName: 'Temasys'
  1554. };
  1555. if(!!navigator.platform.match(/^Mac/i)) {
  1556. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1557. }
  1558. else if(!!navigator.platform.match(/^Win/i)) {
  1559. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1560. }
  1561. // Unique identifier of each opened page
  1562. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1563. // Use this whenever you want to call the plugin.
  1564. AdapterJS.WebRTCPlugin.plugin = null;
  1565. // Set log level for the plugin once it is ready.
  1566. // The different values are
  1567. // This is an asynchronous function that will run when the plugin is ready
  1568. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1569. // Defines webrtc's JS interface according to the plugin's implementation.
  1570. // Define plugin Browsers as WebRTC Interface.
  1571. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1572. // This function detects whether or not a plugin is installed.
  1573. // Checks if Not IE (firefox, for example), else if it's IE,
  1574. // we're running IE and do something. If not it is not supported.
  1575. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1576. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1577. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1578. // Inject the HTML DOM object element into the page.
  1579. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1580. // States of readiness that the plugin goes through when
  1581. // being injected and stated
  1582. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1583. NONE : 0, // no plugin use
  1584. INITIALIZING : 1, // Detected need for plugin
  1585. INJECTING : 2, // Injecting plugin
  1586. INJECTED: 3, // Plugin element injected but not usable yet
  1587. READY: 4 // Plugin ready to be used
  1588. };
  1589. // Current state of the plugin. You cannot use the plugin before this is
  1590. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1591. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1592. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1593. // Used to make sure AdapterJS.onwebrtcready is only called once
  1594. AdapterJS.onwebrtcreadyDone = false;
  1595. // Log levels for the plugin.
  1596. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1597. /*
  1598. Log outputs are prefixed in some cases.
  1599. INFO: Information reported by the plugin.
  1600. ERROR: Errors originating from within the plugin.
  1601. WEBRTC: Error originating from within the libWebRTC library
  1602. */
  1603. // From the least verbose to the most verbose
  1604. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1605. NONE : 'NONE',
  1606. ERROR : 'ERROR',
  1607. WARNING : 'WARNING',
  1608. INFO: 'INFO',
  1609. VERBOSE: 'VERBOSE',
  1610. SENSITIVE: 'SENSITIVE'
  1611. };
  1612. // Does a waiting check before proceeding to load the plugin.
  1613. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1614. // This methid will use an interval to wait for the plugin to be ready.
  1615. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1616. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1617. // This function will be called when plugin is ready. It sends necessary
  1618. // details to the plugin.
  1619. // The function will wait for the document to be ready and the set the
  1620. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1621. // indicating that it can start being requested.
  1622. // This function is not in the IE/Safari condition brackets so that
  1623. // TemPluginLoaded function might be called on Chrome/Firefox.
  1624. // This function is the only private function that is not encapsulated to
  1625. // allow the plugin method to be called.
  1626. __TemWebRTCReady0 = function () {
  1627. if (document.readyState === 'complete') {
  1628. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1629. AdapterJS.maybeThroughWebRTCReady();
  1630. } else {
  1631. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  1632. if (document.readyState === 'complete') {
  1633. // TODO: update comments, we wait for the document to be ready
  1634. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  1635. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1636. AdapterJS.maybeThroughWebRTCReady();
  1637. }
  1638. }, 100);
  1639. }
  1640. };
  1641. AdapterJS.maybeThroughWebRTCReady = function() {
  1642. if (!AdapterJS.onwebrtcreadyDone) {
  1643. AdapterJS.onwebrtcreadyDone = true;
  1644. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  1645. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  1646. }
  1647. }
  1648. };
  1649. // Text namespace
  1650. AdapterJS.TEXT = {
  1651. PLUGIN: {
  1652. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  1653. 'to work on this browser.',
  1654. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  1655. BUTTON: 'Install Now'
  1656. },
  1657. REFRESH: {
  1658. REQUIRE_REFRESH: 'Please refresh page',
  1659. BUTTON: 'Refresh Page'
  1660. }
  1661. };
  1662. // The result of ice connection states.
  1663. // - starting: Ice connection is starting.
  1664. // - checking: Ice connection is checking.
  1665. // - connected Ice connection is connected.
  1666. // - completed Ice connection is connected.
  1667. // - done Ice connection has been completed.
  1668. // - disconnected Ice connection has been disconnected.
  1669. // - failed Ice connection has failed.
  1670. // - closed Ice connection is closed.
  1671. AdapterJS._iceConnectionStates = {
  1672. starting : 'starting',
  1673. checking : 'checking',
  1674. connected : 'connected',
  1675. completed : 'connected',
  1676. done : 'completed',
  1677. disconnected : 'disconnected',
  1678. failed : 'failed',
  1679. closed : 'closed'
  1680. };
  1681. //The IceConnection states that has been fired for each peer.
  1682. AdapterJS._iceConnectionFiredStates = [];
  1683. // Check if WebRTC Interface is defined.
  1684. AdapterJS.isDefined = null;
  1685. // This function helps to retrieve the webrtc detected browser information.
  1686. // This sets:
  1687. // - webrtcDetectedBrowser: The browser agent name.
  1688. // - webrtcDetectedVersion: The browser version.
  1689. // - webrtcDetectedType: The types of webRTC support.
  1690. // - 'moz': Mozilla implementation of webRTC.
  1691. // - 'webkit': WebKit implementation of webRTC.
  1692. // - 'plugin': Using the plugin implementation.
  1693. AdapterJS.parseWebrtcDetectedBrowser = function () {
  1694. var hasMatch, checkMatch = navigator.userAgent.match(
  1695. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  1696. if (/trident/i.test(checkMatch[1])) {
  1697. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  1698. webrtcDetectedBrowser = 'IE';
  1699. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  1700. } else if (checkMatch[1] === 'Chrome') {
  1701. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  1702. if (hasMatch !== null) {
  1703. webrtcDetectedBrowser = 'opera';
  1704. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  1705. }
  1706. }
  1707. if (navigator.userAgent.indexOf('Safari')) {
  1708. if (typeof InstallTrigger !== 'undefined') {
  1709. webrtcDetectedBrowser = 'firefox';
  1710. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  1711. webrtcDetectedBrowser = 'IE';
  1712. } else if (
  1713. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  1714. webrtcDetectedBrowser = 'safari';
  1715. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  1716. webrtcDetectedBrowser = 'opera';
  1717. } else if (!!window.chrome) {
  1718. webrtcDetectedBrowser = 'chrome';
  1719. }
  1720. }
  1721. if (!webrtcDetectedBrowser) {
  1722. webrtcDetectedVersion = checkMatch[1];
  1723. }
  1724. if (!webrtcDetectedVersion) {
  1725. try {
  1726. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  1727. [navigator.appName, navigator.appVersion, '-?'];
  1728. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  1729. checkMatch.splice(1, 1, hasMatch[1]);
  1730. }
  1731. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  1732. } catch (error) { }
  1733. }
  1734. };
  1735. // To fix configuration as some browsers does not support
  1736. // the 'urls' attribute.
  1737. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  1738. if (pcConfig === null) {
  1739. return;
  1740. }
  1741. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  1742. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  1743. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  1744. delete pcConfig.iceServers[i].urls;
  1745. }
  1746. }
  1747. };
  1748. AdapterJS.addEvent = function(elem, evnt, func) {
  1749. if (elem.addEventListener) { // W3C DOM
  1750. elem.addEventListener(evnt, func, false);
  1751. } else if (elem.attachEvent) {// OLD IE DOM
  1752. elem.attachEvent('on'+evnt, func);
  1753. } else { // No much to do
  1754. elem[evnt] = func;
  1755. }
  1756. };
  1757. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  1758. // only inject once the page is ready
  1759. if (document.readyState !== 'complete') {
  1760. return;
  1761. }
  1762. var w = window;
  1763. var i = document.createElement('iframe');
  1764. i.style.position = 'fixed';
  1765. i.style.top = '-41px';
  1766. i.style.left = 0;
  1767. i.style.right = 0;
  1768. i.style.width = '100%';
  1769. i.style.height = '40px';
  1770. i.style.backgroundColor = '#ffffe1';
  1771. i.style.border = 'none';
  1772. i.style.borderBottom = '1px solid #888888';
  1773. i.style.zIndex = '9999999';
  1774. if(typeof i.style.webkitTransition === 'string') {
  1775. i.style.webkitTransition = 'all .5s ease-out';
  1776. } else if(typeof i.style.transition === 'string') {
  1777. i.style.transition = 'all .5s ease-out';
  1778. }
  1779. document.body.appendChild(i);
  1780. c = (i.contentWindow) ? i.contentWindow :
  1781. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  1782. c.document.open();
  1783. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  1784. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  1785. 'middle; cursor: default;">' + text + '</span>');
  1786. if(buttonText && buttonLink) {
  1787. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  1788. c.document.close();
  1789. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  1790. if (!!displayRefreshBar) {
  1791. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  1792. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  1793. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  1794. }
  1795. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  1796. e.preventDefault();
  1797. try {
  1798. event.cancelBubble = true;
  1799. } catch(error) { }
  1800. var pluginInstallInterval = setInterval(function(){
  1801. if(! isIE) {
  1802. navigator.plugins.refresh(false);
  1803. }
  1804. AdapterJS.WebRTCPlugin.isPluginInstalled(
  1805. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  1806. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  1807. function() {
  1808. clearInterval(pluginInstallInterval);
  1809. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  1810. },
  1811. function() { //Does nothing because not used here
  1812. });
  1813. } , 500);
  1814. });
  1815. }else {
  1816. c.document.close();
  1817. }
  1818. AdapterJS.addEvent(c.document, 'click', function() {
  1819. w.document.body.removeChild(i);
  1820. });
  1821. setTimeout(function() {
  1822. if(typeof i.style.webkitTransform === 'string') {
  1823. i.style.webkitTransform = 'translateY(40px)';
  1824. } else if(typeof i.style.transform === 'string') {
  1825. i.style.transform = 'translateY(40px)';
  1826. } else {
  1827. i.style.top = '0px';
  1828. }
  1829. }, 300);
  1830. };
  1831. // -----------------------------------------------------------
  1832. // Detected webrtc implementation. Types are:
  1833. // - 'moz': Mozilla implementation of webRTC.
  1834. // - 'webkit': WebKit implementation of webRTC.
  1835. // - 'plugin': Using the plugin implementation.
  1836. webrtcDetectedType = null;
  1837. // Detected webrtc datachannel support. Types are:
  1838. // - 'SCTP': SCTP datachannel support.
  1839. // - 'RTP': RTP datachannel support.
  1840. webrtcDetectedDCSupport = null;
  1841. // Set the settings for creating DataChannels, MediaStream for
  1842. // Cross-browser compability.
  1843. // - This is only for SCTP based support browsers.
  1844. // the 'urls' attribute.
  1845. checkMediaDataChannelSettings =
  1846. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  1847. if (typeof callback !== 'function') {
  1848. return;
  1849. }
  1850. var beOfferer = true;
  1851. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  1852. // Nightly version does not require MozDontOfferDataChannel for interop
  1853. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  1854. var isPeerFirefox = peerBrowserAgent === 'firefox';
  1855. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  1856. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  1857. // Resends an updated version of constraints for MozDataChannel to work
  1858. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  1859. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  1860. try {
  1861. delete constraints.mandatory.MozDontOfferDataChannel;
  1862. } catch (error) {
  1863. console.error('Failed deleting MozDontOfferDataChannel');
  1864. console.error(error);
  1865. }
  1866. } else if ((isLocalFirefox && !isPeerFirefox)) {
  1867. constraints.mandatory.MozDontOfferDataChannel = true;
  1868. }
  1869. if (!isLocalFirefox) {
  1870. // temporary measure to remove Moz* constraints in non Firefox browsers
  1871. for (var prop in constraints.mandatory) {
  1872. if (constraints.mandatory.hasOwnProperty(prop)) {
  1873. if (prop.indexOf('Moz') !== -1) {
  1874. delete constraints.mandatory[prop];
  1875. }
  1876. }
  1877. }
  1878. }
  1879. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  1880. // interopability of the media stream
  1881. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  1882. beOfferer = false;
  1883. }
  1884. callback(beOfferer, constraints);
  1885. };
  1886. // Handles the differences for all browsers ice connection state output.
  1887. // - Tested outcomes are:
  1888. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  1889. // - Chrome (answerer) : 'checking' > 'connected'
  1890. // - Firefox (offerer) : 'checking' > 'connected'
  1891. // - Firefox (answerer): 'checking' > 'connected'
  1892. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  1893. if (typeof callback !== 'function') {
  1894. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  1895. return;
  1896. }
  1897. peerId = (peerId) ? peerId : 'peer';
  1898. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  1899. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  1900. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  1901. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  1902. AdapterJS._iceConnectionFiredStates[peerId] = [];
  1903. }
  1904. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  1905. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  1906. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  1907. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  1908. setTimeout(function () {
  1909. AdapterJS._iceConnectionFiredStates[peerId]
  1910. .push(AdapterJS._iceConnectionStates.done);
  1911. callback(AdapterJS._iceConnectionStates.done);
  1912. }, 1000);
  1913. }
  1914. callback(iceConnectionState);
  1915. }
  1916. return;
  1917. };
  1918. // Firefox:
  1919. // - Creates iceServer from the url for Firefox.
  1920. // - Create iceServer with stun url.
  1921. // - Create iceServer with turn url.
  1922. // - Ignore the transport parameter from TURN url for FF version <=27.
  1923. // - Return null for createIceServer if transport=tcp.
  1924. // - FF 27 and above supports transport parameters in TURN url,
  1925. // - So passing in the full url to create iceServer.
  1926. // Chrome:
  1927. // - Creates iceServer from the url for Chrome M33 and earlier.
  1928. // - Create iceServer with stun url.
  1929. // - Chrome M28 & above uses below TURN format.
  1930. // Plugin:
  1931. // - Creates Ice Server for Plugin Browsers
  1932. // - If Stun - Create iceServer with stun url.
  1933. // - Else - Create iceServer with turn url
  1934. // - This is a WebRTC Function
  1935. createIceServer = null;
  1936. // Firefox:
  1937. // - Creates IceServers for Firefox
  1938. // - Use .url for FireFox.
  1939. // - Multiple Urls support
  1940. // Chrome:
  1941. // - Creates iceServers from the urls for Chrome M34 and above.
  1942. // - .urls is supported since Chrome M34.
  1943. // - Multiple Urls support
  1944. // Plugin:
  1945. // - Creates Ice Servers for Plugin Browsers
  1946. // - Multiple Urls support
  1947. // - This is a WebRTC Function
  1948. createIceServers = null;
  1949. //------------------------------------------------------------
  1950. //The RTCPeerConnection object.
  1951. RTCPeerConnection = null;
  1952. // Creates RTCSessionDescription object for Plugin Browsers
  1953. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  1954. RTCSessionDescription : null;
  1955. // Creates RTCIceCandidate object for Plugin Browsers
  1956. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  1957. RTCIceCandidate : null;
  1958. // Get UserMedia (only difference is the prefix).
  1959. // Code from Adam Barth.
  1960. getUserMedia = null;
  1961. // Attach a media stream to an element.
  1962. attachMediaStream = null;
  1963. // Re-attach a media stream to an element.
  1964. reattachMediaStream = null;
  1965. // Detected browser agent name. Types are:
  1966. // - 'firefox': Firefox browser.
  1967. // - 'chrome': Chrome browser.
  1968. // - 'opera': Opera browser.
  1969. // - 'safari': Safari browser.
  1970. // - 'IE' - Internet Explorer browser.
  1971. webrtcDetectedBrowser = null;
  1972. // Detected browser version.
  1973. webrtcDetectedVersion = null;
  1974. // Check for browser types and react accordingly
  1975. if (navigator.mozGetUserMedia) {
  1976. webrtcDetectedBrowser = 'firefox';
  1977. webrtcDetectedVersion = parseInt(navigator
  1978. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1979. webrtcDetectedType = 'moz';
  1980. webrtcDetectedDCSupport = 'SCTP';
  1981. RTCPeerConnection = function (pcConfig, pcConstraints) {
  1982. AdapterJS.maybeFixConfiguration(pcConfig);
  1983. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  1984. };
  1985. // The RTCSessionDescription object.
  1986. RTCSessionDescription = mozRTCSessionDescription;
  1987. window.RTCSessionDescription = RTCSessionDescription;
  1988. // The RTCIceCandidate object.
  1989. RTCIceCandidate = mozRTCIceCandidate;
  1990. window.RTCIceCandidate = RTCIceCandidate;
  1991. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1992. navigator.getUserMedia = window.getUserMedia;
  1993. // Shim for MediaStreamTrack.getSources.
  1994. MediaStreamTrack.getSources = function(successCb) {
  1995. setTimeout(function() {
  1996. var infos = [
  1997. { kind: 'audio', id: 'default', label:'', facing:'' },
  1998. { kind: 'video', id: 'default', label:'', facing:'' }
  1999. ];
  2000. successCb(infos);
  2001. }, 0);
  2002. };
  2003. createIceServer = function (url, username, password) {
  2004. var iceServer = null;
  2005. var url_parts = url.split(':');
  2006. if (url_parts[0].indexOf('stun') === 0) {
  2007. iceServer = { url : url };
  2008. } else if (url_parts[0].indexOf('turn') === 0) {
  2009. if (webrtcDetectedVersion < 27) {
  2010. var turn_url_parts = url.split('?');
  2011. if (turn_url_parts.length === 1 ||
  2012. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2013. iceServer = {
  2014. url : turn_url_parts[0],
  2015. credential : password,
  2016. username : username
  2017. };
  2018. }
  2019. } else {
  2020. iceServer = {
  2021. url : url,
  2022. credential : password,
  2023. username : username
  2024. };
  2025. }
  2026. }
  2027. return iceServer;
  2028. };
  2029. createIceServers = function (urls, username, password) {
  2030. var iceServers = [];
  2031. for (i = 0; i < urls.length; i++) {
  2032. var iceServer = createIceServer(urls[i], username, password);
  2033. if (iceServer !== null) {
  2034. iceServers.push(iceServer);
  2035. }
  2036. }
  2037. return iceServers;
  2038. };
  2039. attachMediaStream = function (element, stream) {
  2040. element.mozSrcObject = stream;
  2041. if (stream !== null)
  2042. element.play();
  2043. return element;
  2044. };
  2045. reattachMediaStream = function (to, from) {
  2046. to.mozSrcObject = from.mozSrcObject;
  2047. to.play();
  2048. return to;
  2049. };
  2050. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2051. if (!callback) {
  2052. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2053. ': 1 argument required, but only 0 present.');
  2054. }
  2055. return callback([]);
  2056. };
  2057. // Fake get{Video,Audio}Tracks
  2058. if (!MediaStream.prototype.getVideoTracks) {
  2059. MediaStream.prototype.getVideoTracks = function () {
  2060. return [];
  2061. };
  2062. }
  2063. if (!MediaStream.prototype.getAudioTracks) {
  2064. MediaStream.prototype.getAudioTracks = function () {
  2065. return [];
  2066. };
  2067. }
  2068. AdapterJS.maybeThroughWebRTCReady();
  2069. } else if (navigator.webkitGetUserMedia) {
  2070. webrtcDetectedBrowser = 'chrome';
  2071. webrtcDetectedType = 'webkit';
  2072. webrtcDetectedVersion = parseInt(navigator
  2073. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2074. // check if browser is opera 20+
  2075. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2076. if (checkIfOpera !== null) {
  2077. webrtcDetectedBrowser = 'opera';
  2078. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2079. }
  2080. // check browser datachannel support
  2081. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2082. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2083. webrtcDetectedDCSupport = 'SCTP';
  2084. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2085. webrtcDetectedVersion > 24) {
  2086. webrtcDetectedDCSupport = 'RTP';
  2087. } else {
  2088. webrtcDetectedDCSupport = '';
  2089. }
  2090. createIceServer = function (url, username, password) {
  2091. var iceServer = null;
  2092. var url_parts = url.split(':');
  2093. if (url_parts[0].indexOf('stun') === 0) {
  2094. iceServer = { 'url' : url };
  2095. } else if (url_parts[0].indexOf('turn') === 0) {
  2096. iceServer = {
  2097. 'url' : url,
  2098. 'credential' : password,
  2099. 'username' : username
  2100. };
  2101. }
  2102. return iceServer;
  2103. };
  2104. createIceServers = function (urls, username, password) {
  2105. var iceServers = [];
  2106. if (webrtcDetectedVersion >= 34) {
  2107. iceServers = {
  2108. 'urls' : urls,
  2109. 'credential' : password,
  2110. 'username' : username
  2111. };
  2112. } else {
  2113. for (i = 0; i < urls.length; i++) {
  2114. var iceServer = createIceServer(urls[i], username, password);
  2115. if (iceServer !== null) {
  2116. iceServers.push(iceServer);
  2117. }
  2118. }
  2119. }
  2120. return iceServers;
  2121. };
  2122. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2123. if (webrtcDetectedVersion < 34) {
  2124. AdapterJS.maybeFixConfiguration(pcConfig);
  2125. }
  2126. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2127. };
  2128. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2129. navigator.getUserMedia = window.getUserMedia;
  2130. attachMediaStream = function (element, stream) {
  2131. if (typeof element.srcObject !== 'undefined') {
  2132. element.srcObject = stream;
  2133. } else if (typeof element.mozSrcObject !== 'undefined') {
  2134. element.mozSrcObject = stream;
  2135. } else if (typeof element.src !== 'undefined') {
  2136. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2137. } else {
  2138. console.log('Error attaching stream to element.');
  2139. }
  2140. return element;
  2141. };
  2142. reattachMediaStream = function (to, from) {
  2143. to.src = from.src;
  2144. return to;
  2145. };
  2146. AdapterJS.maybeThroughWebRTCReady();
  2147. } else { // TRY TO USE PLUGIN
  2148. // IE 9 is not offering an implementation of console.log until you open a console
  2149. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2150. /* jshint -W020 */
  2151. console = {} || console;
  2152. // Implemented based on console specs from MDN
  2153. // You may override these functions
  2154. console.log = function (arg) {};
  2155. console.info = function (arg) {};
  2156. console.error = function (arg) {};
  2157. console.dir = function (arg) {};
  2158. console.exception = function (arg) {};
  2159. console.trace = function (arg) {};
  2160. console.warn = function (arg) {};
  2161. console.count = function (arg) {};
  2162. console.debug = function (arg) {};
  2163. console.count = function (arg) {};
  2164. console.time = function (arg) {};
  2165. console.timeEnd = function (arg) {};
  2166. console.group = function (arg) {};
  2167. console.groupCollapsed = function (arg) {};
  2168. console.groupEnd = function (arg) {};
  2169. /* jshint +W020 */
  2170. }
  2171. webrtcDetectedType = 'plugin';
  2172. webrtcDetectedDCSupport = 'plugin';
  2173. AdapterJS.parseWebrtcDetectedBrowser();
  2174. isIE = webrtcDetectedBrowser === 'IE';
  2175. /* jshint -W035 */
  2176. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2177. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2178. /* empty because it needs to prevent the function from running. */
  2179. }
  2180. };
  2181. /* jshint +W035 */
  2182. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2183. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2184. // Call immediately if possible
  2185. // Once the plugin is set, the code will always take this path
  2186. callback();
  2187. } else {
  2188. // otherwise start a 100ms interval
  2189. var checkPluginReadyState = setInterval(function () {
  2190. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2191. clearInterval(checkPluginReadyState);
  2192. callback();
  2193. }
  2194. }, 100);
  2195. }
  2196. };
  2197. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2198. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2199. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2200. });
  2201. };
  2202. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2203. // only inject once the page is ready
  2204. if (document.readyState !== 'complete') {
  2205. return;
  2206. }
  2207. // Prevent multiple injections
  2208. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2209. return;
  2210. }
  2211. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2212. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2213. var frag = document.createDocumentFragment();
  2214. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2215. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2216. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2217. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2218. '<param name="pluginId" value="' +
  2219. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2220. '<param name="windowless" value="false" /> ' +
  2221. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2222. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2223. '" />' +
  2224. // uncomment to be able to use virtual cams
  2225. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2226. '</object>';
  2227. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2228. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2229. }
  2230. document.body.appendChild(frag);
  2231. // Need to re-fetch the plugin
  2232. AdapterJS.WebRTCPlugin.plugin =
  2233. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2234. } else {
  2235. // Load Plugin
  2236. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2237. AdapterJS.WebRTCPlugin.plugin.id =
  2238. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2239. // IE will only start the plugin if it's ACTUALLY visible
  2240. if (isIE) {
  2241. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2242. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2243. } else { // The size of the plugin on Safari should be 0x0px
  2244. // so that the autorisation prompt is at the top
  2245. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2246. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2247. }
  2248. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2249. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2250. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2251. '<param name="pluginId" value="' +
  2252. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2253. '<param name="windowless" value="false" /> ' +
  2254. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2255. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2256. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2257. }
  2258. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2259. };
  2260. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2261. function (comName, plugName, installedCb, notInstalledCb) {
  2262. if (!isIE) {
  2263. var pluginArray = navigator.plugins;
  2264. for (var i = 0; i < pluginArray.length; i++) {
  2265. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2266. installedCb();
  2267. return;
  2268. }
  2269. }
  2270. notInstalledCb();
  2271. } else {
  2272. try {
  2273. var axo = new ActiveXObject(comName + '.' + plugName);
  2274. } catch (e) {
  2275. notInstalledCb();
  2276. return;
  2277. }
  2278. installedCb();
  2279. }
  2280. };
  2281. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2282. if (AdapterJS.WebRTCPlugin.pluginState ===
  2283. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2284. console.error("WebRTC interface has been defined already");
  2285. return;
  2286. }
  2287. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2288. AdapterJS.isDefined = function (variable) {
  2289. return variable !== null && variable !== undefined;
  2290. };
  2291. createIceServer = function (url, username, password) {
  2292. var iceServer = null;
  2293. var url_parts = url.split(':');
  2294. if (url_parts[0].indexOf('stun') === 0) {
  2295. iceServer = {
  2296. 'url' : url,
  2297. 'hasCredentials' : false
  2298. };
  2299. } else if (url_parts[0].indexOf('turn') === 0) {
  2300. iceServer = {
  2301. 'url' : url,
  2302. 'hasCredentials' : true,
  2303. 'credential' : password,
  2304. 'username' : username
  2305. };
  2306. }
  2307. return iceServer;
  2308. };
  2309. createIceServers = function (urls, username, password) {
  2310. var iceServers = [];
  2311. for (var i = 0; i < urls.length; ++i) {
  2312. iceServers.push(createIceServer(urls[i], username, password));
  2313. }
  2314. return iceServers;
  2315. };
  2316. RTCSessionDescription = function (info) {
  2317. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2318. return AdapterJS.WebRTCPlugin.plugin.
  2319. ConstructSessionDescription(info.type, info.sdp);
  2320. };
  2321. RTCPeerConnection = function (servers, constraints) {
  2322. var iceServers = null;
  2323. if (servers) {
  2324. iceServers = servers.iceServers;
  2325. for (var i = 0; i < iceServers.length; i++) {
  2326. if (iceServers[i].urls && !iceServers[i].url) {
  2327. iceServers[i].url = iceServers[i].urls;
  2328. }
  2329. iceServers[i].hasCredentials = AdapterJS.
  2330. isDefined(iceServers[i].username) &&
  2331. AdapterJS.isDefined(iceServers[i].credential);
  2332. }
  2333. }
  2334. var mandatory = (constraints && constraints.mandatory) ?
  2335. constraints.mandatory : null;
  2336. var optional = (constraints && constraints.optional) ?
  2337. constraints.optional : null;
  2338. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2339. return AdapterJS.WebRTCPlugin.plugin.
  2340. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2341. iceServers, mandatory, optional);
  2342. };
  2343. MediaStreamTrack = {};
  2344. MediaStreamTrack.getSources = function (callback) {
  2345. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2346. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2347. });
  2348. };
  2349. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2350. constraints.audio = constraints.audio || false;
  2351. constraints.video = constraints.video || false;
  2352. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2353. AdapterJS.WebRTCPlugin.plugin.
  2354. getUserMedia(constraints, successCallback, failureCallback);
  2355. });
  2356. };
  2357. window.navigator.getUserMedia = window.getUserMedia;
  2358. attachMediaStream = function (element, stream) {
  2359. if (!element || !element.parentNode) {
  2360. return;
  2361. }
  2362. var streamId
  2363. if (stream === null) {
  2364. streamId = '';
  2365. }
  2366. else {
  2367. stream.enableSoundTracks(true);
  2368. streamId = stream.id;
  2369. }
  2370. if (element.nodeName.toLowerCase() !== 'audio') {
  2371. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2372. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2373. var frag = document.createDocumentFragment();
  2374. var temp = document.createElement('div');
  2375. var classHTML = '';
  2376. if (element.className) {
  2377. classHTML = 'class="' + element.className + '" ';
  2378. } else if (element.attributes && element.attributes['class']) {
  2379. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2380. }
  2381. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2382. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2383. '<param name="pluginId" value="' + elementId + '" /> ' +
  2384. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2385. '<param name="windowless" value="true" /> ' +
  2386. '<param name="streamId" value="' + streamId + '" /> ' +
  2387. '</object>';
  2388. while (temp.firstChild) {
  2389. frag.appendChild(temp.firstChild);
  2390. }
  2391. var height = '';
  2392. var width = '';
  2393. if (element.getBoundingClientRect) {
  2394. var rectObject = element.getBoundingClientRect();
  2395. width = rectObject.width + 'px';
  2396. height = rectObject.height + 'px';
  2397. }
  2398. else if (element.width) {
  2399. width = element.width;
  2400. height = element.height;
  2401. } else {
  2402. // TODO: What scenario could bring us here?
  2403. }
  2404. element.parentNode.insertBefore(frag, element);
  2405. frag = document.getElementById(elementId);
  2406. frag.width = width;
  2407. frag.height = height;
  2408. element.parentNode.removeChild(element);
  2409. } else {
  2410. var children = element.children;
  2411. for (var i = 0; i !== children.length; ++i) {
  2412. if (children[i].name === 'streamId') {
  2413. children[i].value = streamId;
  2414. break;
  2415. }
  2416. }
  2417. element.setStreamId(streamId);
  2418. }
  2419. var newElement = document.getElementById(elementId);
  2420. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2421. if (isIE) { // on IE the event needs to be plugged manually
  2422. newElement.attachEvent('onplaying', newElement.onplaying);
  2423. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2424. newElement._TemOnClick = function (id) {
  2425. var arg = {
  2426. srcElement : document.getElementById(id)
  2427. };
  2428. newElement.onclick(arg);
  2429. };
  2430. }
  2431. return newElement;
  2432. } else {
  2433. return element;
  2434. }
  2435. };
  2436. reattachMediaStream = function (to, from) {
  2437. var stream = null;
  2438. var children = from.children;
  2439. for (var i = 0; i !== children.length; ++i) {
  2440. if (children[i].name === 'streamId') {
  2441. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2442. stream = AdapterJS.WebRTCPlugin.plugin
  2443. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2444. break;
  2445. }
  2446. }
  2447. if (stream !== null) {
  2448. return attachMediaStream(to, stream);
  2449. } else {
  2450. console.log('Could not find the stream associated with this element');
  2451. }
  2452. };
  2453. RTCIceCandidate = function (candidate) {
  2454. if (!candidate.sdpMid) {
  2455. candidate.sdpMid = '';
  2456. }
  2457. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2458. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2459. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2460. );
  2461. };
  2462. // inject plugin
  2463. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2464. AdapterJS.WebRTCPlugin.injectPlugin();
  2465. };
  2466. // This function will be called if the plugin is needed (browser different
  2467. // from Chrome or Firefox), but the plugin is not installed.
  2468. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2469. function() {
  2470. AdapterJS.addEvent(document,
  2471. 'readystatechange',
  2472. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2473. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2474. };
  2475. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2476. if (AdapterJS.options.hidePluginInstallPrompt) {
  2477. return;
  2478. }
  2479. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2480. if(downloadLink) { // if download link
  2481. var popupString;
  2482. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2483. popupString = 'This website requires you to install the ' +
  2484. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2485. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2486. ' WebRTC Plugin</a>' +
  2487. ' to work on this browser.';
  2488. } else { // no portal link, just print a generic explanation
  2489. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2490. }
  2491. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2492. } else { // no download link, just print a generic explanation
  2493. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2494. }
  2495. };
  2496. // Try to detect the plugin and act accordingly
  2497. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2498. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2499. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2500. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2501. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2502. }
  2503. (function () {
  2504. 'use strict';
  2505. var baseGetUserMedia = null;
  2506. AdapterJS.TEXT.EXTENSION = {
  2507. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2508. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2509. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2510. BUTTON_FF: 'Install Now',
  2511. BUTTON_CHROME: 'Go to Chrome Web Store'
  2512. };
  2513. var clone = function(obj) {
  2514. if (null == obj || "object" != typeof obj) return obj;
  2515. var copy = obj.constructor();
  2516. for (var attr in obj) {
  2517. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2518. }
  2519. return copy;
  2520. };
  2521. if (window.navigator.mozGetUserMedia) {
  2522. baseGetUserMedia = window.navigator.getUserMedia;
  2523. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2524. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2525. // intercepting screensharing requests
  2526. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2527. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2528. }
  2529. var updatedConstraints = clone(constraints);
  2530. //constraints.video.mediaSource = constraints.video.mediaSource;
  2531. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2532. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2533. // strange but this works anyway
  2534. var checkIfReady = setInterval(function () {
  2535. if (document.readyState === 'complete') {
  2536. clearInterval(checkIfReady);
  2537. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2538. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2539. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2540. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2541. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2542. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2543. } else {
  2544. failureCb(error);
  2545. }
  2546. });
  2547. }
  2548. }, 1);
  2549. } else { // regular GetUserMediaRequest
  2550. baseGetUserMedia(constraints, successCb, failureCb);
  2551. }
  2552. };
  2553. getUserMedia = navigator.getUserMedia;
  2554. } else if (window.navigator.webkitGetUserMedia) {
  2555. baseGetUserMedia = window.navigator.getUserMedia;
  2556. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2557. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2558. if (window.webrtcDetectedBrowser !== 'chrome') {
  2559. throw new Error('Current browser does not support screensharing');
  2560. }
  2561. // would be fine since no methods
  2562. var updatedConstraints = clone(constraints);
  2563. var chromeCallback = function(error, sourceId) {
  2564. if(!error) {
  2565. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2566. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2567. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2568. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2569. if (sourceId) {
  2570. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2571. }
  2572. delete updatedConstraints.video.mediaSource;
  2573. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2574. } else {
  2575. if (error === 'permission-denied') {
  2576. throw new Error('Permission denied for screen retrieval');
  2577. } else {
  2578. throw new Error('Failed retrieving selected screen');
  2579. }
  2580. }
  2581. };
  2582. var onIFrameCallback = function (event) {
  2583. if (!event.data) {
  2584. return;
  2585. }
  2586. if (event.data.chromeMediaSourceId) {
  2587. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2588. chromeCallback('permission-denied');
  2589. } else {
  2590. chromeCallback(null, event.data.chromeMediaSourceId);
  2591. }
  2592. }
  2593. if (event.data.chromeExtensionStatus) {
  2594. if (event.data.chromeExtensionStatus === 'not-installed') {
  2595. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2596. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2597. event.data.data, true, true);
  2598. } else {
  2599. chromeCallback(event.data.chromeExtensionStatus, null);
  2600. }
  2601. }
  2602. // this event listener is no more needed
  2603. window.removeEventListener('message', onIFrameCallback);
  2604. };
  2605. window.addEventListener('message', onIFrameCallback);
  2606. postFrameMessage({
  2607. captureSourceId: true
  2608. });
  2609. } else {
  2610. baseGetUserMedia(constraints, successCb, failureCb);
  2611. }
  2612. };
  2613. getUserMedia = navigator.getUserMedia;
  2614. } else {
  2615. baseGetUserMedia = window.navigator.getUserMedia;
  2616. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2617. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2618. // would be fine since no methods
  2619. var updatedConstraints = clone(constraints);
  2620. // wait for plugin to be ready
  2621. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2622. // check if screensharing feature is available
  2623. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2624. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2625. // set the constraints
  2626. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  2627. updatedConstraints.video.optional.push({
  2628. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  2629. });
  2630. delete updatedConstraints.video.mediaSource;
  2631. } else {
  2632. throw new Error('Your WebRTC plugin does not support screensharing');
  2633. }
  2634. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2635. });
  2636. } else {
  2637. baseGetUserMedia(constraints, successCb, failureCb);
  2638. }
  2639. };
  2640. getUserMedia = window.navigator.getUserMedia;
  2641. }
  2642. if (window.webrtcDetectedBrowser === 'chrome') {
  2643. var iframe = document.createElement('iframe');
  2644. iframe.onload = function() {
  2645. iframe.isLoaded = true;
  2646. };
  2647. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  2648. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  2649. iframe.style.display = 'none';
  2650. (document.body || document.documentElement).appendChild(iframe);
  2651. var postFrameMessage = function (object) {
  2652. object = object || {};
  2653. if (!iframe.isLoaded) {
  2654. setTimeout(function () {
  2655. iframe.contentWindow.postMessage(object, '*');
  2656. }, 100);
  2657. return;
  2658. }
  2659. iframe.contentWindow.postMessage(object, '*');
  2660. };
  2661. }
  2662. })();
  2663. },{}],11:[function(require,module,exports){
  2664. /* global Strophe, APP, $, config, interfaceConfig, toastr */
  2665. var UI = {};
  2666. var VideoLayout = require("./videolayout/VideoLayout.js");
  2667. var AudioLevels = require("./audio_levels/AudioLevels.js");
  2668. var Prezi = require("./prezi/Prezi.js");
  2669. var Etherpad = require("./etherpad/Etherpad.js");
  2670. var Chat = require("./side_pannels/chat/Chat.js");
  2671. var Toolbar = require("./toolbars/Toolbar");
  2672. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  2673. var BottomToolbar = require("./toolbars/BottomToolbar");
  2674. var ContactList = require("./side_pannels/contactlist/ContactList");
  2675. var Avatar = require("./avatar/Avatar");
  2676. var EventEmitter = require("events");
  2677. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  2678. var Settings = require("./../settings/Settings");
  2679. var PanelToggler = require("./side_pannels/SidePanelToggler");
  2680. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  2681. UI.messageHandler = require("./util/MessageHandler");
  2682. var messageHandler = UI.messageHandler;
  2683. var Authentication = require("./authentication/Authentication");
  2684. var UIUtil = require("./util/UIUtil");
  2685. var NicknameHandler = require("./util/NicknameHandler");
  2686. var JitsiPopover = require("./util/JitsiPopover");
  2687. var CQEvents = require("../../service/connectionquality/CQEvents");
  2688. var DesktopSharingEventTypes
  2689. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2690. var RTCEvents = require("../../service/RTC/RTCEvents");
  2691. var RTCBrowserType = require("../RTC/RTCBrowserType");
  2692. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  2693. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  2694. var UIEvents = require("../../service/UI/UIEvents");
  2695. var MemberEvents = require("../../service/members/Events");
  2696. var eventEmitter = new EventEmitter();
  2697. var roomName = null;
  2698. function promptDisplayName() {
  2699. var message = '<h2 data-i18n="dialog.displayNameRequired">';
  2700. message += APP.translation.translateString(
  2701. "dialog.displayNameRequired");
  2702. message += '</h2>' +
  2703. '<input name="displayName" type="text" data-i18n=' +
  2704. '"[placeholder]defaultNickname" placeholder="' +
  2705. APP.translation.translateString(
  2706. "defaultNickname", {name: "Jane Pink"}) +
  2707. '" autofocus>';
  2708. var buttonTxt
  2709. = APP.translation.generateTranslationHTML("dialog.Ok");
  2710. var buttons = [];
  2711. buttons.push({title: buttonTxt, value: "ok"});
  2712. messageHandler.openDialog(null, message,
  2713. true,
  2714. buttons,
  2715. function (e, v, m, f) {
  2716. if (v == "ok") {
  2717. var displayName = f.displayName;
  2718. if (displayName) {
  2719. VideoLayout.inputDisplayNameHandler(displayName);
  2720. return true;
  2721. }
  2722. }
  2723. e.preventDefault();
  2724. },
  2725. function () {
  2726. var form = $.prompt.getPrompt();
  2727. var input = form.find("input[name='displayName']");
  2728. input.focus();
  2729. var button = form.find("button");
  2730. button.attr("disabled", "disabled");
  2731. input.keyup(function () {
  2732. if(!input.val())
  2733. button.attr("disabled", "disabled");
  2734. else
  2735. button.removeAttr("disabled");
  2736. });
  2737. }
  2738. );
  2739. }
  2740. function notifyForInitialMute() {
  2741. messageHandler.notify(null, "notify.mutedTitle", "connected",
  2742. "notify.muted", null, {timeOut: 120000});
  2743. }
  2744. function setupPrezi() {
  2745. $("#reloadPresentationLink").click(function() {
  2746. Prezi.reloadPresentation();
  2747. });
  2748. }
  2749. function setupChat() {
  2750. Chat.init();
  2751. $("#toggle_smileys").click(function() {
  2752. Chat.toggleSmileys();
  2753. });
  2754. }
  2755. function setupToolbars() {
  2756. Toolbar.init(UI);
  2757. Toolbar.setupButtonsFromConfig();
  2758. BottomToolbar.init();
  2759. }
  2760. function streamHandler(stream, isMuted) {
  2761. switch (stream.type) {
  2762. case "audio":
  2763. VideoLayout.changeLocalAudio(stream, isMuted);
  2764. break;
  2765. case "video":
  2766. VideoLayout.changeLocalVideo(stream, isMuted);
  2767. break;
  2768. case "stream":
  2769. VideoLayout.changeLocalStream(stream, isMuted);
  2770. break;
  2771. }
  2772. }
  2773. function onXmppConnectionFailed(stropheErrorMsg) {
  2774. var title = APP.translation.generateTranslationHTML(
  2775. "dialog.error");
  2776. var message;
  2777. if (stropheErrorMsg) {
  2778. message = APP.translation.generateTranslationHTML(
  2779. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  2780. } else {
  2781. message = APP.translation.generateTranslationHTML(
  2782. "dialog.connectError");
  2783. }
  2784. messageHandler.openDialog(
  2785. title, message, true, {}, function (e, v, m, f) { return false; });
  2786. }
  2787. function onDisposeConference(unload) {
  2788. Toolbar.showAuthenticateButton(false);
  2789. }
  2790. function onDisplayNameChanged(jid, displayName) {
  2791. ContactList.onDisplayNameChange(jid, displayName);
  2792. SettingsMenu.onDisplayNameChange(jid, displayName);
  2793. VideoLayout.onDisplayNameChanged(jid, displayName);
  2794. }
  2795. function registerListeners() {
  2796. APP.RTC.addStreamListener(streamHandler,
  2797. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  2798. APP.RTC.addStreamListener(streamHandler,
  2799. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  2800. APP.RTC.addStreamListener(function (stream) {
  2801. VideoLayout.onRemoteStreamAdded(stream);
  2802. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  2803. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  2804. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED,
  2805. function (resourceJid) {
  2806. VideoLayout.onDominantSpeakerChanged(resourceJid);
  2807. });
  2808. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  2809. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  2810. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  2811. endpointsEnteringLastN, stream);
  2812. });
  2813. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  2814. function (devices) {
  2815. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  2816. });
  2817. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, UI.setVideoMuteButtonsState);
  2818. APP.RTC.addListener(RTCEvents.DATA_CHANNEL_OPEN, function () {
  2819. // when the data channel becomes available, tell the bridge about video
  2820. // selections so that it can do adaptive simulcast,
  2821. // we want the notification to trigger even if userJid is undefined,
  2822. // or null.
  2823. var userResource = APP.UI.getLargeVideoResource();
  2824. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, userResource);
  2825. });
  2826. APP.statistics.addAudioLevelListener(function(jid, audioLevel) {
  2827. var resourceJid;
  2828. if(jid === APP.statistics.LOCAL_JID) {
  2829. resourceJid = AudioLevels.LOCAL_LEVEL;
  2830. if(APP.RTC.localAudio.isMuted()) {
  2831. audioLevel = 0;
  2832. }
  2833. } else {
  2834. resourceJid = Strophe.getResourceFromJid(jid);
  2835. }
  2836. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  2837. UI.getLargeVideoResource());
  2838. });
  2839. APP.desktopsharing.addListener(function () {
  2840. ToolbarToggler.showDesktopSharingButton();
  2841. }, DesktopSharingEventTypes.INIT);
  2842. APP.desktopsharing.addListener(
  2843. Toolbar.changeDesktopSharingButtonState,
  2844. DesktopSharingEventTypes.SWITCHING_DONE);
  2845. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  2846. VideoLayout.updateLocalConnectionStats);
  2847. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  2848. VideoLayout.updateConnectionStats);
  2849. APP.connectionquality.addListener(CQEvents.STOP,
  2850. VideoLayout.onStatsStop);
  2851. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  2852. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  2853. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  2854. messageHandler.openMessageDialog(
  2855. 'dialog.serviceUnavailable',
  2856. 'dialog.gracefulShutdown'
  2857. );
  2858. });
  2859. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  2860. var title = APP.translation.generateTranslationHTML(
  2861. "dialog.reservationError");
  2862. var message = APP.translation.generateTranslationHTML(
  2863. "dialog.reservationErrorMsg", {code: code, msg: msg});
  2864. messageHandler.openDialog(
  2865. title,
  2866. message,
  2867. true, {},
  2868. function (event, value, message, formVals) {
  2869. return false;
  2870. }
  2871. );
  2872. });
  2873. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  2874. messageHandler.openMessageDialog("dialog.sessTerminated",
  2875. "dialog.kickMessage");
  2876. });
  2877. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  2878. //FIXME: use Session Terminated from translation, but
  2879. // 'reason' text comes from XMPP packet and is not translated
  2880. var title = APP.translation.generateTranslationHTML("dialog.sessTerminated");
  2881. messageHandler.openDialog(
  2882. title, reason, true, {},
  2883. function (event, value, message, formVals) {
  2884. return false;
  2885. }
  2886. );
  2887. });
  2888. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  2889. messageHandler.showError("dialog.error",
  2890. "dialog.bridgeUnavailable");
  2891. });
  2892. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  2893. Avatar.setUserAvatar(from, id);
  2894. });
  2895. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  2896. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  2897. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  2898. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  2899. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  2900. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  2901. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  2902. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  2903. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  2904. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  2905. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  2906. onAuthenticationRequired);
  2907. APP.xmpp.addListener(XMPPEvents.PARTICIPANT_VIDEO_TYPE_CHANGED,
  2908. onPeerVideoTypeChanged);
  2909. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  2910. function (resource, devices) {
  2911. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  2912. });
  2913. APP.xmpp.addListener(XMPPEvents.PARTICIPANT_AUDIO_MUTED,
  2914. VideoLayout.onAudioMute);
  2915. APP.xmpp.addListener(XMPPEvents.PARTICIPANT_VIDEO_MUTED,
  2916. VideoLayout.onVideoMute);
  2917. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS, function (doMuteAudio) {
  2918. UI.setAudioMuted(doMuteAudio);
  2919. });
  2920. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  2921. onDtmfSupportChanged);
  2922. APP.xmpp.addListener(XMPPEvents.START_MUTED_SETTING_CHANGED, function (audio, video) {
  2923. SettingsMenu.setStartMuted(audio, video);
  2924. });
  2925. APP.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS, function (audio, video) {
  2926. UI.setInitialMuteFromFocus(audio, video);
  2927. });
  2928. APP.xmpp.addListener(XMPPEvents.JINGLE_FATAL_ERROR, function (session, error) {
  2929. UI.messageHandler.showError("dialog.sorry",
  2930. "dialog.internalError");
  2931. });
  2932. APP.xmpp.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR, function () {
  2933. messageHandler.showError("dialog.error",
  2934. "dialog.SLDFailure");
  2935. });
  2936. APP.xmpp.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR, function () {
  2937. messageHandler.showError("dialog.error",
  2938. "dialog.SRDFailure");
  2939. });
  2940. APP.xmpp.addListener(XMPPEvents.CREATE_ANSWER_ERROR, function () {
  2941. messageHandler.showError();
  2942. });
  2943. APP.xmpp.addListener(XMPPEvents.PROMPT_FOR_LOGIN, function () {
  2944. // FIXME: re-use LoginDialog which supports retries
  2945. UI.showLoginPopup(connect);
  2946. });
  2947. APP.xmpp.addListener(XMPPEvents.FOCUS_DISCONNECTED, function (focusComponent, retrySec) {
  2948. UI.messageHandler.notify(
  2949. null, "notify.focus",
  2950. 'disconnected', "notify.focusFail",
  2951. {component: focusComponent, ms: retrySec});
  2952. });
  2953. APP.xmpp.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  2954. UI.messageHandler.openReportDialog(null,
  2955. "dialog.joinError", pres);
  2956. });
  2957. APP.xmpp.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  2958. UI.messageHandler.openReportDialog(null,
  2959. "dialog.connectError", pres);
  2960. });
  2961. APP.xmpp.addListener(XMPPEvents.READY_TO_JOIN, function () {
  2962. var roomName = UI.generateRoomName();
  2963. APP.xmpp.allocateConferenceFocus(roomName, UI.checkForNicknameAndJoin);
  2964. });
  2965. //NicknameHandler emits this event
  2966. UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  2967. APP.xmpp.addToPresence("displayName", nickname);
  2968. });
  2969. UI.addListener(UIEvents.LARGEVIDEO_INIT, function () {
  2970. AudioLevels.init();
  2971. });
  2972. if (!interfaceConfig.filmStripOnly) {
  2973. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  2974. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  2975. // Listens for video interruption events.
  2976. APP.xmpp.addListener(XMPPEvents.CONNECTION_INTERRUPTED, VideoLayout.onVideoInterrupted);
  2977. // Listens for video restores events.
  2978. APP.xmpp.addListener(XMPPEvents.CONNECTION_RESTORED, VideoLayout.onVideoRestored);
  2979. }
  2980. }
  2981. /**
  2982. * Mutes/unmutes the local video.
  2983. *
  2984. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  2985. * @param options an object which specifies optional arguments such as the
  2986. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  2987. * specifies whether the method was initiated in response to a user command (in
  2988. * contrast to an automatic decision taken by the application logic)
  2989. */
  2990. function setVideoMute(mute, options) {
  2991. APP.RTC.setVideoMute(mute,
  2992. UI.setVideoMuteButtonsState,
  2993. options);
  2994. }
  2995. function onResize() {
  2996. Chat.resizeChat();
  2997. VideoLayout.resizeLargeVideoContainer();
  2998. }
  2999. function bindEvents() {
  3000. /**
  3001. * Resizes and repositions videos in full screen mode.
  3002. */
  3003. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  3004. onResize);
  3005. $(window).resize(onResize);
  3006. }
  3007. UI.start = function (init) {
  3008. document.title = interfaceConfig.APP_NAME;
  3009. var setupWelcomePage = null;
  3010. if(config.enableWelcomePage && window.location.pathname == "/" &&
  3011. (!window.localStorage.welcomePageDisabled ||
  3012. window.localStorage.welcomePageDisabled == "false")) {
  3013. $("#videoconference_page").hide();
  3014. if (!setupWelcomePage)
  3015. setupWelcomePage = require("./welcome_page/WelcomePage");
  3016. setupWelcomePage();
  3017. return;
  3018. }
  3019. $("#welcome_page").hide();
  3020. // Set the defaults for prompt dialogs.
  3021. $.prompt.setDefaults({persistent: false});
  3022. registerListeners();
  3023. VideoLayout.init(eventEmitter);
  3024. NicknameHandler.init(eventEmitter);
  3025. bindEvents();
  3026. setupPrezi();
  3027. if (!interfaceConfig.filmStripOnly) {
  3028. $("#videospace").mousemove(function () {
  3029. return ToolbarToggler.showToolbar();
  3030. });
  3031. setupToolbars();
  3032. setupChat();
  3033. // Display notice message at the top of the toolbar
  3034. if (config.noticeMessage) {
  3035. $('#noticeText').text(config.noticeMessage);
  3036. $('#notice').css({display: 'block'});
  3037. }
  3038. $("#downloadlog").click(function (event) {
  3039. dump(event.target);
  3040. });
  3041. }
  3042. else
  3043. {
  3044. $("#header").css("display", "none");
  3045. $("#bottomToolbar").css("display", "none");
  3046. $("#downloadlog").css("display", "none");
  3047. $("#remoteVideos").css("padding", "0px 0px 18px 0px");
  3048. $("#remoteVideos").css("right", "0px");
  3049. messageHandler.disableNotifications();
  3050. $('body').popover("disable");
  3051. // $("[data-toggle=popover]").popover("disable");
  3052. JitsiPopover.enabled = false;
  3053. }
  3054. document.title = interfaceConfig.APP_NAME;
  3055. if(config.requireDisplayName) {
  3056. var currentSettings = Settings.getSettings();
  3057. if (!currentSettings.displayName) {
  3058. promptDisplayName();
  3059. }
  3060. }
  3061. init();
  3062. if (!interfaceConfig.filmStripOnly) {
  3063. toastr.options = {
  3064. "closeButton": true,
  3065. "debug": false,
  3066. "positionClass": "notification-bottom-right",
  3067. "onclick": null,
  3068. "showDuration": "300",
  3069. "hideDuration": "1000",
  3070. "timeOut": "2000",
  3071. "extendedTimeOut": "1000",
  3072. "showEasing": "swing",
  3073. "hideEasing": "linear",
  3074. "showMethod": "fadeIn",
  3075. "hideMethod": "fadeOut",
  3076. "reposition": function () {
  3077. if (PanelToggler.isVisible()) {
  3078. $("#toast-container").addClass("notification-bottom-right-center");
  3079. } else {
  3080. $("#toast-container").removeClass("notification-bottom-right-center");
  3081. }
  3082. },
  3083. "newestOnTop": false
  3084. };
  3085. SettingsMenu.init();
  3086. }
  3087. };
  3088. function chatAddError(errorMessage, originalText) {
  3089. return Chat.chatAddError(errorMessage, originalText);
  3090. }
  3091. function chatSetSubject(text) {
  3092. return Chat.chatSetSubject(text);
  3093. }
  3094. function updateChatConversation(from, displayName, message, myjid, stamp) {
  3095. return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
  3096. }
  3097. function onMucJoined(jid, info) {
  3098. Toolbar.updateRoomUrl(window.location.href);
  3099. var meHTML = APP.translation.generateTranslationHTML("me");
  3100. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  3101. var settings = Settings.getSettings();
  3102. // Make sure we configure our avatar id, before creating avatar for us
  3103. Avatar.setUserAvatar(jid, settings.email || settings.uid);
  3104. // Add myself to the contact list.
  3105. ContactList.addContact(jid);
  3106. // Once we've joined the muc show the toolbar
  3107. ToolbarToggler.showToolbar();
  3108. var displayName =
  3109. config.displayJids ? Strophe.getResourceFromJid(jid) : info.displayName;
  3110. if (displayName)
  3111. onDisplayNameChanged('localVideoContainer', displayName);
  3112. VideoLayout.mucJoined();
  3113. }
  3114. function initEtherpad(name) {
  3115. Etherpad.init(name);
  3116. }
  3117. function onMucMemberLeft(jid) {
  3118. console.log('left.muc', jid);
  3119. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  3120. '>.displayname').html();
  3121. messageHandler.notify(displayName,'notify.somebody',
  3122. 'disconnected',
  3123. 'notify.disconnected');
  3124. if (!config.startAudioMuted ||
  3125. config.startAudioMuted > APP.members.size()) {
  3126. UIUtil.playSoundNotification('userLeft');
  3127. }
  3128. ContactList.removeContact(jid);
  3129. VideoLayout.participantLeft(jid);
  3130. }
  3131. function onLocalRoleChanged(jid, info, pres, isModerator) {
  3132. console.info("My role changed, new role: " + info.role);
  3133. onModeratorStatusChanged(isModerator);
  3134. VideoLayout.showModeratorIndicator();
  3135. SettingsMenu.onRoleChanged();
  3136. if (isModerator) {
  3137. Authentication.closeAuthenticationWindow();
  3138. messageHandler.notify(null, "notify.me",
  3139. 'connected', "notify.moderator");
  3140. Toolbar.checkAutoRecord();
  3141. }
  3142. }
  3143. function onModeratorStatusChanged(isModerator) {
  3144. Toolbar.showSipCallButton(isModerator);
  3145. Toolbar.showRecordingButton(
  3146. isModerator); //&&
  3147. // FIXME:
  3148. // Recording visible if
  3149. // there are at least 2(+ 1 focus) participants
  3150. //Object.keys(connection.emuc.members).length >= 3);
  3151. }
  3152. function onPasswordRequired(callback) {
  3153. // password is required
  3154. Toolbar.lockLockButton();
  3155. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3156. message += APP.translation.translateString(
  3157. "dialog.passwordRequired");
  3158. message += '</h2>' +
  3159. '<input name="lockKey" type="text" data-i18n=' +
  3160. '"[placeholder]dialog.password" placeholder="' +
  3161. APP.translation.translateString("dialog.password") +
  3162. '" autofocus>';
  3163. messageHandler.openTwoButtonDialog(null, null, null, message,
  3164. true,
  3165. "dialog.Ok",
  3166. function (e, v, m, f) {},
  3167. null,
  3168. function (e, v, m, f) {
  3169. if (v) {
  3170. var lockKey = f.lockKey;
  3171. if (lockKey) {
  3172. Toolbar.setSharedKey(lockKey);
  3173. callback(lockKey);
  3174. }
  3175. }
  3176. },
  3177. ':input:first'
  3178. );
  3179. }
  3180. /**
  3181. * The dialpad button is shown iff there is at least one member that supports
  3182. * DTMF (e.g. jigasi).
  3183. */
  3184. function onDtmfSupportChanged(dtmfSupport) {
  3185. //TODO: enable when the UI is ready
  3186. //Toolbar.showDialPadButton(dtmfSupport);
  3187. }
  3188. function onMucMemberJoined(jid, id, displayName) {
  3189. messageHandler.notify(displayName,'notify.somebody',
  3190. 'connected',
  3191. 'notify.connected');
  3192. if (!config.startAudioMuted ||
  3193. config.startAudioMuted > APP.members.size())
  3194. UIUtil.playSoundNotification('userJoined');
  3195. // Configure avatar
  3196. Avatar.setUserAvatar(jid, id);
  3197. // Add Peer's container
  3198. VideoLayout.ensurePeerContainerExists(jid);
  3199. }
  3200. function onMucPresenceStatus(jid, info) {
  3201. VideoLayout.setPresenceStatus(Strophe.getResourceFromJid(jid), info.status);
  3202. }
  3203. function onPeerVideoTypeChanged(resourceJid, newVideoType) {
  3204. VideoLayout.onVideoTypeChanged(resourceJid, newVideoType);
  3205. }
  3206. function onMucRoleChanged(role, displayName) {
  3207. VideoLayout.showModeratorIndicator();
  3208. if (role === 'moderator') {
  3209. var messageKey, messageOptions = {};
  3210. if (!displayName) {
  3211. messageKey = "notify.grantedToUnknown";
  3212. }
  3213. else {
  3214. messageKey = "notify.grantedTo";
  3215. messageOptions = {to: displayName};
  3216. }
  3217. messageHandler.notify(
  3218. displayName,'notify.somebody',
  3219. 'connected', messageKey,
  3220. messageOptions);
  3221. }
  3222. }
  3223. function onAuthenticationRequired(intervalCallback) {
  3224. Authentication.openAuthenticationDialog(
  3225. roomName, intervalCallback, function () {
  3226. Toolbar.authenticateClicked();
  3227. });
  3228. }
  3229. function onLastNChanged(oldValue, newValue) {
  3230. if (config.muteLocalVideoIfNotInLastN) {
  3231. setVideoMute(!newValue, { 'byUser': false });
  3232. }
  3233. }
  3234. UI.toggleSmileys = function () {
  3235. Chat.toggleSmileys();
  3236. };
  3237. UI.getSettings = function () {
  3238. return Settings.getSettings();
  3239. };
  3240. UI.toggleFilmStrip = function () {
  3241. return BottomToolbar.toggleFilmStrip();
  3242. };
  3243. UI.toggleChat = function () {
  3244. return BottomToolbar.toggleChat();
  3245. };
  3246. UI.toggleContactList = function () {
  3247. return BottomToolbar.toggleContactList();
  3248. };
  3249. UI.inputDisplayNameHandler = function (value) {
  3250. VideoLayout.inputDisplayNameHandler(value);
  3251. };
  3252. UI.getLargeVideoResource = function () {
  3253. return VideoLayout.getLargeVideoResource();
  3254. };
  3255. UI.generateRoomName = function() {
  3256. if(roomName)
  3257. return roomName;
  3258. var roomnode = null;
  3259. var path = window.location.pathname;
  3260. // determinde the room node from the url
  3261. // TODO: just the roomnode or the whole bare jid?
  3262. if (config.getroomnode && typeof config.getroomnode === 'function') {
  3263. // custom function might be responsible for doing the pushstate
  3264. roomnode = config.getroomnode(path);
  3265. } else {
  3266. /* fall back to default strategy
  3267. * this is making assumptions about how the URL->room mapping happens.
  3268. * It currently assumes deployment at root, with a rewrite like the
  3269. * following one (for nginx):
  3270. location ~ ^/([a-zA-Z0-9]+)$ {
  3271. rewrite ^/(.*)$ / break;
  3272. }
  3273. */
  3274. if (path.length > 1) {
  3275. roomnode = path.substr(1).toLowerCase();
  3276. } else {
  3277. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  3278. roomnode = word.toLowerCase();
  3279. window.history.pushState('VideoChat',
  3280. 'Room: ' + word, window.location.pathname + word);
  3281. }
  3282. }
  3283. roomName = roomnode + '@' + config.hosts.muc;
  3284. return roomName;
  3285. };
  3286. UI.connectionIndicatorShowMore = function(jid) {
  3287. return VideoLayout.showMore(jid);
  3288. };
  3289. UI.showLoginPopup = function(callback) {
  3290. console.log('password is required');
  3291. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3292. message += APP.translation.translateString(
  3293. "dialog.passwordRequired");
  3294. message += '</h2>' +
  3295. '<input name="username" type="text" ' +
  3296. 'placeholder="user@domain.net" autofocus>' +
  3297. '<input name="password" ' +
  3298. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3299. ' placeholder="user password">';
  3300. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  3301. true,
  3302. "dialog.Ok",
  3303. function (e, v, m, f) {
  3304. if (v) {
  3305. if (f.username !== null && f.password != null) {
  3306. callback(f.username, f.password);
  3307. }
  3308. }
  3309. },
  3310. null, null, ':input:first'
  3311. );
  3312. };
  3313. UI.checkForNicknameAndJoin = function () {
  3314. Authentication.closeAuthenticationDialog();
  3315. Authentication.stopInterval();
  3316. var nick = null;
  3317. if (config.useNicks) {
  3318. nick = window.prompt('Your nickname (optional)');
  3319. }
  3320. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  3321. };
  3322. function dump(elem, filename) {
  3323. elem = elem.parentNode;
  3324. elem.download = filename || 'meetlog.json';
  3325. elem.href = 'data:application/json;charset=utf-8,\n';
  3326. var data = APP.xmpp.getJingleLog();
  3327. var metadata = {};
  3328. metadata.time = new Date();
  3329. metadata.url = window.location.href;
  3330. metadata.ua = navigator.userAgent;
  3331. var log = APP.xmpp.getXmppLog();
  3332. if (log) {
  3333. metadata.xmpp = log;
  3334. }
  3335. data.metadata = metadata;
  3336. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  3337. return false;
  3338. }
  3339. UI.getRoomName = function () {
  3340. return roomName;
  3341. };
  3342. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  3343. if (muteAudio || muteVideo)
  3344. notifyForInitialMute();
  3345. if (muteAudio)
  3346. UI.setAudioMuted(true);
  3347. if (muteVideo)
  3348. UI.setVideoMute(true);
  3349. };
  3350. /**
  3351. * Mutes/unmutes the local video.
  3352. */
  3353. UI.toggleVideo = function () {
  3354. setVideoMute(!APP.RTC.localVideo.isMuted());
  3355. };
  3356. /**
  3357. * Mutes / unmutes audio for the local participant.
  3358. */
  3359. UI.toggleAudio = function() {
  3360. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  3361. };
  3362. /**
  3363. * Sets muted audio state for the local participant.
  3364. */
  3365. UI.setAudioMuted = function (mute, earlyMute) {
  3366. var audioMute = null;
  3367. if (earlyMute)
  3368. audioMute = function (mute, cb) {
  3369. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  3370. };
  3371. else
  3372. audioMute = function (mute, cb) {
  3373. return APP.xmpp.setAudioMute(mute, cb);
  3374. };
  3375. if (!audioMute(mute, function () {
  3376. VideoLayout.showLocalAudioIndicator(mute);
  3377. UIUtil.buttonClick("#toolbar_button_mute", "icon-microphone icon-mic-disabled");
  3378. })) {
  3379. // We still click the button.
  3380. UIUtil.buttonClick("#toolbar_button_mute", "icon-microphone icon-mic-disabled");
  3381. return;
  3382. }
  3383. };
  3384. UI.addListener = function (type, listener) {
  3385. eventEmitter.on(type, listener);
  3386. };
  3387. UI.clickOnVideo = function (videoNumber) {
  3388. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  3389. if (remoteVideos.length > videoNumber) {
  3390. remoteVideos[videoNumber].click();
  3391. }
  3392. };
  3393. //Used by torture
  3394. UI.showToolbar = function () {
  3395. return ToolbarToggler.showToolbar();
  3396. };
  3397. //Used by torture
  3398. UI.dockToolbar = function (isDock) {
  3399. return ToolbarToggler.dockToolbar(isDock);
  3400. };
  3401. UI.setVideoMuteButtonsState = function (mute) {
  3402. var video = $('#toolbar_button_camera');
  3403. var communicativeClass = "icon-camera";
  3404. var muteClass = "icon-camera icon-camera-disabled";
  3405. if (mute) {
  3406. video.removeClass(communicativeClass);
  3407. video.addClass(muteClass);
  3408. } else {
  3409. video.removeClass(muteClass);
  3410. video.addClass(communicativeClass);
  3411. }
  3412. };
  3413. UI.userAvatarChanged = function (resourceJid, thumbUrl, contactListUrl) {
  3414. VideoLayout.userAvatarChanged(resourceJid, thumbUrl);
  3415. ContactList.userAvatarChanged(resourceJid, contactListUrl);
  3416. if(resourceJid === APP.xmpp.myResource())
  3417. SettingsMenu.changeAvatar(thumbUrl);
  3418. };
  3419. UI.setVideoMute = setVideoMute;
  3420. module.exports = UI;
  3421. },{"../../service/RTC/RTCEvents":152,"../../service/RTC/StreamEventTypes":154,"../../service/UI/UIEvents":155,"../../service/connectionquality/CQEvents":157,"../../service/desktopsharing/DesktopSharingEventTypes":158,"../../service/members/Events":159,"../../service/xmpp/XMPPEvents":161,"../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":162}],12:[function(require,module,exports){
  3422. /* global APP, interfaceConfig, $, Strophe */
  3423. var CanvasUtil = require("./CanvasUtils");
  3424. var ASDrawContext = null;
  3425. function initActiveSpeakerAudioLevels() {
  3426. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  3427. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  3428. // Draw a circle.
  3429. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  3430. // Add a shadow around the circle
  3431. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  3432. ASDrawContext.shadowOffsetX = 0;
  3433. ASDrawContext.shadowOffsetY = 0;
  3434. }
  3435. /**
  3436. * The audio Levels plugin.
  3437. */
  3438. var AudioLevels = (function(my) {
  3439. var audioLevelCanvasCache = {};
  3440. my.LOCAL_LEVEL = 'local';
  3441. my.init = function () {
  3442. ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  3443. initActiveSpeakerAudioLevels();
  3444. };
  3445. /**
  3446. * Updates the audio level canvas for the given peerJid. If the canvas
  3447. * didn't exist we create it.
  3448. */
  3449. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  3450. var resourceJid = null;
  3451. var videoSpanId = null;
  3452. if (!peerJid)
  3453. videoSpanId = 'localVideoContainer';
  3454. else {
  3455. resourceJid = Strophe.getResourceFromJid(peerJid);
  3456. videoSpanId = 'participant_' + resourceJid;
  3457. }
  3458. var videoSpan = document.getElementById(videoSpanId);
  3459. if (!videoSpan) {
  3460. if (resourceJid)
  3461. console.error("No video element for jid", resourceJid);
  3462. else
  3463. console.error("No video element for local video.");
  3464. return;
  3465. }
  3466. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  3467. var videoSpaceWidth = $('#remoteVideos').width();
  3468. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  3469. var thumbnailWidth = thumbnailSize[0];
  3470. var thumbnailHeight = thumbnailSize[1];
  3471. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  3472. audioLevelCanvas = document.createElement('canvas');
  3473. audioLevelCanvas.className = "audiolevel";
  3474. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3475. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3476. resizeAudioLevelCanvas( audioLevelCanvas,
  3477. thumbnailWidth,
  3478. thumbnailHeight);
  3479. videoSpan.appendChild(audioLevelCanvas);
  3480. } else {
  3481. audioLevelCanvas = audioLevelCanvas.get(0);
  3482. resizeAudioLevelCanvas( audioLevelCanvas,
  3483. thumbnailWidth,
  3484. thumbnailHeight);
  3485. }
  3486. };
  3487. /**
  3488. * Updates the audio level UI for the given resourceJid.
  3489. *
  3490. * @param resourceJid the resource jid indicating the video element for
  3491. * which we draw the audio level
  3492. * @param audioLevel the newAudio level to render
  3493. */
  3494. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  3495. drawAudioLevelCanvas(resourceJid, audioLevel);
  3496. var videoSpanId = getVideoSpanId(resourceJid);
  3497. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  3498. if (!audioLevelCanvas)
  3499. return;
  3500. var drawContext = audioLevelCanvas.getContext('2d');
  3501. var canvasCache = audioLevelCanvasCache[resourceJid];
  3502. drawContext.clearRect (0, 0,
  3503. audioLevelCanvas.width, audioLevelCanvas.height);
  3504. drawContext.drawImage(canvasCache, 0, 0);
  3505. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  3506. if(!APP.xmpp.myJid()) {
  3507. return;
  3508. }
  3509. resourceJid = APP.xmpp.myResource();
  3510. }
  3511. if(resourceJid === largeVideoResourceJid) {
  3512. window.requestAnimationFrame(function () {
  3513. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  3514. });
  3515. }
  3516. };
  3517. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  3518. if($("#activeSpeaker").css("visibility") == "hidden" || ASDrawContext === null)
  3519. return;
  3520. ASDrawContext.clearRect(0, 0, 300, 300);
  3521. if(audioLevel == 0)
  3522. return;
  3523. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  3524. // Fill the shape.
  3525. ASDrawContext.fill();
  3526. };
  3527. /**
  3528. * Resizes the given audio level canvas to match the given thumbnail size.
  3529. */
  3530. function resizeAudioLevelCanvas(audioLevelCanvas,
  3531. thumbnailWidth,
  3532. thumbnailHeight) {
  3533. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  3534. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  3535. }
  3536. /**
  3537. * Draws the audio level canvas into the cached canvas object.
  3538. *
  3539. * @param resourceJid the resource jid indicating the video element for
  3540. * which we draw the audio level
  3541. * @param audioLevel the newAudio level to render
  3542. */
  3543. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  3544. if (!audioLevelCanvasCache[resourceJid]) {
  3545. var videoSpanId = getVideoSpanId(resourceJid);
  3546. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  3547. /*
  3548. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  3549. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  3550. * error. Since audio levels are frequently updated, the errors have
  3551. * been observed to pile into the console, strain the CPU.
  3552. */
  3553. if (audioLevelCanvasOrig) {
  3554. audioLevelCanvasCache[resourceJid] =
  3555. CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  3556. }
  3557. }
  3558. var canvas = audioLevelCanvasCache[resourceJid];
  3559. if (!canvas)
  3560. return;
  3561. var drawContext = canvas.getContext('2d');
  3562. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  3563. var shadowLevel = getShadowLevel(audioLevel);
  3564. if (shadowLevel > 0) {
  3565. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  3566. CanvasUtil.drawRoundRectGlow(drawContext,
  3567. interfaceConfig.CANVAS_EXTRA / 2, interfaceConfig.CANVAS_EXTRA / 2,
  3568. canvas.width - interfaceConfig.CANVAS_EXTRA,
  3569. canvas.height - interfaceConfig.CANVAS_EXTRA,
  3570. interfaceConfig.CANVAS_RADIUS,
  3571. interfaceConfig.SHADOW_COLOR,
  3572. shadowLevel);
  3573. }
  3574. }
  3575. /**
  3576. * Returns the shadow/glow level for the given audio level.
  3577. *
  3578. * @param audioLevel the audio level from which we determine the shadow
  3579. * level
  3580. */
  3581. function getShadowLevel (audioLevel) {
  3582. var shadowLevel = 0;
  3583. if (audioLevel <= 0.3) {
  3584. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  3585. }
  3586. else if (audioLevel <= 0.6) {
  3587. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  3588. }
  3589. else {
  3590. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  3591. }
  3592. return shadowLevel;
  3593. }
  3594. /**
  3595. * Returns the video span id corresponding to the given resourceJid or local
  3596. * user.
  3597. */
  3598. function getVideoSpanId(resourceJid) {
  3599. var videoSpanId = null;
  3600. if (resourceJid === AudioLevels.LOCAL_LEVEL ||
  3601. (APP.xmpp.myResource() && resourceJid === APP.xmpp.myResource()))
  3602. videoSpanId = 'localVideoContainer';
  3603. else
  3604. videoSpanId = 'participant_' + resourceJid;
  3605. return videoSpanId;
  3606. }
  3607. /**
  3608. * Indicates that the remote video has been resized.
  3609. */
  3610. $(document).bind('remotevideo.resized', function (event, width, height) {
  3611. var resized = false;
  3612. $('#remoteVideos>span>canvas').each(function() {
  3613. var canvas = $(this).get(0);
  3614. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  3615. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  3616. resized = true;
  3617. }
  3618. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  3619. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  3620. resized = true;
  3621. }
  3622. });
  3623. if (resized)
  3624. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  3625. audioLevelCanvasCache[resourceJid].width =
  3626. width + interfaceConfig.CANVAS_EXTRA;
  3627. audioLevelCanvasCache[resourceJid].height =
  3628. height + interfaceConfig.CANVAS_EXTRA;
  3629. });
  3630. });
  3631. return my;
  3632. })(AudioLevels || {});
  3633. module.exports = AudioLevels;
  3634. },{"./CanvasUtils":13}],13:[function(require,module,exports){
  3635. /**
  3636. * Utility class for drawing canvas shapes.
  3637. */
  3638. var CanvasUtil = (function(my) {
  3639. /**
  3640. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  3641. * of the glow.
  3642. *
  3643. * @param drawContext the context of the canvas to draw to
  3644. * @param x the x coordinate of the round rectangle
  3645. * @param y the y coordinate of the round rectangle
  3646. * @param w the width of the round rectangle
  3647. * @param h the height of the round rectangle
  3648. * @param glowColor the color of the glow
  3649. * @param glowWidth the width of the glow
  3650. */
  3651. my.drawRoundRectGlow
  3652. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  3653. // Save the previous state of the context.
  3654. drawContext.save();
  3655. if (w < 2 * r) r = w / 2;
  3656. if (h < 2 * r) r = h / 2;
  3657. // Draw a round rectangle.
  3658. drawContext.beginPath();
  3659. drawContext.moveTo(x+r, y);
  3660. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3661. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3662. drawContext.arcTo(x, y+h, x, y, r);
  3663. drawContext.arcTo(x, y, x+w, y, r);
  3664. drawContext.closePath();
  3665. // Add a shadow around the rectangle
  3666. drawContext.shadowColor = glowColor;
  3667. drawContext.shadowBlur = glowWidth;
  3668. drawContext.shadowOffsetX = 0;
  3669. drawContext.shadowOffsetY = 0;
  3670. // Fill the shape.
  3671. drawContext.fill();
  3672. drawContext.save();
  3673. drawContext.restore();
  3674. // 1) Uncomment this line to use Composite Operation, which is doing the
  3675. // same as the clip function below and is also antialiasing the round
  3676. // border, but is said to be less fast performance wise.
  3677. // drawContext.globalCompositeOperation='destination-out';
  3678. drawContext.beginPath();
  3679. drawContext.moveTo(x+r, y);
  3680. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3681. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3682. drawContext.arcTo(x, y+h, x, y, r);
  3683. drawContext.arcTo(x, y, x+w, y, r);
  3684. drawContext.closePath();
  3685. // 2) Uncomment this line to use Composite Operation, which is doing the
  3686. // same as the clip function below and is also antialiasing the round
  3687. // border, but is said to be less fast performance wise.
  3688. // drawContext.fill();
  3689. // Comment these two lines if choosing to do the same with composite
  3690. // operation above 1 and 2.
  3691. drawContext.clip();
  3692. drawContext.clearRect(0, 0, 277, 200);
  3693. // Restore the previous context state.
  3694. drawContext.restore();
  3695. };
  3696. /**
  3697. * Clones the given canvas.
  3698. *
  3699. * @return the new cloned canvas.
  3700. */
  3701. my.cloneCanvas = function (oldCanvas) {
  3702. /*
  3703. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  3704. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  3705. * levels are frequently updated, the errors have been observed to pile
  3706. * into the console, strain the CPU.
  3707. */
  3708. if (!oldCanvas)
  3709. return oldCanvas;
  3710. //create a new canvas
  3711. var newCanvas = document.createElement('canvas');
  3712. var context = newCanvas.getContext('2d');
  3713. //set dimensions
  3714. newCanvas.width = oldCanvas.width;
  3715. newCanvas.height = oldCanvas.height;
  3716. //apply the old canvas to the new one
  3717. context.drawImage(oldCanvas, 0, 0);
  3718. //return the new canvas
  3719. return newCanvas;
  3720. };
  3721. return my;
  3722. })(CanvasUtil || {});
  3723. module.exports = CanvasUtil;
  3724. },{}],14:[function(require,module,exports){
  3725. /* global $, APP*/
  3726. var LoginDialog = require('./LoginDialog');
  3727. var Moderator = require('../../xmpp/moderator');
  3728. /* Initial "authentication required" dialog */
  3729. var authDialog = null;
  3730. /* Loop retry ID that wits for other user to create the room */
  3731. var authRetryId = null;
  3732. var authenticationWindow = null;
  3733. var Authentication = {
  3734. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  3735. // This is the loop that will wait for the room to be created by
  3736. // someone else. 'auth_required.moderator' will bring us back here.
  3737. authRetryId = window.setTimeout(intervalCallback, 5000);
  3738. // Show prompt only if it's not open
  3739. if (authDialog !== null) {
  3740. return;
  3741. }
  3742. // extract room name from 'room@muc.server.net'
  3743. var room = roomName.substr(0, roomName.indexOf('@'));
  3744. var title
  3745. = APP.translation.generateTranslationHTML("dialog.WaitingForHost");
  3746. var msg
  3747. = APP.translation.generateTranslationHTML(
  3748. "dialog.WaitForHostMsg", {room: room});
  3749. var buttonTxt
  3750. = APP.translation.generateTranslationHTML("dialog.IamHost");
  3751. var buttons = [];
  3752. buttons.push({title: buttonTxt, value: "authNow"});
  3753. authDialog = APP.UI.messageHandler.openDialog(
  3754. title,
  3755. msg,
  3756. true,
  3757. buttons,
  3758. function (onSubmitEvent, submitValue) {
  3759. // Do not close the dialog yet
  3760. onSubmitEvent.preventDefault();
  3761. // Open login popup
  3762. if (submitValue === 'authNow') {
  3763. callback();
  3764. }
  3765. }
  3766. );
  3767. },
  3768. closeAuthenticationWindow: function () {
  3769. if (authenticationWindow) {
  3770. authenticationWindow.close();
  3771. authenticationWindow = null;
  3772. }
  3773. },
  3774. xmppAuthenticate: function () {
  3775. var loginDialog = LoginDialog.show(
  3776. function (connection, state) {
  3777. if (!state) {
  3778. // User cancelled
  3779. loginDialog.close();
  3780. return;
  3781. } else if (state == APP.xmpp.Status.CONNECTED) {
  3782. loginDialog.close();
  3783. Authentication.stopInterval();
  3784. Authentication.closeAuthenticationDialog();
  3785. // Close the connection as anonymous one will be used
  3786. // to create the conference. Session-id will authorize
  3787. // the request.
  3788. connection.disconnect();
  3789. var roomName = APP.UI.generateRoomName();
  3790. Moderator.allocateConferenceFocus(roomName, function () {
  3791. // If it's not "on the fly" authentication now join
  3792. // the conference room
  3793. if (!APP.xmpp.isMUCJoined()) {
  3794. APP.UI.checkForNicknameAndJoin();
  3795. }
  3796. });
  3797. }
  3798. }, true);
  3799. },
  3800. focusAuthenticationWindow: function () {
  3801. // If auth window exists just bring it to the front
  3802. if (authenticationWindow) {
  3803. authenticationWindow.focus();
  3804. return;
  3805. }
  3806. },
  3807. closeAuthenticationDialog: function () {
  3808. // Close authentication dialog if opened
  3809. if (authDialog) {
  3810. authDialog.close();
  3811. authDialog = null;
  3812. }
  3813. },
  3814. createAuthenticationWindow: function (callback, url) {
  3815. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  3816. url, 910, 660,
  3817. // On closed
  3818. function () {
  3819. // Close authentication dialog if opened
  3820. Authentication.closeAuthenticationDialog();
  3821. callback();
  3822. authenticationWindow = null;
  3823. });
  3824. return authenticationWindow;
  3825. },
  3826. stopInterval: function () {
  3827. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  3828. if (authRetryId) {
  3829. window.clearTimeout(authRetryId);
  3830. authRetryId = null;
  3831. }
  3832. }
  3833. };
  3834. module.exports = Authentication;
  3835. },{"../../xmpp/moderator":60,"./LoginDialog":15}],15:[function(require,module,exports){
  3836. /* global $, APP, config*/
  3837. var XMPP = require('../../xmpp/xmpp');
  3838. var Moderator = require('../../xmpp/moderator');
  3839. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  3840. // anonymous domain is not enabled
  3841. /**
  3842. * Creates new <tt>Dialog</tt> instance.
  3843. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  3844. * when we either fail to connect or succeed(check Strophe.Status).
  3845. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  3846. * in order to create session-id after the connection is established.
  3847. * @constructor
  3848. */
  3849. function Dialog(callback, obtainSession) {
  3850. var self = this;
  3851. var stop = false;
  3852. var connection = APP.xmpp.createConnection();
  3853. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3854. message += APP.translation.translateString("dialog.passwordRequired");
  3855. message += '</h2>' +
  3856. '<input name="username" type="text" ' +
  3857. 'placeholder="user@domain.net" autofocus>' +
  3858. '<input name="password" ' +
  3859. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3860. ' placeholder="user password">';
  3861. var okButton = APP.translation.generateTranslationHTML("dialog.Ok");
  3862. var cancelButton = APP.translation.generateTranslationHTML("dialog.Cancel");
  3863. var states = {
  3864. login: {
  3865. html: message,
  3866. buttons: [
  3867. { title: okButton, value: true},
  3868. { title: cancelButton, value: false}
  3869. ],
  3870. focus: ':input:first',
  3871. submit: function (e, v, m, f) {
  3872. e.preventDefault();
  3873. if (v) {
  3874. var jid = f.username;
  3875. var password = f.password;
  3876. if (jid && password) {
  3877. stop = false;
  3878. connection.reset();
  3879. connDialog.goToState('connecting');
  3880. connection.connect(jid, password, stateHandler);
  3881. }
  3882. } else {
  3883. // User cancelled
  3884. stop = true;
  3885. callback();
  3886. }
  3887. }
  3888. },
  3889. connecting: {
  3890. title: APP.translation.translateString('dialog.connecting'),
  3891. html: '<div id="connectionStatus"></div>',
  3892. buttons: [],
  3893. defaultButton: 0
  3894. },
  3895. finished: {
  3896. title: APP.translation.translateString('dialog.error'),
  3897. html: '<div id="errorMessage"></div>',
  3898. buttons: [
  3899. {
  3900. title: APP.translation.translateString('dialog.retry'),
  3901. value: 'retry'
  3902. },
  3903. {
  3904. title: APP.translation.translateString('dialog.Cancel'),
  3905. value: 'cancel'
  3906. },
  3907. ],
  3908. defaultButton: 0,
  3909. submit: function (e, v, m, f) {
  3910. e.preventDefault();
  3911. if (v === 'retry')
  3912. connDialog.goToState('login');
  3913. else
  3914. callback();
  3915. }
  3916. }
  3917. };
  3918. var connDialog
  3919. = APP.UI.messageHandler.openDialogWithStates(states,
  3920. { persistent: true, closeText: '' }, null);
  3921. var stateHandler = function (status, message) {
  3922. if (stop) {
  3923. return;
  3924. }
  3925. var translateKey = "connection." + XMPP.getStatusString(status);
  3926. var statusStr = APP.translation.translateString(translateKey);
  3927. // Display current state
  3928. var connectionStatus =
  3929. connDialog.getState('connecting').find('#connectionStatus');
  3930. connectionStatus.text(statusStr);
  3931. switch (status) {
  3932. case XMPP.Status.CONNECTED:
  3933. stop = true;
  3934. if (!obtainSession) {
  3935. callback(connection, status);
  3936. return;
  3937. }
  3938. // Obtaining session-id status
  3939. connectionStatus.text(
  3940. APP.translation.translateString(
  3941. 'connection.FETCH_SESSION_ID'));
  3942. // Authenticate with Jicofo and obtain session-id
  3943. var roomName = APP.UI.generateRoomName();
  3944. // Jicofo will return new session-id when connected
  3945. // from authenticated domain
  3946. connection.sendIQ(
  3947. Moderator.createConferenceIq(roomName),
  3948. function (result) {
  3949. connectionStatus.text(
  3950. APP.translation.translateString(
  3951. 'connection.GOT_SESSION_ID'));
  3952. stop = true;
  3953. // Parse session-id
  3954. Moderator.parseSessionId(result);
  3955. callback(connection, status);
  3956. },
  3957. function (error) {
  3958. console.error("Auth on the fly failed", error);
  3959. stop = true;
  3960. var errorMsg =
  3961. APP.translation.translateString(
  3962. 'connection.GET_SESSION_ID_ERROR') +
  3963. $(error).find('>error').attr('code');
  3964. self.displayError(errorMsg);
  3965. connection.disconnect();
  3966. });
  3967. break;
  3968. case XMPP.Status.AUTHFAIL:
  3969. case XMPP.Status.CONNFAIL:
  3970. case XMPP.Status.DISCONNECTED:
  3971. stop = true;
  3972. callback(connection, status);
  3973. var errorMessage = statusStr;
  3974. if (message)
  3975. {
  3976. errorMessage += ': ' + message;
  3977. }
  3978. self.displayError(errorMessage);
  3979. break;
  3980. default:
  3981. break;
  3982. }
  3983. };
  3984. /**
  3985. * Displays error message in 'finished' state which allows either to cancel
  3986. * or retry.
  3987. * @param message the final message to be displayed.
  3988. */
  3989. this.displayError = function (message) {
  3990. var finishedState = connDialog.getState('finished');
  3991. var errorMessageElem = finishedState.find('#errorMessage');
  3992. errorMessageElem.text(message);
  3993. connDialog.goToState('finished');
  3994. };
  3995. /**
  3996. * Closes LoginDialog.
  3997. */
  3998. this.close = function () {
  3999. stop = true;
  4000. connDialog.close();
  4001. };
  4002. }
  4003. var LoginDialog = {
  4004. /**
  4005. * Displays login prompt used to establish new XMPP connection. Given
  4006. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  4007. * called when we connect successfully(status === CONNECTED) or when we fail
  4008. * to do so. On connection failure program can call Dialog.close() method in
  4009. * order to cancel or do nothing to let the user retry.
  4010. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  4011. * called when we either fail to connect or succeed(check
  4012. * Strophe.Status).
  4013. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  4014. * Jicofo in order to create session-id after the connection is
  4015. * established.
  4016. * @returns {Dialog}
  4017. */
  4018. show: function (callback, obtainSession) {
  4019. return new Dialog(callback, obtainSession);
  4020. }
  4021. };
  4022. module.exports = LoginDialog;
  4023. },{"../../xmpp/moderator":60,"../../xmpp/xmpp":68}],16:[function(require,module,exports){
  4024. var Settings = require("../../settings/Settings");
  4025. var users = {};
  4026. var Avatar = {
  4027. /**
  4028. * Sets the user's avatar in the settings menu(if local user), contact list
  4029. * and thumbnail
  4030. * @param jid jid of the user
  4031. * @param id email or userID to be used as a hash
  4032. */
  4033. setUserAvatar: function (jid, id) {
  4034. if (id) {
  4035. if (users[jid] === id) {
  4036. return;
  4037. }
  4038. users[jid] = id;
  4039. }
  4040. var thumbUrl = this.getThumbUrl(jid);
  4041. var contactListUrl = this.getContactListUrl(jid);
  4042. var resourceJid = Strophe.getResourceFromJid(jid);
  4043. APP.UI.userAvatarChanged(resourceJid, thumbUrl, contactListUrl);
  4044. },
  4045. /**
  4046. * Returns image URL for the avatar to be displayed on large video area
  4047. * where current active speaker is presented.
  4048. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4049. */
  4050. getActiveSpeakerUrl: function (jid) {
  4051. return this.getGravatarUrl(jid, 100);
  4052. },
  4053. /**
  4054. * Returns image URL for the avatar to be displayed on small video thumbnail
  4055. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4056. */
  4057. getThumbUrl: function (jid) {
  4058. return this.getGravatarUrl(jid, 100);
  4059. },
  4060. /**
  4061. * Returns the URL for the avatar to be displayed as contactlist item
  4062. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4063. */
  4064. getContactListUrl: function (jid) {
  4065. return this.getGravatarUrl(jid, 30);
  4066. },
  4067. getGravatarUrl: function (jid, size) {
  4068. if (!jid) {
  4069. console.error("Get gravatar - jid is undefined");
  4070. return null;
  4071. }
  4072. var id = users[jid];
  4073. if (!id) {
  4074. console.warn(
  4075. "No avatar stored yet for " + jid + " - using JID as ID");
  4076. id = jid;
  4077. }
  4078. return 'https://www.gravatar.com/avatar/' +
  4079. MD5.hexdigest(id.trim().toLowerCase()) +
  4080. "?d=wavatar&size=" + (size || "30");
  4081. }
  4082. };
  4083. module.exports = Avatar;
  4084. },{"../../settings/Settings":47}],17:[function(require,module,exports){
  4085. /* global $, config,
  4086. setLargeVideoVisible, Util */
  4087. var VideoLayout = require("../videolayout/VideoLayout");
  4088. var Prezi = require("../prezi/Prezi");
  4089. var UIUtil = require("../util/UIUtil");
  4090. var etherpadName = null;
  4091. var etherpadIFrame = null;
  4092. var domain = null;
  4093. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  4094. /**
  4095. * Resizes the etherpad.
  4096. */
  4097. function resize() {
  4098. if ($('#etherpad>iframe').length) {
  4099. var remoteVideos = $('#remoteVideos');
  4100. var availableHeight
  4101. = window.innerHeight - remoteVideos.outerHeight();
  4102. var availableWidth = UIUtil.getAvailableVideoWidth();
  4103. $('#etherpad>iframe').width(availableWidth);
  4104. $('#etherpad>iframe').height(availableHeight);
  4105. }
  4106. }
  4107. /**
  4108. * Creates the Etherpad button and adds it to the toolbar.
  4109. */
  4110. function enableEtherpadButton() {
  4111. if (!$('#toolbar_button_etherpad').is(":visible"))
  4112. $('#toolbar_button_etherpad').css({display: 'inline-block'});
  4113. }
  4114. /**
  4115. * Creates the IFrame for the etherpad.
  4116. */
  4117. function createIFrame() {
  4118. etherpadIFrame = VideoLayout.createEtherpadIframe(
  4119. domain + etherpadName + options, function() {
  4120. document.domain = document.domain;
  4121. bubbleIframeMouseMove(etherpadIFrame);
  4122. setTimeout(function() {
  4123. // the iframes inside of the etherpad are
  4124. // not yet loaded when the etherpad iframe is loaded
  4125. var outer = etherpadIFrame.
  4126. contentDocument.getElementsByName("ace_outer")[0];
  4127. bubbleIframeMouseMove(outer);
  4128. var inner = outer.
  4129. contentDocument.getElementsByName("ace_inner")[0];
  4130. bubbleIframeMouseMove(inner);
  4131. }, 2000);
  4132. });
  4133. }
  4134. function bubbleIframeMouseMove(iframe){
  4135. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  4136. iframe.contentWindow.onmousemove = function(e){
  4137. if(existingOnMouseMove) existingOnMouseMove(e);
  4138. var evt = document.createEvent("MouseEvents");
  4139. var boundingClientRect = iframe.getBoundingClientRect();
  4140. evt.initMouseEvent(
  4141. "mousemove",
  4142. true, // bubbles
  4143. false, // not cancelable
  4144. window,
  4145. e.detail,
  4146. e.screenX,
  4147. e.screenY,
  4148. e.clientX + boundingClientRect.left,
  4149. e.clientY + boundingClientRect.top,
  4150. e.ctrlKey,
  4151. e.altKey,
  4152. e.shiftKey,
  4153. e.metaKey,
  4154. e.button,
  4155. null // no related element
  4156. );
  4157. iframe.dispatchEvent(evt);
  4158. };
  4159. }
  4160. var Etherpad = {
  4161. /**
  4162. * Initializes the etherpad.
  4163. */
  4164. init: function (name) {
  4165. if (config.etherpad_base && !etherpadName && name) {
  4166. domain = config.etherpad_base;
  4167. etherpadName = name;
  4168. enableEtherpadButton();
  4169. /**
  4170. * Resizes the etherpad, when the window is resized.
  4171. */
  4172. $(window).resize(function () {
  4173. resize();
  4174. });
  4175. }
  4176. },
  4177. /**
  4178. * Opens/hides the Etherpad.
  4179. */
  4180. toggleEtherpad: function (isPresentation) {
  4181. if (!etherpadIFrame)
  4182. createIFrame();
  4183. if(VideoLayout.getLargeVideoState() === "etherpad")
  4184. {
  4185. VideoLayout.setLargeVideoState("video");
  4186. }
  4187. else
  4188. {
  4189. VideoLayout.setLargeVideoState("etherpad");
  4190. }
  4191. resize();
  4192. }
  4193. };
  4194. module.exports = Etherpad;
  4195. },{"../prezi/Prezi":18,"../util/UIUtil":33,"../videolayout/VideoLayout":39}],18:[function(require,module,exports){
  4196. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4197. var UIUtil = require("../util/UIUtil");
  4198. var VideoLayout = require("../videolayout/VideoLayout");
  4199. var messageHandler = require("../util/MessageHandler");
  4200. var PreziPlayer = require("./PreziPlayer");
  4201. var preziPlayer = null;
  4202. /**
  4203. * Shows/hides a presentation.
  4204. */
  4205. function setPresentationVisible(visible) {
  4206. if (visible) {
  4207. VideoLayout.setLargeVideoState("prezi");
  4208. }
  4209. else {
  4210. VideoLayout.setLargeVideoState("video");
  4211. }
  4212. }
  4213. var Prezi = {
  4214. /**
  4215. * Reloads the current presentation.
  4216. */
  4217. reloadPresentation: function() {
  4218. var iframe = document.getElementById(preziPlayer.options.preziId);
  4219. iframe.src = iframe.src;
  4220. },
  4221. /**
  4222. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  4223. * otherwise.
  4224. */
  4225. isPresentationVisible: function () {
  4226. return ($('#presentation>iframe') != null
  4227. && $('#presentation>iframe').css('opacity') == 1);
  4228. },
  4229. /**
  4230. * Opens the Prezi dialog, from which the user could choose a presentation
  4231. * to load.
  4232. */
  4233. openPreziDialog: function() {
  4234. var myprezi = APP.xmpp.getPrezi();
  4235. if (myprezi) {
  4236. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  4237. null,
  4238. "dialog.removePreziMsg",
  4239. null,
  4240. false,
  4241. "dialog.Remove",
  4242. function(e,v,m,f) {
  4243. if(v) {
  4244. APP.xmpp.removePreziFromPresence();
  4245. }
  4246. }
  4247. );
  4248. }
  4249. else if (preziPlayer != null) {
  4250. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  4251. null, "dialog.sharePreziMsg",
  4252. null,
  4253. false,
  4254. "dialog.Ok",
  4255. function(e,v,m,f) {
  4256. $.prompt.close();
  4257. }
  4258. );
  4259. }
  4260. else {
  4261. var html = APP.translation.generateTranslationHTML(
  4262. "dialog.sharePreziTitle");
  4263. var cancelButton = APP.translation.generateTranslationHTML(
  4264. "dialog.Cancel");
  4265. var shareButton = APP.translation.generateTranslationHTML(
  4266. "dialog.Share");
  4267. var backButton = APP.translation.generateTranslationHTML(
  4268. "dialog.Back");
  4269. var buttons = [];
  4270. var buttons1 = [];
  4271. // Cancel button to both states
  4272. buttons.push({title: cancelButton, value: false});
  4273. buttons1.push({title: cancelButton, value: false});
  4274. // Share button
  4275. buttons.push({title: shareButton, value: true});
  4276. // Back button
  4277. buttons1.push({title: backButton, value: true});
  4278. var linkError = APP.translation.generateTranslationHTML(
  4279. "dialog.preziLinkError");
  4280. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  4281. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  4282. var openPreziState = {
  4283. state0: {
  4284. html: '<h2>' + html + '</h2>' +
  4285. '<input name="preziUrl" type="text" ' +
  4286. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  4287. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  4288. '\' placeholder="' + defaultUrl + '" autofocus>',
  4289. persistent: false,
  4290. buttons: buttons,
  4291. focus: ':input:first',
  4292. defaultButton: 0,
  4293. submit: function (e, v, m, f) {
  4294. e.preventDefault();
  4295. if(v)
  4296. {
  4297. var preziUrl = f.preziUrl;
  4298. if (preziUrl)
  4299. {
  4300. var urlValue
  4301. = encodeURI(UIUtil.escapeHtml(preziUrl));
  4302. if (urlValue.indexOf('http://prezi.com/') != 0
  4303. && urlValue.indexOf('https://prezi.com/') != 0)
  4304. {
  4305. $.prompt.goToState('state1');
  4306. return false;
  4307. }
  4308. else {
  4309. var presIdTmp = urlValue.substring(
  4310. urlValue.indexOf("prezi.com/") + 10);
  4311. if (!isAlphanumeric(presIdTmp)
  4312. || presIdTmp.indexOf('/') < 2) {
  4313. $.prompt.goToState('state1');
  4314. return false;
  4315. }
  4316. else {
  4317. APP.xmpp.addToPresence("prezi", urlValue);
  4318. $.prompt.close();
  4319. }
  4320. }
  4321. }
  4322. }
  4323. else
  4324. $.prompt.close();
  4325. }
  4326. },
  4327. state1: {
  4328. html: '<h2>' + html + '</h2>' +
  4329. linkError,
  4330. persistent: false,
  4331. buttons: buttons1,
  4332. focus: ':input:first',
  4333. defaultButton: 1,
  4334. submit: function (e, v, m, f) {
  4335. e.preventDefault();
  4336. if (v === 0)
  4337. $.prompt.close();
  4338. else
  4339. $.prompt.goToState('state0');
  4340. }
  4341. }
  4342. };
  4343. messageHandler.openDialogWithStates(openPreziState);
  4344. }
  4345. }
  4346. };
  4347. /**
  4348. * A new presentation has been added.
  4349. *
  4350. * @param event the event indicating the add of a presentation
  4351. * @param jid the jid from which the presentation was added
  4352. * @param presUrl url of the presentation
  4353. * @param currentSlide the current slide to which we should move
  4354. */
  4355. function presentationAdded(event, jid, presUrl, currentSlide) {
  4356. console.log("presentation added", presUrl);
  4357. var presId = getPresentationId(presUrl);
  4358. var elementId = 'participant_'
  4359. + Strophe.getResourceFromJid(jid)
  4360. + '_' + presId;
  4361. VideoLayout.addPreziContainer(elementId);
  4362. var controlsEnabled = false;
  4363. if (jid === APP.xmpp.myJid())
  4364. controlsEnabled = true;
  4365. setPresentationVisible(true);
  4366. VideoLayout.setLargeVideoHover(
  4367. function (event) {
  4368. if (Prezi.isPresentationVisible()) {
  4369. var reloadButtonRight = window.innerWidth
  4370. - $('#presentation>iframe').offset().left
  4371. - $('#presentation>iframe').width();
  4372. $('#reloadPresentation').css({ right: reloadButtonRight,
  4373. display:'inline-block'});
  4374. }
  4375. },
  4376. function (event) {
  4377. if (!Prezi.isPresentationVisible())
  4378. $('#reloadPresentation').css({display:'none'});
  4379. else {
  4380. var e = event.toElement || event.relatedTarget;
  4381. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  4382. $('#reloadPresentation').css({display:'none'});
  4383. }
  4384. });
  4385. preziPlayer = new PreziPlayer(
  4386. 'presentation',
  4387. {preziId: presId,
  4388. width: getPresentationWidth(),
  4389. height: getPresentationHeihgt(),
  4390. controls: controlsEnabled,
  4391. debug: true
  4392. });
  4393. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  4394. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  4395. console.log("prezi status", event.value);
  4396. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  4397. if (jid != APP.xmpp.myJid())
  4398. preziPlayer.flyToStep(currentSlide);
  4399. }
  4400. });
  4401. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  4402. console.log("event value", event.value);
  4403. APP.xmpp.addToPresence("preziSlide", event.value);
  4404. });
  4405. $("#" + elementId).css( 'background-image',
  4406. 'url(../images/avatarprezi.png)');
  4407. $("#" + elementId).click(
  4408. function () {
  4409. setPresentationVisible(true);
  4410. }
  4411. );
  4412. };
  4413. /**
  4414. * A presentation has been removed.
  4415. *
  4416. * @param event the event indicating the remove of a presentation
  4417. * @param jid the jid for which the presentation was removed
  4418. * @param the url of the presentation
  4419. */
  4420. function presentationRemoved(event, jid, presUrl) {
  4421. console.log('presentation removed', presUrl);
  4422. var presId = getPresentationId(presUrl);
  4423. setPresentationVisible(false);
  4424. $('#participant_'
  4425. + Strophe.getResourceFromJid(jid)
  4426. + '_' + presId).remove();
  4427. $('#presentation>iframe').remove();
  4428. if (preziPlayer != null) {
  4429. preziPlayer.destroy();
  4430. preziPlayer = null;
  4431. }
  4432. };
  4433. /**
  4434. * Indicates if the given string is an alphanumeric string.
  4435. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  4436. * purpose of checking URIs.
  4437. */
  4438. function isAlphanumeric(unsafeText) {
  4439. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  4440. return regex.test(unsafeText);
  4441. }
  4442. /**
  4443. * Returns the presentation id from the given url.
  4444. */
  4445. function getPresentationId (presUrl) {
  4446. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  4447. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  4448. }
  4449. /**
  4450. * Returns the presentation width.
  4451. */
  4452. function getPresentationWidth() {
  4453. var availableWidth = UIUtil.getAvailableVideoWidth();
  4454. var availableHeight = getPresentationHeihgt();
  4455. var aspectRatio = 16.0 / 9.0;
  4456. if (availableHeight < availableWidth / aspectRatio) {
  4457. availableWidth = Math.floor(availableHeight * aspectRatio);
  4458. }
  4459. return availableWidth;
  4460. }
  4461. /**
  4462. * Returns the presentation height.
  4463. */
  4464. function getPresentationHeihgt() {
  4465. var remoteVideos = $('#remoteVideos');
  4466. return window.innerHeight - remoteVideos.outerHeight();
  4467. }
  4468. /**
  4469. * Resizes the presentation iframe.
  4470. */
  4471. function resize() {
  4472. if ($('#presentation>iframe')) {
  4473. $('#presentation>iframe').width(getPresentationWidth());
  4474. $('#presentation>iframe').height(getPresentationHeihgt());
  4475. }
  4476. }
  4477. /**
  4478. * Presentation has been removed.
  4479. */
  4480. $(document).bind('presentationremoved.muc', presentationRemoved);
  4481. /**
  4482. * Presentation has been added.
  4483. */
  4484. $(document).bind('presentationadded.muc', presentationAdded);
  4485. /*
  4486. * Indicates presentation slide change.
  4487. */
  4488. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  4489. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  4490. preziPlayer.flyToStep(current);
  4491. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  4492. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  4493. preziPlayer.flyToStep(current, i);
  4494. }
  4495. }
  4496. });
  4497. $(window).resize(function () {
  4498. resize();
  4499. });
  4500. module.exports = Prezi;
  4501. },{"../toolbars/ToolbarToggler":29,"../util/MessageHandler":31,"../util/UIUtil":33,"../videolayout/VideoLayout":39,"./PreziPlayer":19}],19:[function(require,module,exports){
  4502. (function() {
  4503. "use strict";
  4504. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  4505. window.PreziPlayer = (function() {
  4506. PreziPlayer.API_VERSION = 1;
  4507. PreziPlayer.CURRENT_STEP = 'currentStep';
  4508. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  4509. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  4510. PreziPlayer.STATUS_LOADING = 'loading';
  4511. PreziPlayer.STATUS_READY = 'ready';
  4512. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  4513. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  4514. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  4515. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  4516. PreziPlayer.EVENT_STATUS = "statusChange";
  4517. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  4518. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  4519. PreziPlayer.domain = "https://prezi.com";
  4520. PreziPlayer.path = "/player/";
  4521. PreziPlayer.players = {};
  4522. PreziPlayer.binded_methods = ['changesHandler'];
  4523. PreziPlayer.createMultiplePlayers = function(optionArray){
  4524. for(var i=0; i<optionArray.length; i++) {
  4525. var optionSet = optionArray[i];
  4526. new PreziPlayer(optionSet.id, optionSet);
  4527. };
  4528. };
  4529. PreziPlayer.messageReceived = function(event){
  4530. var message, item, player;
  4531. try {
  4532. message = JSON.parse(event.data);
  4533. if (message.id && (player = PreziPlayer.players[message.id])) {
  4534. if (player.options.debug === true) {
  4535. if (console && console.log)
  4536. console.log('received', message);
  4537. }
  4538. if (message.type === "changes") {
  4539. player.changesHandler(message);
  4540. }
  4541. for (var i = 0; i < player.callbacks.length; i++) {
  4542. item = player.callbacks[i];
  4543. if (item && message.type === item.event) {
  4544. item.callback(message);
  4545. }
  4546. }
  4547. }
  4548. } catch (e) { }
  4549. };
  4550. function PreziPlayer(id, options) {
  4551. var params, paramString = "", _this = this;
  4552. if (PreziPlayer.players[id]){
  4553. PreziPlayer.players[id].destroy();
  4554. }
  4555. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  4556. var method_name = PreziPlayer.binded_methods[i];
  4557. _this[method_name] = __bind(_this[method_name], _this);
  4558. };
  4559. options = options || {};
  4560. this.options = options;
  4561. this.values = {'status': PreziPlayer.STATUS_LOADING};
  4562. this.values[PreziPlayer.CURRENT_STEP] = 0;
  4563. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  4564. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  4565. this.callbacks = [];
  4566. this.id = id;
  4567. this.embedTo = document.getElementById(id);
  4568. if (!this.embedTo) {
  4569. throw "The element id is not available.";
  4570. }
  4571. this.iframe = document.createElement('iframe');
  4572. params = [
  4573. { name: 'oid', value: options.preziId },
  4574. { name: 'explorable', value: options.explorable ? 1 : 0 },
  4575. { name: 'controls', value: options.controls ? 1 : 0 }
  4576. ];
  4577. for(var i=0; i<params.length; i++) {
  4578. var param = params[i];
  4579. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  4580. };
  4581. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  4582. this.iframe.frameBorder = 0;
  4583. this.iframe.scrolling = "no";
  4584. this.iframe.width = options.width || 640;
  4585. this.iframe.height = options.height || 480;
  4586. this.embedTo.innerHTML = '';
  4587. // JITSI: IN CASE SOMETHING GOES WRONG.
  4588. try {
  4589. this.embedTo.appendChild(this.iframe);
  4590. }
  4591. catch (err) {
  4592. console.log("CATCH ERROR");
  4593. }
  4594. // JITSI: Increase interval from 200 to 500, which fixes prezi
  4595. // crashes for us.
  4596. this.initPollInterval = setInterval(function(){
  4597. _this.sendMessage({'action': 'init'});
  4598. }, 500);
  4599. PreziPlayer.players[id] = this;
  4600. }
  4601. PreziPlayer.prototype.changesHandler = function(message) {
  4602. var key, value, j, item;
  4603. if (this.initPollInterval) {
  4604. clearInterval(this.initPollInterval);
  4605. this.initPollInterval = false;
  4606. }
  4607. for (key in message.data) {
  4608. if (message.data.hasOwnProperty(key)){
  4609. value = message.data[key];
  4610. this.values[key] = value;
  4611. for (j=0; j<this.callbacks.length; j++) {
  4612. item = this.callbacks[j];
  4613. if (item && item.event === key + "Change"){
  4614. item.callback({type: item.event, value: value});
  4615. }
  4616. }
  4617. }
  4618. }
  4619. };
  4620. PreziPlayer.prototype.destroy = function() {
  4621. if (this.initPollInterval) {
  4622. clearInterval(this.initPollInterval);
  4623. this.initPollInterval = false;
  4624. }
  4625. this.embedTo.innerHTML = '';
  4626. };
  4627. PreziPlayer.prototype.sendMessage = function(message) {
  4628. if (this.options.debug === true) {
  4629. if (console && console.log) console.log('sent', message);
  4630. }
  4631. message.version = PreziPlayer.API_VERSION;
  4632. message.id = this.id;
  4633. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  4634. };
  4635. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  4636. PreziPlayer.prototype.flyToNextStep = function() {
  4637. return this.sendMessage({
  4638. 'action': 'present',
  4639. 'data': ['moveToNextStep']
  4640. });
  4641. };
  4642. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  4643. PreziPlayer.prototype.flyToPreviousStep = function() {
  4644. return this.sendMessage({
  4645. 'action': 'present',
  4646. 'data': ['moveToPrevStep']
  4647. });
  4648. };
  4649. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  4650. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  4651. var obj = this;
  4652. // check animation_step
  4653. if (animation_step > 0 &&
  4654. obj.values.animationCountOnSteps &&
  4655. obj.values.animationCountOnSteps[step] <= animation_step) {
  4656. animation_step = obj.values.animationCountOnSteps[step];
  4657. }
  4658. // jump to animation steps by calling flyToNextStep()
  4659. function doAnimationSteps() {
  4660. if (obj.values.isMoving == true) {
  4661. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  4662. return;
  4663. }
  4664. while (animation_step-- > 0) {
  4665. obj.flyToNextStep(); // do the animation steps
  4666. }
  4667. }
  4668. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  4669. // jump to the step
  4670. return this.sendMessage({
  4671. 'action': 'present',
  4672. 'data': ['moveToStep', step]
  4673. });
  4674. };
  4675. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  4676. PreziPlayer.prototype.flyToObject = function(objectId) {
  4677. return this.sendMessage({
  4678. 'action': 'present',
  4679. 'data': ['moveToObject', objectId]
  4680. });
  4681. };
  4682. PreziPlayer.prototype.play = function(defaultDelay) {
  4683. return this.sendMessage({
  4684. 'action': 'present',
  4685. 'data': ['startAutoPlay', defaultDelay]
  4686. });
  4687. };
  4688. PreziPlayer.prototype.stop = function() {
  4689. return this.sendMessage({
  4690. 'action': 'present',
  4691. 'data': ['stopAutoPlay']
  4692. });
  4693. };
  4694. PreziPlayer.prototype.pause = function(defaultDelay) {
  4695. return this.sendMessage({
  4696. 'action': 'present',
  4697. 'data': ['pauseAutoPlay', defaultDelay]
  4698. });
  4699. };
  4700. PreziPlayer.prototype.getCurrentStep = function() {
  4701. return this.values.currentStep;
  4702. };
  4703. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  4704. return this.values.currentAnimationStep;
  4705. };
  4706. PreziPlayer.prototype.getCurrentObject = function() {
  4707. return this.values.currentObject;
  4708. };
  4709. PreziPlayer.prototype.getStatus = function() {
  4710. return this.values.status;
  4711. };
  4712. PreziPlayer.prototype.isPlaying = function() {
  4713. return this.values.isAutoPlaying;
  4714. };
  4715. PreziPlayer.prototype.getStepCount = function() {
  4716. return this.values.stepCount;
  4717. };
  4718. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  4719. return this.values.animationCountOnSteps;
  4720. };
  4721. PreziPlayer.prototype.getTitle = function() {
  4722. return this.values.title;
  4723. };
  4724. PreziPlayer.prototype.setDimensions = function(dims) {
  4725. for (var parameter in dims) {
  4726. this.iframe[parameter] = dims[parameter];
  4727. }
  4728. }
  4729. PreziPlayer.prototype.getDimensions = function() {
  4730. return {
  4731. width: parseInt(this.iframe.width, 10),
  4732. height: parseInt(this.iframe.height, 10)
  4733. }
  4734. }
  4735. PreziPlayer.prototype.on = function(event, callback) {
  4736. this.callbacks.push({
  4737. event: event,
  4738. callback: callback
  4739. });
  4740. };
  4741. PreziPlayer.prototype.off = function(event, callback) {
  4742. var j, item;
  4743. if (event === undefined) {
  4744. this.callbacks = [];
  4745. }
  4746. j = this.callbacks.length;
  4747. while (j--) {
  4748. item = this.callbacks[j];
  4749. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  4750. this.callbacks.splice(j, 1);
  4751. }
  4752. }
  4753. };
  4754. if (window.addEventListener) {
  4755. window.addEventListener('message', PreziPlayer.messageReceived, false);
  4756. } else {
  4757. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  4758. }
  4759. return PreziPlayer;
  4760. })();
  4761. })();
  4762. module.exports = PreziPlayer;
  4763. },{}],20:[function(require,module,exports){
  4764. /* global require, $ */
  4765. var Chat = require("./chat/Chat");
  4766. var ContactList = require("./contactlist/ContactList");
  4767. var Settings = require("./../../settings/Settings");
  4768. var SettingsMenu = require("./settings/SettingsMenu");
  4769. var VideoLayout = require("../videolayout/VideoLayout");
  4770. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4771. var UIUtil = require("../util/UIUtil");
  4772. var LargeVideo = require("../videolayout/LargeVideo");
  4773. /**
  4774. * Toggler for the chat, contact list, settings menu, etc..
  4775. */
  4776. var PanelToggler = (function(my) {
  4777. var currentlyOpen = null;
  4778. var buttons = {
  4779. '#chatspace': '#chatBottomButton',
  4780. '#contactlist': '#contactListButton',
  4781. '#settingsmenu': '#toolbar_button_settings'
  4782. };
  4783. /**
  4784. * Toggles the windows in the side panel
  4785. * @param object the window that should be shown
  4786. * @param selector the selector for the element containing the panel
  4787. * @param onOpenComplete function to be called when the panel is opened
  4788. * @param onOpen function to be called if the window is going to be opened
  4789. * @param onClose function to be called if the window is going to be closed
  4790. */
  4791. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  4792. UIUtil.buttonClick(buttons[selector], "active");
  4793. if (object.isVisible()) {
  4794. $("#toast-container").animate({
  4795. right: '5px'
  4796. },
  4797. {
  4798. queue: false,
  4799. duration: 500
  4800. });
  4801. $(selector).hide("slide", {
  4802. direction: "right",
  4803. queue: false,
  4804. duration: 500
  4805. });
  4806. if(typeof onClose === "function") {
  4807. onClose();
  4808. }
  4809. currentlyOpen = null;
  4810. }
  4811. else {
  4812. // Undock the toolbar when the chat is shown and if we're in a
  4813. // video mode.
  4814. if (LargeVideo.isLargeVideoVisible()) {
  4815. ToolbarToggler.dockToolbar(false);
  4816. }
  4817. if(currentlyOpen) {
  4818. var current = $(currentlyOpen);
  4819. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  4820. current.css('z-index', 4);
  4821. setTimeout(function () {
  4822. current.css('display', 'none');
  4823. current.css('z-index', 5);
  4824. }, 500);
  4825. }
  4826. $("#toast-container").animate({
  4827. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  4828. },
  4829. {
  4830. queue: false,
  4831. duration: 500
  4832. });
  4833. $(selector).show("slide", {
  4834. direction: "right",
  4835. queue: false,
  4836. duration: 500,
  4837. complete: onOpenComplete
  4838. });
  4839. if(typeof onOpen === "function") {
  4840. onOpen();
  4841. }
  4842. currentlyOpen = selector;
  4843. }
  4844. };
  4845. /**
  4846. * Opens / closes the chat area.
  4847. */
  4848. my.toggleChat = function() {
  4849. var chatCompleteFunction = Chat.isVisible() ?
  4850. function() {} : function () {
  4851. Chat.scrollChatToBottom();
  4852. $('#chatspace').trigger('shown');
  4853. };
  4854. VideoLayout.resizeVideoArea(!Chat.isVisible(), chatCompleteFunction);
  4855. toggle(Chat,
  4856. '#chatspace',
  4857. function () {
  4858. // Request the focus in the nickname field or the chat input field.
  4859. if ($('#nickname').css('visibility') === 'visible') {
  4860. $('#nickinput').focus();
  4861. } else {
  4862. $('#usermsg').focus();
  4863. }
  4864. },
  4865. null,
  4866. Chat.resizeChat,
  4867. null);
  4868. };
  4869. /**
  4870. * Opens / closes the contact list area.
  4871. */
  4872. my.toggleContactList = function () {
  4873. var completeFunction = ContactList.isVisible() ?
  4874. function() {} : function () { $('#contactlist').trigger('shown');};
  4875. VideoLayout.resizeVideoArea(!ContactList.isVisible(), completeFunction);
  4876. toggle(ContactList,
  4877. '#contactlist',
  4878. null,
  4879. function() {
  4880. ContactList.setVisualNotification(false);
  4881. },
  4882. null);
  4883. };
  4884. /**
  4885. * Opens / closes the settings menu
  4886. */
  4887. my.toggleSettingsMenu = function() {
  4888. VideoLayout.resizeVideoArea(!SettingsMenu.isVisible(), function (){});
  4889. toggle(SettingsMenu,
  4890. '#settingsmenu',
  4891. null,
  4892. function() {
  4893. var settings = Settings.getSettings();
  4894. $('#setDisplayName').get(0).value = settings.displayName;
  4895. $('#setEmail').get(0).value = settings.email;
  4896. },
  4897. null);
  4898. };
  4899. /**
  4900. * Returns the size of the side panel.
  4901. */
  4902. my.getPanelSize = function () {
  4903. var availableHeight = window.innerHeight;
  4904. var availableWidth = window.innerWidth;
  4905. var panelWidth = 200;
  4906. if (availableWidth * 0.2 < 200) {
  4907. panelWidth = availableWidth * 0.2;
  4908. }
  4909. return [panelWidth, availableHeight];
  4910. };
  4911. my.isVisible = function() {
  4912. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  4913. };
  4914. return my;
  4915. }(PanelToggler || {}));
  4916. module.exports = PanelToggler;
  4917. },{"../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){
  4918. /* global APP, $, Util, nickname:true */
  4919. var Replacement = require("./Replacement");
  4920. var CommandsProcessor = require("./Commands");
  4921. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  4922. var smileys = require("./smileys.json").smileys;
  4923. var NicknameHandler = require("../../util/NicknameHandler");
  4924. var UIUtil = require("../../util/UIUtil");
  4925. var UIEvents = require("../../../../service/UI/UIEvents");
  4926. var notificationInterval = false;
  4927. var unreadMessages = 0;
  4928. /**
  4929. * Shows/hides a visual notification, indicating that a message has arrived.
  4930. */
  4931. function setVisualNotification(show) {
  4932. var unreadMsgElement = document.getElementById('unreadMessages');
  4933. var unreadMsgBottomElement
  4934. = document.getElementById('bottomUnreadMessages');
  4935. var glower = $('#toolbar_button_chat');
  4936. var bottomGlower = $('#chatBottomButton');
  4937. if (unreadMessages) {
  4938. unreadMsgElement.innerHTML = unreadMessages.toString();
  4939. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  4940. ToolbarToggler.dockToolbar(true);
  4941. var chatButtonElement
  4942. = document.getElementById('toolbar_button_chat');
  4943. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  4944. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  4945. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  4946. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  4947. unreadMsgElement.setAttribute(
  4948. 'style',
  4949. 'top:' + topIndent +
  4950. '; left:' + leftIndent + ';');
  4951. var chatBottomButtonElement
  4952. = document.getElementById('chatBottomButton').parentNode;
  4953. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  4954. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  4955. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  4956. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  4957. unreadMsgBottomElement.setAttribute(
  4958. 'style',
  4959. 'top:' + bottomTopIndent +
  4960. '; left:' + bottomLeftIndent + ';');
  4961. if (!glower.hasClass('icon-chat-simple')) {
  4962. glower.removeClass('icon-chat');
  4963. glower.addClass('icon-chat-simple');
  4964. }
  4965. }
  4966. else {
  4967. unreadMsgElement.innerHTML = '';
  4968. unreadMsgBottomElement.innerHTML = '';
  4969. glower.removeClass('icon-chat-simple');
  4970. glower.addClass('icon-chat');
  4971. }
  4972. if (show && !notificationInterval) {
  4973. notificationInterval = window.setInterval(function () {
  4974. glower.toggleClass('active');
  4975. bottomGlower.toggleClass('active glowing');
  4976. }, 800);
  4977. }
  4978. else if (!show && notificationInterval) {
  4979. window.clearInterval(notificationInterval);
  4980. notificationInterval = false;
  4981. glower.removeClass('active');
  4982. bottomGlower.removeClass('glowing');
  4983. bottomGlower.addClass('active');
  4984. }
  4985. }
  4986. /**
  4987. * Returns the current time in the format it is shown to the user
  4988. * @returns {string}
  4989. */
  4990. function getCurrentTime(stamp) {
  4991. var now = (stamp? new Date(stamp): new Date());
  4992. var hour = now.getHours();
  4993. var minute = now.getMinutes();
  4994. var second = now.getSeconds();
  4995. if(hour.toString().length === 1) {
  4996. hour = '0'+hour;
  4997. }
  4998. if(minute.toString().length === 1) {
  4999. minute = '0'+minute;
  5000. }
  5001. if(second.toString().length === 1) {
  5002. second = '0'+second;
  5003. }
  5004. return hour+':'+minute+':'+second;
  5005. }
  5006. function toggleSmileys() {
  5007. var smileys = $('#smileysContainer');
  5008. if(!smileys.is(':visible')) {
  5009. smileys.show("slide", { direction: "down", duration: 300});
  5010. } else {
  5011. smileys.hide("slide", { direction: "down", duration: 300});
  5012. }
  5013. $('#usermsg').focus();
  5014. }
  5015. function addClickFunction(smiley, number) {
  5016. smiley.onclick = function addSmileyToMessage() {
  5017. var usermsg = $('#usermsg');
  5018. var message = usermsg.val();
  5019. message += smileys['smiley' + number];
  5020. usermsg.val(message);
  5021. usermsg.get(0).setSelectionRange(message.length, message.length);
  5022. toggleSmileys();
  5023. usermsg.focus();
  5024. };
  5025. }
  5026. /**
  5027. * Adds the smileys container to the chat
  5028. */
  5029. function addSmileys() {
  5030. var smileysContainer = document.createElement('div');
  5031. smileysContainer.id = 'smileysContainer';
  5032. for(var i = 1; i <= 21; i++) {
  5033. var smileyContainer = document.createElement('div');
  5034. smileyContainer.id = 'smiley' + i;
  5035. smileyContainer.className = 'smileyContainer';
  5036. var smiley = document.createElement('img');
  5037. smiley.src = 'images/smileys/smiley' + i + '.svg';
  5038. smiley.className = 'smiley';
  5039. addClickFunction(smiley, i);
  5040. smileyContainer.appendChild(smiley);
  5041. smileysContainer.appendChild(smileyContainer);
  5042. }
  5043. $("#chatspace").append(smileysContainer);
  5044. }
  5045. /**
  5046. * Resizes the chat conversation.
  5047. */
  5048. function resizeChatConversation() {
  5049. var msgareaHeight = $('#usermsg').outerHeight();
  5050. var chatspace = $('#chatspace');
  5051. var width = chatspace.width();
  5052. var chat = $('#chatconversation');
  5053. var smileys = $('#smileysarea');
  5054. smileys.height(msgareaHeight);
  5055. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  5056. $('#smileysContainer').css('bottom', msgareaHeight);
  5057. chat.width(width - 10);
  5058. chat.height(window.innerHeight - 15 - msgareaHeight);
  5059. }
  5060. /**
  5061. * Chat related user interface.
  5062. */
  5063. var Chat = (function (my) {
  5064. /**
  5065. * Initializes chat related interface.
  5066. */
  5067. my.init = function () {
  5068. if(NicknameHandler.getNickname())
  5069. Chat.setChatConversationMode(true);
  5070. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  5071. function (nickname) {
  5072. Chat.setChatConversationMode(true);
  5073. });
  5074. $('#nickinput').keydown(function (event) {
  5075. if (event.keyCode === 13) {
  5076. event.preventDefault();
  5077. var val = UIUtil.escapeHtml(this.value);
  5078. this.value = '';
  5079. if (!NicknameHandler.getNickname()) {
  5080. NicknameHandler.setNickname(val);
  5081. return;
  5082. }
  5083. }
  5084. });
  5085. var usermsg = $('#usermsg');
  5086. usermsg.keydown(function (event) {
  5087. if (event.keyCode === 13) {
  5088. event.preventDefault();
  5089. var value = this.value;
  5090. usermsg.val('').trigger('autosize.resize');
  5091. this.focus();
  5092. var command = new CommandsProcessor(value);
  5093. if(command.isCommand()) {
  5094. command.processCommand();
  5095. }
  5096. else {
  5097. var message = UIUtil.escapeHtml(value);
  5098. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  5099. }
  5100. }
  5101. });
  5102. var onTextAreaResize = function () {
  5103. resizeChatConversation();
  5104. Chat.scrollChatToBottom();
  5105. };
  5106. usermsg.autosize({callback: onTextAreaResize});
  5107. $("#chatspace").bind("shown",
  5108. function () {
  5109. unreadMessages = 0;
  5110. setVisualNotification(false);
  5111. });
  5112. addSmileys();
  5113. };
  5114. /**
  5115. * Appends the given message to the chat conversation.
  5116. */
  5117. my.updateChatConversation =
  5118. function (from, displayName, message, myjid, stamp) {
  5119. var divClassName = '';
  5120. if (APP.xmpp.myJid() === from) {
  5121. divClassName = "localuser";
  5122. }
  5123. else {
  5124. divClassName = "remoteuser";
  5125. if (!Chat.isVisible()) {
  5126. unreadMessages++;
  5127. UIUtil.playSoundNotification('chatNotification');
  5128. setVisualNotification(true);
  5129. }
  5130. }
  5131. // replace links and smileys
  5132. // Strophe already escapes special symbols on sending,
  5133. // so we escape here only tags to avoid double &amp;
  5134. var escMessage = message.replace(/</g, '&lt;').
  5135. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  5136. var escDisplayName = UIUtil.escapeHtml(displayName);
  5137. message = Replacement.processReplacements(escMessage);
  5138. var messageContainer =
  5139. '<div class="chatmessage">'+
  5140. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  5141. '<div class="username ' + divClassName +'">' + escDisplayName +
  5142. '</div>' + '<div class="timestamp">' + getCurrentTime(stamp) +
  5143. '</div>' + '<div class="usermessage">' + message + '</div>' +
  5144. '</div>';
  5145. $('#chatconversation').append(messageContainer);
  5146. $('#chatconversation').animate(
  5147. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5148. };
  5149. /**
  5150. * Appends error message to the conversation
  5151. * @param errorMessage the received error message.
  5152. * @param originalText the original message.
  5153. */
  5154. my.chatAddError = function(errorMessage, originalText) {
  5155. errorMessage = UIUtil.escapeHtml(errorMessage);
  5156. originalText = UIUtil.escapeHtml(originalText);
  5157. $('#chatconversation').append(
  5158. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  5159. (originalText? (' \"'+ originalText + '\"') : "") +
  5160. ' was not sent.' +
  5161. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  5162. $('#chatconversation').animate(
  5163. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5164. };
  5165. /**
  5166. * Sets the subject to the UI
  5167. * @param subject the subject
  5168. */
  5169. my.chatSetSubject = function(subject) {
  5170. if (subject)
  5171. subject = subject.trim();
  5172. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  5173. if(subject === "") {
  5174. $("#subject").css({display: "none"});
  5175. }
  5176. else {
  5177. $("#subject").css({display: "block"});
  5178. }
  5179. };
  5180. /**
  5181. * Sets the chat conversation mode.
  5182. */
  5183. my.setChatConversationMode = function (isConversationMode) {
  5184. if (isConversationMode) {
  5185. $('#nickname').css({visibility: 'hidden'});
  5186. $('#chatconversation').css({visibility: 'visible'});
  5187. $('#usermsg').css({visibility: 'visible'});
  5188. $('#smileysarea').css({visibility: 'visible'});
  5189. $('#usermsg').focus();
  5190. }
  5191. };
  5192. /**
  5193. * Resizes the chat area.
  5194. */
  5195. my.resizeChat = function () {
  5196. var chatSize = require("../SidePanelToggler").getPanelSize();
  5197. $('#chatspace').width(chatSize[0]);
  5198. $('#chatspace').height(chatSize[1]);
  5199. resizeChatConversation();
  5200. };
  5201. /**
  5202. * Indicates if the chat is currently visible.
  5203. */
  5204. my.isVisible = function () {
  5205. return $('#chatspace').is(":visible");
  5206. };
  5207. /**
  5208. * Shows and hides the window with the smileys
  5209. */
  5210. my.toggleSmileys = toggleSmileys;
  5211. /**
  5212. * Scrolls chat to the bottom.
  5213. */
  5214. my.scrollChatToBottom = function() {
  5215. setTimeout(function () {
  5216. $('#chatconversation').scrollTop(
  5217. $('#chatconversation')[0].scrollHeight);
  5218. }, 5);
  5219. };
  5220. return my;
  5221. }(Chat || {}));
  5222. module.exports = Chat;
  5223. },{"../../../../service/UI/UIEvents":155,"../../toolbars/ToolbarToggler":29,"../../util/NicknameHandler":32,"../../util/UIUtil":33,"../SidePanelToggler":20,"./Commands":22,"./Replacement":23,"./smileys.json":24}],22:[function(require,module,exports){
  5224. /* global APP, require */
  5225. var UIUtil = require("../../util/UIUtil");
  5226. /**
  5227. * List with supported commands. The keys are the names of the commands and
  5228. * the value is the function that processes the message.
  5229. * @type {{String: function}}
  5230. */
  5231. var commands = {
  5232. "topic" : processTopic
  5233. };
  5234. /**
  5235. * Extracts the command from the message.
  5236. * @param message the received message
  5237. * @returns {string} the command
  5238. */
  5239. function getCommand(message) {
  5240. if(message) {
  5241. for(var command in commands) {
  5242. if(message.indexOf("/" + command) == 0)
  5243. return command;
  5244. }
  5245. }
  5246. return "";
  5247. }
  5248. /**
  5249. * Processes the data for topic command.
  5250. * @param commandArguments the arguments of the topic command.
  5251. */
  5252. function processTopic(commandArguments) {
  5253. var topic = UIUtil.escapeHtml(commandArguments);
  5254. APP.xmpp.setSubject(topic);
  5255. }
  5256. /**
  5257. * Constructs a new CommandProccessor instance from a message that
  5258. * handles commands received via chat messages.
  5259. * @param message the message
  5260. * @constructor
  5261. */
  5262. function CommandsProcessor(message) {
  5263. var command = getCommand(message);
  5264. /**
  5265. * Returns the name of the command.
  5266. * @returns {String} the command
  5267. */
  5268. this.getCommand = function() {
  5269. return command;
  5270. };
  5271. var messageArgument = message.substr(command.length + 2);
  5272. /**
  5273. * Returns the arguments of the command.
  5274. * @returns {string}
  5275. */
  5276. this.getArgument = function() {
  5277. return messageArgument;
  5278. };
  5279. }
  5280. /**
  5281. * Checks whether this instance is valid command or not.
  5282. * @returns {boolean}
  5283. */
  5284. CommandsProcessor.prototype.isCommand = function() {
  5285. if (this.getCommand())
  5286. return true;
  5287. return false;
  5288. };
  5289. /**
  5290. * Processes the command.
  5291. */
  5292. CommandsProcessor.prototype.processCommand = function() {
  5293. if(!this.isCommand())
  5294. return;
  5295. commands[this.getCommand()](this.getArgument());
  5296. };
  5297. module.exports = CommandsProcessor;
  5298. },{"../../util/UIUtil":33}],23:[function(require,module,exports){
  5299. var Smileys = require("./smileys.json");
  5300. /**
  5301. * Processes links and smileys in "body"
  5302. */
  5303. function processReplacements(body)
  5304. {
  5305. //make links clickable
  5306. body = linkify(body);
  5307. //add smileys
  5308. body = smilify(body);
  5309. return body;
  5310. }
  5311. /**
  5312. * Finds and replaces all links in the links in "body"
  5313. * with their <a href=""></a>
  5314. */
  5315. function linkify(inputText)
  5316. {
  5317. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  5318. //URLs starting with http://, https://, or ftp://
  5319. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  5320. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  5321. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  5322. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  5323. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  5324. //Change email addresses to mailto:: links.
  5325. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  5326. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  5327. return replacedText;
  5328. }
  5329. /**
  5330. * Replaces common smiley strings with images
  5331. */
  5332. function smilify(body)
  5333. {
  5334. if(!body) {
  5335. return body;
  5336. }
  5337. var regexs = Smileys["regexs"];
  5338. for(var smiley in regexs) {
  5339. if(regexs.hasOwnProperty(smiley)) {
  5340. body = body.replace(regexs[smiley],
  5341. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  5342. }
  5343. }
  5344. return body;
  5345. }
  5346. module.exports = {
  5347. processReplacements: processReplacements,
  5348. linkify: linkify
  5349. };
  5350. },{"./smileys.json":24}],24:[function(require,module,exports){
  5351. module.exports={
  5352. "smileys": {
  5353. "smiley1": ":)",
  5354. "smiley2": ":(",
  5355. "smiley3": ":D",
  5356. "smiley4": "(y)",
  5357. "smiley5": " :P",
  5358. "smiley6": "(wave)",
  5359. "smiley7": "(blush)",
  5360. "smiley8": "(chuckle)",
  5361. "smiley9": "(shocked)",
  5362. "smiley10": ":*",
  5363. "smiley11": "(n)",
  5364. "smiley12": "(search)",
  5365. "smiley13": " <3",
  5366. "smiley14": "(oops)",
  5367. "smiley15": "(angry)",
  5368. "smiley16": "(angel)",
  5369. "smiley17": "(sick)",
  5370. "smiley18": ";(",
  5371. "smiley19": "(bomb)",
  5372. "smiley20": "(clap)",
  5373. "smiley21": " ;)"
  5374. },
  5375. "regexs": {
  5376. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  5377. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  5378. "smiley1": /(:-\)|:\))/gi,
  5379. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  5380. "smiley5": /(:-P|:P|:-p|:p)/gi,
  5381. "smiley6": /(\(wave\))/gi,
  5382. "smiley7": /(\(blush\))/gi,
  5383. "smiley8": /(\(chuckle\))/gi,
  5384. "smiley9": /(:-0|\(shocked\))/gi,
  5385. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  5386. "smiley11": /(\(n\))/gi,
  5387. "smiley12": /(\(search\))/g,
  5388. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  5389. "smiley14": /(\(oops\))/gi,
  5390. "smiley15": /(\(angry\))/gi,
  5391. "smiley16": /(\(angel\))/gi,
  5392. "smiley17": /(\(sick\))/gi,
  5393. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  5394. "smiley19": /(\(bomb\))/gi,
  5395. "smiley20": /(\(clap\))/gi,
  5396. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  5397. }
  5398. }
  5399. },{}],25:[function(require,module,exports){
  5400. /* global $, APP, Strophe */
  5401. var Avatar = require('../../avatar/Avatar');
  5402. var numberOfContacts = 0;
  5403. var notificationInterval;
  5404. /**
  5405. * Updates the number of participants in the contact list button and sets
  5406. * the glow
  5407. * @param delta indicates whether a new user has joined (1) or someone has
  5408. * left(-1)
  5409. */
  5410. function updateNumberOfParticipants(delta) {
  5411. numberOfContacts += delta;
  5412. if (numberOfContacts === 1) {
  5413. // when the user is alone we don't show the number of participants
  5414. $("#numberOfParticipants").text('');
  5415. ContactList.setVisualNotification(false);
  5416. } else if (numberOfContacts > 1) {
  5417. ContactList.setVisualNotification(!ContactList.isVisible());
  5418. $("#numberOfParticipants").text(numberOfContacts);
  5419. } else {
  5420. console.error("Invalid number of participants: " + numberOfContacts);
  5421. }
  5422. }
  5423. /**
  5424. * Creates the avatar element.
  5425. *
  5426. * @return {object} the newly created avatar element
  5427. */
  5428. function createAvatar(jid) {
  5429. var avatar = document.createElement('img');
  5430. avatar.className = "icon-avatar avatar";
  5431. avatar.src = Avatar.getContactListUrl(jid);
  5432. return avatar;
  5433. }
  5434. /**
  5435. * Creates the display name paragraph.
  5436. *
  5437. * @param displayName the display name to set
  5438. */
  5439. function createDisplayNameParagraph(key, displayName) {
  5440. var p = document.createElement('p');
  5441. if(displayName)
  5442. p.innerText = displayName;
  5443. else if(key) {
  5444. p.setAttribute("data-i18n",key);
  5445. p.innerText = APP.translation.translateString(key);
  5446. }
  5447. return p;
  5448. }
  5449. function stopGlowing(glower) {
  5450. window.clearInterval(notificationInterval);
  5451. notificationInterval = false;
  5452. glower.removeClass('glowing');
  5453. if (!ContactList.isVisible()) {
  5454. glower.removeClass('active');
  5455. }
  5456. }
  5457. /**
  5458. * Contact list.
  5459. */
  5460. var ContactList = {
  5461. /**
  5462. * Indicates if the chat is currently visible.
  5463. *
  5464. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  5465. * otherwise
  5466. */
  5467. isVisible: function () {
  5468. return $('#contactlist').is(":visible");
  5469. },
  5470. /**
  5471. * Adds a contact for the given peerJid if such doesn't yet exist.
  5472. *
  5473. * @param peerJid the peerJid corresponding to the contact
  5474. */
  5475. ensureAddContact: function (peerJid) {
  5476. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5477. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5478. if (!contact || contact.length <= 0)
  5479. ContactList.addContact(peerJid);
  5480. },
  5481. /**
  5482. * Adds a contact for the given peer jid.
  5483. *
  5484. * @param peerJid the jid of the contact to add
  5485. */
  5486. addContact: function (peerJid) {
  5487. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5488. var contactlist = $('#contacts');
  5489. var newContact = document.createElement('li');
  5490. newContact.id = resourceJid;
  5491. newContact.className = "clickable";
  5492. newContact.onclick = function (event) {
  5493. if (event.currentTarget.className === "clickable") {
  5494. $(ContactList).trigger('contactclicked', [peerJid]);
  5495. }
  5496. };
  5497. newContact.appendChild(createAvatar(peerJid));
  5498. newContact.appendChild(createDisplayNameParagraph("participant"));
  5499. if (resourceJid === APP.xmpp.myResource()) {
  5500. contactlist.prepend(newContact);
  5501. }
  5502. else {
  5503. contactlist.append(newContact);
  5504. }
  5505. updateNumberOfParticipants(1);
  5506. },
  5507. /**
  5508. * Removes a contact for the given peer jid.
  5509. *
  5510. * @param peerJid the peerJid corresponding to the contact to remove
  5511. */
  5512. removeContact: function (peerJid) {
  5513. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5514. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5515. if (contact && contact.length > 0) {
  5516. var contactlist = $('#contactlist>ul');
  5517. contactlist.get(0).removeChild(contact.get(0));
  5518. updateNumberOfParticipants(-1);
  5519. }
  5520. },
  5521. setVisualNotification: function (show, stopGlowingIn) {
  5522. var glower = $('#contactListButton');
  5523. if (show && !notificationInterval) {
  5524. notificationInterval = window.setInterval(function () {
  5525. glower.toggleClass('active glowing');
  5526. }, 800);
  5527. }
  5528. else if (!show && notificationInterval) {
  5529. stopGlowing(glower);
  5530. }
  5531. if (stopGlowingIn) {
  5532. setTimeout(function () {
  5533. stopGlowing(glower);
  5534. }, stopGlowingIn);
  5535. }
  5536. },
  5537. setClickable: function (resourceJid, isClickable) {
  5538. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5539. if (isClickable) {
  5540. contact.addClass('clickable');
  5541. } else {
  5542. contact.removeClass('clickable');
  5543. }
  5544. },
  5545. onDisplayNameChange: function (peerJid, displayName) {
  5546. if (peerJid === 'localVideoContainer')
  5547. peerJid = APP.xmpp.myJid();
  5548. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5549. var contactName = $('#contacts #' + resourceJid + '>p');
  5550. if (contactName && displayName && displayName.length > 0)
  5551. contactName.html(displayName);
  5552. },
  5553. userAvatarChanged: function (resourceJid, contactListUrl) {
  5554. // set the avatar in the contact list
  5555. var contact = $('#' + resourceJid + '>img');
  5556. if (contact && contact.length > 0) {
  5557. contact.get(0).src = contactListUrl;
  5558. }
  5559. }
  5560. };
  5561. module.exports = ContactList;
  5562. },{"../../avatar/Avatar":16}],26:[function(require,module,exports){
  5563. /* global APP, $ */
  5564. var Avatar = require("../../avatar/Avatar");
  5565. var Settings = require("./../../../settings/Settings");
  5566. var UIUtil = require("../../util/UIUtil");
  5567. var languages = require("../../../../service/translation/languages");
  5568. function generateLanguagesSelectBox() {
  5569. var currentLang = APP.translation.getCurrentLanguage();
  5570. var html = "<select id=\"languages_selectbox\">";
  5571. var langArray = languages.getLanguages();
  5572. for(var i = 0; i < langArray.length; i++) {
  5573. var lang = langArray[i];
  5574. html += "<option ";
  5575. if(lang === currentLang)
  5576. html += "selected ";
  5577. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  5578. html += "</option>";
  5579. }
  5580. return html + "</select>";
  5581. }
  5582. var SettingsMenu = {
  5583. init: function () {
  5584. var startMutedSelector = $("#startMutedOptions");
  5585. startMutedSelector.before(generateLanguagesSelectBox());
  5586. APP.translation.translateElement($("#languages_selectbox"));
  5587. $('#settingsmenu>input').keyup(function(event){
  5588. if(event.keyCode === 13) {//enter
  5589. SettingsMenu.update();
  5590. }
  5591. });
  5592. if (APP.xmpp.isModerator()) {
  5593. startMutedSelector.css("display", "block");
  5594. }
  5595. else {
  5596. startMutedSelector.css("display", "none");
  5597. }
  5598. $("#updateSettings").click(function () {
  5599. SettingsMenu.update();
  5600. });
  5601. },
  5602. onRoleChanged: function () {
  5603. if(APP.xmpp.isModerator()) {
  5604. $("#startMutedOptions").css("display", "block");
  5605. }
  5606. else {
  5607. $("#startMutedOptions").css("display", "none");
  5608. }
  5609. },
  5610. setStartMuted: function (audio, video) {
  5611. $("#startAudioMuted").attr("checked", audio);
  5612. $("#startVideoMuted").attr("checked", video);
  5613. },
  5614. update: function() {
  5615. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  5616. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  5617. if(newDisplayName) {
  5618. var displayName = Settings.setDisplayName(newDisplayName);
  5619. APP.xmpp.addToPresence("displayName", displayName, true);
  5620. }
  5621. var language = $("#languages_selectbox").val();
  5622. APP.translation.setLanguage(language);
  5623. Settings.setLanguage(language);
  5624. APP.xmpp.addToPresence("email", newEmail);
  5625. var email = Settings.setEmail(newEmail);
  5626. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  5627. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  5628. APP.xmpp.addToPresence("startMuted",
  5629. [startAudioMuted, startVideoMuted]);
  5630. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  5631. },
  5632. isVisible: function() {
  5633. return $('#settingsmenu').is(':visible');
  5634. },
  5635. setDisplayName: function(newDisplayName) {
  5636. var displayName = Settings.setDisplayName(newDisplayName);
  5637. $('#setDisplayName').get(0).value = displayName;
  5638. },
  5639. onDisplayNameChange: function(peerJid, newDisplayName) {
  5640. if(peerJid === 'localVideoContainer' ||
  5641. peerJid === APP.xmpp.myJid()) {
  5642. this.setDisplayName(newDisplayName);
  5643. }
  5644. },
  5645. changeAvatar: function (thumbUrl) {
  5646. $('#avatar').get(0).src = thumbUrl;
  5647. }
  5648. };
  5649. module.exports = SettingsMenu;
  5650. },{"../../../../service/translation/languages":160,"../../avatar/Avatar":16,"../../util/UIUtil":33,"./../../../settings/Settings":47}],27:[function(require,module,exports){
  5651. /* global $ */
  5652. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5653. var buttonHandlers = {
  5654. "bottom_toolbar_contact_list": function () {
  5655. BottomToolbar.toggleContactList();
  5656. },
  5657. "bottom_toolbar_film_strip": function () {
  5658. BottomToolbar.toggleFilmStrip();
  5659. },
  5660. "bottom_toolbar_chat": function () {
  5661. BottomToolbar.toggleChat();
  5662. }
  5663. };
  5664. var BottomToolbar = (function (my) {
  5665. my.init = function () {
  5666. for(var k in buttonHandlers)
  5667. $("#" + k).click(buttonHandlers[k]);
  5668. };
  5669. my.toggleChat = function() {
  5670. PanelToggler.toggleChat();
  5671. };
  5672. my.toggleContactList = function() {
  5673. PanelToggler.toggleContactList();
  5674. };
  5675. my.toggleFilmStrip = function() {
  5676. var filmstrip = $("#remoteVideos");
  5677. filmstrip.toggleClass("hidden");
  5678. };
  5679. $(document).bind("remotevideo.resized", function (event, width, height) {
  5680. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  5681. $('#bottomToolbar').css({bottom: bottom + 'px'});
  5682. });
  5683. return my;
  5684. }(BottomToolbar || {}));
  5685. module.exports = BottomToolbar;
  5686. },{"../side_pannels/SidePanelToggler":20}],28:[function(require,module,exports){
  5687. /* global APP, $, buttonClick, config, lockRoom, interfaceConfig, setSharedKey,
  5688. Util */
  5689. var messageHandler = require("../util/MessageHandler");
  5690. var BottomToolbar = require("./BottomToolbar");
  5691. var Prezi = require("../prezi/Prezi");
  5692. var Etherpad = require("../etherpad/Etherpad");
  5693. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5694. var Authentication = require("../authentication/Authentication");
  5695. var UIUtil = require("../util/UIUtil");
  5696. var AuthenticationEvents
  5697. = require("../../../service/authentication/AuthenticationEvents");
  5698. var roomUrl = null;
  5699. var sharedKey = '';
  5700. var UI = null;
  5701. var recordingToaster = null;
  5702. var buttonHandlers = {
  5703. "toolbar_button_mute": function () {
  5704. return APP.UI.toggleAudio();
  5705. },
  5706. "toolbar_button_camera": function () {
  5707. return APP.UI.toggleVideo();
  5708. },
  5709. /*"toolbar_button_authentication": function () {
  5710. return Toolbar.authenticateClicked();
  5711. },*/
  5712. "toolbar_button_record": function () {
  5713. return toggleRecording();
  5714. },
  5715. "toolbar_button_security": function () {
  5716. return Toolbar.openLockDialog();
  5717. },
  5718. "toolbar_button_link": function () {
  5719. return Toolbar.openLinkDialog();
  5720. },
  5721. "toolbar_button_chat": function () {
  5722. return BottomToolbar.toggleChat();
  5723. },
  5724. "toolbar_button_prezi": function () {
  5725. return Prezi.openPreziDialog();
  5726. },
  5727. "toolbar_button_etherpad": function () {
  5728. return Etherpad.toggleEtherpad(0);
  5729. },
  5730. "toolbar_button_desktopsharing": function () {
  5731. return APP.desktopsharing.toggleScreenSharing();
  5732. },
  5733. "toolbar_button_fullScreen": function() {
  5734. UIUtil.buttonClick("#toolbar_button_fullScreen", "icon-full-screen icon-exit-full-screen");
  5735. return Toolbar.toggleFullScreen();
  5736. },
  5737. "toolbar_button_sip": function () {
  5738. return callSipButtonClicked();
  5739. },
  5740. "toolbar_button_dialpad": function () {
  5741. return dialpadButtonClicked();
  5742. },
  5743. "toolbar_button_settings": function () {
  5744. PanelToggler.toggleSettingsMenu();
  5745. },
  5746. "toolbar_button_hangup": function () {
  5747. return hangup();
  5748. },
  5749. "toolbar_button_login": function () {
  5750. Toolbar.authenticateClicked();
  5751. },
  5752. "toolbar_button_logout": function () {
  5753. // Ask for confirmation
  5754. messageHandler.openTwoButtonDialog(
  5755. "dialog.logoutTitle",
  5756. null,
  5757. "dialog.logoutQuestion",
  5758. null,
  5759. false,
  5760. "dialog.Yes",
  5761. function (evt, yes) {
  5762. if (yes) {
  5763. APP.xmpp.logout(function (url) {
  5764. if (url) {
  5765. window.location.href = url;
  5766. } else {
  5767. hangup();
  5768. }
  5769. });
  5770. }
  5771. });
  5772. }
  5773. };
  5774. function hangup() {
  5775. APP.xmpp.disposeConference();
  5776. if(config.enableWelcomePage) {
  5777. setTimeout(function() {
  5778. window.localStorage.welcomePageDisabled = false;
  5779. window.location.pathname = "/";
  5780. }, 10000);
  5781. }
  5782. var title = APP.translation.generateTranslationHTML(
  5783. "dialog.sessTerminated");
  5784. var msg = APP.translation.generateTranslationHTML(
  5785. "dialog.hungUp");
  5786. var button = APP.translation.generateTranslationHTML(
  5787. "dialog.joinAgain");
  5788. var buttons = [];
  5789. buttons.push({title: button, value: true});
  5790. UI.messageHandler.openDialog(
  5791. title,
  5792. msg,
  5793. true,
  5794. buttons,
  5795. function(event, value, message, formVals) {
  5796. window.location.reload();
  5797. return false;
  5798. }
  5799. );
  5800. }
  5801. /**
  5802. * Starts or stops the recording for the conference.
  5803. */
  5804. function toggleRecording(predefinedToken) {
  5805. APP.xmpp.toggleRecording(function (callback) {
  5806. if (predefinedToken) {
  5807. callback(UIUtil.escapeHtml(predefinedToken));
  5808. return;
  5809. }
  5810. var msg = APP.translation.generateTranslationHTML(
  5811. "dialog.recordingToken");
  5812. var token = APP.translation.translateString("dialog.token");
  5813. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  5814. '<h2>' + msg + '</h2>' +
  5815. '<input name="recordingToken" type="text" ' +
  5816. ' data-i18n="[placeholder]dialog.token" ' +
  5817. 'placeholder="' + token + '" autofocus>',
  5818. false,
  5819. "dialog.Save",
  5820. function (e, v, m, f) {
  5821. if (v) {
  5822. var token = f.recordingToken;
  5823. if (token) {
  5824. callback(UIUtil.escapeHtml(token));
  5825. }
  5826. }
  5827. },
  5828. null,
  5829. function () { },
  5830. ':input:first'
  5831. );
  5832. }, Toolbar.setRecordingButtonState);
  5833. }
  5834. /**
  5835. * Locks / unlocks the room.
  5836. */
  5837. function lockRoom(lock) {
  5838. var currentSharedKey = '';
  5839. if (lock)
  5840. currentSharedKey = sharedKey;
  5841. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  5842. // password is required
  5843. if (sharedKey) {
  5844. console.log('set room password');
  5845. Toolbar.lockLockButton();
  5846. }
  5847. else {
  5848. console.log('removed room password');
  5849. Toolbar.unlockLockButton();
  5850. }
  5851. }, function (err) {
  5852. console.warn('setting password failed', err);
  5853. messageHandler.showError("dialog.lockTitle",
  5854. "dialog.lockMessage");
  5855. Toolbar.setSharedKey('');
  5856. }, function () {
  5857. console.warn('room passwords not supported');
  5858. messageHandler.showError("dialog.warning",
  5859. "dialog.passwordNotSupported");
  5860. Toolbar.setSharedKey('');
  5861. });
  5862. }
  5863. /**
  5864. * Invite participants to conference.
  5865. */
  5866. function inviteParticipants() {
  5867. if (roomUrl === null)
  5868. return;
  5869. var sharedKeyText = "";
  5870. if (sharedKey && sharedKey.length > 0) {
  5871. sharedKeyText =
  5872. APP.translation.translateString("email.sharedKey",
  5873. {sharedKey: sharedKey});
  5874. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  5875. }
  5876. var supportedBrowsers = "Chromium, Google Chrome " +
  5877. APP.translation.translateString("email.and") + " Opera";
  5878. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  5879. var subject = APP.translation.translateString("email.subject",
  5880. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  5881. var body = APP.translation.translateString("email.body",
  5882. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  5883. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  5884. body = body.replace(/\n/g, "%0D%0A");
  5885. if (window.localStorage.displayname) {
  5886. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  5887. }
  5888. if (interfaceConfig.INVITATION_POWERED_BY) {
  5889. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  5890. }
  5891. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  5892. }
  5893. function dialpadButtonClicked() {
  5894. //TODO show the dialpad box
  5895. }
  5896. function callSipButtonClicked() {
  5897. var defaultNumber
  5898. = config.defaultSipNumber ? config.defaultSipNumber : '';
  5899. var sipMsg = APP.translation.generateTranslationHTML(
  5900. "dialog.sipMsg");
  5901. messageHandler.openTwoButtonDialog(null, null, null,
  5902. '<h2>' + sipMsg + '</h2>' +
  5903. '<input name="sipNumber" type="text"' +
  5904. ' value="' + defaultNumber + '" autofocus>',
  5905. false,
  5906. "dialog.Dial",
  5907. function (e, v, m, f) {
  5908. if (v) {
  5909. var numberInput = f.sipNumber;
  5910. if (numberInput) {
  5911. APP.xmpp.dial(
  5912. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  5913. }
  5914. }
  5915. },
  5916. null, null, ':input:first'
  5917. );
  5918. }
  5919. var Toolbar = (function (my) {
  5920. my.init = function (ui) {
  5921. for(var k in buttonHandlers)
  5922. $("#" + k).click(buttonHandlers[k]);
  5923. UI = ui;
  5924. // Update login info
  5925. APP.xmpp.addListener(
  5926. AuthenticationEvents.IDENTITY_UPDATED,
  5927. function (authenticationEnabled, userIdentity) {
  5928. var loggedIn = false;
  5929. if (userIdentity) {
  5930. loggedIn = true;
  5931. }
  5932. Toolbar.showAuthenticateButton(authenticationEnabled);
  5933. if (authenticationEnabled) {
  5934. Toolbar.setAuthenticatedIdentity(userIdentity);
  5935. Toolbar.showLoginButton(!loggedIn);
  5936. Toolbar.showLogoutButton(loggedIn);
  5937. }
  5938. }
  5939. );
  5940. };
  5941. /**
  5942. * Sets shared key
  5943. * @param sKey the shared key
  5944. */
  5945. my.setSharedKey = function (sKey) {
  5946. sharedKey = sKey;
  5947. };
  5948. my.authenticateClicked = function () {
  5949. Authentication.focusAuthenticationWindow();
  5950. if (!APP.xmpp.isExternalAuthEnabled()) {
  5951. Authentication.xmppAuthenticate();
  5952. return;
  5953. }
  5954. // Get authentication URL
  5955. if (!APP.xmpp.isMUCJoined()) {
  5956. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  5957. // If conference has not been started yet - redirect to login page
  5958. window.location.href = url;
  5959. });
  5960. } else {
  5961. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  5962. // Otherwise - open popup with authentication URL
  5963. var authenticationWindow = Authentication.createAuthenticationWindow(
  5964. function () {
  5965. // On popup closed - retry room allocation
  5966. APP.xmpp.allocateConferenceFocus(
  5967. APP.UI.getRoomName(),
  5968. function () { console.info("AUTH DONE"); }
  5969. );
  5970. }, url);
  5971. if (!authenticationWindow) {
  5972. messageHandler.openMessageDialog(
  5973. null, "dialog.popupError");
  5974. }
  5975. });
  5976. }
  5977. };
  5978. /**
  5979. * Updates the room invite url.
  5980. */
  5981. my.updateRoomUrl = function (newRoomUrl) {
  5982. roomUrl = newRoomUrl;
  5983. // If the invite dialog has been already opened we update the information.
  5984. var inviteLink = document.getElementById('inviteLinkRef');
  5985. if (inviteLink) {
  5986. inviteLink.value = roomUrl;
  5987. inviteLink.select();
  5988. $('#inviteLinkRef').parent()
  5989. .find('button[value=true]').prop('disabled', false);
  5990. }
  5991. };
  5992. /**
  5993. * Disables and enables some of the buttons.
  5994. */
  5995. my.setupButtonsFromConfig = function () {
  5996. if (config.disablePrezi) {
  5997. $("#toolbar_button_prezi").css({display: "none"});
  5998. }
  5999. };
  6000. /**
  6001. * Opens the lock room dialog.
  6002. */
  6003. my.openLockDialog = function () {
  6004. // Only the focus is able to set a shared key.
  6005. if (!APP.xmpp.isModerator()) {
  6006. if (sharedKey) {
  6007. messageHandler.openMessageDialog(null,
  6008. "dialog.passwordError");
  6009. } else {
  6010. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  6011. }
  6012. } else {
  6013. if (sharedKey) {
  6014. messageHandler.openTwoButtonDialog(null, null,
  6015. "dialog.passwordCheck",
  6016. null,
  6017. false,
  6018. "dialog.Remove",
  6019. function (e, v) {
  6020. if (v) {
  6021. Toolbar.setSharedKey('');
  6022. lockRoom(false);
  6023. }
  6024. });
  6025. } else {
  6026. var msg = APP.translation.generateTranslationHTML(
  6027. "dialog.passwordMsg");
  6028. var yourPassword = APP.translation.translateString(
  6029. "dialog.yourPassword");
  6030. messageHandler.openTwoButtonDialog(null, null, null,
  6031. '<h2>' + msg + '</h2>' +
  6032. '<input name="lockKey" type="text"' +
  6033. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  6034. 'placeholder="' + yourPassword + '" autofocus>',
  6035. false,
  6036. "dialog.Save",
  6037. function (e, v, m, f) {
  6038. if (v) {
  6039. var lockKey = f.lockKey;
  6040. if (lockKey) {
  6041. Toolbar.setSharedKey(
  6042. UIUtil.escapeHtml(lockKey));
  6043. lockRoom(true);
  6044. }
  6045. }
  6046. },
  6047. null, null, 'input:first'
  6048. );
  6049. }
  6050. }
  6051. };
  6052. /**
  6053. * Opens the invite link dialog.
  6054. */
  6055. my.openLinkDialog = function () {
  6056. var inviteAttreibutes;
  6057. if (roomUrl === null) {
  6058. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  6059. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  6060. } else {
  6061. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  6062. }
  6063. messageHandler.openTwoButtonDialog("dialog.shareLink",
  6064. null, null,
  6065. '<input id="inviteLinkRef" type="text" ' +
  6066. inviteAttreibutes + ' onclick="this.select();" readonly>',
  6067. false,
  6068. "dialog.Invite",
  6069. function (e, v) {
  6070. if (v) {
  6071. if (roomUrl) {
  6072. inviteParticipants();
  6073. }
  6074. }
  6075. },
  6076. function (event) {
  6077. if (roomUrl) {
  6078. document.getElementById('inviteLinkRef').select();
  6079. } else {
  6080. if (event && event.target)
  6081. $(event.target)
  6082. .find('button[value=true]').prop('disabled', true);
  6083. }
  6084. }
  6085. );
  6086. };
  6087. /**
  6088. * Opens the settings dialog.
  6089. * FIXME: not used ?
  6090. */
  6091. my.openSettingsDialog = function () {
  6092. var settings1 = APP.translation.generateTranslationHTML(
  6093. "dialog.settings1");
  6094. var settings2 = APP.translation.generateTranslationHTML(
  6095. "dialog.settings2");
  6096. var settings3 = APP.translation.generateTranslationHTML(
  6097. "dialog.settings3");
  6098. var yourPassword = APP.translation.translateString(
  6099. "dialog.yourPassword");
  6100. messageHandler.openTwoButtonDialog(null,
  6101. '<h2>' + settings1 + '</h2>' +
  6102. '<input type="checkbox" id="initMuted">' +
  6103. settings2 + '<br/>' +
  6104. '<input type="checkbox" id="requireNicknames">' +
  6105. settings3 +
  6106. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  6107. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  6108. null,
  6109. null,
  6110. false,
  6111. "dialog.Save",
  6112. function () {
  6113. document.getElementById('lockKey').focus();
  6114. },
  6115. function (e, v) {
  6116. if (v) {
  6117. if ($('#initMuted').is(":checked")) {
  6118. // it is checked
  6119. }
  6120. if ($('#requireNicknames').is(":checked")) {
  6121. // it is checked
  6122. }
  6123. /*
  6124. var lockKey = document.getElementById('lockKey');
  6125. if (lockKey.value) {
  6126. setSharedKey(lockKey.value);
  6127. lockRoom(true);
  6128. }
  6129. */
  6130. }
  6131. }
  6132. );
  6133. };
  6134. /**
  6135. * Toggles the application in and out of full screen mode
  6136. * (a.k.a. presentation mode in Chrome).
  6137. */
  6138. my.toggleFullScreen = function () {
  6139. var fsElement = document.documentElement;
  6140. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  6141. //Enter Full Screen
  6142. if (fsElement.mozRequestFullScreen) {
  6143. fsElement.mozRequestFullScreen();
  6144. }
  6145. else {
  6146. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  6147. }
  6148. } else {
  6149. //Exit Full Screen
  6150. if (document.mozCancelFullScreen) {
  6151. document.mozCancelFullScreen();
  6152. } else {
  6153. document.webkitCancelFullScreen();
  6154. }
  6155. }
  6156. };
  6157. /**
  6158. * Unlocks the lock button state.
  6159. */
  6160. my.unlockLockButton = function () {
  6161. if ($("#toolbar_button_security").hasClass("icon-security-locked"))
  6162. UIUtil.buttonClick("#toolbar_button_security", "icon-security icon-security-locked");
  6163. };
  6164. /**
  6165. * Updates the lock button state to locked.
  6166. */
  6167. my.lockLockButton = function () {
  6168. if ($("#toolbar_button_security").hasClass("icon-security"))
  6169. UIUtil.buttonClick("#toolbar_button_security", "icon-security icon-security-locked");
  6170. };
  6171. /**
  6172. * Shows or hides authentication button
  6173. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  6174. */
  6175. my.showAuthenticateButton = function (show) {
  6176. if (show) {
  6177. $('#authentication').css({display: "inline"});
  6178. }
  6179. else {
  6180. $('#authentication').css({display: "none"});
  6181. }
  6182. };
  6183. // Shows or hides the 'recording' button.
  6184. my.showRecordingButton = function (show) {
  6185. if (!config.enableRecording) {
  6186. return;
  6187. }
  6188. if (show) {
  6189. $('#toolbar_button_record').css({display: "inline-block"});
  6190. }
  6191. else {
  6192. $('#toolbar_button_record').css({display: "none"});
  6193. }
  6194. };
  6195. // Sets the state of the recording button
  6196. my.setRecordingButtonState = function (recordingState) {
  6197. var selector = $('#toolbar_button_record');
  6198. if (recordingState === 'on') {
  6199. selector.removeClass("icon-recEnable");
  6200. selector.addClass("icon-recEnable active");
  6201. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6202. var recordOnKey = "recording.on";
  6203. $('#videoConnectionMessage').attr("data-i18n", recordOnKey);
  6204. $('#videoConnectionMessage').text(APP.translation.translateString(recordOnKey));
  6205. setTimeout(function(){
  6206. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6207. $('#videoConnectionMessage').css({display: "none"});
  6208. }, 1500);
  6209. recordingToaster = messageHandler.notify(null, "recording.toaster", null,
  6210. null, null, {timeOut: 0, closeButton: null, tapToDismiss: false});
  6211. } else if (recordingState === 'off') {
  6212. selector.removeClass("icon-recEnable active");
  6213. selector.addClass("icon-recEnable");
  6214. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6215. $('#videoConnectionMessage').css({display: "none"});
  6216. if (recordingToaster)
  6217. messageHandler.remove(recordingToaster);
  6218. } else if (recordingState === 'pending') {
  6219. selector.removeClass("icon-recEnable active");
  6220. selector.addClass("icon-recEnable");
  6221. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6222. var recordPendingKey = "recording.pending";
  6223. $('#videoConnectionMessage').attr("data-i18n", recordPendingKey);
  6224. $('#videoConnectionMessage').text(APP.translation.translateString(recordPendingKey));
  6225. $('#videoConnectionMessage').css({display: "block"});
  6226. }
  6227. };
  6228. // checks whether recording is enabled and whether we have params to start automatically recording
  6229. my.checkAutoRecord = function () {
  6230. if (config.enableRecording && config.autoRecord) {
  6231. toggleRecording(config.autoRecordToken);
  6232. }
  6233. }
  6234. // Shows or hides SIP calls button
  6235. my.showSipCallButton = function (show) {
  6236. if (APP.xmpp.isSipGatewayEnabled() && show) {
  6237. $('#toolbar_button_sip').css({display: "inline-block"});
  6238. } else {
  6239. $('#toolbar_button_sip').css({display: "none"});
  6240. }
  6241. };
  6242. // Shows or hides the dialpad button
  6243. my.showDialPadButton = function (show) {
  6244. if (show) {
  6245. $('#toolbar_button_dialpad').css({display: "inline-block"});
  6246. } else {
  6247. $('#toolbar_button_dialpad').css({display: "none"});
  6248. }
  6249. };
  6250. /**
  6251. * Displays user authenticated identity name(login).
  6252. * @param authIdentity identity name to be displayed.
  6253. */
  6254. my.setAuthenticatedIdentity = function (authIdentity) {
  6255. if (authIdentity) {
  6256. var selector = $('#toolbar_auth_identity');
  6257. selector.css({display: "list-item"});
  6258. selector.text(authIdentity);
  6259. } else {
  6260. $('#toolbar_auth_identity').css({display: "none"});
  6261. }
  6262. };
  6263. /**
  6264. * Shows/hides login button.
  6265. * @param show <tt>true</tt> to show
  6266. */
  6267. my.showLoginButton = function (show) {
  6268. if (show) {
  6269. $('#toolbar_button_login').css({display: "list-item"});
  6270. } else {
  6271. $('#toolbar_button_login').css({display: "none"});
  6272. }
  6273. };
  6274. /**
  6275. * Shows/hides logout button.
  6276. * @param show <tt>true</tt> to show
  6277. */
  6278. my.showLogoutButton = function (show) {
  6279. if (show) {
  6280. $('#toolbar_button_logout').css({display: "list-item"});
  6281. } else {
  6282. $('#toolbar_button_logout').css({display: "none"});
  6283. }
  6284. };
  6285. /**
  6286. * Sets the state of the button. The button has blue glow if desktop
  6287. * streaming is active.
  6288. * @param active the state of the desktop streaming.
  6289. */
  6290. my.changeDesktopSharingButtonState = function (active) {
  6291. var button = $("#toolbar_button_desktopsharing");
  6292. if (active) {
  6293. button.addClass("glow");
  6294. } else {
  6295. button.removeClass("glow");
  6296. }
  6297. };
  6298. return my;
  6299. }(Toolbar || {}));
  6300. module.exports = Toolbar;
  6301. },{"../../../service/authentication/AuthenticationEvents":156,"../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){
  6302. /* global APP, config, $, interfaceConfig, Moderator,
  6303. DesktopStreaming.showDesktopSharingButton */
  6304. var toolbarTimeoutObject,
  6305. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  6306. function showDesktopSharingButton() {
  6307. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  6308. $('#toolbar_button_desktopsharing').css({display: "inline-block"});
  6309. } else {
  6310. $('#toolbar_button_desktopsharing').css({display: "none"});
  6311. }
  6312. }
  6313. /**
  6314. * Hides the toolbar.
  6315. */
  6316. function hideToolbar() {
  6317. if(config.alwaysVisibleToolbar)
  6318. return;
  6319. var header = $("#header"),
  6320. bottomToolbar = $("#bottomToolbar");
  6321. var isToolbarHover = false;
  6322. header.find('*').each(function () {
  6323. var id = $(this).attr('id');
  6324. if ($("#" + id + ":hover").length > 0) {
  6325. isToolbarHover = true;
  6326. }
  6327. });
  6328. if ($("#bottomToolbar:hover").length > 0) {
  6329. isToolbarHover = true;
  6330. }
  6331. clearTimeout(toolbarTimeoutObject);
  6332. toolbarTimeoutObject = null;
  6333. if (!isToolbarHover) {
  6334. header.hide("slide", { direction: "up", duration: 300});
  6335. $('#subject').animate({top: "-=40"}, 300);
  6336. if ($("#remoteVideos").hasClass("hidden")) {
  6337. bottomToolbar.hide(
  6338. "slide", {direction: "right", duration: 300});
  6339. }
  6340. }
  6341. else {
  6342. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6343. }
  6344. }
  6345. var ToolbarToggler = {
  6346. /**
  6347. * Shows the main toolbar.
  6348. */
  6349. showToolbar: function () {
  6350. if (interfaceConfig.filmStripOnly)
  6351. return;
  6352. var header = $("#header"),
  6353. bottomToolbar = $("#bottomToolbar");
  6354. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  6355. header.show("slide", { direction: "up", duration: 300});
  6356. $('#subject').animate({top: "+=40"}, 300);
  6357. if (!bottomToolbar.is(":visible")) {
  6358. bottomToolbar.show(
  6359. "slide", {direction: "right", duration: 300});
  6360. }
  6361. if (toolbarTimeoutObject) {
  6362. clearTimeout(toolbarTimeoutObject);
  6363. toolbarTimeoutObject = null;
  6364. }
  6365. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6366. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  6367. }
  6368. if (APP.xmpp.isModerator())
  6369. {
  6370. // TODO: Enable settings functionality.
  6371. // Need to uncomment the settings button in index.html.
  6372. // $('#settingsButton').css({visibility:"visible"});
  6373. }
  6374. // Show/hide desktop sharing button
  6375. showDesktopSharingButton();
  6376. },
  6377. /**
  6378. * Docks/undocks the toolbar.
  6379. *
  6380. * @param isDock indicates what operation to perform
  6381. */
  6382. dockToolbar: function (isDock) {
  6383. if (interfaceConfig.filmStripOnly)
  6384. return;
  6385. if (isDock) {
  6386. // First make sure the toolbar is shown.
  6387. if (!$('#header').is(':visible')) {
  6388. this.showToolbar();
  6389. }
  6390. // Then clear the time out, to dock the toolbar.
  6391. if (toolbarTimeoutObject) {
  6392. clearTimeout(toolbarTimeoutObject);
  6393. toolbarTimeoutObject = null;
  6394. }
  6395. }
  6396. else {
  6397. if (!$('#header').is(':visible')) {
  6398. this.showToolbar();
  6399. }
  6400. else {
  6401. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6402. }
  6403. }
  6404. },
  6405. showDesktopSharingButton: showDesktopSharingButton
  6406. };
  6407. module.exports = ToolbarToggler;
  6408. },{}],30:[function(require,module,exports){
  6409. /* global $ */
  6410. var JitsiPopover = (function () {
  6411. /**
  6412. * Constructs new JitsiPopover and attaches it to the element
  6413. * @param element jquery selector
  6414. * @param options the options for the popover.
  6415. * @constructor
  6416. */
  6417. function JitsiPopover(element, options)
  6418. {
  6419. this.options = {
  6420. skin: "white",
  6421. content: ""
  6422. };
  6423. if(options)
  6424. {
  6425. if(options.skin)
  6426. this.options.skin = options.skin;
  6427. if(options.content)
  6428. this.options.content = options.content;
  6429. }
  6430. this.elementIsHovered = false;
  6431. this.popoverIsHovered = false;
  6432. this.popoverShown = false;
  6433. element.data("jitsi_popover", this);
  6434. this.element = element;
  6435. this.template = ' <div class="jitsipopover ' + this.options.skin +
  6436. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  6437. '<div class="jitsiPopupmenuPadding"></div></div>';
  6438. var self = this;
  6439. this.element.on("mouseenter", function () {
  6440. self.elementIsHovered = true;
  6441. self.show();
  6442. }).on("mouseleave", function () {
  6443. self.elementIsHovered = false;
  6444. setTimeout(function () {
  6445. self.hide();
  6446. }, 10);
  6447. });
  6448. }
  6449. /**
  6450. * Shows the popover
  6451. */
  6452. JitsiPopover.prototype.show = function () {
  6453. if(!JitsiPopover.enabled)
  6454. return;
  6455. this.createPopover();
  6456. this.popoverShown = true;
  6457. };
  6458. /**
  6459. * Hides the popover
  6460. */
  6461. JitsiPopover.prototype.hide = function () {
  6462. if(!this.elementIsHovered && !this.popoverIsHovered &&
  6463. this.popoverShown) {
  6464. this.forceHide();
  6465. }
  6466. };
  6467. /**
  6468. * Hides the popover.
  6469. */
  6470. JitsiPopover.prototype.forceHide = function () {
  6471. $(".jitsipopover").remove();
  6472. this.popoverShown = false;
  6473. };
  6474. /**
  6475. * Creates the popover html.
  6476. */
  6477. JitsiPopover.prototype.createPopover = function () {
  6478. $("body").append(this.template);
  6479. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  6480. var self = this;
  6481. $(".jitsipopover").on("mouseenter", function () {
  6482. self.popoverIsHovered = true;
  6483. }).on("mouseleave", function () {
  6484. self.popoverIsHovered = false;
  6485. self.hide();
  6486. });
  6487. this.refreshPosition();
  6488. };
  6489. /**
  6490. * Refreshes the position of the popover.
  6491. */
  6492. JitsiPopover.prototype.refreshPosition = function () {
  6493. $(".jitsipopover").position({
  6494. my: "bottom",
  6495. at: "top",
  6496. collision: "fit",
  6497. of: this.element,
  6498. using: function (position, elements) {
  6499. var calcLeft = elements.target.left - elements.element.left +
  6500. elements.target.width/2;
  6501. $(".jitsipopover").css(
  6502. {top: position.top, left: position.left, display: "table"});
  6503. $(".jitsipopover > .arrow").css({left: calcLeft});
  6504. $(".jitsipopover > .jitsiPopupmenuPadding").css(
  6505. {left: calcLeft - 50});
  6506. }
  6507. });
  6508. };
  6509. /**
  6510. * Updates the content of popover.
  6511. * @param content new content
  6512. */
  6513. JitsiPopover.prototype.updateContent = function (content) {
  6514. this.options.content = content;
  6515. if(!this.popoverShown)
  6516. return;
  6517. $(".jitsipopover").remove();
  6518. this.createPopover();
  6519. };
  6520. JitsiPopover.enabled = true;
  6521. return JitsiPopover;
  6522. })();
  6523. module.exports = JitsiPopover;
  6524. },{}],31:[function(require,module,exports){
  6525. /* global $, APP, jQuery, toastr */
  6526. /**
  6527. * Flag for enable/disable of the notifications.
  6528. * @type {boolean}
  6529. */
  6530. var notificationsEnabled = true;
  6531. var messageHandler = (function(my) {
  6532. /**
  6533. * Shows a message to the user.
  6534. *
  6535. * @param titleKey the title of the message
  6536. * @param messageKey the text of the message
  6537. */
  6538. my.openMessageDialog = function(titleKey, messageKey) {
  6539. var title = null;
  6540. if(titleKey) {
  6541. title = APP.translation.generateTranslationHTML(titleKey);
  6542. }
  6543. var message = APP.translation.generateTranslationHTML(messageKey);
  6544. $.prompt(message,
  6545. {title: title, persistent: false}
  6546. );
  6547. };
  6548. /**
  6549. * Shows a message to the user with two buttons: first is given as a
  6550. * parameter and the second is Cancel.
  6551. *
  6552. * @param titleString the title of the message
  6553. * @param msgString the text of the message
  6554. * @param persistent boolean value which determines whether the message is
  6555. * persistent or not
  6556. * @param leftButton the fist button's text
  6557. * @param submitFunction function to be called on submit
  6558. * @param loadedFunction function to be called after the prompt is fully
  6559. * loaded
  6560. * @param closeFunction function to be called after the prompt is closed
  6561. * @param focus optional focus selector or button index to be focused after
  6562. * the dialog is opened
  6563. * @param defaultButton index of default button which will be activated when
  6564. * the user press 'enter'. Indexed from 0.
  6565. */
  6566. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  6567. persistent, leftButtonKey, submitFunction, loadedFunction,
  6568. closeFunction, focus, defaultButton) {
  6569. var buttons = [];
  6570. var leftButton = APP.translation.generateTranslationHTML(leftButtonKey);
  6571. buttons.push({ title: leftButton, value: true});
  6572. var cancelButton
  6573. = APP.translation.generateTranslationHTML("dialog.Cancel");
  6574. buttons.push({title: cancelButton, value: false});
  6575. var message = msgString, title = titleString;
  6576. if (titleKey) {
  6577. title = APP.translation.generateTranslationHTML(titleKey);
  6578. }
  6579. if (msgKey) {
  6580. message = APP.translation.generateTranslationHTML(msgKey);
  6581. }
  6582. $.prompt(message, {
  6583. title: title,
  6584. persistent: false,
  6585. buttons: buttons,
  6586. defaultButton: defaultButton,
  6587. focus: focus,
  6588. loaded: loadedFunction,
  6589. submit: submitFunction,
  6590. close: closeFunction
  6591. });
  6592. };
  6593. /**
  6594. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6595. *
  6596. * @param titleString the title of the message
  6597. * @param msgString the text of the message
  6598. * @param persistent boolean value which determines whether the message is
  6599. * persistent or not
  6600. * @param buttons object with the buttons. The keys must be the name of the
  6601. * button and value is the value that will be passed to
  6602. * submitFunction
  6603. * @param submitFunction function to be called on submit
  6604. * @param loadedFunction function to be called after the prompt is fully
  6605. * loaded
  6606. */
  6607. my.openDialog = function (titleString, msgString, persistent, buttons,
  6608. submitFunction, loadedFunction) {
  6609. var args = {
  6610. title: titleString,
  6611. persistent: persistent,
  6612. buttons: buttons,
  6613. defaultButton: 1,
  6614. loaded: loadedFunction,
  6615. submit: submitFunction
  6616. };
  6617. if (persistent) {
  6618. args.closeText = '';
  6619. }
  6620. return new Impromptu(msgString, args);
  6621. };
  6622. /**
  6623. * Closes currently opened dialog.
  6624. */
  6625. my.closeDialog = function () {
  6626. $.prompt.close();
  6627. };
  6628. /**
  6629. * Shows a dialog with different states to the user.
  6630. *
  6631. * @param statesObject object containing all the states of the dialog.
  6632. */
  6633. my.openDialogWithStates = function (statesObject, options) {
  6634. return new Impromptu(statesObject, options);
  6635. };
  6636. /**
  6637. * Opens new popup window for given <tt>url</tt> centered over current
  6638. * window.
  6639. *
  6640. * @param url the URL to be displayed in the popup window
  6641. * @param w the width of the popup window
  6642. * @param h the height of the popup window
  6643. * @param onPopupClosed optional callback function called when popup window
  6644. * has been closed.
  6645. *
  6646. * @returns {object} popup window object if opened successfully or undefined
  6647. * in case we failed to open it(popup blocked)
  6648. */
  6649. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  6650. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  6651. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  6652. var popup = window.open(
  6653. url, '_blank',
  6654. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  6655. if (popup && onPopupClosed) {
  6656. var pollTimer = window.setInterval(function () {
  6657. if (popup.closed !== false) {
  6658. window.clearInterval(pollTimer);
  6659. onPopupClosed();
  6660. }
  6661. }, 200);
  6662. }
  6663. return popup;
  6664. };
  6665. /**
  6666. * Shows a dialog prompting the user to send an error report.
  6667. *
  6668. * @param titleKey the title of the message
  6669. * @param msgKey the text of the message
  6670. * @param error the error that is being reported
  6671. */
  6672. my.openReportDialog = function(titleKey, msgKey, error) {
  6673. my.openMessageDialog(titleKey, msgKey);
  6674. console.log(error);
  6675. //FIXME send the error to the server
  6676. };
  6677. /**
  6678. * Shows an error dialog to the user.
  6679. * @param titleKey the title of the message.
  6680. * @param msgKey the text of the message.
  6681. */
  6682. my.showError = function(titleKey, msgKey) {
  6683. if (!titleKey) {
  6684. titleKey = "dialog.oops";
  6685. }
  6686. if (!msgKey) {
  6687. msgKey = "dialog.defaultError";
  6688. }
  6689. messageHandler.openMessageDialog(titleKey, msgKey);
  6690. };
  6691. /**
  6692. * Displayes notification.
  6693. * @param displayName display name of the participant that is associated with the notification.
  6694. * @param displayNameKey the key from the language file for the display name.
  6695. * @param cls css class for the notification
  6696. * @param messageKey the key from the language file for the text of the message.
  6697. * @param messageArguments object with the arguments for the message.
  6698. * @param options object with language options.
  6699. */
  6700. my.notify = function(displayName, displayNameKey,
  6701. cls, messageKey, messageArguments, options) {
  6702. if(!notificationsEnabled)
  6703. return;
  6704. var displayNameSpan = '<span class="nickname" ';
  6705. if (displayName) {
  6706. displayNameSpan += ">" + displayName;
  6707. } else {
  6708. displayNameSpan += "data-i18n='" + displayNameKey +
  6709. "'>" + APP.translation.translateString(displayNameKey);
  6710. }
  6711. displayNameSpan += "</span>";
  6712. return toastr.info(
  6713. displayNameSpan + '<br>' +
  6714. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  6715. (messageArguments?
  6716. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  6717. : "") + ">" +
  6718. APP.translation.translateString(messageKey,
  6719. messageArguments) +
  6720. '</span>', null, options);
  6721. };
  6722. /**
  6723. * Removes the toaster.
  6724. * @param toasterElement
  6725. */
  6726. my.remove = function(toasterElement) {
  6727. toasterElement.remove();
  6728. };
  6729. /**
  6730. * Disables notifications.
  6731. */
  6732. my.disableNotifications = function () {
  6733. notificationsEnabled = false;
  6734. };
  6735. /**
  6736. * Enables notifications.
  6737. */
  6738. my.enableNotifications = function () {
  6739. notificationsEnabled = true;
  6740. };
  6741. return my;
  6742. }(messageHandler || {}));
  6743. module.exports = messageHandler;
  6744. },{}],32:[function(require,module,exports){
  6745. var UIEvents = require("../../../service/UI/UIEvents");
  6746. var nickname = null;
  6747. var eventEmitter = null;
  6748. var NicknameHandler = {
  6749. init: function (emitter) {
  6750. eventEmitter = emitter;
  6751. var storedDisplayName = window.localStorage.displayname;
  6752. if (storedDisplayName) {
  6753. nickname = storedDisplayName;
  6754. }
  6755. },
  6756. setNickname: function (newNickname) {
  6757. if (!newNickname || nickname === newNickname)
  6758. return;
  6759. nickname = newNickname;
  6760. window.localStorage.displayname = nickname;
  6761. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  6762. },
  6763. getNickname: function () {
  6764. return nickname;
  6765. },
  6766. addListener: function (type, listener) {
  6767. eventEmitter.on(type, listener);
  6768. }
  6769. };
  6770. module.exports = NicknameHandler;
  6771. },{"../../../service/UI/UIEvents":155}],33:[function(require,module,exports){
  6772. /* global $ */
  6773. /**
  6774. * Created by hristo on 12/22/14.
  6775. */
  6776. module.exports = {
  6777. /**
  6778. * Returns the available video width.
  6779. */
  6780. getAvailableVideoWidth: function (isVisible) {
  6781. var PanelToggler = require("../side_pannels/SidePanelToggler");
  6782. if(typeof isVisible === "undefined" || isVisible === null)
  6783. isVisible = PanelToggler.isVisible();
  6784. var rightPanelWidth
  6785. = isVisible ? PanelToggler.getPanelSize()[0] : 0;
  6786. return window.innerWidth - rightPanelWidth;
  6787. },
  6788. /**
  6789. * Changes the style class of the element given by id.
  6790. */
  6791. buttonClick: function(id, classname) {
  6792. $(id).toggleClass(classname); // add the class to the clicked element
  6793. },
  6794. /**
  6795. * Returns the text width for the given element.
  6796. *
  6797. * @param el the element
  6798. */
  6799. getTextWidth: function (el) {
  6800. return (el.clientWidth + 1);
  6801. },
  6802. /**
  6803. * Returns the text height for the given element.
  6804. *
  6805. * @param el the element
  6806. */
  6807. getTextHeight: function (el) {
  6808. return (el.clientHeight + 1);
  6809. },
  6810. /**
  6811. * Plays the sound given by id.
  6812. *
  6813. * @param id the identifier of the audio element.
  6814. */
  6815. playSoundNotification: function (id) {
  6816. document.getElementById(id).play();
  6817. },
  6818. /**
  6819. * Escapes the given text.
  6820. */
  6821. escapeHtml: function (unsafeText) {
  6822. return $('<div/>').text(unsafeText).html();
  6823. },
  6824. imageToGrayScale: function (canvas) {
  6825. var context = canvas.getContext('2d');
  6826. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  6827. var pixels = imgData.data;
  6828. for (var i = 0, n = pixels.length; i < n; i += 4) {
  6829. var grayscale
  6830. = pixels[i] * 0.3 + pixels[i+1] * 0.59 + pixels[i+2] * 0.11;
  6831. pixels[i ] = grayscale; // red
  6832. pixels[i+1] = grayscale; // green
  6833. pixels[i+2] = grayscale; // blue
  6834. // pixels[i+3] is alpha
  6835. }
  6836. // redraw the image in black & white
  6837. context.putImageData(imgData, 0, 0);
  6838. },
  6839. setTooltip: function (element, key, position) {
  6840. element.setAttribute("data-i18n", "[data-content]" + key);
  6841. element.setAttribute("data-toggle", "popover");
  6842. element.setAttribute("data-placement", position);
  6843. element.setAttribute("data-html", true);
  6844. element.setAttribute("data-container", "body");
  6845. },
  6846. /**
  6847. * Inserts given child element as the first one into the container.
  6848. * @param container the container to which new child element will be added
  6849. * @param newChild the new element that will be inserted into the container
  6850. */
  6851. prependChild: function (container, newChild) {
  6852. var firstChild = container.childNodes[0];
  6853. if (firstChild) {
  6854. container.insertBefore(newChild, firstChild);
  6855. } else {
  6856. container.appendChild(newChild);
  6857. }
  6858. }
  6859. };
  6860. },{"../side_pannels/SidePanelToggler":20}],34:[function(require,module,exports){
  6861. /* global APP, $ */
  6862. var JitsiPopover = require("../util/JitsiPopover");
  6863. /**
  6864. * Constructs new connection indicator.
  6865. * @param videoContainer the video container associated with the indicator.
  6866. * @constructor
  6867. */
  6868. function ConnectionIndicator(videoContainer, jid) {
  6869. this.videoContainer = videoContainer;
  6870. this.bandwidth = null;
  6871. this.packetLoss = null;
  6872. this.bitrate = null;
  6873. this.showMoreValue = false;
  6874. this.resolution = null;
  6875. this.transport = [];
  6876. this.popover = null;
  6877. this.jid = jid;
  6878. this.create();
  6879. }
  6880. /**
  6881. * Values for the connection quality
  6882. * @type {{98: string,
  6883. * 81: string,
  6884. * 64: string,
  6885. * 47: string,
  6886. * 30: string,
  6887. * 0: string}}
  6888. */
  6889. ConnectionIndicator.connectionQualityValues = {
  6890. 98: "18px", //full
  6891. 81: "15px",//4 bars
  6892. 64: "11px",//3 bars
  6893. 47: "7px",//2 bars
  6894. 30: "3px",//1 bar
  6895. 0: "0px"//empty
  6896. };
  6897. ConnectionIndicator.getIP = function(value) {
  6898. return value.substring(0, value.lastIndexOf(":"));
  6899. };
  6900. ConnectionIndicator.getPort = function(value) {
  6901. return value.substring(value.lastIndexOf(":") + 1, value.length);
  6902. };
  6903. ConnectionIndicator.getStringFromArray = function (array) {
  6904. var res = "";
  6905. for(var i = 0; i < array.length; i++) {
  6906. res += (i === 0? "" : ", ") + array[i];
  6907. }
  6908. return res;
  6909. };
  6910. /**
  6911. * Generates the html content.
  6912. * @returns {string} the html content.
  6913. */
  6914. ConnectionIndicator.prototype.generateText = function () {
  6915. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  6916. var translate = APP.translation.translateString;
  6917. if(this.bitrate === null) {
  6918. downloadBitrate = "N/A";
  6919. uploadBitrate = "N/A";
  6920. }
  6921. else {
  6922. downloadBitrate =
  6923. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  6924. uploadBitrate =
  6925. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  6926. }
  6927. if(this.packetLoss === null) {
  6928. packetLoss = "N/A";
  6929. } else {
  6930. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  6931. (this.packetLoss.download !== null ?
  6932. this.packetLoss.download : "N/A") +
  6933. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  6934. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") +
  6935. "%";
  6936. }
  6937. var resolutionValue = null;
  6938. if(this.resolution && this.jid != null) {
  6939. var keys = Object.keys(this.resolution);
  6940. for(var ssrc in this.resolution) {
  6941. resolutionValue = this.resolution[ssrc];
  6942. }
  6943. }
  6944. if(this.jid === null) {
  6945. resolution = "";
  6946. if(this.resolution === null || !Object.keys(this.resolution) ||
  6947. Object.keys(this.resolution).length === 0) {
  6948. resolution = "N/A";
  6949. } else {
  6950. for (i in this.resolution) {
  6951. resolutionValue = this.resolution[i];
  6952. if (resolutionValue) {
  6953. if (resolutionValue.height &&
  6954. resolutionValue.width) {
  6955. resolution += (resolution === "" ? "" : ", ") +
  6956. resolutionValue.width + "x" +
  6957. resolutionValue.height;
  6958. }
  6959. }
  6960. }
  6961. }
  6962. } else if(!resolutionValue ||
  6963. !resolutionValue.height ||
  6964. !resolutionValue.width) {
  6965. resolution = "N/A";
  6966. } else {
  6967. resolution = resolutionValue.width + "x" + resolutionValue.height;
  6968. }
  6969. var result = "<table style='width:100%'>" +
  6970. "<tr>" +
  6971. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  6972. translate("connectionindicator.bitrate") + "</span></td>" +
  6973. "<td><span class='jitsipopover_green'>&darr;</span>" +
  6974. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  6975. uploadBitrate + "</td>" +
  6976. "</tr><tr>" +
  6977. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  6978. translate("connectionindicator.packetloss") + "</span></td>" +
  6979. "<td>" + packetLoss + "</td>" +
  6980. "</tr><tr>" +
  6981. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  6982. translate("connectionindicator.resolution") + "</span></td>" +
  6983. "<td>" + resolution + "</td></tr></table>";
  6984. if(this.videoContainer.videoSpanId == "localVideoContainer") {
  6985. result += "<div class=\"jitsipopover_showmore\" " +
  6986. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  6987. // FIXME: we do not know local jid when this text is generated
  6988. //this.jid + "')\" data-i18n='connectionindicator." +
  6989. "local')\" data-i18n='connectionindicator." +
  6990. (this.showMoreValue ? "less" : "more") + "'>" +
  6991. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  6992. "</div><br />";
  6993. }
  6994. if (this.showMoreValue) {
  6995. var downloadBandwidth, uploadBandwidth, transport;
  6996. if (this.bandwidth === null) {
  6997. downloadBandwidth = "N/A";
  6998. uploadBandwidth = "N/A";
  6999. } else {
  7000. downloadBandwidth = this.bandwidth.download?
  7001. this.bandwidth.download + " Kbps" :
  7002. "N/A";
  7003. uploadBandwidth = this.bandwidth.upload?
  7004. this.bandwidth.upload + " Kbps" :
  7005. "N/A";
  7006. }
  7007. if (!this.transport || this.transport.length === 0) {
  7008. transport = "<tr>" +
  7009. "<td><span class='jitsipopover_blue' " +
  7010. "data-i18n='connectionindicator.address'>" +
  7011. translate("connectionindicator.address") + "</span></td>" +
  7012. "<td> N/A</td></tr>";
  7013. } else {
  7014. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  7015. for(i = 0; i < this.transport.length; i++) {
  7016. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  7017. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  7018. var localIP =
  7019. ConnectionIndicator.getIP(this.transport[i].localip);
  7020. var localPort =
  7021. ConnectionIndicator.getPort(this.transport[i].localip);
  7022. if(data.remoteIP.indexOf(ip) == -1) {
  7023. data.remoteIP.push(ip);
  7024. }
  7025. if(data.remotePort.indexOf(port) == -1) {
  7026. data.remotePort.push(port);
  7027. }
  7028. if(data.localIP.indexOf(localIP) == -1) {
  7029. data.localIP.push(localIP);
  7030. }
  7031. if(data.localPort.indexOf(localPort) == -1) {
  7032. data.localPort.push(localPort);
  7033. }
  7034. }
  7035. var local_address_key = "connectionindicator.localaddress";
  7036. var remote_address_key = "connectionindicator.remoteaddress";
  7037. var localTransport =
  7038. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7039. local_address_key +"' data-i18n-options='" +
  7040. JSON.stringify({count: data.localIP.length}) + "'>" +
  7041. translate(local_address_key, {count: data.localIP.length}) +
  7042. "</span></td><td> " +
  7043. ConnectionIndicator.getStringFromArray(data.localIP) +
  7044. "</td></tr>";
  7045. transport =
  7046. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7047. remote_address_key + "' data-i18n-options='" +
  7048. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  7049. translate(remote_address_key,
  7050. {count: data.remoteIP.length}) +
  7051. "</span></td><td> " +
  7052. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  7053. "</td></tr>";
  7054. var key_remote = "connectionindicator.remoteport",
  7055. key_local = "connectionindicator.localport";
  7056. transport += "<tr>" +
  7057. "<td>" +
  7058. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  7059. "' data-i18n-options='" +
  7060. JSON.stringify({count: this.transport.length}) + "'>" +
  7061. translate(key_remote, {count: this.transport.length}) +
  7062. "</span></td><td>";
  7063. localTransport += "<tr>" +
  7064. "<td>" +
  7065. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  7066. "' data-i18n-options='" +
  7067. JSON.stringify({count: this.transport.length}) + "'>" +
  7068. translate(key_local, {count: this.transport.length}) +
  7069. "</span></td><td>";
  7070. transport +=
  7071. ConnectionIndicator.getStringFromArray(data.remotePort);
  7072. localTransport +=
  7073. ConnectionIndicator.getStringFromArray(data.localPort);
  7074. transport += "</td></tr>";
  7075. transport += localTransport + "</td></tr>";
  7076. transport +="<tr>" +
  7077. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  7078. translate("connectionindicator.transport") + "</span></td>" +
  7079. "<td>" + this.transport[0].type + "</td></tr>";
  7080. }
  7081. result += "<table style='width:100%'>" +
  7082. "<tr>" +
  7083. "<td>" +
  7084. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  7085. translate("connectionindicator.bandwidth") + "</span>" +
  7086. "</td><td>" +
  7087. "<span class='jitsipopover_green'>&darr;</span>" +
  7088. downloadBandwidth +
  7089. " <span class='jitsipopover_orange'>&uarr;</span>" +
  7090. uploadBandwidth + "</td></tr>";
  7091. result += transport + "</table>";
  7092. }
  7093. return result;
  7094. };
  7095. /**
  7096. * Shows or hide the additional information.
  7097. */
  7098. ConnectionIndicator.prototype.showMore = function () {
  7099. this.showMoreValue = !this.showMoreValue;
  7100. this.updatePopoverData();
  7101. };
  7102. function createIcon(classes) {
  7103. var icon = document.createElement("span");
  7104. for(var i in classes) {
  7105. icon.classList.add(classes[i]);
  7106. }
  7107. icon.appendChild(
  7108. document.createElement("i")).classList.add("icon-connection");
  7109. return icon;
  7110. }
  7111. /**
  7112. * Creates the indicator
  7113. */
  7114. ConnectionIndicator.prototype.create = function () {
  7115. this.connectionIndicatorContainer = document.createElement("div");
  7116. this.connectionIndicatorContainer.className = "connectionindicator";
  7117. this.connectionIndicatorContainer.style.display = "none";
  7118. this.videoContainer.container.appendChild(
  7119. this.connectionIndicatorContainer);
  7120. this.popover = new JitsiPopover(
  7121. $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
  7122. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  7123. APP.translation.translateString("connectionindicator.na") + "</div>",
  7124. skin: "black"});
  7125. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  7126. createIcon(["connection", "connection_empty"]));
  7127. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  7128. createIcon(["connection", "connection_full"]));
  7129. };
  7130. /**
  7131. * Removes the indicator
  7132. */
  7133. ConnectionIndicator.prototype.remove = function() {
  7134. if (this.connectionIndicatorContainer.parentNode) {
  7135. this.connectionIndicatorContainer.parentNode.removeChild(
  7136. this.connectionIndicatorContainer);
  7137. }
  7138. this.popover.forceHide();
  7139. };
  7140. /**
  7141. * Updates the data of the indicator
  7142. * @param percent the percent of connection quality
  7143. * @param object the statistics data.
  7144. */
  7145. ConnectionIndicator.prototype.updateConnectionQuality =
  7146. function (percent, object) {
  7147. if (percent === null) {
  7148. this.connectionIndicatorContainer.style.display = "none";
  7149. this.popover.forceHide();
  7150. return;
  7151. } else {
  7152. if(this.connectionIndicatorContainer.style.display == "none") {
  7153. this.connectionIndicatorContainer.style.display = "block";
  7154. this.videoContainer.updateIconPositions();
  7155. }
  7156. }
  7157. this.bandwidth = object.bandwidth;
  7158. this.bitrate = object.bitrate;
  7159. this.packetLoss = object.packetLoss;
  7160. this.transport = object.transport;
  7161. if (object.resolution) {
  7162. this.resolution = object.resolution;
  7163. }
  7164. for (var quality in ConnectionIndicator.connectionQualityValues) {
  7165. if (percent >= quality) {
  7166. this.fullIcon.style.width =
  7167. ConnectionIndicator.connectionQualityValues[quality];
  7168. }
  7169. }
  7170. this.updatePopoverData();
  7171. };
  7172. /**
  7173. * Updates the resolution
  7174. * @param resolution the new resolution
  7175. */
  7176. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  7177. this.resolution = resolution;
  7178. this.updatePopoverData();
  7179. };
  7180. /**
  7181. * Updates the content of the popover
  7182. */
  7183. ConnectionIndicator.prototype.updatePopoverData = function () {
  7184. this.popover.updateContent(
  7185. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  7186. APP.translation.translateElement($(".connection_info"));
  7187. };
  7188. /**
  7189. * Hides the popover
  7190. */
  7191. ConnectionIndicator.prototype.hide = function () {
  7192. this.popover.forceHide();
  7193. };
  7194. /**
  7195. * Hides the indicator
  7196. */
  7197. ConnectionIndicator.prototype.hideIndicator = function () {
  7198. this.connectionIndicatorContainer.style.display = "none";
  7199. if(this.popover)
  7200. this.popover.forceHide();
  7201. };
  7202. module.exports = ConnectionIndicator;
  7203. },{"../util/JitsiPopover":30}],35:[function(require,module,exports){
  7204. /* global $, APP, Strophe, interfaceConfig */
  7205. var Avatar = require("../avatar/Avatar");
  7206. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7207. var UIUtil = require("../util/UIUtil");
  7208. var UIEvents = require("../../../service/UI/UIEvents");
  7209. var xmpp = require("../../xmpp/xmpp");
  7210. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  7211. // FIXME: With Temasys we have to re-select everytime
  7212. //var video = $('#largeVideo');
  7213. var currentVideoWidth = null;
  7214. var currentVideoHeight = null;
  7215. // By default we use camera
  7216. var getVideoSize = getCameraVideoSize;
  7217. var getVideoPosition = getCameraVideoPosition;
  7218. /**
  7219. * The small video instance that is displayed in the large video
  7220. * @type {SmallVideo}
  7221. */
  7222. var currentSmallVideo = null;
  7223. /**
  7224. * Indicates whether the large video is enabled.
  7225. * @type {boolean}
  7226. */
  7227. var isEnabled = true;
  7228. /**
  7229. * Current large video state.
  7230. * Possible values - video, prezi or etherpad.
  7231. * @type {string}
  7232. */
  7233. var state = "video";
  7234. /**
  7235. * Returns the html element associated with the passed state of large video
  7236. * @param state the state.
  7237. * @returns {JQuery|*|jQuery|HTMLElement} the container.
  7238. */
  7239. function getContainerByState(state)
  7240. {
  7241. var selector = null;
  7242. switch (state)
  7243. {
  7244. case "video":
  7245. selector = "#largeVideo";
  7246. break;
  7247. case "etherpad":
  7248. selector = "#etherpad>iframe";
  7249. break;
  7250. case "prezi":
  7251. selector = "#presentation>iframe";
  7252. break;
  7253. }
  7254. return (selector !== null)? $(selector) : null;
  7255. }
  7256. /**
  7257. * Sets the size and position of the given video element.
  7258. *
  7259. * @param video the video element to position
  7260. * @param width the desired video width
  7261. * @param height the desired video height
  7262. * @param horizontalIndent the left and right indent
  7263. * @param verticalIndent the top and bottom indent
  7264. */
  7265. function positionVideo(video,
  7266. width,
  7267. height,
  7268. horizontalIndent,
  7269. verticalIndent,
  7270. animate) {
  7271. if (animate) {
  7272. video.animate({
  7273. width: width,
  7274. height: height,
  7275. top: verticalIndent,
  7276. bottom: verticalIndent,
  7277. left: horizontalIndent,
  7278. right: horizontalIndent
  7279. },
  7280. {
  7281. queue: false,
  7282. duration: 500
  7283. });
  7284. } else {
  7285. video.width(width);
  7286. video.height(height);
  7287. video.css({ top: verticalIndent + 'px',
  7288. bottom: verticalIndent + 'px',
  7289. left: horizontalIndent + 'px',
  7290. right: horizontalIndent + 'px'});
  7291. }
  7292. }
  7293. /**
  7294. * Returns an array of the video dimensions, so that it keeps it's aspect
  7295. * ratio and fits available area with it's larger dimension. This method
  7296. * ensures that whole video will be visible and can leave empty areas.
  7297. *
  7298. * @return an array with 2 elements, the video width and the video height
  7299. */
  7300. function getDesktopVideoSize(videoWidth,
  7301. videoHeight,
  7302. videoSpaceWidth,
  7303. videoSpaceHeight) {
  7304. if (!videoWidth)
  7305. videoWidth = currentVideoWidth;
  7306. if (!videoHeight)
  7307. videoHeight = currentVideoHeight;
  7308. var aspectRatio = videoWidth / videoHeight;
  7309. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7310. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7311. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  7312. if (availableWidth / aspectRatio >= videoSpaceHeight)
  7313. {
  7314. availableHeight = videoSpaceHeight;
  7315. availableWidth = availableHeight * aspectRatio;
  7316. }
  7317. if (availableHeight * aspectRatio >= videoSpaceWidth)
  7318. {
  7319. availableWidth = videoSpaceWidth;
  7320. availableHeight = availableWidth / aspectRatio;
  7321. }
  7322. return [availableWidth, availableHeight];
  7323. }
  7324. /**
  7325. * Returns an array of the video horizontal and vertical indents,
  7326. * so that if fits its parent.
  7327. *
  7328. * @return an array with 2 elements, the horizontal indent and the vertical
  7329. * indent
  7330. */
  7331. function getCameraVideoPosition(videoWidth,
  7332. videoHeight,
  7333. videoSpaceWidth,
  7334. videoSpaceHeight) {
  7335. // Parent height isn't completely calculated when we position the video in
  7336. // full screen mode and this is why we use the screen height in this case.
  7337. // Need to think it further at some point and implement it properly.
  7338. var isFullScreen = document.fullScreen ||
  7339. document.mozFullScreen ||
  7340. document.webkitIsFullScreen;
  7341. if (isFullScreen)
  7342. videoSpaceHeight = window.innerHeight;
  7343. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7344. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  7345. return [horizontalIndent, verticalIndent];
  7346. }
  7347. /**
  7348. * Returns an array of the video horizontal and vertical indents.
  7349. * Centers horizontally and top aligns vertically.
  7350. *
  7351. * @return an array with 2 elements, the horizontal indent and the vertical
  7352. * indent
  7353. */
  7354. function getDesktopVideoPosition(videoWidth,
  7355. videoHeight,
  7356. videoSpaceWidth,
  7357. videoSpaceHeight) {
  7358. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7359. var verticalIndent = 0;// Top aligned
  7360. return [horizontalIndent, verticalIndent];
  7361. }
  7362. /**
  7363. * Returns an array of the video dimensions, so that it covers the screen.
  7364. * It leaves no empty areas, but some parts of the video might not be visible.
  7365. *
  7366. * @return an array with 2 elements, the video width and the video height
  7367. */
  7368. function getCameraVideoSize(videoWidth,
  7369. videoHeight,
  7370. videoSpaceWidth,
  7371. videoSpaceHeight) {
  7372. if (!videoWidth)
  7373. videoWidth = currentVideoWidth;
  7374. if (!videoHeight)
  7375. videoHeight = currentVideoHeight;
  7376. var aspectRatio = videoWidth / videoHeight;
  7377. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7378. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7379. if (availableWidth / aspectRatio < videoSpaceHeight) {
  7380. availableHeight = videoSpaceHeight;
  7381. availableWidth = availableHeight * aspectRatio;
  7382. }
  7383. if (availableHeight * aspectRatio < videoSpaceWidth) {
  7384. availableWidth = videoSpaceWidth;
  7385. availableHeight = availableWidth / aspectRatio;
  7386. }
  7387. return [availableWidth, availableHeight];
  7388. }
  7389. /**
  7390. * Updates the src of the active speaker avatar
  7391. * @param jid of the current active speaker
  7392. */
  7393. function updateActiveSpeakerAvatarSrc() {
  7394. var avatar = $("#activeSpeakerAvatar")[0];
  7395. var jid = currentSmallVideo.peerJid;
  7396. var url = Avatar.getActiveSpeakerUrl(jid);
  7397. if (avatar.src === url)
  7398. return;
  7399. if (jid) {
  7400. avatar.src = url;
  7401. currentSmallVideo.showAvatar();
  7402. }
  7403. }
  7404. /**
  7405. * Change the video source of the large video.
  7406. * @param isVisible
  7407. */
  7408. function changeVideo(isVisible) {
  7409. if (!currentSmallVideo) {
  7410. console.error("Unable to change large video - no 'currentSmallVideo'");
  7411. return;
  7412. }
  7413. updateActiveSpeakerAvatarSrc();
  7414. APP.RTC.setVideoSrc($('#largeVideo')[0], currentSmallVideo.getSrc());
  7415. var videoTransform = document.getElementById('largeVideo')
  7416. .style.webkitTransform;
  7417. var flipX = currentSmallVideo.flipX;
  7418. if (flipX && videoTransform !== 'scaleX(-1)') {
  7419. document.getElementById('largeVideo').style.webkitTransform =
  7420. "scaleX(-1)";
  7421. } else if (!flipX && videoTransform === 'scaleX(-1)') {
  7422. document.getElementById('largeVideo').style.webkitTransform =
  7423. "none";
  7424. }
  7425. var isDesktop = currentSmallVideo.getVideoType() === 'screen';
  7426. // Change the way we'll be measuring and positioning large video
  7427. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7428. getVideoPosition = isDesktop ? getDesktopVideoPosition :
  7429. getCameraVideoPosition;
  7430. // Only if the large video is currently visible.
  7431. if (isVisible) {
  7432. LargeVideo.VideoLayout.largeVideoUpdated(currentSmallVideo);
  7433. $('#largeVideo').fadeIn(300);
  7434. }
  7435. }
  7436. /**
  7437. * Creates the html elements for the large video.
  7438. */
  7439. function createLargeVideoHTML()
  7440. {
  7441. var html = '<div id="largeVideoContainer" class="videocontainer">';
  7442. html += '<div id="presentation"></div>' +
  7443. '<div id="etherpad"></div>' +
  7444. '<a target="_new"><div class="watermark leftwatermark"></div></a>' +
  7445. '<a target="_new"><div class="watermark rightwatermark"></div></a>' +
  7446. '<a class="poweredby" href="http://jitsi.org" target="_new" >' +
  7447. '<span data-i18n="poweredby"></span> jitsi.org' +
  7448. '</a>'+
  7449. '<div id="activeSpeaker">' +
  7450. '<img id="activeSpeakerAvatar" src=""/>' +
  7451. '<canvas id="activeSpeakerAudioLevel"></canvas>' +
  7452. '</div>' +
  7453. '<video id="largeVideo" autoplay oncontextmenu="return false;"></video>' +
  7454. '<span id="videoConnectionMessage"></span>';
  7455. html += '</div>';
  7456. $(html).prependTo("#videospace");
  7457. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7458. var leftWatermarkDiv
  7459. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  7460. leftWatermarkDiv.css({display: 'block'});
  7461. leftWatermarkDiv.parent().get(0).href
  7462. = interfaceConfig.JITSI_WATERMARK_LINK;
  7463. }
  7464. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7465. var rightWatermarkDiv
  7466. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  7467. rightWatermarkDiv.css({display: 'block'});
  7468. rightWatermarkDiv.parent().get(0).href
  7469. = interfaceConfig.BRAND_WATERMARK_LINK;
  7470. rightWatermarkDiv.get(0).style.backgroundImage
  7471. = "url(images/rightwatermark.png)";
  7472. }
  7473. if (interfaceConfig.SHOW_POWERED_BY) {
  7474. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  7475. }
  7476. if (!RTCBrowserType.isIExplorer()) {
  7477. $('#largeVideo').volume = 0;
  7478. }
  7479. }
  7480. var LargeVideo = {
  7481. init: function (VideoLayout, emitter) {
  7482. if(!isEnabled)
  7483. return;
  7484. createLargeVideoHTML();
  7485. this.VideoLayout = VideoLayout;
  7486. this.eventEmitter = emitter;
  7487. this.eventEmitter.emit(UIEvents.LARGEVIDEO_INIT);
  7488. var self = this;
  7489. // Listen for large video size updates
  7490. var largeVideo = $('#largeVideo')[0];
  7491. var onplaying = function (arg1, arg2, arg3) {
  7492. // re-select
  7493. if (RTCBrowserType.isTemasysPluginUsed())
  7494. largeVideo = $('#largeVideo')[0];
  7495. currentVideoWidth = largeVideo.videoWidth;
  7496. currentVideoHeight = largeVideo.videoHeight;
  7497. self.position(currentVideoWidth, currentVideoHeight);
  7498. };
  7499. largeVideo.onplaying = onplaying;
  7500. },
  7501. /**
  7502. * Indicates if the large video is currently visible.
  7503. *
  7504. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  7505. */
  7506. isLargeVideoVisible: function() {
  7507. return $('#largeVideo').is(':visible');
  7508. },
  7509. /**
  7510. * Returns <tt>true</tt> if the user is currently displayed on large video.
  7511. */
  7512. isCurrentlyOnLarge: function (resourceJid) {
  7513. return currentSmallVideo && resourceJid &&
  7514. currentSmallVideo.getResourceJid() === resourceJid;
  7515. },
  7516. /**
  7517. * Updates the large video with the given new video source.
  7518. */
  7519. updateLargeVideo: function (resourceJid, forceUpdate) {
  7520. if(!isEnabled)
  7521. return;
  7522. var newSmallVideo = this.VideoLayout.getSmallVideo(resourceJid);
  7523. console.log('hover in ' + resourceJid + ', video: ', newSmallVideo);
  7524. if (!LargeVideo.isCurrentlyOnLarge(resourceJid) || forceUpdate) {
  7525. $('#activeSpeaker').css('visibility', 'hidden');
  7526. var oldSmallVideo = null;
  7527. if (currentSmallVideo) {
  7528. oldSmallVideo = currentSmallVideo;
  7529. }
  7530. currentSmallVideo = newSmallVideo;
  7531. var oldJid = null;
  7532. if (oldSmallVideo)
  7533. oldJid = oldSmallVideo.peerJid;
  7534. if (oldJid !== resourceJid) {
  7535. // we want the notification to trigger even if userJid is undefined,
  7536. // or null.
  7537. this.eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, resourceJid);
  7538. }
  7539. if (RTCBrowserType.isSafari()) {
  7540. // FIXME In Safari fadeOut works only for the first time
  7541. changeVideo(this.isLargeVideoVisible());
  7542. } else {
  7543. $('#largeVideo').fadeOut(300,
  7544. changeVideo.bind($('#largeVideo'), this.isLargeVideoVisible()));
  7545. }
  7546. } else {
  7547. if (currentSmallVideo) {
  7548. currentSmallVideo.showAvatar();
  7549. }
  7550. }
  7551. },
  7552. /**
  7553. * Shows/hides the large video.
  7554. */
  7555. setLargeVideoVisible: function(isVisible) {
  7556. if(!isEnabled)
  7557. return;
  7558. if (isVisible) {
  7559. $('#largeVideo').css({visibility: 'visible'});
  7560. $('.watermark').css({visibility: 'visible'});
  7561. if(currentSmallVideo)
  7562. currentSmallVideo.enableDominantSpeaker(true);
  7563. }
  7564. else {
  7565. $('#largeVideo').css({visibility: 'hidden'});
  7566. $('#activeSpeaker').css('visibility', 'hidden');
  7567. $('.watermark').css({visibility: 'hidden'});
  7568. if(currentSmallVideo)
  7569. currentSmallVideo.enableDominantSpeaker(false);
  7570. }
  7571. },
  7572. onVideoTypeChanged: function (resourceJid, newVideoType) {
  7573. if (!isEnabled)
  7574. return;
  7575. if (LargeVideo.isCurrentlyOnLarge(resourceJid))
  7576. {
  7577. var isDesktop = newVideoType === 'screen';
  7578. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7579. getVideoPosition = isDesktop ? getDesktopVideoPosition
  7580. : getCameraVideoPosition;
  7581. this.position(null, null);
  7582. }
  7583. },
  7584. /**
  7585. * Positions the large video.
  7586. *
  7587. * @param videoWidth the stream video width
  7588. * @param videoHeight the stream video height
  7589. */
  7590. position: function (videoWidth, videoHeight,
  7591. videoSpaceWidth, videoSpaceHeight, animate) {
  7592. if(!isEnabled)
  7593. return;
  7594. if(!videoSpaceWidth)
  7595. videoSpaceWidth = $('#videospace').width();
  7596. if(!videoSpaceHeight)
  7597. videoSpaceHeight = window.innerHeight;
  7598. var videoSize = getVideoSize(videoWidth,
  7599. videoHeight,
  7600. videoSpaceWidth,
  7601. videoSpaceHeight);
  7602. var largeVideoWidth = videoSize[0];
  7603. var largeVideoHeight = videoSize[1];
  7604. var videoPosition = getVideoPosition(largeVideoWidth,
  7605. largeVideoHeight,
  7606. videoSpaceWidth,
  7607. videoSpaceHeight);
  7608. var horizontalIndent = videoPosition[0];
  7609. var verticalIndent = videoPosition[1];
  7610. positionVideo($('#largeVideo'),
  7611. largeVideoWidth,
  7612. largeVideoHeight,
  7613. horizontalIndent, verticalIndent, animate);
  7614. },
  7615. /**
  7616. * Resizes the large html elements.
  7617. * @param animate boolean property that indicates whether the resize should be animated or not.
  7618. * @param isChatVisible boolean property that indicates whether the chat area is displayed or not.
  7619. * If that parameter is null the method will check the chat pannel visibility.
  7620. * @param completeFunction a function to be called when the video space is resized
  7621. * @returns {*[]} array with the current width and height values of the largeVideo html element.
  7622. */
  7623. resize: function (animate, isVisible, completeFunction) {
  7624. if(!isEnabled)
  7625. return;
  7626. var availableHeight = window.innerHeight;
  7627. var availableWidth = UIUtil.getAvailableVideoWidth(isVisible);
  7628. if (availableWidth < 0 || availableHeight < 0) return;
  7629. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7630. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7631. $('#activeSpeaker').css('top', top);
  7632. this.VideoLayout.resizeVideoSpace(animate, isVisible, completeFunction);
  7633. if(animate) {
  7634. $('#largeVideoContainer').animate({
  7635. width: availableWidth,
  7636. height: availableHeight
  7637. },
  7638. {
  7639. queue: false,
  7640. duration: 500
  7641. });
  7642. } else {
  7643. $('#largeVideoContainer').width(availableWidth);
  7644. $('#largeVideoContainer').height(availableHeight);
  7645. }
  7646. return [availableWidth, availableHeight];
  7647. },
  7648. resizeVideoAreaAnimated: function (isVisible, completeFunction) {
  7649. if(!isEnabled)
  7650. return;
  7651. var size = this.resize(true, isVisible, completeFunction);
  7652. this.position(null, null, size[0], size[1], true);
  7653. },
  7654. getResourceJid: function () {
  7655. return currentSmallVideo ? currentSmallVideo.getResourceJid() : null;
  7656. },
  7657. updateAvatar: function (resourceJid) {
  7658. if(!isEnabled)
  7659. return;
  7660. if (resourceJid === this.getResourceJid()) {
  7661. updateActiveSpeakerAvatarSrc();
  7662. }
  7663. },
  7664. showAvatar: function (resourceJid, show) {
  7665. if(!isEnabled)
  7666. return;
  7667. if(this.getResourceJid() === resourceJid && state === "video") {
  7668. $("#largeVideo").css("visibility", show ? "hidden" : "visible");
  7669. $('#activeSpeaker').css("visibility", show ? "visible" : "hidden");
  7670. return true;
  7671. }
  7672. return false;
  7673. },
  7674. /**
  7675. * Disables the large video
  7676. */
  7677. disable: function () {
  7678. isEnabled = false;
  7679. },
  7680. /**
  7681. * Enables the large video
  7682. */
  7683. enable: function () {
  7684. isEnabled = true;
  7685. },
  7686. /**
  7687. * Returns true if the video is enabled.
  7688. */
  7689. isEnabled: function () {
  7690. return isEnabled;
  7691. },
  7692. /**
  7693. * Creates the iframe used by the etherpad
  7694. * @param src the value for src attribute
  7695. * @param onloadHandler handler executed when the iframe loads it content
  7696. * @returns {HTMLElement} the iframe
  7697. */
  7698. createEtherpadIframe: function (src, onloadHandler) {
  7699. if(!isEnabled)
  7700. return;
  7701. var etherpadIFrame = document.createElement('iframe');
  7702. etherpadIFrame.src = src;
  7703. etherpadIFrame.frameBorder = 0;
  7704. etherpadIFrame.scrolling = "no";
  7705. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  7706. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  7707. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  7708. document.getElementById('etherpad').appendChild(etherpadIFrame);
  7709. etherpadIFrame.onload = onloadHandler;
  7710. return etherpadIFrame;
  7711. },
  7712. /**
  7713. * Changes the state of the large video.
  7714. * Possible values - video, prezi, etherpad.
  7715. * @param newState - the new state
  7716. */
  7717. setState: function (newState) {
  7718. if(state === newState)
  7719. return;
  7720. var currentContainer = getContainerByState(state);
  7721. if(!currentContainer)
  7722. return;
  7723. var self = this;
  7724. var oldState = state;
  7725. switch (newState)
  7726. {
  7727. case "etherpad":
  7728. $('#activeSpeaker').css('visibility', 'hidden');
  7729. currentContainer.fadeOut(300, function () {
  7730. if (oldState === "prezi") {
  7731. currentContainer.css({opacity: '0'});
  7732. $('#reloadPresentation').css({display: 'none'});
  7733. }
  7734. else {
  7735. self.setLargeVideoVisible(false);
  7736. }
  7737. });
  7738. $('#etherpad>iframe').fadeIn(300, function () {
  7739. document.body.style.background = '#eeeeee';
  7740. $('#etherpad>iframe').css({visibility: 'visible'});
  7741. $('#etherpad').css({zIndex: 2});
  7742. });
  7743. break;
  7744. case "prezi":
  7745. var prezi = $('#presentation>iframe');
  7746. currentContainer.fadeOut(300, function() {
  7747. document.body.style.background = 'black';
  7748. });
  7749. prezi.fadeIn(300, function() {
  7750. prezi.css({opacity:'1'});
  7751. ToolbarToggler.dockToolbar(true);//fix that
  7752. self.setLargeVideoVisible(false);
  7753. $('#etherpad>iframe').css({visibility: 'hidden'});
  7754. $('#etherpad').css({zIndex: 0});
  7755. });
  7756. $('#activeSpeaker').css('visibility', 'hidden');
  7757. break;
  7758. case "video":
  7759. currentContainer.fadeOut(300, function () {
  7760. $('#presentation>iframe').css({opacity:'0'});
  7761. $('#reloadPresentation').css({display:'none'});
  7762. $('#etherpad>iframe').css({visibility: 'hidden'});
  7763. $('#etherpad').css({zIndex: 0});
  7764. document.body.style.background = 'black';
  7765. ToolbarToggler.dockToolbar(false);//fix that
  7766. });
  7767. $('#largeVideo').fadeIn(300, function () {
  7768. self.setLargeVideoVisible(true);
  7769. });
  7770. break;
  7771. }
  7772. state = newState;
  7773. },
  7774. /**
  7775. * Returns the current state of the large video.
  7776. * @returns {string} the current state - video, prezi or etherpad.
  7777. */
  7778. getState: function () {
  7779. return state;
  7780. },
  7781. /**
  7782. * Sets hover handlers for the large video container div.
  7783. *
  7784. * @param inHandler
  7785. * @param outHandler
  7786. */
  7787. setHover: function(inHandler, outHandler)
  7788. {
  7789. $('#largeVideoContainer').hover(inHandler, outHandler);
  7790. },
  7791. /**
  7792. * Enables/disables the filter indicating a video problem to the user.
  7793. *
  7794. * @param enable <tt>true</tt> to enable, <tt>false</tt> to disable
  7795. */
  7796. enableVideoProblemFilter: function (enable) {
  7797. $("#largeVideo").toggleClass("videoProblemFilter", enable);
  7798. }
  7799. };
  7800. module.exports = LargeVideo;
  7801. },{"../../../service/UI/UIEvents":155,"../../RTC/RTCBrowserType":8,"../../xmpp/xmpp":68,"../avatar/Avatar":16,"../toolbars/ToolbarToggler":29,"../util/UIUtil":33}],36:[function(require,module,exports){
  7802. /* global $, interfaceConfig, APP */
  7803. var SmallVideo = require("./SmallVideo");
  7804. var ConnectionIndicator = require("./ConnectionIndicator");
  7805. var NicknameHandler = require("../util/NicknameHandler");
  7806. var UIUtil = require("../util/UIUtil");
  7807. var LargeVideo = require("./LargeVideo");
  7808. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7809. function LocalVideo(VideoLayout) {
  7810. this.videoSpanId = "localVideoContainer";
  7811. this.container = $("#localVideoContainer").get(0);
  7812. this.VideoLayout = VideoLayout;
  7813. this.flipX = true;
  7814. this.isLocal = true;
  7815. this.peerJid = null;
  7816. }
  7817. LocalVideo.prototype = Object.create(SmallVideo.prototype);
  7818. LocalVideo.prototype.constructor = LocalVideo;
  7819. /**
  7820. * Creates the edit display name button.
  7821. *
  7822. * @returns {object} the edit button
  7823. */
  7824. function createEditDisplayNameButton() {
  7825. var editButton = document.createElement('a');
  7826. editButton.className = 'displayname';
  7827. UIUtil.setTooltip(editButton,
  7828. "videothumbnail.editnickname",
  7829. "top");
  7830. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  7831. return editButton;
  7832. }
  7833. /**
  7834. * Sets the display name for the given video span id.
  7835. */
  7836. LocalVideo.prototype.setDisplayName = function(displayName, key) {
  7837. if (!this.container) {
  7838. console.warn(
  7839. "Unable to set displayName - " + this.videoSpanId +
  7840. " does not exist");
  7841. return;
  7842. }
  7843. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  7844. var defaultLocalDisplayName = APP.translation.generateTranslationHTML(
  7845. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7846. var meHTML;
  7847. // If we already have a display name for this video.
  7848. if (nameSpan.length > 0) {
  7849. if (nameSpan.text() !== displayName) {
  7850. if (displayName && displayName.length > 0) {
  7851. meHTML = APP.translation.generateTranslationHTML("me");
  7852. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  7853. } else {
  7854. $('#localDisplayName').html(defaultLocalDisplayName);
  7855. }
  7856. }
  7857. } else {
  7858. var editButton = createEditDisplayNameButton();
  7859. nameSpan = document.createElement('span');
  7860. nameSpan.className = 'displayname';
  7861. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  7862. if (displayName && displayName.length > 0) {
  7863. meHTML = APP.translation.generateTranslationHTML("me");
  7864. nameSpan.innerHTML = displayName + meHTML;
  7865. }
  7866. else {
  7867. nameSpan.innerHTML = defaultLocalDisplayName;
  7868. }
  7869. nameSpan.id = 'localDisplayName';
  7870. this.container.appendChild(editButton);
  7871. //translates popover of edit button
  7872. APP.translation.translateElement($("a.displayname"));
  7873. var editableText = document.createElement('input');
  7874. editableText.className = 'displayname';
  7875. editableText.type = 'text';
  7876. editableText.id = 'editDisplayName';
  7877. if (displayName && displayName.length) {
  7878. editableText.value = displayName;
  7879. }
  7880. var defaultNickname = APP.translation.translateString(
  7881. "defaultNickname", {name: "Jane Pink"});
  7882. editableText.setAttribute('style', 'display:none;');
  7883. editableText.setAttribute('data-18n',
  7884. '[placeholder]defaultNickname');
  7885. editableText.setAttribute("data-i18n-options",
  7886. JSON.stringify({name: "Jane Pink"}));
  7887. editableText.setAttribute("placeholder", defaultNickname);
  7888. this.container.appendChild(editableText);
  7889. var self = this;
  7890. $('#localVideoContainer .displayname')
  7891. .bind("click", function (e) {
  7892. var editDisplayName = $('#editDisplayName');
  7893. e.preventDefault();
  7894. e.stopPropagation();
  7895. $('#localDisplayName').hide();
  7896. editDisplayName.show();
  7897. editDisplayName.focus();
  7898. editDisplayName.select();
  7899. editDisplayName.one("focusout", function (e) {
  7900. self.VideoLayout.inputDisplayNameHandler(this.value);
  7901. });
  7902. editDisplayName.on('keydown', function (e) {
  7903. if (e.keyCode === 13) {
  7904. e.preventDefault();
  7905. self.VideoLayout.inputDisplayNameHandler(this.value);
  7906. }
  7907. });
  7908. });
  7909. }
  7910. };
  7911. LocalVideo.prototype.inputDisplayNameHandler = function (name) {
  7912. NicknameHandler.setNickname(name);
  7913. var localDisplayName = $('#localDisplayName');
  7914. if (!localDisplayName.is(":visible")) {
  7915. if (NicknameHandler.getNickname()) {
  7916. var meHTML = APP.translation.generateTranslationHTML("me");
  7917. localDisplayName.html(NicknameHandler.getNickname() + " (" +
  7918. meHTML + ")");
  7919. } else {
  7920. var defaultHTML = APP.translation.generateTranslationHTML(
  7921. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7922. localDisplayName .html(defaultHTML);
  7923. }
  7924. localDisplayName.show();
  7925. }
  7926. $('#editDisplayName').hide();
  7927. };
  7928. LocalVideo.prototype.createConnectionIndicator = function() {
  7929. if(this.connectionIndicator)
  7930. return;
  7931. this.connectionIndicator = new ConnectionIndicator(this, null);
  7932. };
  7933. LocalVideo.prototype.changeVideo = function (stream, isMuted) {
  7934. var self = this;
  7935. function localVideoClick(event) {
  7936. // FIXME: with Temasys plugin event arg is not an event, but
  7937. // the clicked object itself, so we have to skip this call
  7938. if (event.stopPropagation) {
  7939. event.stopPropagation();
  7940. }
  7941. self.VideoLayout.handleVideoThumbClicked(
  7942. false,
  7943. APP.xmpp.myResource());
  7944. }
  7945. var localVideoContainerSelector = $('#localVideoContainer');
  7946. localVideoContainerSelector.off('click');
  7947. localVideoContainerSelector.on('click', localVideoClick);
  7948. // Add hover handler
  7949. localVideoContainerSelector.hover(
  7950. function() {
  7951. self.showDisplayName(true);
  7952. },
  7953. function() {
  7954. if (!LargeVideo.isLargeVideoVisible() ||
  7955. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid())) {
  7956. self.showDisplayName(false);
  7957. }
  7958. }
  7959. );
  7960. if(isMuted) {
  7961. APP.UI.setVideoMute(true);
  7962. return;
  7963. }
  7964. this.flipX = stream.videoType != "screen";
  7965. var localVideo = document.createElement('video');
  7966. localVideo.id = 'localVideo_' +
  7967. APP.RTC.getStreamID(stream.getOriginalStream());
  7968. if (!RTCBrowserType.isIExplorer()) {
  7969. localVideo.autoplay = true;
  7970. localVideo.volume = 0; // is it required if audio is separated ?
  7971. }
  7972. localVideo.oncontextmenu = function () { return false; };
  7973. var localVideoContainer = document.getElementById('localVideoWrapper');
  7974. // Put the new video always in front
  7975. UIUtil.prependChild(localVideoContainer, localVideo);
  7976. var localVideoSelector = $('#' + localVideo.id);
  7977. // Add click handler to both video and video wrapper elements in case
  7978. // there's no video.
  7979. // onclick has to be used with Temasys plugin
  7980. localVideo.onclick = localVideoClick;
  7981. if (this.flipX) {
  7982. localVideoSelector.addClass("flipVideoX");
  7983. }
  7984. // Attach WebRTC stream
  7985. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  7986. // Add stream ended handler
  7987. stream.getOriginalStream().onended = function () {
  7988. // We have to re-select after attach when Temasys plugin is used,
  7989. // because <video> element is replaced with <object>
  7990. localVideo = $('#' + localVideo.id)[0];
  7991. localVideoContainer.removeChild(localVideo);
  7992. self.VideoLayout.updateRemovedVideo(APP.xmpp.myResource());
  7993. };
  7994. };
  7995. LocalVideo.prototype.joined = function (jid) {
  7996. this.peerJid = jid;
  7997. };
  7998. LocalVideo.prototype.getResourceJid = function () {
  7999. var myResource = APP.xmpp.myResource();
  8000. if (!myResource) {
  8001. console.error("Requested local resource before we're in the MUC");
  8002. }
  8003. return myResource;
  8004. };
  8005. module.exports = LocalVideo;
  8006. },{"../../RTC/RTCBrowserType":8,"../util/NicknameHandler":32,"../util/UIUtil":33,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],37:[function(require,module,exports){
  8007. /* global $, APP, require, Strophe, interfaceConfig */
  8008. var ConnectionIndicator = require("./ConnectionIndicator");
  8009. var SmallVideo = require("./SmallVideo");
  8010. var AudioLevels = require("../audio_levels/AudioLevels");
  8011. var LargeVideo = require("./LargeVideo");
  8012. var Avatar = require("../avatar/Avatar");
  8013. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8014. var UIUtils = require("../util/UIUtil");
  8015. function RemoteVideo(peerJid, VideoLayout) {
  8016. this.peerJid = peerJid;
  8017. this.resourceJid = Strophe.getResourceFromJid(peerJid);
  8018. this.videoSpanId = 'participant_' + this.resourceJid;
  8019. this.VideoLayout = VideoLayout;
  8020. this.addRemoteVideoContainer();
  8021. this.connectionIndicator = new ConnectionIndicator(
  8022. this, this.peerJid);
  8023. this.setDisplayName();
  8024. var nickfield = document.createElement('span');
  8025. nickfield.className = "nick";
  8026. nickfield.appendChild(document.createTextNode(this.resourceJid));
  8027. this.container.appendChild(nickfield);
  8028. this.flipX = false;
  8029. this.isLocal = false;
  8030. }
  8031. RemoteVideo.prototype = Object.create(SmallVideo.prototype);
  8032. RemoteVideo.prototype.constructor = RemoteVideo;
  8033. RemoteVideo.prototype.addRemoteVideoContainer = function() {
  8034. this.container = RemoteVideo.createContainer(this.videoSpanId);
  8035. if (APP.xmpp.isModerator())
  8036. this.addRemoteVideoMenu();
  8037. AudioLevels.updateAudioLevelCanvas(this.peerJid, this.VideoLayout);
  8038. return this.container;
  8039. };
  8040. /**
  8041. * Adds the remote video menu element for the given <tt>jid</tt> in the
  8042. * given <tt>parentElement</tt>.
  8043. *
  8044. * @param jid the jid indicating the video for which we're adding a menu.
  8045. * @param parentElement the parent element where this menu will be added
  8046. */
  8047. if (!interfaceConfig.filmStripOnly) {
  8048. RemoteVideo.prototype.addRemoteVideoMenu = function () {
  8049. var spanElement = document.createElement('span');
  8050. spanElement.className = 'remotevideomenu';
  8051. this.container.appendChild(spanElement);
  8052. var menuElement = document.createElement('i');
  8053. menuElement.className = 'fa fa-angle-down';
  8054. menuElement.title = 'Remote user controls';
  8055. spanElement.appendChild(menuElement);
  8056. var popupmenuElement = document.createElement('ul');
  8057. popupmenuElement.className = 'popupmenu';
  8058. popupmenuElement.id = 'remote_popupmenu_' + this.getResourceJid();
  8059. spanElement.appendChild(popupmenuElement);
  8060. var muteMenuItem = document.createElement('li');
  8061. var muteLinkItem = document.createElement('a');
  8062. var mutedIndicator = "<i style='float:left;' " +
  8063. "class='icon-mic-disabled'></i>";
  8064. if (!this.isMuted) {
  8065. muteLinkItem.innerHTML = mutedIndicator +
  8066. " <div style='width: 90px;margin-left: 20px;' " +
  8067. "data-i18n='videothumbnail.domute'></div>";
  8068. muteLinkItem.className = 'mutelink';
  8069. }
  8070. else {
  8071. muteLinkItem.innerHTML = mutedIndicator +
  8072. " <div style='width: 90px;margin-left: 20px;' " +
  8073. "data-i18n='videothumbnail.muted'></div>";
  8074. muteLinkItem.className = 'mutelink disabled';
  8075. }
  8076. var self = this;
  8077. muteLinkItem.onclick = function(){
  8078. if ($(this).attr('disabled') != undefined) {
  8079. event.preventDefault();
  8080. }
  8081. var isMute = self.isMuted == true;
  8082. APP.xmpp.setMute(self.peerJid, !isMute);
  8083. popupmenuElement.setAttribute('style', 'display:none;');
  8084. if (isMute) {
  8085. this.innerHTML = mutedIndicator +
  8086. " <div style='width: 90px;margin-left: 20px;' " +
  8087. "data-i18n='videothumbnail.muted'></div>";
  8088. this.className = 'mutelink disabled';
  8089. }
  8090. else {
  8091. this.innerHTML = mutedIndicator +
  8092. " <div style='width: 90px;margin-left: 20px;' " +
  8093. "data-i18n='videothumbnail.domute'></div>";
  8094. this.className = 'mutelink';
  8095. }
  8096. };
  8097. muteMenuItem.appendChild(muteLinkItem);
  8098. popupmenuElement.appendChild(muteMenuItem);
  8099. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  8100. var ejectMenuItem = document.createElement('li');
  8101. var ejectLinkItem = document.createElement('a');
  8102. var ejectText = "<div style='width: 90px;margin-left: 20px;' " +
  8103. "data-i18n='videothumbnail.kick'>&nbsp;</div>";
  8104. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  8105. ejectLinkItem.onclick = function(){
  8106. APP.xmpp.eject(self.peerJid);
  8107. popupmenuElement.setAttribute('style', 'display:none;');
  8108. };
  8109. ejectMenuItem.appendChild(ejectLinkItem);
  8110. popupmenuElement.appendChild(ejectMenuItem);
  8111. var paddingSpan = document.createElement('span');
  8112. paddingSpan.className = 'popupmenuPadding';
  8113. popupmenuElement.appendChild(paddingSpan);
  8114. APP.translation.translateElement(
  8115. $("#" + popupmenuElement.id + " > li > a > div"));
  8116. };
  8117. } else {
  8118. RemoteVideo.prototype.addRemoteVideoMenu = function() {}
  8119. }
  8120. /**
  8121. * Removes the remote stream element corresponding to the given stream and
  8122. * parent container.
  8123. *
  8124. * @param stream the stream
  8125. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  8126. */
  8127. RemoteVideo.prototype.removeRemoteStreamElement =
  8128. function (stream, isVideo, id) {
  8129. if (!this.container)
  8130. return false;
  8131. var select = null;
  8132. if (isVideo) {
  8133. select = $('#' + id);
  8134. }
  8135. else
  8136. select = $('#' + this.videoSpanId + '>audio');
  8137. select.remove();
  8138. console.info((isVideo ? "Video" : "Audio") +
  8139. " removed " + this.getResourceJid(), select);
  8140. if (isVideo)
  8141. this.VideoLayout.updateRemovedVideo(this.getResourceJid());
  8142. };
  8143. /**
  8144. * Removes RemoteVideo from the page.
  8145. */
  8146. RemoteVideo.prototype.remove = function () {
  8147. console.log("Remove thumbnail", this.peerJid);
  8148. this.removeConnectionIndicator();
  8149. // Remove whole container
  8150. if (this.container.parentNode)
  8151. this.container.parentNode.removeChild(this.container);
  8152. };
  8153. RemoteVideo.prototype.waitForPlayback = function (sel, stream) {
  8154. var isVideo = stream.getVideoTracks().length > 0;
  8155. if (!isVideo || stream.id === 'mixedmslabel') {
  8156. return;
  8157. }
  8158. var self = this;
  8159. var resourceJid = this.getResourceJid();
  8160. // Register 'onplaying' listener to trigger 'videoactive' on VideoLayout
  8161. // when video playback starts
  8162. var onPlayingHandler = function () {
  8163. // FIXME: why do i have to do this for FF?
  8164. if (RTCBrowserType.isFirefox()) {
  8165. APP.RTC.attachMediaStream(sel, stream);
  8166. }
  8167. if (RTCBrowserType.isTemasysPluginUsed()) {
  8168. sel = self.VideoLayout.getPeerVideoSel(resourceJid);
  8169. }
  8170. self.VideoLayout.videoactive(sel, resourceJid);
  8171. sel[0].onplaying = null;
  8172. if (RTCBrowserType.isTemasysPluginUsed()) {
  8173. // 'currentTime' is used to check if the video has started
  8174. // and the value is not set by the plugin, so we do it
  8175. sel[0].currentTime = 1;
  8176. }
  8177. };
  8178. sel[0].onplaying = onPlayingHandler;
  8179. };
  8180. RemoteVideo.prototype.addRemoteStreamElement = function (sid, stream, thessrc) {
  8181. if (!this.container)
  8182. return;
  8183. var self = this;
  8184. var isVideo = stream.getVideoTracks().length > 0;
  8185. var streamElement = SmallVideo.createStreamElement(sid, stream);
  8186. var newElementId = streamElement.id;
  8187. // Put new stream element always in front
  8188. UIUtils.prependChild(this.container, streamElement);
  8189. var sel = $('#' + newElementId);
  8190. sel.hide();
  8191. // If the container is currently visible we attach the stream.
  8192. if (!isVideo || (this.container.offsetParent !== null && isVideo)) {
  8193. this.waitForPlayback(sel, stream);
  8194. APP.RTC.attachMediaStream(sel, stream);
  8195. }
  8196. stream.onended = function () {
  8197. console.log('stream ended', this);
  8198. self.removeRemoteStreamElement(stream, isVideo, newElementId);
  8199. };
  8200. // Name of video element name is different for IE/Safari
  8201. var videoElem = APP.RTC.getVideoElementName();
  8202. // Add click handler.
  8203. var onClickHandler = function (event) {
  8204. self.VideoLayout.handleVideoThumbClicked(false, self.getResourceJid());
  8205. // On IE we need to populate this handler on video <object>
  8206. // and it does not give event instance as an argument,
  8207. // so we check here for methods.
  8208. if (event.stopPropagation && event.preventDefault) {
  8209. event.stopPropagation();
  8210. event.preventDefault();
  8211. }
  8212. return false;
  8213. };
  8214. this.container.onclick = onClickHandler;
  8215. // reselect
  8216. if (RTCBrowserType.isTemasysPluginUsed())
  8217. sel = $('#' + newElementId);
  8218. sel[0].onclick = onClickHandler;
  8219. //FIXME
  8220. // Add hover handler
  8221. $(this.container).hover(
  8222. function() {
  8223. self.showDisplayName(true);
  8224. },
  8225. function() {
  8226. // If the video has been "pinned" by the user we want to
  8227. // keep the display name on place.
  8228. if (!LargeVideo.isLargeVideoVisible() ||
  8229. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid()))
  8230. self.showDisplayName(false);
  8231. }
  8232. );
  8233. },
  8234. /**
  8235. * Show/hide peer container for the given resourceJid.
  8236. */
  8237. RemoteVideo.prototype.showPeerContainer = function (state) {
  8238. if (!this.container)
  8239. return;
  8240. var isHide = state === 'hide';
  8241. var resizeThumbnails = false;
  8242. if (!isHide) {
  8243. if (!$(this.container).is(':visible')) {
  8244. resizeThumbnails = true;
  8245. $(this.container).show();
  8246. }
  8247. this.showAvatar(state !== 'show');
  8248. }
  8249. else if ($(this.container).is(':visible') && isHide)
  8250. {
  8251. resizeThumbnails = true;
  8252. $(this.container).hide();
  8253. if(this.connectionIndicator)
  8254. this.connectionIndicator.hide();
  8255. }
  8256. if (resizeThumbnails) {
  8257. this.VideoLayout.resizeThumbnails();
  8258. }
  8259. // We want to be able to pin a participant from the contact list, even
  8260. // if he's not in the lastN set!
  8261. // ContactList.setClickable(resourceJid, !isHide);
  8262. };
  8263. RemoteVideo.prototype.removeConnectionIndicator = function () {
  8264. if (this.connectionIndicator)
  8265. this.connectionIndicator.remove();
  8266. };
  8267. RemoteVideo.prototype.hideConnectionIndicator = function () {
  8268. if (this.connectionIndicator)
  8269. this.connectionIndicator.hide();
  8270. };
  8271. /**
  8272. * Updates the remote video menu.
  8273. *
  8274. * @param jid the jid indicating the video for which we're adding a menu.
  8275. * @param isMuted indicates the current mute state
  8276. */
  8277. RemoteVideo.prototype.updateRemoteVideoMenu = function (isMuted) {
  8278. var muteMenuItem
  8279. = $('#remote_popupmenu_' + this.getResourceJid() + '>li>a.mutelink');
  8280. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  8281. if (muteMenuItem.length) {
  8282. var muteLink = muteMenuItem.get(0);
  8283. if (isMuted === 'true') {
  8284. muteLink.innerHTML = mutedIndicator + ' Muted';
  8285. muteLink.className = 'mutelink disabled';
  8286. }
  8287. else {
  8288. muteLink.innerHTML = mutedIndicator + ' Mute';
  8289. muteLink.className = 'mutelink';
  8290. }
  8291. }
  8292. };
  8293. /**
  8294. * Sets the display name for the given video span id.
  8295. */
  8296. RemoteVideo.prototype.setDisplayName = function(displayName, key) {
  8297. if (!this.container) {
  8298. console.warn( "Unable to set displayName - " + this.videoSpanId +
  8299. " does not exist");
  8300. return;
  8301. }
  8302. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8303. // If we already have a display name for this video.
  8304. if (nameSpan.length > 0) {
  8305. if (displayName && displayName.length > 0) {
  8306. $('#' + this.videoSpanId + '_name').html(displayName);
  8307. }
  8308. else if (key && key.length > 0) {
  8309. var nameHtml = APP.translation.generateTranslationHTML(key);
  8310. $('#' + this.videoSpanId + '_name').html(nameHtml);
  8311. }
  8312. else
  8313. $('#' + this.videoSpanId + '_name').text(
  8314. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  8315. } else {
  8316. nameSpan = document.createElement('span');
  8317. nameSpan.className = 'displayname';
  8318. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8319. if (displayName && displayName.length > 0) {
  8320. nameSpan.innerText = displayName;
  8321. }
  8322. else
  8323. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  8324. nameSpan.id = this.videoSpanId + '_name';
  8325. }
  8326. };
  8327. /**
  8328. * Removes remote video menu element from video element identified by
  8329. * given <tt>videoElementId</tt>.
  8330. *
  8331. * @param videoElementId the id of local or remote video element.
  8332. */
  8333. RemoteVideo.prototype.removeRemoteVideoMenu = function() {
  8334. var menuSpan = $('#' + this.videoSpanId + '>span.remotevideomenu');
  8335. if (menuSpan.length) {
  8336. menuSpan.remove();
  8337. }
  8338. };
  8339. RemoteVideo.prototype.getResourceJid = function () {
  8340. if (!this.resourceJid) {
  8341. console.error("Undefined resource jid");
  8342. }
  8343. return this.resourceJid;
  8344. };
  8345. RemoteVideo.createContainer = function (spanId) {
  8346. var container = document.createElement('span');
  8347. container.id = spanId;
  8348. container.className = 'videocontainer';
  8349. var remotes = document.getElementById('remoteVideos');
  8350. return remotes.appendChild(container);
  8351. };
  8352. module.exports = RemoteVideo;
  8353. },{"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../avatar/Avatar":16,"../util/UIUtil":33,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],38:[function(require,module,exports){
  8354. /* global $, APP, require */
  8355. var Avatar = require("../avatar/Avatar");
  8356. var UIUtil = require("../util/UIUtil");
  8357. var LargeVideo = require("./LargeVideo");
  8358. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8359. function SmallVideo() {
  8360. this.isMuted = false;
  8361. this.hasAvatar = false;
  8362. }
  8363. function setVisibility(selector, show) {
  8364. if (selector && selector.length > 0) {
  8365. selector.css("visibility", show ? "visible" : "hidden");
  8366. }
  8367. }
  8368. SmallVideo.prototype.showDisplayName = function(isShow) {
  8369. var nameSpan = $('#' + this.videoSpanId + '>span.displayname').get(0);
  8370. if (isShow) {
  8371. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  8372. nameSpan.setAttribute("style", "display:inline-block;");
  8373. }
  8374. else {
  8375. if (nameSpan)
  8376. nameSpan.setAttribute("style", "display:none;");
  8377. }
  8378. };
  8379. SmallVideo.prototype.setDeviceAvailabilityIcons = function (devices) {
  8380. if(!this.container)
  8381. return;
  8382. var noMic = $("#" + this.videoSpanId + " > .noMic");
  8383. var noVideo = $("#" + this.videoSpanId + " > .noVideo");
  8384. noMic.remove();
  8385. noVideo.remove();
  8386. if (!devices.audio) {
  8387. this.container.appendChild(
  8388. document.createElement("div")).setAttribute("class", "noMic");
  8389. }
  8390. if (!devices.video) {
  8391. this.container.appendChild(
  8392. document.createElement("div")).setAttribute("class", "noVideo");
  8393. }
  8394. if (!devices.audio && !devices.video) {
  8395. noMic.css("background-position", "75%");
  8396. noVideo.css("background-position", "25%");
  8397. noVideo.css("background-color", "transparent");
  8398. }
  8399. };
  8400. /**
  8401. * Sets the type of the video displayed by this instance.
  8402. * @param videoType 'camera' or 'screen'
  8403. */
  8404. SmallVideo.prototype.setVideoType = function (videoType) {
  8405. this.videoType = videoType;
  8406. };
  8407. /**
  8408. * Returns the type of the video displayed by this instance.
  8409. * @returns {String} 'camera', 'screen' or undefined.
  8410. */
  8411. SmallVideo.prototype.getVideoType = function () {
  8412. return this.videoType;
  8413. };
  8414. /**
  8415. * Shows the presence status message for the given video.
  8416. */
  8417. SmallVideo.prototype.setPresenceStatus = function (statusMsg) {
  8418. if (!this.container) {
  8419. // No container
  8420. return;
  8421. }
  8422. var statusSpan = $('#' + this.videoSpanId + '>span.status');
  8423. if (!statusSpan.length) {
  8424. //Add status span
  8425. statusSpan = document.createElement('span');
  8426. statusSpan.className = 'status';
  8427. statusSpan.id = this.videoSpanId + '_status';
  8428. $('#' + this.videoSpanId)[0].appendChild(statusSpan);
  8429. statusSpan = $('#' + this.videoSpanId + '>span.status');
  8430. }
  8431. // Display status
  8432. if (statusMsg && statusMsg.length) {
  8433. $('#' + this.videoSpanId + '_status').text(statusMsg);
  8434. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  8435. }
  8436. else {
  8437. // Hide
  8438. statusSpan.get(0).setAttribute("style", "display:none;");
  8439. }
  8440. };
  8441. /**
  8442. * Creates an audio or video stream element.
  8443. */
  8444. SmallVideo.createStreamElement = function (sid, stream) {
  8445. var isVideo = stream.getVideoTracks().length > 0;
  8446. var element = isVideo ? document.createElement('video')
  8447. : document.createElement('audio');
  8448. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_') + sid + '_' +
  8449. APP.RTC.getStreamID(stream);
  8450. element.id = id;
  8451. if (!RTCBrowserType.isIExplorer()) {
  8452. element.autoplay = true;
  8453. }
  8454. element.oncontextmenu = function () { return false; };
  8455. return element;
  8456. };
  8457. /**
  8458. * Updates the data for the indicator
  8459. * @param id the id of the indicator
  8460. * @param percent the percent for connection quality
  8461. * @param object the data
  8462. */
  8463. SmallVideo.prototype.updateStatsIndicator = function (percent, object) {
  8464. if(this.connectionIndicator)
  8465. this.connectionIndicator.updateConnectionQuality(percent, object);
  8466. };
  8467. SmallVideo.prototype.hideIndicator = function () {
  8468. if(this.connectionIndicator)
  8469. this.connectionIndicator.hideIndicator();
  8470. };
  8471. /**
  8472. * Shows audio muted indicator over small videos.
  8473. * @param {string} isMuted
  8474. */
  8475. SmallVideo.prototype.showAudioIndicator = function(isMuted) {
  8476. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8477. if (!isMuted) {
  8478. if (audioMutedSpan.length > 0) {
  8479. audioMutedSpan.popover('hide');
  8480. audioMutedSpan.remove();
  8481. }
  8482. }
  8483. else {
  8484. if(audioMutedSpan.length == 0 ) {
  8485. audioMutedSpan = document.createElement('span');
  8486. audioMutedSpan.className = 'audioMuted';
  8487. UIUtil.setTooltip(audioMutedSpan,
  8488. "videothumbnail.mute",
  8489. "top");
  8490. this.container.appendChild(audioMutedSpan);
  8491. APP.translation.translateElement($('#' + this.videoSpanId + " > span"));
  8492. var mutedIndicator = document.createElement('i');
  8493. mutedIndicator.className = 'icon-mic-disabled';
  8494. audioMutedSpan.appendChild(mutedIndicator);
  8495. }
  8496. this.updateIconPositions();
  8497. }
  8498. this.isMuted = isMuted;
  8499. };
  8500. /**
  8501. * Shows video muted indicator over small videos.
  8502. */
  8503. SmallVideo.prototype.showVideoIndicator = function(isMuted) {
  8504. this.showAvatar(isMuted);
  8505. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8506. if (isMuted === false) {
  8507. if (videoMutedSpan.length > 0) {
  8508. videoMutedSpan.remove();
  8509. }
  8510. }
  8511. else {
  8512. if(videoMutedSpan.length == 0) {
  8513. videoMutedSpan = document.createElement('span');
  8514. videoMutedSpan.className = 'videoMuted';
  8515. this.container.appendChild(videoMutedSpan);
  8516. var mutedIndicator = document.createElement('i');
  8517. mutedIndicator.className = 'icon-camera-disabled';
  8518. UIUtil.setTooltip(mutedIndicator,
  8519. "videothumbnail.videomute",
  8520. "top");
  8521. videoMutedSpan.appendChild(mutedIndicator);
  8522. //translate texts for muted indicator
  8523. APP.translation.translateElement($('#' + this.videoSpanId + " > span > i"));
  8524. }
  8525. this.updateIconPositions();
  8526. }
  8527. };
  8528. SmallVideo.prototype.enableDominantSpeaker = function (isEnable) {
  8529. var resourceJid = this.getResourceJid();
  8530. var displayName = resourceJid;
  8531. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8532. if (nameSpan.length > 0)
  8533. displayName = nameSpan.html();
  8534. console.log("UI enable dominant speaker",
  8535. displayName,
  8536. resourceJid,
  8537. isEnable);
  8538. if (!this.container) {
  8539. return;
  8540. }
  8541. if (isEnable) {
  8542. this.showDisplayName(LargeVideo.getState() === "video");
  8543. if (!this.container.classList.contains("dominantspeaker"))
  8544. this.container.classList.add("dominantspeaker");
  8545. }
  8546. else {
  8547. this.showDisplayName(false);
  8548. if (this.container.classList.contains("dominantspeaker"))
  8549. this.container.classList.remove("dominantspeaker");
  8550. }
  8551. this.showAvatar();
  8552. };
  8553. SmallVideo.prototype.updateIconPositions = function () {
  8554. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8555. var connectionIndicator = $('#' + this.videoSpanId + '>div.connectionindicator');
  8556. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8557. if(connectionIndicator.length > 0 &&
  8558. connectionIndicator[0].style.display != "none") {
  8559. audioMutedSpan.css({right: "23px"});
  8560. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  8561. } else {
  8562. audioMutedSpan.css({right: "0px"});
  8563. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  8564. }
  8565. };
  8566. /**
  8567. * Creates the element indicating the moderator(owner) of the conference.
  8568. *
  8569. * @param parentElement the parent element where the owner indicator will
  8570. * be added
  8571. */
  8572. SmallVideo.prototype.createModeratorIndicatorElement = function () {
  8573. // Show moderator indicator
  8574. var indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8575. if (!indicatorSpan || indicatorSpan.length === 0) {
  8576. indicatorSpan = document.createElement('span');
  8577. indicatorSpan.className = 'focusindicator';
  8578. this.container.appendChild(indicatorSpan);
  8579. indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8580. }
  8581. if (indicatorSpan.children().length !== 0)
  8582. return;
  8583. var moderatorIndicator = document.createElement('i');
  8584. moderatorIndicator.className = 'fa fa-star';
  8585. indicatorSpan[0].appendChild(moderatorIndicator);
  8586. UIUtil.setTooltip(indicatorSpan[0],
  8587. "videothumbnail.moderator",
  8588. "top");
  8589. //translates text in focus indicators
  8590. APP.translation.translateElement($('#' + this.videoSpanId + ' .focusindicator'));
  8591. };
  8592. SmallVideo.prototype.getSrc = function () {
  8593. var videoElement = APP.RTC.getVideoElementName();
  8594. return APP.RTC.getVideoSrc(
  8595. $('#' + this.videoSpanId).find(videoElement).get(0));
  8596. };
  8597. SmallVideo.prototype.focus = function(isFocused) {
  8598. if(!isFocused) {
  8599. this.container.classList.remove("videoContainerFocused");
  8600. } else {
  8601. this.container.classList.add("videoContainerFocused");
  8602. }
  8603. };
  8604. SmallVideo.prototype.hasVideo = function () {
  8605. return $("#" + this.videoSpanId).find(
  8606. APP.RTC.getVideoElementName()).length !== 0;
  8607. };
  8608. /**
  8609. * Hides or shows the user's avatar
  8610. * @param show whether we should show the avatar or not
  8611. * video because there is no dominant speaker and no focused speaker
  8612. */
  8613. SmallVideo.prototype.showAvatar = function (show) {
  8614. if (!this.hasAvatar) {
  8615. if (this.peerJid) {
  8616. // Init avatar
  8617. this.avatarChanged(Avatar.getThumbUrl(this.peerJid));
  8618. } else {
  8619. console.error("Unable to init avatar - no peerjid", this);
  8620. return;
  8621. }
  8622. }
  8623. var resourceJid = this.getResourceJid();
  8624. var videoElem = APP.RTC.getVideoElementName();
  8625. var video = $('#' + this.videoSpanId).find(videoElem);
  8626. var avatar = $('#avatar_' + resourceJid);
  8627. if (show === undefined || show === null) {
  8628. if (!this.isLocal &&
  8629. !this.VideoLayout.isInLastN(resourceJid)) {
  8630. show = true;
  8631. } else {
  8632. // We want to show the avatar when the video is muted or not exists
  8633. // that is when 'true' or 'null' is returned
  8634. show = APP.RTC.isVideoMuted(this.peerJid) !== false;
  8635. }
  8636. }
  8637. if (LargeVideo.showAvatar(resourceJid, show)) {
  8638. setVisibility(avatar, false);
  8639. setVisibility(video, false);
  8640. } else {
  8641. if (video && video.length > 0) {
  8642. setVisibility(video, !show);
  8643. }
  8644. setVisibility(avatar, show);
  8645. }
  8646. };
  8647. SmallVideo.prototype.avatarChanged = function (thumbUrl) {
  8648. var thumbnail = $('#' + this.videoSpanId);
  8649. var resourceJid = this.getResourceJid();
  8650. var avatar = $('#avatar_' + resourceJid);
  8651. this.hasAvatar = true;
  8652. // set the avatar in the thumbnail
  8653. if (avatar && avatar.length > 0) {
  8654. avatar[0].src = thumbUrl;
  8655. } else {
  8656. if (thumbnail && thumbnail.length > 0) {
  8657. avatar = document.createElement('img');
  8658. avatar.id = 'avatar_' + resourceJid;
  8659. avatar.className = 'userAvatar';
  8660. avatar.src = thumbUrl;
  8661. thumbnail.append(avatar);
  8662. }
  8663. }
  8664. };
  8665. module.exports = SmallVideo;
  8666. },{"../../RTC/RTCBrowserType":8,"../avatar/Avatar":16,"../util/UIUtil":33,"./LargeVideo":35}],39:[function(require,module,exports){
  8667. /* global config, APP, $, Strophe, require, interfaceConfig */
  8668. var AudioLevels = require("../audio_levels/AudioLevels");
  8669. var ContactList = require("../side_pannels/contactlist/ContactList");
  8670. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  8671. var UIEvents = require("../../../service/UI/UIEvents");
  8672. var UIUtil = require("../util/UIUtil");
  8673. var RTC = require("../../RTC/RTC");
  8674. var RTCBrowserType = require('../../RTC/RTCBrowserType');
  8675. var RemoteVideo = require("./RemoteVideo");
  8676. var LargeVideo = require("./LargeVideo");
  8677. var LocalVideo = require("./LocalVideo");
  8678. var remoteVideos = {};
  8679. var remoteVideoTypes = {};
  8680. var localVideoThumbnail = null;
  8681. var currentDominantSpeaker = null;
  8682. var lastNCount = config.channelLastN;
  8683. var localLastNCount = config.channelLastN;
  8684. var localLastNSet = [];
  8685. var lastNEndpointsCache = [];
  8686. var lastNPickupJid = null;
  8687. var eventEmitter = null;
  8688. /**
  8689. * Currently focused video jid
  8690. * @type {String}
  8691. */
  8692. var focusedVideoResourceJid = null;
  8693. var VideoLayout = (function (my) {
  8694. my.init = function (emitter) {
  8695. eventEmitter = emitter;
  8696. localVideoThumbnail = new LocalVideo(VideoLayout);
  8697. if (interfaceConfig.filmStripOnly) {
  8698. LargeVideo.disable();
  8699. } else {
  8700. LargeVideo.init(VideoLayout, emitter);
  8701. }
  8702. VideoLayout.resizeLargeVideoContainer();
  8703. };
  8704. my.isInLastN = function(resource) {
  8705. return lastNCount < 0 || // lastN is disabled
  8706. // lastNEndpoints cache not built yet
  8707. (lastNCount > 0 && lastNEndpointsCache.length == 0) ||
  8708. (lastNEndpointsCache &&
  8709. lastNEndpointsCache.indexOf(resource) !== -1);
  8710. };
  8711. my.changeLocalStream = function (stream, isMuted) {
  8712. VideoLayout.changeLocalVideo(stream, isMuted);
  8713. };
  8714. my.changeLocalAudio = function(stream, isMuted) {
  8715. if (isMuted)
  8716. APP.UI.setAudioMuted(true, true);
  8717. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  8718. var localAudio = document.getElementById('localAudio');
  8719. // Writing volume not allowed in IE
  8720. if (!RTCBrowserType.isIExplorer()) {
  8721. localAudio.autoplay = true;
  8722. localAudio.volume = 0;
  8723. }
  8724. };
  8725. my.changeLocalVideo = function(stream, isMuted) {
  8726. // Set default display name.
  8727. localVideoThumbnail.setDisplayName();
  8728. localVideoThumbnail.createConnectionIndicator();
  8729. this.onVideoTypeChanged(APP.xmpp.myResource(), stream.videoType);
  8730. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  8731. localVideoThumbnail.changeVideo(stream, isMuted);
  8732. /* force update if we're currently being displayed */
  8733. if (LargeVideo.isCurrentlyOnLarge(APP.xmpp.myResource())) {
  8734. LargeVideo.updateLargeVideo(APP.xmpp.myResource(), true);
  8735. }
  8736. };
  8737. my.mucJoined = function () {
  8738. var myResourceJid = APP.xmpp.myResource();
  8739. localVideoThumbnail.joined(APP.xmpp.myJid());
  8740. if (!LargeVideo.getResourceJid())
  8741. LargeVideo.updateLargeVideo(myResourceJid, true);
  8742. };
  8743. /**
  8744. * Adds or removes icons for not available camera and microphone.
  8745. * @param resourceJid the jid of user
  8746. * @param devices available devices
  8747. */
  8748. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  8749. if(!devices)
  8750. return;
  8751. if(!resourceJid) {
  8752. localVideoThumbnail.setDeviceAvailabilityIcons(devices);
  8753. } else {
  8754. if(remoteVideos[resourceJid])
  8755. remoteVideos[resourceJid].setDeviceAvailabilityIcons(devices);
  8756. }
  8757. };
  8758. /**
  8759. * Checks if removed video is currently displayed and tries to display
  8760. * another one instead.
  8761. * @param removedVideoSrc src stream identifier of the video.
  8762. */
  8763. my.updateRemovedVideo = function(resourceJid) {
  8764. if (resourceJid === LargeVideo.getResourceJid()) {
  8765. var newResourceJid;
  8766. // We'll show user's avatar if he is the dominant speaker or if
  8767. // his video thumbnail is pinned
  8768. if (remoteVideos[resourceJid] &&
  8769. resourceJid === focusedVideoResourceJid ||
  8770. resourceJid === currentDominantSpeaker) {
  8771. newResourceJid = resourceJid;
  8772. } else {
  8773. // Otherwise select last visible video
  8774. newResourceJid = this.electLastVisibleVideo();
  8775. }
  8776. LargeVideo.updateLargeVideo(newResourceJid);
  8777. }
  8778. };
  8779. my.electLastVisibleVideo = function() {
  8780. // pick the last visible video in the row
  8781. // if nobody else is left, this picks the local video
  8782. var jid;
  8783. var videoElem = RTC.getVideoElementName();
  8784. var pick = $('#remoteVideos>span[id!="mixedstream"]:visible:last>' + videoElem);
  8785. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8786. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8787. } else {
  8788. console.info("Last visible video no longer exists");
  8789. pick = $('#remoteVideos>span[id!="mixedstream"]>' + videoElem);
  8790. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8791. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8792. } else {
  8793. // Try local video
  8794. console.info("Fallback to local video...");
  8795. jid = APP.xmpp.myResource();
  8796. }
  8797. }
  8798. console.info("electLastVisibleVideo: " + jid);
  8799. return jid;
  8800. };
  8801. my.onRemoteStreamAdded = function (stream) {
  8802. if (stream.peerjid) {
  8803. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  8804. var resourceJid = Strophe.getResourceFromJid(stream.peerjid);
  8805. remoteVideos[resourceJid].addRemoteStreamElement(
  8806. stream.sid,
  8807. stream.getOriginalStream(),
  8808. stream.ssrc);
  8809. }
  8810. };
  8811. my.getLargeVideoResource = function () {
  8812. return LargeVideo.getResourceJid();
  8813. };
  8814. /**
  8815. * Called when large video update is finished
  8816. * @param currentSmallVideo small video currently displayed on large video
  8817. */
  8818. my.largeVideoUpdated = function (currentSmallVideo) {
  8819. // Makes sure that dominant speaker UI
  8820. // is enabled only on current small video
  8821. localVideoThumbnail.enableDominantSpeaker(
  8822. localVideoThumbnail === currentSmallVideo);
  8823. Object.keys(remoteVideos).forEach(
  8824. function (resourceJid) {
  8825. var remoteVideo = remoteVideos[resourceJid];
  8826. if (remoteVideo) {
  8827. remoteVideo.enableDominantSpeaker(
  8828. remoteVideo === currentSmallVideo);
  8829. }
  8830. }
  8831. );
  8832. };
  8833. my.handleVideoThumbClicked = function(noPinnedEndpointChangedEvent,
  8834. resourceJid) {
  8835. if(focusedVideoResourceJid) {
  8836. var oldSmallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  8837. if (oldSmallVideo && !interfaceConfig.filmStripOnly)
  8838. oldSmallVideo.focus(false);
  8839. }
  8840. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  8841. // Unlock current focused.
  8842. if (focusedVideoResourceJid === resourceJid)
  8843. {
  8844. focusedVideoResourceJid = null;
  8845. // Enable the currently set dominant speaker.
  8846. if (currentDominantSpeaker) {
  8847. if(smallVideo && smallVideo.hasVideo()) {
  8848. LargeVideo.updateLargeVideo(currentDominantSpeaker);
  8849. }
  8850. }
  8851. if (!noPinnedEndpointChangedEvent) {
  8852. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  8853. }
  8854. return;
  8855. }
  8856. // Lock new video
  8857. focusedVideoResourceJid = resourceJid;
  8858. // Update focused/pinned interface.
  8859. if (resourceJid) {
  8860. if (smallVideo && !interfaceConfig.filmStripOnly)
  8861. smallVideo.focus(true);
  8862. if (!noPinnedEndpointChangedEvent) {
  8863. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  8864. }
  8865. }
  8866. LargeVideo.setState("video");
  8867. LargeVideo.updateLargeVideo(resourceJid);
  8868. // Writing volume not allowed in IE
  8869. if (!RTCBrowserType.isIExplorer()) {
  8870. $('audio').each(function (idx, el) {
  8871. el.volume = 0;
  8872. el.volume = 1;
  8873. });
  8874. }
  8875. };
  8876. /**
  8877. * Checks if container for participant identified by given peerJid exists
  8878. * in the document and creates it eventually.
  8879. *
  8880. * @param peerJid peer Jid to check.
  8881. *
  8882. * @return Returns <tt>true</tt> if the peer container exists,
  8883. * <tt>false</tt> - otherwise
  8884. */
  8885. my.ensurePeerContainerExists = function(peerJid) {
  8886. ContactList.ensureAddContact(peerJid);
  8887. var resourceJid = Strophe.getResourceFromJid(peerJid);
  8888. if (!remoteVideos[resourceJid]) {
  8889. var remoteVideo = new RemoteVideo(peerJid, VideoLayout);
  8890. remoteVideos[resourceJid] = remoteVideo;
  8891. var videoType = remoteVideoTypes[resourceJid];
  8892. if (videoType) {
  8893. remoteVideo.setVideoType(videoType);
  8894. }
  8895. // In case this is not currently in the last n we don't show it.
  8896. if (localLastNCount &&
  8897. localLastNCount > 0 &&
  8898. $('#remoteVideos>span').length >= localLastNCount + 2) {
  8899. remoteVideo.showPeerContainer('hide');
  8900. }
  8901. else
  8902. VideoLayout.resizeThumbnails();
  8903. }
  8904. };
  8905. my.inputDisplayNameHandler = function (name) {
  8906. localVideoThumbnail.inputDisplayNameHandler(name);
  8907. };
  8908. my.videoactive = function (videoelem, resourceJid) {
  8909. console.info(resourceJid + " video is now active");
  8910. videoelem.show();
  8911. VideoLayout.resizeThumbnails();
  8912. // Update the large video to the last added video only if there's no
  8913. // current dominant, focused speaker or prezi playing or update it to
  8914. // the current dominant speaker.
  8915. if ((!focusedVideoResourceJid &&
  8916. !currentDominantSpeaker &&
  8917. !require("../prezi/Prezi").isPresentationVisible()) ||
  8918. focusedVideoResourceJid === resourceJid ||
  8919. (resourceJid &&
  8920. currentDominantSpeaker === resourceJid)) {
  8921. LargeVideo.updateLargeVideo(resourceJid, true);
  8922. }
  8923. };
  8924. /**
  8925. * Shows the presence status message for the given video.
  8926. */
  8927. my.setPresenceStatus = function (resourceJid, statusMsg) {
  8928. remoteVideos[resourceJid].setPresenceStatus(statusMsg);
  8929. };
  8930. /**
  8931. * Shows a visual indicator for the moderator of the conference.
  8932. */
  8933. my.showModeratorIndicator = function () {
  8934. var isModerator = APP.xmpp.isModerator();
  8935. if (isModerator) {
  8936. localVideoThumbnail.createModeratorIndicatorElement();
  8937. }
  8938. var members = APP.xmpp.getMembers();
  8939. Object.keys(members).forEach(function (jid) {
  8940. if (Strophe.getResourceFromJid(jid) === 'focus') {
  8941. // Skip server side focus
  8942. return;
  8943. }
  8944. var resourceJid = Strophe.getResourceFromJid(jid);
  8945. var member = members[jid];
  8946. if (member.role === 'moderator') {
  8947. remoteVideos[resourceJid].removeRemoteVideoMenu();
  8948. remoteVideos[resourceJid].createModeratorIndicatorElement();
  8949. } else if (isModerator) {
  8950. // We are moderator, but user is not - add menu
  8951. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  8952. remoteVideos[resourceJid].addRemoteVideoMenu();
  8953. }
  8954. }
  8955. });
  8956. };
  8957. /*
  8958. * Shows or hides the audio muted indicator over the local thumbnail video.
  8959. * @param {boolean} isMuted
  8960. */
  8961. my.showLocalAudioIndicator = function(isMuted) {
  8962. localVideoThumbnail.showAudioIndicator(isMuted);
  8963. };
  8964. /**
  8965. * Resizes the large video container.
  8966. */
  8967. my.resizeLargeVideoContainer = function () {
  8968. if(LargeVideo.isEnabled()) {
  8969. LargeVideo.resize();
  8970. } else {
  8971. VideoLayout.resizeVideoSpace();
  8972. }
  8973. VideoLayout.resizeThumbnails();
  8974. LargeVideo.position();
  8975. };
  8976. /**
  8977. * Resizes thumbnails.
  8978. */
  8979. my.resizeThumbnails = function(animate) {
  8980. var videoSpaceWidth = $('#remoteVideos').width();
  8981. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  8982. var width = thumbnailSize[0];
  8983. var height = thumbnailSize[1];
  8984. $('.userAvatar').css('left', (width - height) / 2);
  8985. if(animate) {
  8986. $('#remoteVideos').animate({
  8987. height: height + 2 // adds 2 px because of small video 1px border
  8988. },
  8989. {
  8990. queue: false,
  8991. duration: 500
  8992. });
  8993. $('#remoteVideos>span').animate({
  8994. height: height,
  8995. width: width
  8996. },
  8997. {
  8998. queue: false,
  8999. duration: 500,
  9000. complete: function () {
  9001. $(document).trigger(
  9002. "remotevideo.resized",
  9003. [width,
  9004. height]);
  9005. }
  9006. });
  9007. } else {
  9008. // size videos so that while keeping AR and max height, we have a
  9009. // nice fit
  9010. $('#remoteVideos').height(height + 2);// adds 2 px because of small video 1px border
  9011. $('#remoteVideos>span').width(width);
  9012. $('#remoteVideos>span').height(height);
  9013. $(document).trigger("remotevideo.resized", [width, height]);
  9014. }
  9015. };
  9016. /**
  9017. * Calculates the thumbnail size.
  9018. *
  9019. * @param videoSpaceWidth the width of the video space
  9020. */
  9021. my.calculateThumbnailSize = function (videoSpaceWidth) {
  9022. // Calculate the available height, which is the inner window height minus
  9023. // 39px for the header minus 2px for the delimiter lines on the top and
  9024. // bottom of the large video, minus the 36px space inside the remoteVideos
  9025. // container used for highlighting shadow.
  9026. var availableHeight = 100;
  9027. var numvids = $('#remoteVideos>span:visible').length;
  9028. if (localLastNCount && localLastNCount > 0) {
  9029. numvids = Math.min(localLastNCount + 1, numvids);
  9030. }
  9031. // Remove the 3px borders arround videos and border around the remote
  9032. // videos area and the 4 pixels between the local video and the others
  9033. //TODO: Find out where the 4 pixels come from and remove them
  9034. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  9035. var availableWidth = availableWinWidth / numvids;
  9036. var aspectRatio = 16.0 / 9.0;
  9037. var maxHeight = Math.min(160, availableHeight);
  9038. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio, window.innerHeight - 18);
  9039. if (availableHeight < availableWidth / aspectRatio) {
  9040. availableWidth = Math.floor(availableHeight * aspectRatio);
  9041. }
  9042. return [availableWidth, availableHeight];
  9043. };
  9044. /**
  9045. * Returns the corresponding resource jid to the given peer container
  9046. * DOM element.
  9047. *
  9048. * @return the corresponding resource jid to the given peer container
  9049. * DOM element
  9050. */
  9051. my.getPeerContainerResourceJid = function (containerElement) {
  9052. var i = containerElement.id.indexOf('participant_');
  9053. if (i >= 0)
  9054. return containerElement.id.substring(i + 12);
  9055. };
  9056. my.getPeerVideoSel = function (peerResourceJid) {
  9057. return $('#participant_' + peerResourceJid +
  9058. '>' + APP.RTC.getVideoElementName());
  9059. };
  9060. /**
  9061. * On contact list item clicked.
  9062. */
  9063. $(ContactList).bind('contactclicked', function(event, jid) {
  9064. if (!jid) {
  9065. return;
  9066. }
  9067. if (jid === APP.xmpp.myJid()) {
  9068. $("#localVideoContainer").click();
  9069. return;
  9070. }
  9071. var resource = Strophe.getResourceFromJid(jid);
  9072. var videoSel = VideoLayout.getPeerVideoSel(resource);
  9073. if (videoSel.length > 0) {
  9074. var videoThumb = videoSel[0];
  9075. // It is not always the case that a videoThumb exists (if there is
  9076. // no actual video).
  9077. if (RTC.getVideoSrc(videoThumb)) {
  9078. // We have a video src, great! Let's update the large video
  9079. // now.
  9080. VideoLayout.handleVideoThumbClicked(
  9081. false,
  9082. Strophe.getResourceFromJid(jid));
  9083. } else {
  9084. // If we don't have a video src for jid, there's absolutely
  9085. // no point in calling handleVideoThumbClicked; Quite
  9086. // simply, it won't work because it needs an src to attach
  9087. // to the large video.
  9088. //
  9089. // Instead, we trigger the pinned endpoint changed event to
  9090. // let the bridge adjust its lastN set for myjid and store
  9091. // the pinned user in the lastNPickupJid variable to be
  9092. // picked up later by the lastN changed event handler.
  9093. lastNPickupJid = jid;
  9094. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  9095. Strophe.getResourceFromJid(jid));
  9096. }
  9097. }
  9098. });
  9099. /**
  9100. * On audio muted event.
  9101. */
  9102. my.onAudioMute = function (jid, isMuted) {
  9103. var resourceJid = Strophe.getResourceFromJid(jid);
  9104. if (resourceJid === APP.xmpp.myResource()) {
  9105. localVideoThumbnail.showAudioIndicator(isMuted);
  9106. } else {
  9107. VideoLayout.ensurePeerContainerExists(jid);
  9108. remoteVideos[resourceJid].showAudioIndicator(isMuted);
  9109. if (APP.xmpp.isModerator()) {
  9110. remoteVideos[resourceJid].updateRemoteVideoMenu(isMuted);
  9111. }
  9112. }
  9113. };
  9114. /**
  9115. * On video muted event.
  9116. */
  9117. my.onVideoMute = function (jid, value) {
  9118. if (jid !== APP.xmpp.myJid() &&
  9119. !APP.RTC.muteRemoteVideoStream(jid, value))
  9120. return;
  9121. if (jid === APP.xmpp.myJid()) {
  9122. localVideoThumbnail.showVideoIndicator(value);
  9123. } else {
  9124. var resource = Strophe.getResourceFromJid(jid);
  9125. VideoLayout.ensurePeerContainerExists(jid);
  9126. remoteVideos[resource].showVideoIndicator(value);
  9127. var el = VideoLayout.getPeerVideoSel(resource);
  9128. if (!value)
  9129. el.show();
  9130. else
  9131. el.hide();
  9132. }
  9133. };
  9134. /**
  9135. * Display name changed.
  9136. */
  9137. my.onDisplayNameChanged =
  9138. function (jid, displayName, status) {
  9139. if (jid === 'localVideoContainer' ||
  9140. jid === APP.xmpp.myJid()) {
  9141. localVideoThumbnail.setDisplayName(displayName);
  9142. } else {
  9143. VideoLayout.ensurePeerContainerExists(jid);
  9144. remoteVideos[Strophe.getResourceFromJid(jid)].setDisplayName(
  9145. displayName,
  9146. status);
  9147. }
  9148. };
  9149. /**
  9150. * On dominant speaker changed event.
  9151. */
  9152. my.onDominantSpeakerChanged = function (resourceJid) {
  9153. // We ignore local user events.
  9154. if (resourceJid === APP.xmpp.myResource())
  9155. return;
  9156. var members = APP.xmpp.getMembers();
  9157. // Update the current dominant speaker.
  9158. if (resourceJid !== currentDominantSpeaker) {
  9159. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  9160. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  9161. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  9162. !members[currentJID].displayName) && remoteVideos[resourceJid]) {
  9163. remoteVideos[resourceJid].setDisplayName(null);
  9164. }
  9165. if(resourceJid && (!members || !members[newJID] ||
  9166. !members[newJID].displayName) && remoteVideos[resourceJid]) {
  9167. remoteVideos[resourceJid].setDisplayName(null,
  9168. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  9169. }
  9170. currentDominantSpeaker = resourceJid;
  9171. } else {
  9172. return;
  9173. }
  9174. // Obtain container for new dominant speaker.
  9175. var videoSel = VideoLayout.getPeerVideoSel(resourceJid);
  9176. // Local video will not have container found, but that's ok
  9177. // since we don't want to switch to local video.
  9178. if (!focusedVideoResourceJid && videoSel.length) {
  9179. // Update the large video if the video source is already available,
  9180. // otherwise wait for the "videoactive.jingle" event.
  9181. if (videoSel[0].currentTime > 0) {
  9182. LargeVideo.updateLargeVideo(resourceJid);
  9183. }
  9184. }
  9185. };
  9186. /**
  9187. * On last N change event.
  9188. *
  9189. * @param lastNEndpoints the list of last N endpoints
  9190. * @param endpointsEnteringLastN the list currently entering last N
  9191. * endpoints
  9192. */
  9193. my.onLastNEndpointsChanged = function (lastNEndpoints,
  9194. endpointsEnteringLastN,
  9195. stream) {
  9196. if (lastNCount !== lastNEndpoints.length)
  9197. lastNCount = lastNEndpoints.length;
  9198. lastNEndpointsCache = lastNEndpoints;
  9199. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  9200. //
  9201. // If LastN drops to, say, 2, because of adaptivity, then E should see
  9202. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  9203. // so E sees them. C is only in E's local LastN set.
  9204. //
  9205. // If F starts talking and LastN = 3, then E should see thumbnails for
  9206. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  9207. // enters E's local LastN ejecting C.
  9208. // Increase the local LastN set size, if necessary.
  9209. if (lastNCount > localLastNCount) {
  9210. localLastNCount = lastNCount;
  9211. }
  9212. // Update the local LastN set preserving the order in which the
  9213. // endpoints appeared in the LastN/local LastN set.
  9214. var nextLocalLastNSet = lastNEndpoints.slice(0);
  9215. for (var i = 0; i < localLastNSet.length; i++) {
  9216. if (nextLocalLastNSet.length >= localLastNCount) {
  9217. break;
  9218. }
  9219. var resourceJid = localLastNSet[i];
  9220. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  9221. nextLocalLastNSet.push(resourceJid);
  9222. }
  9223. }
  9224. localLastNSet = nextLocalLastNSet;
  9225. var updateLargeVideo = false;
  9226. // Handle LastN/local LastN changes.
  9227. $('#remoteVideos>span').each(function( index, element ) {
  9228. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  9229. var isReceived = true;
  9230. if (resourceJid &&
  9231. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9232. localLastNSet.indexOf(resourceJid) < 0) {
  9233. console.log("Remove from last N", resourceJid);
  9234. remoteVideos[resourceJid].showPeerContainer('hide');
  9235. isReceived = false;
  9236. } else if (resourceJid &&
  9237. $('#participant_' + resourceJid).is(':visible') &&
  9238. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9239. localLastNSet.indexOf(resourceJid) >= 0) {
  9240. remoteVideos[resourceJid].showPeerContainer('avatar');
  9241. isReceived = false;
  9242. }
  9243. if (!isReceived) {
  9244. // resourceJid has dropped out of the server side lastN set, so
  9245. // it is no longer being received. If resourceJid was being
  9246. // displayed in the large video we have to switch to another
  9247. // user.
  9248. if (!updateLargeVideo &&
  9249. resourceJid === LargeVideo.getResourceJid()) {
  9250. updateLargeVideo = true;
  9251. }
  9252. }
  9253. });
  9254. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  9255. endpointsEnteringLastN = lastNEndpoints;
  9256. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  9257. endpointsEnteringLastN.forEach(function (resourceJid) {
  9258. var isVisible = $('#participant_' + resourceJid).is(':visible');
  9259. remoteVideos[resourceJid].showPeerContainer('show');
  9260. if (!isVisible) {
  9261. console.log("Add to last N", resourceJid);
  9262. var jid = APP.xmpp.findJidFromResource(resourceJid);
  9263. var mediaStream =
  9264. APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9265. var sel = VideoLayout.getPeerVideoSel(resourceJid);
  9266. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  9267. if (lastNPickupJid == mediaStream.peerjid) {
  9268. // Clean up the lastN pickup jid.
  9269. lastNPickupJid = null;
  9270. // Don't fire the events again, they've already
  9271. // been fired in the contact list click handler.
  9272. VideoLayout.handleVideoThumbClicked(
  9273. false,
  9274. Strophe.getResourceFromJid(mediaStream.peerjid));
  9275. updateLargeVideo = false;
  9276. }
  9277. remoteVideos[resourceJid].
  9278. waitForPlayback(sel, mediaStream.stream);
  9279. }
  9280. });
  9281. }
  9282. // The endpoint that was being shown in the large video has dropped out
  9283. // of the lastN set and there was no lastN pickup jid. We need to update
  9284. // the large video now.
  9285. if (updateLargeVideo) {
  9286. var resource;
  9287. var myResource
  9288. = APP.xmpp.myResource();
  9289. // Find out which endpoint to show in the large video.
  9290. for (i = 0; i < lastNEndpoints.length; i++) {
  9291. resource = lastNEndpoints[i];
  9292. if (!resource || resource === myResource)
  9293. continue;
  9294. // videoSrcToSsrc needs to be update for this call to succeed.
  9295. LargeVideo.updateLargeVideo(resource);
  9296. break;
  9297. }
  9298. }
  9299. };
  9300. /**
  9301. * Updates local stats
  9302. * @param percent
  9303. * @param object
  9304. */
  9305. my.updateLocalConnectionStats = function (percent, object) {
  9306. var resolution = null;
  9307. if (object.resolution !== null) {
  9308. resolution = object.resolution;
  9309. object.resolution = resolution[APP.xmpp.myJid()];
  9310. delete resolution[APP.xmpp.myJid()];
  9311. }
  9312. localVideoThumbnail.updateStatsIndicator(percent, object);
  9313. for (var jid in resolution) {
  9314. if (resolution[jid] === null)
  9315. continue;
  9316. var resourceJid = Strophe.getResourceFromJid(jid);
  9317. if (remoteVideos[resourceJid] &&
  9318. remoteVideos[resourceJid].connectionIndicator) {
  9319. remoteVideos[resourceJid].connectionIndicator.
  9320. updateResolution(resolution[jid]);
  9321. }
  9322. }
  9323. };
  9324. /**
  9325. * Updates remote stats.
  9326. * @param jid the jid associated with the stats
  9327. * @param percent the connection quality percent
  9328. * @param object the stats data
  9329. */
  9330. my.updateConnectionStats = function (jid, percent, object) {
  9331. var resourceJid = Strophe.getResourceFromJid(jid);
  9332. if (remoteVideos[resourceJid])
  9333. remoteVideos[resourceJid].updateStatsIndicator(percent, object);
  9334. };
  9335. /**
  9336. * Hides the connection indicator
  9337. * @param jid
  9338. */
  9339. my.hideConnectionIndicator = function (jid) {
  9340. remoteVideos[Strophe.getResourceFromJid(jid)].hideConnectionIndicator();
  9341. };
  9342. /**
  9343. * Hides all the indicators
  9344. */
  9345. my.onStatsStop = function () {
  9346. for(var video in remoteVideos) {
  9347. remoteVideos[video].hideIndicator();
  9348. }
  9349. localVideoThumbnail.hideIndicator();
  9350. };
  9351. my.participantLeft = function (jid) {
  9352. // Unlock large video
  9353. var resourceJid = Strophe.getResourceFromJid(jid);
  9354. if (focusedVideoResourceJid === resourceJid) {
  9355. console.info("Focused video owner has left the conference");
  9356. focusedVideoResourceJid = null;
  9357. }
  9358. if (currentDominantSpeaker === resourceJid)
  9359. {
  9360. console.info("Dominant speaker has left the conference");
  9361. currentDominantSpeaker = null;
  9362. }
  9363. var remoteVideo = remoteVideos[resourceJid];
  9364. if (remoteVideo) {
  9365. // Remove remote video
  9366. console.info("Removing remote video: " + resourceJid);
  9367. remoteVideo.remove();
  9368. delete remoteVideos[resourceJid];
  9369. } else {
  9370. console.warn("No remote video for " + resourceJid);
  9371. }
  9372. VideoLayout.resizeThumbnails();
  9373. };
  9374. my.onVideoTypeChanged = function (resourceJid, newVideoType) {
  9375. if (remoteVideoTypes[resourceJid] === newVideoType) {
  9376. return;
  9377. }
  9378. console.info("Peer video type changed: ", resourceJid, newVideoType);
  9379. remoteVideoTypes[resourceJid] = newVideoType;
  9380. var smallVideo;
  9381. if (resourceJid === APP.xmpp.myResource()) {
  9382. if (!localVideoThumbnail) {
  9383. console.warn("Local video not ready yet");
  9384. return;
  9385. }
  9386. smallVideo = localVideoThumbnail;
  9387. } else if (remoteVideos[resourceJid]) {
  9388. smallVideo = remoteVideos[resourceJid];
  9389. } else {
  9390. return;
  9391. }
  9392. smallVideo.setVideoType(newVideoType);
  9393. LargeVideo.onVideoTypeChanged(resourceJid, newVideoType);
  9394. };
  9395. my.showMore = function (jid) {
  9396. if (jid === 'local') {
  9397. localVideoThumbnail.connectionIndicator.showMore();
  9398. } else {
  9399. var remoteVideo = remoteVideos[Strophe.getResourceFromJid(jid)];
  9400. if (remoteVideo) {
  9401. remoteVideo.connectionIndicator.showMore();
  9402. } else {
  9403. console.info("Error - no remote video for jid: " + jid);
  9404. }
  9405. }
  9406. };
  9407. my.addPreziContainer = function (id) {
  9408. var container = RemoteVideo.createContainer(id);
  9409. VideoLayout.resizeThumbnails();
  9410. return container;
  9411. };
  9412. my.setLargeVideoVisible = function (isVisible) {
  9413. LargeVideo.setLargeVideoVisible(isVisible);
  9414. if(!isVisible && focusedVideoResourceJid) {
  9415. var smallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9416. if(smallVideo) {
  9417. smallVideo.focus(false);
  9418. smallVideo.showAvatar();
  9419. }
  9420. focusedVideoResourceJid = null;
  9421. }
  9422. };
  9423. /**
  9424. * Resizes the video area
  9425. * @param callback a function to be called when the video space is
  9426. * resized.
  9427. */
  9428. my.resizeVideoArea = function(isVisible, callback) {
  9429. LargeVideo.resizeVideoAreaAnimated(isVisible, callback);
  9430. VideoLayout.resizeThumbnails(true);
  9431. };
  9432. /**
  9433. * Resizes the #videospace html element
  9434. * @param animate boolean property that indicates whether the resize should be animated or not.
  9435. * @param isChatVisible boolean property that indicates whether the chat area is displayed or not.
  9436. * If that parameter is null the method will check the chat pannel visibility.
  9437. * @param completeFunction a function to be called when the video space is resized
  9438. */
  9439. my.resizeVideoSpace = function (animate, isChatVisible, completeFunction) {
  9440. var availableHeight = window.innerHeight;
  9441. var availableWidth = UIUtil.getAvailableVideoWidth(isChatVisible);
  9442. if (availableWidth < 0 || availableHeight < 0) return;
  9443. if(animate) {
  9444. $('#videospace').animate({
  9445. right: window.innerWidth - availableWidth,
  9446. width: availableWidth,
  9447. height: availableHeight
  9448. },
  9449. {
  9450. queue: false,
  9451. duration: 500,
  9452. complete: completeFunction
  9453. });
  9454. } else {
  9455. $('#videospace').width(availableWidth);
  9456. $('#videospace').height(availableHeight);
  9457. }
  9458. };
  9459. my.getSmallVideo = function (resourceJid) {
  9460. if(resourceJid == APP.xmpp.myResource()) {
  9461. return localVideoThumbnail;
  9462. } else {
  9463. if(!remoteVideos[resourceJid])
  9464. return null;
  9465. return remoteVideos[resourceJid];
  9466. }
  9467. };
  9468. my.userAvatarChanged = function(resourceJid, thumbUrl) {
  9469. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9470. if(smallVideo)
  9471. smallVideo.avatarChanged(thumbUrl);
  9472. else
  9473. console.warn(
  9474. "Missed avatar update - no small video yet for " + resourceJid);
  9475. LargeVideo.updateAvatar(resourceJid, thumbUrl);
  9476. };
  9477. my.createEtherpadIframe = function(src, onloadHandler)
  9478. {
  9479. return LargeVideo.createEtherpadIframe(src, onloadHandler);
  9480. };
  9481. my.setLargeVideoState = function (state) {
  9482. LargeVideo.setState(state);
  9483. };
  9484. my.getLargeVideoState = function () {
  9485. return LargeVideo.getState();
  9486. };
  9487. my.setLargeVideoHover = function (inHandler, outHandler) {
  9488. LargeVideo.setHover(inHandler, outHandler);
  9489. };
  9490. /**
  9491. * Indicates that the video has been interrupted.
  9492. */
  9493. my.onVideoInterrupted = function () {
  9494. LargeVideo.enableVideoProblemFilter(true);
  9495. var reconnectingKey = "connection.RECONNECTING";
  9496. $('#videoConnectionMessage').attr("data-i18n", reconnectingKey);
  9497. $('#videoConnectionMessage').text(APP.translation.translateString(reconnectingKey));
  9498. $('#videoConnectionMessage').css({display: "block"});
  9499. };
  9500. /**
  9501. * Indicates that the video has been restored.
  9502. */
  9503. my.onVideoRestored = function () {
  9504. LargeVideo.enableVideoProblemFilter(false);
  9505. $('#videoConnectionMessage').css({display: "none"});
  9506. };
  9507. return my;
  9508. }(VideoLayout || {}));
  9509. module.exports = VideoLayout;
  9510. },{"../../../service/RTC/MediaStreamTypes":151,"../../../service/UI/UIEvents":155,"../../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){
  9511. //var nouns = [
  9512. //];
  9513. var pluralNouns = [
  9514. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  9515. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  9516. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  9517. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  9518. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  9519. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  9520. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  9521. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  9522. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  9523. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  9524. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  9525. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  9526. ];
  9527. //var places = [
  9528. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  9529. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  9530. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  9531. // "Bridge"
  9532. //];
  9533. var verbs = [
  9534. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  9535. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  9536. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  9537. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  9538. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  9539. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  9540. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  9541. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  9542. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  9543. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  9544. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  9545. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  9546. ];
  9547. var adverbs = [
  9548. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  9549. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  9550. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  9551. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  9552. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  9553. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  9554. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  9555. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  9556. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  9557. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  9558. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  9559. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  9560. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  9561. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  9562. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly",
  9563. "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  9564. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  9565. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  9566. ];
  9567. var adjectives = [
  9568. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  9569. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  9570. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  9571. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  9572. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  9573. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  9574. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  9575. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  9576. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  9577. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  9578. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  9579. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  9580. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  9581. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  9582. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  9583. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  9584. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  9585. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  9586. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  9587. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  9588. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  9589. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  9590. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  9591. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  9592. "Zealous"
  9593. ];
  9594. //var pronouns = [
  9595. //];
  9596. //var conjunctions = [
  9597. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  9598. //];
  9599. /*
  9600. * Maps a string (category name) to the array of words from that category.
  9601. */
  9602. var CATEGORIES =
  9603. {
  9604. //"_NOUN_": nouns,
  9605. "_PLURALNOUN_": pluralNouns,
  9606. //"_PLACE_": places,
  9607. "_VERB_": verbs,
  9608. "_ADVERB_": adverbs,
  9609. "_ADJECTIVE_": adjectives
  9610. //"_PRONOUN_": pronouns,
  9611. //"_CONJUNCTION_": conjunctions,
  9612. };
  9613. var PATTERNS = [
  9614. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  9615. // BeautifulFungiOrSpaghetti
  9616. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  9617. // AmazinglyScaryToy
  9618. //"_ADVERB__ADJECTIVE__NOUN_",
  9619. // NeitherTrashNorRifle
  9620. //"Neither_NOUN_Nor_NOUN_",
  9621. //"Either_NOUN_Or_NOUN_",
  9622. // EitherCopulateOrInvestigate
  9623. //"Either_VERB_Or_VERB_",
  9624. //"Neither_VERB_Nor_VERB_",
  9625. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  9626. //"The_ADVERB__ADJECTIVE__NOUN_",
  9627. //"The_ADVERB__ADJECTIVE__NOUN_s",
  9628. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  9629. // WolvesComputeBadly
  9630. //"_PLURALNOUN__VERB__ADVERB_",
  9631. // UniteFacilitateAndMerge
  9632. //"_VERB__VERB_And_VERB_",
  9633. //NastyWitchesAtThePub
  9634. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  9635. ];
  9636. /*
  9637. * Returns a random element from the array 'arr'
  9638. */
  9639. function randomElement(arr) {
  9640. return arr[Math.floor(Math.random() * arr.length)];
  9641. }
  9642. /*
  9643. * Returns true if the string 's' contains one of the
  9644. * template strings.
  9645. */
  9646. function hasTemplate(s) {
  9647. for (var template in CATEGORIES){
  9648. if (s.indexOf(template) >= 0){
  9649. return true;
  9650. }
  9651. }
  9652. }
  9653. /**
  9654. * Generates new room name.
  9655. */
  9656. var RoomNameGenerator = {
  9657. generateRoomWithoutSeparator: function() {
  9658. // Note that if more than one pattern is available, the choice of
  9659. // 'name' won't have a uniform distribution amongst all patterns (names
  9660. // from patterns with fewer options will have higher probability of
  9661. // being chosen that names from patterns with more options).
  9662. var name = randomElement(PATTERNS);
  9663. var word;
  9664. while (hasTemplate(name)) {
  9665. for (var template in CATEGORIES) {
  9666. word = randomElement(CATEGORIES[template]);
  9667. name = name.replace(template, word);
  9668. }
  9669. }
  9670. return name;
  9671. }
  9672. };
  9673. module.exports = RoomNameGenerator;
  9674. },{}],41:[function(require,module,exports){
  9675. /* global $, interfaceConfig */
  9676. var animateTimeout, updateTimeout;
  9677. var RoomNameGenerator = require("./RoomnameGenerator");
  9678. function enter_room() {
  9679. var val = $("#enter_room_field").val();
  9680. if(!val) {
  9681. val = $("#enter_room_field").attr("room_name");
  9682. }
  9683. if (val) {
  9684. window.location.pathname = "/" + val;
  9685. }
  9686. }
  9687. function animate(word) {
  9688. var currentVal = $("#enter_room_field").attr("placeholder");
  9689. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  9690. animateTimeout = setTimeout(function() {
  9691. animate(word.substring(1, word.length))
  9692. }, 70);
  9693. }
  9694. function update_roomname() {
  9695. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  9696. $("#enter_room_field").attr("room_name", word);
  9697. $("#enter_room_field").attr("placeholder", "");
  9698. clearTimeout(animateTimeout);
  9699. animate(word);
  9700. updateTimeout = setTimeout(update_roomname, 10000);
  9701. }
  9702. function setupWelcomePage() {
  9703. $("#videoconference_page").hide();
  9704. $("#domain_name").text(
  9705. window.location.protocol + "//" + window.location.host + "/");
  9706. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  9707. var leftWatermarkDiv =
  9708. $("#welcome_page_header div[class='watermark leftwatermark']");
  9709. if(leftWatermarkDiv && leftWatermarkDiv.length > 0) {
  9710. leftWatermarkDiv.css({display: 'block'});
  9711. leftWatermarkDiv.parent().get(0).href =
  9712. interfaceConfig.JITSI_WATERMARK_LINK;
  9713. }
  9714. }
  9715. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  9716. var rightWatermarkDiv =
  9717. $("#welcome_page_header div[class='watermark rightwatermark']");
  9718. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  9719. rightWatermarkDiv.css({display: 'block'});
  9720. rightWatermarkDiv.parent().get(0).href =
  9721. interfaceConfig.BRAND_WATERMARK_LINK;
  9722. rightWatermarkDiv.get(0).style.backgroundImage =
  9723. "url(images/rightwatermark.png)";
  9724. }
  9725. }
  9726. if (interfaceConfig.SHOW_POWERED_BY) {
  9727. $("#welcome_page_header>a[class='poweredby']")
  9728. .css({display: 'block'});
  9729. }
  9730. $("#enter_room_button").click(function() {
  9731. enter_room();
  9732. });
  9733. $("#enter_room_field").keydown(function (event) {
  9734. if (event.keyCode === 13 /* enter */) {
  9735. enter_room();
  9736. }
  9737. });
  9738. if (interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE !== false) {
  9739. var updateTimeout;
  9740. var animateTimeout;
  9741. var selector = $("#reload_roomname");
  9742. selector.click(function () {
  9743. clearTimeout(updateTimeout);
  9744. clearTimeout(animateTimeout);
  9745. update_roomname();
  9746. });
  9747. selector.show();
  9748. update_roomname();
  9749. }
  9750. $("#disable_welcome").click(function () {
  9751. window.localStorage.welcomePageDisabled =
  9752. $("#disable_welcome").is(":checked");
  9753. });
  9754. }
  9755. module.exports = setupWelcomePage;
  9756. },{"./RoomnameGenerator":40}],42:[function(require,module,exports){
  9757. /* global $, $iq, config, interfaceConfig */
  9758. var params = {};
  9759. function getConfigParamsFromUrl() {
  9760. if(!location.hash)
  9761. return {};
  9762. var hash = location.hash.substr(1);
  9763. var result = {};
  9764. hash.split("&").forEach(function(part) {
  9765. var item = part.split("=");
  9766. result[item[0]] = JSON.parse(
  9767. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  9768. });
  9769. return result;
  9770. }
  9771. params = getConfigParamsFromUrl();
  9772. var URLProcessor = {
  9773. setConfigParametersFromUrl: function () {
  9774. for(var key in params) {
  9775. if(typeof key !== "string")
  9776. continue;
  9777. var confObj = null, confKey;
  9778. if (key.indexOf("config.") === 0) {
  9779. confObj = config;
  9780. confKey = key.substr("config.".length);
  9781. } else if (key.indexOf("interfaceConfig.") === 0) {
  9782. confObj = interfaceConfig;
  9783. confKey = key.substr("interfaceConfig.".length);
  9784. }
  9785. if (!confObj)
  9786. continue;
  9787. var value = params[key];
  9788. if (confObj[confKey] && typeof confObj[confKey] !== typeof value)
  9789. {
  9790. console.warn("The type of " + key +
  9791. " is wrong. That parameter won't be updated in config.js.");
  9792. continue;
  9793. }
  9794. confObj[confKey] = value;
  9795. }
  9796. }
  9797. };
  9798. module.exports = URLProcessor;
  9799. },{}],43:[function(require,module,exports){
  9800. /* global APP, require */
  9801. var EventEmitter = require("events");
  9802. var eventEmitter = new EventEmitter();
  9803. var CQEvents = require("../../service/connectionquality/CQEvents");
  9804. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9805. /**
  9806. * local stats
  9807. * @type {{}}
  9808. */
  9809. var stats = {};
  9810. /**
  9811. * remote stats
  9812. * @type {{}}
  9813. */
  9814. var remoteStats = {};
  9815. /**
  9816. * Interval for sending statistics to other participants
  9817. * @type {null}
  9818. */
  9819. var sendIntervalId = null;
  9820. /**
  9821. * Start statistics sending.
  9822. */
  9823. function startSendingStats() {
  9824. sendStats();
  9825. sendIntervalId = setInterval(sendStats, 10000);
  9826. }
  9827. /**
  9828. * Sends statistics to other participants
  9829. */
  9830. function sendStats() {
  9831. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  9832. }
  9833. /**
  9834. * Converts statistics to format for sending through XMPP
  9835. * @param stats the statistics
  9836. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  9837. */
  9838. function convertToMUCStats(stats) {
  9839. return {
  9840. "bitrate_download": stats.bitrate.download,
  9841. "bitrate_upload": stats.bitrate.upload,
  9842. "packetLoss_total": stats.packetLoss.total,
  9843. "packetLoss_download": stats.packetLoss.download,
  9844. "packetLoss_upload": stats.packetLoss.upload
  9845. };
  9846. }
  9847. /**
  9848. * Converts statistics to format used by VideoLayout
  9849. * @param stats
  9850. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  9851. */
  9852. function parseMUCStats(stats) {
  9853. return {
  9854. bitrate: {
  9855. download: stats.bitrate_download,
  9856. upload: stats.bitrate_upload
  9857. },
  9858. packetLoss: {
  9859. total: stats.packetLoss_total,
  9860. download: stats.packetLoss_download,
  9861. upload: stats.packetLoss_upload
  9862. }
  9863. };
  9864. }
  9865. var ConnectionQuality = {
  9866. init: function () {
  9867. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  9868. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  9869. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  9870. },
  9871. /**
  9872. * Updates the local statistics
  9873. * @param data new statistics
  9874. */
  9875. updateLocalStats: function (data) {
  9876. stats = data;
  9877. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  9878. if (sendIntervalId == null) {
  9879. startSendingStats();
  9880. }
  9881. },
  9882. /**
  9883. * Updates remote statistics
  9884. * @param jid the jid associated with the statistics
  9885. * @param data the statistics
  9886. */
  9887. updateRemoteStats: function (jid, data) {
  9888. if (data == null || data.packetLoss_total == null) {
  9889. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  9890. return;
  9891. }
  9892. remoteStats[jid] = parseMUCStats(data);
  9893. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  9894. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  9895. },
  9896. /**
  9897. * Stops statistics sending.
  9898. */
  9899. stopSendingStats: function () {
  9900. clearInterval(sendIntervalId);
  9901. sendIntervalId = null;
  9902. //notify UI about stopping statistics gathering
  9903. eventEmitter.emit(CQEvents.STOP);
  9904. },
  9905. /**
  9906. * Returns the local statistics.
  9907. */
  9908. getStats: function () {
  9909. return stats;
  9910. },
  9911. addListener: function (type, listener) {
  9912. eventEmitter.on(type, listener);
  9913. }
  9914. };
  9915. module.exports = ConnectionQuality;
  9916. },{"../../service/connectionquality/CQEvents":157,"../../service/xmpp/XMPPEvents":161,"events":162}],44:[function(require,module,exports){
  9917. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  9918. getUserMediaWithConstraints */
  9919. /**
  9920. * Indicates that desktop stream is currently in use(for toggle purpose).
  9921. * @type {boolean}
  9922. */
  9923. var isUsingScreenStream = false;
  9924. /**
  9925. * Indicates that switch stream operation is in progress and prevent from
  9926. * triggering new events.
  9927. * @type {boolean}
  9928. */
  9929. var switchInProgress = false;
  9930. /**
  9931. * Method used to get screen sharing stream.
  9932. *
  9933. * @type {function (stream_callback, failure_callback}
  9934. */
  9935. var obtainDesktopStream = null;
  9936. /**
  9937. * Indicates whether desktop sharing extension is installed.
  9938. * @type {boolean}
  9939. */
  9940. var extInstalled = false;
  9941. /**
  9942. * Indicates whether update of desktop sharing extension is required.
  9943. * @type {boolean}
  9944. */
  9945. var extUpdateRequired = false;
  9946. var AdapterJS = require("../RTC/adapter.screenshare");
  9947. var EventEmitter = require("events");
  9948. var eventEmitter = new EventEmitter();
  9949. var DesktopSharingEventTypes
  9950. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  9951. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9952. var RTCEvents = require("../../service/RTC/RTCEvents");
  9953. /**
  9954. * Method obtains desktop stream from WebRTC 'screen' source.
  9955. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  9956. */
  9957. function obtainWebRTCScreen(streamCallback, failCallback) {
  9958. APP.RTC.getUserMediaWithConstraints(
  9959. ['screen'],
  9960. streamCallback,
  9961. failCallback
  9962. );
  9963. }
  9964. /**
  9965. * Constructs inline install URL for Chrome desktop streaming extension.
  9966. * The 'chromeExtensionId' must be defined in config.js.
  9967. * @returns {string}
  9968. */
  9969. function getWebStoreInstallUrl()
  9970. {
  9971. return "https://chrome.google.com/webstore/detail/" +
  9972. config.chromeExtensionId;
  9973. }
  9974. /**
  9975. * Checks whether extension update is required.
  9976. * @param minVersion minimal required version
  9977. * @param extVersion current extension version
  9978. * @returns {boolean}
  9979. */
  9980. function isUpdateRequired(minVersion, extVersion)
  9981. {
  9982. try
  9983. {
  9984. var s1 = minVersion.split('.');
  9985. var s2 = extVersion.split('.');
  9986. var len = Math.max(s1.length, s2.length);
  9987. for (var i = 0; i < len; i++)
  9988. {
  9989. var n1 = 0,
  9990. n2 = 0;
  9991. if (i < s1.length)
  9992. n1 = parseInt(s1[i]);
  9993. if (i < s2.length)
  9994. n2 = parseInt(s2[i]);
  9995. if (isNaN(n1) || isNaN(n2))
  9996. {
  9997. return true;
  9998. }
  9999. else if (n1 !== n2)
  10000. {
  10001. return n1 > n2;
  10002. }
  10003. }
  10004. // will happen if boths version has identical numbers in
  10005. // their components (even if one of them is longer, has more components)
  10006. return false;
  10007. }
  10008. catch (e)
  10009. {
  10010. console.error("Failed to parse extension version", e);
  10011. APP.UI.messageHandler.showError("dialog.error",
  10012. "dialog.detectext");
  10013. return true;
  10014. }
  10015. }
  10016. function checkChromeExtInstalled(callback) {
  10017. if (!chrome.runtime) {
  10018. // No API, so no extension for sure
  10019. callback(false, false);
  10020. return;
  10021. }
  10022. chrome.runtime.sendMessage(
  10023. config.chromeExtensionId,
  10024. { getVersion: true },
  10025. function (response) {
  10026. if (!response || !response.version) {
  10027. // Communication failure - assume that no endpoint exists
  10028. console.warn(
  10029. "Extension not installed?: ", chrome.runtime.lastError);
  10030. callback(false, false);
  10031. return;
  10032. }
  10033. // Check installed extension version
  10034. var extVersion = response.version;
  10035. console.log('Extension version is: ' + extVersion);
  10036. var updateRequired
  10037. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  10038. callback(!updateRequired, updateRequired);
  10039. }
  10040. );
  10041. }
  10042. function doGetStreamFromExtension(streamCallback, failCallback) {
  10043. // Sends 'getStream' msg to the extension.
  10044. // Extension id must be defined in the config.
  10045. chrome.runtime.sendMessage(
  10046. config.chromeExtensionId,
  10047. { getStream: true, sources: config.desktopSharingSources },
  10048. function (response) {
  10049. if (!response) {
  10050. failCallback(chrome.runtime.lastError);
  10051. return;
  10052. }
  10053. console.log("Response from extension: " + response);
  10054. if (response.streamId) {
  10055. APP.RTC.getUserMediaWithConstraints(
  10056. ['desktop'],
  10057. function (stream) {
  10058. streamCallback(stream);
  10059. },
  10060. failCallback,
  10061. null, null, null,
  10062. response.streamId);
  10063. } else {
  10064. failCallback("Extension failed to get the stream");
  10065. }
  10066. }
  10067. );
  10068. }
  10069. /**
  10070. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  10071. * stream for returned stream token.
  10072. */
  10073. function obtainScreenFromExtension(streamCallback, failCallback) {
  10074. if (extInstalled) {
  10075. doGetStreamFromExtension(streamCallback, failCallback);
  10076. } else {
  10077. if (extUpdateRequired) {
  10078. alert(
  10079. 'Jitsi Desktop Streamer requires update. ' +
  10080. 'Changes will take effect after next Chrome restart.');
  10081. }
  10082. chrome.webstore.install(
  10083. getWebStoreInstallUrl(),
  10084. function (arg) {
  10085. console.log("Extension installed successfully", arg);
  10086. extInstalled = true;
  10087. // We need to give a moment for the endpoint to become available
  10088. window.setTimeout(function () {
  10089. doGetStreamFromExtension(streamCallback, failCallback);
  10090. }, 500);
  10091. },
  10092. function (arg) {
  10093. console.log("Failed to install the extension", arg);
  10094. failCallback(arg);
  10095. APP.UI.messageHandler.showError("dialog.error",
  10096. "dialog.failtoinstall");
  10097. }
  10098. );
  10099. }
  10100. }
  10101. /**
  10102. * Call this method to toggle desktop sharing feature.
  10103. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  10104. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  10105. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  10106. * enabled), pass any other string or nothing in order to disable this
  10107. * feature completely.
  10108. */
  10109. function setDesktopSharing(method) {
  10110. obtainDesktopStream = null;
  10111. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  10112. // care about 'method' parameter
  10113. if (RTCBrowserType.isTemasysPluginUsed()) {
  10114. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  10115. console.info("Screensharing not supported by this plugin version");
  10116. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  10117. console.info(
  10118. "Screensharing not available with Temasys plugin on this site");
  10119. } else {
  10120. obtainDesktopStream = obtainWebRTCScreen;
  10121. console.info("Using Temasys plugin for desktop sharing");
  10122. }
  10123. } else if (RTCBrowserType.isChrome()) {
  10124. if (method == "ext") {
  10125. if (RTCBrowserType.getChromeVersion() >= 34) {
  10126. obtainDesktopStream = obtainScreenFromExtension;
  10127. console.info("Using Chrome extension for desktop sharing");
  10128. initChromeExtension();
  10129. } else {
  10130. console.info("Chrome extension not supported until ver 34");
  10131. }
  10132. } else if (method == "webrtc") {
  10133. obtainDesktopStream = obtainWebRTCScreen;
  10134. console.info("Using Chrome WebRTC for desktop sharing");
  10135. }
  10136. }
  10137. if (!obtainDesktopStream) {
  10138. console.info("Desktop sharing disabled");
  10139. }
  10140. }
  10141. /**
  10142. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  10143. * config.js to support inline installs. Host site must be selected as main
  10144. * website of published extension.
  10145. */
  10146. function initInlineInstalls()
  10147. {
  10148. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  10149. }
  10150. function initChromeExtension() {
  10151. // Initialize Chrome extension inline installs
  10152. initInlineInstalls();
  10153. // Check if extension is installed
  10154. checkChromeExtInstalled(function (installed, updateRequired) {
  10155. extInstalled = installed;
  10156. extUpdateRequired = updateRequired;
  10157. console.info(
  10158. "Chrome extension installed: " + extInstalled +
  10159. " updateRequired: " + extUpdateRequired);
  10160. });
  10161. }
  10162. function getVideoStreamFailed(error) {
  10163. console.error("Failed to obtain the stream to switch to", error);
  10164. switchInProgress = false;
  10165. isUsingScreenStream = false;
  10166. newStreamCreated(null);
  10167. }
  10168. function getDesktopStreamFailed(error) {
  10169. console.error("Failed to obtain the stream to switch to", error);
  10170. switchInProgress = false;
  10171. }
  10172. function streamSwitchDone() {
  10173. switchInProgress = false;
  10174. eventEmitter.emit(
  10175. DesktopSharingEventTypes.SWITCHING_DONE,
  10176. isUsingScreenStream);
  10177. }
  10178. function newStreamCreated(stream)
  10179. {
  10180. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  10181. stream, isUsingScreenStream, streamSwitchDone);
  10182. }
  10183. function onEndedHandler(stream) {
  10184. if (!switchInProgress && isUsingScreenStream) {
  10185. APP.desktopsharing.toggleScreenSharing();
  10186. }
  10187. //FIXME: to be verified
  10188. if (stream.removeEventListener) {
  10189. stream.removeEventListener('ended', onEndedHandler);
  10190. } else {
  10191. stream.detachEvent('ended', onEndedHandler);
  10192. }
  10193. }
  10194. // Called when RTC finishes initialization
  10195. function onWebRtcReady() {
  10196. setDesktopSharing(config.desktopSharing);
  10197. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  10198. }
  10199. module.exports = {
  10200. isUsingScreenStream: function () {
  10201. return isUsingScreenStream;
  10202. },
  10203. /**
  10204. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  10205. * and enabled.
  10206. */
  10207. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  10208. init: function () {
  10209. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  10210. },
  10211. addListener: function (listener, type)
  10212. {
  10213. eventEmitter.on(type, listener);
  10214. },
  10215. removeListener: function (listener, type) {
  10216. eventEmitter.removeListener(type, listener);
  10217. },
  10218. /*
  10219. * Toggles screen sharing.
  10220. */
  10221. toggleScreenSharing: function () {
  10222. if (switchInProgress || !obtainDesktopStream) {
  10223. console.warn("Switch in progress or no method defined");
  10224. return;
  10225. }
  10226. switchInProgress = true;
  10227. if (!isUsingScreenStream)
  10228. {
  10229. // Switch to desktop stream
  10230. obtainDesktopStream(
  10231. function (stream) {
  10232. // We now use screen stream
  10233. isUsingScreenStream = true;
  10234. // Hook 'ended' event to restore camera
  10235. // when screen stream stops
  10236. //FIXME: to be verified
  10237. if (stream.addEventListener) {
  10238. stream.addEventListener('ended', function () {
  10239. onEndedHandler(stream);
  10240. });
  10241. } else {
  10242. stream.attachEvent('ended', function () {
  10243. onEndedHandler(stream);
  10244. });
  10245. }
  10246. newStreamCreated(stream);
  10247. },
  10248. getDesktopStreamFailed);
  10249. } else {
  10250. // Disable screen stream
  10251. APP.RTC.getUserMediaWithConstraints(
  10252. ['video'],
  10253. function (stream) {
  10254. // We are now using camera stream
  10255. isUsingScreenStream = false;
  10256. newStreamCreated(stream);
  10257. },
  10258. getVideoStreamFailed, config.resolution || '360'
  10259. );
  10260. }
  10261. }
  10262. };
  10263. },{"../../service/RTC/RTCEvents":152,"../../service/desktopsharing/DesktopSharingEventTypes":158,"../RTC/RTCBrowserType":8,"../RTC/adapter.screenshare":10,"events":162}],45:[function(require,module,exports){
  10264. /* global APP, $ */
  10265. //maps keycode to character, id of popover for given function and function
  10266. var shortcuts = {};
  10267. function initShortcutHandlers() {
  10268. shortcuts = {
  10269. 67: {
  10270. character: "C",
  10271. id: "toggleChatPopover",
  10272. function: APP.UI.toggleChat
  10273. },
  10274. 70: {
  10275. character: "F",
  10276. id: "filmstripPopover",
  10277. function: APP.UI.toggleFilmStrip
  10278. },
  10279. 77: {
  10280. character: "M",
  10281. id: "mutePopover",
  10282. function: APP.UI.toggleAudio
  10283. },
  10284. 84: {
  10285. character: "T",
  10286. function: function() {
  10287. if(!APP.RTC.localAudio.isMuted()) {
  10288. APP.UI.toggleAudio();
  10289. }
  10290. }
  10291. },
  10292. 86: {
  10293. character: "V",
  10294. id: "toggleVideoPopover",
  10295. function: APP.UI.toggleVideo
  10296. }
  10297. };
  10298. }
  10299. var KeyboardShortcut = {
  10300. init: function () {
  10301. initShortcutHandlers();
  10302. window.onkeyup = function(e) {
  10303. var keycode = e.which;
  10304. if(!($(":focus").is("input[type=text]") ||
  10305. $(":focus").is("input[type=password]") ||
  10306. $(":focus").is("textarea"))) {
  10307. if (typeof shortcuts[keycode] === "object") {
  10308. shortcuts[keycode].function();
  10309. }
  10310. else if (keycode >= "0".charCodeAt(0) &&
  10311. keycode <= "9".charCodeAt(0)) {
  10312. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  10313. }
  10314. //esc while the smileys are visible hides them
  10315. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  10316. APP.UI.toggleSmileys();
  10317. }
  10318. };
  10319. window.onkeydown = function(e) {
  10320. if(!($(":focus").is("input[type=text]") ||
  10321. $(":focus").is("input[type=password]") ||
  10322. $(":focus").is("textarea"))) {
  10323. if(e.which === "T".charCodeAt(0)) {
  10324. if(APP.RTC.localAudio.isMuted()) {
  10325. APP.UI.toggleAudio();
  10326. }
  10327. }
  10328. }
  10329. };
  10330. var self = this;
  10331. $('body').popover({ selector: '[data-toggle=popover]',
  10332. trigger: 'click hover',
  10333. content: function() {
  10334. return this.getAttribute("content") +
  10335. self.getShortcut(this.getAttribute("shortcut"));
  10336. }
  10337. });
  10338. },
  10339. /**
  10340. *
  10341. * @param id indicates the popover associated with the shortcut
  10342. * @returns {string} the keyboard shortcut used for the id given
  10343. */
  10344. getShortcut: function (id) {
  10345. for (var keycode in shortcuts) {
  10346. if (shortcuts.hasOwnProperty(keycode)) {
  10347. if (shortcuts[keycode].id === id) {
  10348. return " (" + shortcuts[keycode].character + ")";
  10349. }
  10350. }
  10351. }
  10352. return "";
  10353. }
  10354. };
  10355. module.exports = KeyboardShortcut;
  10356. },{}],46:[function(require,module,exports){
  10357. /* global APP, require, $ */
  10358. /**
  10359. * This module is meant to (eventually) contain and manage all information
  10360. * about members/participants of the conference, so that other modules don't
  10361. * have to do it on their own, and so that other modules can access members'
  10362. * information from a single place.
  10363. *
  10364. * Currently this module only manages information about the support of jingle
  10365. * DTMF of the members. Other fields, as well as accessor methods are meant to
  10366. * be added as needed.
  10367. */
  10368. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10369. var Events = require("../../service/members/Events");
  10370. var EventEmitter = require("events");
  10371. var eventEmitter = new EventEmitter();
  10372. /**
  10373. * The actual container.
  10374. */
  10375. var members = {};
  10376. /**
  10377. * There is at least one member that supports DTMF (i.e. is jigasi).
  10378. */
  10379. var atLeastOneDtmf = false;
  10380. function registerListeners() {
  10381. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  10382. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  10383. }
  10384. /**
  10385. * Handles a new member joining the MUC.
  10386. */
  10387. function onMucMemberJoined(jid, id, displayName) {
  10388. var member = {
  10389. displayName: displayName
  10390. };
  10391. APP.xmpp.getConnection().disco.info(
  10392. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  10393. members[jid] = member;
  10394. }
  10395. /**
  10396. * Handles a member leaving the MUC.
  10397. */
  10398. function onMucMemberLeft(jid) {
  10399. delete members[jid];
  10400. updateAtLeastOneDtmf();
  10401. }
  10402. /**
  10403. * Handles the reception of a disco#info packet from a particular JID.
  10404. * @param jid the JID sending the packet.
  10405. * @param iq the packet.
  10406. */
  10407. function onDiscoInfoReceived(jid, iq) {
  10408. if (!members[jid])
  10409. return;
  10410. var supportsDtmf
  10411. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  10412. updateDtmf(jid, supportsDtmf);
  10413. }
  10414. /**
  10415. * Updates the 'supportsDtmf' field for a member.
  10416. * @param jid the jid of the member.
  10417. * @param newValue the new value for the 'supportsDtmf' field.
  10418. */
  10419. function updateDtmf(jid, newValue) {
  10420. var oldValue = members[jid].supportsDtmf;
  10421. members[jid].supportsDtmf = newValue;
  10422. if (newValue != oldValue) {
  10423. updateAtLeastOneDtmf();
  10424. }
  10425. }
  10426. /**
  10427. * Checks each member's 'supportsDtmf' field and updates
  10428. * 'atLastOneSupportsDtmf'.
  10429. */
  10430. function updateAtLeastOneDtmf() {
  10431. var newAtLeastOneDtmf = false;
  10432. for (var key in members) {
  10433. if (typeof members[key].supportsDtmf !== 'undefined'
  10434. && members[key].supportsDtmf) {
  10435. newAtLeastOneDtmf= true;
  10436. break;
  10437. }
  10438. }
  10439. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  10440. atLeastOneDtmf = newAtLeastOneDtmf;
  10441. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  10442. }
  10443. }
  10444. /**
  10445. * Exported interface.
  10446. */
  10447. var Members = {
  10448. start: function() {
  10449. registerListeners();
  10450. },
  10451. addListener: function(type, listener) {
  10452. eventEmitter.on(type, listener);
  10453. },
  10454. removeListener: function (type, listener) {
  10455. eventEmitter.removeListener(type, listener);
  10456. },
  10457. size: function () {
  10458. return Object.keys(members).length;
  10459. },
  10460. getMembers: function () {
  10461. return members;
  10462. }
  10463. };
  10464. module.exports = Members;
  10465. },{"../../service/members/Events":159,"../../service/xmpp/XMPPEvents":161,"events":162}],47:[function(require,module,exports){
  10466. var email = '';
  10467. var displayName = '';
  10468. var userId;
  10469. var language = null;
  10470. function supportsLocalStorage() {
  10471. try {
  10472. return 'localStorage' in window && window.localStorage !== null;
  10473. } catch (e) {
  10474. console.log("localstorage is not supported");
  10475. return false;
  10476. }
  10477. }
  10478. function generateUniqueId() {
  10479. function _p8() {
  10480. return (Math.random().toString(16) + "000000000").substr(2, 8);
  10481. }
  10482. return _p8() + _p8() + _p8() + _p8();
  10483. }
  10484. if (supportsLocalStorage()) {
  10485. if (!window.localStorage.jitsiMeetId) {
  10486. window.localStorage.jitsiMeetId = generateUniqueId();
  10487. console.log("generated id", window.localStorage.jitsiMeetId);
  10488. }
  10489. userId = window.localStorage.jitsiMeetId || '';
  10490. email = window.localStorage.email || '';
  10491. displayName = window.localStorage.displayname || '';
  10492. language = window.localStorage.language;
  10493. } else {
  10494. console.log("local storage is not supported");
  10495. userId = generateUniqueId();
  10496. }
  10497. var Settings = {
  10498. setDisplayName: function (newDisplayName) {
  10499. displayName = newDisplayName;
  10500. window.localStorage.displayname = displayName;
  10501. return displayName;
  10502. },
  10503. setEmail: function (newEmail) {
  10504. email = newEmail;
  10505. window.localStorage.email = newEmail;
  10506. return email;
  10507. },
  10508. getSettings: function () {
  10509. return {
  10510. email: email,
  10511. displayName: displayName,
  10512. uid: userId,
  10513. language: language
  10514. };
  10515. },
  10516. setLanguage: function (lang) {
  10517. language = lang;
  10518. window.localStorage.language = lang;
  10519. }
  10520. };
  10521. module.exports = Settings;
  10522. },{}],48:[function(require,module,exports){
  10523. /* global config, $, APP, Strophe, callstats */
  10524. var jsSHA = require('jssha');
  10525. var io = require('socket.io-client');
  10526. var callStats = null;
  10527. function initCallback (err, msg) {
  10528. console.log("Initializing Status: err="+err+" msg="+msg);
  10529. }
  10530. var CallStats = {
  10531. init: function (jingleSession) {
  10532. if(!config.callStatsID || !config.callStatsSecret || callStats !== null)
  10533. return;
  10534. callStats = new callstats($, io, jsSHA);
  10535. this.session = jingleSession;
  10536. this.peerconnection = jingleSession.peerconnection.peerconnection;
  10537. this.userID = APP.xmpp.myResource();
  10538. var location = window.location;
  10539. this.confID = location.protocol + "//" +
  10540. location.hostname + location.pathname;
  10541. //userID is generated or given by the origin server
  10542. callStats.initialize(config.callStatsID,
  10543. config.callStatsSecret,
  10544. this.userID,
  10545. initCallback);
  10546. var usage = callStats.fabricUsage.multiplex;
  10547. callStats.addNewFabric(this.peerconnection,
  10548. Strophe.getResourceFromJid(jingleSession.peerjid),
  10549. usage,
  10550. this.confID,
  10551. this.pcCallback.bind(this));
  10552. },
  10553. pcCallback: function (err, msg) {
  10554. if (!callStats)
  10555. return;
  10556. console.log("Monitoring status: "+ err + " msg: " + msg);
  10557. callStats.sendFabricEvent(this.peerconnection,
  10558. callStats.fabricEvent.fabricSetup, this.confID);
  10559. },
  10560. sendMuteEvent: function (mute, type) {
  10561. if (!callStats)
  10562. return;
  10563. var event = null;
  10564. if (type === "video") {
  10565. event = (mute? callStats.fabricEvent.videoPause :
  10566. callStats.fabricEvent.videoResume);
  10567. }
  10568. else {
  10569. event = (mute? callStats.fabricEvent.audioMute :
  10570. callStats.fabricEvent.audioUnmute);
  10571. }
  10572. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  10573. },
  10574. sendTerminateEvent: function () {
  10575. if(!callStats) {
  10576. return;
  10577. }
  10578. callStats.sendFabricEvent(this.peerconnection,
  10579. callStats.fabricEvent.fabricTerminated, this.confID);
  10580. },
  10581. sendSetupFailedEvent: function () {
  10582. if(!callStats) {
  10583. return;
  10584. }
  10585. callStats.sendFabricEvent(this.peerconnection,
  10586. callStats.fabricEvent.fabricSetupFailed, this.confID);
  10587. }
  10588. };
  10589. module.exports = CallStats;
  10590. },{"jssha":71,"socket.io-client":101}],49:[function(require,module,exports){
  10591. /* global config */
  10592. /**
  10593. * Provides statistics for the local stream.
  10594. */
  10595. var RTCBrowserType = require('../RTC/RTCBrowserType');
  10596. /**
  10597. * Size of the webaudio analyzer buffer.
  10598. * @type {number}
  10599. */
  10600. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  10601. /**
  10602. * Value of the webaudio analyzer smoothing time parameter.
  10603. * @type {number}
  10604. */
  10605. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  10606. /**
  10607. * Converts time domain data array to audio level.
  10608. * @param samples the time domain data array.
  10609. * @returns {number} the audio level
  10610. */
  10611. function timeDomainDataToAudioLevel(samples) {
  10612. var maxVolume = 0;
  10613. var length = samples.length;
  10614. for (var i = 0; i < length; i++) {
  10615. if (maxVolume < samples[i])
  10616. maxVolume = samples[i];
  10617. }
  10618. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  10619. }
  10620. /**
  10621. * Animates audio level change
  10622. * @param newLevel the new audio level
  10623. * @param lastLevel the last audio level
  10624. * @returns {Number} the audio level to be set
  10625. */
  10626. function animateLevel(newLevel, lastLevel) {
  10627. var value = 0;
  10628. var diff = lastLevel - newLevel;
  10629. if(diff > 0.2) {
  10630. value = lastLevel - 0.2;
  10631. }
  10632. else if(diff < -0.4) {
  10633. value = lastLevel + 0.4;
  10634. }
  10635. else {
  10636. value = newLevel;
  10637. }
  10638. return parseFloat(value.toFixed(3));
  10639. }
  10640. /**
  10641. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  10642. *
  10643. * @param stream the local stream
  10644. * @param interval stats refresh interval given in ms.
  10645. * @constructor
  10646. */
  10647. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  10648. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  10649. this.stream = stream;
  10650. this.intervalId = null;
  10651. this.intervalMilis = interval;
  10652. this.eventEmitter = eventEmitter;
  10653. this.audioLevel = 0;
  10654. this.statisticsService = statisticsService;
  10655. }
  10656. /**
  10657. * Starts the collecting the statistics.
  10658. */
  10659. LocalStatsCollector.prototype.start = function () {
  10660. if (config.disableAudioLevels || !window.AudioContext ||
  10661. RTCBrowserType.isTemasysPluginUsed())
  10662. return;
  10663. var context = new AudioContext();
  10664. var analyser = context.createAnalyser();
  10665. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  10666. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  10667. var source = context.createMediaStreamSource(this.stream);
  10668. source.connect(analyser);
  10669. var self = this;
  10670. this.intervalId = setInterval(
  10671. function () {
  10672. var array = new Uint8Array(analyser.frequencyBinCount);
  10673. analyser.getByteTimeDomainData(array);
  10674. var audioLevel = timeDomainDataToAudioLevel(array);
  10675. if (audioLevel != self.audioLevel) {
  10676. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10677. self.eventEmitter.emit(
  10678. "statistics.audioLevel",
  10679. self.statisticsService.LOCAL_JID,
  10680. self.audioLevel);
  10681. }
  10682. },
  10683. this.intervalMilis
  10684. );
  10685. };
  10686. /**
  10687. * Stops collecting the statistics.
  10688. */
  10689. LocalStatsCollector.prototype.stop = function () {
  10690. if (this.intervalId) {
  10691. clearInterval(this.intervalId);
  10692. this.intervalId = null;
  10693. }
  10694. };
  10695. module.exports = LocalStatsCollector;
  10696. },{"../RTC/RTCBrowserType":8}],50:[function(require,module,exports){
  10697. /* global require, ssrc2jid */
  10698. /* jshint -W117 */
  10699. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10700. /* Whether we support the browser we are running into for logging statistics */
  10701. var browserSupported = RTCBrowserType.isChrome() ||
  10702. RTCBrowserType.isOpera();
  10703. /**
  10704. * Calculates packet lost percent using the number of lost packets and the
  10705. * number of all packet.
  10706. * @param lostPackets the number of lost packets
  10707. * @param totalPackets the number of all packets.
  10708. * @returns {number} packet loss percent
  10709. */
  10710. function calculatePacketLoss(lostPackets, totalPackets) {
  10711. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  10712. return 0;
  10713. return Math.round((lostPackets/totalPackets)*100);
  10714. }
  10715. function getStatValue(item, name) {
  10716. var browserType = RTCBrowserType.getBrowserType();
  10717. if (!keyMap[browserType][name])
  10718. throw "The property isn't supported!";
  10719. var key = keyMap[browserType][name];
  10720. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  10721. item.stat(key) : item[key];
  10722. }
  10723. /**
  10724. * Peer statistics data holder.
  10725. * @constructor
  10726. */
  10727. function PeerStats()
  10728. {
  10729. this.ssrc2Loss = {};
  10730. this.ssrc2AudioLevel = {};
  10731. this.ssrc2bitrate = {};
  10732. this.ssrc2resolution = {};
  10733. }
  10734. /**
  10735. * The bandwidth
  10736. * @type {{}}
  10737. */
  10738. PeerStats.bandwidth = {};
  10739. /**
  10740. * The bit rate
  10741. * @type {{}}
  10742. */
  10743. PeerStats.bitrate = {};
  10744. /**
  10745. * The packet loss rate
  10746. * @type {{}}
  10747. */
  10748. PeerStats.packetLoss = null;
  10749. /**
  10750. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  10751. * represented by this instance.
  10752. * @param ssrc audio or video RTP stream SSRC.
  10753. * @param lossRate new packet loss rate value to be set.
  10754. */
  10755. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  10756. {
  10757. this.ssrc2Loss[ssrc] = lossRate;
  10758. };
  10759. /**
  10760. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  10761. * represented by this instance.
  10762. * @param ssrc audio or video RTP stream SSRC.
  10763. * @param resolution new resolution value to be set.
  10764. */
  10765. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  10766. {
  10767. if(resolution === null && this.ssrc2resolution[ssrc])
  10768. {
  10769. delete this.ssrc2resolution[ssrc];
  10770. }
  10771. else if(resolution !== null)
  10772. this.ssrc2resolution[ssrc] = resolution;
  10773. };
  10774. /**
  10775. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  10776. * represented by this instance.
  10777. * @param ssrc audio or video RTP stream SSRC.
  10778. * @param bitrate new bitrate value to be set.
  10779. */
  10780. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  10781. {
  10782. if(this.ssrc2bitrate[ssrc])
  10783. {
  10784. this.ssrc2bitrate[ssrc].download += bitrate.download;
  10785. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  10786. }
  10787. else {
  10788. this.ssrc2bitrate[ssrc] = bitrate;
  10789. }
  10790. };
  10791. /**
  10792. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  10793. * the stream which belongs to the peer represented by this instance.
  10794. * @param ssrc RTP stream SSRC for which current audio level value will be
  10795. * updated.
  10796. * @param audioLevel the new audio level value to be set. Value is truncated to
  10797. * fit the range from 0 to 1.
  10798. */
  10799. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  10800. {
  10801. // Range limit 0 - 1
  10802. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  10803. };
  10804. function formatAudioLevel(audioLevel) {
  10805. return Math.min(Math.max(audioLevel, 0), 1);
  10806. }
  10807. /**
  10808. * Array with the transport information.
  10809. * @type {Array}
  10810. */
  10811. PeerStats.transport = [];
  10812. /**
  10813. * <tt>StatsCollector</tt> registers for stats updates of given
  10814. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  10815. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  10816. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  10817. * instance as an event source.
  10818. *
  10819. * @param peerconnection webRTC peer connection object.
  10820. * @param interval stats refresh interval given in ms.
  10821. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  10822. * called on stats update.
  10823. * @constructor
  10824. */
  10825. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  10826. {
  10827. this.peerconnection = peerconnection;
  10828. this.baselineAudioLevelsReport = null;
  10829. this.currentAudioLevelsReport = null;
  10830. this.currentStatsReport = null;
  10831. this.baselineStatsReport = null;
  10832. this.audioLevelsIntervalId = null;
  10833. this.eventEmitter = eventEmitter;
  10834. /**
  10835. * Gather PeerConnection stats once every this many milliseconds.
  10836. */
  10837. this.GATHER_INTERVAL = 15000;
  10838. /**
  10839. * Log stats via the focus once every this many milliseconds.
  10840. */
  10841. this.LOG_INTERVAL = 60000;
  10842. /**
  10843. * Gather stats and store them in this.statsToBeLogged.
  10844. */
  10845. this.gatherStatsIntervalId = null;
  10846. /**
  10847. * Send the stats already saved in this.statsToBeLogged to be logged via
  10848. * the focus.
  10849. */
  10850. this.logStatsIntervalId = null;
  10851. /**
  10852. * Stores the statistics which will be send to the focus to be logged.
  10853. */
  10854. this.statsToBeLogged =
  10855. {
  10856. timestamps: [],
  10857. stats: {}
  10858. };
  10859. // Updates stats interval
  10860. this.audioLevelsIntervalMilis = audioLevelsInterval;
  10861. this.statsIntervalId = null;
  10862. this.statsIntervalMilis = statsInterval;
  10863. // Map of jids to PeerStats
  10864. this.jid2stats = {};
  10865. }
  10866. module.exports = StatsCollector;
  10867. /**
  10868. * Stops stats updates.
  10869. */
  10870. StatsCollector.prototype.stop = function () {
  10871. if (this.audioLevelsIntervalId) {
  10872. clearInterval(this.audioLevelsIntervalId);
  10873. this.audioLevelsIntervalId = null;
  10874. }
  10875. if (this.statsIntervalId)
  10876. {
  10877. clearInterval(this.statsIntervalId);
  10878. this.statsIntervalId = null;
  10879. }
  10880. if(this.logStatsIntervalId)
  10881. {
  10882. clearInterval(this.logStatsIntervalId);
  10883. this.logStatsIntervalId = null;
  10884. }
  10885. if(this.gatherStatsIntervalId)
  10886. {
  10887. clearInterval(this.gatherStatsIntervalId);
  10888. this.gatherStatsIntervalId = null;
  10889. }
  10890. };
  10891. /**
  10892. * Callback passed to <tt>getStats</tt> method.
  10893. * @param error an error that occurred on <tt>getStats</tt> call.
  10894. */
  10895. StatsCollector.prototype.errorCallback = function (error)
  10896. {
  10897. console.error("Get stats error", error);
  10898. this.stop();
  10899. };
  10900. /**
  10901. * Starts stats updates.
  10902. */
  10903. StatsCollector.prototype.start = function ()
  10904. {
  10905. var self = this;
  10906. if (!config.disableAudioLevels) {
  10907. this.audioLevelsIntervalId = setInterval(
  10908. function () {
  10909. // Interval updates
  10910. self.peerconnection.getStats(
  10911. function (report) {
  10912. var results = null;
  10913. if (!report || !report.result ||
  10914. typeof report.result != 'function') {
  10915. results = report;
  10916. }
  10917. else {
  10918. results = report.result();
  10919. }
  10920. //console.error("Got interval report", results);
  10921. self.currentAudioLevelsReport = results;
  10922. self.processAudioLevelReport();
  10923. self.baselineAudioLevelsReport =
  10924. self.currentAudioLevelsReport;
  10925. },
  10926. self.errorCallback
  10927. );
  10928. },
  10929. self.audioLevelsIntervalMilis
  10930. );
  10931. }
  10932. if (!config.disableStats && browserSupported) {
  10933. this.statsIntervalId = setInterval(
  10934. function () {
  10935. // Interval updates
  10936. self.peerconnection.getStats(
  10937. function (report) {
  10938. var results = null;
  10939. if (!report || !report.result ||
  10940. typeof report.result != 'function') {
  10941. //firefox
  10942. results = report;
  10943. }
  10944. else {
  10945. //chrome
  10946. results = report.result();
  10947. }
  10948. //console.error("Got interval report", results);
  10949. self.currentStatsReport = results;
  10950. try {
  10951. self.processStatsReport();
  10952. }
  10953. catch (e) {
  10954. console.error("Unsupported key:" + e, e);
  10955. }
  10956. self.baselineStatsReport = self.currentStatsReport;
  10957. },
  10958. self.errorCallback
  10959. );
  10960. },
  10961. self.statsIntervalMilis
  10962. );
  10963. }
  10964. if (config.logStats && browserSupported) {
  10965. this.gatherStatsIntervalId = setInterval(
  10966. function () {
  10967. self.peerconnection.getStats(
  10968. function (report) {
  10969. self.addStatsToBeLogged(report.result());
  10970. },
  10971. function () {
  10972. }
  10973. );
  10974. },
  10975. this.GATHER_INTERVAL
  10976. );
  10977. this.logStatsIntervalId = setInterval(
  10978. function() { self.logStats(); },
  10979. this.LOG_INTERVAL);
  10980. }
  10981. };
  10982. /**
  10983. * Checks whether a certain record should be included in the logged statistics.
  10984. */
  10985. function acceptStat(reportId, reportType, statName) {
  10986. if (reportType == "googCandidatePair" && statName == "googChannelId")
  10987. return false;
  10988. if (reportType == "ssrc") {
  10989. if (statName == "googTrackId" ||
  10990. statName == "transportId" ||
  10991. statName == "ssrc")
  10992. return false;
  10993. }
  10994. return true;
  10995. }
  10996. /**
  10997. * Checks whether a certain record should be included in the logged statistics.
  10998. */
  10999. function acceptReport(id, type) {
  11000. if (id.substring(0, 15) == "googCertificate" ||
  11001. id.substring(0, 9) == "googTrack" ||
  11002. id.substring(0, 20) == "googLibjingleSession")
  11003. return false;
  11004. if (type == "googComponent")
  11005. return false;
  11006. return true;
  11007. }
  11008. /**
  11009. * Converts the stats to the format used for logging, and saves the data in
  11010. * this.statsToBeLogged.
  11011. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  11012. */
  11013. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  11014. var self = this;
  11015. var num_records = this.statsToBeLogged.timestamps.length;
  11016. this.statsToBeLogged.timestamps.push(new Date().getTime());
  11017. reports.map(function (report) {
  11018. if (!acceptReport(report.id, report.type))
  11019. return;
  11020. var stat = self.statsToBeLogged.stats[report.id];
  11021. if (!stat) {
  11022. stat = self.statsToBeLogged.stats[report.id] = {};
  11023. }
  11024. stat.type = report.type;
  11025. report.names().map(function (name) {
  11026. if (!acceptStat(report.id, report.type, name))
  11027. return;
  11028. var values = stat[name];
  11029. if (!values) {
  11030. values = stat[name] = [];
  11031. }
  11032. while (values.length < num_records) {
  11033. values.push(null);
  11034. }
  11035. values.push(report.stat(name));
  11036. });
  11037. });
  11038. };
  11039. StatsCollector.prototype.logStats = function () {
  11040. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  11041. return;
  11042. // Reset the stats
  11043. this.statsToBeLogged.stats = {};
  11044. this.statsToBeLogged.timestamps = [];
  11045. };
  11046. var keyMap = {};
  11047. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  11048. "ssrc": "ssrc",
  11049. "packetsReceived": "packetsReceived",
  11050. "packetsLost": "packetsLost",
  11051. "packetsSent": "packetsSent",
  11052. "bytesReceived": "bytesReceived",
  11053. "bytesSent": "bytesSent"
  11054. };
  11055. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  11056. "receiveBandwidth": "googAvailableReceiveBandwidth",
  11057. "sendBandwidth": "googAvailableSendBandwidth",
  11058. "remoteAddress": "googRemoteAddress",
  11059. "transportType": "googTransportType",
  11060. "localAddress": "googLocalAddress",
  11061. "activeConnection": "googActiveConnection",
  11062. "ssrc": "ssrc",
  11063. "packetsReceived": "packetsReceived",
  11064. "packetsSent": "packetsSent",
  11065. "packetsLost": "packetsLost",
  11066. "bytesReceived": "bytesReceived",
  11067. "bytesSent": "bytesSent",
  11068. "googFrameHeightReceived": "googFrameHeightReceived",
  11069. "googFrameWidthReceived": "googFrameWidthReceived",
  11070. "googFrameHeightSent": "googFrameHeightSent",
  11071. "googFrameWidthSent": "googFrameWidthSent",
  11072. "audioInputLevel": "audioInputLevel",
  11073. "audioOutputLevel": "audioOutputLevel"
  11074. };
  11075. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  11076. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  11077. /**
  11078. * Stats processing logic.
  11079. */
  11080. StatsCollector.prototype.processStatsReport = function () {
  11081. if (!this.baselineStatsReport) {
  11082. return;
  11083. }
  11084. for (var idx in this.currentStatsReport) {
  11085. var now = this.currentStatsReport[idx];
  11086. try {
  11087. if (getStatValue(now, 'receiveBandwidth') ||
  11088. getStatValue(now, 'sendBandwidth')) {
  11089. PeerStats.bandwidth = {
  11090. "download": Math.round(
  11091. (getStatValue(now, 'receiveBandwidth')) / 1000),
  11092. "upload": Math.round(
  11093. (getStatValue(now, 'sendBandwidth')) / 1000)
  11094. };
  11095. }
  11096. }
  11097. catch(e){/*not supported*/}
  11098. if(now.type == 'googCandidatePair')
  11099. {
  11100. var ip, type, localIP, active;
  11101. try {
  11102. ip = getStatValue(now, 'remoteAddress');
  11103. type = getStatValue(now, "transportType");
  11104. localIP = getStatValue(now, "localAddress");
  11105. active = getStatValue(now, "activeConnection");
  11106. }
  11107. catch(e){/*not supported*/}
  11108. if(!ip || !type || !localIP || active != "true")
  11109. continue;
  11110. var addressSaved = false;
  11111. for(var i = 0; i < PeerStats.transport.length; i++)
  11112. {
  11113. if(PeerStats.transport[i].ip == ip &&
  11114. PeerStats.transport[i].type == type &&
  11115. PeerStats.transport[i].localip == localIP)
  11116. {
  11117. addressSaved = true;
  11118. }
  11119. }
  11120. if(addressSaved)
  11121. continue;
  11122. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  11123. continue;
  11124. }
  11125. if(now.type == "candidatepair")
  11126. {
  11127. if(now.state == "succeeded")
  11128. continue;
  11129. var local = this.currentStatsReport[now.localCandidateId];
  11130. var remote = this.currentStatsReport[now.remoteCandidateId];
  11131. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  11132. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  11133. }
  11134. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  11135. now.type != "inboundrtp") {
  11136. continue;
  11137. }
  11138. var before = this.baselineStatsReport[idx];
  11139. if (!before) {
  11140. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11141. continue;
  11142. }
  11143. var ssrc = getStatValue(now, 'ssrc');
  11144. if(!ssrc)
  11145. continue;
  11146. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11147. if (!jid && (Date.now() - now.timestamp) < 3000) {
  11148. console.warn("No jid for ssrc: " + ssrc);
  11149. continue;
  11150. }
  11151. var jidStats = this.jid2stats[jid];
  11152. if (!jidStats) {
  11153. jidStats = new PeerStats();
  11154. this.jid2stats[jid] = jidStats;
  11155. }
  11156. var isDownloadStream = true;
  11157. var key = 'packetsReceived';
  11158. if (!getStatValue(now, key))
  11159. {
  11160. isDownloadStream = false;
  11161. key = 'packetsSent';
  11162. if (!getStatValue(now, key))
  11163. {
  11164. console.warn("No packetsReceived nor packetSent stat found");
  11165. continue;
  11166. }
  11167. }
  11168. var packetsNow = getStatValue(now, key);
  11169. if(!packetsNow || packetsNow < 0)
  11170. packetsNow = 0;
  11171. var packetsBefore = getStatValue(before, key);
  11172. if(!packetsBefore || packetsBefore < 0)
  11173. packetsBefore = 0;
  11174. var packetRate = packetsNow - packetsBefore;
  11175. if(!packetRate || packetRate < 0)
  11176. packetRate = 0;
  11177. var currentLoss = getStatValue(now, 'packetsLost');
  11178. if(!currentLoss || currentLoss < 0)
  11179. currentLoss = 0;
  11180. var previousLoss = getStatValue(before, 'packetsLost');
  11181. if(!previousLoss || previousLoss < 0)
  11182. previousLoss = 0;
  11183. var lossRate = currentLoss - previousLoss;
  11184. if(!lossRate || lossRate < 0)
  11185. lossRate = 0;
  11186. var packetsTotal = (packetRate + lossRate);
  11187. jidStats.setSsrcLoss(ssrc,
  11188. {"packetsTotal": packetsTotal,
  11189. "packetsLost": lossRate,
  11190. "isDownloadStream": isDownloadStream});
  11191. var bytesReceived = 0, bytesSent = 0;
  11192. if(getStatValue(now, "bytesReceived"))
  11193. {
  11194. bytesReceived = getStatValue(now, "bytesReceived") -
  11195. getStatValue(before, "bytesReceived");
  11196. }
  11197. if(getStatValue(now, "bytesSent"))
  11198. {
  11199. bytesSent = getStatValue(now, "bytesSent") -
  11200. getStatValue(before, "bytesSent");
  11201. }
  11202. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  11203. if(bytesReceived <= 0 || time <= 0)
  11204. {
  11205. bytesReceived = 0;
  11206. }
  11207. else
  11208. {
  11209. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  11210. }
  11211. if(bytesSent <= 0 || time <= 0)
  11212. {
  11213. bytesSent = 0;
  11214. }
  11215. else
  11216. {
  11217. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  11218. }
  11219. jidStats.setSsrcBitrate(ssrc, {
  11220. "download": bytesReceived,
  11221. "upload": bytesSent});
  11222. var resolution = {height: null, width: null};
  11223. try {
  11224. if (getStatValue(now, "googFrameHeightReceived") &&
  11225. getStatValue(now, "googFrameWidthReceived")) {
  11226. resolution.height = getStatValue(now, "googFrameHeightReceived");
  11227. resolution.width = getStatValue(now, "googFrameWidthReceived");
  11228. }
  11229. else if (getStatValue(now, "googFrameHeightSent") &&
  11230. getStatValue(now, "googFrameWidthSent")) {
  11231. resolution.height = getStatValue(now, "googFrameHeightSent");
  11232. resolution.width = getStatValue(now, "googFrameWidthSent");
  11233. }
  11234. }
  11235. catch(e){/*not supported*/}
  11236. if(resolution.height && resolution.width)
  11237. {
  11238. jidStats.setSsrcResolution(ssrc, resolution);
  11239. }
  11240. else
  11241. {
  11242. jidStats.setSsrcResolution(ssrc, null);
  11243. }
  11244. }
  11245. var self = this;
  11246. // Jid stats
  11247. var totalPackets = {download: 0, upload: 0};
  11248. var lostPackets = {download: 0, upload: 0};
  11249. var bitrateDownload = 0;
  11250. var bitrateUpload = 0;
  11251. var resolutions = {};
  11252. Object.keys(this.jid2stats).forEach(
  11253. function (jid)
  11254. {
  11255. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  11256. function (ssrc)
  11257. {
  11258. var type = "upload";
  11259. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  11260. type = "download";
  11261. totalPackets[type] +=
  11262. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  11263. lostPackets[type] +=
  11264. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  11265. }
  11266. );
  11267. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  11268. function (ssrc) {
  11269. bitrateDownload +=
  11270. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  11271. bitrateUpload +=
  11272. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  11273. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  11274. }
  11275. );
  11276. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  11277. }
  11278. );
  11279. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  11280. PeerStats.packetLoss = {
  11281. total:
  11282. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  11283. totalPackets.download + totalPackets.upload),
  11284. download:
  11285. calculatePacketLoss(lostPackets.download, totalPackets.download),
  11286. upload:
  11287. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  11288. };
  11289. this.eventEmitter.emit("statistics.connectionstats",
  11290. {
  11291. "bitrate": PeerStats.bitrate,
  11292. "packetLoss": PeerStats.packetLoss,
  11293. "bandwidth": PeerStats.bandwidth,
  11294. "resolution": resolutions,
  11295. "transport": PeerStats.transport
  11296. });
  11297. PeerStats.transport = [];
  11298. };
  11299. /**
  11300. * Stats processing logic.
  11301. */
  11302. StatsCollector.prototype.processAudioLevelReport = function () {
  11303. if (!this.baselineAudioLevelsReport) {
  11304. return;
  11305. }
  11306. for (var idx in this.currentAudioLevelsReport) {
  11307. var now = this.currentAudioLevelsReport[idx];
  11308. if (now.type != 'ssrc') {
  11309. continue;
  11310. }
  11311. var before = this.baselineAudioLevelsReport[idx];
  11312. if (!before) {
  11313. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11314. continue;
  11315. }
  11316. var ssrc = getStatValue(now, 'ssrc');
  11317. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11318. if (!jid) {
  11319. if((Date.now() - now.timestamp) < 3000)
  11320. console.warn("No jid for ssrc: " + ssrc);
  11321. continue;
  11322. }
  11323. var jidStats = this.jid2stats[jid];
  11324. if (!jidStats) {
  11325. jidStats = new PeerStats();
  11326. this.jid2stats[jid] = jidStats;
  11327. }
  11328. // Audio level
  11329. var audioLevel = null;
  11330. try {
  11331. audioLevel = getStatValue(now, 'audioInputLevel');
  11332. if (!audioLevel)
  11333. audioLevel = getStatValue(now, 'audioOutputLevel');
  11334. }
  11335. catch(e) {/*not supported*/
  11336. console.warn("Audio Levels are not available in the statistics.");
  11337. clearInterval(this.audioLevelsIntervalId);
  11338. return;
  11339. }
  11340. if (audioLevel) {
  11341. // TODO: can't find specs about what this value really is,
  11342. // but it seems to vary between 0 and around 32k.
  11343. audioLevel = audioLevel / 32767;
  11344. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  11345. if(jid != APP.xmpp.myJid())
  11346. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  11347. }
  11348. }
  11349. };
  11350. },{"../RTC/RTCBrowserType":8}],51:[function(require,module,exports){
  11351. /* global require, APP */
  11352. /**
  11353. * Created by hristo on 8/4/14.
  11354. */
  11355. var LocalStats = require("./LocalStatsCollector.js");
  11356. var RTPStats = require("./RTPStatsCollector.js");
  11357. var EventEmitter = require("events");
  11358. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  11359. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11360. var CallStats = require("./CallStats");
  11361. var RTCEvents = require("../../service/RTC/RTCEvents");
  11362. var eventEmitter = new EventEmitter();
  11363. var localStats = null;
  11364. var rtpStats = null;
  11365. function stopLocal() {
  11366. if (localStats) {
  11367. localStats.stop();
  11368. localStats = null;
  11369. }
  11370. }
  11371. function stopRemote() {
  11372. if (rtpStats) {
  11373. rtpStats.stop();
  11374. eventEmitter.emit("statistics.stop");
  11375. rtpStats = null;
  11376. }
  11377. }
  11378. function startRemoteStats (peerconnection) {
  11379. if (rtpStats) {
  11380. rtpStats.stop();
  11381. }
  11382. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  11383. rtpStats.start();
  11384. }
  11385. function onStreamCreated(stream) {
  11386. if(stream.getOriginalStream().getAudioTracks().length === 0) {
  11387. return;
  11388. }
  11389. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  11390. eventEmitter);
  11391. localStats.start();
  11392. }
  11393. function onDisposeConference(onUnload) {
  11394. CallStats.sendTerminateEvent();
  11395. stopRemote();
  11396. if(onUnload) {
  11397. stopLocal();
  11398. eventEmitter.removeAllListeners();
  11399. }
  11400. }
  11401. var statistics = {
  11402. /**
  11403. * Indicates that this audio level is for local jid.
  11404. * @type {string}
  11405. */
  11406. LOCAL_JID: 'local',
  11407. addAudioLevelListener: function(listener)
  11408. {
  11409. eventEmitter.on("statistics.audioLevel", listener);
  11410. },
  11411. removeAudioLevelListener: function(listener)
  11412. {
  11413. eventEmitter.removeListener("statistics.audioLevel", listener);
  11414. },
  11415. addConnectionStatsListener: function(listener)
  11416. {
  11417. eventEmitter.on("statistics.connectionstats", listener);
  11418. },
  11419. removeConnectionStatsListener: function(listener)
  11420. {
  11421. eventEmitter.removeListener("statistics.connectionstats", listener);
  11422. },
  11423. addRemoteStatsStopListener: function(listener)
  11424. {
  11425. eventEmitter.on("statistics.stop", listener);
  11426. },
  11427. removeRemoteStatsStopListener: function(listener)
  11428. {
  11429. eventEmitter.removeListener("statistics.stop", listener);
  11430. },
  11431. stop: function () {
  11432. stopLocal();
  11433. stopRemote();
  11434. if(eventEmitter)
  11435. {
  11436. eventEmitter.removeAllListeners();
  11437. }
  11438. },
  11439. stopRemoteStatistics: function()
  11440. {
  11441. stopRemote();
  11442. },
  11443. start: function () {
  11444. APP.RTC.addStreamListener(onStreamCreated,
  11445. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  11446. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  11447. //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  11448. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  11449. startRemoteStats(event.peerconnection);
  11450. // CallStats.init(event);
  11451. });
  11452. APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  11453. CallStats.init(session);
  11454. });
  11455. APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  11456. CallStats.sendMuteEvent(mute, "audio");
  11457. });
  11458. APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  11459. CallStats.sendSetupFailedEvent();
  11460. });
  11461. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  11462. CallStats.sendMuteEvent(mute, "video");
  11463. });
  11464. }
  11465. };
  11466. module.exports = statistics;
  11467. },{"../../service/RTC/RTCEvents":152,"../../service/RTC/StreamEventTypes.js":154,"../../service/xmpp/XMPPEvents":161,"./CallStats":48,"./LocalStatsCollector.js":49,"./RTPStatsCollector.js":50,"events":162}],52:[function(require,module,exports){
  11468. /* global $, require, config, interfaceConfig */
  11469. var i18n = require("i18next-client");
  11470. var languages = require("../../service/translation/languages");
  11471. var Settings = require("../settings/Settings");
  11472. var DEFAULT_LANG = languages.EN;
  11473. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  11474. return value.replace("__app__", interfaceConfig.APP_NAME);
  11475. });
  11476. var defaultOptions = {
  11477. detectLngQS: "lang",
  11478. useCookie: false,
  11479. fallbackLng: DEFAULT_LANG,
  11480. load: "unspecific",
  11481. resGetPath: 'lang/__ns__-__lng__.json',
  11482. ns: {
  11483. namespaces: ['main', 'languages'],
  11484. defaultNs: 'main'
  11485. },
  11486. lngWhitelist : languages.getLanguages(),
  11487. fallbackOnNull: true,
  11488. fallbackOnEmpty: true,
  11489. useDataAttrOptions: true,
  11490. app: interfaceConfig.APP_NAME,
  11491. getAsync: false,
  11492. defaultValueFromContent: false,
  11493. customLoad: function(lng, ns, options, done) {
  11494. var resPath = "lang/__ns__-__lng__.json";
  11495. if(lng === languages.EN)
  11496. resPath = "lang/__ns__.json";
  11497. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  11498. i18n.functions.ajax({
  11499. url: url,
  11500. success: function(data, status, xhr) {
  11501. i18n.functions.log('loaded: ' + url);
  11502. done(null, data);
  11503. },
  11504. error : function(xhr, status, error) {
  11505. if ((status && status == 200) ||
  11506. (xhr && xhr.status && xhr.status == 200)) {
  11507. // file loaded but invalid json, stop waste time !
  11508. i18n.functions.error('There is a typo in: ' + url);
  11509. } else if ((status && status == 404) ||
  11510. (xhr && xhr.status && xhr.status == 404)) {
  11511. i18n.functions.log('Does not exist: ' + url);
  11512. } else {
  11513. var theStatus = status ? status :
  11514. ((xhr && xhr.status) ? xhr.status : null);
  11515. i18n.functions.log(theStatus + ' when loading ' + url);
  11516. }
  11517. done(error, {});
  11518. },
  11519. dataType: "json",
  11520. async : options.getAsync
  11521. });
  11522. }
  11523. // options for caching
  11524. // useLocalStorage: true,
  11525. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  11526. };
  11527. function initCompleted(t) {
  11528. $("[data-i18n]").i18n();
  11529. }
  11530. function checkForParameter() {
  11531. var query = window.location.search.substring(1);
  11532. var vars = query.split("&");
  11533. for (var i=0;i<vars.length;i++) {
  11534. var pair = vars[i].split("=");
  11535. if(pair[0] == "lang")
  11536. {
  11537. return pair[1];
  11538. }
  11539. }
  11540. return null;
  11541. }
  11542. module.exports = {
  11543. init: function (lang) {
  11544. var options = defaultOptions;
  11545. if(!lang)
  11546. {
  11547. lang = checkForParameter();
  11548. if(!lang)
  11549. {
  11550. var settings = Settings.getSettings();
  11551. if(settings)
  11552. lang = settings.language;
  11553. if(!lang && config.defaultLanguage)
  11554. {
  11555. lang = config.defaultLanguage;
  11556. }
  11557. }
  11558. }
  11559. if(lang) {
  11560. options.lng = lang;
  11561. }
  11562. i18n.init(options, initCompleted);
  11563. },
  11564. translateString: function (key, options) {
  11565. return i18n.t(key, options);
  11566. },
  11567. setLanguage: function (lang) {
  11568. if(!lang)
  11569. lang = DEFAULT_LANG;
  11570. i18n.setLng(lang, defaultOptions, initCompleted);
  11571. },
  11572. getCurrentLanguage: function () {
  11573. return i18n.lng();
  11574. },
  11575. translateElement: function (selector) {
  11576. selector.i18n();
  11577. },
  11578. generateTranslationHTML: function (key, options) {
  11579. var str = "<span data-i18n=\"" + key + "\"";
  11580. if(options)
  11581. {
  11582. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  11583. }
  11584. str += ">";
  11585. str += this.translateString(key, options);
  11586. str += "</span>";
  11587. return str;
  11588. }
  11589. };
  11590. },{"../../service/translation/languages":160,"../settings/Settings":47,"i18next-client":70}],53:[function(require,module,exports){
  11591. /*
  11592. * JingleSession provides an API to manage a single Jingle session. We will
  11593. * have different implementations depending on the underlying interface used
  11594. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  11595. */
  11596. function JingleSession(me, sid, connection, service, eventEmitter) {
  11597. /**
  11598. * Our JID.
  11599. */
  11600. this.me = me;
  11601. /**
  11602. * The Jingle session identifier.
  11603. */
  11604. this.sid = sid;
  11605. /**
  11606. * The XMPP connection.
  11607. */
  11608. this.connection = connection;
  11609. /**
  11610. * The XMPP service.
  11611. */
  11612. this.service = service;
  11613. /**
  11614. * The event emitter.
  11615. */
  11616. this.eventEmitter = eventEmitter;
  11617. /**
  11618. * Whether to use dripping or not. Dripping is sending trickle candidates
  11619. * not one-by-one.
  11620. * Note: currently we do not support 'false'.
  11621. */
  11622. this.usedrip = true;
  11623. /**
  11624. * When dripping is used, stores ICE candidates which are to be sent.
  11625. */
  11626. this.drip_container = [];
  11627. // Media constraints. Is this WebRTC only?
  11628. this.media_constraints = null;
  11629. // ICE servers config (RTCConfiguration?).
  11630. this.ice_config = {};
  11631. }
  11632. /**
  11633. * Prepares this object to initiate a session.
  11634. * @param peerjid the JID of the remote peer.
  11635. * @param isInitiator whether we will be the Jingle initiator.
  11636. * @param media_constraints
  11637. * @param ice_config
  11638. */
  11639. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  11640. media_constraints, ice_config) {
  11641. this.media_constraints = media_constraints;
  11642. this.ice_config = ice_config;
  11643. if (this.state !== null) {
  11644. console.error('attempt to initiate on session ' + this.sid +
  11645. 'in state ' + this.state);
  11646. return;
  11647. }
  11648. this.state = 'pending';
  11649. this.initiator = isInitiator ? this.me : peerjid;
  11650. this.responder = !isInitiator ? this.me : peerjid;
  11651. this.peerjid = peerjid;
  11652. this.doInitialize();
  11653. };
  11654. /**
  11655. * Finishes initialization.
  11656. */
  11657. JingleSession.prototype.doInitialize = function() {};
  11658. /**
  11659. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  11660. * Note: currently only used on transport-info
  11661. */
  11662. JingleSession.prototype.addIceCandidates = function(contents) {};
  11663. /**
  11664. * Handles an 'add-source' event.
  11665. *
  11666. * @param contents an array of Jingle 'content' elements.
  11667. */
  11668. JingleSession.prototype.addSources = function(contents) {};
  11669. /**
  11670. * Handles a 'remove-source' event.
  11671. *
  11672. * @param contents an array of Jingle 'content' elements.
  11673. */
  11674. JingleSession.prototype.removeSources = function(contents) {};
  11675. /**
  11676. * Terminates this Jingle session (stops sending media and closes the streams?)
  11677. */
  11678. JingleSession.prototype.terminate = function() {};
  11679. /**
  11680. * Sends a Jingle session-terminate message to the peer and terminates the
  11681. * session.
  11682. * @param reason
  11683. * @param text
  11684. */
  11685. JingleSession.prototype.sendTerminate = function(reason, text) {};
  11686. /**
  11687. * Handles an offer from the remote peer (prepares to accept a session).
  11688. * @param jingle the 'jingle' XML element.
  11689. */
  11690. JingleSession.prototype.setOffer = function(jingle) {};
  11691. /**
  11692. * Handles an answer from the remote peer (prepares to accept a session).
  11693. * @param jingle the 'jingle' XML element.
  11694. */
  11695. JingleSession.prototype.setAnswer = function(jingle) {};
  11696. module.exports = JingleSession;
  11697. },{}],54:[function(require,module,exports){
  11698. /* jshint -W117 */
  11699. var JingleSession = require("./JingleSession");
  11700. var TraceablePeerConnection = require("./TraceablePeerConnection");
  11701. var SDPDiffer = require("./SDPDiffer");
  11702. var SDPUtil = require("./SDPUtil");
  11703. var SDP = require("./SDP");
  11704. var async = require("async");
  11705. var transform = require("sdp-transform");
  11706. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11707. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11708. var SSRCReplacement = require("./LocalSSRCReplacement");
  11709. // Jingle stuff
  11710. function JingleSessionPC(me, sid, connection, service, eventEmitter) {
  11711. JingleSession.call(this, me, sid, connection, service, eventEmitter);
  11712. this.initiator = null;
  11713. this.responder = null;
  11714. this.peerjid = null;
  11715. this.state = null;
  11716. this.localSDP = null;
  11717. this.remoteSDP = null;
  11718. this.relayedStreams = [];
  11719. this.pc_constraints = null;
  11720. this.usetrickle = true;
  11721. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  11722. this.hadstuncandidate = false;
  11723. this.hadturncandidate = false;
  11724. this.lasticecandidate = false;
  11725. this.statsinterval = null;
  11726. this.reason = null;
  11727. this.addssrc = [];
  11728. this.removessrc = [];
  11729. this.pendingop = null;
  11730. this.switchstreams = false;
  11731. this.wait = true;
  11732. this.localStreamsSSRC = null;
  11733. this.ssrcOwners = {};
  11734. this.ssrcVideoTypes = {};
  11735. this.eventEmitter = eventEmitter;
  11736. /**
  11737. * The indicator which determines whether the (local) video has been muted
  11738. * in response to a user command in contrast to an automatic decision made
  11739. * by the application logic.
  11740. */
  11741. this.videoMuteByUser = false;
  11742. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  11743. // We start with the queue paused. We resume it when the signaling state is
  11744. // stable and the ice connection state is connected.
  11745. this.modifySourcesQueue.pause();
  11746. }
  11747. JingleSessionPC.prototype = JingleSession.prototype;
  11748. JingleSessionPC.prototype.constructor = JingleSessionPC;
  11749. JingleSessionPC.prototype.setOffer = function(offer) {
  11750. this.setRemoteDescription(offer, 'offer');
  11751. };
  11752. JingleSessionPC.prototype.setAnswer = function(answer) {
  11753. this.setRemoteDescription(answer, 'answer');
  11754. };
  11755. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  11756. var signalingState = this.peerconnection.signalingState;
  11757. var iceConnectionState = this.peerconnection.iceConnectionState;
  11758. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  11759. this.modifySourcesQueue.resume();
  11760. } else {
  11761. this.modifySourcesQueue.pause();
  11762. }
  11763. };
  11764. JingleSessionPC.prototype.doInitialize = function () {
  11765. var self = this;
  11766. this.hadstuncandidate = false;
  11767. this.hadturncandidate = false;
  11768. this.lasticecandidate = false;
  11769. this.isreconnect = false;
  11770. this.peerconnection = new TraceablePeerConnection(
  11771. this.connection.jingle.ice_config,
  11772. this.connection.jingle.pc_constraints,
  11773. this);
  11774. this.peerconnection.onicecandidate = function (event) {
  11775. self.sendIceCandidate(event.candidate);
  11776. };
  11777. this.peerconnection.onaddstream = function (event) {
  11778. if (event.stream.id !== 'default') {
  11779. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  11780. self.remoteStreamAdded(event);
  11781. } else {
  11782. // This is a recvonly stream. Clients that implement Unified Plan,
  11783. // such as Firefox use recvonly "streams/channels/tracks" for
  11784. // receiving remote stream/tracks, as opposed to Plan B where there
  11785. // are only 3 channels: audio, video and data.
  11786. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  11787. }
  11788. };
  11789. this.peerconnection.onremovestream = function (event) {
  11790. // Remove the stream from remoteStreams
  11791. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  11792. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  11793. };
  11794. this.peerconnection.onsignalingstatechange = function (event) {
  11795. if (!(self && self.peerconnection)) return;
  11796. self.updateModifySourcesQueue();
  11797. };
  11798. /**
  11799. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  11800. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  11801. * RTCPeerConnection.iceConnectionState changes.
  11802. *
  11803. * @param event the event containing information about the change
  11804. */
  11805. this.peerconnection.oniceconnectionstatechange = function (event) {
  11806. if (!(self && self.peerconnection)) return;
  11807. self.updateModifySourcesQueue();
  11808. switch (self.peerconnection.iceConnectionState) {
  11809. case 'connected':
  11810. // Informs interested parties that the connection has been restored.
  11811. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  11812. self.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  11813. self.isreconnect = false;
  11814. break;
  11815. case 'disconnected':
  11816. self.isreconnect = true;
  11817. // Informs interested parties that the connection has been interrupted.
  11818. if (self.peerconnection.signalingState === 'stable')
  11819. self.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  11820. break;
  11821. case 'failed':
  11822. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11823. break;
  11824. }
  11825. onIceConnectionStateChange(self.sid, self);
  11826. };
  11827. this.peerconnection.onnegotiationneeded = function (event) {
  11828. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  11829. };
  11830. // add any local and relayed stream
  11831. APP.RTC.localStreams.forEach(function(stream) {
  11832. self.peerconnection.addStream(stream.getOriginalStream());
  11833. });
  11834. this.relayedStreams.forEach(function(stream) {
  11835. self.peerconnection.addStream(stream);
  11836. });
  11837. };
  11838. function onIceConnectionStateChange(sid, session) {
  11839. switch (session.peerconnection.iceConnectionState) {
  11840. case 'checking':
  11841. session.timeChecking = (new Date()).getTime();
  11842. session.firstconnect = true;
  11843. break;
  11844. case 'completed': // on caller side
  11845. case 'connected':
  11846. if (session.firstconnect) {
  11847. session.firstconnect = false;
  11848. var metadata = {};
  11849. metadata.setupTime
  11850. = (new Date()).getTime() - session.timeChecking;
  11851. session.peerconnection.getStats(function (res) {
  11852. if(res && res.result) {
  11853. res.result().forEach(function (report) {
  11854. if (report.type == 'googCandidatePair' &&
  11855. report.stat('googActiveConnection') == 'true') {
  11856. metadata.localCandidateType
  11857. = report.stat('googLocalCandidateType');
  11858. metadata.remoteCandidateType
  11859. = report.stat('googRemoteCandidateType');
  11860. // log pair as well so we can get nice pie
  11861. // charts
  11862. metadata.candidatePair
  11863. = report.stat('googLocalCandidateType') +
  11864. ';' +
  11865. report.stat('googRemoteCandidateType');
  11866. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  11867. {
  11868. metadata.ipv6 = true;
  11869. }
  11870. }
  11871. });
  11872. }
  11873. });
  11874. }
  11875. break;
  11876. }
  11877. }
  11878. JingleSessionPC.prototype.accept = function () {
  11879. this.state = 'active';
  11880. var pranswer = this.peerconnection.localDescription;
  11881. if (!pranswer || pranswer.type != 'pranswer') {
  11882. return;
  11883. }
  11884. console.log('going from pranswer to answer');
  11885. if (this.usetrickle) {
  11886. // remove candidates already sent from session-accept
  11887. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  11888. for (var i = 0; i < lines.length; i++) {
  11889. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  11890. }
  11891. }
  11892. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  11893. // FIXME: change any inactive to sendrecv or whatever they were originally
  11894. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  11895. }
  11896. var prsdp = new SDP(pranswer.sdp);
  11897. var accept = $iq({to: this.peerjid,
  11898. type: 'set'})
  11899. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11900. action: 'session-accept',
  11901. initiator: this.initiator,
  11902. responder: this.responder,
  11903. sid: this.sid });
  11904. // FIXME why do we generate session-accept in 3 different places ?
  11905. prsdp.toJingle(
  11906. accept,
  11907. this.initiator == this.me ? 'initiator' : 'responder',
  11908. this.localStreamsSSRC);
  11909. var sdp = this.peerconnection.localDescription.sdp;
  11910. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  11911. // FIXME: change any inactive to sendrecv or whatever they were originally
  11912. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  11913. }
  11914. var self = this;
  11915. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  11916. function () {
  11917. //console.log('setLocalDescription success');
  11918. self.setLocalDescription();
  11919. SSRCReplacement.processSessionInit(accept);
  11920. self.connection.sendIQ(accept,
  11921. function () {
  11922. var ack = {};
  11923. ack.source = 'answer';
  11924. $(document).trigger('ack.jingle', [self.sid, ack]);
  11925. },
  11926. function (stanza) {
  11927. var error = ($(stanza).find('error').length) ? {
  11928. code: $(stanza).find('error').attr('code'),
  11929. reason: $(stanza).find('error :first')[0].tagName
  11930. }:{};
  11931. error.source = 'answer';
  11932. JingleSessionPC.onJingleError(self.sid, error);
  11933. },
  11934. 10000);
  11935. },
  11936. function (e) {
  11937. console.error('setLocalDescription failed', e);
  11938. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11939. }
  11940. );
  11941. };
  11942. JingleSessionPC.prototype.terminate = function (reason) {
  11943. this.state = 'ended';
  11944. this.reason = reason;
  11945. this.peerconnection.close();
  11946. if (this.statsinterval !== null) {
  11947. window.clearInterval(this.statsinterval);
  11948. this.statsinterval = null;
  11949. }
  11950. };
  11951. JingleSessionPC.prototype.active = function () {
  11952. return this.state == 'active';
  11953. };
  11954. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  11955. var self = this;
  11956. if (candidate && !this.lasticecandidate) {
  11957. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  11958. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  11959. if (!(ice && jcand)) {
  11960. console.error('failed to get ice && jcand');
  11961. return;
  11962. }
  11963. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11964. if (jcand.type === 'srflx') {
  11965. this.hadstuncandidate = true;
  11966. } else if (jcand.type === 'relay') {
  11967. this.hadturncandidate = true;
  11968. }
  11969. if (this.usetrickle) {
  11970. if (this.usedrip) {
  11971. if (this.drip_container.length === 0) {
  11972. // start 20ms callout
  11973. window.setTimeout(function () {
  11974. if (self.drip_container.length === 0) return;
  11975. self.sendIceCandidates(self.drip_container);
  11976. self.drip_container = [];
  11977. }, 20);
  11978. }
  11979. this.drip_container.push(candidate);
  11980. return;
  11981. } else {
  11982. self.sendIceCandidate([candidate]);
  11983. }
  11984. }
  11985. } else {
  11986. //console.log('sendIceCandidate: last candidate.');
  11987. if (!this.usetrickle) {
  11988. //console.log('should send full offer now...');
  11989. //FIXME why do we generate session-accept in 3 different places ?
  11990. var init = $iq({to: this.peerjid,
  11991. type: 'set'})
  11992. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11993. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  11994. initiator: this.initiator,
  11995. sid: this.sid});
  11996. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  11997. var sendJingle = function (ssrc) {
  11998. if(!ssrc)
  11999. ssrc = {};
  12000. self.localSDP.toJingle(
  12001. init,
  12002. self.initiator == self.me ? 'initiator' : 'responder',
  12003. ssrc);
  12004. SSRCReplacement.processSessionInit(init);
  12005. self.connection.sendIQ(init,
  12006. function () {
  12007. //console.log('session initiate ack');
  12008. var ack = {};
  12009. ack.source = 'offer';
  12010. $(document).trigger('ack.jingle', [self.sid, ack]);
  12011. },
  12012. function (stanza) {
  12013. self.state = 'error';
  12014. self.peerconnection.close();
  12015. var error = ($(stanza).find('error').length) ? {
  12016. code: $(stanza).find('error').attr('code'),
  12017. reason: $(stanza).find('error :first')[0].tagName,
  12018. }:{};
  12019. error.source = 'offer';
  12020. JingleSessionPC.onJingleError(self.sid, error);
  12021. },
  12022. 10000);
  12023. };
  12024. sendJingle();
  12025. }
  12026. this.lasticecandidate = true;
  12027. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  12028. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  12029. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  12030. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  12031. }
  12032. }
  12033. };
  12034. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  12035. console.log('sendIceCandidates', candidates);
  12036. var cand = $iq({to: this.peerjid, type: 'set'})
  12037. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12038. action: 'transport-info',
  12039. initiator: this.initiator,
  12040. sid: this.sid});
  12041. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  12042. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  12043. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  12044. if (cands.length > 0) {
  12045. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  12046. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12047. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  12048. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  12049. }).c('transport', ice);
  12050. for (var i = 0; i < cands.length; i++) {
  12051. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  12052. }
  12053. // add fingerprint
  12054. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  12055. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  12056. tmp.required = true;
  12057. cand.c(
  12058. 'fingerprint',
  12059. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  12060. .t(tmp.fingerprint);
  12061. delete tmp.fingerprint;
  12062. cand.attrs(tmp);
  12063. cand.up();
  12064. }
  12065. cand.up(); // transport
  12066. cand.up(); // content
  12067. }
  12068. }
  12069. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  12070. //console.log('was this the last candidate', this.lasticecandidate);
  12071. this.connection.sendIQ(cand,
  12072. function () {
  12073. var ack = {};
  12074. ack.source = 'transportinfo';
  12075. $(document).trigger('ack.jingle', [this.sid, ack]);
  12076. },
  12077. function (stanza) {
  12078. var error = ($(stanza).find('error').length) ? {
  12079. code: $(stanza).find('error').attr('code'),
  12080. reason: $(stanza).find('error :first')[0].tagName,
  12081. }:{};
  12082. error.source = 'transportinfo';
  12083. JingleSessionPC.onJingleError(this.sid, error);
  12084. },
  12085. 10000);
  12086. };
  12087. JingleSessionPC.prototype.sendOffer = function () {
  12088. //console.log('sendOffer...');
  12089. var self = this;
  12090. this.peerconnection.createOffer(function (sdp) {
  12091. self.createdOffer(sdp);
  12092. },
  12093. function (e) {
  12094. console.error('createOffer failed', e);
  12095. },
  12096. this.media_constraints
  12097. );
  12098. };
  12099. // FIXME createdOffer is never used in jitsi-meet
  12100. JingleSessionPC.prototype.createdOffer = function (sdp) {
  12101. //console.log('createdOffer', sdp);
  12102. var self = this;
  12103. this.localSDP = new SDP(sdp.sdp);
  12104. //this.localSDP.mangle();
  12105. var sendJingle = function () {
  12106. var init = $iq({to: this.peerjid,
  12107. type: 'set'})
  12108. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12109. action: 'session-initiate',
  12110. initiator: this.initiator,
  12111. sid: this.sid});
  12112. self.localSDP.toJingle(
  12113. init,
  12114. this.initiator == this.me ? 'initiator' : 'responder',
  12115. this.localStreamsSSRC);
  12116. SSRCReplacement.processSessionInit(init);
  12117. self.connection.sendIQ(init,
  12118. function () {
  12119. var ack = {};
  12120. ack.source = 'offer';
  12121. $(document).trigger('ack.jingle', [self.sid, ack]);
  12122. },
  12123. function (stanza) {
  12124. self.state = 'error';
  12125. self.peerconnection.close();
  12126. var error = ($(stanza).find('error').length) ? {
  12127. code: $(stanza).find('error').attr('code'),
  12128. reason: $(stanza).find('error :first')[0].tagName,
  12129. }:{};
  12130. error.source = 'offer';
  12131. JingleSessionPC.onJingleError(self.sid, error);
  12132. },
  12133. 10000);
  12134. }
  12135. sdp.sdp = this.localSDP.raw;
  12136. this.peerconnection.setLocalDescription(sdp,
  12137. function () {
  12138. if(self.usetrickle)
  12139. {
  12140. sendJingle();
  12141. }
  12142. self.setLocalDescription();
  12143. //console.log('setLocalDescription success');
  12144. },
  12145. function (e) {
  12146. console.error('setLocalDescription failed', e);
  12147. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12148. }
  12149. );
  12150. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12151. for (var i = 0; i < cands.length; i++) {
  12152. var cand = SDPUtil.parse_icecandidate(cands[i]);
  12153. if (cand.type == 'srflx') {
  12154. this.hadstuncandidate = true;
  12155. } else if (cand.type == 'relay') {
  12156. this.hadturncandidate = true;
  12157. }
  12158. }
  12159. };
  12160. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  12161. var self = this;
  12162. $(contents).each(function (idx, content) {
  12163. var name = $(content).attr('name');
  12164. var mediaType = this.getAttribute('name');
  12165. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12166. ssrcs.each(function () {
  12167. var ssrc = this.getAttribute('ssrc');
  12168. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  12169. function () {
  12170. var owner = this.getAttribute('owner');
  12171. self.ssrcOwners[ssrc] = owner;
  12172. }
  12173. );
  12174. });
  12175. });
  12176. };
  12177. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  12178. return this.ssrcOwners[ssrc];
  12179. };
  12180. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  12181. //console.log('setting remote description... ', desctype);
  12182. this.remoteSDP = new SDP('');
  12183. this.remoteSDP.fromJingle(elem);
  12184. this.readSsrcInfo($(elem).find(">content"));
  12185. if (this.peerconnection.remoteDescription !== null) {
  12186. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  12187. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  12188. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  12189. for (var i = 0; i < pranswer.media.length; i++) {
  12190. // make sure we have ice ufrag and pwd
  12191. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  12192. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  12193. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  12194. } else {
  12195. console.warn('no ice ufrag?');
  12196. }
  12197. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  12198. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  12199. } else {
  12200. console.warn('no ice pwd?');
  12201. }
  12202. }
  12203. // copy over candidates
  12204. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  12205. for (var j = 0; j < lines.length; j++) {
  12206. this.remoteSDP.media[i] += lines[j] + '\r\n';
  12207. }
  12208. }
  12209. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12210. }
  12211. }
  12212. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  12213. this.peerconnection.setRemoteDescription(remotedesc,
  12214. function () {
  12215. //console.log('setRemoteDescription success');
  12216. },
  12217. function (e) {
  12218. console.error('setRemoteDescription error', e);
  12219. JingleSessionPC.onJingleFatalError(self, e);
  12220. }
  12221. );
  12222. };
  12223. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  12224. var self = this;
  12225. if (this.peerconnection.signalingState == 'closed') {
  12226. return;
  12227. }
  12228. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  12229. console.log('trickle ice candidate arriving before session accept...');
  12230. // create a PRANSWER for setRemoteDescription
  12231. if (!this.remoteSDP) {
  12232. var cobbled = 'v=0\r\n' +
  12233. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12234. 's=-\r\n' +
  12235. 't=0 0\r\n';
  12236. // first, take some things from the local description
  12237. for (var i = 0; i < this.localSDP.media.length; i++) {
  12238. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  12239. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  12240. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  12241. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  12242. }
  12243. cobbled += 'a=inactive\r\n';
  12244. }
  12245. this.remoteSDP = new SDP(cobbled);
  12246. }
  12247. // then add things like ice and dtls from remote candidate
  12248. elem.each(function () {
  12249. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  12250. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12251. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12252. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  12253. var tmp = $(this).find('transport');
  12254. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  12255. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  12256. tmp = $(this).find('transport>fingerprint');
  12257. if (tmp.length) {
  12258. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  12259. } else {
  12260. console.log('no dtls fingerprint (webrtc issue #1718?)');
  12261. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  12262. }
  12263. break;
  12264. }
  12265. }
  12266. }
  12267. });
  12268. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12269. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  12270. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  12271. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  12272. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  12273. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  12274. }).length == this.remoteSDP.media.length;
  12275. if (iscomplete) {
  12276. console.log('setting pranswer');
  12277. try {
  12278. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  12279. function() {
  12280. },
  12281. function(e) {
  12282. console.log('setRemoteDescription pranswer failed', e.toString());
  12283. });
  12284. } catch (e) {
  12285. console.error('setting pranswer failed', e);
  12286. }
  12287. } else {
  12288. //console.log('not yet setting pranswer');
  12289. }
  12290. }
  12291. // operate on each content element
  12292. elem.each(function () {
  12293. // would love to deactivate this, but firefox still requires it
  12294. var idx = -1;
  12295. var i;
  12296. for (i = 0; i < self.remoteSDP.media.length; i++) {
  12297. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12298. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12299. idx = i;
  12300. break;
  12301. }
  12302. }
  12303. if (idx == -1) { // fall back to localdescription
  12304. for (i = 0; i < self.localSDP.media.length; i++) {
  12305. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12306. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12307. idx = i;
  12308. break;
  12309. }
  12310. }
  12311. }
  12312. var name = $(this).attr('name');
  12313. // TODO: check ice-pwd and ice-ufrag?
  12314. $(this).find('transport>candidate').each(function () {
  12315. var line, candidate;
  12316. line = SDPUtil.candidateFromJingle(this);
  12317. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  12318. sdpMid: name,
  12319. candidate: line});
  12320. try {
  12321. self.peerconnection.addIceCandidate(candidate);
  12322. } catch (e) {
  12323. console.error('addIceCandidate failed', e.toString(), line);
  12324. }
  12325. });
  12326. });
  12327. };
  12328. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  12329. //console.log('createAnswer', provisional);
  12330. var self = this;
  12331. this.peerconnection.createAnswer(
  12332. function (sdp) {
  12333. self.createdAnswer(sdp, provisional);
  12334. },
  12335. function (e) {
  12336. console.error('createAnswer failed', e);
  12337. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12338. },
  12339. this.media_constraints
  12340. );
  12341. };
  12342. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  12343. //console.log('createAnswer callback');
  12344. var self = this;
  12345. this.localSDP = new SDP(sdp.sdp);
  12346. //this.localSDP.mangle();
  12347. this.usepranswer = provisional === true;
  12348. if (this.usetrickle) {
  12349. if (this.usepranswer) {
  12350. sdp.type = 'pranswer';
  12351. for (var i = 0; i < this.localSDP.media.length; i++) {
  12352. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  12353. }
  12354. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  12355. }
  12356. }
  12357. var self = this;
  12358. var sendJingle = function (ssrcs) {
  12359. // FIXME why do we generate session-accept in 3 different places ?
  12360. var accept = $iq({to: self.peerjid,
  12361. type: 'set'})
  12362. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12363. action: 'session-accept',
  12364. initiator: self.initiator,
  12365. responder: self.responder,
  12366. sid: self.sid });
  12367. self.localSDP.toJingle(
  12368. accept,
  12369. self.initiator == self.me ? 'initiator' : 'responder',
  12370. ssrcs);
  12371. SSRCReplacement.processSessionInit(accept);
  12372. self.connection.sendIQ(accept,
  12373. function () {
  12374. var ack = {};
  12375. ack.source = 'answer';
  12376. $(document).trigger('ack.jingle', [self.sid, ack]);
  12377. },
  12378. function (stanza) {
  12379. var error = ($(stanza).find('error').length) ? {
  12380. code: $(stanza).find('error').attr('code'),
  12381. reason: $(stanza).find('error :first')[0].tagName,
  12382. }:{};
  12383. error.source = 'answer';
  12384. JingleSessionPC.onJingleError(self.sid, error);
  12385. },
  12386. 10000);
  12387. }
  12388. sdp.sdp = this.localSDP.raw;
  12389. this.peerconnection.setLocalDescription(sdp,
  12390. function () {
  12391. //console.log('setLocalDescription success');
  12392. if (self.usetrickle && !self.usepranswer) {
  12393. sendJingle();
  12394. }
  12395. self.setLocalDescription();
  12396. },
  12397. function (e) {
  12398. console.error('setLocalDescription failed', e);
  12399. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12400. }
  12401. );
  12402. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12403. for (var j = 0; j < cands.length; j++) {
  12404. var cand = SDPUtil.parse_icecandidate(cands[j]);
  12405. if (cand.type == 'srflx') {
  12406. this.hadstuncandidate = true;
  12407. } else if (cand.type == 'relay') {
  12408. this.hadturncandidate = true;
  12409. }
  12410. }
  12411. };
  12412. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  12413. var self = this,
  12414. term = $iq({to: this.peerjid,
  12415. type: 'set'})
  12416. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12417. action: 'session-terminate',
  12418. initiator: this.initiator,
  12419. sid: this.sid})
  12420. .c('reason')
  12421. .c(reason || 'success');
  12422. if (text) {
  12423. term.up().c('text').t(text);
  12424. }
  12425. this.connection.sendIQ(term,
  12426. function () {
  12427. self.peerconnection.close();
  12428. self.peerconnection = null;
  12429. self.terminate();
  12430. var ack = {};
  12431. ack.source = 'terminate';
  12432. $(document).trigger('ack.jingle', [self.sid, ack]);
  12433. },
  12434. function (stanza) {
  12435. var error = ($(stanza).find('error').length) ? {
  12436. code: $(stanza).find('error').attr('code'),
  12437. reason: $(stanza).find('error :first')[0].tagName,
  12438. }:{};
  12439. $(document).trigger('ack.jingle', [self.sid, error]);
  12440. },
  12441. 10000);
  12442. if (this.statsinterval !== null) {
  12443. window.clearInterval(this.statsinterval);
  12444. this.statsinterval = null;
  12445. }
  12446. };
  12447. JingleSessionPC.prototype.addSource = function (elem, fromJid) {
  12448. var self = this;
  12449. // FIXME: dirty waiting
  12450. if (!this.peerconnection.localDescription)
  12451. {
  12452. console.warn("addSource - localDescription not ready yet")
  12453. setTimeout(function()
  12454. {
  12455. self.addSource(elem, fromJid);
  12456. },
  12457. 200
  12458. );
  12459. return;
  12460. }
  12461. console.log('addssrc', new Date().getTime());
  12462. console.log('ice', this.peerconnection.iceConnectionState);
  12463. this.readSsrcInfo(elem);
  12464. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12465. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12466. $(elem).each(function (idx, content) {
  12467. var name = $(content).attr('name');
  12468. var lines = '';
  12469. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12470. var semantics = this.getAttribute('semantics');
  12471. var ssrcs = $(this).find('>source').map(function () {
  12472. return this.getAttribute('ssrc');
  12473. }).get();
  12474. if (ssrcs.length != 0) {
  12475. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12476. }
  12477. });
  12478. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12479. tmp.each(function () {
  12480. var ssrc = $(this).attr('ssrc');
  12481. if(mySdp.containsSSRC(ssrc)){
  12482. /**
  12483. * This happens when multiple participants change their streams at the same time and
  12484. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  12485. * addssrc are scheduled for update IQ. See
  12486. */
  12487. console.warn("Got add stream request for my own ssrc: "+ssrc);
  12488. return;
  12489. }
  12490. if (sdp.containsSSRC(ssrc)) {
  12491. console.warn("Source-add request for existing SSRC: " + ssrc);
  12492. return;
  12493. }
  12494. $(this).find('>parameter').each(function () {
  12495. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12496. if ($(this).attr('value') && $(this).attr('value').length)
  12497. lines += ':' + $(this).attr('value');
  12498. lines += '\r\n';
  12499. });
  12500. });
  12501. sdp.media.forEach(function(media, idx) {
  12502. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12503. return;
  12504. sdp.media[idx] += lines;
  12505. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  12506. self.addssrc[idx] += lines;
  12507. });
  12508. sdp.raw = sdp.session + sdp.media.join('');
  12509. });
  12510. this.modifySourcesQueue.push(function() {
  12511. // When a source is added and if this is FF, a new channel is allocated
  12512. // for receiving the added source. We need to diffuse the SSRC of this
  12513. // new recvonly channel to the rest of the peers.
  12514. console.log('modify sources done');
  12515. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12516. console.log("SDPs", mySdp, newSdp);
  12517. self.notifyMySSRCUpdate(mySdp, newSdp);
  12518. });
  12519. };
  12520. JingleSessionPC.prototype.removeSource = function (elem, fromJid) {
  12521. var self = this;
  12522. // FIXME: dirty waiting
  12523. if (!this.peerconnection.localDescription)
  12524. {
  12525. console.warn("removeSource - localDescription not ready yet")
  12526. setTimeout(function()
  12527. {
  12528. self.removeSource(elem, fromJid);
  12529. },
  12530. 200
  12531. );
  12532. return;
  12533. }
  12534. console.log('removessrc', new Date().getTime());
  12535. console.log('ice', this.peerconnection.iceConnectionState);
  12536. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12537. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12538. $(elem).each(function (idx, content) {
  12539. var name = $(content).attr('name');
  12540. var lines = '';
  12541. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12542. var semantics = this.getAttribute('semantics');
  12543. var ssrcs = $(this).find('>source').map(function () {
  12544. return this.getAttribute('ssrc');
  12545. }).get();
  12546. if (ssrcs.length != 0) {
  12547. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12548. }
  12549. });
  12550. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12551. tmp.each(function () {
  12552. var ssrc = $(this).attr('ssrc');
  12553. // This should never happen, but can be useful for bug detection
  12554. if(mySdp.containsSSRC(ssrc)){
  12555. console.error("Got remove stream request for my own ssrc: "+ssrc);
  12556. return;
  12557. }
  12558. $(this).find('>parameter').each(function () {
  12559. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12560. if ($(this).attr('value') && $(this).attr('value').length)
  12561. lines += ':' + $(this).attr('value');
  12562. lines += '\r\n';
  12563. });
  12564. });
  12565. sdp.media.forEach(function(media, idx) {
  12566. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12567. return;
  12568. sdp.media[idx] += lines;
  12569. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  12570. self.removessrc[idx] += lines;
  12571. });
  12572. sdp.raw = sdp.session + sdp.media.join('');
  12573. });
  12574. this.modifySourcesQueue.push(function() {
  12575. // When a source is removed and if this is FF, the recvonly channel that
  12576. // receives the remote stream is deactivated . We need to diffuse the
  12577. // recvonly SSRC removal to the rest of the peers.
  12578. console.log('modify sources done');
  12579. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12580. console.log("SDPs", mySdp, newSdp);
  12581. self.notifyMySSRCUpdate(mySdp, newSdp);
  12582. });
  12583. };
  12584. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  12585. var self = this;
  12586. if (this.peerconnection.signalingState == 'closed') return;
  12587. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  12588. // There is nothing to do since scheduled job might have been executed by another succeeding call
  12589. this.setLocalDescription();
  12590. if(successCallback){
  12591. successCallback();
  12592. }
  12593. queueCallback();
  12594. return;
  12595. }
  12596. // Reset switch streams flag
  12597. this.switchstreams = false;
  12598. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12599. // add sources
  12600. this.addssrc.forEach(function(lines, idx) {
  12601. sdp.media[idx] += lines;
  12602. });
  12603. this.addssrc = [];
  12604. // remove sources
  12605. this.removessrc.forEach(function(lines, idx) {
  12606. lines = lines.split('\r\n');
  12607. lines.pop(); // remove empty last element;
  12608. lines.forEach(function(line) {
  12609. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  12610. });
  12611. });
  12612. this.removessrc = [];
  12613. sdp.raw = sdp.session + sdp.media.join('');
  12614. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  12615. function() {
  12616. if(self.signalingState == 'closed') {
  12617. console.error("createAnswer attempt on closed state");
  12618. queueCallback("createAnswer attempt on closed state");
  12619. return;
  12620. }
  12621. self.peerconnection.createAnswer(
  12622. function(modifiedAnswer) {
  12623. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  12624. if (self.pendingop !== null) {
  12625. var sdp = new SDP(modifiedAnswer.sdp);
  12626. if (sdp.media.length > 1) {
  12627. switch(self.pendingop) {
  12628. case 'mute':
  12629. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  12630. break;
  12631. case 'unmute':
  12632. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  12633. break;
  12634. }
  12635. sdp.raw = sdp.session + sdp.media.join('');
  12636. modifiedAnswer.sdp = sdp.raw;
  12637. }
  12638. self.pendingop = null;
  12639. }
  12640. // FIXME: pushing down an answer while ice connection state
  12641. // is still checking is bad...
  12642. //console.log(self.peerconnection.iceConnectionState);
  12643. // trying to work around another chrome bug
  12644. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  12645. self.peerconnection.setLocalDescription(modifiedAnswer,
  12646. function() {
  12647. //console.log('modified setLocalDescription ok');
  12648. self.setLocalDescription();
  12649. if(successCallback){
  12650. successCallback();
  12651. }
  12652. queueCallback();
  12653. },
  12654. function(error) {
  12655. console.error('modified setLocalDescription failed', error);
  12656. queueCallback(error);
  12657. }
  12658. );
  12659. },
  12660. function(error) {
  12661. console.error('modified answer failed', error);
  12662. queueCallback(error);
  12663. }
  12664. );
  12665. },
  12666. function(error) {
  12667. console.error('modify failed', error);
  12668. queueCallback(error);
  12669. }
  12670. );
  12671. };
  12672. /**
  12673. * Switches video streams.
  12674. * @param new_stream new stream that will be used as video of this session.
  12675. * @param oldStream old video stream of this session.
  12676. * @param success_callback callback executed after successful stream switch.
  12677. */
  12678. JingleSessionPC.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  12679. var self = this;
  12680. // Remember SDP to figure out added/removed SSRCs
  12681. var oldSdp = null;
  12682. if(self.peerconnection) {
  12683. if(self.peerconnection.localDescription) {
  12684. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12685. }
  12686. self.peerconnection.removeStream(oldStream, true);
  12687. if(new_stream)
  12688. self.peerconnection.addStream(new_stream);
  12689. }
  12690. // Conference is not active
  12691. if(!oldSdp || !self.peerconnection) {
  12692. success_callback();
  12693. return;
  12694. }
  12695. self.switchstreams = true;
  12696. self.modifySourcesQueue.push(function() {
  12697. console.log('modify sources done');
  12698. success_callback();
  12699. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12700. console.log("SDPs", oldSdp, newSdp);
  12701. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12702. });
  12703. };
  12704. /**
  12705. * Figures out added/removed ssrcs and send update IQs.
  12706. * @param old_sdp SDP object for old description.
  12707. * @param new_sdp SDP object for new description.
  12708. */
  12709. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  12710. if (!(this.peerconnection.signalingState == 'stable' &&
  12711. this.peerconnection.iceConnectionState == 'connected')){
  12712. console.log("Too early to send updates");
  12713. return;
  12714. }
  12715. // send source-remove IQ.
  12716. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  12717. var remove = $iq({to: this.peerjid, type: 'set'})
  12718. .c('jingle', {
  12719. xmlns: 'urn:xmpp:jingle:1',
  12720. action: 'source-remove',
  12721. initiator: this.initiator,
  12722. sid: this.sid
  12723. }
  12724. );
  12725. var removed = sdpDiffer.toJingle(remove);
  12726. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  12727. // it in the current form
  12728. if (removed)
  12729. remove = SSRCReplacement.processSourceRemove(remove);
  12730. if (removed && remove) {
  12731. console.info("Sending source-remove", remove);
  12732. this.connection.sendIQ(remove,
  12733. function (res) {
  12734. console.info('got remove result', res);
  12735. },
  12736. function (err) {
  12737. console.error('got remove error', err);
  12738. }
  12739. );
  12740. } else {
  12741. console.log('removal not necessary');
  12742. }
  12743. // send source-add IQ.
  12744. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  12745. var add = $iq({to: this.peerjid, type: 'set'})
  12746. .c('jingle', {
  12747. xmlns: 'urn:xmpp:jingle:1',
  12748. action: 'source-add',
  12749. initiator: this.initiator,
  12750. sid: this.sid
  12751. }
  12752. );
  12753. var added = sdpDiffer.toJingle(add);
  12754. // Let 'source-add' IQ through the hack and see if we're allowed to send
  12755. // it in the current form
  12756. if (added)
  12757. add = SSRCReplacement.processSourceAdd(add);
  12758. if (added && add) {
  12759. console.info("Sending source-add", add);
  12760. this.connection.sendIQ(add,
  12761. function (res) {
  12762. console.info('got add result', res);
  12763. },
  12764. function (err) {
  12765. console.error('got add error', err);
  12766. }
  12767. );
  12768. } else {
  12769. console.log('addition not necessary');
  12770. }
  12771. };
  12772. /**
  12773. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  12774. *
  12775. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  12776. * tracks; otherwise, <tt>false</tt>
  12777. * @param callback a function to be invoked with <tt>mute</tt> after all video
  12778. * tracks have been enabled/disabled. The function may, optionally, return
  12779. * another function which is to be invoked after the whole mute/unmute operation
  12780. * has completed successfully.
  12781. * @param options an object which specifies optional arguments such as the
  12782. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  12783. * specifies whether the method was initiated in response to a user command (in
  12784. * contrast to an automatic decision made by the application logic)
  12785. */
  12786. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  12787. var byUser;
  12788. if (options) {
  12789. byUser = options.byUser;
  12790. if (typeof byUser === 'undefined') {
  12791. byUser = true;
  12792. }
  12793. } else {
  12794. byUser = true;
  12795. }
  12796. // The user's command to mute the (local) video takes precedence over any
  12797. // automatic decision made by the application logic.
  12798. if (byUser) {
  12799. this.videoMuteByUser = mute;
  12800. } else if (this.videoMuteByUser) {
  12801. return;
  12802. }
  12803. this.hardMuteVideo(mute);
  12804. var self = this;
  12805. var oldSdp = null;
  12806. if(self.peerconnection) {
  12807. if(self.peerconnection.localDescription) {
  12808. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12809. }
  12810. }
  12811. this.modifySourcesQueue.push(function() {
  12812. console.log('modify sources done');
  12813. callback(mute);
  12814. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12815. console.log("SDPs", oldSdp, newSdp);
  12816. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12817. });
  12818. };
  12819. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  12820. this.pendingop = muted ? 'mute' : 'unmute';
  12821. };
  12822. JingleSessionPC.prototype.sendMute = function (muted, content) {
  12823. var info = $iq({to: this.peerjid,
  12824. type: 'set'})
  12825. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12826. action: 'session-info',
  12827. initiator: this.initiator,
  12828. sid: this.sid });
  12829. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12830. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  12831. if (content) {
  12832. info.attrs({'name': content});
  12833. }
  12834. this.connection.send(info);
  12835. };
  12836. JingleSessionPC.prototype.sendRinging = function () {
  12837. var info = $iq({to: this.peerjid,
  12838. type: 'set'})
  12839. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12840. action: 'session-info',
  12841. initiator: this.initiator,
  12842. sid: this.sid });
  12843. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12844. this.connection.send(info);
  12845. };
  12846. JingleSessionPC.prototype.getStats = function (interval) {
  12847. var self = this;
  12848. var recv = {audio: 0, video: 0};
  12849. var lost = {audio: 0, video: 0};
  12850. var lastrecv = {audio: 0, video: 0};
  12851. var lastlost = {audio: 0, video: 0};
  12852. var loss = {audio: 0, video: 0};
  12853. var delta = {audio: 0, video: 0};
  12854. this.statsinterval = window.setInterval(function () {
  12855. if (self && self.peerconnection && self.peerconnection.getStats) {
  12856. self.peerconnection.getStats(function (stats) {
  12857. var results = stats.result();
  12858. // TODO: there are so much statistics you can get from this..
  12859. for (var i = 0; i < results.length; ++i) {
  12860. if (results[i].type == 'ssrc') {
  12861. var packetsrecv = results[i].stat('packetsReceived');
  12862. var packetslost = results[i].stat('packetsLost');
  12863. if (packetsrecv && packetslost) {
  12864. packetsrecv = parseInt(packetsrecv, 10);
  12865. packetslost = parseInt(packetslost, 10);
  12866. if (results[i].stat('googFrameRateReceived')) {
  12867. lastlost.video = lost.video;
  12868. lastrecv.video = recv.video;
  12869. recv.video = packetsrecv;
  12870. lost.video = packetslost;
  12871. } else {
  12872. lastlost.audio = lost.audio;
  12873. lastrecv.audio = recv.audio;
  12874. recv.audio = packetsrecv;
  12875. lost.audio = packetslost;
  12876. }
  12877. }
  12878. }
  12879. }
  12880. delta.audio = recv.audio - lastrecv.audio;
  12881. delta.video = recv.video - lastrecv.video;
  12882. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  12883. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  12884. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  12885. });
  12886. }
  12887. }, interval || 3000);
  12888. return this.statsinterval;
  12889. };
  12890. JingleSessionPC.onJingleError = function (session, error)
  12891. {
  12892. console.error("Jingle error", error);
  12893. }
  12894. JingleSessionPC.onJingleFatalError = function (session, error)
  12895. {
  12896. this.service.sessionTerminated = true;
  12897. this.connection.emuc.doLeave();
  12898. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12899. this.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  12900. }
  12901. JingleSessionPC.prototype.setLocalDescription = function () {
  12902. var self = this;
  12903. var newssrcs = [];
  12904. var session = transform.parse(this.peerconnection.localDescription.sdp);
  12905. session.media.forEach(function (media) {
  12906. if (media.ssrcs != null && media.ssrcs.length > 0) {
  12907. // TODO(gp) maybe exclude FID streams?
  12908. media.ssrcs.forEach(function (ssrc) {
  12909. if (ssrc.attribute !== 'cname') {
  12910. return;
  12911. }
  12912. newssrcs.push({
  12913. 'ssrc': ssrc.id,
  12914. 'type': media.type
  12915. });
  12916. });
  12917. }
  12918. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  12919. {
  12920. newssrcs.push({
  12921. 'ssrc': self.localStreamsSSRC[media.type],
  12922. 'type': media.type
  12923. });
  12924. }
  12925. });
  12926. console.log('new ssrcs', newssrcs);
  12927. // Bind us as local SSRCs owner
  12928. if (newssrcs.length > 0) {
  12929. for (var i = 1; i <= newssrcs.length; i ++) {
  12930. var ssrc = newssrcs[i-1].ssrc;
  12931. var myJid = self.connection.emuc.myroomjid;
  12932. self.ssrcOwners[ssrc] = myJid;
  12933. }
  12934. }
  12935. }
  12936. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12937. // TODO: is this hack (along with the XMPPEvent-s used only for it) still needed
  12938. // now that we announce an SSRC for receive-only streams?
  12939. function sendKeyframe(pc) {
  12940. console.log('sendkeyframe', pc.iceConnectionState);
  12941. if (pc.iceConnectionState !== 'connected') return; // safe...
  12942. pc.setRemoteDescription(
  12943. pc.remoteDescription,
  12944. function () {
  12945. pc.createAnswer(
  12946. function (modifiedAnswer) {
  12947. pc.setLocalDescription(
  12948. modifiedAnswer,
  12949. function () {
  12950. // noop
  12951. },
  12952. function (error) {
  12953. console.log('triggerKeyframe setLocalDescription failed', error);
  12954. eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  12955. }
  12956. );
  12957. },
  12958. function (error) {
  12959. console.log('triggerKeyframe createAnswer failed', error);
  12960. eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  12961. }
  12962. );
  12963. },
  12964. function (error) {
  12965. console.log('triggerKeyframe setRemoteDescription failed', error);
  12966. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  12967. }
  12968. );
  12969. }
  12970. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  12971. var self = this;
  12972. var thessrc;
  12973. var streamId = APP.RTC.getStreamID(data.stream);
  12974. // look up an associated JID for a stream id
  12975. if (!streamId) {
  12976. console.error("No stream ID for", data.stream);
  12977. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  12978. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  12979. var ssrclines
  12980. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  12981. ssrclines = ssrclines.filter(function (line) {
  12982. // NOTE(gp) previously we filtered on the mslabel, but that property
  12983. // is not always present.
  12984. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  12985. if (RTCBrowserType.isTemasysPluginUsed()) {
  12986. return ((line.indexOf('mslabel:' + streamId) !== -1));
  12987. } else {
  12988. return ((line.indexOf('msid:' + streamId) !== -1));
  12989. }
  12990. });
  12991. if (ssrclines.length) {
  12992. thessrc = ssrclines[0].substring(7).split(' ')[0];
  12993. if (!self.ssrcOwners[thessrc]) {
  12994. console.error("No SSRC owner known for: " + thessrc);
  12995. return;
  12996. }
  12997. data.peerjid = self.ssrcOwners[thessrc];
  12998. console.log('associated jid', self.ssrcOwners[thessrc]);
  12999. } else {
  13000. console.error("No SSRC lines for ", streamId);
  13001. }
  13002. }
  13003. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  13004. var isVideo = data.stream.getVideoTracks().length > 0;
  13005. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  13006. // TODO: is this hack still needed now that we announce an SSRC for
  13007. // receive-only streams?
  13008. if (isVideo &&
  13009. data.peerjid && this.peerjid === data.peerjid &&
  13010. data.stream.getVideoTracks().length === 0 &&
  13011. APP.RTC.localVideo.getTracks().length > 0) {
  13012. window.setTimeout(function () {
  13013. sendKeyframe(self.peerconnection);
  13014. }, 3000);
  13015. }
  13016. }
  13017. module.exports = JingleSessionPC;
  13018. },{"../../service/xmpp/XMPPEvents":161,"../RTC/RTCBrowserType":8,"./JingleSession":53,"./LocalSSRCReplacement":55,"./SDP":56,"./SDPDiffer":57,"./SDPUtil":58,"./TraceablePeerConnection":59,"async":69,"sdp-transform":98}],55:[function(require,module,exports){
  13019. /* global $ */
  13020. /*
  13021. Here we do modifications of local video SSRCs. There are 2 situations we have
  13022. to handle:
  13023. 1. We generate SSRC for local recvonly video stream. This is the case when we
  13024. have no local camera and it is not generated automatically, but SSRC=1 is
  13025. used implicitly. If that happens RTCP packets will be dropped by the JVB
  13026. and we won't be able to request video key frames correctly.
  13027. 2. A hack to re-use SSRC of the first video stream for any new stream created
  13028. in future. It turned out that Chrome may keep on using the SSRC of removed
  13029. video stream in RTCP even though a new one has been created. So we just
  13030. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  13031. notifications are blocked once first video SSRC is advertised to the focus.
  13032. What this hack does:
  13033. 1. Stores the SSRC of the first video stream created by
  13034. a) scanning Jingle session-accept/session-invite for existing video SSRC
  13035. b) watching for 'source-add' for new video stream if it has not been
  13036. created in step a)
  13037. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  13038. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  13039. returned to the other parts of the application.
  13040. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  13041. blocks those notifications. This makes Jicofo and all participants think
  13042. that it exists all the time even if the video stream has been removed or
  13043. replaced locally. Thanks to that there is no additional signaling activity
  13044. on video mute or when switching to the desktop stream.
  13045. */
  13046. var SDP = require('./SDP');
  13047. var RTCBrowserType = require('../RTC/RTCBrowserType');
  13048. /**
  13049. * The hack is enabled on all browsers except FF by default
  13050. * FIXME finish the hack once removeStream method is implemented in FF
  13051. * @type {boolean}
  13052. */
  13053. var isEnabled = !RTCBrowserType.isFirefox();
  13054. /**
  13055. * Stored SSRC of local video stream.
  13056. */
  13057. var localVideoSSRC;
  13058. /**
  13059. * SSRC used for recvonly video stream when we have no local camera.
  13060. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  13061. * instead of 1.
  13062. */
  13063. var localRecvOnlySSRC;
  13064. /**
  13065. * cname for <tt>localRecvOnlySSRC</tt>
  13066. */
  13067. var localRecvOnlyCName;
  13068. /**
  13069. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  13070. * from given Jingle IQ.
  13071. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  13072. * @param actionName display name of the action which will be printed in log
  13073. * messages.
  13074. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  13075. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  13076. * other SSRCs left to be signaled after removing it.
  13077. */
  13078. var filterOutSource = function (modifyIq, actionName) {
  13079. var modifyIqTree = $(modifyIq.tree());
  13080. if (!localVideoSSRC)
  13081. return modifyIqTree[0];
  13082. var videoSSRC = modifyIqTree.find(
  13083. '>jingle>content[name="video"]' +
  13084. '>description>source[ssrc="' + localVideoSSRC + '"]');
  13085. if (!videoSSRC.length) {
  13086. return modifyIqTree[0];
  13087. }
  13088. console.info(
  13089. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  13090. videoSSRC.remove();
  13091. // Check if any sources still left to be added/removed
  13092. if (modifyIqTree.find('>jingle>content>description>source').length) {
  13093. return modifyIqTree[0];
  13094. } else {
  13095. return null;
  13096. }
  13097. };
  13098. /**
  13099. * Scans given Jingle IQ for video SSRC and stores it.
  13100. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  13101. */
  13102. var storeLocalVideoSSRC = function (jingleIq) {
  13103. var videoSSRCs =
  13104. $(jingleIq.tree())
  13105. .find('>jingle>content[name="video"]>description>source');
  13106. videoSSRCs.each(function (idx, ssrcElem) {
  13107. if (localVideoSSRC)
  13108. return;
  13109. // We consider SSRC real only if it has msid attribute
  13110. // recvonly streams in FF do not have it as well as local SSRCs
  13111. // we generate for recvonly streams in Chrome
  13112. var ssrSel = $(ssrcElem);
  13113. var msid = ssrSel.find('>parameter[name="msid"]');
  13114. if (msid.length) {
  13115. var ssrcVal = ssrSel.attr('ssrc');
  13116. if (ssrcVal) {
  13117. localVideoSSRC = ssrcVal;
  13118. console.info('Stored local video SSRC' +
  13119. ' for future re-use: ' + localVideoSSRC);
  13120. }
  13121. }
  13122. });
  13123. };
  13124. /**
  13125. * Generates new SSRC for local video recvonly stream.
  13126. * FIXME what about eventual SSRC collision ?
  13127. */
  13128. function generateRecvonlySSRC() {
  13129. //
  13130. localRecvOnlySSRC =
  13131. Math.random().toString(10).substring(2, 11);
  13132. localRecvOnlyCName =
  13133. Math.random().toString(36).substring(2);
  13134. console.info(
  13135. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  13136. ", cname: " + localRecvOnlyCName);
  13137. }
  13138. var LocalSSRCReplacement = {
  13139. /**
  13140. * Method must be called before 'session-initiate' or 'session-invite' is
  13141. * sent. Scans the IQ for local video SSRC and stores it if detected.
  13142. *
  13143. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  13144. * which will be scanned for local video SSRC.
  13145. */
  13146. processSessionInit: function (sessionInit) {
  13147. if (!isEnabled)
  13148. return;
  13149. if (localVideoSSRC) {
  13150. console.error("Local SSRC stored already: " + localVideoSSRC);
  13151. return;
  13152. }
  13153. storeLocalVideoSSRC(sessionInit);
  13154. },
  13155. /**
  13156. * If we have local video SSRC stored searched given
  13157. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  13158. * with the stored one.
  13159. * @param localDescription local description object that will have local
  13160. * video SSRC replaced with the stored one
  13161. * @returns modified <tt>localDescription</tt> object.
  13162. */
  13163. mungeLocalVideoSSRC: function (localDescription) {
  13164. if (!isEnabled)
  13165. return localDescription;
  13166. if (!localDescription) {
  13167. console.warn("localDescription is null or undefined");
  13168. return localDescription;
  13169. }
  13170. // IF we have local video SSRC stored make sure it is replaced
  13171. // with old SSRC
  13172. if (localVideoSSRC) {
  13173. var newSdp = new SDP(localDescription.sdp);
  13174. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  13175. !newSdp.containsSSRC(localVideoSSRC)) {
  13176. // Get new video SSRC
  13177. var map = newSdp.getMediaSsrcMap();
  13178. var videoPart = map[1];
  13179. var videoSSRCs = videoPart.ssrcs;
  13180. var newSSRC = Object.keys(videoSSRCs)[0];
  13181. console.info(
  13182. "Replacing new video SSRC: " + newSSRC +
  13183. " with " + localVideoSSRC);
  13184. localDescription.sdp =
  13185. newSdp.raw.replace(
  13186. new RegExp('a=ssrc:' + newSSRC, 'g'),
  13187. 'a=ssrc:' + localVideoSSRC);
  13188. }
  13189. } else {
  13190. // Make sure we have any SSRC for recvonly video stream
  13191. var sdp = new SDP(localDescription.sdp);
  13192. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  13193. sdp.media[1].indexOf('a=recvonly') !== -1) {
  13194. if (!localRecvOnlySSRC) {
  13195. generateRecvonlySSRC();
  13196. }
  13197. console.info('No SSRC in video recvonly stream' +
  13198. ' - adding SSRC: ' + localRecvOnlySSRC);
  13199. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  13200. ' cname:' + localRecvOnlyCName + '\r\n';
  13201. localDescription.sdp = sdp.session + sdp.media.join('');
  13202. }
  13203. }
  13204. return localDescription;
  13205. },
  13206. /**
  13207. * Method must be called before 'source-add' notification is sent. In case
  13208. * we have local video SSRC advertised already it will be removed from the
  13209. * notification. If no other SSRCs are described by given IQ null will be
  13210. * returned which means that there is no point in sending the notification.
  13211. * @param sourceAdd 'source-add' Jingle IQ to be processed
  13212. * @returns modified 'source-add' IQ which can be sent to the focus or
  13213. * <tt>null</tt> if no notification shall be sent. It is no longer
  13214. * a Strophe IQ Builder instance, but DOM element tree.
  13215. */
  13216. processSourceAdd: function (sourceAdd) {
  13217. if (!isEnabled)
  13218. return sourceAdd;
  13219. if (!localVideoSSRC) {
  13220. // Store local SSRC if available
  13221. storeLocalVideoSSRC(sourceAdd);
  13222. return sourceAdd;
  13223. } else {
  13224. return filterOutSource(sourceAdd, 'source-add');
  13225. }
  13226. },
  13227. /**
  13228. * Method must be called before 'source-remove' notification is sent.
  13229. * Removes local video SSRC from the notification. If there are no other
  13230. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  13231. * means that there is no point in sending the notification.
  13232. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  13233. * @returns modified 'source-remove' IQ which can be sent to the focus or
  13234. * <tt>null</tt> if no notification shall be sent. It is no longer
  13235. * a Strophe IQ Builder instance, but DOM element tree.
  13236. */
  13237. processSourceRemove: function (sourceRemove) {
  13238. if (!isEnabled)
  13239. return sourceRemove;
  13240. return filterOutSource(sourceRemove, 'source-remove');
  13241. },
  13242. /**
  13243. * Turns the hack on or off
  13244. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  13245. * to disable it
  13246. */
  13247. setEnabled: function (enabled) {
  13248. isEnabled = enabled;
  13249. }
  13250. };
  13251. module.exports = LocalSSRCReplacement;
  13252. },{"../RTC/RTCBrowserType":8,"./SDP":56}],56:[function(require,module,exports){
  13253. /* jshint -W117 */
  13254. var SDPUtil = require("./SDPUtil");
  13255. // SDP STUFF
  13256. function SDP(sdp) {
  13257. this.media = sdp.split('\r\nm=');
  13258. for (var i = 1; i < this.media.length; i++) {
  13259. this.media[i] = 'm=' + this.media[i];
  13260. if (i != this.media.length - 1) {
  13261. this.media[i] += '\r\n';
  13262. }
  13263. }
  13264. this.session = this.media.shift() + '\r\n';
  13265. this.raw = this.session + this.media.join('');
  13266. }
  13267. /**
  13268. * Returns map of MediaChannel mapped per channel idx.
  13269. */
  13270. SDP.prototype.getMediaSsrcMap = function() {
  13271. var self = this;
  13272. var media_ssrcs = {};
  13273. var tmp;
  13274. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  13275. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  13276. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  13277. var media = {
  13278. mediaindex: mediaindex,
  13279. mid: mid,
  13280. ssrcs: {},
  13281. ssrcGroups: []
  13282. };
  13283. media_ssrcs[mediaindex] = media;
  13284. tmp.forEach(function (line) {
  13285. var linessrc = line.substring(7).split(' ')[0];
  13286. // allocate new ChannelSsrc
  13287. if(!media.ssrcs[linessrc]) {
  13288. media.ssrcs[linessrc] = {
  13289. ssrc: linessrc,
  13290. lines: []
  13291. };
  13292. }
  13293. media.ssrcs[linessrc].lines.push(line);
  13294. });
  13295. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  13296. tmp.forEach(function(line){
  13297. var semantics = line.substr(0, idx).substr(13);
  13298. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13299. if (ssrcs.length != 0) {
  13300. media.ssrcGroups.push({
  13301. semantics: semantics,
  13302. ssrcs: ssrcs
  13303. });
  13304. }
  13305. });
  13306. }
  13307. return media_ssrcs;
  13308. };
  13309. /**
  13310. * Returns <tt>true</tt> if this SDP contains given SSRC.
  13311. * @param ssrc the ssrc to check.
  13312. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  13313. */
  13314. SDP.prototype.containsSSRC = function(ssrc) {
  13315. var medias = this.getMediaSsrcMap();
  13316. var contains = false;
  13317. Object.keys(medias).forEach(function(mediaindex){
  13318. var media = medias[mediaindex];
  13319. //console.log("Check", channel, ssrc);
  13320. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  13321. contains = true;
  13322. }
  13323. });
  13324. return contains;
  13325. };
  13326. // remove iSAC and CN from SDP
  13327. SDP.prototype.mangle = function () {
  13328. var i, j, mline, lines, rtpmap, newdesc;
  13329. for (i = 0; i < this.media.length; i++) {
  13330. lines = this.media[i].split('\r\n');
  13331. lines.pop(); // remove empty last element
  13332. mline = SDPUtil.parse_mline(lines.shift());
  13333. if (mline.media != 'audio')
  13334. continue;
  13335. newdesc = '';
  13336. mline.fmt.length = 0;
  13337. for (j = 0; j < lines.length; j++) {
  13338. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  13339. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  13340. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  13341. continue;
  13342. mline.fmt.push(rtpmap.id);
  13343. newdesc += lines[j] + '\r\n';
  13344. } else {
  13345. newdesc += lines[j] + '\r\n';
  13346. }
  13347. }
  13348. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  13349. this.media[i] += newdesc;
  13350. }
  13351. this.raw = this.session + this.media.join('');
  13352. };
  13353. // remove lines matching prefix from session section
  13354. SDP.prototype.removeSessionLines = function(prefix) {
  13355. var self = this;
  13356. var lines = SDPUtil.find_lines(this.session, prefix);
  13357. lines.forEach(function(line) {
  13358. self.session = self.session.replace(line + '\r\n', '');
  13359. });
  13360. this.raw = this.session + this.media.join('');
  13361. return lines;
  13362. }
  13363. // remove lines matching prefix from a media section specified by mediaindex
  13364. // TODO: non-numeric mediaindex could match mid
  13365. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  13366. var self = this;
  13367. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  13368. lines.forEach(function(line) {
  13369. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  13370. });
  13371. this.raw = this.session + this.media.join('');
  13372. return lines;
  13373. }
  13374. // add content's to a jingle element
  13375. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  13376. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  13377. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  13378. var self = this;
  13379. // new bundle plan
  13380. if (SDPUtil.find_line(this.session, 'a=group:')) {
  13381. lines = SDPUtil.find_lines(this.session, 'a=group:');
  13382. for (i = 0; i < lines.length; i++) {
  13383. tmp = lines[i].split(' ');
  13384. var semantics = tmp.shift().substr(8);
  13385. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  13386. for (j = 0; j < tmp.length; j++) {
  13387. elem.c('content', {name: tmp[j]}).up();
  13388. }
  13389. elem.up();
  13390. }
  13391. }
  13392. for (i = 0; i < this.media.length; i++) {
  13393. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  13394. if (!(mline.media === 'audio' ||
  13395. mline.media === 'video' ||
  13396. mline.media === 'application'))
  13397. {
  13398. continue;
  13399. }
  13400. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  13401. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  13402. } else {
  13403. if(ssrcs && ssrcs[mline.media])
  13404. {
  13405. ssrc = ssrcs[mline.media];
  13406. }
  13407. else
  13408. ssrc = false;
  13409. }
  13410. elem.c('content', {creator: thecreator, name: mline.media});
  13411. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  13412. // prefer identifier from a=mid if present
  13413. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  13414. elem.attrs({ name: mid });
  13415. }
  13416. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  13417. {
  13418. elem.c('description',
  13419. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  13420. media: mline.media });
  13421. if (ssrc) {
  13422. elem.attrs({ssrc: ssrc});
  13423. }
  13424. for (j = 0; j < mline.fmt.length; j++) {
  13425. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  13426. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  13427. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  13428. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  13429. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  13430. for (k = 0; k < tmp.length; k++) {
  13431. elem.c('parameter', tmp[k]).up();
  13432. }
  13433. }
  13434. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  13435. elem.up();
  13436. }
  13437. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  13438. elem.c('encryption', {required: 1});
  13439. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  13440. crypto.forEach(function(line) {
  13441. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  13442. });
  13443. elem.up(); // end of encryption
  13444. }
  13445. if (ssrc) {
  13446. // new style mapping
  13447. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13448. // FIXME: group by ssrc and support multiple different ssrcs
  13449. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  13450. if(ssrclines.length > 0) {
  13451. ssrclines.forEach(function (line) {
  13452. idx = line.indexOf(' ');
  13453. var linessrc = line.substr(0, idx).substr(7);
  13454. if (linessrc != ssrc) {
  13455. elem.up();
  13456. ssrc = linessrc;
  13457. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13458. }
  13459. var kv = line.substr(idx + 1);
  13460. elem.c('parameter');
  13461. if (kv.indexOf(':') == -1) {
  13462. elem.attrs({ name: kv });
  13463. } else {
  13464. var k = kv.split(':', 2)[0];
  13465. elem.attrs({ name: k });
  13466. var v = kv.split(':', 2)[1];
  13467. v = SDPUtil.filter_special_chars(v);
  13468. elem.attrs({ value: v });
  13469. }
  13470. elem.up();
  13471. });
  13472. }
  13473. else
  13474. {
  13475. elem.up();
  13476. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13477. elem.c('parameter');
  13478. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  13479. elem.up();
  13480. var msid = null;
  13481. if(mline.media == "audio")
  13482. {
  13483. msid = APP.RTC.localAudio.getId();
  13484. }
  13485. else
  13486. {
  13487. msid = APP.RTC.localVideo.getId();
  13488. }
  13489. if(msid != null)
  13490. {
  13491. msid = SDPUtil.filter_special_chars(msid);
  13492. elem.c('parameter');
  13493. elem.attrs({name: "msid", value:msid});
  13494. elem.up();
  13495. elem.c('parameter');
  13496. elem.attrs({name: "mslabel", value:msid});
  13497. elem.up();
  13498. elem.c('parameter');
  13499. elem.attrs({name: "label", value:msid});
  13500. elem.up();
  13501. }
  13502. }
  13503. elem.up();
  13504. // XEP-0339 handle ssrc-group attributes
  13505. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  13506. ssrc_group_lines.forEach(function(line) {
  13507. idx = line.indexOf(' ');
  13508. var semantics = line.substr(0, idx).substr(13);
  13509. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13510. if (ssrcs.length != 0) {
  13511. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13512. ssrcs.forEach(function(ssrc) {
  13513. elem.c('source', { ssrc: ssrc })
  13514. .up();
  13515. });
  13516. elem.up();
  13517. }
  13518. });
  13519. }
  13520. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  13521. elem.c('rtcp-mux').up();
  13522. }
  13523. // XEP-0293 -- map a=rtcp-fb:*
  13524. this.RtcpFbToJingle(i, elem, '*');
  13525. // XEP-0294
  13526. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  13527. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  13528. for (j = 0; j < lines.length; j++) {
  13529. tmp = SDPUtil.parse_extmap(lines[j]);
  13530. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  13531. uri: tmp.uri,
  13532. id: tmp.value });
  13533. if (tmp.hasOwnProperty('direction')) {
  13534. switch (tmp.direction) {
  13535. case 'sendonly':
  13536. elem.attrs({senders: 'responder'});
  13537. break;
  13538. case 'recvonly':
  13539. elem.attrs({senders: 'initiator'});
  13540. break;
  13541. case 'sendrecv':
  13542. elem.attrs({senders: 'both'});
  13543. break;
  13544. case 'inactive':
  13545. elem.attrs({senders: 'none'});
  13546. break;
  13547. }
  13548. }
  13549. // TODO: handle params
  13550. elem.up();
  13551. }
  13552. }
  13553. elem.up(); // end of description
  13554. }
  13555. // map ice-ufrag/pwd, dtls fingerprint, candidates
  13556. this.TransportToJingle(i, elem);
  13557. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  13558. elem.attrs({senders: 'both'});
  13559. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  13560. elem.attrs({senders: 'initiator'});
  13561. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  13562. elem.attrs({senders: 'responder'});
  13563. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  13564. elem.attrs({senders: 'none'});
  13565. }
  13566. if (mline.port == '0') {
  13567. // estos hack to reject an m-line
  13568. elem.attrs({senders: 'rejected'});
  13569. }
  13570. elem.up(); // end of content
  13571. }
  13572. elem.up();
  13573. return elem;
  13574. };
  13575. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  13576. var i = mediaindex;
  13577. var tmp;
  13578. var self = this;
  13579. elem.c('transport');
  13580. // XEP-0343 DTLS/SCTP
  13581. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  13582. {
  13583. var sctpmap = SDPUtil.find_line(
  13584. this.media[i], 'a=sctpmap:', self.session);
  13585. if (sctpmap)
  13586. {
  13587. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  13588. elem.c('sctpmap',
  13589. {
  13590. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  13591. number: sctpAttrs[0], /* SCTP port */
  13592. protocol: sctpAttrs[1], /* protocol */
  13593. });
  13594. // Optional stream count attribute
  13595. if (sctpAttrs.length > 2)
  13596. elem.attrs({ streams: sctpAttrs[2]});
  13597. elem.up();
  13598. }
  13599. }
  13600. // XEP-0320
  13601. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  13602. fingerprints.forEach(function(line) {
  13603. tmp = SDPUtil.parse_fingerprint(line);
  13604. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  13605. elem.c('fingerprint').t(tmp.fingerprint);
  13606. delete tmp.fingerprint;
  13607. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  13608. if (line) {
  13609. tmp.setup = line.substr(8);
  13610. }
  13611. elem.attrs(tmp);
  13612. elem.up(); // end of fingerprint
  13613. });
  13614. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  13615. if (tmp) {
  13616. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  13617. elem.attrs(tmp);
  13618. // XEP-0176
  13619. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  13620. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  13621. lines.forEach(function (line) {
  13622. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  13623. });
  13624. }
  13625. }
  13626. elem.up(); // end of transport
  13627. }
  13628. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  13629. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  13630. lines.forEach(function (line) {
  13631. var tmp = SDPUtil.parse_rtcpfb(line);
  13632. if (tmp.type == 'trr-int') {
  13633. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  13634. elem.up();
  13635. } else {
  13636. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  13637. if (tmp.params.length > 0) {
  13638. elem.attrs({'subtype': tmp.params[0]});
  13639. }
  13640. elem.up();
  13641. }
  13642. });
  13643. };
  13644. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  13645. var media = '';
  13646. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13647. if (tmp.length) {
  13648. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  13649. if (tmp.attr('value')) {
  13650. media += tmp.attr('value');
  13651. } else {
  13652. media += '0';
  13653. }
  13654. media += '\r\n';
  13655. }
  13656. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13657. tmp.each(function () {
  13658. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  13659. if ($(this).attr('subtype')) {
  13660. media += ' ' + $(this).attr('subtype');
  13661. }
  13662. media += '\r\n';
  13663. });
  13664. return media;
  13665. };
  13666. // construct an SDP from a jingle stanza
  13667. SDP.prototype.fromJingle = function (jingle) {
  13668. var self = this;
  13669. this.raw = 'v=0\r\n' +
  13670. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  13671. 's=-\r\n' +
  13672. 't=0 0\r\n';
  13673. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  13674. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  13675. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  13676. var contents = $(group).find('>content').map(function (idx, content) {
  13677. return content.getAttribute('name');
  13678. }).get();
  13679. if (contents.length > 0) {
  13680. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  13681. }
  13682. });
  13683. }
  13684. this.session = this.raw;
  13685. jingle.find('>content').each(function () {
  13686. var m = self.jingle2media($(this));
  13687. self.media.push(m);
  13688. });
  13689. // reconstruct msid-semantic -- apparently not necessary
  13690. /*
  13691. var msid = SDPUtil.parse_ssrc(this.raw);
  13692. if (msid.hasOwnProperty('mslabel')) {
  13693. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  13694. }
  13695. */
  13696. this.raw = this.session + this.media.join('');
  13697. };
  13698. // translate a jingle content element into an an SDP media part
  13699. SDP.prototype.jingle2media = function (content) {
  13700. var media = '',
  13701. desc = content.find('description'),
  13702. ssrc = desc.attr('ssrc'),
  13703. self = this,
  13704. tmp;
  13705. var sctp = content.find(
  13706. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  13707. tmp = { media: desc.attr('media') };
  13708. tmp.port = '1';
  13709. if (content.attr('senders') == 'rejected') {
  13710. // estos hack to reject an m-line.
  13711. tmp.port = '0';
  13712. }
  13713. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  13714. if (sctp.length)
  13715. tmp.proto = 'DTLS/SCTP';
  13716. else
  13717. tmp.proto = 'RTP/SAVPF';
  13718. } else {
  13719. tmp.proto = 'RTP/AVPF';
  13720. }
  13721. if (!sctp.length)
  13722. {
  13723. tmp.fmt = desc.find('payload-type').map(
  13724. function () { return this.getAttribute('id'); }).get();
  13725. media += SDPUtil.build_mline(tmp) + '\r\n';
  13726. }
  13727. else
  13728. {
  13729. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  13730. media += 'a=sctpmap:' + sctp.attr('number') +
  13731. ' ' + sctp.attr('protocol');
  13732. var streamCount = sctp.attr('streams');
  13733. if (streamCount)
  13734. media += ' ' + streamCount + '\r\n';
  13735. else
  13736. media += '\r\n';
  13737. }
  13738. media += 'c=IN IP4 0.0.0.0\r\n';
  13739. if (!sctp.length)
  13740. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  13741. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  13742. if (tmp.length) {
  13743. if (tmp.attr('ufrag')) {
  13744. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  13745. }
  13746. if (tmp.attr('pwd')) {
  13747. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  13748. }
  13749. tmp.find('>fingerprint').each(function () {
  13750. // FIXME: check namespace at some point
  13751. media += 'a=fingerprint:' + this.getAttribute('hash');
  13752. media += ' ' + $(this).text();
  13753. media += '\r\n';
  13754. if (this.getAttribute('setup')) {
  13755. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  13756. }
  13757. });
  13758. }
  13759. switch (content.attr('senders')) {
  13760. case 'initiator':
  13761. media += 'a=sendonly\r\n';
  13762. break;
  13763. case 'responder':
  13764. media += 'a=recvonly\r\n';
  13765. break;
  13766. case 'none':
  13767. media += 'a=inactive\r\n';
  13768. break;
  13769. case 'both':
  13770. media += 'a=sendrecv\r\n';
  13771. break;
  13772. }
  13773. media += 'a=mid:' + content.attr('name') + '\r\n';
  13774. // <description><rtcp-mux/></description>
  13775. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  13776. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  13777. if (desc.find('rtcp-mux').length) {
  13778. media += 'a=rtcp-mux\r\n';
  13779. }
  13780. if (desc.find('encryption').length) {
  13781. desc.find('encryption>crypto').each(function () {
  13782. media += 'a=crypto:' + this.getAttribute('tag');
  13783. media += ' ' + this.getAttribute('crypto-suite');
  13784. media += ' ' + this.getAttribute('key-params');
  13785. if (this.getAttribute('session-params')) {
  13786. media += ' ' + this.getAttribute('session-params');
  13787. }
  13788. media += '\r\n';
  13789. });
  13790. }
  13791. desc.find('payload-type').each(function () {
  13792. media += SDPUtil.build_rtpmap(this) + '\r\n';
  13793. if ($(this).find('>parameter').length) {
  13794. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  13795. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  13796. media += '\r\n';
  13797. }
  13798. // xep-0293
  13799. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  13800. });
  13801. // xep-0293
  13802. media += self.RtcpFbFromJingle(desc, '*');
  13803. // xep-0294
  13804. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  13805. tmp.each(function () {
  13806. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  13807. });
  13808. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  13809. media += SDPUtil.candidateFromJingle(this);
  13810. });
  13811. // XEP-0339 handle ssrc-group attributes
  13812. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  13813. var semantics = this.getAttribute('semantics');
  13814. var ssrcs = $(this).find('>source').map(function() {
  13815. return this.getAttribute('ssrc');
  13816. }).get();
  13817. if (ssrcs.length != 0) {
  13818. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  13819. }
  13820. });
  13821. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  13822. tmp.each(function () {
  13823. var ssrc = this.getAttribute('ssrc');
  13824. $(this).find('>parameter').each(function () {
  13825. var name = this.getAttribute('name');
  13826. var value = this.getAttribute('value');
  13827. value = SDPUtil.filter_special_chars(value);
  13828. media += 'a=ssrc:' + ssrc + ' ' + name;
  13829. if (value && value.length)
  13830. media += ':' + value;
  13831. media += '\r\n';
  13832. });
  13833. });
  13834. return media;
  13835. };
  13836. module.exports = SDP;
  13837. },{"./SDPUtil":58}],57:[function(require,module,exports){
  13838. var SDPUtil = require("./SDPUtil");
  13839. function SDPDiffer(mySDP, otherSDP) {
  13840. this.mySDP = mySDP;
  13841. this.otherSDP = otherSDP;
  13842. }
  13843. /**
  13844. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  13845. * @param otherSdp the other SDP to check ssrc with.
  13846. */
  13847. SDPDiffer.prototype.getNewMedia = function() {
  13848. // this could be useful in Array.prototype.
  13849. function arrayEquals(array) {
  13850. // if the other array is a falsy value, return
  13851. if (!array)
  13852. return false;
  13853. // compare lengths - can save a lot of time
  13854. if (this.length != array.length)
  13855. return false;
  13856. for (var i = 0, l=this.length; i < l; i++) {
  13857. // Check if we have nested arrays
  13858. if (this[i] instanceof Array && array[i] instanceof Array) {
  13859. // recurse into the nested arrays
  13860. if (!this[i].equals(array[i]))
  13861. return false;
  13862. }
  13863. else if (this[i] != array[i]) {
  13864. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  13865. return false;
  13866. }
  13867. }
  13868. return true;
  13869. }
  13870. var myMedias = this.mySDP.getMediaSsrcMap();
  13871. var othersMedias = this.otherSDP.getMediaSsrcMap();
  13872. var newMedia = {};
  13873. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  13874. var myMedia = myMedias[othersMediaIdx];
  13875. var othersMedia = othersMedias[othersMediaIdx];
  13876. if(!myMedia && othersMedia) {
  13877. // Add whole channel
  13878. newMedia[othersMediaIdx] = othersMedia;
  13879. return;
  13880. }
  13881. // Look for new ssrcs accross the channel
  13882. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  13883. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  13884. // Allocate channel if we've found ssrc that doesn't exist in our channel
  13885. if(!newMedia[othersMediaIdx]){
  13886. newMedia[othersMediaIdx] = {
  13887. mediaindex: othersMedia.mediaindex,
  13888. mid: othersMedia.mid,
  13889. ssrcs: {},
  13890. ssrcGroups: []
  13891. };
  13892. }
  13893. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  13894. }
  13895. });
  13896. // Look for new ssrc groups across the channels
  13897. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  13898. // try to match the other ssrc-group with an ssrc-group of ours
  13899. var matched = false;
  13900. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  13901. var mySsrcGroup = myMedia.ssrcGroups[i];
  13902. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  13903. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  13904. matched = true;
  13905. break;
  13906. }
  13907. }
  13908. if (!matched) {
  13909. // Allocate channel if we've found an ssrc-group that doesn't
  13910. // exist in our channel
  13911. if(!newMedia[othersMediaIdx]){
  13912. newMedia[othersMediaIdx] = {
  13913. mediaindex: othersMedia.mediaindex,
  13914. mid: othersMedia.mid,
  13915. ssrcs: {},
  13916. ssrcGroups: []
  13917. };
  13918. }
  13919. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  13920. }
  13921. });
  13922. });
  13923. return newMedia;
  13924. };
  13925. /**
  13926. * Sends SSRC update IQ.
  13927. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  13928. * @param sid session identifier that will be put into the IQ.
  13929. * @param initiator initiator identifier.
  13930. * @param toJid destination Jid
  13931. * @param isAdd indicates if this is remove or add operation.
  13932. */
  13933. SDPDiffer.prototype.toJingle = function(modify) {
  13934. var sdpMediaSsrcs = this.getNewMedia();
  13935. var self = this;
  13936. // FIXME: only announce video ssrcs since we mix audio and dont need
  13937. // the audio ssrcs therefore
  13938. var modified = false;
  13939. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  13940. modified = true;
  13941. var media = sdpMediaSsrcs[mediaindex];
  13942. modify.c('content', {name: media.mid});
  13943. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  13944. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  13945. // generate sources from lines
  13946. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  13947. var mediaSsrc = media.ssrcs[ssrcNum];
  13948. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13949. modify.attrs({ssrc: mediaSsrc.ssrc});
  13950. // iterate over ssrc lines
  13951. mediaSsrc.lines.forEach(function (line) {
  13952. var idx = line.indexOf(' ');
  13953. var kv = line.substr(idx + 1);
  13954. modify.c('parameter');
  13955. if (kv.indexOf(':') == -1) {
  13956. modify.attrs({ name: kv });
  13957. } else {
  13958. var nv = kv.split(':', 2);
  13959. var name = nv[0];
  13960. var value = SDPUtil.filter_special_chars(nv[1]);
  13961. modify.attrs({ name: name });
  13962. modify.attrs({ value: value });
  13963. }
  13964. modify.up(); // end of parameter
  13965. });
  13966. modify.up(); // end of source
  13967. });
  13968. // generate source groups from lines
  13969. media.ssrcGroups.forEach(function(ssrcGroup) {
  13970. if (ssrcGroup.ssrcs.length != 0) {
  13971. modify.c('ssrc-group', {
  13972. semantics: ssrcGroup.semantics,
  13973. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  13974. });
  13975. ssrcGroup.ssrcs.forEach(function (ssrc) {
  13976. modify.c('source', { ssrc: ssrc })
  13977. .up(); // end of source
  13978. });
  13979. modify.up(); // end of ssrc-group
  13980. }
  13981. });
  13982. modify.up(); // end of description
  13983. modify.up(); // end of content
  13984. });
  13985. return modified;
  13986. };
  13987. module.exports = SDPDiffer;
  13988. },{"./SDPUtil":58}],58:[function(require,module,exports){
  13989. SDPUtil = {
  13990. filter_special_chars: function (text) {
  13991. return text.replace(/[\\\/\{,\}\+]/g, "");
  13992. },
  13993. iceparams: function (mediadesc, sessiondesc) {
  13994. var data = null;
  13995. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  13996. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  13997. data = {
  13998. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  13999. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  14000. };
  14001. }
  14002. return data;
  14003. },
  14004. parse_iceufrag: function (line) {
  14005. return line.substring(12);
  14006. },
  14007. build_iceufrag: function (frag) {
  14008. return 'a=ice-ufrag:' + frag;
  14009. },
  14010. parse_icepwd: function (line) {
  14011. return line.substring(10);
  14012. },
  14013. build_icepwd: function (pwd) {
  14014. return 'a=ice-pwd:' + pwd;
  14015. },
  14016. parse_mid: function (line) {
  14017. return line.substring(6);
  14018. },
  14019. parse_mline: function (line) {
  14020. var parts = line.substring(2).split(' '),
  14021. data = {};
  14022. data.media = parts.shift();
  14023. data.port = parts.shift();
  14024. data.proto = parts.shift();
  14025. if (parts[parts.length - 1] === '') { // trailing whitespace
  14026. parts.pop();
  14027. }
  14028. data.fmt = parts;
  14029. return data;
  14030. },
  14031. build_mline: function (mline) {
  14032. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  14033. },
  14034. parse_rtpmap: function (line) {
  14035. var parts = line.substring(9).split(' '),
  14036. data = {};
  14037. data.id = parts.shift();
  14038. parts = parts[0].split('/');
  14039. data.name = parts.shift();
  14040. data.clockrate = parts.shift();
  14041. data.channels = parts.length ? parts.shift() : '1';
  14042. return data;
  14043. },
  14044. /**
  14045. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  14046. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  14047. * @returns [SCTP port number, protocol, streams]
  14048. */
  14049. parse_sctpmap: function (line)
  14050. {
  14051. var parts = line.substring(10).split(' ');
  14052. var sctpPort = parts[0];
  14053. var protocol = parts[1];
  14054. // Stream count is optional
  14055. var streamCount = parts.length > 2 ? parts[2] : null;
  14056. return [sctpPort, protocol, streamCount];// SCTP port
  14057. },
  14058. build_rtpmap: function (el) {
  14059. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  14060. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  14061. line += '/' + el.getAttribute('channels');
  14062. }
  14063. return line;
  14064. },
  14065. parse_crypto: function (line) {
  14066. var parts = line.substring(9).split(' '),
  14067. data = {};
  14068. data.tag = parts.shift();
  14069. data['crypto-suite'] = parts.shift();
  14070. data['key-params'] = parts.shift();
  14071. if (parts.length) {
  14072. data['session-params'] = parts.join(' ');
  14073. }
  14074. return data;
  14075. },
  14076. parse_fingerprint: function (line) { // RFC 4572
  14077. var parts = line.substring(14).split(' '),
  14078. data = {};
  14079. data.hash = parts.shift();
  14080. data.fingerprint = parts.shift();
  14081. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  14082. return data;
  14083. },
  14084. parse_fmtp: function (line) {
  14085. var parts = line.split(' '),
  14086. i, key, value,
  14087. data = [];
  14088. parts.shift();
  14089. parts = parts.join(' ').split(';');
  14090. for (i = 0; i < parts.length; i++) {
  14091. key = parts[i].split('=')[0];
  14092. while (key.length && key[0] == ' ') {
  14093. key = key.substring(1);
  14094. }
  14095. value = parts[i].split('=')[1];
  14096. if (key && value) {
  14097. data.push({name: key, value: value});
  14098. } else if (key) {
  14099. // rfc 4733 (DTMF) style stuff
  14100. data.push({name: '', value: key});
  14101. }
  14102. }
  14103. return data;
  14104. },
  14105. parse_icecandidate: function (line) {
  14106. var candidate = {},
  14107. elems = line.split(' ');
  14108. candidate.foundation = elems[0].substring(12);
  14109. candidate.component = elems[1];
  14110. candidate.protocol = elems[2].toLowerCase();
  14111. candidate.priority = elems[3];
  14112. candidate.ip = elems[4];
  14113. candidate.port = elems[5];
  14114. // elems[6] => "typ"
  14115. candidate.type = elems[7];
  14116. candidate.generation = 0; // default value, may be overwritten below
  14117. for (var i = 8; i < elems.length; i += 2) {
  14118. switch (elems[i]) {
  14119. case 'raddr':
  14120. candidate['rel-addr'] = elems[i + 1];
  14121. break;
  14122. case 'rport':
  14123. candidate['rel-port'] = elems[i + 1];
  14124. break;
  14125. case 'generation':
  14126. candidate.generation = elems[i + 1];
  14127. break;
  14128. case 'tcptype':
  14129. candidate.tcptype = elems[i + 1];
  14130. break;
  14131. default: // TODO
  14132. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  14133. }
  14134. }
  14135. candidate.network = '1';
  14136. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  14137. return candidate;
  14138. },
  14139. build_icecandidate: function (cand) {
  14140. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  14141. line += ' ';
  14142. switch (cand.type) {
  14143. case 'srflx':
  14144. case 'prflx':
  14145. case 'relay':
  14146. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  14147. line += 'raddr';
  14148. line += ' ';
  14149. line += cand['rel-addr'];
  14150. line += ' ';
  14151. line += 'rport';
  14152. line += ' ';
  14153. line += cand['rel-port'];
  14154. line += ' ';
  14155. }
  14156. break;
  14157. }
  14158. if (cand.hasOwnAttribute('tcptype')) {
  14159. line += 'tcptype';
  14160. line += ' ';
  14161. line += cand.tcptype;
  14162. line += ' ';
  14163. }
  14164. line += 'generation';
  14165. line += ' ';
  14166. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  14167. return line;
  14168. },
  14169. parse_ssrc: function (desc) {
  14170. // proprietary mapping of a=ssrc lines
  14171. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  14172. // and parse according to that
  14173. var lines = desc.split('\r\n'),
  14174. data = {};
  14175. for (var i = 0; i < lines.length; i++) {
  14176. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  14177. var idx = lines[i].indexOf(' ');
  14178. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  14179. }
  14180. }
  14181. return data;
  14182. },
  14183. parse_rtcpfb: function (line) {
  14184. var parts = line.substr(10).split(' ');
  14185. var data = {};
  14186. data.pt = parts.shift();
  14187. data.type = parts.shift();
  14188. data.params = parts;
  14189. return data;
  14190. },
  14191. parse_extmap: function (line) {
  14192. var parts = line.substr(9).split(' ');
  14193. var data = {};
  14194. data.value = parts.shift();
  14195. if (data.value.indexOf('/') != -1) {
  14196. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  14197. data.value = data.value.substr(0, data.value.indexOf('/'));
  14198. } else {
  14199. data.direction = 'both';
  14200. }
  14201. data.uri = parts.shift();
  14202. data.params = parts;
  14203. return data;
  14204. },
  14205. find_line: function (haystack, needle, sessionpart) {
  14206. var lines = haystack.split('\r\n');
  14207. for (var i = 0; i < lines.length; i++) {
  14208. if (lines[i].substring(0, needle.length) == needle) {
  14209. return lines[i];
  14210. }
  14211. }
  14212. if (!sessionpart) {
  14213. return false;
  14214. }
  14215. // search session part
  14216. lines = sessionpart.split('\r\n');
  14217. for (var j = 0; j < lines.length; j++) {
  14218. if (lines[j].substring(0, needle.length) == needle) {
  14219. return lines[j];
  14220. }
  14221. }
  14222. return false;
  14223. },
  14224. find_lines: function (haystack, needle, sessionpart) {
  14225. var lines = haystack.split('\r\n'),
  14226. needles = [];
  14227. for (var i = 0; i < lines.length; i++) {
  14228. if (lines[i].substring(0, needle.length) == needle)
  14229. needles.push(lines[i]);
  14230. }
  14231. if (needles.length || !sessionpart) {
  14232. return needles;
  14233. }
  14234. // search session part
  14235. lines = sessionpart.split('\r\n');
  14236. for (var j = 0; j < lines.length; j++) {
  14237. if (lines[j].substring(0, needle.length) == needle) {
  14238. needles.push(lines[j]);
  14239. }
  14240. }
  14241. return needles;
  14242. },
  14243. candidateToJingle: function (line) {
  14244. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  14245. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  14246. if (line.indexOf('candidate:') === 0) {
  14247. line = 'a=' + line;
  14248. } else if (line.substring(0, 12) != 'a=candidate:') {
  14249. console.log('parseCandidate called with a line that is not a candidate line');
  14250. console.log(line);
  14251. return null;
  14252. }
  14253. if (line.substring(line.length - 2) == '\r\n') // chomp it
  14254. line = line.substring(0, line.length - 2);
  14255. var candidate = {},
  14256. elems = line.split(' '),
  14257. i;
  14258. if (elems[6] != 'typ') {
  14259. console.log('did not find typ in the right place');
  14260. console.log(line);
  14261. return null;
  14262. }
  14263. candidate.foundation = elems[0].substring(12);
  14264. candidate.component = elems[1];
  14265. candidate.protocol = elems[2].toLowerCase();
  14266. candidate.priority = elems[3];
  14267. candidate.ip = elems[4];
  14268. candidate.port = elems[5];
  14269. // elems[6] => "typ"
  14270. candidate.type = elems[7];
  14271. candidate.generation = '0'; // default, may be overwritten below
  14272. for (i = 8; i < elems.length; i += 2) {
  14273. switch (elems[i]) {
  14274. case 'raddr':
  14275. candidate['rel-addr'] = elems[i + 1];
  14276. break;
  14277. case 'rport':
  14278. candidate['rel-port'] = elems[i + 1];
  14279. break;
  14280. case 'generation':
  14281. candidate.generation = elems[i + 1];
  14282. break;
  14283. case 'tcptype':
  14284. candidate.tcptype = elems[i + 1];
  14285. break;
  14286. default: // TODO
  14287. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  14288. }
  14289. }
  14290. candidate.network = '1';
  14291. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  14292. return candidate;
  14293. },
  14294. candidateFromJingle: function (cand) {
  14295. var line = 'a=candidate:';
  14296. line += cand.getAttribute('foundation');
  14297. line += ' ';
  14298. line += cand.getAttribute('component');
  14299. line += ' ';
  14300. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  14301. line += ' ';
  14302. line += cand.getAttribute('priority');
  14303. line += ' ';
  14304. line += cand.getAttribute('ip');
  14305. line += ' ';
  14306. line += cand.getAttribute('port');
  14307. line += ' ';
  14308. line += 'typ';
  14309. line += ' ' + cand.getAttribute('type');
  14310. line += ' ';
  14311. switch (cand.getAttribute('type')) {
  14312. case 'srflx':
  14313. case 'prflx':
  14314. case 'relay':
  14315. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  14316. line += 'raddr';
  14317. line += ' ';
  14318. line += cand.getAttribute('rel-addr');
  14319. line += ' ';
  14320. line += 'rport';
  14321. line += ' ';
  14322. line += cand.getAttribute('rel-port');
  14323. line += ' ';
  14324. }
  14325. break;
  14326. }
  14327. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  14328. line += 'tcptype';
  14329. line += ' ';
  14330. line += cand.getAttribute('tcptype');
  14331. line += ' ';
  14332. }
  14333. line += 'generation';
  14334. line += ' ';
  14335. line += cand.getAttribute('generation') || '0';
  14336. return line + '\r\n';
  14337. }
  14338. };
  14339. module.exports = SDPUtil;
  14340. },{}],59:[function(require,module,exports){
  14341. var RTC = require('../RTC/RTC');
  14342. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  14343. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14344. var SSRCReplacement = require("./LocalSSRCReplacement");
  14345. function TraceablePeerConnection(ice_config, constraints, session) {
  14346. var self = this;
  14347. var RTCPeerConnectionType = null;
  14348. if (RTCBrowserType.isFirefox()) {
  14349. RTCPeerConnectionType = mozRTCPeerConnection;
  14350. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  14351. RTCPeerConnectionType = RTCPeerConnection;
  14352. } else {
  14353. RTCPeerConnectionType = webkitRTCPeerConnection;
  14354. }
  14355. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  14356. this.updateLog = [];
  14357. this.stats = {};
  14358. this.statsinterval = null;
  14359. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  14360. var Interop = require('sdp-interop').Interop;
  14361. this.interop = new Interop();
  14362. var Simulcast = require('sdp-simulcast');
  14363. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  14364. // override as desired
  14365. this.trace = function (what, info) {
  14366. /*console.warn('WTRACE', what, info);
  14367. if (info && RTCBrowserType.isIExplorer()) {
  14368. if (info.length > 1024) {
  14369. console.warn('WTRACE', what, info.substr(1024));
  14370. }
  14371. if (info.length > 2048) {
  14372. console.warn('WTRACE', what, info.substr(2048));
  14373. }
  14374. }*/
  14375. self.updateLog.push({
  14376. time: new Date(),
  14377. type: what,
  14378. value: info || ""
  14379. });
  14380. };
  14381. this.onicecandidate = null;
  14382. this.peerconnection.onicecandidate = function (event) {
  14383. // FIXME: this causes stack overflow with Temasys Plugin
  14384. if (!RTCBrowserType.isTemasysPluginUsed())
  14385. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  14386. if (self.onicecandidate !== null) {
  14387. self.onicecandidate(event);
  14388. }
  14389. };
  14390. this.onaddstream = null;
  14391. this.peerconnection.onaddstream = function (event) {
  14392. self.trace('onaddstream', event.stream.id);
  14393. if (self.onaddstream !== null) {
  14394. self.onaddstream(event);
  14395. }
  14396. };
  14397. this.onremovestream = null;
  14398. this.peerconnection.onremovestream = function (event) {
  14399. self.trace('onremovestream', event.stream.id);
  14400. if (self.onremovestream !== null) {
  14401. self.onremovestream(event);
  14402. }
  14403. };
  14404. this.onsignalingstatechange = null;
  14405. this.peerconnection.onsignalingstatechange = function (event) {
  14406. self.trace('onsignalingstatechange', self.signalingState);
  14407. if (self.onsignalingstatechange !== null) {
  14408. self.onsignalingstatechange(event);
  14409. }
  14410. };
  14411. this.oniceconnectionstatechange = null;
  14412. this.peerconnection.oniceconnectionstatechange = function (event) {
  14413. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  14414. if (self.oniceconnectionstatechange !== null) {
  14415. self.oniceconnectionstatechange(event);
  14416. }
  14417. };
  14418. this.onnegotiationneeded = null;
  14419. this.peerconnection.onnegotiationneeded = function (event) {
  14420. self.trace('onnegotiationneeded');
  14421. if (self.onnegotiationneeded !== null) {
  14422. self.onnegotiationneeded(event);
  14423. }
  14424. };
  14425. self.ondatachannel = null;
  14426. this.peerconnection.ondatachannel = function (event) {
  14427. self.trace('ondatachannel', event);
  14428. if (self.ondatachannel !== null) {
  14429. self.ondatachannel(event);
  14430. }
  14431. };
  14432. // XXX: do all non-firefox browsers which we support also support this?
  14433. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  14434. this.statsinterval = window.setInterval(function() {
  14435. self.peerconnection.getStats(function(stats) {
  14436. var results = stats.result();
  14437. var now = new Date();
  14438. for (var i = 0; i < results.length; ++i) {
  14439. results[i].names().forEach(function (name) {
  14440. var id = results[i].id + '-' + name;
  14441. if (!self.stats[id]) {
  14442. self.stats[id] = {
  14443. startTime: now,
  14444. endTime: now,
  14445. values: [],
  14446. times: []
  14447. };
  14448. }
  14449. self.stats[id].values.push(results[i].stat(name));
  14450. self.stats[id].times.push(now.getTime());
  14451. if (self.stats[id].values.length > self.maxstats) {
  14452. self.stats[id].values.shift();
  14453. self.stats[id].times.shift();
  14454. }
  14455. self.stats[id].endTime = now;
  14456. });
  14457. }
  14458. });
  14459. }, 1000);
  14460. }
  14461. }
  14462. /**
  14463. * Returns a string representation of a SessionDescription object.
  14464. */
  14465. var dumpSDP = function(description) {
  14466. if (typeof description === 'undefined' || description == null) {
  14467. return '';
  14468. }
  14469. return 'type: ' + description.type + '\r\n' + description.sdp;
  14470. };
  14471. /**
  14472. * Takes a SessionDescription object and returns a "normalized" version.
  14473. * Currently it only takes care of ordering the a=ssrc lines.
  14474. */
  14475. var normalizePlanB = function(desc) {
  14476. if (typeof desc !== 'object' || desc === null ||
  14477. typeof desc.sdp !== 'string') {
  14478. console.warn('An empty description was passed as an argument.');
  14479. return desc;
  14480. }
  14481. var transform = require('sdp-transform');
  14482. var session = transform.parse(desc.sdp);
  14483. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  14484. Array.isArray(session.media)) {
  14485. session.media.forEach(function (mLine) {
  14486. // Chrome appears to be picky about the order in which a=ssrc lines
  14487. // are listed in an m-line when rtx is enabled (and thus there are
  14488. // a=ssrc-group lines with FID semantics). Specifically if we have
  14489. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  14490. // the "a=ssrc:S1" lines, SRD fails.
  14491. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  14492. // first.
  14493. var firstSsrcs = [];
  14494. var newSsrcLines = [];
  14495. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  14496. mLine.ssrcGroups.forEach(function (group) {
  14497. if (typeof group.semantics !== 'undefined' &&
  14498. group.semantics === 'FID') {
  14499. if (typeof group.ssrcs !== 'undefined') {
  14500. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  14501. }
  14502. }
  14503. });
  14504. }
  14505. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  14506. for (var i = 0; i<mLine.ssrcs.length; i++){
  14507. if (typeof mLine.ssrcs[i] === 'object'
  14508. && typeof mLine.ssrcs[i].id !== 'undefined'
  14509. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  14510. newSsrcLines.push(mLine.ssrcs[i]);
  14511. delete mLine.ssrcs[i];
  14512. }
  14513. }
  14514. for (var i = 0; i<mLine.ssrcs.length; i++){
  14515. if (typeof mLine.ssrcs[i] !== 'undefined') {
  14516. newSsrcLines.push(mLine.ssrcs[i]);
  14517. }
  14518. }
  14519. mLine.ssrcs = newSsrcLines;
  14520. }
  14521. });
  14522. }
  14523. var resStr = transform.write(session);
  14524. return new RTCSessionDescription({
  14525. type: desc.type,
  14526. sdp: resStr
  14527. });
  14528. };
  14529. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  14530. TraceablePeerConnection.prototype.__defineGetter__(
  14531. 'signalingState',
  14532. function() { return this.peerconnection.signalingState; });
  14533. TraceablePeerConnection.prototype.__defineGetter__(
  14534. 'iceConnectionState',
  14535. function() { return this.peerconnection.iceConnectionState; });
  14536. TraceablePeerConnection.prototype.__defineGetter__(
  14537. 'localDescription',
  14538. function() {
  14539. var desc = this.peerconnection.localDescription;
  14540. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  14541. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  14542. // if we're running on FF, transform to Plan B first.
  14543. if (RTCBrowserType.usesUnifiedPlan()) {
  14544. desc = this.interop.toPlanB(desc);
  14545. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  14546. }
  14547. return desc;
  14548. });
  14549. TraceablePeerConnection.prototype.__defineGetter__(
  14550. 'remoteDescription',
  14551. function() {
  14552. var desc = this.peerconnection.remoteDescription;
  14553. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  14554. // if we're running on FF, transform to Plan B first.
  14555. if (RTCBrowserType.usesUnifiedPlan()) {
  14556. desc = this.interop.toPlanB(desc);
  14557. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  14558. }
  14559. return desc;
  14560. });
  14561. }
  14562. TraceablePeerConnection.prototype.addStream = function (stream) {
  14563. this.trace('addStream', stream.id);
  14564. try
  14565. {
  14566. this.peerconnection.addStream(stream);
  14567. }
  14568. catch (e)
  14569. {
  14570. console.error(e);
  14571. }
  14572. };
  14573. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  14574. this.trace('removeStream', stream.id);
  14575. if(stopStreams) {
  14576. stream.getAudioTracks().forEach(function (track) {
  14577. // stop() not supported with IE
  14578. if (track.stop) {
  14579. track.stop();
  14580. }
  14581. });
  14582. stream.getVideoTracks().forEach(function (track) {
  14583. // stop() not supported with IE
  14584. if (track.stop) {
  14585. track.stop();
  14586. }
  14587. });
  14588. if (stream.stop) {
  14589. stream.stop();
  14590. }
  14591. }
  14592. try {
  14593. // FF doesn't support this yet.
  14594. if (this.peerconnection.removeStream)
  14595. this.peerconnection.removeStream(stream);
  14596. } catch (e) {
  14597. console.error(e);
  14598. }
  14599. };
  14600. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  14601. this.trace('createDataChannel', label, opts);
  14602. return this.peerconnection.createDataChannel(label, opts);
  14603. };
  14604. TraceablePeerConnection.prototype.setLocalDescription
  14605. = function (description, successCallback, failureCallback) {
  14606. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  14607. // if we're running on FF, transform to Plan A first.
  14608. if (RTCBrowserType.usesUnifiedPlan()) {
  14609. description = this.interop.toUnifiedPlan(description);
  14610. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  14611. }
  14612. var self = this;
  14613. this.peerconnection.setLocalDescription(description,
  14614. function () {
  14615. self.trace('setLocalDescriptionOnSuccess');
  14616. successCallback();
  14617. },
  14618. function (err) {
  14619. self.trace('setLocalDescriptionOnFailure', err);
  14620. failureCallback(err);
  14621. }
  14622. );
  14623. /*
  14624. if (this.statsinterval === null && this.maxstats > 0) {
  14625. // start gathering stats
  14626. }
  14627. */
  14628. };
  14629. TraceablePeerConnection.prototype.setRemoteDescription
  14630. = function (description, successCallback, failureCallback) {
  14631. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  14632. // TODO the focus should squeze or explode the remote simulcast
  14633. description = this.simulcast.mungeRemoteDescription(description);
  14634. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  14635. // if we're running on FF, transform to Plan A first.
  14636. if (RTCBrowserType.usesUnifiedPlan()) {
  14637. description = this.interop.toUnifiedPlan(description);
  14638. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  14639. }
  14640. if (RTCBrowserType.usesPlanB()) {
  14641. description = normalizePlanB(description);
  14642. }
  14643. var self = this;
  14644. this.peerconnection.setRemoteDescription(description,
  14645. function () {
  14646. self.trace('setRemoteDescriptionOnSuccess');
  14647. successCallback();
  14648. },
  14649. function (err) {
  14650. self.trace('setRemoteDescriptionOnFailure', err);
  14651. failureCallback(err);
  14652. }
  14653. );
  14654. /*
  14655. if (this.statsinterval === null && this.maxstats > 0) {
  14656. // start gathering stats
  14657. }
  14658. */
  14659. };
  14660. TraceablePeerConnection.prototype.close = function () {
  14661. this.trace('stop');
  14662. if (this.statsinterval !== null) {
  14663. window.clearInterval(this.statsinterval);
  14664. this.statsinterval = null;
  14665. }
  14666. this.peerconnection.close();
  14667. };
  14668. TraceablePeerConnection.prototype.createOffer
  14669. = function (successCallback, failureCallback, constraints) {
  14670. var self = this;
  14671. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  14672. this.peerconnection.createOffer(
  14673. function (offer) {
  14674. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  14675. // NOTE this is not tested because in meet the focus generates the
  14676. // offer.
  14677. // if we're running on FF, transform to Plan B first.
  14678. if (RTCBrowserType.usesUnifiedPlan()) {
  14679. offer = self.interop.toPlanB(offer);
  14680. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  14681. }
  14682. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  14683. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14684. offer = self.simulcast.mungeLocalDescription(offer);
  14685. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  14686. }
  14687. successCallback(offer);
  14688. },
  14689. function(err) {
  14690. self.trace('createOfferOnFailure', err);
  14691. failureCallback(err);
  14692. },
  14693. constraints
  14694. );
  14695. };
  14696. TraceablePeerConnection.prototype.createAnswer
  14697. = function (successCallback, failureCallback, constraints) {
  14698. var self = this;
  14699. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  14700. this.peerconnection.createAnswer(
  14701. function (answer) {
  14702. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  14703. // if we're running on FF, transform to Plan A first.
  14704. if (RTCBrowserType.usesUnifiedPlan()) {
  14705. answer = self.interop.toPlanB(answer);
  14706. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  14707. }
  14708. // munge local video SSRC
  14709. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  14710. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14711. answer = self.simulcast.mungeLocalDescription(answer);
  14712. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  14713. }
  14714. successCallback(answer);
  14715. },
  14716. function(err) {
  14717. self.trace('createAnswerOnFailure', err);
  14718. failureCallback(err);
  14719. },
  14720. constraints
  14721. );
  14722. };
  14723. TraceablePeerConnection.prototype.addIceCandidate
  14724. = function (candidate, successCallback, failureCallback) {
  14725. //var self = this;
  14726. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  14727. this.peerconnection.addIceCandidate(candidate);
  14728. /* maybe later
  14729. this.peerconnection.addIceCandidate(candidate,
  14730. function () {
  14731. self.trace('addIceCandidateOnSuccess');
  14732. successCallback();
  14733. },
  14734. function (err) {
  14735. self.trace('addIceCandidateOnFailure', err);
  14736. failureCallback(err);
  14737. }
  14738. );
  14739. */
  14740. };
  14741. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  14742. // TODO: Is this the correct way to handle Opera, Temasys?
  14743. if (RTCBrowserType.isFirefox()) {
  14744. // ignore for now...
  14745. if(!errback)
  14746. errback = function () {};
  14747. this.peerconnection.getStats(null, callback, errback);
  14748. } else {
  14749. this.peerconnection.getStats(callback);
  14750. }
  14751. };
  14752. module.exports = TraceablePeerConnection;
  14753. },{"../../service/xmpp/XMPPEvents":161,"../RTC/RTC":7,"../RTC/RTCBrowserType.js":8,"./LocalSSRCReplacement":55,"sdp-interop":92,"sdp-simulcast":95,"sdp-transform":98}],60:[function(require,module,exports){
  14754. /* global $, $iq, APP, config, messageHandler,
  14755. roomName, sessionTerminated, Strophe, Util */
  14756. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14757. var Settings = require("../settings/Settings");
  14758. var AuthenticationEvents
  14759. = require("../../service/authentication/AuthenticationEvents");
  14760. /**
  14761. * Contains logic responsible for enabling/disabling functionality available
  14762. * only to moderator users.
  14763. */
  14764. var connection = null;
  14765. var focusUserJid;
  14766. function createExpBackoffTimer(step) {
  14767. var count = 1;
  14768. return function (reset) {
  14769. // Reset call
  14770. if (reset) {
  14771. count = 1;
  14772. return;
  14773. }
  14774. // Calculate next timeout
  14775. var timeout = Math.pow(2, count - 1);
  14776. count += 1;
  14777. return timeout * step;
  14778. };
  14779. }
  14780. var getNextTimeout = createExpBackoffTimer(1000);
  14781. var getNextErrorTimeout = createExpBackoffTimer(1000);
  14782. // External authentication stuff
  14783. var externalAuthEnabled = false;
  14784. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  14785. // it will be enabled automatically if focus detects the component through
  14786. // service discovery.
  14787. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  14788. var eventEmitter = null;
  14789. var Moderator = {
  14790. isModerator: function () {
  14791. return connection && connection.emuc.isModerator();
  14792. },
  14793. isPeerModerator: function (peerJid) {
  14794. return connection &&
  14795. connection.emuc.getMemberRole(peerJid) === 'moderator';
  14796. },
  14797. isExternalAuthEnabled: function () {
  14798. return externalAuthEnabled;
  14799. },
  14800. isSipGatewayEnabled: function () {
  14801. return sipGatewayEnabled;
  14802. },
  14803. setConnection: function (con) {
  14804. connection = con;
  14805. },
  14806. init: function (xmpp, emitter) {
  14807. this.xmppService = xmpp;
  14808. eventEmitter = emitter;
  14809. // Message listener that talks to POPUP window
  14810. function listener(event) {
  14811. if (event.data && event.data.sessionId) {
  14812. if (event.origin !== window.location.origin) {
  14813. console.warn("Ignoring sessionId from different origin: " +
  14814. event.origin);
  14815. return;
  14816. }
  14817. localStorage.setItem('sessionId', event.data.sessionId);
  14818. // After popup is closed we will authenticate
  14819. }
  14820. }
  14821. // Register
  14822. if (window.addEventListener) {
  14823. window.addEventListener("message", listener, false);
  14824. } else {
  14825. window.attachEvent("onmessage", listener);
  14826. }
  14827. },
  14828. onMucMemberLeft: function (jid) {
  14829. console.info("Someone left is it focus ? " + jid);
  14830. var resource = Strophe.getResourceFromJid(jid);
  14831. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  14832. console.info(
  14833. "Focus has left the room - leaving conference");
  14834. //hangUp();
  14835. // We'd rather reload to have everything re-initialized
  14836. // FIXME: show some message before reload
  14837. location.reload();
  14838. }
  14839. },
  14840. setFocusUserJid: function (focusJid) {
  14841. if (!focusUserJid) {
  14842. focusUserJid = focusJid;
  14843. console.info("Focus jid set to: " + focusUserJid);
  14844. }
  14845. },
  14846. getFocusUserJid: function () {
  14847. return focusUserJid;
  14848. },
  14849. getFocusComponent: function () {
  14850. // Get focus component address
  14851. var focusComponent = config.hosts.focus;
  14852. // If not specified use default: 'focus.domain'
  14853. if (!focusComponent) {
  14854. focusComponent = 'focus.' + config.hosts.domain;
  14855. }
  14856. return focusComponent;
  14857. },
  14858. createConferenceIq: function (roomName) {
  14859. // Generate create conference IQ
  14860. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14861. // Session Id used for authentication
  14862. var sessionId = localStorage.getItem('sessionId');
  14863. var machineUID = Settings.getSettings().uid;
  14864. console.info(
  14865. "Session ID: " + sessionId + " machine UID: " + machineUID);
  14866. elem.c('conference', {
  14867. xmlns: 'http://jitsi.org/protocol/focus',
  14868. room: roomName,
  14869. 'machine-uid': machineUID
  14870. });
  14871. if (sessionId) {
  14872. elem.attrs({ 'session-id': sessionId});
  14873. }
  14874. if (config.hosts.bridge !== undefined) {
  14875. elem.c(
  14876. 'property',
  14877. { name: 'bridge', value: config.hosts.bridge})
  14878. .up();
  14879. }
  14880. // Tell the focus we have Jigasi configured
  14881. if (config.hosts.call_control !== undefined) {
  14882. elem.c(
  14883. 'property',
  14884. { name: 'call_control', value: config.hosts.call_control})
  14885. .up();
  14886. }
  14887. if (config.channelLastN !== undefined) {
  14888. elem.c(
  14889. 'property',
  14890. { name: 'channelLastN', value: config.channelLastN})
  14891. .up();
  14892. }
  14893. if (config.adaptiveLastN !== undefined) {
  14894. elem.c(
  14895. 'property',
  14896. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  14897. .up();
  14898. }
  14899. if (config.adaptiveSimulcast !== undefined) {
  14900. elem.c(
  14901. 'property',
  14902. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  14903. .up();
  14904. }
  14905. if (config.openSctp !== undefined) {
  14906. elem.c(
  14907. 'property',
  14908. { name: 'openSctp', value: config.openSctp})
  14909. .up();
  14910. }
  14911. if(config.startAudioMuted !== undefined)
  14912. {
  14913. elem.c(
  14914. 'property',
  14915. { name: 'startAudioMuted', value: config.startAudioMuted})
  14916. .up();
  14917. }
  14918. if(config.startVideoMuted !== undefined)
  14919. {
  14920. elem.c(
  14921. 'property',
  14922. { name: 'startVideoMuted', value: config.startVideoMuted})
  14923. .up();
  14924. }
  14925. elem.c(
  14926. 'property',
  14927. { name: 'simulcastMode', value: 'rewriting'})
  14928. .up();
  14929. elem.up();
  14930. return elem;
  14931. },
  14932. parseSessionId: function (resultIq) {
  14933. var sessionId = $(resultIq).find('conference').attr('session-id');
  14934. if (sessionId) {
  14935. console.info('Received sessionId: ' + sessionId);
  14936. localStorage.setItem('sessionId', sessionId);
  14937. }
  14938. },
  14939. parseConfigOptions: function (resultIq) {
  14940. Moderator.setFocusUserJid(
  14941. $(resultIq).find('conference').attr('focusjid'));
  14942. var authenticationEnabled
  14943. = $(resultIq).find(
  14944. '>conference>property' +
  14945. '[name=\'authentication\'][value=\'true\']').length > 0;
  14946. console.info("Authentication enabled: " + authenticationEnabled);
  14947. externalAuthEnabled = $(resultIq).find(
  14948. '>conference>property' +
  14949. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  14950. console.info('External authentication enabled: ' + externalAuthEnabled);
  14951. if (!externalAuthEnabled) {
  14952. // We expect to receive sessionId in 'internal' authentication mode
  14953. Moderator.parseSessionId(resultIq);
  14954. }
  14955. var authIdentity = $(resultIq).find('>conference').attr('identity');
  14956. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  14957. authenticationEnabled, authIdentity);
  14958. // Check if focus has auto-detected Jigasi component(this will be also
  14959. // included if we have passed our host from the config)
  14960. if ($(resultIq).find(
  14961. '>conference>property' +
  14962. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  14963. sipGatewayEnabled = true;
  14964. }
  14965. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  14966. },
  14967. // FIXME: we need to show the fact that we're waiting for the focus
  14968. // to the user(or that focus is not available)
  14969. allocateConferenceFocus: function (roomName, callback) {
  14970. // Try to use focus user JID from the config
  14971. Moderator.setFocusUserJid(config.focusUserJid);
  14972. // Send create conference IQ
  14973. var iq = Moderator.createConferenceIq(roomName);
  14974. var self = this;
  14975. connection.sendIQ(
  14976. iq,
  14977. function (result) {
  14978. // Setup config options
  14979. Moderator.parseConfigOptions(result);
  14980. if ('true' === $(result).find('conference').attr('ready')) {
  14981. // Reset both timers
  14982. getNextTimeout(true);
  14983. getNextErrorTimeout(true);
  14984. // Exec callback
  14985. callback();
  14986. } else {
  14987. var waitMs = getNextTimeout();
  14988. console.info("Waiting for the focus... " + waitMs);
  14989. // Reset error timeout
  14990. getNextErrorTimeout(true);
  14991. window.setTimeout(
  14992. function () {
  14993. Moderator.allocateConferenceFocus(
  14994. roomName, callback);
  14995. }, waitMs);
  14996. }
  14997. },
  14998. function (error) {
  14999. // Invalid session ? remove and try again
  15000. // without session ID to get a new one
  15001. var invalidSession
  15002. = $(error).find('>error>session-invalid').length;
  15003. if (invalidSession) {
  15004. console.info("Session expired! - removing");
  15005. localStorage.removeItem("sessionId");
  15006. }
  15007. if ($(error).find('>error>graceful-shutdown').length) {
  15008. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  15009. return;
  15010. }
  15011. // Check for error returned by the reservation system
  15012. var reservationErr = $(error).find('>error>reservation-error');
  15013. if (reservationErr.length) {
  15014. // Trigger error event
  15015. var errorCode = reservationErr.attr('error-code');
  15016. var errorMsg;
  15017. if ($(error).find('>error>text')) {
  15018. errorMsg = $(error).find('>error>text').text();
  15019. }
  15020. eventEmitter.emit(
  15021. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  15022. return;
  15023. }
  15024. // Not authorized to create new room
  15025. if ($(error).find('>error>not-authorized').length) {
  15026. console.warn("Unauthorized to start the conference", error);
  15027. var toDomain
  15028. = Strophe.getDomainFromJid(error.getAttribute('to'));
  15029. if (toDomain !== config.hosts.anonymousdomain) {
  15030. // FIXME: "is external" should come either from
  15031. // the focus or config.js
  15032. externalAuthEnabled = true;
  15033. }
  15034. eventEmitter.emit(
  15035. XMPPEvents.AUTHENTICATION_REQUIRED,
  15036. function () {
  15037. Moderator.allocateConferenceFocus(
  15038. roomName, callback);
  15039. });
  15040. return;
  15041. }
  15042. var waitMs = getNextErrorTimeout();
  15043. console.error("Focus error, retry after " + waitMs, error);
  15044. // Show message
  15045. var focusComponent = Moderator.getFocusComponent();
  15046. var retrySec = waitMs / 1000;
  15047. // FIXME: message is duplicated ?
  15048. // Do not show in case of session invalid
  15049. // which means just a retry
  15050. if (!invalidSession) {
  15051. eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  15052. focusComponent, retrySec);
  15053. }
  15054. // Reset response timeout
  15055. getNextTimeout(true);
  15056. window.setTimeout(
  15057. function () {
  15058. Moderator.allocateConferenceFocus(roomName, callback);
  15059. }, waitMs);
  15060. }
  15061. );
  15062. },
  15063. getLoginUrl: function (roomName, urlCallback) {
  15064. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  15065. iq.c('login-url', {
  15066. xmlns: 'http://jitsi.org/protocol/focus',
  15067. room: roomName,
  15068. 'machine-uid': Settings.getSettings().uid
  15069. });
  15070. connection.sendIQ(
  15071. iq,
  15072. function (result) {
  15073. var url = $(result).find('login-url').attr('url');
  15074. url = url = decodeURIComponent(url);
  15075. if (url) {
  15076. console.info("Got auth url: " + url);
  15077. urlCallback(url);
  15078. } else {
  15079. console.error(
  15080. "Failed to get auth url from the focus", result);
  15081. }
  15082. },
  15083. function (error) {
  15084. console.error("Get auth url error", error);
  15085. }
  15086. );
  15087. },
  15088. getPopupLoginUrl: function (roomName, urlCallback) {
  15089. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  15090. iq.c('login-url', {
  15091. xmlns: 'http://jitsi.org/protocol/focus',
  15092. room: roomName,
  15093. 'machine-uid': Settings.getSettings().uid,
  15094. popup: true
  15095. });
  15096. connection.sendIQ(
  15097. iq,
  15098. function (result) {
  15099. var url = $(result).find('login-url').attr('url');
  15100. url = url = decodeURIComponent(url);
  15101. if (url) {
  15102. console.info("Got POPUP auth url: " + url);
  15103. urlCallback(url);
  15104. } else {
  15105. console.error(
  15106. "Failed to get POPUP auth url from the focus", result);
  15107. }
  15108. },
  15109. function (error) {
  15110. console.error('Get POPUP auth url error', error);
  15111. }
  15112. );
  15113. },
  15114. logout: function (callback) {
  15115. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  15116. var sessionId = localStorage.getItem('sessionId');
  15117. if (!sessionId) {
  15118. callback();
  15119. return;
  15120. }
  15121. iq.c('logout', {
  15122. xmlns: 'http://jitsi.org/protocol/focus',
  15123. 'session-id': sessionId
  15124. });
  15125. connection.sendIQ(
  15126. iq,
  15127. function (result) {
  15128. var logoutUrl = $(result).find('logout').attr('logout-url');
  15129. if (logoutUrl) {
  15130. logoutUrl = decodeURIComponent(logoutUrl);
  15131. }
  15132. console.info("Log out OK, url: " + logoutUrl, result);
  15133. localStorage.removeItem('sessionId');
  15134. callback(logoutUrl);
  15135. },
  15136. function (error) {
  15137. console.error("Logout error", error);
  15138. }
  15139. );
  15140. }
  15141. };
  15142. module.exports = Moderator;
  15143. },{"../../service/authentication/AuthenticationEvents":156,"../../service/xmpp/XMPPEvents":161,"../settings/Settings":47}],61:[function(require,module,exports){
  15144. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  15145. Toolbar, Util */
  15146. var Moderator = require("./moderator");
  15147. var recordingToken = null;
  15148. var recordingEnabled;
  15149. /**
  15150. * Whether to use a jirecon component for recording, or use the videobridge
  15151. * through COLIBRI.
  15152. */
  15153. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  15154. /**
  15155. * The ID of the jirecon recording session. Jirecon generates it when we
  15156. * initially start recording, and it needs to be used in subsequent requests
  15157. * to jirecon.
  15158. */
  15159. var jireconRid = null;
  15160. /**
  15161. * The callback to update the recording button. Currently used from colibri
  15162. * after receiving a pending status.
  15163. */
  15164. var recordingStateChangeCallback = null;
  15165. function setRecordingToken(token) {
  15166. recordingToken = token;
  15167. }
  15168. function setRecordingJirecon(state, token, callback, connection) {
  15169. if (state == recordingEnabled){
  15170. return;
  15171. }
  15172. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  15173. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  15174. action: (state === 'on') ? 'start' : 'stop',
  15175. mucjid: connection.emuc.roomjid});
  15176. if (state === 'off'){
  15177. iq.attrs({rid: jireconRid});
  15178. }
  15179. console.log('Start recording');
  15180. connection.sendIQ(
  15181. iq,
  15182. function (result) {
  15183. // TODO wait for an IQ with the real status, since this is
  15184. // provisional?
  15185. jireconRid = $(result).find('recording').attr('rid');
  15186. console.log('Recording ' + ((state === 'on') ? 'started' : 'stopped') +
  15187. '(jirecon)' + result);
  15188. recordingEnabled = state;
  15189. if (state === 'off'){
  15190. jireconRid = null;
  15191. }
  15192. callback(state);
  15193. },
  15194. function (error) {
  15195. console.log('Failed to start recording, error: ', error);
  15196. callback(recordingEnabled);
  15197. });
  15198. }
  15199. // Sends a COLIBRI message which enables or disables (according to 'state')
  15200. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  15201. // with the new recording state, according to the IQ.
  15202. function setRecordingColibri(state, token, callback, connection) {
  15203. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  15204. elem.c('conference', {
  15205. xmlns: 'http://jitsi.org/protocol/colibri'
  15206. });
  15207. elem.c('recording', {state: state, token: token});
  15208. connection.sendIQ(elem,
  15209. function (result) {
  15210. console.log('Set recording "', state, '". Result:', result);
  15211. var recordingElem = $(result).find('>conference>recording');
  15212. var newState = recordingElem.attr('state');
  15213. recordingEnabled = newState;
  15214. callback(newState);
  15215. if (newState === 'pending' && recordingStateChangeCallback == null) {
  15216. recordingStateChangeCallback = callback;
  15217. connection.addHandler(function(iq){
  15218. var state = $(iq).find('recording').attr('state');
  15219. if (state)
  15220. recordingStateChangeCallback(state);
  15221. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  15222. }
  15223. },
  15224. function (error) {
  15225. console.warn(error);
  15226. callback(recordingEnabled);
  15227. }
  15228. );
  15229. }
  15230. function setRecording(state, token, callback, connection) {
  15231. if (useJirecon){
  15232. setRecordingJirecon(state, token, callback, connection);
  15233. } else {
  15234. setRecordingColibri(state, token, callback, connection);
  15235. }
  15236. }
  15237. var Recording = {
  15238. toggleRecording: function (tokenEmptyCallback, recordingStateChangeCallback, connection) {
  15239. if (!Moderator.isModerator()) {
  15240. console.log(
  15241. 'non-focus, or conference not yet organized:' +
  15242. ' not enabling recording');
  15243. return;
  15244. }
  15245. var self = this;
  15246. // Jirecon does not (currently) support a token.
  15247. if (!recordingToken && !useJirecon) {
  15248. tokenEmptyCallback(function (value) {
  15249. setRecordingToken(value);
  15250. self.toggleRecording(tokenEmptyCallback, recordingStateChangeCallback, connection);
  15251. });
  15252. return;
  15253. }
  15254. var oldState = recordingEnabled;
  15255. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  15256. setRecording(newState,
  15257. recordingToken,
  15258. function (state) {
  15259. console.log("New recording state: ", state);
  15260. if (state === oldState) {
  15261. // FIXME: new focus:
  15262. // this will not work when moderator changes
  15263. // during active session. Then it will assume that
  15264. // recording status has changed to true, but it might have
  15265. // been already true(and we only received actual status from
  15266. // the focus).
  15267. //
  15268. // SO we start with status null, so that it is initialized
  15269. // here and will fail only after second click, so if invalid
  15270. // token was used we have to press the button twice before
  15271. // current status will be fetched and token will be reset.
  15272. //
  15273. // Reliable way would be to return authentication error.
  15274. // Or status update when moderator connects.
  15275. // Or we have to stop recording session when current
  15276. // moderator leaves the room.
  15277. // Failed to change, reset the token because it might
  15278. // have been wrong
  15279. setRecordingToken(null);
  15280. }
  15281. recordingStateChangeCallback(state);
  15282. },
  15283. connection
  15284. );
  15285. }
  15286. };
  15287. module.exports = Recording;
  15288. },{"./moderator":60}],62:[function(require,module,exports){
  15289. /* jshint -W117 */
  15290. /* a simple MUC connection plugin
  15291. * can only handle a single MUC room
  15292. */
  15293. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15294. var Moderator = require("./moderator");
  15295. module.exports = function(XMPP, eventEmitter) {
  15296. Strophe.addConnectionPlugin('emuc', {
  15297. connection: null,
  15298. roomjid: null,
  15299. myroomjid: null,
  15300. members: {},
  15301. list_members: [], // so we can elect a new focus
  15302. presMap: {},
  15303. preziMap: {},
  15304. joined: false,
  15305. isOwner: false,
  15306. role: null,
  15307. focusMucJid: null,
  15308. bridgeIsDown: false,
  15309. init: function (conn) {
  15310. this.connection = conn;
  15311. },
  15312. initPresenceMap: function (myroomjid) {
  15313. this.presMap['to'] = myroomjid;
  15314. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  15315. if (APP.RTC.localAudio && APP.RTC.localAudio.isMuted()) {
  15316. this.addAudioInfoToPresence(true);
  15317. }
  15318. if (APP.RTC.localVideo && APP.RTC.localVideo.isMuted()) {
  15319. this.addVideoInfoToPresence(true);
  15320. }
  15321. },
  15322. doJoin: function (jid, password) {
  15323. this.myroomjid = jid;
  15324. console.info("Joined MUC as " + this.myroomjid);
  15325. this.initPresenceMap(this.myroomjid);
  15326. if (!this.roomjid) {
  15327. this.roomjid = Strophe.getBareJidFromJid(jid);
  15328. // add handlers (just once)
  15329. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  15330. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  15331. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  15332. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  15333. }
  15334. if (password !== undefined) {
  15335. this.presMap['password'] = password;
  15336. }
  15337. this.sendPresence();
  15338. },
  15339. doLeave: function () {
  15340. console.log("do leave", this.myroomjid);
  15341. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  15342. this.presMap.length = 0;
  15343. this.connection.send(pres);
  15344. },
  15345. createNonAnonymousRoom: function () {
  15346. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  15347. var getForm = $iq({type: 'get', to: this.roomjid})
  15348. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  15349. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15350. var self = this;
  15351. this.connection.sendIQ(getForm, function (form) {
  15352. if (!$(form).find(
  15353. '>query>x[xmlns="jabber:x:data"]' +
  15354. '>field[var="muc#roomconfig_whois"]').length) {
  15355. console.error('non-anonymous rooms not supported');
  15356. return;
  15357. }
  15358. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  15359. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15360. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15361. formSubmit.c('field', {'var': 'FORM_TYPE'})
  15362. .c('value')
  15363. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15364. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  15365. .c('value').t('anyone').up().up();
  15366. self.connection.sendIQ(formSubmit);
  15367. }, function (error) {
  15368. console.error("Error getting room configuration form");
  15369. });
  15370. },
  15371. onPresence: function (pres) {
  15372. var from = pres.getAttribute('from');
  15373. // What is this for? A workaround for something?
  15374. if (pres.getAttribute('type')) {
  15375. return true;
  15376. }
  15377. // Parse etherpad tag.
  15378. var etherpad = $(pres).find('>etherpad');
  15379. if (etherpad.length) {
  15380. if (config.etherpad_base) {
  15381. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  15382. }
  15383. }
  15384. var url;
  15385. // Parse prezi tag.
  15386. var presentation = $(pres).find('>prezi');
  15387. if (presentation.length) {
  15388. url = presentation.attr('url');
  15389. var current = presentation.find('>current').text();
  15390. console.log('presentation info received from', from, url);
  15391. if (this.preziMap[from] == null) {
  15392. this.preziMap[from] = url;
  15393. $(document).trigger('presentationadded.muc', [from, url, current]);
  15394. }
  15395. else {
  15396. $(document).trigger('gotoslide.muc', [from, url, current]);
  15397. }
  15398. }
  15399. else if (this.preziMap[from] != null) {
  15400. url = this.preziMap[from];
  15401. delete this.preziMap[from];
  15402. $(document).trigger('presentationremoved.muc', [from, url]);
  15403. }
  15404. // Parse audio info tag.
  15405. var audioMuted = $(pres).find('>audiomuted');
  15406. if (audioMuted.length) {
  15407. eventEmitter.emit(XMPPEvents.PARTICIPANT_AUDIO_MUTED,
  15408. from, (audioMuted.text() === "true"));
  15409. }
  15410. // Parse video info tag.
  15411. var videoMuted = $(pres).find('>videomuted');
  15412. if (videoMuted.length) {
  15413. eventEmitter.emit(XMPPEvents.PARTICIPANT_VIDEO_MUTED,
  15414. from, (videoMuted.text() === "true"));
  15415. }
  15416. var startMuted = $(pres).find('>startmuted');
  15417. if (startMuted.length && Moderator.isPeerModerator(from)) {
  15418. eventEmitter.emit(XMPPEvents.START_MUTED_SETTING_CHANGED,
  15419. startMuted.attr("audio") === "true",
  15420. startMuted.attr("video") === "true");
  15421. }
  15422. var devices = $(pres).find('>devices');
  15423. if(devices.length)
  15424. {
  15425. var audio = devices.find('>audio');
  15426. var video = devices.find('>video');
  15427. var devicesValues = {audio: false, video: false};
  15428. if(audio.length && audio.text() === "true")
  15429. {
  15430. devicesValues.audio = true;
  15431. }
  15432. if(video.length && video.text() === "true")
  15433. {
  15434. devicesValues.video = true;
  15435. }
  15436. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  15437. Strophe.getResourceFromJid(from), devicesValues);
  15438. }
  15439. var videoType = $(pres).find('>videoType');
  15440. if (videoType.length)
  15441. {
  15442. if (videoType.text().length)
  15443. {
  15444. eventEmitter.emit(XMPPEvents.PARTICIPANT_VIDEO_TYPE_CHANGED,
  15445. Strophe.getResourceFromJid(from), videoType.text());
  15446. }
  15447. }
  15448. var stats = $(pres).find('>stats');
  15449. if (stats.length) {
  15450. var statsObj = {};
  15451. Strophe.forEachChild(stats[0], "stat", function (el) {
  15452. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  15453. });
  15454. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  15455. }
  15456. // Parse status.
  15457. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  15458. this.isOwner = true;
  15459. this.createNonAnonymousRoom();
  15460. }
  15461. // Parse roles.
  15462. var member = {};
  15463. member.show = $(pres).find('>show').text();
  15464. member.status = $(pres).find('>status').text();
  15465. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  15466. member.affiliation = tmp.attr('affiliation');
  15467. member.role = tmp.attr('role');
  15468. // Focus recognition
  15469. member.jid = tmp.attr('jid');
  15470. member.isFocus = false;
  15471. if (member.jid
  15472. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  15473. member.isFocus = true;
  15474. }
  15475. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  15476. member.displayName = (nicktag.length > 0 ? nicktag.text() : null);
  15477. if (from == this.myroomjid) {
  15478. if (member.affiliation == 'owner') this.isOwner = true;
  15479. if (this.role !== member.role) {
  15480. this.role = member.role;
  15481. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  15482. from, member, pres, Moderator.isModerator());
  15483. }
  15484. if (!this.joined) {
  15485. this.joined = true;
  15486. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  15487. this.list_members.push(from);
  15488. }
  15489. } else if (this.members[from] === undefined) {
  15490. // new participant
  15491. this.members[from] = member;
  15492. this.list_members.push(from);
  15493. console.log('entered', from, member);
  15494. if (member.isFocus) {
  15495. this.focusMucJid = from;
  15496. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  15497. }
  15498. else {
  15499. var id = $(pres).find('>userId').text();
  15500. var email = $(pres).find('>email');
  15501. if (email.length > 0) {
  15502. id = email.text();
  15503. }
  15504. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  15505. }
  15506. } else {
  15507. // Presence update for existing participant
  15508. // Watch role change:
  15509. if (this.members[from].role != member.role) {
  15510. this.members[from].role = member.role;
  15511. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  15512. member.role, member.displayName);
  15513. }
  15514. }
  15515. // Always trigger presence to update bindings
  15516. this.parsePresence(from, member, pres);
  15517. // Trigger status message update
  15518. if (member.status) {
  15519. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  15520. }
  15521. return true;
  15522. },
  15523. onPresenceUnavailable: function (pres) {
  15524. var from = pres.getAttribute('from');
  15525. // room destroyed ?
  15526. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15527. '>destroy').length) {
  15528. var reason;
  15529. var reasonSelect = $(pres).find(
  15530. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15531. '>destroy>reason');
  15532. if (reasonSelect.length) {
  15533. reason = reasonSelect.text();
  15534. }
  15535. XMPP.disposeConference(false);
  15536. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  15537. return true;
  15538. }
  15539. // Status code 110 indicates that this notification is "self-presence".
  15540. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  15541. delete this.members[from];
  15542. this.list_members.splice(this.list_members.indexOf(from), 1);
  15543. this.onParticipantLeft(from);
  15544. }
  15545. // If the status code is 110 this means we're leaving and we would like
  15546. // to remove everyone else from our view, so we trigger the event.
  15547. else if (this.list_members.length > 1) {
  15548. for (var i = 0; i < this.list_members.length; i++) {
  15549. var member = this.list_members[i];
  15550. delete this.members[i];
  15551. this.list_members.splice(i, 1);
  15552. this.onParticipantLeft(member);
  15553. }
  15554. }
  15555. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  15556. $(document).trigger('kicked.muc', [from]);
  15557. if (this.myroomjid === from) {
  15558. XMPP.disposeConference(false);
  15559. eventEmitter.emit(XMPPEvents.KICKED);
  15560. }
  15561. }
  15562. return true;
  15563. },
  15564. onPresenceError: function (pres) {
  15565. var from = pres.getAttribute('from');
  15566. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15567. console.log('on password required', from);
  15568. var self = this;
  15569. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  15570. self.doJoin(from, value);
  15571. });
  15572. } else if ($(pres).find(
  15573. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15574. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  15575. if (toDomain === config.hosts.anonymousdomain) {
  15576. // enter the room by replying with 'not-authorized'. This would
  15577. // result in reconnection from authorized domain.
  15578. // We're either missing Jicofo/Prosody config for anonymous
  15579. // domains or something is wrong.
  15580. // XMPP.promptLogin();
  15581. eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  15582. } else {
  15583. console.warn('onPresError ', pres);
  15584. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15585. }
  15586. } else {
  15587. console.warn('onPresError ', pres);
  15588. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15589. }
  15590. return true;
  15591. },
  15592. sendMessage: function (body, nickname) {
  15593. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15594. msg.c('body', body).up();
  15595. if (nickname) {
  15596. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  15597. }
  15598. this.connection.send(msg);
  15599. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  15600. },
  15601. setSubject: function (subject) {
  15602. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15603. msg.c('subject', subject);
  15604. this.connection.send(msg);
  15605. console.log("topic changed to " + subject);
  15606. },
  15607. onMessage: function (msg) {
  15608. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  15609. var from = msg.getAttribute('from');
  15610. var nick =
  15611. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  15612. .text() ||
  15613. Strophe.getResourceFromJid(from);
  15614. var txt = $(msg).find('>body').text();
  15615. var type = msg.getAttribute("type");
  15616. if (type == "error") {
  15617. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  15618. $(msg).find('>text').text(), txt);
  15619. return true;
  15620. }
  15621. var subject = $(msg).find('>subject');
  15622. if (subject.length) {
  15623. var subjectText = subject.text();
  15624. if (subjectText || subjectText == "") {
  15625. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  15626. console.log("Subject is changed to " + subjectText);
  15627. }
  15628. }
  15629. // xep-0203 delay
  15630. var stamp = $(msg).find('>delay').attr('stamp');
  15631. if (!stamp) {
  15632. // or xep-0091 delay, UTC timestamp
  15633. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  15634. if (stamp) {
  15635. // the format is CCYYMMDDThh:mm:ss
  15636. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  15637. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  15638. }
  15639. }
  15640. if (txt) {
  15641. console.log('chat', nick, txt);
  15642. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  15643. from, nick, txt, this.myroomjid, stamp);
  15644. }
  15645. return true;
  15646. },
  15647. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15648. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  15649. var ob = this;
  15650. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  15651. function (res) {
  15652. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  15653. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15654. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15655. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15656. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  15657. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  15658. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  15659. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  15660. ob.connection.sendIQ(formsubmit,
  15661. onSuccess,
  15662. onError);
  15663. } else {
  15664. onNotSupported();
  15665. }
  15666. }, onError);
  15667. },
  15668. kick: function (jid) {
  15669. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  15670. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  15671. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  15672. .c('reason').t('You have been kicked.').up().up().up();
  15673. this.connection.sendIQ(
  15674. kickIQ,
  15675. function (result) {
  15676. console.log('Kick participant with jid: ', jid, result);
  15677. },
  15678. function (error) {
  15679. console.log('Kick participant error: ', error);
  15680. });
  15681. },
  15682. sendPresence: function () {
  15683. if (!this.presMap['to']) {
  15684. // Too early to send presence - not initialized
  15685. return;
  15686. }
  15687. var pres = $pres({to: this.presMap['to'] });
  15688. pres.c('x', {xmlns: this.presMap['xns']});
  15689. if (this.presMap['password']) {
  15690. pres.c('password').t(this.presMap['password']).up();
  15691. }
  15692. pres.up();
  15693. // Send XEP-0115 'c' stanza that contains our capabilities info
  15694. if (this.connection.caps) {
  15695. this.connection.caps.node = config.clientNode;
  15696. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  15697. }
  15698. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  15699. .t(navigator.userAgent).up();
  15700. if (this.presMap['bridgeIsDown']) {
  15701. pres.c('bridgeIsDown').up();
  15702. }
  15703. if (this.presMap['email']) {
  15704. pres.c('email').t(this.presMap['email']).up();
  15705. }
  15706. if (this.presMap['userId']) {
  15707. pres.c('userId').t(this.presMap['userId']).up();
  15708. }
  15709. if (this.presMap['displayName']) {
  15710. // XEP-0172
  15711. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  15712. .t(this.presMap['displayName']).up();
  15713. }
  15714. if(this.presMap["devices"])
  15715. {
  15716. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  15717. .c('video').t(this.presMap['devices'].video).up().up();
  15718. }
  15719. if (this.presMap['audions']) {
  15720. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  15721. .t(this.presMap['audiomuted']).up();
  15722. }
  15723. if (this.presMap['videons']) {
  15724. pres.c('videomuted', {xmlns: this.presMap['videons']})
  15725. .t(this.presMap['videomuted']).up();
  15726. }
  15727. if (this.presMap['videoTypeNs']) {
  15728. pres.c('videoType', { xmlns: this.presMap['videoTypeNs'] })
  15729. .t(this.presMap['videoType']).up();
  15730. }
  15731. if (this.presMap['statsns']) {
  15732. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  15733. for (var stat in this.presMap["stats"])
  15734. if (this.presMap["stats"][stat] != null)
  15735. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  15736. pres.up();
  15737. }
  15738. if (this.presMap['prezins']) {
  15739. pres.c('prezi',
  15740. {xmlns: this.presMap['prezins'],
  15741. 'url': this.presMap['preziurl']})
  15742. .c('current').t(this.presMap['prezicurrent']).up().up();
  15743. }
  15744. if(this.presMap["startMuted"] !== undefined)
  15745. {
  15746. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  15747. video: this.presMap["startMuted"].video,
  15748. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  15749. delete this.presMap["startMuted"];
  15750. }
  15751. pres.up();
  15752. this.connection.send(pres);
  15753. },
  15754. addDisplayNameToPresence: function (displayName) {
  15755. this.presMap['displayName'] = displayName;
  15756. },
  15757. addDevicesToPresence: function (devices) {
  15758. this.presMap['devices'] = devices;
  15759. },
  15760. /**
  15761. * Adds the info about the type of our video stream.
  15762. * @param videoType 'camera' or 'screen'
  15763. */
  15764. addVideoTypeToPresence: function (videoType) {
  15765. this.presMap['videoTypeNs'] = 'http://jitsi.org/jitmeet/video';
  15766. this.presMap['videoType'] = videoType;
  15767. },
  15768. addPreziToPresence: function (url, currentSlide) {
  15769. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  15770. this.presMap['preziurl'] = url;
  15771. this.presMap['prezicurrent'] = currentSlide;
  15772. },
  15773. removePreziFromPresence: function () {
  15774. delete this.presMap['prezins'];
  15775. delete this.presMap['preziurl'];
  15776. delete this.presMap['prezicurrent'];
  15777. },
  15778. addCurrentSlideToPresence: function (currentSlide) {
  15779. this.presMap['prezicurrent'] = currentSlide;
  15780. },
  15781. getPrezi: function (roomjid) {
  15782. return this.preziMap[roomjid];
  15783. },
  15784. addAudioInfoToPresence: function (isMuted) {
  15785. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  15786. this.presMap['audiomuted'] = isMuted.toString();
  15787. },
  15788. addVideoInfoToPresence: function (isMuted) {
  15789. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  15790. this.presMap['videomuted'] = isMuted.toString();
  15791. },
  15792. addConnectionInfoToPresence: function (stats) {
  15793. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  15794. this.presMap['stats'] = stats;
  15795. },
  15796. findJidFromResource: function (resourceJid) {
  15797. if (resourceJid &&
  15798. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  15799. return this.myroomjid;
  15800. }
  15801. var peerJid = null;
  15802. Object.keys(this.members).some(function (jid) {
  15803. peerJid = jid;
  15804. return Strophe.getResourceFromJid(jid) === resourceJid;
  15805. });
  15806. return peerJid;
  15807. },
  15808. addBridgeIsDownToPresence: function () {
  15809. this.presMap['bridgeIsDown'] = true;
  15810. },
  15811. addEmailToPresence: function (email) {
  15812. this.presMap['email'] = email;
  15813. },
  15814. addUserIdToPresence: function (userId) {
  15815. this.presMap['userId'] = userId;
  15816. },
  15817. addStartMutedToPresence: function (audio, video) {
  15818. this.presMap["startMuted"] = {audio: audio, video: video};
  15819. },
  15820. isModerator: function () {
  15821. return this.role === 'moderator';
  15822. },
  15823. getMemberRole: function (peerJid) {
  15824. if (this.members[peerJid]) {
  15825. return this.members[peerJid].role;
  15826. }
  15827. return null;
  15828. },
  15829. onParticipantLeft: function (jid) {
  15830. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  15831. this.connection.jingle.terminateByJid(jid);
  15832. if (this.getPrezi(jid)) {
  15833. $(document).trigger('presentationremoved.muc',
  15834. [jid, this.getPrezi(jid)]);
  15835. }
  15836. Moderator.onMucMemberLeft(jid);
  15837. },
  15838. parsePresence: function (from, member, pres) {
  15839. if($(pres).find(">bridgeIsDown").length > 0 && !this.bridgeIsDown) {
  15840. this.bridgeIsDown = true;
  15841. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  15842. }
  15843. if(member.isFocus)
  15844. return;
  15845. var displayName = !config.displayJids
  15846. ? member.displayName : Strophe.getResourceFromJid(from);
  15847. if (displayName && displayName.length > 0) {
  15848. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  15849. }
  15850. console.info("Display name: " + displayName, pres);
  15851. var id = $(pres).find('>userID').text();
  15852. var email = $(pres).find('>email');
  15853. if (email.length > 0) {
  15854. id = email.text();
  15855. }
  15856. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  15857. }
  15858. });
  15859. };
  15860. },{"../../service/xmpp/XMPPEvents":161,"./moderator":60}],63:[function(require,module,exports){
  15861. /* jshint -W117 */
  15862. var JingleSession = require("./JingleSessionPC");
  15863. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15864. var RTCBrowserType = require("../RTC/RTCBrowserType");
  15865. module.exports = function(XMPP, eventEmitter) {
  15866. Strophe.addConnectionPlugin('jingle', {
  15867. connection: null,
  15868. sessions: {},
  15869. jid2session: {},
  15870. ice_config: {iceServers: []},
  15871. pc_constraints: {},
  15872. activecall: null,
  15873. media_constraints: {
  15874. mandatory: {
  15875. 'OfferToReceiveAudio': true,
  15876. 'OfferToReceiveVideo': true
  15877. }
  15878. // MozDontOfferDataChannel: true when this is firefox
  15879. },
  15880. init: function (conn) {
  15881. this.connection = conn;
  15882. if (this.connection.disco) {
  15883. // http://xmpp.org/extensions/xep-0167.html#support
  15884. // http://xmpp.org/extensions/xep-0176.html#support
  15885. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  15886. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  15887. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  15888. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  15889. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  15890. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  15891. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  15892. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  15893. || RTCBrowserType.isTemasysPluginUsed()) {
  15894. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  15895. }
  15896. // this is dealt with by SDP O/A so we don't need to announce this
  15897. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  15898. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  15899. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  15900. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  15901. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  15902. }
  15903. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  15904. },
  15905. onJingle: function (iq) {
  15906. var sid = $(iq).find('jingle').attr('sid');
  15907. var action = $(iq).find('jingle').attr('action');
  15908. var fromJid = iq.getAttribute('from');
  15909. // send ack first
  15910. var ack = $iq({type: 'result',
  15911. to: fromJid,
  15912. id: iq.getAttribute('id')
  15913. });
  15914. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  15915. var sess = this.sessions[sid];
  15916. if ('session-initiate' != action) {
  15917. if (sess === null) {
  15918. ack.type = 'error';
  15919. ack.c('error', {type: 'cancel'})
  15920. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15921. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15922. this.connection.send(ack);
  15923. return true;
  15924. }
  15925. // local jid is not checked
  15926. if (fromJid != sess.peerjid) {
  15927. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  15928. ack.type = 'error';
  15929. ack.c('error', {type: 'cancel'})
  15930. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15931. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15932. this.connection.send(ack);
  15933. return true;
  15934. }
  15935. } else if (sess !== undefined) {
  15936. // existing session with same session id
  15937. // this might be out-of-order if the sess.peerjid is the same as from
  15938. ack.type = 'error';
  15939. ack.c('error', {type: 'cancel'})
  15940. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  15941. console.warn('duplicate session id', sid);
  15942. this.connection.send(ack);
  15943. return true;
  15944. }
  15945. // FIXME: check for a defined action
  15946. this.connection.send(ack);
  15947. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  15948. switch (action) {
  15949. case 'session-initiate':
  15950. var startMuted = $(iq).find('jingle>startmuted');
  15951. if (startMuted && startMuted.length > 0) {
  15952. var audioMuted = startMuted.attr("audio");
  15953. var videoMuted = startMuted.attr("video");
  15954. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  15955. audioMuted === "true", videoMuted === "true");
  15956. }
  15957. sess = new JingleSession(
  15958. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  15959. this.connection, XMPP, eventEmitter);
  15960. // configure session
  15961. sess.media_constraints = this.media_constraints;
  15962. sess.pc_constraints = this.pc_constraints;
  15963. sess.ice_config = this.ice_config;
  15964. sess.initialize(fromJid, false);
  15965. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  15966. sess.setOffer($(iq).find('>jingle'));
  15967. this.sessions[sess.sid] = sess;
  15968. this.jid2session[sess.peerjid] = sess;
  15969. // the callback should either
  15970. // .sendAnswer and .accept
  15971. // or .sendTerminate -- not necessarily synchronous
  15972. // TODO: do we check activecall == null?
  15973. this.connection.jingle.activecall = sess;
  15974. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  15975. // TODO: check affiliation and/or role
  15976. console.log('emuc data for', sess.peerjid,
  15977. this.connection.emuc.members[sess.peerjid]);
  15978. sess.sendAnswer();
  15979. sess.accept();
  15980. break;
  15981. case 'session-accept':
  15982. sess.setAnswer($(iq).find('>jingle'));
  15983. sess.accept();
  15984. $(document).trigger('callaccepted.jingle', [sess.sid]);
  15985. break;
  15986. case 'session-terminate':
  15987. // If this is not the focus sending the terminate, we have
  15988. // nothing more to do here.
  15989. if (Object.keys(this.sessions).length < 1
  15990. || !(this.sessions[Object.keys(this.sessions)[0]]
  15991. instanceof JingleSession))
  15992. {
  15993. break;
  15994. }
  15995. console.log('terminating...', sess.sid);
  15996. sess.terminate();
  15997. this.terminate(sess.sid);
  15998. if ($(iq).find('>jingle>reason').length) {
  15999. $(document).trigger('callterminated.jingle', [
  16000. sess.sid,
  16001. sess.peerjid,
  16002. $(iq).find('>jingle>reason>:first')[0].tagName,
  16003. $(iq).find('>jingle>reason>text').text()
  16004. ]);
  16005. } else {
  16006. $(document).trigger('callterminated.jingle',
  16007. [sess.sid, sess.peerjid]);
  16008. }
  16009. break;
  16010. case 'transport-info':
  16011. sess.addIceCandidate($(iq).find('>jingle>content'));
  16012. break;
  16013. case 'session-info':
  16014. var affected;
  16015. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  16016. $(document).trigger('ringing.jingle', [sess.sid]);
  16017. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  16018. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  16019. $(document).trigger('mute.jingle', [sess.sid, affected]);
  16020. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  16021. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  16022. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  16023. }
  16024. break;
  16025. case 'addsource': // FIXME: proprietary, un-jingleish
  16026. case 'source-add': // FIXME: proprietary
  16027. sess.addSource($(iq).find('>jingle>content'), fromJid);
  16028. break;
  16029. case 'removesource': // FIXME: proprietary, un-jingleish
  16030. case 'source-remove': // FIXME: proprietary
  16031. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  16032. break;
  16033. default:
  16034. console.warn('jingle action not implemented', action);
  16035. break;
  16036. }
  16037. return true;
  16038. },
  16039. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  16040. var sess = new JingleSession(myjid || this.connection.jid,
  16041. Math.random().toString(36).substr(2, 12), // random string
  16042. this.connection, XMPP, eventEmitter);
  16043. // configure session
  16044. sess.media_constraints = this.media_constraints;
  16045. sess.pc_constraints = this.pc_constraints;
  16046. sess.ice_config = this.ice_config;
  16047. sess.initialize(peerjid, true);
  16048. this.sessions[sess.sid] = sess;
  16049. this.jid2session[sess.peerjid] = sess;
  16050. sess.sendOffer();
  16051. return sess;
  16052. },
  16053. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  16054. if (sid === null || sid === undefined) {
  16055. for (sid in this.sessions) {
  16056. if (this.sessions[sid].state != 'ended') {
  16057. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  16058. this.sessions[sid].terminate();
  16059. }
  16060. delete this.jid2session[this.sessions[sid].peerjid];
  16061. delete this.sessions[sid];
  16062. }
  16063. } else if (this.sessions.hasOwnProperty(sid)) {
  16064. if (this.sessions[sid].state != 'ended') {
  16065. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  16066. this.sessions[sid].terminate();
  16067. }
  16068. delete this.jid2session[this.sessions[sid].peerjid];
  16069. delete this.sessions[sid];
  16070. }
  16071. },
  16072. // Used to terminate a session when an unavailable presence is received.
  16073. terminateByJid: function (jid) {
  16074. if (this.jid2session.hasOwnProperty(jid)) {
  16075. var sess = this.jid2session[jid];
  16076. if (sess) {
  16077. sess.terminate();
  16078. console.log('peer went away silently', jid);
  16079. delete this.sessions[sess.sid];
  16080. delete this.jid2session[jid];
  16081. $(document).trigger('callterminated.jingle',
  16082. [sess.sid, jid], 'gone');
  16083. }
  16084. }
  16085. },
  16086. terminateRemoteByJid: function (jid, reason) {
  16087. if (this.jid2session.hasOwnProperty(jid)) {
  16088. var sess = this.jid2session[jid];
  16089. if (sess) {
  16090. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  16091. sess.terminate();
  16092. console.log('terminate peer with jid', sess.sid, jid);
  16093. delete this.sessions[sess.sid];
  16094. delete this.jid2session[jid];
  16095. $(document).trigger('callterminated.jingle',
  16096. [sess.sid, jid, 'kicked']);
  16097. }
  16098. }
  16099. },
  16100. getStunAndTurnCredentials: function () {
  16101. // get stun and turn configuration from server via xep-0215
  16102. // uses time-limited credentials as described in
  16103. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  16104. //
  16105. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  16106. // for a prosody module which implements this
  16107. //
  16108. // currently, this doesn't work with updateIce and therefore credentials with a long
  16109. // validity have to be fetched before creating the peerconnection
  16110. // TODO: implement refresh via updateIce as described in
  16111. // https://code.google.com/p/webrtc/issues/detail?id=1650
  16112. var self = this;
  16113. this.connection.sendIQ(
  16114. $iq({type: 'get', to: this.connection.domain})
  16115. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  16116. function (res) {
  16117. var iceservers = [];
  16118. $(res).find('>services>service').each(function (idx, el) {
  16119. el = $(el);
  16120. var dict = {};
  16121. var type = el.attr('type');
  16122. switch (type) {
  16123. case 'stun':
  16124. dict.url = 'stun:' + el.attr('host');
  16125. if (el.attr('port')) {
  16126. dict.url += ':' + el.attr('port');
  16127. }
  16128. iceservers.push(dict);
  16129. break;
  16130. case 'turn':
  16131. case 'turns':
  16132. dict.url = type + ':';
  16133. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  16134. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  16135. dict.url += el.attr('username') + '@';
  16136. } else {
  16137. dict.username = el.attr('username'); // only works in M28
  16138. }
  16139. }
  16140. dict.url += el.attr('host');
  16141. if (el.attr('port') && el.attr('port') != '3478') {
  16142. dict.url += ':' + el.attr('port');
  16143. }
  16144. if (el.attr('transport') && el.attr('transport') != 'udp') {
  16145. dict.url += '?transport=' + el.attr('transport');
  16146. }
  16147. if (el.attr('password')) {
  16148. dict.credential = el.attr('password');
  16149. }
  16150. iceservers.push(dict);
  16151. break;
  16152. }
  16153. });
  16154. self.ice_config.iceServers = iceservers;
  16155. },
  16156. function (err) {
  16157. console.warn('getting turn credentials failed', err);
  16158. console.warn('is mod_turncredentials or similar installed?');
  16159. }
  16160. );
  16161. // implement push?
  16162. },
  16163. /**
  16164. * Returns the data saved in 'updateLog' in a format to be logged.
  16165. */
  16166. getLog: function () {
  16167. var data = {};
  16168. var self = this;
  16169. Object.keys(this.sessions).forEach(function (sid) {
  16170. var session = self.sessions[sid];
  16171. if (session.peerconnection && session.peerconnection.updateLog) {
  16172. // FIXME: should probably be a .dump call
  16173. data["jingle_" + session.sid] = {
  16174. updateLog: session.peerconnection.updateLog,
  16175. stats: session.peerconnection.stats,
  16176. url: window.location.href
  16177. };
  16178. }
  16179. });
  16180. return data;
  16181. }
  16182. });
  16183. };
  16184. },{"../../service/xmpp/XMPPEvents":161,"../RTC/RTCBrowserType":8,"./JingleSessionPC":54}],64:[function(require,module,exports){
  16185. /* global Strophe */
  16186. module.exports = function () {
  16187. Strophe.addConnectionPlugin('logger', {
  16188. // logs raw stanzas and makes them available for download as JSON
  16189. connection: null,
  16190. log: [],
  16191. init: function (conn) {
  16192. this.connection = conn;
  16193. this.connection.rawInput = this.log_incoming.bind(this);
  16194. this.connection.rawOutput = this.log_outgoing.bind(this);
  16195. },
  16196. log_incoming: function (stanza) {
  16197. this.log.push([new Date().getTime(), 'incoming', stanza]);
  16198. },
  16199. log_outgoing: function (stanza) {
  16200. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  16201. }
  16202. });
  16203. };
  16204. },{}],65:[function(require,module,exports){
  16205. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  16206. setAudioMuted, Strophe */
  16207. /**
  16208. * Moderate connection plugin.
  16209. */
  16210. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16211. module.exports = function (XMPP, eventEmitter) {
  16212. Strophe.addConnectionPlugin('moderate', {
  16213. connection: null,
  16214. init: function (conn) {
  16215. this.connection = conn;
  16216. this.connection.addHandler(this.onMute.bind(this),
  16217. 'http://jitsi.org/jitmeet/audio',
  16218. 'iq',
  16219. 'set',
  16220. null,
  16221. null);
  16222. },
  16223. setMute: function (jid, mute) {
  16224. console.info("set mute", mute);
  16225. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  16226. .c('mute', {
  16227. xmlns: 'http://jitsi.org/jitmeet/audio',
  16228. jid: jid
  16229. })
  16230. .t(mute.toString())
  16231. .up();
  16232. this.connection.sendIQ(
  16233. iqToFocus,
  16234. function (result) {
  16235. console.log('set mute', result);
  16236. },
  16237. function (error) {
  16238. console.log('set mute error', error);
  16239. });
  16240. },
  16241. onMute: function (iq) {
  16242. var from = iq.getAttribute('from');
  16243. if (from !== this.connection.emuc.focusMucJid) {
  16244. console.warn("Ignored mute from non focus peer");
  16245. return false;
  16246. }
  16247. var mute = $(iq).find('mute');
  16248. if (mute.length) {
  16249. var doMuteAudio = mute.text() === "true";
  16250. eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  16251. XMPP.forceMuted = doMuteAudio;
  16252. }
  16253. return true;
  16254. },
  16255. eject: function (jid) {
  16256. // We're not the focus, so can't terminate
  16257. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  16258. this.connection.emuc.kick(jid);
  16259. }
  16260. });
  16261. }
  16262. },{"../../service/xmpp/XMPPEvents":161}],66:[function(require,module,exports){
  16263. /* jshint -W117 */
  16264. module.exports = function() {
  16265. Strophe.addConnectionPlugin('rayo',
  16266. {
  16267. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  16268. connection: null,
  16269. init: function (conn) {
  16270. this.connection = conn;
  16271. if (this.connection.disco) {
  16272. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  16273. }
  16274. this.connection.addHandler(
  16275. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  16276. },
  16277. onRayo: function (iq) {
  16278. console.info("Rayo IQ", iq);
  16279. },
  16280. dial: function (to, from, roomName, roomPass) {
  16281. var self = this;
  16282. var req = $iq(
  16283. {
  16284. type: 'set',
  16285. to: this.connection.emuc.focusMucJid
  16286. }
  16287. );
  16288. req.c('dial',
  16289. {
  16290. xmlns: this.RAYO_XMLNS,
  16291. to: to,
  16292. from: from
  16293. });
  16294. req.c('header',
  16295. {
  16296. name: 'JvbRoomName',
  16297. value: roomName
  16298. }).up();
  16299. if (roomPass !== null && roomPass.length) {
  16300. req.c('header',
  16301. {
  16302. name: 'JvbRoomPassword',
  16303. value: roomPass
  16304. }).up();
  16305. }
  16306. this.connection.sendIQ(
  16307. req,
  16308. function (result) {
  16309. console.info('Dial result ', result);
  16310. var resource = $(result).find('ref').attr('uri');
  16311. this.call_resource = resource.substr('xmpp:'.length);
  16312. console.info(
  16313. "Received call resource: " + this.call_resource);
  16314. },
  16315. function (error) {
  16316. console.info('Dial error ', error);
  16317. }
  16318. );
  16319. },
  16320. hang_up: function () {
  16321. if (!this.call_resource) {
  16322. console.warn("No call in progress");
  16323. return;
  16324. }
  16325. var self = this;
  16326. var req = $iq(
  16327. {
  16328. type: 'set',
  16329. to: this.call_resource
  16330. }
  16331. );
  16332. req.c('hangup',
  16333. {
  16334. xmlns: this.RAYO_XMLNS
  16335. });
  16336. this.connection.sendIQ(
  16337. req,
  16338. function (result) {
  16339. console.info('Hangup result ', result);
  16340. self.call_resource = null;
  16341. },
  16342. function (error) {
  16343. console.info('Hangup error ', error);
  16344. self.call_resource = null;
  16345. }
  16346. );
  16347. }
  16348. }
  16349. );
  16350. };
  16351. },{}],67:[function(require,module,exports){
  16352. /**
  16353. * Strophe logger implementation. Logs from level WARN and above.
  16354. */
  16355. module.exports = function () {
  16356. Strophe.log = function (level, msg) {
  16357. switch (level) {
  16358. case Strophe.LogLevel.WARN:
  16359. console.warn("Strophe: " + msg);
  16360. break;
  16361. case Strophe.LogLevel.ERROR:
  16362. case Strophe.LogLevel.FATAL:
  16363. console.error("Strophe: " + msg);
  16364. break;
  16365. }
  16366. };
  16367. Strophe.getStatusString = function (status) {
  16368. switch (status) {
  16369. case Strophe.Status.ERROR:
  16370. return "ERROR";
  16371. case Strophe.Status.CONNECTING:
  16372. return "CONNECTING";
  16373. case Strophe.Status.CONNFAIL:
  16374. return "CONNFAIL";
  16375. case Strophe.Status.AUTHENTICATING:
  16376. return "AUTHENTICATING";
  16377. case Strophe.Status.AUTHFAIL:
  16378. return "AUTHFAIL";
  16379. case Strophe.Status.CONNECTED:
  16380. return "CONNECTED";
  16381. case Strophe.Status.DISCONNECTED:
  16382. return "DISCONNECTED";
  16383. case Strophe.Status.DISCONNECTING:
  16384. return "DISCONNECTING";
  16385. case Strophe.Status.ATTACHED:
  16386. return "ATTACHED";
  16387. default:
  16388. return "unknown";
  16389. }
  16390. };
  16391. };
  16392. },{}],68:[function(require,module,exports){
  16393. /* global $, APP, config, Strophe*/
  16394. var Moderator = require("./moderator");
  16395. var EventEmitter = require("events");
  16396. var Recording = require("./recording");
  16397. var SDP = require("./SDP");
  16398. var Settings = require("../settings/Settings");
  16399. var Pako = require("pako");
  16400. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  16401. var RTCEvents = require("../../service/RTC/RTCEvents");
  16402. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16403. var retry = require('retry');
  16404. var eventEmitter = new EventEmitter();
  16405. var connection = null;
  16406. var authenticatedUser = false;
  16407. function connect(jid, password) {
  16408. var faultTolerantConnect = retry.operation({
  16409. retries: 3
  16410. });
  16411. // fault tolerant connect
  16412. faultTolerantConnect.attempt(function () {
  16413. connection = XMPP.createConnection();
  16414. Moderator.setConnection(connection);
  16415. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  16416. if (config.useIPv6) {
  16417. // https://code.google.com/p/webrtc/issues/detail?id=2828
  16418. if (!connection.jingle.pc_constraints.optional)
  16419. connection.jingle.pc_constraints.optional = [];
  16420. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  16421. }
  16422. // Include user info in MUC presence
  16423. var settings = Settings.getSettings();
  16424. if (settings.email) {
  16425. connection.emuc.addEmailToPresence(settings.email);
  16426. }
  16427. if (settings.uid) {
  16428. connection.emuc.addUserIdToPresence(settings.uid);
  16429. }
  16430. if (settings.displayName) {
  16431. connection.emuc.addDisplayNameToPresence(settings.displayName);
  16432. }
  16433. // connection.connect() starts the connection process.
  16434. //
  16435. // As the connection process proceeds, the user supplied callback will
  16436. // be triggered multiple times with status updates. The callback should
  16437. // take two arguments - the status code and the error condition.
  16438. //
  16439. // The status code will be one of the values in the Strophe.Status
  16440. // constants. The error condition will be one of the conditions defined
  16441. // in RFC 3920 or the condition ‘strophe-parsererror’.
  16442. //
  16443. // The Parameters wait, hold and route are optional and only relevant
  16444. // for BOSH connections. Please see XEP 124 for a more detailed
  16445. // explanation of the optional parameters.
  16446. //
  16447. // Connection status constants for use by the connection handler
  16448. // callback.
  16449. //
  16450. // Status.ERROR - An error has occurred (websockets specific)
  16451. // Status.CONNECTING - The connection is currently being made
  16452. // Status.CONNFAIL - The connection attempt failed
  16453. // Status.AUTHENTICATING - The connection is authenticating
  16454. // Status.AUTHFAIL - The authentication attempt failed
  16455. // Status.CONNECTED - The connection has succeeded
  16456. // Status.DISCONNECTED - The connection has been terminated
  16457. // Status.DISCONNECTING - The connection is currently being terminated
  16458. // Status.ATTACHED - The connection has been attached
  16459. var anonymousConnectionFailed = false;
  16460. var connectionFailed = false;
  16461. var lastErrorMsg;
  16462. connection.connect(jid, password, function (status, msg) {
  16463. console.log('Strophe status changed to',
  16464. Strophe.getStatusString(status), msg);
  16465. if (status === Strophe.Status.CONNECTED) {
  16466. if (config.useStunTurn) {
  16467. connection.jingle.getStunAndTurnCredentials();
  16468. }
  16469. console.info("My Jabber ID: " + connection.jid);
  16470. if (password)
  16471. authenticatedUser = true;
  16472. maybeDoJoin();
  16473. } else if (status === Strophe.Status.CONNFAIL) {
  16474. if (msg === 'x-strophe-bad-non-anon-jid') {
  16475. anonymousConnectionFailed = true;
  16476. } else {
  16477. connectionFailed = true;
  16478. }
  16479. lastErrorMsg = msg;
  16480. } else if (status === Strophe.Status.DISCONNECTED) {
  16481. if (anonymousConnectionFailed) {
  16482. // prompt user for username and password
  16483. XMPP.promptLogin();
  16484. } else {
  16485. // Strophe already has built-in HTTP/BOSH error handling and
  16486. // request retry logic. Requests are resent automatically
  16487. // until their error count reaches 5. Strophe.js disconnects
  16488. // if the error count is > 5. We are not replicating this
  16489. // here.
  16490. //
  16491. // The "problem" is that failed HTTP/BOSH requests don't
  16492. // trigger a callback with a status update, so when a
  16493. // callback with status Strophe.Status.DISCONNECTED arrives,
  16494. // we can't be sure if it's a graceful disconnect or if it's
  16495. // triggered by some HTTP/BOSH error.
  16496. //
  16497. // But that's a minor issue in Jitsi Meet as we never
  16498. // disconnect anyway, not even when the user closes the
  16499. // browser window (which is kind of wrong, but the point is
  16500. // that we should never ever get disconnected).
  16501. //
  16502. // On the other hand, failed connections due to XMPP layer
  16503. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  16504. //
  16505. // Here we implement retry logic for failed connections due
  16506. // to XMPP layer errors and we display an error to the user
  16507. // if we get disconnected from the XMPP server permanently.
  16508. // If the connection failed, retry.
  16509. if (connectionFailed &&
  16510. faultTolerantConnect.retry("connection-failed")) {
  16511. return;
  16512. }
  16513. // If we failed to connect to the XMPP server, fire an event
  16514. // to let all the interested module now about it.
  16515. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  16516. msg ? msg : lastErrorMsg);
  16517. }
  16518. } else if (status === Strophe.Status.AUTHFAIL) {
  16519. // wrong password or username, prompt user
  16520. XMPP.promptLogin();
  16521. }
  16522. });
  16523. });
  16524. }
  16525. function maybeDoJoin() {
  16526. if (connection && connection.connected &&
  16527. Strophe.getResourceFromJid(connection.jid) &&
  16528. (APP.RTC.localAudio || APP.RTC.localVideo)) {
  16529. // .connected is true while connecting?
  16530. doJoin();
  16531. }
  16532. }
  16533. function doJoin() {
  16534. eventEmitter.emit(XMPPEvents.READY_TO_JOIN);
  16535. }
  16536. function initStrophePlugins()
  16537. {
  16538. require("./strophe.emuc")(XMPP, eventEmitter);
  16539. require("./strophe.jingle")(XMPP, eventEmitter);
  16540. require("./strophe.moderate")(XMPP, eventEmitter);
  16541. require("./strophe.util")();
  16542. require("./strophe.rayo")();
  16543. require("./strophe.logger")();
  16544. }
  16545. /**
  16546. * If given <tt>localStream</tt> is video one this method will advertise it's
  16547. * video type in MUC presence.
  16548. * @param localStream new or modified <tt>LocalStream</tt>.
  16549. */
  16550. function broadcastLocalVideoType(localStream) {
  16551. if (localStream.videoType)
  16552. XMPP.addToPresence('videoType', localStream.videoType);
  16553. }
  16554. function registerListeners() {
  16555. APP.RTC.addStreamListener(
  16556. function (localStream) {
  16557. maybeDoJoin();
  16558. broadcastLocalVideoType(localStream);
  16559. },
  16560. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED
  16561. );
  16562. APP.RTC.addStreamListener(
  16563. broadcastLocalVideoType,
  16564. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  16565. );
  16566. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  16567. XMPP.addToPresence("devices", devices);
  16568. });
  16569. }
  16570. var unload = (function () {
  16571. var unloaded = false;
  16572. return function () {
  16573. if (unloaded) { return; }
  16574. unloaded = true;
  16575. if (connection && connection.connected) {
  16576. // ensure signout
  16577. $.ajax({
  16578. type: 'POST',
  16579. url: config.bosh,
  16580. async: false,
  16581. cache: false,
  16582. contentType: 'application/xml',
  16583. data: "<body rid='" +
  16584. (connection.rid || connection._proto.rid) +
  16585. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  16586. (connection.sid || connection._proto.sid) +
  16587. "' type='terminate'>" +
  16588. "<presence xmlns='jabber:client' type='unavailable'/>" +
  16589. "</body>",
  16590. success: function (data) {
  16591. console.log('signed out');
  16592. console.log(data);
  16593. },
  16594. error: function (XMLHttpRequest, textStatus, errorThrown) {
  16595. console.log('signout error',
  16596. textStatus + ' (' + errorThrown + ')');
  16597. }
  16598. });
  16599. }
  16600. XMPP.disposeConference(true);
  16601. };
  16602. })();
  16603. function setupEvents() {
  16604. // In recent versions of FF the 'beforeunload' event is not fired when the
  16605. // window or the tab is closed. It is only fired when we leave the page
  16606. // (change URL). If this participant doesn't unload properly, then it
  16607. // becomes a ghost for the rest of the participants that stay in the
  16608. // conference. Thankfully handling the 'unload' event in addition to the
  16609. // 'beforeunload' event seems to guarantee the execution of the 'unload'
  16610. // method at least once.
  16611. //
  16612. // The 'unload' method can safely be run multiple times, it will actually do
  16613. // something only the first time that it's run, so we're don't have to worry
  16614. // about browsers that fire both events.
  16615. $(window).bind('beforeunload', unload);
  16616. $(window).bind('unload', unload);
  16617. }
  16618. var XMPP = {
  16619. getConnection: function(){ return connection; },
  16620. sessionTerminated: false,
  16621. /**
  16622. * XMPP connection status
  16623. */
  16624. Status: Strophe.Status,
  16625. /**
  16626. * Remembers if we were muted by the focus.
  16627. * @type {boolean}
  16628. */
  16629. forceMuted: false,
  16630. start: function () {
  16631. setupEvents();
  16632. initStrophePlugins();
  16633. registerListeners();
  16634. Moderator.init(this, eventEmitter);
  16635. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  16636. // Force authenticated domain if room is appended with '?login=true'
  16637. if (config.hosts.anonymousdomain &&
  16638. window.location.search.indexOf("login=true") !== -1) {
  16639. configDomain = config.hosts.domain;
  16640. }
  16641. var jid = configDomain || window.location.hostname;
  16642. connect(jid, null);
  16643. },
  16644. createConnection: function () {
  16645. var bosh = config.bosh || '/http-bind';
  16646. return new Strophe.Connection(bosh);
  16647. },
  16648. getStatusString: function (status) {
  16649. return Strophe.getStatusString(status);
  16650. },
  16651. promptLogin: function () {
  16652. eventEmitter.emit(XMPPEvents.PROMPT_FOR_LOGIN);
  16653. },
  16654. joinRoom: function(roomName, useNicks, nick) {
  16655. var roomjid = roomName;
  16656. if (useNicks) {
  16657. if (nick) {
  16658. roomjid += '/' + nick;
  16659. } else {
  16660. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  16661. }
  16662. } else {
  16663. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  16664. if(!authenticatedUser)
  16665. tmpJid = tmpJid.substr(0, 8);
  16666. roomjid += '/' + tmpJid;
  16667. }
  16668. connection.emuc.doJoin(roomjid);
  16669. },
  16670. myJid: function () {
  16671. if(!connection)
  16672. return null;
  16673. return connection.emuc.myroomjid;
  16674. },
  16675. myResource: function () {
  16676. if(!connection || ! connection.emuc.myroomjid)
  16677. return null;
  16678. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  16679. },
  16680. disposeConference: function (onUnload) {
  16681. var handler = connection.jingle.activecall;
  16682. if (handler && handler.peerconnection) {
  16683. // FIXME: probably removing streams is not required and close() should
  16684. // be enough
  16685. if (APP.RTC.localAudio) {
  16686. handler.peerconnection.removeStream(
  16687. APP.RTC.localAudio.getOriginalStream(), onUnload);
  16688. }
  16689. if (APP.RTC.localVideo) {
  16690. handler.peerconnection.removeStream(
  16691. APP.RTC.localVideo.getOriginalStream(), onUnload);
  16692. }
  16693. handler.peerconnection.close();
  16694. }
  16695. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  16696. connection.jingle.activecall = null;
  16697. if (!onUnload) {
  16698. this.sessionTerminated = true;
  16699. connection.emuc.doLeave();
  16700. }
  16701. },
  16702. addListener: function(type, listener) {
  16703. eventEmitter.on(type, listener);
  16704. },
  16705. removeListener: function (type, listener) {
  16706. eventEmitter.removeListener(type, listener);
  16707. },
  16708. allocateConferenceFocus: function(roomName, callback) {
  16709. Moderator.allocateConferenceFocus(roomName, callback);
  16710. },
  16711. getLoginUrl: function (roomName, callback) {
  16712. Moderator.getLoginUrl(roomName, callback);
  16713. },
  16714. getPopupLoginUrl: function (roomName, callback) {
  16715. Moderator.getPopupLoginUrl(roomName, callback);
  16716. },
  16717. isModerator: function () {
  16718. return Moderator.isModerator();
  16719. },
  16720. isSipGatewayEnabled: function () {
  16721. return Moderator.isSipGatewayEnabled();
  16722. },
  16723. isExternalAuthEnabled: function () {
  16724. return Moderator.isExternalAuthEnabled();
  16725. },
  16726. isConferenceInProgress: function () {
  16727. return connection && connection.jingle.activecall &&
  16728. connection.jingle.activecall.peerconnection;
  16729. },
  16730. switchStreams: function (stream, oldStream, callback, isAudio) {
  16731. if (this.isConferenceInProgress()) {
  16732. // FIXME: will block switchInProgress on true value in case of exception
  16733. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  16734. } else {
  16735. // We are done immediately
  16736. console.warn("No conference handler or conference not started yet");
  16737. callback();
  16738. }
  16739. },
  16740. sendVideoInfoPresence: function (mute) {
  16741. if(!connection)
  16742. return;
  16743. connection.emuc.addVideoInfoToPresence(mute);
  16744. connection.emuc.sendPresence();
  16745. },
  16746. setVideoMute: function (mute, callback, options) {
  16747. if(!connection)
  16748. return;
  16749. var self = this;
  16750. var localCallback = function (mute) {
  16751. self.sendVideoInfoPresence(mute);
  16752. return callback(mute);
  16753. };
  16754. if(connection.jingle.activecall)
  16755. {
  16756. connection.jingle.activecall.setVideoMute(
  16757. mute, localCallback, options);
  16758. }
  16759. else {
  16760. localCallback(mute);
  16761. }
  16762. },
  16763. setAudioMute: function (mute, callback) {
  16764. if (!(connection && APP.RTC.localAudio)) {
  16765. return false;
  16766. }
  16767. if (this.forceMuted && !mute) {
  16768. console.info("Asking focus for unmute");
  16769. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  16770. // FIXME: wait for result before resetting muted status
  16771. this.forceMuted = false;
  16772. }
  16773. if (mute == APP.RTC.localAudio.isMuted()) {
  16774. // Nothing to do
  16775. return true;
  16776. }
  16777. APP.RTC.localAudio.setMute(mute);
  16778. this.sendAudioInfoPresence(mute, callback);
  16779. return true;
  16780. },
  16781. sendAudioInfoPresence: function(mute, callback) {
  16782. if(connection) {
  16783. connection.emuc.addAudioInfoToPresence(mute);
  16784. connection.emuc.sendPresence();
  16785. }
  16786. callback();
  16787. return true;
  16788. },
  16789. toggleRecording: function (tokenEmptyCallback,
  16790. recordingStateChangeCallback) {
  16791. Recording.toggleRecording(tokenEmptyCallback,
  16792. recordingStateChangeCallback, connection);
  16793. },
  16794. addToPresence: function (name, value, dontSend) {
  16795. switch (name) {
  16796. case "displayName":
  16797. connection.emuc.addDisplayNameToPresence(value);
  16798. break;
  16799. case "prezi":
  16800. connection.emuc.addPreziToPresence(value, 0);
  16801. break;
  16802. case "preziSlide":
  16803. connection.emuc.addCurrentSlideToPresence(value);
  16804. break;
  16805. case "connectionQuality":
  16806. connection.emuc.addConnectionInfoToPresence(value);
  16807. break;
  16808. case "email":
  16809. connection.emuc.addEmailToPresence(value);
  16810. break;
  16811. case "devices":
  16812. connection.emuc.addDevicesToPresence(value);
  16813. break;
  16814. case "videoType":
  16815. connection.emuc.addVideoTypeToPresence(value);
  16816. break;
  16817. case "startMuted":
  16818. if(!Moderator.isModerator())
  16819. return;
  16820. connection.emuc.addStartMutedToPresence(value[0],
  16821. value[1]);
  16822. break;
  16823. default :
  16824. console.log("Unknown tag for presence: " + name);
  16825. return;
  16826. }
  16827. if (!dontSend)
  16828. connection.emuc.sendPresence();
  16829. },
  16830. /**
  16831. * Sends 'data' as a log message to the focus. Returns true iff a message
  16832. * was sent.
  16833. * @param data
  16834. * @returns {boolean} true iff a message was sent.
  16835. */
  16836. sendLogs: function (data) {
  16837. if(!connection.emuc.focusMucJid)
  16838. return false;
  16839. var deflate = true;
  16840. var content = JSON.stringify(data);
  16841. if (deflate) {
  16842. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  16843. }
  16844. content = Base64.encode(content);
  16845. // XEP-0337-ish
  16846. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  16847. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  16848. id: 'PeerConnectionStats'});
  16849. message.c('message').t(content).up();
  16850. if (deflate) {
  16851. message.c('tag', {name: "deflated", value: "true"}).up();
  16852. }
  16853. message.up();
  16854. connection.send(message);
  16855. return true;
  16856. },
  16857. // Gets the logs from strophe.jingle.
  16858. getJingleLog: function () {
  16859. return connection.jingle ? connection.jingle.getLog() : {};
  16860. },
  16861. // Gets the logs from strophe.
  16862. getXmppLog: function () {
  16863. return connection.logger ? connection.logger.log : null;
  16864. },
  16865. getPrezi: function () {
  16866. return connection.emuc.getPrezi(this.myJid());
  16867. },
  16868. removePreziFromPresence: function () {
  16869. connection.emuc.removePreziFromPresence();
  16870. connection.emuc.sendPresence();
  16871. },
  16872. sendChatMessage: function (message, nickname) {
  16873. connection.emuc.sendMessage(message, nickname);
  16874. },
  16875. setSubject: function (topic) {
  16876. connection.emuc.setSubject(topic);
  16877. },
  16878. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  16879. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  16880. },
  16881. dial: function (to, from, roomName,roomPass) {
  16882. connection.rayo.dial(to, from, roomName,roomPass);
  16883. },
  16884. setMute: function (jid, mute) {
  16885. connection.moderate.setMute(jid, mute);
  16886. },
  16887. eject: function (jid) {
  16888. connection.moderate.eject(jid);
  16889. },
  16890. logout: function (callback) {
  16891. Moderator.logout(callback);
  16892. },
  16893. findJidFromResource: function (resource) {
  16894. return connection.emuc.findJidFromResource(resource);
  16895. },
  16896. getMembers: function () {
  16897. return connection.emuc.members;
  16898. },
  16899. getJidFromSSRC: function (ssrc) {
  16900. if (!this.isConferenceInProgress())
  16901. return null;
  16902. return connection.jingle.activecall.getSsrcOwner(ssrc);
  16903. },
  16904. // Returns true iff we have joined the MUC.
  16905. isMUCJoined: function () {
  16906. return connection.emuc.joined;
  16907. },
  16908. getSessions: function () {
  16909. return connection.jingle.sessions;
  16910. },
  16911. removeStream: function (stream) {
  16912. if (!this.isConferenceInProgress())
  16913. return;
  16914. connection.jingle.activecall.peerconnection.removeStream(stream);
  16915. }
  16916. };
  16917. module.exports = XMPP;
  16918. },{"../../service/RTC/RTCEvents":152,"../../service/RTC/StreamEventTypes":154,"../../service/xmpp/XMPPEvents":161,"../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":162,"pako":72,"retry":88}],69:[function(require,module,exports){
  16919. (function (process){
  16920. /*!
  16921. * async
  16922. * https://github.com/caolan/async
  16923. *
  16924. * Copyright 2010-2014 Caolan McMahon
  16925. * Released under the MIT license
  16926. */
  16927. /*jshint onevar: false, indent:4 */
  16928. /*global setImmediate: false, setTimeout: false, console: false */
  16929. (function () {
  16930. var async = {};
  16931. // global on the server, window in the browser
  16932. var root, previous_async;
  16933. root = this;
  16934. if (root != null) {
  16935. previous_async = root.async;
  16936. }
  16937. async.noConflict = function () {
  16938. root.async = previous_async;
  16939. return async;
  16940. };
  16941. function only_once(fn) {
  16942. var called = false;
  16943. return function() {
  16944. if (called) throw new Error("Callback was already called.");
  16945. called = true;
  16946. fn.apply(root, arguments);
  16947. }
  16948. }
  16949. //// cross-browser compatiblity functions ////
  16950. var _toString = Object.prototype.toString;
  16951. var _isArray = Array.isArray || function (obj) {
  16952. return _toString.call(obj) === '[object Array]';
  16953. };
  16954. var _each = function (arr, iterator) {
  16955. if (arr.forEach) {
  16956. return arr.forEach(iterator);
  16957. }
  16958. for (var i = 0; i < arr.length; i += 1) {
  16959. iterator(arr[i], i, arr);
  16960. }
  16961. };
  16962. var _map = function (arr, iterator) {
  16963. if (arr.map) {
  16964. return arr.map(iterator);
  16965. }
  16966. var results = [];
  16967. _each(arr, function (x, i, a) {
  16968. results.push(iterator(x, i, a));
  16969. });
  16970. return results;
  16971. };
  16972. var _reduce = function (arr, iterator, memo) {
  16973. if (arr.reduce) {
  16974. return arr.reduce(iterator, memo);
  16975. }
  16976. _each(arr, function (x, i, a) {
  16977. memo = iterator(memo, x, i, a);
  16978. });
  16979. return memo;
  16980. };
  16981. var _keys = function (obj) {
  16982. if (Object.keys) {
  16983. return Object.keys(obj);
  16984. }
  16985. var keys = [];
  16986. for (var k in obj) {
  16987. if (obj.hasOwnProperty(k)) {
  16988. keys.push(k);
  16989. }
  16990. }
  16991. return keys;
  16992. };
  16993. //// exported async module functions ////
  16994. //// nextTick implementation with browser-compatible fallback ////
  16995. if (typeof process === 'undefined' || !(process.nextTick)) {
  16996. if (typeof setImmediate === 'function') {
  16997. async.nextTick = function (fn) {
  16998. // not a direct alias for IE10 compatibility
  16999. setImmediate(fn);
  17000. };
  17001. async.setImmediate = async.nextTick;
  17002. }
  17003. else {
  17004. async.nextTick = function (fn) {
  17005. setTimeout(fn, 0);
  17006. };
  17007. async.setImmediate = async.nextTick;
  17008. }
  17009. }
  17010. else {
  17011. async.nextTick = process.nextTick;
  17012. if (typeof setImmediate !== 'undefined') {
  17013. async.setImmediate = function (fn) {
  17014. // not a direct alias for IE10 compatibility
  17015. setImmediate(fn);
  17016. };
  17017. }
  17018. else {
  17019. async.setImmediate = async.nextTick;
  17020. }
  17021. }
  17022. async.each = function (arr, iterator, callback) {
  17023. callback = callback || function () {};
  17024. if (!arr.length) {
  17025. return callback();
  17026. }
  17027. var completed = 0;
  17028. _each(arr, function (x) {
  17029. iterator(x, only_once(done) );
  17030. });
  17031. function done(err) {
  17032. if (err) {
  17033. callback(err);
  17034. callback = function () {};
  17035. }
  17036. else {
  17037. completed += 1;
  17038. if (completed >= arr.length) {
  17039. callback();
  17040. }
  17041. }
  17042. }
  17043. };
  17044. async.forEach = async.each;
  17045. async.eachSeries = function (arr, iterator, callback) {
  17046. callback = callback || function () {};
  17047. if (!arr.length) {
  17048. return callback();
  17049. }
  17050. var completed = 0;
  17051. var iterate = function () {
  17052. iterator(arr[completed], function (err) {
  17053. if (err) {
  17054. callback(err);
  17055. callback = function () {};
  17056. }
  17057. else {
  17058. completed += 1;
  17059. if (completed >= arr.length) {
  17060. callback();
  17061. }
  17062. else {
  17063. iterate();
  17064. }
  17065. }
  17066. });
  17067. };
  17068. iterate();
  17069. };
  17070. async.forEachSeries = async.eachSeries;
  17071. async.eachLimit = function (arr, limit, iterator, callback) {
  17072. var fn = _eachLimit(limit);
  17073. fn.apply(null, [arr, iterator, callback]);
  17074. };
  17075. async.forEachLimit = async.eachLimit;
  17076. var _eachLimit = function (limit) {
  17077. return function (arr, iterator, callback) {
  17078. callback = callback || function () {};
  17079. if (!arr.length || limit <= 0) {
  17080. return callback();
  17081. }
  17082. var completed = 0;
  17083. var started = 0;
  17084. var running = 0;
  17085. (function replenish () {
  17086. if (completed >= arr.length) {
  17087. return callback();
  17088. }
  17089. while (running < limit && started < arr.length) {
  17090. started += 1;
  17091. running += 1;
  17092. iterator(arr[started - 1], function (err) {
  17093. if (err) {
  17094. callback(err);
  17095. callback = function () {};
  17096. }
  17097. else {
  17098. completed += 1;
  17099. running -= 1;
  17100. if (completed >= arr.length) {
  17101. callback();
  17102. }
  17103. else {
  17104. replenish();
  17105. }
  17106. }
  17107. });
  17108. }
  17109. })();
  17110. };
  17111. };
  17112. var doParallel = function (fn) {
  17113. return function () {
  17114. var args = Array.prototype.slice.call(arguments);
  17115. return fn.apply(null, [async.each].concat(args));
  17116. };
  17117. };
  17118. var doParallelLimit = function(limit, fn) {
  17119. return function () {
  17120. var args = Array.prototype.slice.call(arguments);
  17121. return fn.apply(null, [_eachLimit(limit)].concat(args));
  17122. };
  17123. };
  17124. var doSeries = function (fn) {
  17125. return function () {
  17126. var args = Array.prototype.slice.call(arguments);
  17127. return fn.apply(null, [async.eachSeries].concat(args));
  17128. };
  17129. };
  17130. var _asyncMap = function (eachfn, arr, iterator, callback) {
  17131. arr = _map(arr, function (x, i) {
  17132. return {index: i, value: x};
  17133. });
  17134. if (!callback) {
  17135. eachfn(arr, function (x, callback) {
  17136. iterator(x.value, function (err) {
  17137. callback(err);
  17138. });
  17139. });
  17140. } else {
  17141. var results = [];
  17142. eachfn(arr, function (x, callback) {
  17143. iterator(x.value, function (err, v) {
  17144. results[x.index] = v;
  17145. callback(err);
  17146. });
  17147. }, function (err) {
  17148. callback(err, results);
  17149. });
  17150. }
  17151. };
  17152. async.map = doParallel(_asyncMap);
  17153. async.mapSeries = doSeries(_asyncMap);
  17154. async.mapLimit = function (arr, limit, iterator, callback) {
  17155. return _mapLimit(limit)(arr, iterator, callback);
  17156. };
  17157. var _mapLimit = function(limit) {
  17158. return doParallelLimit(limit, _asyncMap);
  17159. };
  17160. // reduce only has a series version, as doing reduce in parallel won't
  17161. // work in many situations.
  17162. async.reduce = function (arr, memo, iterator, callback) {
  17163. async.eachSeries(arr, function (x, callback) {
  17164. iterator(memo, x, function (err, v) {
  17165. memo = v;
  17166. callback(err);
  17167. });
  17168. }, function (err) {
  17169. callback(err, memo);
  17170. });
  17171. };
  17172. // inject alias
  17173. async.inject = async.reduce;
  17174. // foldl alias
  17175. async.foldl = async.reduce;
  17176. async.reduceRight = function (arr, memo, iterator, callback) {
  17177. var reversed = _map(arr, function (x) {
  17178. return x;
  17179. }).reverse();
  17180. async.reduce(reversed, memo, iterator, callback);
  17181. };
  17182. // foldr alias
  17183. async.foldr = async.reduceRight;
  17184. var _filter = function (eachfn, arr, iterator, callback) {
  17185. var results = [];
  17186. arr = _map(arr, function (x, i) {
  17187. return {index: i, value: x};
  17188. });
  17189. eachfn(arr, function (x, callback) {
  17190. iterator(x.value, function (v) {
  17191. if (v) {
  17192. results.push(x);
  17193. }
  17194. callback();
  17195. });
  17196. }, function (err) {
  17197. callback(_map(results.sort(function (a, b) {
  17198. return a.index - b.index;
  17199. }), function (x) {
  17200. return x.value;
  17201. }));
  17202. });
  17203. };
  17204. async.filter = doParallel(_filter);
  17205. async.filterSeries = doSeries(_filter);
  17206. // select alias
  17207. async.select = async.filter;
  17208. async.selectSeries = async.filterSeries;
  17209. var _reject = function (eachfn, arr, iterator, callback) {
  17210. var results = [];
  17211. arr = _map(arr, function (x, i) {
  17212. return {index: i, value: x};
  17213. });
  17214. eachfn(arr, function (x, callback) {
  17215. iterator(x.value, function (v) {
  17216. if (!v) {
  17217. results.push(x);
  17218. }
  17219. callback();
  17220. });
  17221. }, function (err) {
  17222. callback(_map(results.sort(function (a, b) {
  17223. return a.index - b.index;
  17224. }), function (x) {
  17225. return x.value;
  17226. }));
  17227. });
  17228. };
  17229. async.reject = doParallel(_reject);
  17230. async.rejectSeries = doSeries(_reject);
  17231. var _detect = function (eachfn, arr, iterator, main_callback) {
  17232. eachfn(arr, function (x, callback) {
  17233. iterator(x, function (result) {
  17234. if (result) {
  17235. main_callback(x);
  17236. main_callback = function () {};
  17237. }
  17238. else {
  17239. callback();
  17240. }
  17241. });
  17242. }, function (err) {
  17243. main_callback();
  17244. });
  17245. };
  17246. async.detect = doParallel(_detect);
  17247. async.detectSeries = doSeries(_detect);
  17248. async.some = function (arr, iterator, main_callback) {
  17249. async.each(arr, function (x, callback) {
  17250. iterator(x, function (v) {
  17251. if (v) {
  17252. main_callback(true);
  17253. main_callback = function () {};
  17254. }
  17255. callback();
  17256. });
  17257. }, function (err) {
  17258. main_callback(false);
  17259. });
  17260. };
  17261. // any alias
  17262. async.any = async.some;
  17263. async.every = function (arr, iterator, main_callback) {
  17264. async.each(arr, function (x, callback) {
  17265. iterator(x, function (v) {
  17266. if (!v) {
  17267. main_callback(false);
  17268. main_callback = function () {};
  17269. }
  17270. callback();
  17271. });
  17272. }, function (err) {
  17273. main_callback(true);
  17274. });
  17275. };
  17276. // all alias
  17277. async.all = async.every;
  17278. async.sortBy = function (arr, iterator, callback) {
  17279. async.map(arr, function (x, callback) {
  17280. iterator(x, function (err, criteria) {
  17281. if (err) {
  17282. callback(err);
  17283. }
  17284. else {
  17285. callback(null, {value: x, criteria: criteria});
  17286. }
  17287. });
  17288. }, function (err, results) {
  17289. if (err) {
  17290. return callback(err);
  17291. }
  17292. else {
  17293. var fn = function (left, right) {
  17294. var a = left.criteria, b = right.criteria;
  17295. return a < b ? -1 : a > b ? 1 : 0;
  17296. };
  17297. callback(null, _map(results.sort(fn), function (x) {
  17298. return x.value;
  17299. }));
  17300. }
  17301. });
  17302. };
  17303. async.auto = function (tasks, callback) {
  17304. callback = callback || function () {};
  17305. var keys = _keys(tasks);
  17306. var remainingTasks = keys.length
  17307. if (!remainingTasks) {
  17308. return callback();
  17309. }
  17310. var results = {};
  17311. var listeners = [];
  17312. var addListener = function (fn) {
  17313. listeners.unshift(fn);
  17314. };
  17315. var removeListener = function (fn) {
  17316. for (var i = 0; i < listeners.length; i += 1) {
  17317. if (listeners[i] === fn) {
  17318. listeners.splice(i, 1);
  17319. return;
  17320. }
  17321. }
  17322. };
  17323. var taskComplete = function () {
  17324. remainingTasks--
  17325. _each(listeners.slice(0), function (fn) {
  17326. fn();
  17327. });
  17328. };
  17329. addListener(function () {
  17330. if (!remainingTasks) {
  17331. var theCallback = callback;
  17332. // prevent final callback from calling itself if it errors
  17333. callback = function () {};
  17334. theCallback(null, results);
  17335. }
  17336. });
  17337. _each(keys, function (k) {
  17338. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  17339. var taskCallback = function (err) {
  17340. var args = Array.prototype.slice.call(arguments, 1);
  17341. if (args.length <= 1) {
  17342. args = args[0];
  17343. }
  17344. if (err) {
  17345. var safeResults = {};
  17346. _each(_keys(results), function(rkey) {
  17347. safeResults[rkey] = results[rkey];
  17348. });
  17349. safeResults[k] = args;
  17350. callback(err, safeResults);
  17351. // stop subsequent errors hitting callback multiple times
  17352. callback = function () {};
  17353. }
  17354. else {
  17355. results[k] = args;
  17356. async.setImmediate(taskComplete);
  17357. }
  17358. };
  17359. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  17360. var ready = function () {
  17361. return _reduce(requires, function (a, x) {
  17362. return (a && results.hasOwnProperty(x));
  17363. }, true) && !results.hasOwnProperty(k);
  17364. };
  17365. if (ready()) {
  17366. task[task.length - 1](taskCallback, results);
  17367. }
  17368. else {
  17369. var listener = function () {
  17370. if (ready()) {
  17371. removeListener(listener);
  17372. task[task.length - 1](taskCallback, results);
  17373. }
  17374. };
  17375. addListener(listener);
  17376. }
  17377. });
  17378. };
  17379. async.retry = function(times, task, callback) {
  17380. var DEFAULT_TIMES = 5;
  17381. var attempts = [];
  17382. // Use defaults if times not passed
  17383. if (typeof times === 'function') {
  17384. callback = task;
  17385. task = times;
  17386. times = DEFAULT_TIMES;
  17387. }
  17388. // Make sure times is a number
  17389. times = parseInt(times, 10) || DEFAULT_TIMES;
  17390. var wrappedTask = function(wrappedCallback, wrappedResults) {
  17391. var retryAttempt = function(task, finalAttempt) {
  17392. return function(seriesCallback) {
  17393. task(function(err, result){
  17394. seriesCallback(!err || finalAttempt, {err: err, result: result});
  17395. }, wrappedResults);
  17396. };
  17397. };
  17398. while (times) {
  17399. attempts.push(retryAttempt(task, !(times-=1)));
  17400. }
  17401. async.series(attempts, function(done, data){
  17402. data = data[data.length - 1];
  17403. (wrappedCallback || callback)(data.err, data.result);
  17404. });
  17405. }
  17406. // If a callback is passed, run this as a controll flow
  17407. return callback ? wrappedTask() : wrappedTask
  17408. };
  17409. async.waterfall = function (tasks, callback) {
  17410. callback = callback || function () {};
  17411. if (!_isArray(tasks)) {
  17412. var err = new Error('First argument to waterfall must be an array of functions');
  17413. return callback(err);
  17414. }
  17415. if (!tasks.length) {
  17416. return callback();
  17417. }
  17418. var wrapIterator = function (iterator) {
  17419. return function (err) {
  17420. if (err) {
  17421. callback.apply(null, arguments);
  17422. callback = function () {};
  17423. }
  17424. else {
  17425. var args = Array.prototype.slice.call(arguments, 1);
  17426. var next = iterator.next();
  17427. if (next) {
  17428. args.push(wrapIterator(next));
  17429. }
  17430. else {
  17431. args.push(callback);
  17432. }
  17433. async.setImmediate(function () {
  17434. iterator.apply(null, args);
  17435. });
  17436. }
  17437. };
  17438. };
  17439. wrapIterator(async.iterator(tasks))();
  17440. };
  17441. var _parallel = function(eachfn, tasks, callback) {
  17442. callback = callback || function () {};
  17443. if (_isArray(tasks)) {
  17444. eachfn.map(tasks, function (fn, callback) {
  17445. if (fn) {
  17446. fn(function (err) {
  17447. var args = Array.prototype.slice.call(arguments, 1);
  17448. if (args.length <= 1) {
  17449. args = args[0];
  17450. }
  17451. callback.call(null, err, args);
  17452. });
  17453. }
  17454. }, callback);
  17455. }
  17456. else {
  17457. var results = {};
  17458. eachfn.each(_keys(tasks), function (k, callback) {
  17459. tasks[k](function (err) {
  17460. var args = Array.prototype.slice.call(arguments, 1);
  17461. if (args.length <= 1) {
  17462. args = args[0];
  17463. }
  17464. results[k] = args;
  17465. callback(err);
  17466. });
  17467. }, function (err) {
  17468. callback(err, results);
  17469. });
  17470. }
  17471. };
  17472. async.parallel = function (tasks, callback) {
  17473. _parallel({ map: async.map, each: async.each }, tasks, callback);
  17474. };
  17475. async.parallelLimit = function(tasks, limit, callback) {
  17476. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  17477. };
  17478. async.series = function (tasks, callback) {
  17479. callback = callback || function () {};
  17480. if (_isArray(tasks)) {
  17481. async.mapSeries(tasks, function (fn, callback) {
  17482. if (fn) {
  17483. fn(function (err) {
  17484. var args = Array.prototype.slice.call(arguments, 1);
  17485. if (args.length <= 1) {
  17486. args = args[0];
  17487. }
  17488. callback.call(null, err, args);
  17489. });
  17490. }
  17491. }, callback);
  17492. }
  17493. else {
  17494. var results = {};
  17495. async.eachSeries(_keys(tasks), function (k, callback) {
  17496. tasks[k](function (err) {
  17497. var args = Array.prototype.slice.call(arguments, 1);
  17498. if (args.length <= 1) {
  17499. args = args[0];
  17500. }
  17501. results[k] = args;
  17502. callback(err);
  17503. });
  17504. }, function (err) {
  17505. callback(err, results);
  17506. });
  17507. }
  17508. };
  17509. async.iterator = function (tasks) {
  17510. var makeCallback = function (index) {
  17511. var fn = function () {
  17512. if (tasks.length) {
  17513. tasks[index].apply(null, arguments);
  17514. }
  17515. return fn.next();
  17516. };
  17517. fn.next = function () {
  17518. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  17519. };
  17520. return fn;
  17521. };
  17522. return makeCallback(0);
  17523. };
  17524. async.apply = function (fn) {
  17525. var args = Array.prototype.slice.call(arguments, 1);
  17526. return function () {
  17527. return fn.apply(
  17528. null, args.concat(Array.prototype.slice.call(arguments))
  17529. );
  17530. };
  17531. };
  17532. var _concat = function (eachfn, arr, fn, callback) {
  17533. var r = [];
  17534. eachfn(arr, function (x, cb) {
  17535. fn(x, function (err, y) {
  17536. r = r.concat(y || []);
  17537. cb(err);
  17538. });
  17539. }, function (err) {
  17540. callback(err, r);
  17541. });
  17542. };
  17543. async.concat = doParallel(_concat);
  17544. async.concatSeries = doSeries(_concat);
  17545. async.whilst = function (test, iterator, callback) {
  17546. if (test()) {
  17547. iterator(function (err) {
  17548. if (err) {
  17549. return callback(err);
  17550. }
  17551. async.whilst(test, iterator, callback);
  17552. });
  17553. }
  17554. else {
  17555. callback();
  17556. }
  17557. };
  17558. async.doWhilst = function (iterator, test, callback) {
  17559. iterator(function (err) {
  17560. if (err) {
  17561. return callback(err);
  17562. }
  17563. var args = Array.prototype.slice.call(arguments, 1);
  17564. if (test.apply(null, args)) {
  17565. async.doWhilst(iterator, test, callback);
  17566. }
  17567. else {
  17568. callback();
  17569. }
  17570. });
  17571. };
  17572. async.until = function (test, iterator, callback) {
  17573. if (!test()) {
  17574. iterator(function (err) {
  17575. if (err) {
  17576. return callback(err);
  17577. }
  17578. async.until(test, iterator, callback);
  17579. });
  17580. }
  17581. else {
  17582. callback();
  17583. }
  17584. };
  17585. async.doUntil = function (iterator, test, callback) {
  17586. iterator(function (err) {
  17587. if (err) {
  17588. return callback(err);
  17589. }
  17590. var args = Array.prototype.slice.call(arguments, 1);
  17591. if (!test.apply(null, args)) {
  17592. async.doUntil(iterator, test, callback);
  17593. }
  17594. else {
  17595. callback();
  17596. }
  17597. });
  17598. };
  17599. async.queue = function (worker, concurrency) {
  17600. if (concurrency === undefined) {
  17601. concurrency = 1;
  17602. }
  17603. function _insert(q, data, pos, callback) {
  17604. if (!q.started){
  17605. q.started = true;
  17606. }
  17607. if (!_isArray(data)) {
  17608. data = [data];
  17609. }
  17610. if(data.length == 0) {
  17611. // call drain immediately if there are no tasks
  17612. return async.setImmediate(function() {
  17613. if (q.drain) {
  17614. q.drain();
  17615. }
  17616. });
  17617. }
  17618. _each(data, function(task) {
  17619. var item = {
  17620. data: task,
  17621. callback: typeof callback === 'function' ? callback : null
  17622. };
  17623. if (pos) {
  17624. q.tasks.unshift(item);
  17625. } else {
  17626. q.tasks.push(item);
  17627. }
  17628. if (q.saturated && q.tasks.length === q.concurrency) {
  17629. q.saturated();
  17630. }
  17631. async.setImmediate(q.process);
  17632. });
  17633. }
  17634. var workers = 0;
  17635. var q = {
  17636. tasks: [],
  17637. concurrency: concurrency,
  17638. saturated: null,
  17639. empty: null,
  17640. drain: null,
  17641. started: false,
  17642. paused: false,
  17643. push: function (data, callback) {
  17644. _insert(q, data, false, callback);
  17645. },
  17646. kill: function () {
  17647. q.drain = null;
  17648. q.tasks = [];
  17649. },
  17650. unshift: function (data, callback) {
  17651. _insert(q, data, true, callback);
  17652. },
  17653. process: function () {
  17654. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  17655. var task = q.tasks.shift();
  17656. if (q.empty && q.tasks.length === 0) {
  17657. q.empty();
  17658. }
  17659. workers += 1;
  17660. var next = function () {
  17661. workers -= 1;
  17662. if (task.callback) {
  17663. task.callback.apply(task, arguments);
  17664. }
  17665. if (q.drain && q.tasks.length + workers === 0) {
  17666. q.drain();
  17667. }
  17668. q.process();
  17669. };
  17670. var cb = only_once(next);
  17671. worker(task.data, cb);
  17672. }
  17673. },
  17674. length: function () {
  17675. return q.tasks.length;
  17676. },
  17677. running: function () {
  17678. return workers;
  17679. },
  17680. idle: function() {
  17681. return q.tasks.length + workers === 0;
  17682. },
  17683. pause: function () {
  17684. if (q.paused === true) { return; }
  17685. q.paused = true;
  17686. q.process();
  17687. },
  17688. resume: function () {
  17689. if (q.paused === false) { return; }
  17690. q.paused = false;
  17691. q.process();
  17692. }
  17693. };
  17694. return q;
  17695. };
  17696. async.priorityQueue = function (worker, concurrency) {
  17697. function _compareTasks(a, b){
  17698. return a.priority - b.priority;
  17699. };
  17700. function _binarySearch(sequence, item, compare) {
  17701. var beg = -1,
  17702. end = sequence.length - 1;
  17703. while (beg < end) {
  17704. var mid = beg + ((end - beg + 1) >>> 1);
  17705. if (compare(item, sequence[mid]) >= 0) {
  17706. beg = mid;
  17707. } else {
  17708. end = mid - 1;
  17709. }
  17710. }
  17711. return beg;
  17712. }
  17713. function _insert(q, data, priority, callback) {
  17714. if (!q.started){
  17715. q.started = true;
  17716. }
  17717. if (!_isArray(data)) {
  17718. data = [data];
  17719. }
  17720. if(data.length == 0) {
  17721. // call drain immediately if there are no tasks
  17722. return async.setImmediate(function() {
  17723. if (q.drain) {
  17724. q.drain();
  17725. }
  17726. });
  17727. }
  17728. _each(data, function(task) {
  17729. var item = {
  17730. data: task,
  17731. priority: priority,
  17732. callback: typeof callback === 'function' ? callback : null
  17733. };
  17734. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  17735. if (q.saturated && q.tasks.length === q.concurrency) {
  17736. q.saturated();
  17737. }
  17738. async.setImmediate(q.process);
  17739. });
  17740. }
  17741. // Start with a normal queue
  17742. var q = async.queue(worker, concurrency);
  17743. // Override push to accept second parameter representing priority
  17744. q.push = function (data, priority, callback) {
  17745. _insert(q, data, priority, callback);
  17746. };
  17747. // Remove unshift function
  17748. delete q.unshift;
  17749. return q;
  17750. };
  17751. async.cargo = function (worker, payload) {
  17752. var working = false,
  17753. tasks = [];
  17754. var cargo = {
  17755. tasks: tasks,
  17756. payload: payload,
  17757. saturated: null,
  17758. empty: null,
  17759. drain: null,
  17760. drained: true,
  17761. push: function (data, callback) {
  17762. if (!_isArray(data)) {
  17763. data = [data];
  17764. }
  17765. _each(data, function(task) {
  17766. tasks.push({
  17767. data: task,
  17768. callback: typeof callback === 'function' ? callback : null
  17769. });
  17770. cargo.drained = false;
  17771. if (cargo.saturated && tasks.length === payload) {
  17772. cargo.saturated();
  17773. }
  17774. });
  17775. async.setImmediate(cargo.process);
  17776. },
  17777. process: function process() {
  17778. if (working) return;
  17779. if (tasks.length === 0) {
  17780. if(cargo.drain && !cargo.drained) cargo.drain();
  17781. cargo.drained = true;
  17782. return;
  17783. }
  17784. var ts = typeof payload === 'number'
  17785. ? tasks.splice(0, payload)
  17786. : tasks.splice(0, tasks.length);
  17787. var ds = _map(ts, function (task) {
  17788. return task.data;
  17789. });
  17790. if(cargo.empty) cargo.empty();
  17791. working = true;
  17792. worker(ds, function () {
  17793. working = false;
  17794. var args = arguments;
  17795. _each(ts, function (data) {
  17796. if (data.callback) {
  17797. data.callback.apply(null, args);
  17798. }
  17799. });
  17800. process();
  17801. });
  17802. },
  17803. length: function () {
  17804. return tasks.length;
  17805. },
  17806. running: function () {
  17807. return working;
  17808. }
  17809. };
  17810. return cargo;
  17811. };
  17812. var _console_fn = function (name) {
  17813. return function (fn) {
  17814. var args = Array.prototype.slice.call(arguments, 1);
  17815. fn.apply(null, args.concat([function (err) {
  17816. var args = Array.prototype.slice.call(arguments, 1);
  17817. if (typeof console !== 'undefined') {
  17818. if (err) {
  17819. if (console.error) {
  17820. console.error(err);
  17821. }
  17822. }
  17823. else if (console[name]) {
  17824. _each(args, function (x) {
  17825. console[name](x);
  17826. });
  17827. }
  17828. }
  17829. }]));
  17830. };
  17831. };
  17832. async.log = _console_fn('log');
  17833. async.dir = _console_fn('dir');
  17834. /*async.info = _console_fn('info');
  17835. async.warn = _console_fn('warn');
  17836. async.error = _console_fn('error');*/
  17837. async.memoize = function (fn, hasher) {
  17838. var memo = {};
  17839. var queues = {};
  17840. hasher = hasher || function (x) {
  17841. return x;
  17842. };
  17843. var memoized = function () {
  17844. var args = Array.prototype.slice.call(arguments);
  17845. var callback = args.pop();
  17846. var key = hasher.apply(null, args);
  17847. if (key in memo) {
  17848. async.nextTick(function () {
  17849. callback.apply(null, memo[key]);
  17850. });
  17851. }
  17852. else if (key in queues) {
  17853. queues[key].push(callback);
  17854. }
  17855. else {
  17856. queues[key] = [callback];
  17857. fn.apply(null, args.concat([function () {
  17858. memo[key] = arguments;
  17859. var q = queues[key];
  17860. delete queues[key];
  17861. for (var i = 0, l = q.length; i < l; i++) {
  17862. q[i].apply(null, arguments);
  17863. }
  17864. }]));
  17865. }
  17866. };
  17867. memoized.memo = memo;
  17868. memoized.unmemoized = fn;
  17869. return memoized;
  17870. };
  17871. async.unmemoize = function (fn) {
  17872. return function () {
  17873. return (fn.unmemoized || fn).apply(null, arguments);
  17874. };
  17875. };
  17876. async.times = function (count, iterator, callback) {
  17877. var counter = [];
  17878. for (var i = 0; i < count; i++) {
  17879. counter.push(i);
  17880. }
  17881. return async.map(counter, iterator, callback);
  17882. };
  17883. async.timesSeries = function (count, iterator, callback) {
  17884. var counter = [];
  17885. for (var i = 0; i < count; i++) {
  17886. counter.push(i);
  17887. }
  17888. return async.mapSeries(counter, iterator, callback);
  17889. };
  17890. async.seq = function (/* functions... */) {
  17891. var fns = arguments;
  17892. return function () {
  17893. var that = this;
  17894. var args = Array.prototype.slice.call(arguments);
  17895. var callback = args.pop();
  17896. async.reduce(fns, args, function (newargs, fn, cb) {
  17897. fn.apply(that, newargs.concat([function () {
  17898. var err = arguments[0];
  17899. var nextargs = Array.prototype.slice.call(arguments, 1);
  17900. cb(err, nextargs);
  17901. }]))
  17902. },
  17903. function (err, results) {
  17904. callback.apply(that, [err].concat(results));
  17905. });
  17906. };
  17907. };
  17908. async.compose = function (/* functions... */) {
  17909. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  17910. };
  17911. var _applyEach = function (eachfn, fns /*args...*/) {
  17912. var go = function () {
  17913. var that = this;
  17914. var args = Array.prototype.slice.call(arguments);
  17915. var callback = args.pop();
  17916. return eachfn(fns, function (fn, cb) {
  17917. fn.apply(that, args.concat([cb]));
  17918. },
  17919. callback);
  17920. };
  17921. if (arguments.length > 2) {
  17922. var args = Array.prototype.slice.call(arguments, 2);
  17923. return go.apply(this, args);
  17924. }
  17925. else {
  17926. return go;
  17927. }
  17928. };
  17929. async.applyEach = doParallel(_applyEach);
  17930. async.applyEachSeries = doSeries(_applyEach);
  17931. async.forever = function (fn, callback) {
  17932. function next(err) {
  17933. if (err) {
  17934. if (callback) {
  17935. return callback(err);
  17936. }
  17937. throw err;
  17938. }
  17939. fn(next);
  17940. }
  17941. next();
  17942. };
  17943. // Node.js
  17944. if (typeof module !== 'undefined' && module.exports) {
  17945. module.exports = async;
  17946. }
  17947. // AMD / RequireJS
  17948. else if (typeof define !== 'undefined' && define.amd) {
  17949. define([], function () {
  17950. return async;
  17951. });
  17952. }
  17953. // included directly via <script> tag
  17954. else {
  17955. root.async = async;
  17956. }
  17957. }());
  17958. }).call(this,require('_process'))
  17959. },{"_process":163}],70:[function(require,module,exports){
  17960. // i18next, v1.7.7
  17961. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  17962. // Distributed under MIT license
  17963. // http://i18next.com
  17964. (function() {
  17965. // add indexOf to non ECMA-262 standard compliant browsers
  17966. if (!Array.prototype.indexOf) {
  17967. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  17968. "use strict";
  17969. if (this == null) {
  17970. throw new TypeError();
  17971. }
  17972. var t = Object(this);
  17973. var len = t.length >>> 0;
  17974. if (len === 0) {
  17975. return -1;
  17976. }
  17977. var n = 0;
  17978. if (arguments.length > 0) {
  17979. n = Number(arguments[1]);
  17980. if (n != n) { // shortcut for verifying if it's NaN
  17981. n = 0;
  17982. } else if (n != 0 && n != Infinity && n != -Infinity) {
  17983. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17984. }
  17985. }
  17986. if (n >= len) {
  17987. return -1;
  17988. }
  17989. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  17990. for (; k < len; k++) {
  17991. if (k in t && t[k] === searchElement) {
  17992. return k;
  17993. }
  17994. }
  17995. return -1;
  17996. }
  17997. }
  17998. // add lastIndexOf to non ECMA-262 standard compliant browsers
  17999. if (!Array.prototype.lastIndexOf) {
  18000. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  18001. "use strict";
  18002. if (this == null) {
  18003. throw new TypeError();
  18004. }
  18005. var t = Object(this);
  18006. var len = t.length >>> 0;
  18007. if (len === 0) {
  18008. return -1;
  18009. }
  18010. var n = len;
  18011. if (arguments.length > 1) {
  18012. n = Number(arguments[1]);
  18013. if (n != n) {
  18014. n = 0;
  18015. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  18016. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  18017. }
  18018. }
  18019. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  18020. for (; k >= 0; k--) {
  18021. if (k in t && t[k] === searchElement) {
  18022. return k;
  18023. }
  18024. }
  18025. return -1;
  18026. };
  18027. }
  18028. // Add string trim for IE8.
  18029. if (typeof String.prototype.trim !== 'function') {
  18030. String.prototype.trim = function() {
  18031. return this.replace(/^\s+|\s+$/g, '');
  18032. }
  18033. }
  18034. var root = this
  18035. , $ = root.jQuery || root.Zepto
  18036. , i18n = {}
  18037. , resStore = {}
  18038. , currentLng
  18039. , replacementCounter = 0
  18040. , languages = []
  18041. , initialized = false
  18042. , sync = {};
  18043. // Export the i18next object for **CommonJS**.
  18044. // If we're not in CommonJS, add `i18n` to the
  18045. // global object or to jquery.
  18046. if (typeof module !== 'undefined' && module.exports) {
  18047. if (!$) {
  18048. try {
  18049. $ = require('jquery');
  18050. } catch(e) {
  18051. // just ignore
  18052. }
  18053. }
  18054. if ($) {
  18055. $.i18n = $.i18n || i18n;
  18056. }
  18057. module.exports = i18n;
  18058. } else {
  18059. if ($) {
  18060. $.i18n = $.i18n || i18n;
  18061. }
  18062. root.i18n = root.i18n || i18n;
  18063. }
  18064. sync = {
  18065. load: function(lngs, options, cb) {
  18066. if (options.useLocalStorage) {
  18067. sync._loadLocal(lngs, options, function(err, store) {
  18068. var missingLngs = [];
  18069. for (var i = 0, len = lngs.length; i < len; i++) {
  18070. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  18071. }
  18072. if (missingLngs.length > 0) {
  18073. sync._fetch(missingLngs, options, function(err, fetched) {
  18074. f.extend(store, fetched);
  18075. sync._storeLocal(fetched);
  18076. cb(null, store);
  18077. });
  18078. } else {
  18079. cb(null, store);
  18080. }
  18081. });
  18082. } else {
  18083. sync._fetch(lngs, options, function(err, store){
  18084. cb(null, store);
  18085. });
  18086. }
  18087. },
  18088. _loadLocal: function(lngs, options, cb) {
  18089. var store = {}
  18090. , nowMS = new Date().getTime();
  18091. if(window.localStorage) {
  18092. var todo = lngs.length;
  18093. f.each(lngs, function(key, lng) {
  18094. var local = window.localStorage.getItem('res_' + lng);
  18095. if (local) {
  18096. local = JSON.parse(local);
  18097. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  18098. store[lng] = local;
  18099. }
  18100. }
  18101. todo--; // wait for all done befor callback
  18102. if (todo === 0) cb(null, store);
  18103. });
  18104. }
  18105. },
  18106. _storeLocal: function(store) {
  18107. if(window.localStorage) {
  18108. for (var m in store) {
  18109. store[m].i18nStamp = new Date().getTime();
  18110. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  18111. }
  18112. }
  18113. return;
  18114. },
  18115. _fetch: function(lngs, options, cb) {
  18116. var ns = options.ns
  18117. , store = {};
  18118. if (!options.dynamicLoad) {
  18119. var todo = ns.namespaces.length * lngs.length
  18120. , errors;
  18121. // load each file individual
  18122. f.each(ns.namespaces, function(nsIndex, nsValue) {
  18123. f.each(lngs, function(lngIndex, lngValue) {
  18124. // Call this once our translation has returned.
  18125. var loadComplete = function(err, data) {
  18126. if (err) {
  18127. errors = errors || [];
  18128. errors.push(err);
  18129. }
  18130. store[lngValue] = store[lngValue] || {};
  18131. store[lngValue][nsValue] = data;
  18132. todo--; // wait for all done befor callback
  18133. if (todo === 0) cb(errors, store);
  18134. };
  18135. if(typeof options.customLoad == 'function'){
  18136. // Use the specified custom callback.
  18137. options.customLoad(lngValue, nsValue, options, loadComplete);
  18138. } else {
  18139. //~ // Use our inbuilt sync.
  18140. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  18141. }
  18142. });
  18143. });
  18144. } else {
  18145. // Call this once our translation has returned.
  18146. var loadComplete = function(err, data) {
  18147. cb(null, data);
  18148. };
  18149. if(typeof options.customLoad == 'function'){
  18150. // Use the specified custom callback.
  18151. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  18152. } else {
  18153. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  18154. // load all needed stuff once
  18155. f.ajax({
  18156. url: url,
  18157. success: function(data, status, xhr) {
  18158. f.log('loaded: ' + url);
  18159. loadComplete(null, data);
  18160. },
  18161. error : function(xhr, status, error) {
  18162. f.log('failed loading: ' + url);
  18163. loadComplete('failed loading resource.json error: ' + error);
  18164. },
  18165. dataType: "json",
  18166. async : options.getAsync
  18167. });
  18168. }
  18169. }
  18170. },
  18171. _fetchOne: function(lng, ns, options, done) {
  18172. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  18173. f.ajax({
  18174. url: url,
  18175. success: function(data, status, xhr) {
  18176. f.log('loaded: ' + url);
  18177. done(null, data);
  18178. },
  18179. error : function(xhr, status, error) {
  18180. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  18181. // file loaded but invalid json, stop waste time !
  18182. f.error('There is a typo in: ' + url);
  18183. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  18184. f.log('Does not exist: ' + url);
  18185. } else {
  18186. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  18187. f.log(theStatus + ' when loading ' + url);
  18188. }
  18189. done(error, {});
  18190. },
  18191. dataType: "json",
  18192. async : options.getAsync
  18193. });
  18194. },
  18195. postMissing: function(lng, ns, key, defaultValue, lngs) {
  18196. var payload = {};
  18197. payload[key] = defaultValue;
  18198. var urls = [];
  18199. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  18200. for (var i = 0; i < o.fallbackLng.length; i++) {
  18201. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  18202. }
  18203. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  18204. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  18205. } else if (o.sendMissingTo === 'all') {
  18206. for (var i = 0, l = lngs.length; i < l; i++) {
  18207. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  18208. }
  18209. }
  18210. for (var y = 0, len = urls.length; y < len; y++) {
  18211. var item = urls[y];
  18212. f.ajax({
  18213. url: item.url,
  18214. type: o.sendType,
  18215. data: payload,
  18216. success: function(data, status, xhr) {
  18217. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  18218. // add key to resStore
  18219. var keys = key.split('.');
  18220. var x = 0;
  18221. var value = resStore[item.lng][ns];
  18222. while (keys[x]) {
  18223. if (x === keys.length - 1) {
  18224. value = value[keys[x]] = defaultValue;
  18225. } else {
  18226. value = value[keys[x]] = value[keys[x]] || {};
  18227. }
  18228. x++;
  18229. }
  18230. },
  18231. error : function(xhr, status, error) {
  18232. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  18233. },
  18234. dataType: "json",
  18235. async : o.postAsync
  18236. });
  18237. }
  18238. },
  18239. reload: reload
  18240. };
  18241. // defaults
  18242. var o = {
  18243. lng: undefined,
  18244. load: 'all',
  18245. preload: [],
  18246. lowerCaseLng: false,
  18247. returnObjectTrees: false,
  18248. fallbackLng: ['dev'],
  18249. fallbackNS: [],
  18250. detectLngQS: 'setLng',
  18251. detectLngFromLocalStorage: false,
  18252. ns: 'translation',
  18253. fallbackOnNull: true,
  18254. fallbackOnEmpty: false,
  18255. fallbackToDefaultNS: false,
  18256. nsseparator: ':',
  18257. keyseparator: '.',
  18258. selectorAttr: 'data-i18n',
  18259. debug: false,
  18260. resGetPath: 'locales/__lng__/__ns__.json',
  18261. resPostPath: 'locales/add/__lng__/__ns__',
  18262. getAsync: true,
  18263. postAsync: true,
  18264. resStore: undefined,
  18265. useLocalStorage: false,
  18266. localStorageExpirationTime: 7*24*60*60*1000,
  18267. dynamicLoad: false,
  18268. sendMissing: false,
  18269. sendMissingTo: 'fallback', // current | all
  18270. sendType: 'POST',
  18271. interpolationPrefix: '__',
  18272. interpolationSuffix: '__',
  18273. defaultVariables: false,
  18274. reusePrefix: '$t(',
  18275. reuseSuffix: ')',
  18276. pluralSuffix: '_plural',
  18277. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  18278. contextNotFound: ['context_not_found', Math.random()].join(''),
  18279. escapeInterpolation: false,
  18280. indefiniteSuffix: '_indefinite',
  18281. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  18282. setJqueryExt: true,
  18283. defaultValueFromContent: true,
  18284. useDataAttrOptions: false,
  18285. cookieExpirationTime: undefined,
  18286. useCookie: true,
  18287. cookieName: 'i18next',
  18288. cookieDomain: undefined,
  18289. objectTreeKeyHandler: undefined,
  18290. postProcess: undefined,
  18291. parseMissingKey: undefined,
  18292. missingKeyHandler: sync.postMissing,
  18293. shortcutFunction: 'sprintf' // or: defaultValue
  18294. };
  18295. function _extend(target, source) {
  18296. if (!source || typeof source === 'function') {
  18297. return target;
  18298. }
  18299. for (var attr in source) { target[attr] = source[attr]; }
  18300. return target;
  18301. }
  18302. function _deepExtend(target, source) {
  18303. for (var prop in source)
  18304. if (prop in target)
  18305. _deepExtend(target[prop], source[prop]);
  18306. else
  18307. target[prop] = source[prop];
  18308. return target;
  18309. }
  18310. function _each(object, callback, args) {
  18311. var name, i = 0,
  18312. length = object.length,
  18313. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  18314. if (args) {
  18315. if (isObj) {
  18316. for (name in object) {
  18317. if (callback.apply(object[name], args) === false) {
  18318. break;
  18319. }
  18320. }
  18321. } else {
  18322. for ( ; i < length; ) {
  18323. if (callback.apply(object[i++], args) === false) {
  18324. break;
  18325. }
  18326. }
  18327. }
  18328. // A special, fast, case for the most common use of each
  18329. } else {
  18330. if (isObj) {
  18331. for (name in object) {
  18332. if (callback.call(object[name], name, object[name]) === false) {
  18333. break;
  18334. }
  18335. }
  18336. } else {
  18337. for ( ; i < length; ) {
  18338. if (callback.call(object[i], i, object[i++]) === false) {
  18339. break;
  18340. }
  18341. }
  18342. }
  18343. }
  18344. return object;
  18345. }
  18346. var _entityMap = {
  18347. "&": "&amp;",
  18348. "<": "&lt;",
  18349. ">": "&gt;",
  18350. '"': '&quot;',
  18351. "'": '&#39;',
  18352. "/": '&#x2F;'
  18353. };
  18354. function _escape(data) {
  18355. if (typeof data === 'string') {
  18356. return data.replace(/[&<>"'\/]/g, function (s) {
  18357. return _entityMap[s];
  18358. });
  18359. }else{
  18360. return data;
  18361. }
  18362. }
  18363. function _ajax(options) {
  18364. // v0.5.0 of https://github.com/goloroden/http.js
  18365. var getXhr = function (callback) {
  18366. // Use the native XHR object if the browser supports it.
  18367. if (window.XMLHttpRequest) {
  18368. return callback(null, new XMLHttpRequest());
  18369. } else if (window.ActiveXObject) {
  18370. // In Internet Explorer check for ActiveX versions of the XHR object.
  18371. try {
  18372. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  18373. } catch (e) {
  18374. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  18375. }
  18376. }
  18377. // If no XHR support was found, throw an error.
  18378. return callback(new Error());
  18379. };
  18380. var encodeUsingUrlEncoding = function (data) {
  18381. if(typeof data === 'string') {
  18382. return data;
  18383. }
  18384. var result = [];
  18385. for(var dataItem in data) {
  18386. if(data.hasOwnProperty(dataItem)) {
  18387. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  18388. }
  18389. }
  18390. return result.join('&');
  18391. };
  18392. var utf8 = function (text) {
  18393. text = text.replace(/\r\n/g, '\n');
  18394. var result = '';
  18395. for(var i = 0; i < text.length; i++) {
  18396. var c = text.charCodeAt(i);
  18397. if(c < 128) {
  18398. result += String.fromCharCode(c);
  18399. } else if((c > 127) && (c < 2048)) {
  18400. result += String.fromCharCode((c >> 6) | 192);
  18401. result += String.fromCharCode((c & 63) | 128);
  18402. } else {
  18403. result += String.fromCharCode((c >> 12) | 224);
  18404. result += String.fromCharCode(((c >> 6) & 63) | 128);
  18405. result += String.fromCharCode((c & 63) | 128);
  18406. }
  18407. }
  18408. return result;
  18409. };
  18410. var base64 = function (text) {
  18411. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  18412. text = utf8(text);
  18413. var result = '',
  18414. chr1, chr2, chr3,
  18415. enc1, enc2, enc3, enc4,
  18416. i = 0;
  18417. do {
  18418. chr1 = text.charCodeAt(i++);
  18419. chr2 = text.charCodeAt(i++);
  18420. chr3 = text.charCodeAt(i++);
  18421. enc1 = chr1 >> 2;
  18422. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  18423. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  18424. enc4 = chr3 & 63;
  18425. if(isNaN(chr2)) {
  18426. enc3 = enc4 = 64;
  18427. } else if(isNaN(chr3)) {
  18428. enc4 = 64;
  18429. }
  18430. result +=
  18431. keyStr.charAt(enc1) +
  18432. keyStr.charAt(enc2) +
  18433. keyStr.charAt(enc3) +
  18434. keyStr.charAt(enc4);
  18435. chr1 = chr2 = chr3 = '';
  18436. enc1 = enc2 = enc3 = enc4 = '';
  18437. } while(i < text.length);
  18438. return result;
  18439. };
  18440. var mergeHeaders = function () {
  18441. // Use the first header object as base.
  18442. var result = arguments[0];
  18443. // Iterate through the remaining header objects and add them.
  18444. for(var i = 1; i < arguments.length; i++) {
  18445. var currentHeaders = arguments[i];
  18446. for(var header in currentHeaders) {
  18447. if(currentHeaders.hasOwnProperty(header)) {
  18448. result[header] = currentHeaders[header];
  18449. }
  18450. }
  18451. }
  18452. // Return the merged headers.
  18453. return result;
  18454. };
  18455. var ajax = function (method, url, options, callback) {
  18456. // Adjust parameters.
  18457. if(typeof options === 'function') {
  18458. callback = options;
  18459. options = {};
  18460. }
  18461. // Set default parameter values.
  18462. options.cache = options.cache || false;
  18463. options.data = options.data || {};
  18464. options.headers = options.headers || {};
  18465. options.jsonp = options.jsonp || false;
  18466. options.async = options.async === undefined ? true : options.async;
  18467. // Merge the various header objects.
  18468. var headers = mergeHeaders({
  18469. 'accept': '*/*',
  18470. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  18471. }, ajax.headers, options.headers);
  18472. // Encode the data according to the content-type.
  18473. var payload;
  18474. if (headers['content-type'] === 'application/json') {
  18475. payload = JSON.stringify(options.data);
  18476. } else {
  18477. payload = encodeUsingUrlEncoding(options.data);
  18478. }
  18479. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  18480. // if neccessary.
  18481. if(method === 'GET') {
  18482. // Setup the query string.
  18483. var queryString = [];
  18484. if(payload) {
  18485. queryString.push(payload);
  18486. payload = null;
  18487. }
  18488. // Handle caching.
  18489. if(!options.cache) {
  18490. queryString.push('_=' + (new Date()).getTime());
  18491. }
  18492. // If neccessary prepare the query string for a JSONP call.
  18493. if(options.jsonp) {
  18494. queryString.push('callback=' + options.jsonp);
  18495. queryString.push('jsonp=' + options.jsonp);
  18496. }
  18497. // Merge the query string and attach it to the url.
  18498. queryString = queryString.join('&');
  18499. if (queryString.length > 1) {
  18500. if (url.indexOf('?') > -1) {
  18501. url += '&' + queryString;
  18502. } else {
  18503. url += '?' + queryString;
  18504. }
  18505. }
  18506. // Make a JSONP call if neccessary.
  18507. if(options.jsonp) {
  18508. var head = document.getElementsByTagName('head')[0];
  18509. var script = document.createElement('script');
  18510. script.type = 'text/javascript';
  18511. script.src = url;
  18512. head.appendChild(script);
  18513. return;
  18514. }
  18515. }
  18516. // Since we got here, it is no JSONP request, so make a normal XHR request.
  18517. getXhr(function (err, xhr) {
  18518. if(err) return callback(err);
  18519. // Open the request.
  18520. xhr.open(method, url, options.async);
  18521. // Set the request headers.
  18522. for(var header in headers) {
  18523. if(headers.hasOwnProperty(header)) {
  18524. xhr.setRequestHeader(header, headers[header]);
  18525. }
  18526. }
  18527. // Handle the request events.
  18528. xhr.onreadystatechange = function () {
  18529. if(xhr.readyState === 4) {
  18530. var data = xhr.responseText || '';
  18531. // If no callback is given, return.
  18532. if(!callback) {
  18533. return;
  18534. }
  18535. // Return an object that provides access to the data as text and JSON.
  18536. callback(xhr.status, {
  18537. text: function () {
  18538. return data;
  18539. },
  18540. json: function () {
  18541. try {
  18542. return JSON.parse(data)
  18543. } catch (e) {
  18544. f.error('Can not parse JSON. URL: ' + url);
  18545. return {};
  18546. }
  18547. }
  18548. });
  18549. }
  18550. };
  18551. // Actually send the XHR request.
  18552. xhr.send(payload);
  18553. });
  18554. };
  18555. // Define the external interface.
  18556. var http = {
  18557. authBasic: function (username, password) {
  18558. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  18559. },
  18560. connect: function (url, options, callback) {
  18561. return ajax('CONNECT', url, options, callback);
  18562. },
  18563. del: function (url, options, callback) {
  18564. return ajax('DELETE', url, options, callback);
  18565. },
  18566. get: function (url, options, callback) {
  18567. return ajax('GET', url, options, callback);
  18568. },
  18569. head: function (url, options, callback) {
  18570. return ajax('HEAD', url, options, callback);
  18571. },
  18572. headers: function (headers) {
  18573. ajax.headers = headers || {};
  18574. },
  18575. isAllowed: function (url, verb, callback) {
  18576. this.options(url, function (status, data) {
  18577. callback(data.text().indexOf(verb) !== -1);
  18578. });
  18579. },
  18580. options: function (url, options, callback) {
  18581. return ajax('OPTIONS', url, options, callback);
  18582. },
  18583. patch: function (url, options, callback) {
  18584. return ajax('PATCH', url, options, callback);
  18585. },
  18586. post: function (url, options, callback) {
  18587. return ajax('POST', url, options, callback);
  18588. },
  18589. put: function (url, options, callback) {
  18590. return ajax('PUT', url, options, callback);
  18591. },
  18592. trace: function (url, options, callback) {
  18593. return ajax('TRACE', url, options, callback);
  18594. }
  18595. };
  18596. var methode = options.type ? options.type.toLowerCase() : 'get';
  18597. http[methode](options.url, options, function (status, data) {
  18598. // file: protocol always gives status code 0, so check for data
  18599. if (status === 200 || (status === 0 && data.text())) {
  18600. options.success(data.json(), status, null);
  18601. } else {
  18602. options.error(data.text(), status, null);
  18603. }
  18604. });
  18605. }
  18606. var _cookie = {
  18607. create: function(name,value,minutes,domain) {
  18608. var expires;
  18609. if (minutes) {
  18610. var date = new Date();
  18611. date.setTime(date.getTime()+(minutes*60*1000));
  18612. expires = "; expires="+date.toGMTString();
  18613. }
  18614. else expires = "";
  18615. domain = (domain)? "domain="+domain+";" : "";
  18616. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  18617. },
  18618. read: function(name) {
  18619. var nameEQ = name + "=";
  18620. var ca = document.cookie.split(';');
  18621. for(var i=0;i < ca.length;i++) {
  18622. var c = ca[i];
  18623. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  18624. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  18625. }
  18626. return null;
  18627. },
  18628. remove: function(name) {
  18629. this.create(name,"",-1);
  18630. }
  18631. };
  18632. var cookie_noop = {
  18633. create: function(name,value,minutes,domain) {},
  18634. read: function(name) { return null; },
  18635. remove: function(name) {}
  18636. };
  18637. // move dependent functions to a container so that
  18638. // they can be overriden easier in no jquery environment (node.js)
  18639. var f = {
  18640. extend: $ ? $.extend : _extend,
  18641. deepExtend: _deepExtend,
  18642. each: $ ? $.each : _each,
  18643. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  18644. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  18645. detectLanguage: detectLanguage,
  18646. escape: _escape,
  18647. log: function(str) {
  18648. if (o.debug && typeof console !== "undefined") console.log(str);
  18649. },
  18650. error: function(str) {
  18651. if (typeof console !== "undefined") console.error(str);
  18652. },
  18653. getCountyIndexOfLng: function(lng) {
  18654. var lng_index = 0;
  18655. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  18656. return lng_index;
  18657. },
  18658. toLanguages: function(lng) {
  18659. var log = this.log;
  18660. function applyCase(l) {
  18661. var ret = l;
  18662. if (typeof l === 'string' && l.indexOf('-') > -1) {
  18663. var parts = l.split('-');
  18664. ret = o.lowerCaseLng ?
  18665. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18666. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18667. } else {
  18668. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  18669. }
  18670. return ret;
  18671. }
  18672. var languages = [];
  18673. var whitelist = o.lngWhitelist || false;
  18674. var addLanguage = function(language){
  18675. //reject langs not whitelisted
  18676. if(!whitelist || whitelist.indexOf(language) > -1){
  18677. languages.push(language);
  18678. }else{
  18679. log('rejecting non-whitelisted language: ' + language);
  18680. }
  18681. };
  18682. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  18683. var parts = lng.split('-');
  18684. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  18685. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  18686. } else {
  18687. addLanguage(applyCase(lng));
  18688. }
  18689. for (var i = 0; i < o.fallbackLng.length; i++) {
  18690. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  18691. }
  18692. return languages;
  18693. },
  18694. regexEscape: function(str) {
  18695. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  18696. },
  18697. regexReplacementEscape: function(strOrFn) {
  18698. if (typeof strOrFn === 'string') {
  18699. return strOrFn.replace(/\$/g, "$$$$");
  18700. } else {
  18701. return strOrFn;
  18702. }
  18703. },
  18704. localStorage: {
  18705. setItem: function(key, value) {
  18706. if (window.localStorage) {
  18707. try {
  18708. window.localStorage.setItem(key, value);
  18709. } catch (e) {
  18710. f.log('failed to set value for key "' + key + '" to localStorage.');
  18711. }
  18712. }
  18713. }
  18714. }
  18715. };
  18716. function init(options, cb) {
  18717. if (typeof options === 'function') {
  18718. cb = options;
  18719. options = {};
  18720. }
  18721. options = options || {};
  18722. // override defaults with passed in options
  18723. f.extend(o, options);
  18724. delete o.fixLng; /* passed in each time */
  18725. // override functions: .log(), .detectLanguage(), etc
  18726. if (o.functions) {
  18727. delete o.functions;
  18728. f.extend(f, options.functions);
  18729. }
  18730. // create namespace object if namespace is passed in as string
  18731. if (typeof o.ns == 'string') {
  18732. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  18733. }
  18734. // fallback namespaces
  18735. if (typeof o.fallbackNS == 'string') {
  18736. o.fallbackNS = [o.fallbackNS];
  18737. }
  18738. // fallback languages
  18739. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  18740. o.fallbackLng = [o.fallbackLng];
  18741. }
  18742. // escape prefix/suffix
  18743. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  18744. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  18745. if (!o.lng) o.lng = f.detectLanguage();
  18746. languages = f.toLanguages(o.lng);
  18747. currentLng = languages[0];
  18748. f.log('currentLng set to: ' + currentLng);
  18749. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  18750. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  18751. }
  18752. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  18753. f.localStorage.setItem('i18next_lng', currentLng);
  18754. }
  18755. var lngTranslate = translate;
  18756. if (options.fixLng) {
  18757. lngTranslate = function(key, options) {
  18758. options = options || {};
  18759. options.lng = options.lng || lngTranslate.lng;
  18760. return translate(key, options);
  18761. };
  18762. lngTranslate.lng = currentLng;
  18763. }
  18764. pluralExtensions.setCurrentLng(currentLng);
  18765. // add JQuery extensions
  18766. if ($ && o.setJqueryExt) addJqueryFunct();
  18767. // jQuery deferred
  18768. var deferred;
  18769. if ($ && $.Deferred) {
  18770. deferred = $.Deferred();
  18771. }
  18772. // return immidiatly if res are passed in
  18773. if (o.resStore) {
  18774. resStore = o.resStore;
  18775. initialized = true;
  18776. if (cb) cb(lngTranslate);
  18777. if (deferred) deferred.resolve(lngTranslate);
  18778. if (deferred) return deferred.promise();
  18779. return;
  18780. }
  18781. // languages to load
  18782. var lngsToLoad = f.toLanguages(o.lng);
  18783. if (typeof o.preload === 'string') o.preload = [o.preload];
  18784. for (var i = 0, l = o.preload.length; i < l; i++) {
  18785. var pres = f.toLanguages(o.preload[i]);
  18786. for (var y = 0, len = pres.length; y < len; y++) {
  18787. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18788. lngsToLoad.push(pres[y]);
  18789. }
  18790. }
  18791. }
  18792. // else load them
  18793. i18n.sync.load(lngsToLoad, o, function(err, store) {
  18794. resStore = store;
  18795. initialized = true;
  18796. if (cb) cb(lngTranslate);
  18797. if (deferred) deferred.resolve(lngTranslate);
  18798. });
  18799. if (deferred) return deferred.promise();
  18800. }
  18801. function preload(lngs, cb) {
  18802. if (typeof lngs === 'string') lngs = [lngs];
  18803. for (var i = 0, l = lngs.length; i < l; i++) {
  18804. if (o.preload.indexOf(lngs[i]) < 0) {
  18805. o.preload.push(lngs[i]);
  18806. }
  18807. }
  18808. return init(cb);
  18809. }
  18810. function addResourceBundle(lng, ns, resources, deep) {
  18811. if (typeof ns !== 'string') {
  18812. resources = ns;
  18813. ns = o.ns.defaultNs;
  18814. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18815. o.ns.namespaces.push(ns);
  18816. }
  18817. resStore[lng] = resStore[lng] || {};
  18818. resStore[lng][ns] = resStore[lng][ns] || {};
  18819. if (deep) {
  18820. f.deepExtend(resStore[lng][ns], resources);
  18821. } else {
  18822. f.extend(resStore[lng][ns], resources);
  18823. }
  18824. }
  18825. function hasResourceBundle(lng, ns) {
  18826. if (typeof ns !== 'string') {
  18827. ns = o.ns.defaultNs;
  18828. }
  18829. resStore[lng] = resStore[lng] || {};
  18830. var res = resStore[lng][ns] || {};
  18831. var hasValues = false;
  18832. for(var prop in res) {
  18833. if (res.hasOwnProperty(prop)) {
  18834. hasValues = true;
  18835. }
  18836. }
  18837. return hasValues;
  18838. }
  18839. function removeResourceBundle(lng, ns) {
  18840. if (typeof ns !== 'string') {
  18841. ns = o.ns.defaultNs;
  18842. }
  18843. resStore[lng] = resStore[lng] || {};
  18844. resStore[lng][ns] = {};
  18845. }
  18846. function addResource(lng, ns, key, value) {
  18847. if (typeof ns !== 'string') {
  18848. resource = ns;
  18849. ns = o.ns.defaultNs;
  18850. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18851. o.ns.namespaces.push(ns);
  18852. }
  18853. resStore[lng] = resStore[lng] || {};
  18854. resStore[lng][ns] = resStore[lng][ns] || {};
  18855. var keys = key.split(o.keyseparator);
  18856. var x = 0;
  18857. var node = resStore[lng][ns];
  18858. var origRef = node;
  18859. while (keys[x]) {
  18860. if (x == keys.length - 1)
  18861. node[keys[x]] = value;
  18862. else {
  18863. if (node[keys[x]] == null)
  18864. node[keys[x]] = {};
  18865. node = node[keys[x]];
  18866. }
  18867. x++;
  18868. }
  18869. }
  18870. function addResources(lng, ns, resources) {
  18871. if (typeof ns !== 'string') {
  18872. resource = ns;
  18873. ns = o.ns.defaultNs;
  18874. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18875. o.ns.namespaces.push(ns);
  18876. }
  18877. for (var m in resources) {
  18878. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  18879. }
  18880. }
  18881. function setDefaultNamespace(ns) {
  18882. o.ns.defaultNs = ns;
  18883. }
  18884. function loadNamespace(namespace, cb) {
  18885. loadNamespaces([namespace], cb);
  18886. }
  18887. function loadNamespaces(namespaces, cb) {
  18888. var opts = {
  18889. dynamicLoad: o.dynamicLoad,
  18890. resGetPath: o.resGetPath,
  18891. getAsync: o.getAsync,
  18892. customLoad: o.customLoad,
  18893. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  18894. };
  18895. // languages to load
  18896. var lngsToLoad = f.toLanguages(o.lng);
  18897. if (typeof o.preload === 'string') o.preload = [o.preload];
  18898. for (var i = 0, l = o.preload.length; i < l; i++) {
  18899. var pres = f.toLanguages(o.preload[i]);
  18900. for (var y = 0, len = pres.length; y < len; y++) {
  18901. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18902. lngsToLoad.push(pres[y]);
  18903. }
  18904. }
  18905. }
  18906. // check if we have to load
  18907. var lngNeedLoad = [];
  18908. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  18909. var needLoad = false;
  18910. var resSet = resStore[lngsToLoad[a]];
  18911. if (resSet) {
  18912. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  18913. if (!resSet[namespaces[b]]) needLoad = true;
  18914. }
  18915. } else {
  18916. needLoad = true;
  18917. }
  18918. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  18919. }
  18920. if (lngNeedLoad.length) {
  18921. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  18922. var todo = namespaces.length * lngNeedLoad.length;
  18923. // load each file individual
  18924. f.each(namespaces, function(nsIndex, nsValue) {
  18925. // append namespace to namespace array
  18926. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  18927. o.ns.namespaces.push(nsValue);
  18928. }
  18929. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  18930. resStore[lngValue] = resStore[lngValue] || {};
  18931. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  18932. todo--; // wait for all done befor callback
  18933. if (todo === 0 && cb) {
  18934. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  18935. cb();
  18936. }
  18937. });
  18938. });
  18939. });
  18940. } else {
  18941. if (cb) cb();
  18942. }
  18943. }
  18944. function setLng(lng, options, cb) {
  18945. if (typeof options === 'function') {
  18946. cb = options;
  18947. options = {};
  18948. } else if (!options) {
  18949. options = {};
  18950. }
  18951. options.lng = lng;
  18952. return init(options, cb);
  18953. }
  18954. function lng() {
  18955. return currentLng;
  18956. }
  18957. function reload(cb) {
  18958. resStore = {};
  18959. setLng(currentLng, cb);
  18960. }
  18961. function addJqueryFunct() {
  18962. // $.t shortcut
  18963. $.t = $.t || translate;
  18964. function parse(ele, key, options) {
  18965. if (key.length === 0) return;
  18966. var attr = 'text';
  18967. if (key.indexOf('[') === 0) {
  18968. var parts = key.split(']');
  18969. key = parts[1];
  18970. attr = parts[0].substr(1, parts[0].length-1);
  18971. }
  18972. if (key.indexOf(';') === key.length-1) {
  18973. key = key.substr(0, key.length-2);
  18974. }
  18975. var optionsToUse;
  18976. if (attr === 'html') {
  18977. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18978. ele.html($.t(key, optionsToUse));
  18979. } else if (attr === 'text') {
  18980. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  18981. ele.text($.t(key, optionsToUse));
  18982. } else if (attr === 'prepend') {
  18983. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18984. ele.prepend($.t(key, optionsToUse));
  18985. } else if (attr === 'append') {
  18986. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18987. ele.append($.t(key, optionsToUse));
  18988. } else if (attr.indexOf("data-") === 0) {
  18989. var dataAttr = attr.substr(("data-").length);
  18990. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  18991. var translated = $.t(key, optionsToUse);
  18992. //we change into the data cache
  18993. ele.data(dataAttr, translated);
  18994. //we change into the dom
  18995. ele.attr(attr, translated);
  18996. } else {
  18997. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  18998. ele.attr(attr, $.t(key, optionsToUse));
  18999. }
  19000. }
  19001. function localize(ele, options) {
  19002. var key = ele.attr(o.selectorAttr);
  19003. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  19004. if (!key) return;
  19005. var target = ele
  19006. , targetSelector = ele.data("i18n-target");
  19007. if (targetSelector) {
  19008. target = ele.find(targetSelector) || ele;
  19009. }
  19010. if (!options && o.useDataAttrOptions === true) {
  19011. options = ele.data("i18n-options");
  19012. }
  19013. options = options || {};
  19014. if (key.indexOf(';') >= 0) {
  19015. var keys = key.split(';');
  19016. $.each(keys, function(m, k) {
  19017. if (k !== '') parse(target, k, options);
  19018. });
  19019. } else {
  19020. parse(target, key, options);
  19021. }
  19022. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  19023. }
  19024. // fn
  19025. $.fn.i18n = function (options) {
  19026. return this.each(function() {
  19027. // localize element itself
  19028. localize($(this), options);
  19029. // localize childs
  19030. var elements = $(this).find('[' + o.selectorAttr + ']');
  19031. elements.each(function() {
  19032. localize($(this), options);
  19033. });
  19034. });
  19035. };
  19036. }
  19037. function applyReplacement(str, replacementHash, nestedKey, options) {
  19038. if (!str) return str;
  19039. options = options || replacementHash; // first call uses replacement hash combined with options
  19040. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  19041. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  19042. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  19043. , unEscapingSuffix = 'HTML'+suffix;
  19044. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  19045. f.each(hash, function(key, value) {
  19046. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  19047. if (typeof value === 'object' && value !== null) {
  19048. str = applyReplacement(str, value, nextKey, options);
  19049. } else {
  19050. if (options.escapeInterpolation || o.escapeInterpolation) {
  19051. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  19052. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  19053. } else {
  19054. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  19055. }
  19056. // str = options.escapeInterpolation;
  19057. }
  19058. });
  19059. return str;
  19060. }
  19061. // append it to functions
  19062. f.applyReplacement = applyReplacement;
  19063. function applyReuse(translated, options) {
  19064. var comma = ',';
  19065. var options_open = '{';
  19066. var options_close = '}';
  19067. var opts = f.extend({}, options);
  19068. delete opts.postProcess;
  19069. while (translated.indexOf(o.reusePrefix) != -1) {
  19070. replacementCounter++;
  19071. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  19072. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  19073. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  19074. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  19075. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  19076. if (index_of_end_of_closing <= index_of_opening) {
  19077. f.error('there is an missing closing in following translation value', translated);
  19078. return '';
  19079. }
  19080. if (token_without_symbols.indexOf(comma) != -1) {
  19081. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  19082. 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) {
  19083. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  19084. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  19085. try {
  19086. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  19087. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  19088. } catch (e) {
  19089. }
  19090. }
  19091. }
  19092. var translated_token = _translate(token_without_symbols, opts);
  19093. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  19094. }
  19095. return translated;
  19096. }
  19097. function hasContext(options) {
  19098. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  19099. }
  19100. function needsPlural(options, lng) {
  19101. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  19102. }
  19103. function needsIndefiniteArticle(options) {
  19104. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  19105. }
  19106. function exists(key, options) {
  19107. options = options || {};
  19108. var notFound = _getDefaultValue(key, options)
  19109. , found = _find(key, options);
  19110. return found !== undefined || found === notFound;
  19111. }
  19112. function translate(key, options) {
  19113. options = options || {};
  19114. if (!initialized) {
  19115. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  19116. return options.defaultValue || '';
  19117. };
  19118. replacementCounter = 0;
  19119. return _translate.apply(null, arguments);
  19120. }
  19121. function _getDefaultValue(key, options) {
  19122. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  19123. }
  19124. function _injectSprintfProcessor() {
  19125. var values = [];
  19126. // mh: build array from second argument onwards
  19127. for (var i = 1; i < arguments.length; i++) {
  19128. values.push(arguments[i]);
  19129. }
  19130. return {
  19131. postProcess: 'sprintf',
  19132. sprintf: values
  19133. };
  19134. }
  19135. function _translate(potentialKeys, options) {
  19136. if (options && typeof options !== 'object') {
  19137. if (o.shortcutFunction === 'sprintf') {
  19138. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  19139. options = _injectSprintfProcessor.apply(null, arguments);
  19140. } else if (o.shortcutFunction === 'defaultValue') {
  19141. options = {
  19142. defaultValue: options
  19143. }
  19144. }
  19145. } else {
  19146. options = options || {};
  19147. }
  19148. if (typeof o.defaultVariables === 'object') {
  19149. options = f.extend({}, o.defaultVariables, options);
  19150. }
  19151. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  19152. if (typeof potentialKeys === 'string') {
  19153. potentialKeys = [potentialKeys];
  19154. }
  19155. var key = potentialKeys[0];
  19156. if (potentialKeys.length > 1) {
  19157. for (var i = 0; i < potentialKeys.length; i++) {
  19158. key = potentialKeys[i];
  19159. if (exists(key, options)) {
  19160. break;
  19161. }
  19162. }
  19163. }
  19164. var notFound = _getDefaultValue(key, options)
  19165. , found = _find(key, options)
  19166. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  19167. , ns = options.ns || o.ns.defaultNs
  19168. , parts;
  19169. // split ns and key
  19170. if (key.indexOf(o.nsseparator) > -1) {
  19171. parts = key.split(o.nsseparator);
  19172. ns = parts[0];
  19173. key = parts[1];
  19174. }
  19175. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  19176. if (options.lng) {
  19177. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  19178. } else {
  19179. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  19180. }
  19181. }
  19182. var postProcessor = options.postProcess || o.postProcess;
  19183. if (found !== undefined && postProcessor) {
  19184. if (postProcessors[postProcessor]) {
  19185. found = postProcessors[postProcessor](found, key, options);
  19186. }
  19187. }
  19188. // process notFound if function exists
  19189. var splitNotFound = notFound;
  19190. if (notFound.indexOf(o.nsseparator) > -1) {
  19191. parts = notFound.split(o.nsseparator);
  19192. splitNotFound = parts[1];
  19193. }
  19194. if (splitNotFound === key && o.parseMissingKey) {
  19195. notFound = o.parseMissingKey(notFound);
  19196. }
  19197. if (found === undefined) {
  19198. notFound = applyReplacement(notFound, options);
  19199. notFound = applyReuse(notFound, options);
  19200. if (postProcessor && postProcessors[postProcessor]) {
  19201. var val = _getDefaultValue(key, options);
  19202. found = postProcessors[postProcessor](val, key, options);
  19203. }
  19204. }
  19205. return (found !== undefined) ? found : notFound;
  19206. }
  19207. function _find(key, options) {
  19208. options = options || {};
  19209. var optionWithoutCount, translated
  19210. , notFound = _getDefaultValue(key, options)
  19211. , lngs = languages;
  19212. if (!resStore) { return notFound; } // no resStore to translate from
  19213. // CI mode
  19214. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  19215. // passed in lng
  19216. if (options.lngs) lngs = options.lngs;
  19217. if (options.lng) {
  19218. lngs = f.toLanguages(options.lng, options.fallbackLng);
  19219. if (!resStore[lngs[0]]) {
  19220. var oldAsync = o.getAsync;
  19221. o.getAsync = false;
  19222. i18n.sync.load(lngs, o, function(err, store) {
  19223. f.extend(resStore, store);
  19224. o.getAsync = oldAsync;
  19225. });
  19226. }
  19227. }
  19228. var ns = options.ns || o.ns.defaultNs;
  19229. if (key.indexOf(o.nsseparator) > -1) {
  19230. var parts = key.split(o.nsseparator);
  19231. ns = parts[0];
  19232. key = parts[1];
  19233. }
  19234. if (hasContext(options)) {
  19235. optionWithoutCount = f.extend({}, options);
  19236. delete optionWithoutCount.context;
  19237. optionWithoutCount.defaultValue = o.contextNotFound;
  19238. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  19239. translated = translate(contextKey, optionWithoutCount);
  19240. if (translated != o.contextNotFound) {
  19241. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  19242. } // else continue translation with original/nonContext key
  19243. }
  19244. if (needsPlural(options, lngs[0])) {
  19245. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  19246. delete optionWithoutCount.count;
  19247. delete optionWithoutCount.lng;
  19248. optionWithoutCount.defaultValue = o.pluralNotFound;
  19249. var pluralKey;
  19250. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  19251. pluralKey = ns + o.nsseparator + key;
  19252. } else {
  19253. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  19254. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  19255. if (pluralExtension >= 0) {
  19256. pluralKey = pluralKey + '_' + pluralExtension;
  19257. } else if (pluralExtension === 1) {
  19258. pluralKey = ns + o.nsseparator + key; // singular
  19259. }
  19260. }
  19261. translated = translate(pluralKey, optionWithoutCount);
  19262. if (translated != o.pluralNotFound) {
  19263. return applyReplacement(translated, {
  19264. count: options.count,
  19265. interpolationPrefix: options.interpolationPrefix,
  19266. interpolationSuffix: options.interpolationSuffix
  19267. }); // apply replacement for count only
  19268. } else if (lngs.length > 1) {
  19269. // remove failed lng
  19270. var clone = lngs.slice();
  19271. clone.shift();
  19272. options = f.extend(options, { lngs: clone });
  19273. delete options.lng;
  19274. // retry with fallbacks
  19275. translated = translate(ns + o.nsseparator + key, options);
  19276. if (translated != o.pluralNotFound) return translated;
  19277. } else {
  19278. return translated;
  19279. }
  19280. }
  19281. if (needsIndefiniteArticle(options)) {
  19282. var optionsWithoutIndef = f.extend({}, options);
  19283. delete optionsWithoutIndef.indefinite_article;
  19284. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  19285. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  19286. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  19287. translated = translate(indefiniteKey, optionsWithoutIndef);
  19288. if (translated != o.indefiniteNotFound) {
  19289. return translated;
  19290. }
  19291. }
  19292. var found;
  19293. var keys = key.split(o.keyseparator);
  19294. for (var i = 0, len = lngs.length; i < len; i++ ) {
  19295. if (found !== undefined) break;
  19296. var l = lngs[i];
  19297. var x = 0;
  19298. var value = resStore[l] && resStore[l][ns];
  19299. while (keys[x]) {
  19300. value = value && value[keys[x]];
  19301. x++;
  19302. }
  19303. if (value !== undefined) {
  19304. var valueType = Object.prototype.toString.apply(value);
  19305. if (typeof value === 'string') {
  19306. value = applyReplacement(value, options);
  19307. value = applyReuse(value, options);
  19308. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  19309. value = value.join('\n');
  19310. value = applyReplacement(value, options);
  19311. value = applyReuse(value, options);
  19312. } else if (value === null && o.fallbackOnNull === true) {
  19313. value = undefined;
  19314. } else if (value !== null) {
  19315. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  19316. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  19317. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  19318. } else {
  19319. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  19320. 'returned an object instead of string.';
  19321. f.log(value);
  19322. }
  19323. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  19324. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  19325. f.each(value, function(m) {
  19326. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  19327. });
  19328. value = copy;
  19329. }
  19330. }
  19331. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  19332. value = undefined;
  19333. found = value;
  19334. }
  19335. }
  19336. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  19337. // set flag for fallback lookup - avoid recursion
  19338. options.isFallbackLookup = true;
  19339. if (o.fallbackNS.length) {
  19340. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  19341. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  19342. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  19343. /* compare value without namespace */
  19344. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  19345. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  19346. if (foundValue !== notFoundValue) break;
  19347. }
  19348. }
  19349. } else {
  19350. found = _find(key, options); // fallback to default NS
  19351. }
  19352. options.isFallbackLookup = false;
  19353. }
  19354. return found;
  19355. }
  19356. function detectLanguage() {
  19357. var detectedLng;
  19358. var whitelist = o.lngWhitelist || [];
  19359. var userLngChoices = [];
  19360. // get from qs
  19361. var qsParm = [];
  19362. if (typeof window !== 'undefined') {
  19363. (function() {
  19364. var query = window.location.search.substring(1);
  19365. var params = query.split('&');
  19366. for (var i=0; i<params.length; i++) {
  19367. var pos = params[i].indexOf('=');
  19368. if (pos > 0) {
  19369. var key = params[i].substring(0,pos);
  19370. if (key == o.detectLngQS) {
  19371. userLngChoices.push(params[i].substring(pos+1));
  19372. }
  19373. }
  19374. }
  19375. })();
  19376. }
  19377. // get from cookie
  19378. if (o.useCookie && typeof document !== 'undefined') {
  19379. var c = f.cookie.read(o.cookieName);
  19380. if (c) userLngChoices.push(c);
  19381. }
  19382. // get from localStorage
  19383. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  19384. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  19385. }
  19386. // get from navigator
  19387. if (typeof navigator !== 'undefined') {
  19388. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  19389. for (var i=0;i<navigator.languages.length;i++) {
  19390. userLngChoices.push(navigator.languages[i]);
  19391. }
  19392. }
  19393. if (navigator.userLanguage) {
  19394. userLngChoices.push(navigator.userLanguage);
  19395. }
  19396. if (navigator.language) {
  19397. userLngChoices.push(navigator.language);
  19398. }
  19399. }
  19400. (function() {
  19401. for (var i=0;i<userLngChoices.length;i++) {
  19402. var lng = userLngChoices[i];
  19403. if (lng.indexOf('-') > -1) {
  19404. var parts = lng.split('-');
  19405. lng = o.lowerCaseLng ?
  19406. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  19407. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  19408. }
  19409. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  19410. detectedLng = lng;
  19411. break;
  19412. }
  19413. }
  19414. })();
  19415. //fallback
  19416. if (!detectedLng){
  19417. detectedLng = o.fallbackLng[0];
  19418. }
  19419. return detectedLng;
  19420. }
  19421. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  19422. /* [code, name, numbers, pluralsType] */
  19423. var _rules = [
  19424. ["ach", "Acholi", [1,2], 1],
  19425. ["af", "Afrikaans",[1,2], 2],
  19426. ["ak", "Akan", [1,2], 1],
  19427. ["am", "Amharic", [1,2], 1],
  19428. ["an", "Aragonese",[1,2], 2],
  19429. ["ar", "Arabic", [0,1,2,3,11,100],5],
  19430. ["arn", "Mapudungun",[1,2], 1],
  19431. ["ast", "Asturian", [1,2], 2],
  19432. ["ay", "Aymará", [1], 3],
  19433. ["az", "Azerbaijani",[1,2],2],
  19434. ["be", "Belarusian",[1,2,5],4],
  19435. ["bg", "Bulgarian",[1,2], 2],
  19436. ["bn", "Bengali", [1,2], 2],
  19437. ["bo", "Tibetan", [1], 3],
  19438. ["br", "Breton", [1,2], 1],
  19439. ["bs", "Bosnian", [1,2,5],4],
  19440. ["ca", "Catalan", [1,2], 2],
  19441. ["cgg", "Chiga", [1], 3],
  19442. ["cs", "Czech", [1,2,5],6],
  19443. ["csb", "Kashubian",[1,2,5],7],
  19444. ["cy", "Welsh", [1,2,3,8],8],
  19445. ["da", "Danish", [1,2], 2],
  19446. ["de", "German", [1,2], 2],
  19447. ["dev", "Development Fallback", [1,2], 2],
  19448. ["dz", "Dzongkha", [1], 3],
  19449. ["el", "Greek", [1,2], 2],
  19450. ["en", "English", [1,2], 2],
  19451. ["eo", "Esperanto",[1,2], 2],
  19452. ["es", "Spanish", [1,2], 2],
  19453. ["es_ar","Argentinean Spanish", [1,2], 2],
  19454. ["et", "Estonian", [1,2], 2],
  19455. ["eu", "Basque", [1,2], 2],
  19456. ["fa", "Persian", [1], 3],
  19457. ["fi", "Finnish", [1,2], 2],
  19458. ["fil", "Filipino", [1,2], 1],
  19459. ["fo", "Faroese", [1,2], 2],
  19460. ["fr", "French", [1,2], 9],
  19461. ["fur", "Friulian", [1,2], 2],
  19462. ["fy", "Frisian", [1,2], 2],
  19463. ["ga", "Irish", [1,2,3,7,11],10],
  19464. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  19465. ["gl", "Galician", [1,2], 2],
  19466. ["gu", "Gujarati", [1,2], 2],
  19467. ["gun", "Gun", [1,2], 1],
  19468. ["ha", "Hausa", [1,2], 2],
  19469. ["he", "Hebrew", [1,2], 2],
  19470. ["hi", "Hindi", [1,2], 2],
  19471. ["hr", "Croatian", [1,2,5],4],
  19472. ["hu", "Hungarian",[1,2], 2],
  19473. ["hy", "Armenian", [1,2], 2],
  19474. ["ia", "Interlingua",[1,2],2],
  19475. ["id", "Indonesian",[1], 3],
  19476. ["is", "Icelandic",[1,2], 12],
  19477. ["it", "Italian", [1,2], 2],
  19478. ["ja", "Japanese", [1], 3],
  19479. ["jbo", "Lojban", [1], 3],
  19480. ["jv", "Javanese", [0,1], 13],
  19481. ["ka", "Georgian", [1], 3],
  19482. ["kk", "Kazakh", [1], 3],
  19483. ["km", "Khmer", [1], 3],
  19484. ["kn", "Kannada", [1,2], 2],
  19485. ["ko", "Korean", [1], 3],
  19486. ["ku", "Kurdish", [1,2], 2],
  19487. ["kw", "Cornish", [1,2,3,4],14],
  19488. ["ky", "Kyrgyz", [1], 3],
  19489. ["lb", "Letzeburgesch",[1,2],2],
  19490. ["ln", "Lingala", [1,2], 1],
  19491. ["lo", "Lao", [1], 3],
  19492. ["lt", "Lithuanian",[1,2,10],15],
  19493. ["lv", "Latvian", [1,2,0],16],
  19494. ["mai", "Maithili", [1,2], 2],
  19495. ["mfe", "Mauritian Creole",[1,2],1],
  19496. ["mg", "Malagasy", [1,2], 1],
  19497. ["mi", "Maori", [1,2], 1],
  19498. ["mk", "Macedonian",[1,2],17],
  19499. ["ml", "Malayalam",[1,2], 2],
  19500. ["mn", "Mongolian",[1,2], 2],
  19501. ["mnk", "Mandinka", [0,1,2],18],
  19502. ["mr", "Marathi", [1,2], 2],
  19503. ["ms", "Malay", [1], 3],
  19504. ["mt", "Maltese", [1,2,11,20],19],
  19505. ["nah", "Nahuatl", [1,2], 2],
  19506. ["nap", "Neapolitan",[1,2], 2],
  19507. ["nb", "Norwegian Bokmal",[1,2],2],
  19508. ["ne", "Nepali", [1,2], 2],
  19509. ["nl", "Dutch", [1,2], 2],
  19510. ["nn", "Norwegian Nynorsk",[1,2],2],
  19511. ["no", "Norwegian",[1,2], 2],
  19512. ["nso", "Northern Sotho",[1,2],2],
  19513. ["oc", "Occitan", [1,2], 1],
  19514. ["or", "Oriya", [2,1], 2],
  19515. ["pa", "Punjabi", [1,2], 2],
  19516. ["pap", "Papiamento",[1,2], 2],
  19517. ["pl", "Polish", [1,2,5],7],
  19518. ["pms", "Piemontese",[1,2], 2],
  19519. ["ps", "Pashto", [1,2], 2],
  19520. ["pt", "Portuguese",[1,2], 2],
  19521. ["pt_br","Brazilian Portuguese",[1,2], 2],
  19522. ["rm", "Romansh", [1,2], 2],
  19523. ["ro", "Romanian", [1,2,20],20],
  19524. ["ru", "Russian", [1,2,5],4],
  19525. ["sah", "Yakut", [1], 3],
  19526. ["sco", "Scots", [1,2], 2],
  19527. ["se", "Northern Sami",[1,2], 2],
  19528. ["si", "Sinhala", [1,2], 2],
  19529. ["sk", "Slovak", [1,2,5],6],
  19530. ["sl", "Slovenian",[5,1,2,3],21],
  19531. ["so", "Somali", [1,2], 2],
  19532. ["son", "Songhay", [1,2], 2],
  19533. ["sq", "Albanian", [1,2], 2],
  19534. ["sr", "Serbian", [1,2,5],4],
  19535. ["su", "Sundanese",[1], 3],
  19536. ["sv", "Swedish", [1,2], 2],
  19537. ["sw", "Swahili", [1,2], 2],
  19538. ["ta", "Tamil", [1,2], 2],
  19539. ["te", "Telugu", [1,2], 2],
  19540. ["tg", "Tajik", [1,2], 1],
  19541. ["th", "Thai", [1], 3],
  19542. ["ti", "Tigrinya", [1,2], 1],
  19543. ["tk", "Turkmen", [1,2], 2],
  19544. ["tr", "Turkish", [1,2], 1],
  19545. ["tt", "Tatar", [1], 3],
  19546. ["ug", "Uyghur", [1], 3],
  19547. ["uk", "Ukrainian",[1,2,5],4],
  19548. ["ur", "Urdu", [1,2], 2],
  19549. ["uz", "Uzbek", [1,2], 1],
  19550. ["vi", "Vietnamese",[1], 3],
  19551. ["wa", "Walloon", [1,2], 1],
  19552. ["wo", "Wolof", [1], 3],
  19553. ["yo", "Yoruba", [1,2], 2],
  19554. ["zh", "Chinese", [1], 3]
  19555. ];
  19556. var _rulesPluralsTypes = {
  19557. 1: function(n) {return Number(n > 1);},
  19558. 2: function(n) {return Number(n != 1);},
  19559. 3: function(n) {return 0;},
  19560. 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);},
  19561. 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);},
  19562. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  19563. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19564. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  19565. 9: function(n) {return Number(n >= 2);},
  19566. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  19567. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  19568. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  19569. 13: function(n) {return Number(n !== 0);},
  19570. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  19571. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19572. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  19573. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  19574. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  19575. 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);},
  19576. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  19577. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  19578. };
  19579. var pluralExtensions = {
  19580. rules: (function () {
  19581. var l, rules = {};
  19582. for (l=_rules.length; l-- ;) {
  19583. rules[_rules[l][0]] = {
  19584. name: _rules[l][1],
  19585. numbers: _rules[l][2],
  19586. plurals: _rulesPluralsTypes[_rules[l][3]]
  19587. }
  19588. }
  19589. return rules;
  19590. }()),
  19591. // you can add your own pluralExtensions
  19592. addRule: function(lng, obj) {
  19593. pluralExtensions.rules[lng] = obj;
  19594. },
  19595. setCurrentLng: function(lng) {
  19596. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  19597. var parts = lng.split('-');
  19598. pluralExtensions.currentRule = {
  19599. lng: lng,
  19600. rule: pluralExtensions.rules[parts[0]]
  19601. };
  19602. }
  19603. },
  19604. needsPlural: function(lng, count) {
  19605. var parts = lng.split('-');
  19606. var ext;
  19607. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19608. ext = pluralExtensions.currentRule.rule;
  19609. } else {
  19610. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  19611. }
  19612. if (ext && ext.numbers.length <= 1) {
  19613. return false;
  19614. } else {
  19615. return this.get(lng, count) !== 1;
  19616. }
  19617. },
  19618. get: function(lng, count) {
  19619. var parts = lng.split('-');
  19620. function getResult(l, c) {
  19621. var ext;
  19622. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19623. ext = pluralExtensions.currentRule.rule;
  19624. } else {
  19625. ext = pluralExtensions.rules[l];
  19626. }
  19627. if (ext) {
  19628. var i;
  19629. if (ext.noAbs) {
  19630. i = ext.plurals(c);
  19631. } else {
  19632. i = ext.plurals(Math.abs(c));
  19633. }
  19634. var number = ext.numbers[i];
  19635. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  19636. if (number === 2) {
  19637. number = -1; // regular plural
  19638. } else if (number === 1) {
  19639. number = 1; // singular
  19640. }
  19641. }//console.log(count + '-' + number);
  19642. return number;
  19643. } else {
  19644. return c === 1 ? '1' : '-1';
  19645. }
  19646. }
  19647. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  19648. }
  19649. };
  19650. var postProcessors = {};
  19651. var addPostProcessor = function(name, fc) {
  19652. postProcessors[name] = fc;
  19653. };
  19654. // sprintf support
  19655. var sprintf = (function() {
  19656. function get_type(variable) {
  19657. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  19658. }
  19659. function str_repeat(input, multiplier) {
  19660. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  19661. return output.join('');
  19662. }
  19663. var str_format = function() {
  19664. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  19665. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  19666. }
  19667. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  19668. };
  19669. str_format.format = function(parse_tree, argv) {
  19670. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  19671. for (i = 0; i < tree_length; i++) {
  19672. node_type = get_type(parse_tree[i]);
  19673. if (node_type === 'string') {
  19674. output.push(parse_tree[i]);
  19675. }
  19676. else if (node_type === 'array') {
  19677. match = parse_tree[i]; // convenience purposes only
  19678. if (match[2]) { // keyword argument
  19679. arg = argv[cursor];
  19680. for (k = 0; k < match[2].length; k++) {
  19681. if (!arg.hasOwnProperty(match[2][k])) {
  19682. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  19683. }
  19684. arg = arg[match[2][k]];
  19685. }
  19686. }
  19687. else if (match[1]) { // positional argument (explicit)
  19688. arg = argv[match[1]];
  19689. }
  19690. else { // positional argument (implicit)
  19691. arg = argv[cursor++];
  19692. }
  19693. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  19694. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  19695. }
  19696. switch (match[8]) {
  19697. case 'b': arg = arg.toString(2); break;
  19698. case 'c': arg = String.fromCharCode(arg); break;
  19699. case 'd': arg = parseInt(arg, 10); break;
  19700. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  19701. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  19702. case 'o': arg = arg.toString(8); break;
  19703. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  19704. case 'u': arg = Math.abs(arg); break;
  19705. case 'x': arg = arg.toString(16); break;
  19706. case 'X': arg = arg.toString(16).toUpperCase(); break;
  19707. }
  19708. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  19709. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  19710. pad_length = match[6] - String(arg).length;
  19711. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  19712. output.push(match[5] ? arg + pad : pad + arg);
  19713. }
  19714. }
  19715. return output.join('');
  19716. };
  19717. str_format.cache = {};
  19718. str_format.parse = function(fmt) {
  19719. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  19720. while (_fmt) {
  19721. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  19722. parse_tree.push(match[0]);
  19723. }
  19724. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  19725. parse_tree.push('%');
  19726. }
  19727. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  19728. if (match[2]) {
  19729. arg_names |= 1;
  19730. var field_list = [], replacement_field = match[2], field_match = [];
  19731. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19732. field_list.push(field_match[1]);
  19733. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  19734. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19735. field_list.push(field_match[1]);
  19736. }
  19737. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  19738. field_list.push(field_match[1]);
  19739. }
  19740. else {
  19741. throw('[sprintf] huh?');
  19742. }
  19743. }
  19744. }
  19745. else {
  19746. throw('[sprintf] huh?');
  19747. }
  19748. match[2] = field_list;
  19749. }
  19750. else {
  19751. arg_names |= 2;
  19752. }
  19753. if (arg_names === 3) {
  19754. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  19755. }
  19756. parse_tree.push(match);
  19757. }
  19758. else {
  19759. throw('[sprintf] huh?');
  19760. }
  19761. _fmt = _fmt.substring(match[0].length);
  19762. }
  19763. return parse_tree;
  19764. };
  19765. return str_format;
  19766. })();
  19767. var vsprintf = function(fmt, argv) {
  19768. argv.unshift(fmt);
  19769. return sprintf.apply(null, argv);
  19770. };
  19771. addPostProcessor("sprintf", function(val, key, opts) {
  19772. if (!opts.sprintf) return val;
  19773. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  19774. return vsprintf(val, opts.sprintf);
  19775. } else if (typeof opts.sprintf === 'object') {
  19776. return sprintf(val, opts.sprintf);
  19777. }
  19778. return val;
  19779. });
  19780. // public api interface
  19781. i18n.init = init;
  19782. i18n.setLng = setLng;
  19783. i18n.preload = preload;
  19784. i18n.addResourceBundle = addResourceBundle;
  19785. i18n.hasResourceBundle = hasResourceBundle;
  19786. i18n.addResource = addResource;
  19787. i18n.addResources = addResources;
  19788. i18n.removeResourceBundle = removeResourceBundle;
  19789. i18n.loadNamespace = loadNamespace;
  19790. i18n.loadNamespaces = loadNamespaces;
  19791. i18n.setDefaultNamespace = setDefaultNamespace;
  19792. i18n.t = translate;
  19793. i18n.translate = translate;
  19794. i18n.exists = exists;
  19795. i18n.detectLanguage = f.detectLanguage;
  19796. i18n.pluralExtensions = pluralExtensions;
  19797. i18n.sync = sync;
  19798. i18n.functions = f;
  19799. i18n.lng = lng;
  19800. i18n.addPostProcessor = addPostProcessor;
  19801. i18n.options = o;
  19802. })();
  19803. },{"jquery":"jquery"}],71:[function(require,module,exports){
  19804. /*
  19805. A JavaScript implementation of the SHA family of hashes, as
  19806. defined in FIPS PUB 180-2 as well as the corresponding HMAC implementation
  19807. as defined in FIPS PUB 198a
  19808. Copyright Brian Turek 2008-2013
  19809. Distributed under the BSD License
  19810. See http://caligatio.github.com/jsSHA/ for more information
  19811. Several functions taken from Paul Johnston
  19812. */
  19813. (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"!==
  19814. 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";
  19815. 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"===
  19816. 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|
  19817. (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,
  19818. 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,
  19819. 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=
  19820. {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):
  19821. 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,
  19822. 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>>>
  19823. 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>>>
  19824. 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>>>
  19825. 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-
  19826. 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,
  19827. 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,
  19828. 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],
  19829. 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),
  19830. 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),
  19831. 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,
  19832. 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,
  19833. 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?
  19834. 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,
  19835. 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);
  19836. },{}],72:[function(require,module,exports){
  19837. // Top level file is just a mixin of submodules & constants
  19838. 'use strict';
  19839. var assign = require('./lib/utils/common').assign;
  19840. var deflate = require('./lib/deflate');
  19841. var inflate = require('./lib/inflate');
  19842. var constants = require('./lib/zlib/constants');
  19843. var pako = {};
  19844. assign(pako, deflate, inflate, constants);
  19845. module.exports = pako;
  19846. },{"./lib/deflate":73,"./lib/inflate":74,"./lib/utils/common":75,"./lib/zlib/constants":78}],73:[function(require,module,exports){
  19847. 'use strict';
  19848. var zlib_deflate = require('./zlib/deflate.js');
  19849. var utils = require('./utils/common');
  19850. var strings = require('./utils/strings');
  19851. var msg = require('./zlib/messages');
  19852. var zstream = require('./zlib/zstream');
  19853. var toString = Object.prototype.toString;
  19854. /* Public constants ==========================================================*/
  19855. /* ===========================================================================*/
  19856. var Z_NO_FLUSH = 0;
  19857. var Z_FINISH = 4;
  19858. var Z_OK = 0;
  19859. var Z_STREAM_END = 1;
  19860. var Z_SYNC_FLUSH = 2;
  19861. var Z_DEFAULT_COMPRESSION = -1;
  19862. var Z_DEFAULT_STRATEGY = 0;
  19863. var Z_DEFLATED = 8;
  19864. /* ===========================================================================*/
  19865. /**
  19866. * class Deflate
  19867. *
  19868. * Generic JS-style wrapper for zlib calls. If you don't need
  19869. * streaming behaviour - use more simple functions: [[deflate]],
  19870. * [[deflateRaw]] and [[gzip]].
  19871. **/
  19872. /* internal
  19873. * Deflate.chunks -> Array
  19874. *
  19875. * Chunks of output data, if [[Deflate#onData]] not overriden.
  19876. **/
  19877. /**
  19878. * Deflate.result -> Uint8Array|Array
  19879. *
  19880. * Compressed result, generated by default [[Deflate#onData]]
  19881. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  19882. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  19883. * push a chunk with explicit flush (call [[Deflate#push]] with
  19884. * `Z_SYNC_FLUSH` param).
  19885. **/
  19886. /**
  19887. * Deflate.err -> Number
  19888. *
  19889. * Error code after deflate finished. 0 (Z_OK) on success.
  19890. * You will not need it in real life, because deflate errors
  19891. * are possible only on wrong options or bad `onData` / `onEnd`
  19892. * custom handlers.
  19893. **/
  19894. /**
  19895. * Deflate.msg -> String
  19896. *
  19897. * Error message, if [[Deflate.err]] != 0
  19898. **/
  19899. /**
  19900. * new Deflate(options)
  19901. * - options (Object): zlib deflate options.
  19902. *
  19903. * Creates new deflator instance with specified params. Throws exception
  19904. * on bad params. Supported options:
  19905. *
  19906. * - `level`
  19907. * - `windowBits`
  19908. * - `memLevel`
  19909. * - `strategy`
  19910. *
  19911. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19912. * for more information on these.
  19913. *
  19914. * Additional options, for internal needs:
  19915. *
  19916. * - `chunkSize` - size of generated data chunks (16K by default)
  19917. * - `raw` (Boolean) - do raw deflate
  19918. * - `gzip` (Boolean) - create gzip wrapper
  19919. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19920. * (each char code [0..255])
  19921. * - `header` (Object) - custom header for gzip
  19922. * - `text` (Boolean) - true if compressed data believed to be text
  19923. * - `time` (Number) - modification time, unix timestamp
  19924. * - `os` (Number) - operation system code
  19925. * - `extra` (Array) - array of bytes with extra data (max 65536)
  19926. * - `name` (String) - file name (binary string)
  19927. * - `comment` (String) - comment (binary string)
  19928. * - `hcrc` (Boolean) - true if header crc should be added
  19929. *
  19930. * ##### Example:
  19931. *
  19932. * ```javascript
  19933. * var pako = require('pako')
  19934. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19935. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19936. *
  19937. * var deflate = new pako.Deflate({ level: 3});
  19938. *
  19939. * deflate.push(chunk1, false);
  19940. * deflate.push(chunk2, true); // true -> last chunk
  19941. *
  19942. * if (deflate.err) { throw new Error(deflate.err); }
  19943. *
  19944. * console.log(deflate.result);
  19945. * ```
  19946. **/
  19947. var Deflate = function(options) {
  19948. this.options = utils.assign({
  19949. level: Z_DEFAULT_COMPRESSION,
  19950. method: Z_DEFLATED,
  19951. chunkSize: 16384,
  19952. windowBits: 15,
  19953. memLevel: 8,
  19954. strategy: Z_DEFAULT_STRATEGY,
  19955. to: ''
  19956. }, options || {});
  19957. var opt = this.options;
  19958. if (opt.raw && (opt.windowBits > 0)) {
  19959. opt.windowBits = -opt.windowBits;
  19960. }
  19961. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  19962. opt.windowBits += 16;
  19963. }
  19964. this.err = 0; // error code, if happens (0 = Z_OK)
  19965. this.msg = ''; // error message
  19966. this.ended = false; // used to avoid multiple onEnd() calls
  19967. this.chunks = []; // chunks of compressed data
  19968. this.strm = new zstream();
  19969. this.strm.avail_out = 0;
  19970. var status = zlib_deflate.deflateInit2(
  19971. this.strm,
  19972. opt.level,
  19973. opt.method,
  19974. opt.windowBits,
  19975. opt.memLevel,
  19976. opt.strategy
  19977. );
  19978. if (status !== Z_OK) {
  19979. throw new Error(msg[status]);
  19980. }
  19981. if (opt.header) {
  19982. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  19983. }
  19984. };
  19985. /**
  19986. * Deflate#push(data[, mode]) -> Boolean
  19987. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  19988. * converted to utf8 byte sequence.
  19989. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19990. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19991. *
  19992. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  19993. * new compressed chunks. Returns `true` on success. The last data block must have
  19994. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19995. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19996. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  19997. *
  19998. * On fail call [[Deflate#onEnd]] with error code and return false.
  19999. *
  20000. * We strongly recommend to use `Uint8Array` on input for best speed (output
  20001. * array format is detected automatically). Also, don't skip last param and always
  20002. * use the same type in your code (boolean or number). That will improve JS speed.
  20003. *
  20004. * For regular `Array`-s make sure all elements are [0..255].
  20005. *
  20006. * ##### Example
  20007. *
  20008. * ```javascript
  20009. * push(chunk, false); // push one of data chunks
  20010. * ...
  20011. * push(chunk, true); // push last chunk
  20012. * ```
  20013. **/
  20014. Deflate.prototype.push = function(data, mode) {
  20015. var strm = this.strm;
  20016. var chunkSize = this.options.chunkSize;
  20017. var status, _mode;
  20018. if (this.ended) { return false; }
  20019. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  20020. // Convert data if needed
  20021. if (typeof data === 'string') {
  20022. // If we need to compress text, change encoding to utf8.
  20023. strm.input = strings.string2buf(data);
  20024. } else if (toString.call(data) === '[object ArrayBuffer]') {
  20025. strm.input = new Uint8Array(data);
  20026. } else {
  20027. strm.input = data;
  20028. }
  20029. strm.next_in = 0;
  20030. strm.avail_in = strm.input.length;
  20031. do {
  20032. if (strm.avail_out === 0) {
  20033. strm.output = new utils.Buf8(chunkSize);
  20034. strm.next_out = 0;
  20035. strm.avail_out = chunkSize;
  20036. }
  20037. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  20038. if (status !== Z_STREAM_END && status !== Z_OK) {
  20039. this.onEnd(status);
  20040. this.ended = true;
  20041. return false;
  20042. }
  20043. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  20044. if (this.options.to === 'string') {
  20045. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  20046. } else {
  20047. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  20048. }
  20049. }
  20050. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  20051. // Finalize on the last chunk.
  20052. if (_mode === Z_FINISH) {
  20053. status = zlib_deflate.deflateEnd(this.strm);
  20054. this.onEnd(status);
  20055. this.ended = true;
  20056. return status === Z_OK;
  20057. }
  20058. // callback interim results if Z_SYNC_FLUSH.
  20059. if (_mode === Z_SYNC_FLUSH) {
  20060. this.onEnd(Z_OK);
  20061. strm.avail_out = 0;
  20062. return true;
  20063. }
  20064. return true;
  20065. };
  20066. /**
  20067. * Deflate#onData(chunk) -> Void
  20068. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  20069. * on js engine support. When string output requested, each chunk
  20070. * will be string.
  20071. *
  20072. * By default, stores data blocks in `chunks[]` property and glue
  20073. * those in `onEnd`. Override this handler, if you need another behaviour.
  20074. **/
  20075. Deflate.prototype.onData = function(chunk) {
  20076. this.chunks.push(chunk);
  20077. };
  20078. /**
  20079. * Deflate#onEnd(status) -> Void
  20080. * - status (Number): deflate status. 0 (Z_OK) on success,
  20081. * other if not.
  20082. *
  20083. * Called once after you tell deflate that the input stream is
  20084. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20085. * or if an error happened. By default - join collected chunks,
  20086. * free memory and fill `results` / `err` properties.
  20087. **/
  20088. Deflate.prototype.onEnd = function(status) {
  20089. // On success - join
  20090. if (status === Z_OK) {
  20091. if (this.options.to === 'string') {
  20092. this.result = this.chunks.join('');
  20093. } else {
  20094. this.result = utils.flattenChunks(this.chunks);
  20095. }
  20096. }
  20097. this.chunks = [];
  20098. this.err = status;
  20099. this.msg = this.strm.msg;
  20100. };
  20101. /**
  20102. * deflate(data[, options]) -> Uint8Array|Array|String
  20103. * - data (Uint8Array|Array|String): input data to compress.
  20104. * - options (Object): zlib deflate options.
  20105. *
  20106. * Compress `data` with deflate alrorythm and `options`.
  20107. *
  20108. * Supported options are:
  20109. *
  20110. * - level
  20111. * - windowBits
  20112. * - memLevel
  20113. * - strategy
  20114. *
  20115. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20116. * for more information on these.
  20117. *
  20118. * Sugar (options):
  20119. *
  20120. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20121. * negative windowBits implicitly.
  20122. * - `to` (String) - if equal to 'string', then result will be "binary string"
  20123. * (each char code [0..255])
  20124. *
  20125. * ##### Example:
  20126. *
  20127. * ```javascript
  20128. * var pako = require('pako')
  20129. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  20130. *
  20131. * console.log(pako.deflate(data));
  20132. * ```
  20133. **/
  20134. function deflate(input, options) {
  20135. var deflator = new Deflate(options);
  20136. deflator.push(input, true);
  20137. // That will never happens, if you don't cheat with options :)
  20138. if (deflator.err) { throw deflator.msg; }
  20139. return deflator.result;
  20140. }
  20141. /**
  20142. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  20143. * - data (Uint8Array|Array|String): input data to compress.
  20144. * - options (Object): zlib deflate options.
  20145. *
  20146. * The same as [[deflate]], but creates raw data, without wrapper
  20147. * (header and adler32 crc).
  20148. **/
  20149. function deflateRaw(input, options) {
  20150. options = options || {};
  20151. options.raw = true;
  20152. return deflate(input, options);
  20153. }
  20154. /**
  20155. * gzip(data[, options]) -> Uint8Array|Array|String
  20156. * - data (Uint8Array|Array|String): input data to compress.
  20157. * - options (Object): zlib deflate options.
  20158. *
  20159. * The same as [[deflate]], but create gzip wrapper instead of
  20160. * deflate one.
  20161. **/
  20162. function gzip(input, options) {
  20163. options = options || {};
  20164. options.gzip = true;
  20165. return deflate(input, options);
  20166. }
  20167. exports.Deflate = Deflate;
  20168. exports.deflate = deflate;
  20169. exports.deflateRaw = deflateRaw;
  20170. exports.gzip = gzip;
  20171. },{"./utils/common":75,"./utils/strings":76,"./zlib/deflate.js":80,"./zlib/messages":85,"./zlib/zstream":87}],74:[function(require,module,exports){
  20172. 'use strict';
  20173. var zlib_inflate = require('./zlib/inflate.js');
  20174. var utils = require('./utils/common');
  20175. var strings = require('./utils/strings');
  20176. var c = require('./zlib/constants');
  20177. var msg = require('./zlib/messages');
  20178. var zstream = require('./zlib/zstream');
  20179. var gzheader = require('./zlib/gzheader');
  20180. var toString = Object.prototype.toString;
  20181. /**
  20182. * class Inflate
  20183. *
  20184. * Generic JS-style wrapper for zlib calls. If you don't need
  20185. * streaming behaviour - use more simple functions: [[inflate]]
  20186. * and [[inflateRaw]].
  20187. **/
  20188. /* internal
  20189. * inflate.chunks -> Array
  20190. *
  20191. * Chunks of output data, if [[Inflate#onData]] not overriden.
  20192. **/
  20193. /**
  20194. * Inflate.result -> Uint8Array|Array|String
  20195. *
  20196. * Uncompressed result, generated by default [[Inflate#onData]]
  20197. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  20198. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  20199. * push a chunk with explicit flush (call [[Inflate#push]] with
  20200. * `Z_SYNC_FLUSH` param).
  20201. **/
  20202. /**
  20203. * Inflate.err -> Number
  20204. *
  20205. * Error code after inflate finished. 0 (Z_OK) on success.
  20206. * Should be checked if broken data possible.
  20207. **/
  20208. /**
  20209. * Inflate.msg -> String
  20210. *
  20211. * Error message, if [[Inflate.err]] != 0
  20212. **/
  20213. /**
  20214. * new Inflate(options)
  20215. * - options (Object): zlib inflate options.
  20216. *
  20217. * Creates new inflator instance with specified params. Throws exception
  20218. * on bad params. Supported options:
  20219. *
  20220. * - `windowBits`
  20221. *
  20222. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20223. * for more information on these.
  20224. *
  20225. * Additional options, for internal needs:
  20226. *
  20227. * - `chunkSize` - size of generated data chunks (16K by default)
  20228. * - `raw` (Boolean) - do raw inflate
  20229. * - `to` (String) - if equal to 'string', then result will be converted
  20230. * from utf8 to utf16 (javascript) string. When string output requested,
  20231. * chunk length can differ from `chunkSize`, depending on content.
  20232. *
  20233. * By default, when no options set, autodetect deflate/gzip data format via
  20234. * wrapper header.
  20235. *
  20236. * ##### Example:
  20237. *
  20238. * ```javascript
  20239. * var pako = require('pako')
  20240. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  20241. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  20242. *
  20243. * var inflate = new pako.Inflate({ level: 3});
  20244. *
  20245. * inflate.push(chunk1, false);
  20246. * inflate.push(chunk2, true); // true -> last chunk
  20247. *
  20248. * if (inflate.err) { throw new Error(inflate.err); }
  20249. *
  20250. * console.log(inflate.result);
  20251. * ```
  20252. **/
  20253. var Inflate = function(options) {
  20254. this.options = utils.assign({
  20255. chunkSize: 16384,
  20256. windowBits: 0,
  20257. to: ''
  20258. }, options || {});
  20259. var opt = this.options;
  20260. // Force window size for `raw` data, if not set directly,
  20261. // because we have no header for autodetect.
  20262. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  20263. opt.windowBits = -opt.windowBits;
  20264. if (opt.windowBits === 0) { opt.windowBits = -15; }
  20265. }
  20266. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  20267. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  20268. !(options && options.windowBits)) {
  20269. opt.windowBits += 32;
  20270. }
  20271. // Gzip header has no info about windows size, we can do autodetect only
  20272. // for deflate. So, if window size not set, force it to max when gzip possible
  20273. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  20274. // bit 3 (16) -> gzipped data
  20275. // bit 4 (32) -> autodetect gzip/deflate
  20276. if ((opt.windowBits & 15) === 0) {
  20277. opt.windowBits |= 15;
  20278. }
  20279. }
  20280. this.err = 0; // error code, if happens (0 = Z_OK)
  20281. this.msg = ''; // error message
  20282. this.ended = false; // used to avoid multiple onEnd() calls
  20283. this.chunks = []; // chunks of compressed data
  20284. this.strm = new zstream();
  20285. this.strm.avail_out = 0;
  20286. var status = zlib_inflate.inflateInit2(
  20287. this.strm,
  20288. opt.windowBits
  20289. );
  20290. if (status !== c.Z_OK) {
  20291. throw new Error(msg[status]);
  20292. }
  20293. this.header = new gzheader();
  20294. zlib_inflate.inflateGetHeader(this.strm, this.header);
  20295. };
  20296. /**
  20297. * Inflate#push(data[, mode]) -> Boolean
  20298. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  20299. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  20300. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  20301. *
  20302. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  20303. * new output chunks. Returns `true` on success. The last data block must have
  20304. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  20305. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  20306. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  20307. *
  20308. * On fail call [[Inflate#onEnd]] with error code and return false.
  20309. *
  20310. * We strongly recommend to use `Uint8Array` on input for best speed (output
  20311. * format is detected automatically). Also, don't skip last param and always
  20312. * use the same type in your code (boolean or number). That will improve JS speed.
  20313. *
  20314. * For regular `Array`-s make sure all elements are [0..255].
  20315. *
  20316. * ##### Example
  20317. *
  20318. * ```javascript
  20319. * push(chunk, false); // push one of data chunks
  20320. * ...
  20321. * push(chunk, true); // push last chunk
  20322. * ```
  20323. **/
  20324. Inflate.prototype.push = function(data, mode) {
  20325. var strm = this.strm;
  20326. var chunkSize = this.options.chunkSize;
  20327. var status, _mode;
  20328. var next_out_utf8, tail, utf8str;
  20329. if (this.ended) { return false; }
  20330. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  20331. // Convert data if needed
  20332. if (typeof data === 'string') {
  20333. // Only binary strings can be decompressed on practice
  20334. strm.input = strings.binstring2buf(data);
  20335. } else if (toString.call(data) === '[object ArrayBuffer]') {
  20336. strm.input = new Uint8Array(data);
  20337. } else {
  20338. strm.input = data;
  20339. }
  20340. strm.next_in = 0;
  20341. strm.avail_in = strm.input.length;
  20342. do {
  20343. if (strm.avail_out === 0) {
  20344. strm.output = new utils.Buf8(chunkSize);
  20345. strm.next_out = 0;
  20346. strm.avail_out = chunkSize;
  20347. }
  20348. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  20349. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  20350. this.onEnd(status);
  20351. this.ended = true;
  20352. return false;
  20353. }
  20354. if (strm.next_out) {
  20355. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  20356. if (this.options.to === 'string') {
  20357. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  20358. tail = strm.next_out - next_out_utf8;
  20359. utf8str = strings.buf2string(strm.output, next_out_utf8);
  20360. // move tail
  20361. strm.next_out = tail;
  20362. strm.avail_out = chunkSize - tail;
  20363. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  20364. this.onData(utf8str);
  20365. } else {
  20366. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  20367. }
  20368. }
  20369. }
  20370. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  20371. if (status === c.Z_STREAM_END) {
  20372. _mode = c.Z_FINISH;
  20373. }
  20374. // Finalize on the last chunk.
  20375. if (_mode === c.Z_FINISH) {
  20376. status = zlib_inflate.inflateEnd(this.strm);
  20377. this.onEnd(status);
  20378. this.ended = true;
  20379. return status === c.Z_OK;
  20380. }
  20381. // callback interim results if Z_SYNC_FLUSH.
  20382. if (_mode === c.Z_SYNC_FLUSH) {
  20383. this.onEnd(c.Z_OK);
  20384. strm.avail_out = 0;
  20385. return true;
  20386. }
  20387. return true;
  20388. };
  20389. /**
  20390. * Inflate#onData(chunk) -> Void
  20391. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  20392. * on js engine support. When string output requested, each chunk
  20393. * will be string.
  20394. *
  20395. * By default, stores data blocks in `chunks[]` property and glue
  20396. * those in `onEnd`. Override this handler, if you need another behaviour.
  20397. **/
  20398. Inflate.prototype.onData = function(chunk) {
  20399. this.chunks.push(chunk);
  20400. };
  20401. /**
  20402. * Inflate#onEnd(status) -> Void
  20403. * - status (Number): inflate status. 0 (Z_OK) on success,
  20404. * other if not.
  20405. *
  20406. * Called either after you tell inflate that the input stream is
  20407. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20408. * or if an error happened. By default - join collected chunks,
  20409. * free memory and fill `results` / `err` properties.
  20410. **/
  20411. Inflate.prototype.onEnd = function(status) {
  20412. // On success - join
  20413. if (status === c.Z_OK) {
  20414. if (this.options.to === 'string') {
  20415. // Glue & convert here, until we teach pako to send
  20416. // utf8 alligned strings to onData
  20417. this.result = this.chunks.join('');
  20418. } else {
  20419. this.result = utils.flattenChunks(this.chunks);
  20420. }
  20421. }
  20422. this.chunks = [];
  20423. this.err = status;
  20424. this.msg = this.strm.msg;
  20425. };
  20426. /**
  20427. * inflate(data[, options]) -> Uint8Array|Array|String
  20428. * - data (Uint8Array|Array|String): input data to decompress.
  20429. * - options (Object): zlib inflate options.
  20430. *
  20431. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  20432. * format via wrapper header by default. That's why we don't provide
  20433. * separate `ungzip` method.
  20434. *
  20435. * Supported options are:
  20436. *
  20437. * - windowBits
  20438. *
  20439. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20440. * for more information.
  20441. *
  20442. * Sugar (options):
  20443. *
  20444. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20445. * negative windowBits implicitly.
  20446. * - `to` (String) - if equal to 'string', then result will be converted
  20447. * from utf8 to utf16 (javascript) string. When string output requested,
  20448. * chunk length can differ from `chunkSize`, depending on content.
  20449. *
  20450. *
  20451. * ##### Example:
  20452. *
  20453. * ```javascript
  20454. * var pako = require('pako')
  20455. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  20456. * , output;
  20457. *
  20458. * try {
  20459. * output = pako.inflate(input);
  20460. * } catch (err)
  20461. * console.log(err);
  20462. * }
  20463. * ```
  20464. **/
  20465. function inflate(input, options) {
  20466. var inflator = new Inflate(options);
  20467. inflator.push(input, true);
  20468. // That will never happens, if you don't cheat with options :)
  20469. if (inflator.err) { throw inflator.msg; }
  20470. return inflator.result;
  20471. }
  20472. /**
  20473. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  20474. * - data (Uint8Array|Array|String): input data to decompress.
  20475. * - options (Object): zlib inflate options.
  20476. *
  20477. * The same as [[inflate]], but creates raw data, without wrapper
  20478. * (header and adler32 crc).
  20479. **/
  20480. function inflateRaw(input, options) {
  20481. options = options || {};
  20482. options.raw = true;
  20483. return inflate(input, options);
  20484. }
  20485. /**
  20486. * ungzip(data[, options]) -> Uint8Array|Array|String
  20487. * - data (Uint8Array|Array|String): input data to decompress.
  20488. * - options (Object): zlib inflate options.
  20489. *
  20490. * Just shortcut to [[inflate]], because it autodetects format
  20491. * by header.content. Done for convenience.
  20492. **/
  20493. exports.Inflate = Inflate;
  20494. exports.inflate = inflate;
  20495. exports.inflateRaw = inflateRaw;
  20496. exports.ungzip = inflate;
  20497. },{"./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){
  20498. 'use strict';
  20499. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  20500. (typeof Uint16Array !== 'undefined') &&
  20501. (typeof Int32Array !== 'undefined');
  20502. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  20503. var sources = Array.prototype.slice.call(arguments, 1);
  20504. while (sources.length) {
  20505. var source = sources.shift();
  20506. if (!source) { continue; }
  20507. if (typeof source !== 'object') {
  20508. throw new TypeError(source + 'must be non-object');
  20509. }
  20510. for (var p in source) {
  20511. if (source.hasOwnProperty(p)) {
  20512. obj[p] = source[p];
  20513. }
  20514. }
  20515. }
  20516. return obj;
  20517. };
  20518. // reduce buffer size, avoiding mem copy
  20519. exports.shrinkBuf = function (buf, size) {
  20520. if (buf.length === size) { return buf; }
  20521. if (buf.subarray) { return buf.subarray(0, size); }
  20522. buf.length = size;
  20523. return buf;
  20524. };
  20525. var fnTyped = {
  20526. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20527. if (src.subarray && dest.subarray) {
  20528. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  20529. return;
  20530. }
  20531. // Fallback to ordinary array
  20532. for (var i=0; i<len; i++) {
  20533. dest[dest_offs + i] = src[src_offs + i];
  20534. }
  20535. },
  20536. // Join array of chunks to single array.
  20537. flattenChunks: function(chunks) {
  20538. var i, l, len, pos, chunk, result;
  20539. // calculate data length
  20540. len = 0;
  20541. for (i=0, l=chunks.length; i<l; i++) {
  20542. len += chunks[i].length;
  20543. }
  20544. // join chunks
  20545. result = new Uint8Array(len);
  20546. pos = 0;
  20547. for (i=0, l=chunks.length; i<l; i++) {
  20548. chunk = chunks[i];
  20549. result.set(chunk, pos);
  20550. pos += chunk.length;
  20551. }
  20552. return result;
  20553. }
  20554. };
  20555. var fnUntyped = {
  20556. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20557. for (var i=0; i<len; i++) {
  20558. dest[dest_offs + i] = src[src_offs + i];
  20559. }
  20560. },
  20561. // Join array of chunks to single array.
  20562. flattenChunks: function(chunks) {
  20563. return [].concat.apply([], chunks);
  20564. }
  20565. };
  20566. // Enable/Disable typed arrays use, for testing
  20567. //
  20568. exports.setTyped = function (on) {
  20569. if (on) {
  20570. exports.Buf8 = Uint8Array;
  20571. exports.Buf16 = Uint16Array;
  20572. exports.Buf32 = Int32Array;
  20573. exports.assign(exports, fnTyped);
  20574. } else {
  20575. exports.Buf8 = Array;
  20576. exports.Buf16 = Array;
  20577. exports.Buf32 = Array;
  20578. exports.assign(exports, fnUntyped);
  20579. }
  20580. };
  20581. exports.setTyped(TYPED_OK);
  20582. },{}],76:[function(require,module,exports){
  20583. // String encode/decode helpers
  20584. 'use strict';
  20585. var utils = require('./common');
  20586. // Quick check if we can use fast array to bin string conversion
  20587. //
  20588. // - apply(Array) can fail on Android 2.2
  20589. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  20590. //
  20591. var STR_APPLY_OK = true;
  20592. var STR_APPLY_UIA_OK = true;
  20593. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  20594. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  20595. // Table with utf8 lengths (calculated by first byte of sequence)
  20596. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  20597. // because max possible codepoint is 0x10ffff
  20598. var _utf8len = new utils.Buf8(256);
  20599. for (var q=0; q<256; q++) {
  20600. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  20601. }
  20602. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  20603. // convert string to array (typed, when possible)
  20604. exports.string2buf = function (str) {
  20605. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  20606. // count binary size
  20607. for (m_pos = 0; m_pos < str_len; m_pos++) {
  20608. c = str.charCodeAt(m_pos);
  20609. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20610. c2 = str.charCodeAt(m_pos+1);
  20611. if ((c2 & 0xfc00) === 0xdc00) {
  20612. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20613. m_pos++;
  20614. }
  20615. }
  20616. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  20617. }
  20618. // allocate buffer
  20619. buf = new utils.Buf8(buf_len);
  20620. // convert
  20621. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  20622. c = str.charCodeAt(m_pos);
  20623. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20624. c2 = str.charCodeAt(m_pos+1);
  20625. if ((c2 & 0xfc00) === 0xdc00) {
  20626. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20627. m_pos++;
  20628. }
  20629. }
  20630. if (c < 0x80) {
  20631. /* one byte */
  20632. buf[i++] = c;
  20633. } else if (c < 0x800) {
  20634. /* two bytes */
  20635. buf[i++] = 0xC0 | (c >>> 6);
  20636. buf[i++] = 0x80 | (c & 0x3f);
  20637. } else if (c < 0x10000) {
  20638. /* three bytes */
  20639. buf[i++] = 0xE0 | (c >>> 12);
  20640. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20641. buf[i++] = 0x80 | (c & 0x3f);
  20642. } else {
  20643. /* four bytes */
  20644. buf[i++] = 0xf0 | (c >>> 18);
  20645. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  20646. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20647. buf[i++] = 0x80 | (c & 0x3f);
  20648. }
  20649. }
  20650. return buf;
  20651. };
  20652. // Helper (used in 2 places)
  20653. function buf2binstring(buf, len) {
  20654. // use fallback for big arrays to avoid stack overflow
  20655. if (len < 65537) {
  20656. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  20657. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  20658. }
  20659. }
  20660. var result = '';
  20661. for (var i=0; i < len; i++) {
  20662. result += String.fromCharCode(buf[i]);
  20663. }
  20664. return result;
  20665. }
  20666. // Convert byte array to binary string
  20667. exports.buf2binstring = function(buf) {
  20668. return buf2binstring(buf, buf.length);
  20669. };
  20670. // Convert binary string (typed, when possible)
  20671. exports.binstring2buf = function(str) {
  20672. var buf = new utils.Buf8(str.length);
  20673. for (var i=0, len=buf.length; i < len; i++) {
  20674. buf[i] = str.charCodeAt(i);
  20675. }
  20676. return buf;
  20677. };
  20678. // convert array to string
  20679. exports.buf2string = function (buf, max) {
  20680. var i, out, c, c_len;
  20681. var len = max || buf.length;
  20682. // Reserve max possible length (2 words per char)
  20683. // NB: by unknown reasons, Array is significantly faster for
  20684. // String.fromCharCode.apply than Uint16Array.
  20685. var utf16buf = new Array(len*2);
  20686. for (out=0, i=0; i<len;) {
  20687. c = buf[i++];
  20688. // quick process ascii
  20689. if (c < 0x80) { utf16buf[out++] = c; continue; }
  20690. c_len = _utf8len[c];
  20691. // skip 5 & 6 byte codes
  20692. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  20693. // apply mask on first byte
  20694. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  20695. // join the rest
  20696. while (c_len > 1 && i < len) {
  20697. c = (c << 6) | (buf[i++] & 0x3f);
  20698. c_len--;
  20699. }
  20700. // terminated by end of string?
  20701. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  20702. if (c < 0x10000) {
  20703. utf16buf[out++] = c;
  20704. } else {
  20705. c -= 0x10000;
  20706. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  20707. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  20708. }
  20709. }
  20710. return buf2binstring(utf16buf, out);
  20711. };
  20712. // Calculate max possible position in utf8 buffer,
  20713. // that will not break sequence. If that's not possible
  20714. // - (very small limits) return max size as is.
  20715. //
  20716. // buf[] - utf8 bytes array
  20717. // max - length limit (mandatory);
  20718. exports.utf8border = function(buf, max) {
  20719. var pos;
  20720. max = max || buf.length;
  20721. if (max > buf.length) { max = buf.length; }
  20722. // go back from last position, until start of sequence found
  20723. pos = max-1;
  20724. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  20725. // Fuckup - very small and broken sequence,
  20726. // return max, because we should return something anyway.
  20727. if (pos < 0) { return max; }
  20728. // If we came to start of buffer - that means vuffer is too small,
  20729. // return max too.
  20730. if (pos === 0) { return max; }
  20731. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  20732. };
  20733. },{"./common":75}],77:[function(require,module,exports){
  20734. 'use strict';
  20735. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  20736. // It doesn't worth to make additional optimizationa as in original.
  20737. // Small size is preferable.
  20738. function adler32(adler, buf, len, pos) {
  20739. var s1 = (adler & 0xffff) |0,
  20740. s2 = ((adler >>> 16) & 0xffff) |0,
  20741. n = 0;
  20742. while (len !== 0) {
  20743. // Set limit ~ twice less than 5552, to keep
  20744. // s2 in 31-bits, because we force signed ints.
  20745. // in other case %= will fail.
  20746. n = len > 2000 ? 2000 : len;
  20747. len -= n;
  20748. do {
  20749. s1 = (s1 + buf[pos++]) |0;
  20750. s2 = (s2 + s1) |0;
  20751. } while (--n);
  20752. s1 %= 65521;
  20753. s2 %= 65521;
  20754. }
  20755. return (s1 | (s2 << 16)) |0;
  20756. }
  20757. module.exports = adler32;
  20758. },{}],78:[function(require,module,exports){
  20759. module.exports = {
  20760. /* Allowed flush values; see deflate() and inflate() below for details */
  20761. Z_NO_FLUSH: 0,
  20762. Z_PARTIAL_FLUSH: 1,
  20763. Z_SYNC_FLUSH: 2,
  20764. Z_FULL_FLUSH: 3,
  20765. Z_FINISH: 4,
  20766. Z_BLOCK: 5,
  20767. Z_TREES: 6,
  20768. /* Return codes for the compression/decompression functions. Negative values
  20769. * are errors, positive values are used for special but normal events.
  20770. */
  20771. Z_OK: 0,
  20772. Z_STREAM_END: 1,
  20773. Z_NEED_DICT: 2,
  20774. Z_ERRNO: -1,
  20775. Z_STREAM_ERROR: -2,
  20776. Z_DATA_ERROR: -3,
  20777. //Z_MEM_ERROR: -4,
  20778. Z_BUF_ERROR: -5,
  20779. //Z_VERSION_ERROR: -6,
  20780. /* compression levels */
  20781. Z_NO_COMPRESSION: 0,
  20782. Z_BEST_SPEED: 1,
  20783. Z_BEST_COMPRESSION: 9,
  20784. Z_DEFAULT_COMPRESSION: -1,
  20785. Z_FILTERED: 1,
  20786. Z_HUFFMAN_ONLY: 2,
  20787. Z_RLE: 3,
  20788. Z_FIXED: 4,
  20789. Z_DEFAULT_STRATEGY: 0,
  20790. /* Possible values of the data_type field (though see inflate()) */
  20791. Z_BINARY: 0,
  20792. Z_TEXT: 1,
  20793. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  20794. Z_UNKNOWN: 2,
  20795. /* The deflate compression method */
  20796. Z_DEFLATED: 8
  20797. //Z_NULL: null // Use -1 or null inline, depending on var type
  20798. };
  20799. },{}],79:[function(require,module,exports){
  20800. 'use strict';
  20801. // Note: we can't get significant speed boost here.
  20802. // So write code to minimize size - no pregenerated tables
  20803. // and array tools dependencies.
  20804. // Use ordinary array, since untyped makes no boost here
  20805. function makeTable() {
  20806. var c, table = [];
  20807. for (var n =0; n < 256; n++) {
  20808. c = n;
  20809. for (var k =0; k < 8; k++) {
  20810. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  20811. }
  20812. table[n] = c;
  20813. }
  20814. return table;
  20815. }
  20816. // Create table on load. Just 255 signed longs. Not a problem.
  20817. var crcTable = makeTable();
  20818. function crc32(crc, buf, len, pos) {
  20819. var t = crcTable,
  20820. end = pos + len;
  20821. crc = crc ^ (-1);
  20822. for (var i = pos; i < end; i++) {
  20823. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  20824. }
  20825. return (crc ^ (-1)); // >>> 0;
  20826. }
  20827. module.exports = crc32;
  20828. },{}],80:[function(require,module,exports){
  20829. 'use strict';
  20830. var utils = require('../utils/common');
  20831. var trees = require('./trees');
  20832. var adler32 = require('./adler32');
  20833. var crc32 = require('./crc32');
  20834. var msg = require('./messages');
  20835. /* Public constants ==========================================================*/
  20836. /* ===========================================================================*/
  20837. /* Allowed flush values; see deflate() and inflate() below for details */
  20838. var Z_NO_FLUSH = 0;
  20839. var Z_PARTIAL_FLUSH = 1;
  20840. //var Z_SYNC_FLUSH = 2;
  20841. var Z_FULL_FLUSH = 3;
  20842. var Z_FINISH = 4;
  20843. var Z_BLOCK = 5;
  20844. //var Z_TREES = 6;
  20845. /* Return codes for the compression/decompression functions. Negative values
  20846. * are errors, positive values are used for special but normal events.
  20847. */
  20848. var Z_OK = 0;
  20849. var Z_STREAM_END = 1;
  20850. //var Z_NEED_DICT = 2;
  20851. //var Z_ERRNO = -1;
  20852. var Z_STREAM_ERROR = -2;
  20853. var Z_DATA_ERROR = -3;
  20854. //var Z_MEM_ERROR = -4;
  20855. var Z_BUF_ERROR = -5;
  20856. //var Z_VERSION_ERROR = -6;
  20857. /* compression levels */
  20858. //var Z_NO_COMPRESSION = 0;
  20859. //var Z_BEST_SPEED = 1;
  20860. //var Z_BEST_COMPRESSION = 9;
  20861. var Z_DEFAULT_COMPRESSION = -1;
  20862. var Z_FILTERED = 1;
  20863. var Z_HUFFMAN_ONLY = 2;
  20864. var Z_RLE = 3;
  20865. var Z_FIXED = 4;
  20866. var Z_DEFAULT_STRATEGY = 0;
  20867. /* Possible values of the data_type field (though see inflate()) */
  20868. //var Z_BINARY = 0;
  20869. //var Z_TEXT = 1;
  20870. //var Z_ASCII = 1; // = Z_TEXT
  20871. var Z_UNKNOWN = 2;
  20872. /* The deflate compression method */
  20873. var Z_DEFLATED = 8;
  20874. /*============================================================================*/
  20875. var MAX_MEM_LEVEL = 9;
  20876. /* Maximum value for memLevel in deflateInit2 */
  20877. var MAX_WBITS = 15;
  20878. /* 32K LZ77 window */
  20879. var DEF_MEM_LEVEL = 8;
  20880. var LENGTH_CODES = 29;
  20881. /* number of length codes, not counting the special END_BLOCK code */
  20882. var LITERALS = 256;
  20883. /* number of literal bytes 0..255 */
  20884. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  20885. /* number of Literal or Length codes, including the END_BLOCK code */
  20886. var D_CODES = 30;
  20887. /* number of distance codes */
  20888. var BL_CODES = 19;
  20889. /* number of codes used to transfer the bit lengths */
  20890. var HEAP_SIZE = 2*L_CODES + 1;
  20891. /* maximum heap size */
  20892. var MAX_BITS = 15;
  20893. /* All codes must not exceed MAX_BITS bits */
  20894. var MIN_MATCH = 3;
  20895. var MAX_MATCH = 258;
  20896. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  20897. var PRESET_DICT = 0x20;
  20898. var INIT_STATE = 42;
  20899. var EXTRA_STATE = 69;
  20900. var NAME_STATE = 73;
  20901. var COMMENT_STATE = 91;
  20902. var HCRC_STATE = 103;
  20903. var BUSY_STATE = 113;
  20904. var FINISH_STATE = 666;
  20905. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  20906. var BS_BLOCK_DONE = 2; /* block flush performed */
  20907. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  20908. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  20909. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  20910. function err(strm, errorCode) {
  20911. strm.msg = msg[errorCode];
  20912. return errorCode;
  20913. }
  20914. function rank(f) {
  20915. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  20916. }
  20917. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  20918. /* =========================================================================
  20919. * Flush as much pending output as possible. All deflate() output goes
  20920. * through this function so some applications may wish to modify it
  20921. * to avoid allocating a large strm->output buffer and copying into it.
  20922. * (See also read_buf()).
  20923. */
  20924. function flush_pending(strm) {
  20925. var s = strm.state;
  20926. //_tr_flush_bits(s);
  20927. var len = s.pending;
  20928. if (len > strm.avail_out) {
  20929. len = strm.avail_out;
  20930. }
  20931. if (len === 0) { return; }
  20932. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  20933. strm.next_out += len;
  20934. s.pending_out += len;
  20935. strm.total_out += len;
  20936. strm.avail_out -= len;
  20937. s.pending -= len;
  20938. if (s.pending === 0) {
  20939. s.pending_out = 0;
  20940. }
  20941. }
  20942. function flush_block_only (s, last) {
  20943. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  20944. s.block_start = s.strstart;
  20945. flush_pending(s.strm);
  20946. }
  20947. function put_byte(s, b) {
  20948. s.pending_buf[s.pending++] = b;
  20949. }
  20950. /* =========================================================================
  20951. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  20952. * IN assertion: the stream state is correct and there is enough room in
  20953. * pending_buf.
  20954. */
  20955. function putShortMSB(s, b) {
  20956. // put_byte(s, (Byte)(b >> 8));
  20957. // put_byte(s, (Byte)(b & 0xff));
  20958. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  20959. s.pending_buf[s.pending++] = b & 0xff;
  20960. }
  20961. /* ===========================================================================
  20962. * Read a new buffer from the current input stream, update the adler32
  20963. * and total number of bytes read. All deflate() input goes through
  20964. * this function so some applications may wish to modify it to avoid
  20965. * allocating a large strm->input buffer and copying from it.
  20966. * (See also flush_pending()).
  20967. */
  20968. function read_buf(strm, buf, start, size) {
  20969. var len = strm.avail_in;
  20970. if (len > size) { len = size; }
  20971. if (len === 0) { return 0; }
  20972. strm.avail_in -= len;
  20973. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  20974. if (strm.state.wrap === 1) {
  20975. strm.adler = adler32(strm.adler, buf, len, start);
  20976. }
  20977. else if (strm.state.wrap === 2) {
  20978. strm.adler = crc32(strm.adler, buf, len, start);
  20979. }
  20980. strm.next_in += len;
  20981. strm.total_in += len;
  20982. return len;
  20983. }
  20984. /* ===========================================================================
  20985. * Set match_start to the longest match starting at the given string and
  20986. * return its length. Matches shorter or equal to prev_length are discarded,
  20987. * in which case the result is equal to prev_length and match_start is
  20988. * garbage.
  20989. * IN assertions: cur_match is the head of the hash chain for the current
  20990. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  20991. * OUT assertion: the match length is not greater than s->lookahead.
  20992. */
  20993. function longest_match(s, cur_match) {
  20994. var chain_length = s.max_chain_length; /* max hash chain length */
  20995. var scan = s.strstart; /* current string */
  20996. var match; /* matched string */
  20997. var len; /* length of current match */
  20998. var best_len = s.prev_length; /* best match length so far */
  20999. var nice_match = s.nice_match; /* stop if match long enough */
  21000. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  21001. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  21002. var _win = s.window; // shortcut
  21003. var wmask = s.w_mask;
  21004. var prev = s.prev;
  21005. /* Stop when cur_match becomes <= limit. To simplify the code,
  21006. * we prevent matches with the string of window index 0.
  21007. */
  21008. var strend = s.strstart + MAX_MATCH;
  21009. var scan_end1 = _win[scan + best_len - 1];
  21010. var scan_end = _win[scan + best_len];
  21011. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  21012. * It is easy to get rid of this optimization if necessary.
  21013. */
  21014. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  21015. /* Do not waste too much time if we already have a good match: */
  21016. if (s.prev_length >= s.good_match) {
  21017. chain_length >>= 2;
  21018. }
  21019. /* Do not look for matches beyond the end of the input. This is necessary
  21020. * to make deflate deterministic.
  21021. */
  21022. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  21023. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  21024. do {
  21025. // Assert(cur_match < s->strstart, "no future");
  21026. match = cur_match;
  21027. /* Skip to next match if the match length cannot increase
  21028. * or if the match length is less than 2. Note that the checks below
  21029. * for insufficient lookahead only occur occasionally for performance
  21030. * reasons. Therefore uninitialized memory will be accessed, and
  21031. * conditional jumps will be made that depend on those values.
  21032. * However the length of the match is limited to the lookahead, so
  21033. * the output of deflate is not affected by the uninitialized values.
  21034. */
  21035. if (_win[match + best_len] !== scan_end ||
  21036. _win[match + best_len - 1] !== scan_end1 ||
  21037. _win[match] !== _win[scan] ||
  21038. _win[++match] !== _win[scan + 1]) {
  21039. continue;
  21040. }
  21041. /* The check at best_len-1 can be removed because it will be made
  21042. * again later. (This heuristic is not always a win.)
  21043. * It is not necessary to compare scan[2] and match[2] since they
  21044. * are always equal when the other bytes match, given that
  21045. * the hash keys are equal and that HASH_BITS >= 8.
  21046. */
  21047. scan += 2;
  21048. match++;
  21049. // Assert(*scan == *match, "match[2]?");
  21050. /* We check for insufficient lookahead only every 8th comparison;
  21051. * the 256th check will be made at strstart+258.
  21052. */
  21053. do {
  21054. /*jshint noempty:false*/
  21055. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21056. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21057. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21058. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21059. scan < strend);
  21060. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  21061. len = MAX_MATCH - (strend - scan);
  21062. scan = strend - MAX_MATCH;
  21063. if (len > best_len) {
  21064. s.match_start = cur_match;
  21065. best_len = len;
  21066. if (len >= nice_match) {
  21067. break;
  21068. }
  21069. scan_end1 = _win[scan + best_len - 1];
  21070. scan_end = _win[scan + best_len];
  21071. }
  21072. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  21073. if (best_len <= s.lookahead) {
  21074. return best_len;
  21075. }
  21076. return s.lookahead;
  21077. }
  21078. /* ===========================================================================
  21079. * Fill the window when the lookahead becomes insufficient.
  21080. * Updates strstart and lookahead.
  21081. *
  21082. * IN assertion: lookahead < MIN_LOOKAHEAD
  21083. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  21084. * At least one byte has been read, or avail_in == 0; reads are
  21085. * performed for at least two bytes (required for the zip translate_eol
  21086. * option -- not supported here).
  21087. */
  21088. function fill_window(s) {
  21089. var _w_size = s.w_size;
  21090. var p, n, m, more, str;
  21091. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  21092. do {
  21093. more = s.window_size - s.lookahead - s.strstart;
  21094. // JS ints have 32 bit, block below not needed
  21095. /* Deal with !@#$% 64K limit: */
  21096. //if (sizeof(int) <= 2) {
  21097. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  21098. // more = wsize;
  21099. //
  21100. // } else if (more == (unsigned)(-1)) {
  21101. // /* Very unlikely, but possible on 16 bit machine if
  21102. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  21103. // */
  21104. // more--;
  21105. // }
  21106. //}
  21107. /* If the window is almost full and there is insufficient lookahead,
  21108. * move the upper half to the lower one to make room in the upper half.
  21109. */
  21110. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  21111. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  21112. s.match_start -= _w_size;
  21113. s.strstart -= _w_size;
  21114. /* we now have strstart >= MAX_DIST */
  21115. s.block_start -= _w_size;
  21116. /* Slide the hash table (could be avoided with 32 bit values
  21117. at the expense of memory usage). We slide even when level == 0
  21118. to keep the hash table consistent if we switch back to level > 0
  21119. later. (Using level 0 permanently is not an optimal usage of
  21120. zlib, so we don't care about this pathological case.)
  21121. */
  21122. n = s.hash_size;
  21123. p = n;
  21124. do {
  21125. m = s.head[--p];
  21126. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  21127. } while (--n);
  21128. n = _w_size;
  21129. p = n;
  21130. do {
  21131. m = s.prev[--p];
  21132. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  21133. /* If n is not on any hash chain, prev[n] is garbage but
  21134. * its value will never be used.
  21135. */
  21136. } while (--n);
  21137. more += _w_size;
  21138. }
  21139. if (s.strm.avail_in === 0) {
  21140. break;
  21141. }
  21142. /* If there was no sliding:
  21143. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  21144. * more == window_size - lookahead - strstart
  21145. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  21146. * => more >= window_size - 2*WSIZE + 2
  21147. * In the BIG_MEM or MMAP case (not yet supported),
  21148. * window_size == input_size + MIN_LOOKAHEAD &&
  21149. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  21150. * Otherwise, window_size == 2*WSIZE so more >= 2.
  21151. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  21152. */
  21153. //Assert(more >= 2, "more < 2");
  21154. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  21155. s.lookahead += n;
  21156. /* Initialize the hash value now that we have some input: */
  21157. if (s.lookahead + s.insert >= MIN_MATCH) {
  21158. str = s.strstart - s.insert;
  21159. s.ins_h = s.window[str];
  21160. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  21161. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  21162. //#if MIN_MATCH != 3
  21163. // Call update_hash() MIN_MATCH-3 more times
  21164. //#endif
  21165. while (s.insert) {
  21166. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  21167. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  21168. s.prev[str & s.w_mask] = s.head[s.ins_h];
  21169. s.head[s.ins_h] = str;
  21170. str++;
  21171. s.insert--;
  21172. if (s.lookahead + s.insert < MIN_MATCH) {
  21173. break;
  21174. }
  21175. }
  21176. }
  21177. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  21178. * but this is not important since only literal bytes will be emitted.
  21179. */
  21180. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  21181. /* If the WIN_INIT bytes after the end of the current data have never been
  21182. * written, then zero those bytes in order to avoid memory check reports of
  21183. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  21184. * the longest match routines. Update the high water mark for the next
  21185. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  21186. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  21187. */
  21188. // if (s.high_water < s.window_size) {
  21189. // var curr = s.strstart + s.lookahead;
  21190. // var init = 0;
  21191. //
  21192. // if (s.high_water < curr) {
  21193. // /* Previous high water mark below current data -- zero WIN_INIT
  21194. // * bytes or up to end of window, whichever is less.
  21195. // */
  21196. // init = s.window_size - curr;
  21197. // if (init > WIN_INIT)
  21198. // init = WIN_INIT;
  21199. // zmemzero(s->window + curr, (unsigned)init);
  21200. // s->high_water = curr + init;
  21201. // }
  21202. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  21203. // /* High water mark at or above current data, but below current data
  21204. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  21205. // * to end of window, whichever is less.
  21206. // */
  21207. // init = (ulg)curr + WIN_INIT - s->high_water;
  21208. // if (init > s->window_size - s->high_water)
  21209. // init = s->window_size - s->high_water;
  21210. // zmemzero(s->window + s->high_water, (unsigned)init);
  21211. // s->high_water += init;
  21212. // }
  21213. // }
  21214. //
  21215. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  21216. // "not enough room for search");
  21217. }
  21218. /* ===========================================================================
  21219. * Copy without compression as much as possible from the input stream, return
  21220. * the current block state.
  21221. * This function does not insert new strings in the dictionary since
  21222. * uncompressible data is probably not useful. This function is used
  21223. * only for the level=0 compression option.
  21224. * NOTE: this function should be optimized to avoid extra copying from
  21225. * window to pending_buf.
  21226. */
  21227. function deflate_stored(s, flush) {
  21228. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  21229. * to pending_buf_size, and each stored block has a 5 byte header:
  21230. */
  21231. var max_block_size = 0xffff;
  21232. if (max_block_size > s.pending_buf_size - 5) {
  21233. max_block_size = s.pending_buf_size - 5;
  21234. }
  21235. /* Copy as much as possible from input to output: */
  21236. for (;;) {
  21237. /* Fill the window as much as possible: */
  21238. if (s.lookahead <= 1) {
  21239. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  21240. // s->block_start >= (long)s->w_size, "slide too late");
  21241. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  21242. // s.block_start >= s.w_size)) {
  21243. // throw new Error("slide too late");
  21244. // }
  21245. fill_window(s);
  21246. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  21247. return BS_NEED_MORE;
  21248. }
  21249. if (s.lookahead === 0) {
  21250. break;
  21251. }
  21252. /* flush the current block */
  21253. }
  21254. //Assert(s->block_start >= 0L, "block gone");
  21255. // if (s.block_start < 0) throw new Error("block gone");
  21256. s.strstart += s.lookahead;
  21257. s.lookahead = 0;
  21258. /* Emit a stored block if pending_buf will be full: */
  21259. var max_start = s.block_start + max_block_size;
  21260. if (s.strstart === 0 || s.strstart >= max_start) {
  21261. /* strstart == 0 is possible when wraparound on 16-bit machine */
  21262. s.lookahead = s.strstart - max_start;
  21263. s.strstart = max_start;
  21264. /*** FLUSH_BLOCK(s, 0); ***/
  21265. flush_block_only(s, false);
  21266. if (s.strm.avail_out === 0) {
  21267. return BS_NEED_MORE;
  21268. }
  21269. /***/
  21270. }
  21271. /* Flush if we may have to slide, otherwise block_start may become
  21272. * negative and the data will be gone:
  21273. */
  21274. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  21275. /*** FLUSH_BLOCK(s, 0); ***/
  21276. flush_block_only(s, false);
  21277. if (s.strm.avail_out === 0) {
  21278. return BS_NEED_MORE;
  21279. }
  21280. /***/
  21281. }
  21282. }
  21283. s.insert = 0;
  21284. if (flush === Z_FINISH) {
  21285. /*** FLUSH_BLOCK(s, 1); ***/
  21286. flush_block_only(s, true);
  21287. if (s.strm.avail_out === 0) {
  21288. return BS_FINISH_STARTED;
  21289. }
  21290. /***/
  21291. return BS_FINISH_DONE;
  21292. }
  21293. if (s.strstart > s.block_start) {
  21294. /*** FLUSH_BLOCK(s, 0); ***/
  21295. flush_block_only(s, false);
  21296. if (s.strm.avail_out === 0) {
  21297. return BS_NEED_MORE;
  21298. }
  21299. /***/
  21300. }
  21301. return BS_NEED_MORE;
  21302. }
  21303. /* ===========================================================================
  21304. * Compress as much as possible from the input stream, return the current
  21305. * block state.
  21306. * This function does not perform lazy evaluation of matches and inserts
  21307. * new strings in the dictionary only for unmatched strings or for short
  21308. * matches. It is used only for the fast compression options.
  21309. */
  21310. function deflate_fast(s, flush) {
  21311. var hash_head; /* head of the hash chain */
  21312. var bflush; /* set if current block must be flushed */
  21313. for (;;) {
  21314. /* Make sure that we always have enough lookahead, except
  21315. * at the end of the input file. We need MAX_MATCH bytes
  21316. * for the next match, plus MIN_MATCH bytes to insert the
  21317. * string following the next match.
  21318. */
  21319. if (s.lookahead < MIN_LOOKAHEAD) {
  21320. fill_window(s);
  21321. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21322. return BS_NEED_MORE;
  21323. }
  21324. if (s.lookahead === 0) {
  21325. break; /* flush the current block */
  21326. }
  21327. }
  21328. /* Insert the string window[strstart .. strstart+2] in the
  21329. * dictionary, and set hash_head to the head of the hash chain:
  21330. */
  21331. hash_head = 0/*NIL*/;
  21332. if (s.lookahead >= MIN_MATCH) {
  21333. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21334. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21335. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21336. s.head[s.ins_h] = s.strstart;
  21337. /***/
  21338. }
  21339. /* Find the longest match, discarding those <= prev_length.
  21340. * At this point we have always match_length < MIN_MATCH
  21341. */
  21342. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  21343. /* To simplify the code, we prevent matches with the string
  21344. * of window index 0 (in particular we have to avoid a match
  21345. * of the string with itself at the start of the input file).
  21346. */
  21347. s.match_length = longest_match(s, hash_head);
  21348. /* longest_match() sets match_start */
  21349. }
  21350. if (s.match_length >= MIN_MATCH) {
  21351. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  21352. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  21353. s.match_length - MIN_MATCH, bflush); ***/
  21354. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  21355. s.lookahead -= s.match_length;
  21356. /* Insert new strings in the hash table only if the match length
  21357. * is not too large. This saves time but degrades compression.
  21358. */
  21359. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  21360. s.match_length--; /* string at strstart already in table */
  21361. do {
  21362. s.strstart++;
  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. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  21369. * always MIN_MATCH bytes ahead.
  21370. */
  21371. } while (--s.match_length !== 0);
  21372. s.strstart++;
  21373. } else
  21374. {
  21375. s.strstart += s.match_length;
  21376. s.match_length = 0;
  21377. s.ins_h = s.window[s.strstart];
  21378. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  21379. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  21380. //#if MIN_MATCH != 3
  21381. // Call UPDATE_HASH() MIN_MATCH-3 more times
  21382. //#endif
  21383. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  21384. * matter since it will be recomputed at next deflate call.
  21385. */
  21386. }
  21387. } else {
  21388. /* No match, output a literal byte */
  21389. //Tracevv((stderr,"%c", s.window[s.strstart]));
  21390. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21391. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21392. s.lookahead--;
  21393. s.strstart++;
  21394. }
  21395. if (bflush) {
  21396. /*** FLUSH_BLOCK(s, 0); ***/
  21397. flush_block_only(s, false);
  21398. if (s.strm.avail_out === 0) {
  21399. return BS_NEED_MORE;
  21400. }
  21401. /***/
  21402. }
  21403. }
  21404. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  21405. if (flush === Z_FINISH) {
  21406. /*** FLUSH_BLOCK(s, 1); ***/
  21407. flush_block_only(s, true);
  21408. if (s.strm.avail_out === 0) {
  21409. return BS_FINISH_STARTED;
  21410. }
  21411. /***/
  21412. return BS_FINISH_DONE;
  21413. }
  21414. if (s.last_lit) {
  21415. /*** FLUSH_BLOCK(s, 0); ***/
  21416. flush_block_only(s, false);
  21417. if (s.strm.avail_out === 0) {
  21418. return BS_NEED_MORE;
  21419. }
  21420. /***/
  21421. }
  21422. return BS_BLOCK_DONE;
  21423. }
  21424. /* ===========================================================================
  21425. * Same as above, but achieves better compression. We use a lazy
  21426. * evaluation for matches: a match is finally adopted only if there is
  21427. * no better match at the next window position.
  21428. */
  21429. function deflate_slow(s, flush) {
  21430. var hash_head; /* head of hash chain */
  21431. var bflush; /* set if current block must be flushed */
  21432. var max_insert;
  21433. /* Process the input block. */
  21434. for (;;) {
  21435. /* Make sure that we always have enough lookahead, except
  21436. * at the end of the input file. We need MAX_MATCH bytes
  21437. * for the next match, plus MIN_MATCH bytes to insert the
  21438. * string following the next match.
  21439. */
  21440. if (s.lookahead < MIN_LOOKAHEAD) {
  21441. fill_window(s);
  21442. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21443. return BS_NEED_MORE;
  21444. }
  21445. if (s.lookahead === 0) { break; } /* flush the current block */
  21446. }
  21447. /* Insert the string window[strstart .. strstart+2] in the
  21448. * dictionary, and set hash_head to the head of the hash chain:
  21449. */
  21450. hash_head = 0/*NIL*/;
  21451. if (s.lookahead >= MIN_MATCH) {
  21452. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21453. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21454. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21455. s.head[s.ins_h] = s.strstart;
  21456. /***/
  21457. }
  21458. /* Find the longest match, discarding those <= prev_length.
  21459. */
  21460. s.prev_length = s.match_length;
  21461. s.prev_match = s.match_start;
  21462. s.match_length = MIN_MATCH-1;
  21463. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  21464. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  21465. /* To simplify the code, we prevent matches with the string
  21466. * of window index 0 (in particular we have to avoid a match
  21467. * of the string with itself at the start of the input file).
  21468. */
  21469. s.match_length = longest_match(s, hash_head);
  21470. /* longest_match() sets match_start */
  21471. if (s.match_length <= 5 &&
  21472. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  21473. /* If prev_match is also MIN_MATCH, match_start is garbage
  21474. * but we will ignore the current match anyway.
  21475. */
  21476. s.match_length = MIN_MATCH-1;
  21477. }
  21478. }
  21479. /* If there was a match at the previous step and the current
  21480. * match is not better, output the previous match:
  21481. */
  21482. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  21483. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  21484. /* Do not insert strings in hash table beyond this. */
  21485. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  21486. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  21487. s.prev_length - MIN_MATCH, bflush);***/
  21488. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  21489. /* Insert in hash table all strings up to the end of the match.
  21490. * strstart-1 and strstart are already inserted. If there is not
  21491. * enough lookahead, the last two strings are not inserted in
  21492. * the hash table.
  21493. */
  21494. s.lookahead -= s.prev_length-1;
  21495. s.prev_length -= 2;
  21496. do {
  21497. if (++s.strstart <= max_insert) {
  21498. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21499. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21500. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21501. s.head[s.ins_h] = s.strstart;
  21502. /***/
  21503. }
  21504. } while (--s.prev_length !== 0);
  21505. s.match_available = 0;
  21506. s.match_length = MIN_MATCH-1;
  21507. s.strstart++;
  21508. if (bflush) {
  21509. /*** FLUSH_BLOCK(s, 0); ***/
  21510. flush_block_only(s, false);
  21511. if (s.strm.avail_out === 0) {
  21512. return BS_NEED_MORE;
  21513. }
  21514. /***/
  21515. }
  21516. } else if (s.match_available) {
  21517. /* If there was no match at the previous position, output a
  21518. * single literal. If there was a match but the current match
  21519. * is longer, truncate the previous match to a single literal.
  21520. */
  21521. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21522. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21523. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21524. if (bflush) {
  21525. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  21526. flush_block_only(s, false);
  21527. /***/
  21528. }
  21529. s.strstart++;
  21530. s.lookahead--;
  21531. if (s.strm.avail_out === 0) {
  21532. return BS_NEED_MORE;
  21533. }
  21534. } else {
  21535. /* There is no previous match to compare with, wait for
  21536. * the next step to decide.
  21537. */
  21538. s.match_available = 1;
  21539. s.strstart++;
  21540. s.lookahead--;
  21541. }
  21542. }
  21543. //Assert (flush != Z_NO_FLUSH, "no flush?");
  21544. if (s.match_available) {
  21545. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21546. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21547. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21548. s.match_available = 0;
  21549. }
  21550. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  21551. if (flush === Z_FINISH) {
  21552. /*** FLUSH_BLOCK(s, 1); ***/
  21553. flush_block_only(s, true);
  21554. if (s.strm.avail_out === 0) {
  21555. return BS_FINISH_STARTED;
  21556. }
  21557. /***/
  21558. return BS_FINISH_DONE;
  21559. }
  21560. if (s.last_lit) {
  21561. /*** FLUSH_BLOCK(s, 0); ***/
  21562. flush_block_only(s, false);
  21563. if (s.strm.avail_out === 0) {
  21564. return BS_NEED_MORE;
  21565. }
  21566. /***/
  21567. }
  21568. return BS_BLOCK_DONE;
  21569. }
  21570. /* ===========================================================================
  21571. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  21572. * one. Do not maintain a hash table. (It will be regenerated if this run of
  21573. * deflate switches away from Z_RLE.)
  21574. */
  21575. function deflate_rle(s, flush) {
  21576. var bflush; /* set if current block must be flushed */
  21577. var prev; /* byte at distance one to match */
  21578. var scan, strend; /* scan goes up to strend for length of run */
  21579. var _win = s.window;
  21580. for (;;) {
  21581. /* Make sure that we always have enough lookahead, except
  21582. * at the end of the input file. We need MAX_MATCH bytes
  21583. * for the longest run, plus one for the unrolled loop.
  21584. */
  21585. if (s.lookahead <= MAX_MATCH) {
  21586. fill_window(s);
  21587. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  21588. return BS_NEED_MORE;
  21589. }
  21590. if (s.lookahead === 0) { break; } /* flush the current block */
  21591. }
  21592. /* See how many times the previous byte repeats */
  21593. s.match_length = 0;
  21594. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  21595. scan = s.strstart - 1;
  21596. prev = _win[scan];
  21597. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  21598. strend = s.strstart + MAX_MATCH;
  21599. do {
  21600. /*jshint noempty:false*/
  21601. } while (prev === _win[++scan] && prev === _win[++scan] &&
  21602. prev === _win[++scan] && prev === _win[++scan] &&
  21603. prev === _win[++scan] && prev === _win[++scan] &&
  21604. prev === _win[++scan] && prev === _win[++scan] &&
  21605. scan < strend);
  21606. s.match_length = MAX_MATCH - (strend - scan);
  21607. if (s.match_length > s.lookahead) {
  21608. s.match_length = s.lookahead;
  21609. }
  21610. }
  21611. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  21612. }
  21613. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  21614. if (s.match_length >= MIN_MATCH) {
  21615. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  21616. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  21617. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  21618. s.lookahead -= s.match_length;
  21619. s.strstart += s.match_length;
  21620. s.match_length = 0;
  21621. } else {
  21622. /* No match, output a literal byte */
  21623. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21624. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21625. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21626. s.lookahead--;
  21627. s.strstart++;
  21628. }
  21629. if (bflush) {
  21630. /*** FLUSH_BLOCK(s, 0); ***/
  21631. flush_block_only(s, false);
  21632. if (s.strm.avail_out === 0) {
  21633. return BS_NEED_MORE;
  21634. }
  21635. /***/
  21636. }
  21637. }
  21638. s.insert = 0;
  21639. if (flush === Z_FINISH) {
  21640. /*** FLUSH_BLOCK(s, 1); ***/
  21641. flush_block_only(s, true);
  21642. if (s.strm.avail_out === 0) {
  21643. return BS_FINISH_STARTED;
  21644. }
  21645. /***/
  21646. return BS_FINISH_DONE;
  21647. }
  21648. if (s.last_lit) {
  21649. /*** FLUSH_BLOCK(s, 0); ***/
  21650. flush_block_only(s, false);
  21651. if (s.strm.avail_out === 0) {
  21652. return BS_NEED_MORE;
  21653. }
  21654. /***/
  21655. }
  21656. return BS_BLOCK_DONE;
  21657. }
  21658. /* ===========================================================================
  21659. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  21660. * (It will be regenerated if this run of deflate switches away from Huffman.)
  21661. */
  21662. function deflate_huff(s, flush) {
  21663. var bflush; /* set if current block must be flushed */
  21664. for (;;) {
  21665. /* Make sure that we have a literal to write. */
  21666. if (s.lookahead === 0) {
  21667. fill_window(s);
  21668. if (s.lookahead === 0) {
  21669. if (flush === Z_NO_FLUSH) {
  21670. return BS_NEED_MORE;
  21671. }
  21672. break; /* flush the current block */
  21673. }
  21674. }
  21675. /* Output a literal byte */
  21676. s.match_length = 0;
  21677. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21678. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21679. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21680. s.lookahead--;
  21681. s.strstart++;
  21682. if (bflush) {
  21683. /*** FLUSH_BLOCK(s, 0); ***/
  21684. flush_block_only(s, false);
  21685. if (s.strm.avail_out === 0) {
  21686. return BS_NEED_MORE;
  21687. }
  21688. /***/
  21689. }
  21690. }
  21691. s.insert = 0;
  21692. if (flush === Z_FINISH) {
  21693. /*** FLUSH_BLOCK(s, 1); ***/
  21694. flush_block_only(s, true);
  21695. if (s.strm.avail_out === 0) {
  21696. return BS_FINISH_STARTED;
  21697. }
  21698. /***/
  21699. return BS_FINISH_DONE;
  21700. }
  21701. if (s.last_lit) {
  21702. /*** FLUSH_BLOCK(s, 0); ***/
  21703. flush_block_only(s, false);
  21704. if (s.strm.avail_out === 0) {
  21705. return BS_NEED_MORE;
  21706. }
  21707. /***/
  21708. }
  21709. return BS_BLOCK_DONE;
  21710. }
  21711. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  21712. * the desired pack level (0..9). The values given below have been tuned to
  21713. * exclude worst case performance for pathological files. Better values may be
  21714. * found for specific files.
  21715. */
  21716. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  21717. this.good_length = good_length;
  21718. this.max_lazy = max_lazy;
  21719. this.nice_length = nice_length;
  21720. this.max_chain = max_chain;
  21721. this.func = func;
  21722. };
  21723. var configuration_table;
  21724. configuration_table = [
  21725. /* good lazy nice chain */
  21726. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  21727. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  21728. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  21729. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  21730. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  21731. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  21732. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  21733. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  21734. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  21735. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  21736. ];
  21737. /* ===========================================================================
  21738. * Initialize the "longest match" routines for a new zlib stream
  21739. */
  21740. function lm_init(s) {
  21741. s.window_size = 2 * s.w_size;
  21742. /*** CLEAR_HASH(s); ***/
  21743. zero(s.head); // Fill with NIL (= 0);
  21744. /* Set the default configuration parameters:
  21745. */
  21746. s.max_lazy_match = configuration_table[s.level].max_lazy;
  21747. s.good_match = configuration_table[s.level].good_length;
  21748. s.nice_match = configuration_table[s.level].nice_length;
  21749. s.max_chain_length = configuration_table[s.level].max_chain;
  21750. s.strstart = 0;
  21751. s.block_start = 0;
  21752. s.lookahead = 0;
  21753. s.insert = 0;
  21754. s.match_length = s.prev_length = MIN_MATCH - 1;
  21755. s.match_available = 0;
  21756. s.ins_h = 0;
  21757. }
  21758. function DeflateState() {
  21759. this.strm = null; /* pointer back to this zlib stream */
  21760. this.status = 0; /* as the name implies */
  21761. this.pending_buf = null; /* output still pending */
  21762. this.pending_buf_size = 0; /* size of pending_buf */
  21763. this.pending_out = 0; /* next pending byte to output to the stream */
  21764. this.pending = 0; /* nb of bytes in the pending buffer */
  21765. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21766. this.gzhead = null; /* gzip header information to write */
  21767. this.gzindex = 0; /* where in extra, name, or comment */
  21768. this.method = Z_DEFLATED; /* can only be DEFLATED */
  21769. this.last_flush = -1; /* value of flush param for previous deflate call */
  21770. this.w_size = 0; /* LZ77 window size (32K by default) */
  21771. this.w_bits = 0; /* log2(w_size) (8..16) */
  21772. this.w_mask = 0; /* w_size - 1 */
  21773. this.window = null;
  21774. /* Sliding window. Input bytes are read into the second half of the window,
  21775. * and move to the first half later to keep a dictionary of at least wSize
  21776. * bytes. With this organization, matches are limited to a distance of
  21777. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  21778. * performed with a length multiple of the block size.
  21779. */
  21780. this.window_size = 0;
  21781. /* Actual size of window: 2*wSize, except when the user input buffer
  21782. * is directly used as sliding window.
  21783. */
  21784. this.prev = null;
  21785. /* Link to older string with same hash index. To limit the size of this
  21786. * array to 64K, this link is maintained only for the last 32K strings.
  21787. * An index in this array is thus a window index modulo 32K.
  21788. */
  21789. this.head = null; /* Heads of the hash chains or NIL. */
  21790. this.ins_h = 0; /* hash index of string to be inserted */
  21791. this.hash_size = 0; /* number of elements in hash table */
  21792. this.hash_bits = 0; /* log2(hash_size) */
  21793. this.hash_mask = 0; /* hash_size-1 */
  21794. this.hash_shift = 0;
  21795. /* Number of bits by which ins_h must be shifted at each input
  21796. * step. It must be such that after MIN_MATCH steps, the oldest
  21797. * byte no longer takes part in the hash key, that is:
  21798. * hash_shift * MIN_MATCH >= hash_bits
  21799. */
  21800. this.block_start = 0;
  21801. /* Window position at the beginning of the current output block. Gets
  21802. * negative when the window is moved backwards.
  21803. */
  21804. this.match_length = 0; /* length of best match */
  21805. this.prev_match = 0; /* previous match */
  21806. this.match_available = 0; /* set if previous match exists */
  21807. this.strstart = 0; /* start of string to insert */
  21808. this.match_start = 0; /* start of matching string */
  21809. this.lookahead = 0; /* number of valid bytes ahead in window */
  21810. this.prev_length = 0;
  21811. /* Length of the best match at previous step. Matches not greater than this
  21812. * are discarded. This is used in the lazy match evaluation.
  21813. */
  21814. this.max_chain_length = 0;
  21815. /* To speed up deflation, hash chains are never searched beyond this
  21816. * length. A higher limit improves compression ratio but degrades the
  21817. * speed.
  21818. */
  21819. this.max_lazy_match = 0;
  21820. /* Attempt to find a better match only when the current match is strictly
  21821. * smaller than this value. This mechanism is used only for compression
  21822. * levels >= 4.
  21823. */
  21824. // That's alias to max_lazy_match, don't use directly
  21825. //this.max_insert_length = 0;
  21826. /* Insert new strings in the hash table only if the match length is not
  21827. * greater than this length. This saves time but degrades compression.
  21828. * max_insert_length is used only for compression levels <= 3.
  21829. */
  21830. this.level = 0; /* compression level (1..9) */
  21831. this.strategy = 0; /* favor or force Huffman coding*/
  21832. this.good_match = 0;
  21833. /* Use a faster search when the previous match is longer than this */
  21834. this.nice_match = 0; /* Stop searching when current match exceeds this */
  21835. /* used by trees.c: */
  21836. /* Didn't use ct_data typedef below to suppress compiler warning */
  21837. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  21838. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  21839. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  21840. // Use flat array of DOUBLE size, with interleaved fata,
  21841. // because JS does not support effective
  21842. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  21843. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  21844. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  21845. zero(this.dyn_ltree);
  21846. zero(this.dyn_dtree);
  21847. zero(this.bl_tree);
  21848. this.l_desc = null; /* desc. for literal tree */
  21849. this.d_desc = null; /* desc. for distance tree */
  21850. this.bl_desc = null; /* desc. for bit length tree */
  21851. //ush bl_count[MAX_BITS+1];
  21852. this.bl_count = new utils.Buf16(MAX_BITS+1);
  21853. /* number of codes at each bit length for an optimal tree */
  21854. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  21855. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  21856. zero(this.heap);
  21857. this.heap_len = 0; /* number of elements in the heap */
  21858. this.heap_max = 0; /* element of largest frequency */
  21859. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  21860. * The same heap array is used to build all trees.
  21861. */
  21862. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  21863. zero(this.depth);
  21864. /* Depth of each subtree used as tie breaker for trees of equal frequency
  21865. */
  21866. this.l_buf = 0; /* buffer index for literals or lengths */
  21867. this.lit_bufsize = 0;
  21868. /* Size of match buffer for literals/lengths. There are 4 reasons for
  21869. * limiting lit_bufsize to 64K:
  21870. * - frequencies can be kept in 16 bit counters
  21871. * - if compression is not successful for the first block, all input
  21872. * data is still in the window so we can still emit a stored block even
  21873. * when input comes from standard input. (This can also be done for
  21874. * all blocks if lit_bufsize is not greater than 32K.)
  21875. * - if compression is not successful for a file smaller than 64K, we can
  21876. * even emit a stored file instead of a stored block (saving 5 bytes).
  21877. * This is applicable only for zip (not gzip or zlib).
  21878. * - creating new Huffman trees less frequently may not provide fast
  21879. * adaptation to changes in the input data statistics. (Take for
  21880. * example a binary file with poorly compressible code followed by
  21881. * a highly compressible string table.) Smaller buffer sizes give
  21882. * fast adaptation but have of course the overhead of transmitting
  21883. * trees more frequently.
  21884. * - I can't count above 4
  21885. */
  21886. this.last_lit = 0; /* running index in l_buf */
  21887. this.d_buf = 0;
  21888. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  21889. * the same number of elements. To use different lengths, an extra flag
  21890. * array would be necessary.
  21891. */
  21892. this.opt_len = 0; /* bit length of current block with optimal trees */
  21893. this.static_len = 0; /* bit length of current block with static trees */
  21894. this.matches = 0; /* number of string matches in current block */
  21895. this.insert = 0; /* bytes at end of window left to insert */
  21896. this.bi_buf = 0;
  21897. /* Output buffer. bits are inserted starting at the bottom (least
  21898. * significant bits).
  21899. */
  21900. this.bi_valid = 0;
  21901. /* Number of valid bits in bi_buf. All bits above the last valid bit
  21902. * are always zero.
  21903. */
  21904. // Used for window memory init. We safely ignore it for JS. That makes
  21905. // sense only for pointers and memory check tools.
  21906. //this.high_water = 0;
  21907. /* High water mark offset in window for initialized bytes -- bytes above
  21908. * this are set to zero in order to avoid memory check warnings when
  21909. * longest match routines access bytes past the input. This is then
  21910. * updated to the new high water mark.
  21911. */
  21912. }
  21913. function deflateResetKeep(strm) {
  21914. var s;
  21915. if (!strm || !strm.state) {
  21916. return err(strm, Z_STREAM_ERROR);
  21917. }
  21918. strm.total_in = strm.total_out = 0;
  21919. strm.data_type = Z_UNKNOWN;
  21920. s = strm.state;
  21921. s.pending = 0;
  21922. s.pending_out = 0;
  21923. if (s.wrap < 0) {
  21924. s.wrap = -s.wrap;
  21925. /* was made negative by deflate(..., Z_FINISH); */
  21926. }
  21927. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  21928. strm.adler = (s.wrap === 2) ?
  21929. 0 // crc32(0, Z_NULL, 0)
  21930. :
  21931. 1; // adler32(0, Z_NULL, 0)
  21932. s.last_flush = Z_NO_FLUSH;
  21933. trees._tr_init(s);
  21934. return Z_OK;
  21935. }
  21936. function deflateReset(strm) {
  21937. var ret = deflateResetKeep(strm);
  21938. if (ret === Z_OK) {
  21939. lm_init(strm.state);
  21940. }
  21941. return ret;
  21942. }
  21943. function deflateSetHeader(strm, head) {
  21944. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21945. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  21946. strm.state.gzhead = head;
  21947. return Z_OK;
  21948. }
  21949. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  21950. if (!strm) { // === Z_NULL
  21951. return Z_STREAM_ERROR;
  21952. }
  21953. var wrap = 1;
  21954. if (level === Z_DEFAULT_COMPRESSION) {
  21955. level = 6;
  21956. }
  21957. if (windowBits < 0) { /* suppress zlib wrapper */
  21958. wrap = 0;
  21959. windowBits = -windowBits;
  21960. }
  21961. else if (windowBits > 15) {
  21962. wrap = 2; /* write gzip wrapper instead */
  21963. windowBits -= 16;
  21964. }
  21965. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  21966. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  21967. strategy < 0 || strategy > Z_FIXED) {
  21968. return err(strm, Z_STREAM_ERROR);
  21969. }
  21970. if (windowBits === 8) {
  21971. windowBits = 9;
  21972. }
  21973. /* until 256-byte window bug fixed */
  21974. var s = new DeflateState();
  21975. strm.state = s;
  21976. s.strm = strm;
  21977. s.wrap = wrap;
  21978. s.gzhead = null;
  21979. s.w_bits = windowBits;
  21980. s.w_size = 1 << s.w_bits;
  21981. s.w_mask = s.w_size - 1;
  21982. s.hash_bits = memLevel + 7;
  21983. s.hash_size = 1 << s.hash_bits;
  21984. s.hash_mask = s.hash_size - 1;
  21985. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  21986. s.window = new utils.Buf8(s.w_size * 2);
  21987. s.head = new utils.Buf16(s.hash_size);
  21988. s.prev = new utils.Buf16(s.w_size);
  21989. // Don't need mem init magic for JS.
  21990. //s.high_water = 0; /* nothing written to s->window yet */
  21991. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  21992. s.pending_buf_size = s.lit_bufsize * 4;
  21993. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  21994. s.d_buf = s.lit_bufsize >> 1;
  21995. s.l_buf = (1 + 2) * s.lit_bufsize;
  21996. s.level = level;
  21997. s.strategy = strategy;
  21998. s.method = method;
  21999. return deflateReset(strm);
  22000. }
  22001. function deflateInit(strm, level) {
  22002. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  22003. }
  22004. function deflate(strm, flush) {
  22005. var old_flush, s;
  22006. var beg, val; // for gzip header write only
  22007. if (!strm || !strm.state ||
  22008. flush > Z_BLOCK || flush < 0) {
  22009. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  22010. }
  22011. s = strm.state;
  22012. if (!strm.output ||
  22013. (!strm.input && strm.avail_in !== 0) ||
  22014. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  22015. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  22016. }
  22017. s.strm = strm; /* just in case */
  22018. old_flush = s.last_flush;
  22019. s.last_flush = flush;
  22020. /* Write the header */
  22021. if (s.status === INIT_STATE) {
  22022. if (s.wrap === 2) { // GZIP header
  22023. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  22024. put_byte(s, 31);
  22025. put_byte(s, 139);
  22026. put_byte(s, 8);
  22027. if (!s.gzhead) { // s->gzhead == Z_NULL
  22028. put_byte(s, 0);
  22029. put_byte(s, 0);
  22030. put_byte(s, 0);
  22031. put_byte(s, 0);
  22032. put_byte(s, 0);
  22033. put_byte(s, s.level === 9 ? 2 :
  22034. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  22035. 4 : 0));
  22036. put_byte(s, OS_CODE);
  22037. s.status = BUSY_STATE;
  22038. }
  22039. else {
  22040. put_byte(s, (s.gzhead.text ? 1 : 0) +
  22041. (s.gzhead.hcrc ? 2 : 0) +
  22042. (!s.gzhead.extra ? 0 : 4) +
  22043. (!s.gzhead.name ? 0 : 8) +
  22044. (!s.gzhead.comment ? 0 : 16)
  22045. );
  22046. put_byte(s, s.gzhead.time & 0xff);
  22047. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  22048. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  22049. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  22050. put_byte(s, s.level === 9 ? 2 :
  22051. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  22052. 4 : 0));
  22053. put_byte(s, s.gzhead.os & 0xff);
  22054. if (s.gzhead.extra && s.gzhead.extra.length) {
  22055. put_byte(s, s.gzhead.extra.length & 0xff);
  22056. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  22057. }
  22058. if (s.gzhead.hcrc) {
  22059. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  22060. }
  22061. s.gzindex = 0;
  22062. s.status = EXTRA_STATE;
  22063. }
  22064. }
  22065. else // DEFLATE header
  22066. {
  22067. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  22068. var level_flags = -1;
  22069. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  22070. level_flags = 0;
  22071. } else if (s.level < 6) {
  22072. level_flags = 1;
  22073. } else if (s.level === 6) {
  22074. level_flags = 2;
  22075. } else {
  22076. level_flags = 3;
  22077. }
  22078. header |= (level_flags << 6);
  22079. if (s.strstart !== 0) { header |= PRESET_DICT; }
  22080. header += 31 - (header % 31);
  22081. s.status = BUSY_STATE;
  22082. putShortMSB(s, header);
  22083. /* Save the adler32 of the preset dictionary: */
  22084. if (s.strstart !== 0) {
  22085. putShortMSB(s, strm.adler >>> 16);
  22086. putShortMSB(s, strm.adler & 0xffff);
  22087. }
  22088. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  22089. }
  22090. }
  22091. //#ifdef GZIP
  22092. if (s.status === EXTRA_STATE) {
  22093. if (s.gzhead.extra/* != Z_NULL*/) {
  22094. beg = s.pending; /* start of bytes to update crc */
  22095. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  22096. if (s.pending === s.pending_buf_size) {
  22097. if (s.gzhead.hcrc && s.pending > beg) {
  22098. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22099. }
  22100. flush_pending(strm);
  22101. beg = s.pending;
  22102. if (s.pending === s.pending_buf_size) {
  22103. break;
  22104. }
  22105. }
  22106. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  22107. s.gzindex++;
  22108. }
  22109. if (s.gzhead.hcrc && s.pending > beg) {
  22110. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22111. }
  22112. if (s.gzindex === s.gzhead.extra.length) {
  22113. s.gzindex = 0;
  22114. s.status = NAME_STATE;
  22115. }
  22116. }
  22117. else {
  22118. s.status = NAME_STATE;
  22119. }
  22120. }
  22121. if (s.status === NAME_STATE) {
  22122. if (s.gzhead.name/* != Z_NULL*/) {
  22123. beg = s.pending; /* start of bytes to update crc */
  22124. //int val;
  22125. do {
  22126. if (s.pending === s.pending_buf_size) {
  22127. if (s.gzhead.hcrc && s.pending > beg) {
  22128. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22129. }
  22130. flush_pending(strm);
  22131. beg = s.pending;
  22132. if (s.pending === s.pending_buf_size) {
  22133. val = 1;
  22134. break;
  22135. }
  22136. }
  22137. // JS specific: little magic to add zero terminator to end of string
  22138. if (s.gzindex < s.gzhead.name.length) {
  22139. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  22140. } else {
  22141. val = 0;
  22142. }
  22143. put_byte(s, val);
  22144. } while (val !== 0);
  22145. if (s.gzhead.hcrc && s.pending > beg) {
  22146. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22147. }
  22148. if (val === 0) {
  22149. s.gzindex = 0;
  22150. s.status = COMMENT_STATE;
  22151. }
  22152. }
  22153. else {
  22154. s.status = COMMENT_STATE;
  22155. }
  22156. }
  22157. if (s.status === COMMENT_STATE) {
  22158. if (s.gzhead.comment/* != Z_NULL*/) {
  22159. beg = s.pending; /* start of bytes to update crc */
  22160. //int val;
  22161. do {
  22162. if (s.pending === s.pending_buf_size) {
  22163. if (s.gzhead.hcrc && s.pending > beg) {
  22164. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22165. }
  22166. flush_pending(strm);
  22167. beg = s.pending;
  22168. if (s.pending === s.pending_buf_size) {
  22169. val = 1;
  22170. break;
  22171. }
  22172. }
  22173. // JS specific: little magic to add zero terminator to end of string
  22174. if (s.gzindex < s.gzhead.comment.length) {
  22175. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  22176. } else {
  22177. val = 0;
  22178. }
  22179. put_byte(s, val);
  22180. } while (val !== 0);
  22181. if (s.gzhead.hcrc && s.pending > beg) {
  22182. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22183. }
  22184. if (val === 0) {
  22185. s.status = HCRC_STATE;
  22186. }
  22187. }
  22188. else {
  22189. s.status = HCRC_STATE;
  22190. }
  22191. }
  22192. if (s.status === HCRC_STATE) {
  22193. if (s.gzhead.hcrc) {
  22194. if (s.pending + 2 > s.pending_buf_size) {
  22195. flush_pending(strm);
  22196. }
  22197. if (s.pending + 2 <= s.pending_buf_size) {
  22198. put_byte(s, strm.adler & 0xff);
  22199. put_byte(s, (strm.adler >> 8) & 0xff);
  22200. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  22201. s.status = BUSY_STATE;
  22202. }
  22203. }
  22204. else {
  22205. s.status = BUSY_STATE;
  22206. }
  22207. }
  22208. //#endif
  22209. /* Flush as much pending output as possible */
  22210. if (s.pending !== 0) {
  22211. flush_pending(strm);
  22212. if (strm.avail_out === 0) {
  22213. /* Since avail_out is 0, deflate will be called again with
  22214. * more output space, but possibly with both pending and
  22215. * avail_in equal to zero. There won't be anything to do,
  22216. * but this is not an error situation so make sure we
  22217. * return OK instead of BUF_ERROR at next call of deflate:
  22218. */
  22219. s.last_flush = -1;
  22220. return Z_OK;
  22221. }
  22222. /* Make sure there is something to do and avoid duplicate consecutive
  22223. * flushes. For repeated and useless calls with Z_FINISH, we keep
  22224. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  22225. */
  22226. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  22227. flush !== Z_FINISH) {
  22228. return err(strm, Z_BUF_ERROR);
  22229. }
  22230. /* User must not provide more input after the first FINISH: */
  22231. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  22232. return err(strm, Z_BUF_ERROR);
  22233. }
  22234. /* Start a new block or continue the current one.
  22235. */
  22236. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  22237. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  22238. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  22239. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  22240. configuration_table[s.level].func(s, flush));
  22241. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  22242. s.status = FINISH_STATE;
  22243. }
  22244. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  22245. if (strm.avail_out === 0) {
  22246. s.last_flush = -1;
  22247. /* avoid BUF_ERROR next call, see above */
  22248. }
  22249. return Z_OK;
  22250. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  22251. * of deflate should use the same flush parameter to make sure
  22252. * that the flush is complete. So we don't have to output an
  22253. * empty block here, this will be done at next call. This also
  22254. * ensures that for a very small output buffer, we emit at most
  22255. * one empty block.
  22256. */
  22257. }
  22258. if (bstate === BS_BLOCK_DONE) {
  22259. if (flush === Z_PARTIAL_FLUSH) {
  22260. trees._tr_align(s);
  22261. }
  22262. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  22263. trees._tr_stored_block(s, 0, 0, false);
  22264. /* For a full flush, this empty block will be recognized
  22265. * as a special marker by inflate_sync().
  22266. */
  22267. if (flush === Z_FULL_FLUSH) {
  22268. /*** CLEAR_HASH(s); ***/ /* forget history */
  22269. zero(s.head); // Fill with NIL (= 0);
  22270. if (s.lookahead === 0) {
  22271. s.strstart = 0;
  22272. s.block_start = 0;
  22273. s.insert = 0;
  22274. }
  22275. }
  22276. }
  22277. flush_pending(strm);
  22278. if (strm.avail_out === 0) {
  22279. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  22280. return Z_OK;
  22281. }
  22282. }
  22283. }
  22284. //Assert(strm->avail_out > 0, "bug2");
  22285. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  22286. if (flush !== Z_FINISH) { return Z_OK; }
  22287. if (s.wrap <= 0) { return Z_STREAM_END; }
  22288. /* Write the trailer */
  22289. if (s.wrap === 2) {
  22290. put_byte(s, strm.adler & 0xff);
  22291. put_byte(s, (strm.adler >> 8) & 0xff);
  22292. put_byte(s, (strm.adler >> 16) & 0xff);
  22293. put_byte(s, (strm.adler >> 24) & 0xff);
  22294. put_byte(s, strm.total_in & 0xff);
  22295. put_byte(s, (strm.total_in >> 8) & 0xff);
  22296. put_byte(s, (strm.total_in >> 16) & 0xff);
  22297. put_byte(s, (strm.total_in >> 24) & 0xff);
  22298. }
  22299. else
  22300. {
  22301. putShortMSB(s, strm.adler >>> 16);
  22302. putShortMSB(s, strm.adler & 0xffff);
  22303. }
  22304. flush_pending(strm);
  22305. /* If avail_out is zero, the application will call deflate again
  22306. * to flush the rest.
  22307. */
  22308. if (s.wrap > 0) { s.wrap = -s.wrap; }
  22309. /* write the trailer only once! */
  22310. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  22311. }
  22312. function deflateEnd(strm) {
  22313. var status;
  22314. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  22315. return Z_STREAM_ERROR;
  22316. }
  22317. status = strm.state.status;
  22318. if (status !== INIT_STATE &&
  22319. status !== EXTRA_STATE &&
  22320. status !== NAME_STATE &&
  22321. status !== COMMENT_STATE &&
  22322. status !== HCRC_STATE &&
  22323. status !== BUSY_STATE &&
  22324. status !== FINISH_STATE
  22325. ) {
  22326. return err(strm, Z_STREAM_ERROR);
  22327. }
  22328. strm.state = null;
  22329. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  22330. }
  22331. /* =========================================================================
  22332. * Copy the source state to the destination state
  22333. */
  22334. //function deflateCopy(dest, source) {
  22335. //
  22336. //}
  22337. exports.deflateInit = deflateInit;
  22338. exports.deflateInit2 = deflateInit2;
  22339. exports.deflateReset = deflateReset;
  22340. exports.deflateResetKeep = deflateResetKeep;
  22341. exports.deflateSetHeader = deflateSetHeader;
  22342. exports.deflate = deflate;
  22343. exports.deflateEnd = deflateEnd;
  22344. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  22345. /* Not implemented
  22346. exports.deflateBound = deflateBound;
  22347. exports.deflateCopy = deflateCopy;
  22348. exports.deflateSetDictionary = deflateSetDictionary;
  22349. exports.deflateParams = deflateParams;
  22350. exports.deflatePending = deflatePending;
  22351. exports.deflatePrime = deflatePrime;
  22352. exports.deflateTune = deflateTune;
  22353. */
  22354. },{"../utils/common":75,"./adler32":77,"./crc32":79,"./messages":85,"./trees":86}],81:[function(require,module,exports){
  22355. 'use strict';
  22356. function GZheader() {
  22357. /* true if compressed data believed to be text */
  22358. this.text = 0;
  22359. /* modification time */
  22360. this.time = 0;
  22361. /* extra flags (not used when writing a gzip file) */
  22362. this.xflags = 0;
  22363. /* operating system */
  22364. this.os = 0;
  22365. /* pointer to extra field or Z_NULL if none */
  22366. this.extra = null;
  22367. /* extra field length (valid if extra != Z_NULL) */
  22368. this.extra_len = 0; // Actually, we don't need it in JS,
  22369. // but leave for few code modifications
  22370. //
  22371. // Setup limits is not necessary because in js we should not preallocate memory
  22372. // for inflate use constant limit in 65536 bytes
  22373. //
  22374. /* space at extra (only when reading header) */
  22375. // this.extra_max = 0;
  22376. /* pointer to zero-terminated file name or Z_NULL */
  22377. this.name = '';
  22378. /* space at name (only when reading header) */
  22379. // this.name_max = 0;
  22380. /* pointer to zero-terminated comment or Z_NULL */
  22381. this.comment = '';
  22382. /* space at comment (only when reading header) */
  22383. // this.comm_max = 0;
  22384. /* true if there was or will be a header crc */
  22385. this.hcrc = 0;
  22386. /* true when done reading gzip header (not used when writing a gzip file) */
  22387. this.done = false;
  22388. }
  22389. module.exports = GZheader;
  22390. },{}],82:[function(require,module,exports){
  22391. 'use strict';
  22392. // See state defs from inflate.js
  22393. var BAD = 30; /* got a data error -- remain here until reset */
  22394. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22395. /*
  22396. Decode literal, length, and distance codes and write out the resulting
  22397. literal and match bytes until either not enough input or output is
  22398. available, an end-of-block is encountered, or a data error is encountered.
  22399. When large enough input and output buffers are supplied to inflate(), for
  22400. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  22401. inflate execution time is spent in this routine.
  22402. Entry assumptions:
  22403. state.mode === LEN
  22404. strm.avail_in >= 6
  22405. strm.avail_out >= 258
  22406. start >= strm.avail_out
  22407. state.bits < 8
  22408. On return, state.mode is one of:
  22409. LEN -- ran out of enough output space or enough available input
  22410. TYPE -- reached end of block code, inflate() to interpret next block
  22411. BAD -- error in block data
  22412. Notes:
  22413. - The maximum input bits used by a length/distance pair is 15 bits for the
  22414. length code, 5 bits for the length extra, 15 bits for the distance code,
  22415. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  22416. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  22417. checking for available input while decoding.
  22418. - The maximum bytes that a single length/distance pair can output is 258
  22419. bytes, which is the maximum length that can be coded. inflate_fast()
  22420. requires strm.avail_out >= 258 for each loop to avoid checking for
  22421. output space.
  22422. */
  22423. module.exports = function inflate_fast(strm, start) {
  22424. var state;
  22425. var _in; /* local strm.input */
  22426. var last; /* have enough input while in < last */
  22427. var _out; /* local strm.output */
  22428. var beg; /* inflate()'s initial strm.output */
  22429. var end; /* while out < end, enough space available */
  22430. //#ifdef INFLATE_STRICT
  22431. var dmax; /* maximum distance from zlib header */
  22432. //#endif
  22433. var wsize; /* window size or zero if not using window */
  22434. var whave; /* valid bytes in the window */
  22435. var wnext; /* window write index */
  22436. var window; /* allocated sliding window, if wsize != 0 */
  22437. var hold; /* local strm.hold */
  22438. var bits; /* local strm.bits */
  22439. var lcode; /* local strm.lencode */
  22440. var dcode; /* local strm.distcode */
  22441. var lmask; /* mask for first level of length codes */
  22442. var dmask; /* mask for first level of distance codes */
  22443. var here; /* retrieved table entry */
  22444. var op; /* code bits, operation, extra bits, or */
  22445. /* window position, window bytes to copy */
  22446. var len; /* match length, unused bytes */
  22447. var dist; /* match distance */
  22448. var from; /* where to copy match from */
  22449. var from_source;
  22450. var input, output; // JS specific, because we have no pointers
  22451. /* copy state to local variables */
  22452. state = strm.state;
  22453. //here = state.here;
  22454. _in = strm.next_in;
  22455. input = strm.input;
  22456. last = _in + (strm.avail_in - 5);
  22457. _out = strm.next_out;
  22458. output = strm.output;
  22459. beg = _out - (start - strm.avail_out);
  22460. end = _out + (strm.avail_out - 257);
  22461. //#ifdef INFLATE_STRICT
  22462. dmax = state.dmax;
  22463. //#endif
  22464. wsize = state.wsize;
  22465. whave = state.whave;
  22466. wnext = state.wnext;
  22467. window = state.window;
  22468. hold = state.hold;
  22469. bits = state.bits;
  22470. lcode = state.lencode;
  22471. dcode = state.distcode;
  22472. lmask = (1 << state.lenbits) - 1;
  22473. dmask = (1 << state.distbits) - 1;
  22474. /* decode literals and length/distances until end-of-block or not enough
  22475. input data or output space */
  22476. top:
  22477. do {
  22478. if (bits < 15) {
  22479. hold += input[_in++] << bits;
  22480. bits += 8;
  22481. hold += input[_in++] << bits;
  22482. bits += 8;
  22483. }
  22484. here = lcode[hold & lmask];
  22485. dolen:
  22486. for (;;) { // Goto emulation
  22487. op = here >>> 24/*here.bits*/;
  22488. hold >>>= op;
  22489. bits -= op;
  22490. op = (here >>> 16) & 0xff/*here.op*/;
  22491. if (op === 0) { /* literal */
  22492. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  22493. // "inflate: literal '%c'\n" :
  22494. // "inflate: literal 0x%02x\n", here.val));
  22495. output[_out++] = here & 0xffff/*here.val*/;
  22496. }
  22497. else if (op & 16) { /* length base */
  22498. len = here & 0xffff/*here.val*/;
  22499. op &= 15; /* number of extra bits */
  22500. if (op) {
  22501. if (bits < op) {
  22502. hold += input[_in++] << bits;
  22503. bits += 8;
  22504. }
  22505. len += hold & ((1 << op) - 1);
  22506. hold >>>= op;
  22507. bits -= op;
  22508. }
  22509. //Tracevv((stderr, "inflate: length %u\n", len));
  22510. if (bits < 15) {
  22511. hold += input[_in++] << bits;
  22512. bits += 8;
  22513. hold += input[_in++] << bits;
  22514. bits += 8;
  22515. }
  22516. here = dcode[hold & dmask];
  22517. dodist:
  22518. for (;;) { // goto emulation
  22519. op = here >>> 24/*here.bits*/;
  22520. hold >>>= op;
  22521. bits -= op;
  22522. op = (here >>> 16) & 0xff/*here.op*/;
  22523. if (op & 16) { /* distance base */
  22524. dist = here & 0xffff/*here.val*/;
  22525. op &= 15; /* number of extra bits */
  22526. if (bits < op) {
  22527. hold += input[_in++] << bits;
  22528. bits += 8;
  22529. if (bits < op) {
  22530. hold += input[_in++] << bits;
  22531. bits += 8;
  22532. }
  22533. }
  22534. dist += hold & ((1 << op) - 1);
  22535. //#ifdef INFLATE_STRICT
  22536. if (dist > dmax) {
  22537. strm.msg = 'invalid distance too far back';
  22538. state.mode = BAD;
  22539. break top;
  22540. }
  22541. //#endif
  22542. hold >>>= op;
  22543. bits -= op;
  22544. //Tracevv((stderr, "inflate: distance %u\n", dist));
  22545. op = _out - beg; /* max distance in output */
  22546. if (dist > op) { /* see if copy from window */
  22547. op = dist - op; /* distance back in window */
  22548. if (op > whave) {
  22549. if (state.sane) {
  22550. strm.msg = 'invalid distance too far back';
  22551. state.mode = BAD;
  22552. break top;
  22553. }
  22554. // (!) This block is disabled in zlib defailts,
  22555. // don't enable it for binary compatibility
  22556. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  22557. // if (len <= op - whave) {
  22558. // do {
  22559. // output[_out++] = 0;
  22560. // } while (--len);
  22561. // continue top;
  22562. // }
  22563. // len -= op - whave;
  22564. // do {
  22565. // output[_out++] = 0;
  22566. // } while (--op > whave);
  22567. // if (op === 0) {
  22568. // from = _out - dist;
  22569. // do {
  22570. // output[_out++] = output[from++];
  22571. // } while (--len);
  22572. // continue top;
  22573. // }
  22574. //#endif
  22575. }
  22576. from = 0; // window index
  22577. from_source = window;
  22578. if (wnext === 0) { /* very common case */
  22579. from += wsize - op;
  22580. if (op < len) { /* some from window */
  22581. len -= op;
  22582. do {
  22583. output[_out++] = window[from++];
  22584. } while (--op);
  22585. from = _out - dist; /* rest from output */
  22586. from_source = output;
  22587. }
  22588. }
  22589. else if (wnext < op) { /* wrap around window */
  22590. from += wsize + wnext - op;
  22591. op -= wnext;
  22592. if (op < len) { /* some from end of window */
  22593. len -= op;
  22594. do {
  22595. output[_out++] = window[from++];
  22596. } while (--op);
  22597. from = 0;
  22598. if (wnext < len) { /* some from start of window */
  22599. op = wnext;
  22600. len -= op;
  22601. do {
  22602. output[_out++] = window[from++];
  22603. } while (--op);
  22604. from = _out - dist; /* rest from output */
  22605. from_source = output;
  22606. }
  22607. }
  22608. }
  22609. else { /* contiguous in window */
  22610. from += wnext - op;
  22611. if (op < len) { /* some from window */
  22612. len -= op;
  22613. do {
  22614. output[_out++] = window[from++];
  22615. } while (--op);
  22616. from = _out - dist; /* rest from output */
  22617. from_source = output;
  22618. }
  22619. }
  22620. while (len > 2) {
  22621. output[_out++] = from_source[from++];
  22622. output[_out++] = from_source[from++];
  22623. output[_out++] = from_source[from++];
  22624. len -= 3;
  22625. }
  22626. if (len) {
  22627. output[_out++] = from_source[from++];
  22628. if (len > 1) {
  22629. output[_out++] = from_source[from++];
  22630. }
  22631. }
  22632. }
  22633. else {
  22634. from = _out - dist; /* copy direct from output */
  22635. do { /* minimum length is three */
  22636. output[_out++] = output[from++];
  22637. output[_out++] = output[from++];
  22638. output[_out++] = output[from++];
  22639. len -= 3;
  22640. } while (len > 2);
  22641. if (len) {
  22642. output[_out++] = output[from++];
  22643. if (len > 1) {
  22644. output[_out++] = output[from++];
  22645. }
  22646. }
  22647. }
  22648. }
  22649. else if ((op & 64) === 0) { /* 2nd level distance code */
  22650. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22651. continue dodist;
  22652. }
  22653. else {
  22654. strm.msg = 'invalid distance code';
  22655. state.mode = BAD;
  22656. break top;
  22657. }
  22658. break; // need to emulate goto via "continue"
  22659. }
  22660. }
  22661. else if ((op & 64) === 0) { /* 2nd level length code */
  22662. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22663. continue dolen;
  22664. }
  22665. else if (op & 32) { /* end-of-block */
  22666. //Tracevv((stderr, "inflate: end of block\n"));
  22667. state.mode = TYPE;
  22668. break top;
  22669. }
  22670. else {
  22671. strm.msg = 'invalid literal/length code';
  22672. state.mode = BAD;
  22673. break top;
  22674. }
  22675. break; // need to emulate goto via "continue"
  22676. }
  22677. } while (_in < last && _out < end);
  22678. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  22679. len = bits >> 3;
  22680. _in -= len;
  22681. bits -= len << 3;
  22682. hold &= (1 << bits) - 1;
  22683. /* update state and return */
  22684. strm.next_in = _in;
  22685. strm.next_out = _out;
  22686. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  22687. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  22688. state.hold = hold;
  22689. state.bits = bits;
  22690. return;
  22691. };
  22692. },{}],83:[function(require,module,exports){
  22693. 'use strict';
  22694. var utils = require('../utils/common');
  22695. var adler32 = require('./adler32');
  22696. var crc32 = require('./crc32');
  22697. var inflate_fast = require('./inffast');
  22698. var inflate_table = require('./inftrees');
  22699. var CODES = 0;
  22700. var LENS = 1;
  22701. var DISTS = 2;
  22702. /* Public constants ==========================================================*/
  22703. /* ===========================================================================*/
  22704. /* Allowed flush values; see deflate() and inflate() below for details */
  22705. //var Z_NO_FLUSH = 0;
  22706. //var Z_PARTIAL_FLUSH = 1;
  22707. //var Z_SYNC_FLUSH = 2;
  22708. //var Z_FULL_FLUSH = 3;
  22709. var Z_FINISH = 4;
  22710. var Z_BLOCK = 5;
  22711. var Z_TREES = 6;
  22712. /* Return codes for the compression/decompression functions. Negative values
  22713. * are errors, positive values are used for special but normal events.
  22714. */
  22715. var Z_OK = 0;
  22716. var Z_STREAM_END = 1;
  22717. var Z_NEED_DICT = 2;
  22718. //var Z_ERRNO = -1;
  22719. var Z_STREAM_ERROR = -2;
  22720. var Z_DATA_ERROR = -3;
  22721. var Z_MEM_ERROR = -4;
  22722. var Z_BUF_ERROR = -5;
  22723. //var Z_VERSION_ERROR = -6;
  22724. /* The deflate compression method */
  22725. var Z_DEFLATED = 8;
  22726. /* STATES ====================================================================*/
  22727. /* ===========================================================================*/
  22728. var HEAD = 1; /* i: waiting for magic header */
  22729. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  22730. var TIME = 3; /* i: waiting for modification time (gzip) */
  22731. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  22732. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  22733. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  22734. var NAME = 7; /* i: waiting for end of file name (gzip) */
  22735. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  22736. var HCRC = 9; /* i: waiting for header crc (gzip) */
  22737. var DICTID = 10; /* i: waiting for dictionary check value */
  22738. var DICT = 11; /* waiting for inflateSetDictionary() call */
  22739. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22740. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  22741. var STORED = 14; /* i: waiting for stored size (length and complement) */
  22742. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  22743. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  22744. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  22745. var LENLENS = 18; /* i: waiting for code length code lengths */
  22746. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  22747. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  22748. var LEN = 21; /* i: waiting for length/lit/eob code */
  22749. var LENEXT = 22; /* i: waiting for length extra bits */
  22750. var DIST = 23; /* i: waiting for distance code */
  22751. var DISTEXT = 24; /* i: waiting for distance extra bits */
  22752. var MATCH = 25; /* o: waiting for output space to copy string */
  22753. var LIT = 26; /* o: waiting for output space to write literal */
  22754. var CHECK = 27; /* i: waiting for 32-bit check value */
  22755. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  22756. var DONE = 29; /* finished check, done -- remain here until reset */
  22757. var BAD = 30; /* got a data error -- remain here until reset */
  22758. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  22759. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  22760. /* ===========================================================================*/
  22761. var ENOUGH_LENS = 852;
  22762. var ENOUGH_DISTS = 592;
  22763. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22764. var MAX_WBITS = 15;
  22765. /* 32K LZ77 window */
  22766. var DEF_WBITS = MAX_WBITS;
  22767. function ZSWAP32(q) {
  22768. return (((q >>> 24) & 0xff) +
  22769. ((q >>> 8) & 0xff00) +
  22770. ((q & 0xff00) << 8) +
  22771. ((q & 0xff) << 24));
  22772. }
  22773. function InflateState() {
  22774. this.mode = 0; /* current inflate mode */
  22775. this.last = false; /* true if processing last block */
  22776. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  22777. this.havedict = false; /* true if dictionary provided */
  22778. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  22779. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  22780. this.check = 0; /* protected copy of check value */
  22781. this.total = 0; /* protected copy of output count */
  22782. // TODO: may be {}
  22783. this.head = null; /* where to save gzip header information */
  22784. /* sliding window */
  22785. this.wbits = 0; /* log base 2 of requested window size */
  22786. this.wsize = 0; /* window size or zero if not using window */
  22787. this.whave = 0; /* valid bytes in the window */
  22788. this.wnext = 0; /* window write index */
  22789. this.window = null; /* allocated sliding window, if needed */
  22790. /* bit accumulator */
  22791. this.hold = 0; /* input bit accumulator */
  22792. this.bits = 0; /* number of bits in "in" */
  22793. /* for string and stored block copying */
  22794. this.length = 0; /* literal or length of data to copy */
  22795. this.offset = 0; /* distance back to copy string from */
  22796. /* for table and code decoding */
  22797. this.extra = 0; /* extra bits needed */
  22798. /* fixed and dynamic code tables */
  22799. this.lencode = null; /* starting table for length/literal codes */
  22800. this.distcode = null; /* starting table for distance codes */
  22801. this.lenbits = 0; /* index bits for lencode */
  22802. this.distbits = 0; /* index bits for distcode */
  22803. /* dynamic table building */
  22804. this.ncode = 0; /* number of code length code lengths */
  22805. this.nlen = 0; /* number of length code lengths */
  22806. this.ndist = 0; /* number of distance code lengths */
  22807. this.have = 0; /* number of code lengths in lens[] */
  22808. this.next = null; /* next available space in codes[] */
  22809. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  22810. this.work = new utils.Buf16(288); /* work area for code table building */
  22811. /*
  22812. because we don't have pointers in js, we use lencode and distcode directly
  22813. as buffers so we don't need codes
  22814. */
  22815. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  22816. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  22817. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  22818. this.sane = 0; /* if false, allow invalid distance too far */
  22819. this.back = 0; /* bits back of last unprocessed length/lit */
  22820. this.was = 0; /* initial length of match */
  22821. }
  22822. function inflateResetKeep(strm) {
  22823. var state;
  22824. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22825. state = strm.state;
  22826. strm.total_in = strm.total_out = state.total = 0;
  22827. strm.msg = ''; /*Z_NULL*/
  22828. if (state.wrap) { /* to support ill-conceived Java test suite */
  22829. strm.adler = state.wrap & 1;
  22830. }
  22831. state.mode = HEAD;
  22832. state.last = 0;
  22833. state.havedict = 0;
  22834. state.dmax = 32768;
  22835. state.head = null/*Z_NULL*/;
  22836. state.hold = 0;
  22837. state.bits = 0;
  22838. //state.lencode = state.distcode = state.next = state.codes;
  22839. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  22840. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  22841. state.sane = 1;
  22842. state.back = -1;
  22843. //Tracev((stderr, "inflate: reset\n"));
  22844. return Z_OK;
  22845. }
  22846. function inflateReset(strm) {
  22847. var state;
  22848. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22849. state = strm.state;
  22850. state.wsize = 0;
  22851. state.whave = 0;
  22852. state.wnext = 0;
  22853. return inflateResetKeep(strm);
  22854. }
  22855. function inflateReset2(strm, windowBits) {
  22856. var wrap;
  22857. var state;
  22858. /* get the state */
  22859. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22860. state = strm.state;
  22861. /* extract wrap request from windowBits parameter */
  22862. if (windowBits < 0) {
  22863. wrap = 0;
  22864. windowBits = -windowBits;
  22865. }
  22866. else {
  22867. wrap = (windowBits >> 4) + 1;
  22868. if (windowBits < 48) {
  22869. windowBits &= 15;
  22870. }
  22871. }
  22872. /* set number of window bits, free window if different */
  22873. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  22874. return Z_STREAM_ERROR;
  22875. }
  22876. if (state.window !== null && state.wbits !== windowBits) {
  22877. state.window = null;
  22878. }
  22879. /* update state and reset the rest of it */
  22880. state.wrap = wrap;
  22881. state.wbits = windowBits;
  22882. return inflateReset(strm);
  22883. }
  22884. function inflateInit2(strm, windowBits) {
  22885. var ret;
  22886. var state;
  22887. if (!strm) { return Z_STREAM_ERROR; }
  22888. //strm.msg = Z_NULL; /* in case we return an error */
  22889. state = new InflateState();
  22890. //if (state === Z_NULL) return Z_MEM_ERROR;
  22891. //Tracev((stderr, "inflate: allocated\n"));
  22892. strm.state = state;
  22893. state.window = null/*Z_NULL*/;
  22894. ret = inflateReset2(strm, windowBits);
  22895. if (ret !== Z_OK) {
  22896. strm.state = null/*Z_NULL*/;
  22897. }
  22898. return ret;
  22899. }
  22900. function inflateInit(strm) {
  22901. return inflateInit2(strm, DEF_WBITS);
  22902. }
  22903. /*
  22904. Return state with length and distance decoding tables and index sizes set to
  22905. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  22906. If BUILDFIXED is defined, then instead this routine builds the tables the
  22907. first time it's called, and returns those tables the first time and
  22908. thereafter. This reduces the size of the code by about 2K bytes, in
  22909. exchange for a little execution time. However, BUILDFIXED should not be
  22910. used for threaded applications, since the rewriting of the tables and virgin
  22911. may not be thread-safe.
  22912. */
  22913. var virgin = true;
  22914. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  22915. function fixedtables(state) {
  22916. /* build fixed huffman tables if first call (may not be thread safe) */
  22917. if (virgin) {
  22918. var sym;
  22919. lenfix = new utils.Buf32(512);
  22920. distfix = new utils.Buf32(32);
  22921. /* literal/length table */
  22922. sym = 0;
  22923. while (sym < 144) { state.lens[sym++] = 8; }
  22924. while (sym < 256) { state.lens[sym++] = 9; }
  22925. while (sym < 280) { state.lens[sym++] = 7; }
  22926. while (sym < 288) { state.lens[sym++] = 8; }
  22927. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  22928. /* distance table */
  22929. sym = 0;
  22930. while (sym < 32) { state.lens[sym++] = 5; }
  22931. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  22932. /* do this just once */
  22933. virgin = false;
  22934. }
  22935. state.lencode = lenfix;
  22936. state.lenbits = 9;
  22937. state.distcode = distfix;
  22938. state.distbits = 5;
  22939. }
  22940. /*
  22941. Update the window with the last wsize (normally 32K) bytes written before
  22942. returning. If window does not exist yet, create it. This is only called
  22943. when a window is already in use, or when output has been written during this
  22944. inflate call, but the end of the deflate stream has not been reached yet.
  22945. It is also called to create a window for dictionary data when a dictionary
  22946. is loaded.
  22947. Providing output buffers larger than 32K to inflate() should provide a speed
  22948. advantage, since only the last 32K of output is copied to the sliding window
  22949. upon return from inflate(), and since all distances after the first 32K of
  22950. output will fall in the output data, making match copies simpler and faster.
  22951. The advantage may be dependent on the size of the processor's data caches.
  22952. */
  22953. function updatewindow(strm, src, end, copy) {
  22954. var dist;
  22955. var state = strm.state;
  22956. /* if it hasn't been done already, allocate space for the window */
  22957. if (state.window === null) {
  22958. state.wsize = 1 << state.wbits;
  22959. state.wnext = 0;
  22960. state.whave = 0;
  22961. state.window = new utils.Buf8(state.wsize);
  22962. }
  22963. /* copy state->wsize or less output bytes into the circular window */
  22964. if (copy >= state.wsize) {
  22965. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  22966. state.wnext = 0;
  22967. state.whave = state.wsize;
  22968. }
  22969. else {
  22970. dist = state.wsize - state.wnext;
  22971. if (dist > copy) {
  22972. dist = copy;
  22973. }
  22974. //zmemcpy(state->window + state->wnext, end - copy, dist);
  22975. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  22976. copy -= dist;
  22977. if (copy) {
  22978. //zmemcpy(state->window, end - copy, copy);
  22979. utils.arraySet(state.window,src, end - copy, copy, 0);
  22980. state.wnext = copy;
  22981. state.whave = state.wsize;
  22982. }
  22983. else {
  22984. state.wnext += dist;
  22985. if (state.wnext === state.wsize) { state.wnext = 0; }
  22986. if (state.whave < state.wsize) { state.whave += dist; }
  22987. }
  22988. }
  22989. return 0;
  22990. }
  22991. function inflate(strm, flush) {
  22992. var state;
  22993. var input, output; // input/output buffers
  22994. var next; /* next input INDEX */
  22995. var put; /* next output INDEX */
  22996. var have, left; /* available input and output */
  22997. var hold; /* bit buffer */
  22998. var bits; /* bits in bit buffer */
  22999. var _in, _out; /* save starting available input and output */
  23000. var copy; /* number of stored or match bytes to copy */
  23001. var from; /* where to copy match bytes from */
  23002. var from_source;
  23003. var here = 0; /* current decoding table entry */
  23004. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  23005. //var last; /* parent table entry */
  23006. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  23007. var len; /* length to copy for repeats, bits to drop */
  23008. var ret; /* return code */
  23009. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  23010. var opts;
  23011. var n; // temporary var for NEED_BITS
  23012. var order = /* permutation of code lengths */
  23013. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  23014. if (!strm || !strm.state || !strm.output ||
  23015. (!strm.input && strm.avail_in !== 0)) {
  23016. return Z_STREAM_ERROR;
  23017. }
  23018. state = strm.state;
  23019. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  23020. //--- LOAD() ---
  23021. put = strm.next_out;
  23022. output = strm.output;
  23023. left = strm.avail_out;
  23024. next = strm.next_in;
  23025. input = strm.input;
  23026. have = strm.avail_in;
  23027. hold = state.hold;
  23028. bits = state.bits;
  23029. //---
  23030. _in = have;
  23031. _out = left;
  23032. ret = Z_OK;
  23033. inf_leave: // goto emulation
  23034. for (;;) {
  23035. switch (state.mode) {
  23036. case HEAD:
  23037. if (state.wrap === 0) {
  23038. state.mode = TYPEDO;
  23039. break;
  23040. }
  23041. //=== NEEDBITS(16);
  23042. while (bits < 16) {
  23043. if (have === 0) { break inf_leave; }
  23044. have--;
  23045. hold += input[next++] << bits;
  23046. bits += 8;
  23047. }
  23048. //===//
  23049. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  23050. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  23051. //=== CRC2(state.check, hold);
  23052. hbuf[0] = hold & 0xff;
  23053. hbuf[1] = (hold >>> 8) & 0xff;
  23054. state.check = crc32(state.check, hbuf, 2, 0);
  23055. //===//
  23056. //=== INITBITS();
  23057. hold = 0;
  23058. bits = 0;
  23059. //===//
  23060. state.mode = FLAGS;
  23061. break;
  23062. }
  23063. state.flags = 0; /* expect zlib header */
  23064. if (state.head) {
  23065. state.head.done = false;
  23066. }
  23067. if (!(state.wrap & 1) || /* check if zlib header allowed */
  23068. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  23069. strm.msg = 'incorrect header check';
  23070. state.mode = BAD;
  23071. break;
  23072. }
  23073. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  23074. strm.msg = 'unknown compression method';
  23075. state.mode = BAD;
  23076. break;
  23077. }
  23078. //--- DROPBITS(4) ---//
  23079. hold >>>= 4;
  23080. bits -= 4;
  23081. //---//
  23082. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  23083. if (state.wbits === 0) {
  23084. state.wbits = len;
  23085. }
  23086. else if (len > state.wbits) {
  23087. strm.msg = 'invalid window size';
  23088. state.mode = BAD;
  23089. break;
  23090. }
  23091. state.dmax = 1 << len;
  23092. //Tracev((stderr, "inflate: zlib header ok\n"));
  23093. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  23094. state.mode = hold & 0x200 ? DICTID : TYPE;
  23095. //=== INITBITS();
  23096. hold = 0;
  23097. bits = 0;
  23098. //===//
  23099. break;
  23100. case FLAGS:
  23101. //=== NEEDBITS(16); */
  23102. while (bits < 16) {
  23103. if (have === 0) { break inf_leave; }
  23104. have--;
  23105. hold += input[next++] << bits;
  23106. bits += 8;
  23107. }
  23108. //===//
  23109. state.flags = hold;
  23110. if ((state.flags & 0xff) !== Z_DEFLATED) {
  23111. strm.msg = 'unknown compression method';
  23112. state.mode = BAD;
  23113. break;
  23114. }
  23115. if (state.flags & 0xe000) {
  23116. strm.msg = 'unknown header flags set';
  23117. state.mode = BAD;
  23118. break;
  23119. }
  23120. if (state.head) {
  23121. state.head.text = ((hold >> 8) & 1);
  23122. }
  23123. if (state.flags & 0x0200) {
  23124. //=== CRC2(state.check, hold);
  23125. hbuf[0] = hold & 0xff;
  23126. hbuf[1] = (hold >>> 8) & 0xff;
  23127. state.check = crc32(state.check, hbuf, 2, 0);
  23128. //===//
  23129. }
  23130. //=== INITBITS();
  23131. hold = 0;
  23132. bits = 0;
  23133. //===//
  23134. state.mode = TIME;
  23135. /* falls through */
  23136. case TIME:
  23137. //=== NEEDBITS(32); */
  23138. while (bits < 32) {
  23139. if (have === 0) { break inf_leave; }
  23140. have--;
  23141. hold += input[next++] << bits;
  23142. bits += 8;
  23143. }
  23144. //===//
  23145. if (state.head) {
  23146. state.head.time = hold;
  23147. }
  23148. if (state.flags & 0x0200) {
  23149. //=== CRC4(state.check, hold)
  23150. hbuf[0] = hold & 0xff;
  23151. hbuf[1] = (hold >>> 8) & 0xff;
  23152. hbuf[2] = (hold >>> 16) & 0xff;
  23153. hbuf[3] = (hold >>> 24) & 0xff;
  23154. state.check = crc32(state.check, hbuf, 4, 0);
  23155. //===
  23156. }
  23157. //=== INITBITS();
  23158. hold = 0;
  23159. bits = 0;
  23160. //===//
  23161. state.mode = OS;
  23162. /* falls through */
  23163. case OS:
  23164. //=== NEEDBITS(16); */
  23165. while (bits < 16) {
  23166. if (have === 0) { break inf_leave; }
  23167. have--;
  23168. hold += input[next++] << bits;
  23169. bits += 8;
  23170. }
  23171. //===//
  23172. if (state.head) {
  23173. state.head.xflags = (hold & 0xff);
  23174. state.head.os = (hold >> 8);
  23175. }
  23176. if (state.flags & 0x0200) {
  23177. //=== CRC2(state.check, hold);
  23178. hbuf[0] = hold & 0xff;
  23179. hbuf[1] = (hold >>> 8) & 0xff;
  23180. state.check = crc32(state.check, hbuf, 2, 0);
  23181. //===//
  23182. }
  23183. //=== INITBITS();
  23184. hold = 0;
  23185. bits = 0;
  23186. //===//
  23187. state.mode = EXLEN;
  23188. /* falls through */
  23189. case EXLEN:
  23190. if (state.flags & 0x0400) {
  23191. //=== NEEDBITS(16); */
  23192. while (bits < 16) {
  23193. if (have === 0) { break inf_leave; }
  23194. have--;
  23195. hold += input[next++] << bits;
  23196. bits += 8;
  23197. }
  23198. //===//
  23199. state.length = hold;
  23200. if (state.head) {
  23201. state.head.extra_len = hold;
  23202. }
  23203. if (state.flags & 0x0200) {
  23204. //=== CRC2(state.check, hold);
  23205. hbuf[0] = hold & 0xff;
  23206. hbuf[1] = (hold >>> 8) & 0xff;
  23207. state.check = crc32(state.check, hbuf, 2, 0);
  23208. //===//
  23209. }
  23210. //=== INITBITS();
  23211. hold = 0;
  23212. bits = 0;
  23213. //===//
  23214. }
  23215. else if (state.head) {
  23216. state.head.extra = null/*Z_NULL*/;
  23217. }
  23218. state.mode = EXTRA;
  23219. /* falls through */
  23220. case EXTRA:
  23221. if (state.flags & 0x0400) {
  23222. copy = state.length;
  23223. if (copy > have) { copy = have; }
  23224. if (copy) {
  23225. if (state.head) {
  23226. len = state.head.extra_len - state.length;
  23227. if (!state.head.extra) {
  23228. // Use untyped array for more conveniend processing later
  23229. state.head.extra = new Array(state.head.extra_len);
  23230. }
  23231. utils.arraySet(
  23232. state.head.extra,
  23233. input,
  23234. next,
  23235. // extra field is limited to 65536 bytes
  23236. // - no need for additional size check
  23237. copy,
  23238. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  23239. len
  23240. );
  23241. //zmemcpy(state.head.extra + len, next,
  23242. // len + copy > state.head.extra_max ?
  23243. // state.head.extra_max - len : copy);
  23244. }
  23245. if (state.flags & 0x0200) {
  23246. state.check = crc32(state.check, input, copy, next);
  23247. }
  23248. have -= copy;
  23249. next += copy;
  23250. state.length -= copy;
  23251. }
  23252. if (state.length) { break inf_leave; }
  23253. }
  23254. state.length = 0;
  23255. state.mode = NAME;
  23256. /* falls through */
  23257. case NAME:
  23258. if (state.flags & 0x0800) {
  23259. if (have === 0) { break inf_leave; }
  23260. copy = 0;
  23261. do {
  23262. // TODO: 2 or 1 bytes?
  23263. len = input[next + copy++];
  23264. /* use constant limit because in js we should not preallocate memory */
  23265. if (state.head && len &&
  23266. (state.length < 65536 /*state.head.name_max*/)) {
  23267. state.head.name += String.fromCharCode(len);
  23268. }
  23269. } while (len && copy < have);
  23270. if (state.flags & 0x0200) {
  23271. state.check = crc32(state.check, input, copy, next);
  23272. }
  23273. have -= copy;
  23274. next += copy;
  23275. if (len) { break inf_leave; }
  23276. }
  23277. else if (state.head) {
  23278. state.head.name = null;
  23279. }
  23280. state.length = 0;
  23281. state.mode = COMMENT;
  23282. /* falls through */
  23283. case COMMENT:
  23284. if (state.flags & 0x1000) {
  23285. if (have === 0) { break inf_leave; }
  23286. copy = 0;
  23287. do {
  23288. len = input[next + copy++];
  23289. /* use constant limit because in js we should not preallocate memory */
  23290. if (state.head && len &&
  23291. (state.length < 65536 /*state.head.comm_max*/)) {
  23292. state.head.comment += String.fromCharCode(len);
  23293. }
  23294. } while (len && copy < have);
  23295. if (state.flags & 0x0200) {
  23296. state.check = crc32(state.check, input, copy, next);
  23297. }
  23298. have -= copy;
  23299. next += copy;
  23300. if (len) { break inf_leave; }
  23301. }
  23302. else if (state.head) {
  23303. state.head.comment = null;
  23304. }
  23305. state.mode = HCRC;
  23306. /* falls through */
  23307. case HCRC:
  23308. if (state.flags & 0x0200) {
  23309. //=== NEEDBITS(16); */
  23310. while (bits < 16) {
  23311. if (have === 0) { break inf_leave; }
  23312. have--;
  23313. hold += input[next++] << bits;
  23314. bits += 8;
  23315. }
  23316. //===//
  23317. if (hold !== (state.check & 0xffff)) {
  23318. strm.msg = 'header crc mismatch';
  23319. state.mode = BAD;
  23320. break;
  23321. }
  23322. //=== INITBITS();
  23323. hold = 0;
  23324. bits = 0;
  23325. //===//
  23326. }
  23327. if (state.head) {
  23328. state.head.hcrc = ((state.flags >> 9) & 1);
  23329. state.head.done = true;
  23330. }
  23331. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  23332. state.mode = TYPE;
  23333. break;
  23334. case DICTID:
  23335. //=== NEEDBITS(32); */
  23336. while (bits < 32) {
  23337. if (have === 0) { break inf_leave; }
  23338. have--;
  23339. hold += input[next++] << bits;
  23340. bits += 8;
  23341. }
  23342. //===//
  23343. strm.adler = state.check = ZSWAP32(hold);
  23344. //=== INITBITS();
  23345. hold = 0;
  23346. bits = 0;
  23347. //===//
  23348. state.mode = DICT;
  23349. /* falls through */
  23350. case DICT:
  23351. if (state.havedict === 0) {
  23352. //--- RESTORE() ---
  23353. strm.next_out = put;
  23354. strm.avail_out = left;
  23355. strm.next_in = next;
  23356. strm.avail_in = have;
  23357. state.hold = hold;
  23358. state.bits = bits;
  23359. //---
  23360. return Z_NEED_DICT;
  23361. }
  23362. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  23363. state.mode = TYPE;
  23364. /* falls through */
  23365. case TYPE:
  23366. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  23367. /* falls through */
  23368. case TYPEDO:
  23369. if (state.last) {
  23370. //--- BYTEBITS() ---//
  23371. hold >>>= bits & 7;
  23372. bits -= bits & 7;
  23373. //---//
  23374. state.mode = CHECK;
  23375. break;
  23376. }
  23377. //=== NEEDBITS(3); */
  23378. while (bits < 3) {
  23379. if (have === 0) { break inf_leave; }
  23380. have--;
  23381. hold += input[next++] << bits;
  23382. bits += 8;
  23383. }
  23384. //===//
  23385. state.last = (hold & 0x01)/*BITS(1)*/;
  23386. //--- DROPBITS(1) ---//
  23387. hold >>>= 1;
  23388. bits -= 1;
  23389. //---//
  23390. switch ((hold & 0x03)/*BITS(2)*/) {
  23391. case 0: /* stored block */
  23392. //Tracev((stderr, "inflate: stored block%s\n",
  23393. // state.last ? " (last)" : ""));
  23394. state.mode = STORED;
  23395. break;
  23396. case 1: /* fixed block */
  23397. fixedtables(state);
  23398. //Tracev((stderr, "inflate: fixed codes block%s\n",
  23399. // state.last ? " (last)" : ""));
  23400. state.mode = LEN_; /* decode codes */
  23401. if (flush === Z_TREES) {
  23402. //--- DROPBITS(2) ---//
  23403. hold >>>= 2;
  23404. bits -= 2;
  23405. //---//
  23406. break inf_leave;
  23407. }
  23408. break;
  23409. case 2: /* dynamic block */
  23410. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  23411. // state.last ? " (last)" : ""));
  23412. state.mode = TABLE;
  23413. break;
  23414. case 3:
  23415. strm.msg = 'invalid block type';
  23416. state.mode = BAD;
  23417. }
  23418. //--- DROPBITS(2) ---//
  23419. hold >>>= 2;
  23420. bits -= 2;
  23421. //---//
  23422. break;
  23423. case STORED:
  23424. //--- BYTEBITS() ---// /* go to byte boundary */
  23425. hold >>>= bits & 7;
  23426. bits -= bits & 7;
  23427. //---//
  23428. //=== NEEDBITS(32); */
  23429. while (bits < 32) {
  23430. if (have === 0) { break inf_leave; }
  23431. have--;
  23432. hold += input[next++] << bits;
  23433. bits += 8;
  23434. }
  23435. //===//
  23436. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  23437. strm.msg = 'invalid stored block lengths';
  23438. state.mode = BAD;
  23439. break;
  23440. }
  23441. state.length = hold & 0xffff;
  23442. //Tracev((stderr, "inflate: stored length %u\n",
  23443. // state.length));
  23444. //=== INITBITS();
  23445. hold = 0;
  23446. bits = 0;
  23447. //===//
  23448. state.mode = COPY_;
  23449. if (flush === Z_TREES) { break inf_leave; }
  23450. /* falls through */
  23451. case COPY_:
  23452. state.mode = COPY;
  23453. /* falls through */
  23454. case COPY:
  23455. copy = state.length;
  23456. if (copy) {
  23457. if (copy > have) { copy = have; }
  23458. if (copy > left) { copy = left; }
  23459. if (copy === 0) { break inf_leave; }
  23460. //--- zmemcpy(put, next, copy); ---
  23461. utils.arraySet(output, input, next, copy, put);
  23462. //---//
  23463. have -= copy;
  23464. next += copy;
  23465. left -= copy;
  23466. put += copy;
  23467. state.length -= copy;
  23468. break;
  23469. }
  23470. //Tracev((stderr, "inflate: stored end\n"));
  23471. state.mode = TYPE;
  23472. break;
  23473. case TABLE:
  23474. //=== NEEDBITS(14); */
  23475. while (bits < 14) {
  23476. if (have === 0) { break inf_leave; }
  23477. have--;
  23478. hold += input[next++] << bits;
  23479. bits += 8;
  23480. }
  23481. //===//
  23482. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  23483. //--- DROPBITS(5) ---//
  23484. hold >>>= 5;
  23485. bits -= 5;
  23486. //---//
  23487. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  23488. //--- DROPBITS(5) ---//
  23489. hold >>>= 5;
  23490. bits -= 5;
  23491. //---//
  23492. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  23493. //--- DROPBITS(4) ---//
  23494. hold >>>= 4;
  23495. bits -= 4;
  23496. //---//
  23497. //#ifndef PKZIP_BUG_WORKAROUND
  23498. if (state.nlen > 286 || state.ndist > 30) {
  23499. strm.msg = 'too many length or distance symbols';
  23500. state.mode = BAD;
  23501. break;
  23502. }
  23503. //#endif
  23504. //Tracev((stderr, "inflate: table sizes ok\n"));
  23505. state.have = 0;
  23506. state.mode = LENLENS;
  23507. /* falls through */
  23508. case LENLENS:
  23509. while (state.have < state.ncode) {
  23510. //=== NEEDBITS(3);
  23511. while (bits < 3) {
  23512. if (have === 0) { break inf_leave; }
  23513. have--;
  23514. hold += input[next++] << bits;
  23515. bits += 8;
  23516. }
  23517. //===//
  23518. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  23519. //--- DROPBITS(3) ---//
  23520. hold >>>= 3;
  23521. bits -= 3;
  23522. //---//
  23523. }
  23524. while (state.have < 19) {
  23525. state.lens[order[state.have++]] = 0;
  23526. }
  23527. // We have separate tables & no pointers. 2 commented lines below not needed.
  23528. //state.next = state.codes;
  23529. //state.lencode = state.next;
  23530. // Switch to use dynamic table
  23531. state.lencode = state.lendyn;
  23532. state.lenbits = 7;
  23533. opts = {bits: state.lenbits};
  23534. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  23535. state.lenbits = opts.bits;
  23536. if (ret) {
  23537. strm.msg = 'invalid code lengths set';
  23538. state.mode = BAD;
  23539. break;
  23540. }
  23541. //Tracev((stderr, "inflate: code lengths ok\n"));
  23542. state.have = 0;
  23543. state.mode = CODELENS;
  23544. /* falls through */
  23545. case CODELENS:
  23546. while (state.have < state.nlen + state.ndist) {
  23547. for (;;) {
  23548. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  23549. here_bits = here >>> 24;
  23550. here_op = (here >>> 16) & 0xff;
  23551. here_val = here & 0xffff;
  23552. if ((here_bits) <= bits) { break; }
  23553. //--- PULLBYTE() ---//
  23554. if (have === 0) { break inf_leave; }
  23555. have--;
  23556. hold += input[next++] << bits;
  23557. bits += 8;
  23558. //---//
  23559. }
  23560. if (here_val < 16) {
  23561. //--- DROPBITS(here.bits) ---//
  23562. hold >>>= here_bits;
  23563. bits -= here_bits;
  23564. //---//
  23565. state.lens[state.have++] = here_val;
  23566. }
  23567. else {
  23568. if (here_val === 16) {
  23569. //=== NEEDBITS(here.bits + 2);
  23570. n = here_bits + 2;
  23571. while (bits < n) {
  23572. if (have === 0) { break inf_leave; }
  23573. have--;
  23574. hold += input[next++] << bits;
  23575. bits += 8;
  23576. }
  23577. //===//
  23578. //--- DROPBITS(here.bits) ---//
  23579. hold >>>= here_bits;
  23580. bits -= here_bits;
  23581. //---//
  23582. if (state.have === 0) {
  23583. strm.msg = 'invalid bit length repeat';
  23584. state.mode = BAD;
  23585. break;
  23586. }
  23587. len = state.lens[state.have - 1];
  23588. copy = 3 + (hold & 0x03);//BITS(2);
  23589. //--- DROPBITS(2) ---//
  23590. hold >>>= 2;
  23591. bits -= 2;
  23592. //---//
  23593. }
  23594. else if (here_val === 17) {
  23595. //=== NEEDBITS(here.bits + 3);
  23596. n = here_bits + 3;
  23597. while (bits < n) {
  23598. if (have === 0) { break inf_leave; }
  23599. have--;
  23600. hold += input[next++] << bits;
  23601. bits += 8;
  23602. }
  23603. //===//
  23604. //--- DROPBITS(here.bits) ---//
  23605. hold >>>= here_bits;
  23606. bits -= here_bits;
  23607. //---//
  23608. len = 0;
  23609. copy = 3 + (hold & 0x07);//BITS(3);
  23610. //--- DROPBITS(3) ---//
  23611. hold >>>= 3;
  23612. bits -= 3;
  23613. //---//
  23614. }
  23615. else {
  23616. //=== NEEDBITS(here.bits + 7);
  23617. n = here_bits + 7;
  23618. while (bits < n) {
  23619. if (have === 0) { break inf_leave; }
  23620. have--;
  23621. hold += input[next++] << bits;
  23622. bits += 8;
  23623. }
  23624. //===//
  23625. //--- DROPBITS(here.bits) ---//
  23626. hold >>>= here_bits;
  23627. bits -= here_bits;
  23628. //---//
  23629. len = 0;
  23630. copy = 11 + (hold & 0x7f);//BITS(7);
  23631. //--- DROPBITS(7) ---//
  23632. hold >>>= 7;
  23633. bits -= 7;
  23634. //---//
  23635. }
  23636. if (state.have + copy > state.nlen + state.ndist) {
  23637. strm.msg = 'invalid bit length repeat';
  23638. state.mode = BAD;
  23639. break;
  23640. }
  23641. while (copy--) {
  23642. state.lens[state.have++] = len;
  23643. }
  23644. }
  23645. }
  23646. /* handle error breaks in while */
  23647. if (state.mode === BAD) { break; }
  23648. /* check for end-of-block code (better have one) */
  23649. if (state.lens[256] === 0) {
  23650. strm.msg = 'invalid code -- missing end-of-block';
  23651. state.mode = BAD;
  23652. break;
  23653. }
  23654. /* build code tables -- note: do not change the lenbits or distbits
  23655. values here (9 and 6) without reading the comments in inftrees.h
  23656. concerning the ENOUGH constants, which depend on those values */
  23657. state.lenbits = 9;
  23658. opts = {bits: state.lenbits};
  23659. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  23660. // We have separate tables & no pointers. 2 commented lines below not needed.
  23661. // state.next_index = opts.table_index;
  23662. state.lenbits = opts.bits;
  23663. // state.lencode = state.next;
  23664. if (ret) {
  23665. strm.msg = 'invalid literal/lengths set';
  23666. state.mode = BAD;
  23667. break;
  23668. }
  23669. state.distbits = 6;
  23670. //state.distcode.copy(state.codes);
  23671. // Switch to use dynamic table
  23672. state.distcode = state.distdyn;
  23673. opts = {bits: state.distbits};
  23674. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  23675. // We have separate tables & no pointers. 2 commented lines below not needed.
  23676. // state.next_index = opts.table_index;
  23677. state.distbits = opts.bits;
  23678. // state.distcode = state.next;
  23679. if (ret) {
  23680. strm.msg = 'invalid distances set';
  23681. state.mode = BAD;
  23682. break;
  23683. }
  23684. //Tracev((stderr, 'inflate: codes ok\n'));
  23685. state.mode = LEN_;
  23686. if (flush === Z_TREES) { break inf_leave; }
  23687. /* falls through */
  23688. case LEN_:
  23689. state.mode = LEN;
  23690. /* falls through */
  23691. case LEN:
  23692. if (have >= 6 && left >= 258) {
  23693. //--- RESTORE() ---
  23694. strm.next_out = put;
  23695. strm.avail_out = left;
  23696. strm.next_in = next;
  23697. strm.avail_in = have;
  23698. state.hold = hold;
  23699. state.bits = bits;
  23700. //---
  23701. inflate_fast(strm, _out);
  23702. //--- LOAD() ---
  23703. put = strm.next_out;
  23704. output = strm.output;
  23705. left = strm.avail_out;
  23706. next = strm.next_in;
  23707. input = strm.input;
  23708. have = strm.avail_in;
  23709. hold = state.hold;
  23710. bits = state.bits;
  23711. //---
  23712. if (state.mode === TYPE) {
  23713. state.back = -1;
  23714. }
  23715. break;
  23716. }
  23717. state.back = 0;
  23718. for (;;) {
  23719. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  23720. here_bits = here >>> 24;
  23721. here_op = (here >>> 16) & 0xff;
  23722. here_val = here & 0xffff;
  23723. if (here_bits <= bits) { break; }
  23724. //--- PULLBYTE() ---//
  23725. if (have === 0) { break inf_leave; }
  23726. have--;
  23727. hold += input[next++] << bits;
  23728. bits += 8;
  23729. //---//
  23730. }
  23731. if (here_op && (here_op & 0xf0) === 0) {
  23732. last_bits = here_bits;
  23733. last_op = here_op;
  23734. last_val = here_val;
  23735. for (;;) {
  23736. here = state.lencode[last_val +
  23737. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23738. here_bits = here >>> 24;
  23739. here_op = (here >>> 16) & 0xff;
  23740. here_val = here & 0xffff;
  23741. if ((last_bits + here_bits) <= bits) { break; }
  23742. //--- PULLBYTE() ---//
  23743. if (have === 0) { break inf_leave; }
  23744. have--;
  23745. hold += input[next++] << bits;
  23746. bits += 8;
  23747. //---//
  23748. }
  23749. //--- DROPBITS(last.bits) ---//
  23750. hold >>>= last_bits;
  23751. bits -= last_bits;
  23752. //---//
  23753. state.back += last_bits;
  23754. }
  23755. //--- DROPBITS(here.bits) ---//
  23756. hold >>>= here_bits;
  23757. bits -= here_bits;
  23758. //---//
  23759. state.back += here_bits;
  23760. state.length = here_val;
  23761. if (here_op === 0) {
  23762. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  23763. // "inflate: literal '%c'\n" :
  23764. // "inflate: literal 0x%02x\n", here.val));
  23765. state.mode = LIT;
  23766. break;
  23767. }
  23768. if (here_op & 32) {
  23769. //Tracevv((stderr, "inflate: end of block\n"));
  23770. state.back = -1;
  23771. state.mode = TYPE;
  23772. break;
  23773. }
  23774. if (here_op & 64) {
  23775. strm.msg = 'invalid literal/length code';
  23776. state.mode = BAD;
  23777. break;
  23778. }
  23779. state.extra = here_op & 15;
  23780. state.mode = LENEXT;
  23781. /* falls through */
  23782. case LENEXT:
  23783. if (state.extra) {
  23784. //=== NEEDBITS(state.extra);
  23785. n = state.extra;
  23786. while (bits < n) {
  23787. if (have === 0) { break inf_leave; }
  23788. have--;
  23789. hold += input[next++] << bits;
  23790. bits += 8;
  23791. }
  23792. //===//
  23793. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23794. //--- DROPBITS(state.extra) ---//
  23795. hold >>>= state.extra;
  23796. bits -= state.extra;
  23797. //---//
  23798. state.back += state.extra;
  23799. }
  23800. //Tracevv((stderr, "inflate: length %u\n", state.length));
  23801. state.was = state.length;
  23802. state.mode = DIST;
  23803. /* falls through */
  23804. case DIST:
  23805. for (;;) {
  23806. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  23807. here_bits = here >>> 24;
  23808. here_op = (here >>> 16) & 0xff;
  23809. here_val = here & 0xffff;
  23810. if ((here_bits) <= bits) { break; }
  23811. //--- PULLBYTE() ---//
  23812. if (have === 0) { break inf_leave; }
  23813. have--;
  23814. hold += input[next++] << bits;
  23815. bits += 8;
  23816. //---//
  23817. }
  23818. if ((here_op & 0xf0) === 0) {
  23819. last_bits = here_bits;
  23820. last_op = here_op;
  23821. last_val = here_val;
  23822. for (;;) {
  23823. here = state.distcode[last_val +
  23824. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23825. here_bits = here >>> 24;
  23826. here_op = (here >>> 16) & 0xff;
  23827. here_val = here & 0xffff;
  23828. if ((last_bits + here_bits) <= bits) { break; }
  23829. //--- PULLBYTE() ---//
  23830. if (have === 0) { break inf_leave; }
  23831. have--;
  23832. hold += input[next++] << bits;
  23833. bits += 8;
  23834. //---//
  23835. }
  23836. //--- DROPBITS(last.bits) ---//
  23837. hold >>>= last_bits;
  23838. bits -= last_bits;
  23839. //---//
  23840. state.back += last_bits;
  23841. }
  23842. //--- DROPBITS(here.bits) ---//
  23843. hold >>>= here_bits;
  23844. bits -= here_bits;
  23845. //---//
  23846. state.back += here_bits;
  23847. if (here_op & 64) {
  23848. strm.msg = 'invalid distance code';
  23849. state.mode = BAD;
  23850. break;
  23851. }
  23852. state.offset = here_val;
  23853. state.extra = (here_op) & 15;
  23854. state.mode = DISTEXT;
  23855. /* falls through */
  23856. case DISTEXT:
  23857. if (state.extra) {
  23858. //=== NEEDBITS(state.extra);
  23859. n = state.extra;
  23860. while (bits < n) {
  23861. if (have === 0) { break inf_leave; }
  23862. have--;
  23863. hold += input[next++] << bits;
  23864. bits += 8;
  23865. }
  23866. //===//
  23867. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23868. //--- DROPBITS(state.extra) ---//
  23869. hold >>>= state.extra;
  23870. bits -= state.extra;
  23871. //---//
  23872. state.back += state.extra;
  23873. }
  23874. //#ifdef INFLATE_STRICT
  23875. if (state.offset > state.dmax) {
  23876. strm.msg = 'invalid distance too far back';
  23877. state.mode = BAD;
  23878. break;
  23879. }
  23880. //#endif
  23881. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  23882. state.mode = MATCH;
  23883. /* falls through */
  23884. case MATCH:
  23885. if (left === 0) { break inf_leave; }
  23886. copy = _out - left;
  23887. if (state.offset > copy) { /* copy from window */
  23888. copy = state.offset - copy;
  23889. if (copy > state.whave) {
  23890. if (state.sane) {
  23891. strm.msg = 'invalid distance too far back';
  23892. state.mode = BAD;
  23893. break;
  23894. }
  23895. // (!) This block is disabled in zlib defailts,
  23896. // don't enable it for binary compatibility
  23897. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  23898. // Trace((stderr, "inflate.c too far\n"));
  23899. // copy -= state.whave;
  23900. // if (copy > state.length) { copy = state.length; }
  23901. // if (copy > left) { copy = left; }
  23902. // left -= copy;
  23903. // state.length -= copy;
  23904. // do {
  23905. // output[put++] = 0;
  23906. // } while (--copy);
  23907. // if (state.length === 0) { state.mode = LEN; }
  23908. // break;
  23909. //#endif
  23910. }
  23911. if (copy > state.wnext) {
  23912. copy -= state.wnext;
  23913. from = state.wsize - copy;
  23914. }
  23915. else {
  23916. from = state.wnext - copy;
  23917. }
  23918. if (copy > state.length) { copy = state.length; }
  23919. from_source = state.window;
  23920. }
  23921. else { /* copy from output */
  23922. from_source = output;
  23923. from = put - state.offset;
  23924. copy = state.length;
  23925. }
  23926. if (copy > left) { copy = left; }
  23927. left -= copy;
  23928. state.length -= copy;
  23929. do {
  23930. output[put++] = from_source[from++];
  23931. } while (--copy);
  23932. if (state.length === 0) { state.mode = LEN; }
  23933. break;
  23934. case LIT:
  23935. if (left === 0) { break inf_leave; }
  23936. output[put++] = state.length;
  23937. left--;
  23938. state.mode = LEN;
  23939. break;
  23940. case CHECK:
  23941. if (state.wrap) {
  23942. //=== NEEDBITS(32);
  23943. while (bits < 32) {
  23944. if (have === 0) { break inf_leave; }
  23945. have--;
  23946. // Use '|' insdead of '+' to make sure that result is signed
  23947. hold |= input[next++] << bits;
  23948. bits += 8;
  23949. }
  23950. //===//
  23951. _out -= left;
  23952. strm.total_out += _out;
  23953. state.total += _out;
  23954. if (_out) {
  23955. strm.adler = state.check =
  23956. /*UPDATE(state.check, put - _out, _out);*/
  23957. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  23958. }
  23959. _out = left;
  23960. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  23961. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  23962. strm.msg = 'incorrect data check';
  23963. state.mode = BAD;
  23964. break;
  23965. }
  23966. //=== INITBITS();
  23967. hold = 0;
  23968. bits = 0;
  23969. //===//
  23970. //Tracev((stderr, "inflate: check matches trailer\n"));
  23971. }
  23972. state.mode = LENGTH;
  23973. /* falls through */
  23974. case LENGTH:
  23975. if (state.wrap && state.flags) {
  23976. //=== NEEDBITS(32);
  23977. while (bits < 32) {
  23978. if (have === 0) { break inf_leave; }
  23979. have--;
  23980. hold += input[next++] << bits;
  23981. bits += 8;
  23982. }
  23983. //===//
  23984. if (hold !== (state.total & 0xffffffff)) {
  23985. strm.msg = 'incorrect length check';
  23986. state.mode = BAD;
  23987. break;
  23988. }
  23989. //=== INITBITS();
  23990. hold = 0;
  23991. bits = 0;
  23992. //===//
  23993. //Tracev((stderr, "inflate: length matches trailer\n"));
  23994. }
  23995. state.mode = DONE;
  23996. /* falls through */
  23997. case DONE:
  23998. ret = Z_STREAM_END;
  23999. break inf_leave;
  24000. case BAD:
  24001. ret = Z_DATA_ERROR;
  24002. break inf_leave;
  24003. case MEM:
  24004. return Z_MEM_ERROR;
  24005. case SYNC:
  24006. /* falls through */
  24007. default:
  24008. return Z_STREAM_ERROR;
  24009. }
  24010. }
  24011. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  24012. /*
  24013. Return from inflate(), updating the total counts and the check value.
  24014. If there was no progress during the inflate() call, return a buffer
  24015. error. Call updatewindow() to create and/or update the window state.
  24016. Note: a memory error from inflate() is non-recoverable.
  24017. */
  24018. //--- RESTORE() ---
  24019. strm.next_out = put;
  24020. strm.avail_out = left;
  24021. strm.next_in = next;
  24022. strm.avail_in = have;
  24023. state.hold = hold;
  24024. state.bits = bits;
  24025. //---
  24026. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  24027. (state.mode < CHECK || flush !== Z_FINISH))) {
  24028. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  24029. state.mode = MEM;
  24030. return Z_MEM_ERROR;
  24031. }
  24032. }
  24033. _in -= strm.avail_in;
  24034. _out -= strm.avail_out;
  24035. strm.total_in += _in;
  24036. strm.total_out += _out;
  24037. state.total += _out;
  24038. if (state.wrap && _out) {
  24039. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  24040. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  24041. }
  24042. strm.data_type = state.bits + (state.last ? 64 : 0) +
  24043. (state.mode === TYPE ? 128 : 0) +
  24044. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  24045. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  24046. ret = Z_BUF_ERROR;
  24047. }
  24048. return ret;
  24049. }
  24050. function inflateEnd(strm) {
  24051. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  24052. return Z_STREAM_ERROR;
  24053. }
  24054. var state = strm.state;
  24055. if (state.window) {
  24056. state.window = null;
  24057. }
  24058. strm.state = null;
  24059. return Z_OK;
  24060. }
  24061. function inflateGetHeader(strm, head) {
  24062. var state;
  24063. /* check state */
  24064. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  24065. state = strm.state;
  24066. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  24067. /* save header structure */
  24068. state.head = head;
  24069. head.done = false;
  24070. return Z_OK;
  24071. }
  24072. exports.inflateReset = inflateReset;
  24073. exports.inflateReset2 = inflateReset2;
  24074. exports.inflateResetKeep = inflateResetKeep;
  24075. exports.inflateInit = inflateInit;
  24076. exports.inflateInit2 = inflateInit2;
  24077. exports.inflate = inflate;
  24078. exports.inflateEnd = inflateEnd;
  24079. exports.inflateGetHeader = inflateGetHeader;
  24080. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  24081. /* Not implemented
  24082. exports.inflateCopy = inflateCopy;
  24083. exports.inflateGetDictionary = inflateGetDictionary;
  24084. exports.inflateMark = inflateMark;
  24085. exports.inflatePrime = inflatePrime;
  24086. exports.inflateSetDictionary = inflateSetDictionary;
  24087. exports.inflateSync = inflateSync;
  24088. exports.inflateSyncPoint = inflateSyncPoint;
  24089. exports.inflateUndermine = inflateUndermine;
  24090. */
  24091. },{"../utils/common":75,"./adler32":77,"./crc32":79,"./inffast":82,"./inftrees":84}],84:[function(require,module,exports){
  24092. 'use strict';
  24093. var utils = require('../utils/common');
  24094. var MAXBITS = 15;
  24095. var ENOUGH_LENS = 852;
  24096. var ENOUGH_DISTS = 592;
  24097. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  24098. var CODES = 0;
  24099. var LENS = 1;
  24100. var DISTS = 2;
  24101. var lbase = [ /* Length codes 257..285 base */
  24102. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  24103. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  24104. ];
  24105. var lext = [ /* Length codes 257..285 extra */
  24106. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  24107. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  24108. ];
  24109. var dbase = [ /* Distance codes 0..29 base */
  24110. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  24111. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  24112. 8193, 12289, 16385, 24577, 0, 0
  24113. ];
  24114. var dext = [ /* Distance codes 0..29 extra */
  24115. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  24116. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  24117. 28, 28, 29, 29, 64, 64
  24118. ];
  24119. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  24120. {
  24121. var bits = opts.bits;
  24122. //here = opts.here; /* table entry for duplication */
  24123. var len = 0; /* a code's length in bits */
  24124. var sym = 0; /* index of code symbols */
  24125. var min = 0, max = 0; /* minimum and maximum code lengths */
  24126. var root = 0; /* number of index bits for root table */
  24127. var curr = 0; /* number of index bits for current table */
  24128. var drop = 0; /* code bits to drop for sub-table */
  24129. var left = 0; /* number of prefix codes available */
  24130. var used = 0; /* code entries in table used */
  24131. var huff = 0; /* Huffman code */
  24132. var incr; /* for incrementing code, index */
  24133. var fill; /* index for replicating entries */
  24134. var low; /* low bits for current root entry */
  24135. var mask; /* mask for low root bits */
  24136. var next; /* next available space in table */
  24137. var base = null; /* base value table to use */
  24138. var base_index = 0;
  24139. // var shoextra; /* extra bits table to use */
  24140. var end; /* use base and extra for symbol > end */
  24141. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  24142. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  24143. var extra = null;
  24144. var extra_index = 0;
  24145. var here_bits, here_op, here_val;
  24146. /*
  24147. Process a set of code lengths to create a canonical Huffman code. The
  24148. code lengths are lens[0..codes-1]. Each length corresponds to the
  24149. symbols 0..codes-1. The Huffman code is generated by first sorting the
  24150. symbols by length from short to long, and retaining the symbol order
  24151. for codes with equal lengths. Then the code starts with all zero bits
  24152. for the first code of the shortest length, and the codes are integer
  24153. increments for the same length, and zeros are appended as the length
  24154. increases. For the deflate format, these bits are stored backwards
  24155. from their more natural integer increment ordering, and so when the
  24156. decoding tables are built in the large loop below, the integer codes
  24157. are incremented backwards.
  24158. This routine assumes, but does not check, that all of the entries in
  24159. lens[] are in the range 0..MAXBITS. The caller must assure this.
  24160. 1..MAXBITS is interpreted as that code length. zero means that that
  24161. symbol does not occur in this code.
  24162. The codes are sorted by computing a count of codes for each length,
  24163. creating from that a table of starting indices for each length in the
  24164. sorted table, and then entering the symbols in order in the sorted
  24165. table. The sorted table is work[], with that space being provided by
  24166. the caller.
  24167. The length counts are used for other purposes as well, i.e. finding
  24168. the minimum and maximum length codes, determining if there are any
  24169. codes at all, checking for a valid set of lengths, and looking ahead
  24170. at length counts to determine sub-table sizes when building the
  24171. decoding tables.
  24172. */
  24173. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  24174. for (len = 0; len <= MAXBITS; len++) {
  24175. count[len] = 0;
  24176. }
  24177. for (sym = 0; sym < codes; sym++) {
  24178. count[lens[lens_index + sym]]++;
  24179. }
  24180. /* bound code lengths, force root to be within code lengths */
  24181. root = bits;
  24182. for (max = MAXBITS; max >= 1; max--) {
  24183. if (count[max] !== 0) { break; }
  24184. }
  24185. if (root > max) {
  24186. root = max;
  24187. }
  24188. if (max === 0) { /* no symbols to code at all */
  24189. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  24190. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  24191. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  24192. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  24193. //table.op[opts.table_index] = 64;
  24194. //table.bits[opts.table_index] = 1;
  24195. //table.val[opts.table_index++] = 0;
  24196. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  24197. opts.bits = 1;
  24198. return 0; /* no symbols, but wait for decoding to report error */
  24199. }
  24200. for (min = 1; min < max; min++) {
  24201. if (count[min] !== 0) { break; }
  24202. }
  24203. if (root < min) {
  24204. root = min;
  24205. }
  24206. /* check for an over-subscribed or incomplete set of lengths */
  24207. left = 1;
  24208. for (len = 1; len <= MAXBITS; len++) {
  24209. left <<= 1;
  24210. left -= count[len];
  24211. if (left < 0) {
  24212. return -1;
  24213. } /* over-subscribed */
  24214. }
  24215. if (left > 0 && (type === CODES || max !== 1)) {
  24216. return -1; /* incomplete set */
  24217. }
  24218. /* generate offsets into symbol table for each length for sorting */
  24219. offs[1] = 0;
  24220. for (len = 1; len < MAXBITS; len++) {
  24221. offs[len + 1] = offs[len] + count[len];
  24222. }
  24223. /* sort symbols by length, by symbol order within each length */
  24224. for (sym = 0; sym < codes; sym++) {
  24225. if (lens[lens_index + sym] !== 0) {
  24226. work[offs[lens[lens_index + sym]]++] = sym;
  24227. }
  24228. }
  24229. /*
  24230. Create and fill in decoding tables. In this loop, the table being
  24231. filled is at next and has curr index bits. The code being used is huff
  24232. with length len. That code is converted to an index by dropping drop
  24233. bits off of the bottom. For codes where len is less than drop + curr,
  24234. those top drop + curr - len bits are incremented through all values to
  24235. fill the table with replicated entries.
  24236. root is the number of index bits for the root table. When len exceeds
  24237. root, sub-tables are created pointed to by the root entry with an index
  24238. of the low root bits of huff. This is saved in low to check for when a
  24239. new sub-table should be started. drop is zero when the root table is
  24240. being filled, and drop is root when sub-tables are being filled.
  24241. When a new sub-table is needed, it is necessary to look ahead in the
  24242. code lengths to determine what size sub-table is needed. The length
  24243. counts are used for this, and so count[] is decremented as codes are
  24244. entered in the tables.
  24245. used keeps track of how many table entries have been allocated from the
  24246. provided *table space. It is checked for LENS and DIST tables against
  24247. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  24248. the initial root table size constants. See the comments in inftrees.h
  24249. for more information.
  24250. sym increments through all symbols, and the loop terminates when
  24251. all codes of length max, i.e. all codes, have been processed. This
  24252. routine permits incomplete codes, so another loop after this one fills
  24253. in the rest of the decoding tables with invalid code markers.
  24254. */
  24255. /* set up for code type */
  24256. // poor man optimization - use if-else instead of switch,
  24257. // to avoid deopts in old v8
  24258. if (type === CODES) {
  24259. base = extra = work; /* dummy value--not used */
  24260. end = 19;
  24261. } else if (type === LENS) {
  24262. base = lbase;
  24263. base_index -= 257;
  24264. extra = lext;
  24265. extra_index -= 257;
  24266. end = 256;
  24267. } else { /* DISTS */
  24268. base = dbase;
  24269. extra = dext;
  24270. end = -1;
  24271. }
  24272. /* initialize opts for loop */
  24273. huff = 0; /* starting code */
  24274. sym = 0; /* starting code symbol */
  24275. len = min; /* starting code length */
  24276. next = table_index; /* current table to fill in */
  24277. curr = root; /* current table index bits */
  24278. drop = 0; /* current bits to drop from code for index */
  24279. low = -1; /* trigger new sub-table when len > root */
  24280. used = 1 << root; /* use root table entries */
  24281. mask = used - 1; /* mask for comparing low */
  24282. /* check available table space */
  24283. if ((type === LENS && used > ENOUGH_LENS) ||
  24284. (type === DISTS && used > ENOUGH_DISTS)) {
  24285. return 1;
  24286. }
  24287. var i=0;
  24288. /* process all codes and make table entries */
  24289. for (;;) {
  24290. i++;
  24291. /* create table entry */
  24292. here_bits = len - drop;
  24293. if (work[sym] < end) {
  24294. here_op = 0;
  24295. here_val = work[sym];
  24296. }
  24297. else if (work[sym] > end) {
  24298. here_op = extra[extra_index + work[sym]];
  24299. here_val = base[base_index + work[sym]];
  24300. }
  24301. else {
  24302. here_op = 32 + 64; /* end of block */
  24303. here_val = 0;
  24304. }
  24305. /* replicate for those indices with low len bits equal to huff */
  24306. incr = 1 << (len - drop);
  24307. fill = 1 << curr;
  24308. min = fill; /* save offset to next table */
  24309. do {
  24310. fill -= incr;
  24311. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  24312. } while (fill !== 0);
  24313. /* backwards increment the len-bit code huff */
  24314. incr = 1 << (len - 1);
  24315. while (huff & incr) {
  24316. incr >>= 1;
  24317. }
  24318. if (incr !== 0) {
  24319. huff &= incr - 1;
  24320. huff += incr;
  24321. } else {
  24322. huff = 0;
  24323. }
  24324. /* go to next symbol, update count, len */
  24325. sym++;
  24326. if (--count[len] === 0) {
  24327. if (len === max) { break; }
  24328. len = lens[lens_index + work[sym]];
  24329. }
  24330. /* create new sub-table if needed */
  24331. if (len > root && (huff & mask) !== low) {
  24332. /* if first time, transition to sub-tables */
  24333. if (drop === 0) {
  24334. drop = root;
  24335. }
  24336. /* increment past last table */
  24337. next += min; /* here min is 1 << curr */
  24338. /* determine length of next table */
  24339. curr = len - drop;
  24340. left = 1 << curr;
  24341. while (curr + drop < max) {
  24342. left -= count[curr + drop];
  24343. if (left <= 0) { break; }
  24344. curr++;
  24345. left <<= 1;
  24346. }
  24347. /* check for enough space */
  24348. used += 1 << curr;
  24349. if ((type === LENS && used > ENOUGH_LENS) ||
  24350. (type === DISTS && used > ENOUGH_DISTS)) {
  24351. return 1;
  24352. }
  24353. /* point entry in root table to sub-table */
  24354. low = huff & mask;
  24355. /*table.op[low] = curr;
  24356. table.bits[low] = root;
  24357. table.val[low] = next - opts.table_index;*/
  24358. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  24359. }
  24360. }
  24361. /* fill in remaining table entry if code is incomplete (guaranteed to have
  24362. at most one remaining entry, since if the code is incomplete, the
  24363. maximum code length that was allowed to get this far is one bit) */
  24364. if (huff !== 0) {
  24365. //table.op[next + huff] = 64; /* invalid code marker */
  24366. //table.bits[next + huff] = len - drop;
  24367. //table.val[next + huff] = 0;
  24368. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  24369. }
  24370. /* set return parameters */
  24371. //opts.table_index += used;
  24372. opts.bits = root;
  24373. return 0;
  24374. };
  24375. },{"../utils/common":75}],85:[function(require,module,exports){
  24376. 'use strict';
  24377. module.exports = {
  24378. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  24379. '1': 'stream end', /* Z_STREAM_END 1 */
  24380. '0': '', /* Z_OK 0 */
  24381. '-1': 'file error', /* Z_ERRNO (-1) */
  24382. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  24383. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  24384. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  24385. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  24386. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  24387. };
  24388. },{}],86:[function(require,module,exports){
  24389. 'use strict';
  24390. var utils = require('../utils/common');
  24391. /* Public constants ==========================================================*/
  24392. /* ===========================================================================*/
  24393. //var Z_FILTERED = 1;
  24394. //var Z_HUFFMAN_ONLY = 2;
  24395. //var Z_RLE = 3;
  24396. var Z_FIXED = 4;
  24397. //var Z_DEFAULT_STRATEGY = 0;
  24398. /* Possible values of the data_type field (though see inflate()) */
  24399. var Z_BINARY = 0;
  24400. var Z_TEXT = 1;
  24401. //var Z_ASCII = 1; // = Z_TEXT
  24402. var Z_UNKNOWN = 2;
  24403. /*============================================================================*/
  24404. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  24405. // From zutil.h
  24406. var STORED_BLOCK = 0;
  24407. var STATIC_TREES = 1;
  24408. var DYN_TREES = 2;
  24409. /* The three kinds of block type */
  24410. var MIN_MATCH = 3;
  24411. var MAX_MATCH = 258;
  24412. /* The minimum and maximum match lengths */
  24413. // From deflate.h
  24414. /* ===========================================================================
  24415. * Internal compression state.
  24416. */
  24417. var LENGTH_CODES = 29;
  24418. /* number of length codes, not counting the special END_BLOCK code */
  24419. var LITERALS = 256;
  24420. /* number of literal bytes 0..255 */
  24421. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  24422. /* number of Literal or Length codes, including the END_BLOCK code */
  24423. var D_CODES = 30;
  24424. /* number of distance codes */
  24425. var BL_CODES = 19;
  24426. /* number of codes used to transfer the bit lengths */
  24427. var HEAP_SIZE = 2*L_CODES + 1;
  24428. /* maximum heap size */
  24429. var MAX_BITS = 15;
  24430. /* All codes must not exceed MAX_BITS bits */
  24431. var Buf_size = 16;
  24432. /* size of bit buffer in bi_buf */
  24433. /* ===========================================================================
  24434. * Constants
  24435. */
  24436. var MAX_BL_BITS = 7;
  24437. /* Bit length codes must not exceed MAX_BL_BITS bits */
  24438. var END_BLOCK = 256;
  24439. /* end of block literal code */
  24440. var REP_3_6 = 16;
  24441. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  24442. var REPZ_3_10 = 17;
  24443. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  24444. var REPZ_11_138 = 18;
  24445. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  24446. var extra_lbits = /* extra bits for each length code */
  24447. [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];
  24448. var extra_dbits = /* extra bits for each distance code */
  24449. [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];
  24450. var extra_blbits = /* extra bits for each bit length code */
  24451. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  24452. var bl_order =
  24453. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  24454. /* The lengths of the bit length codes are sent in order of decreasing
  24455. * probability, to avoid transmitting the lengths for unused bit length codes.
  24456. */
  24457. /* ===========================================================================
  24458. * Local data. These are initialized only once.
  24459. */
  24460. // We pre-fill arrays with 0 to avoid uninitialized gaps
  24461. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  24462. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  24463. var static_ltree = new Array((L_CODES+2) * 2);
  24464. zero(static_ltree);
  24465. /* The static literal tree. Since the bit lengths are imposed, there is no
  24466. * need for the L_CODES extra codes used during heap construction. However
  24467. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  24468. * below).
  24469. */
  24470. var static_dtree = new Array(D_CODES * 2);
  24471. zero(static_dtree);
  24472. /* The static distance tree. (Actually a trivial tree since all codes use
  24473. * 5 bits.)
  24474. */
  24475. var _dist_code = new Array(DIST_CODE_LEN);
  24476. zero(_dist_code);
  24477. /* Distance codes. The first 256 values correspond to the distances
  24478. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  24479. * the 15 bit distances.
  24480. */
  24481. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  24482. zero(_length_code);
  24483. /* length code for each normalized match length (0 == MIN_MATCH) */
  24484. var base_length = new Array(LENGTH_CODES);
  24485. zero(base_length);
  24486. /* First normalized length for each code (0 = MIN_MATCH) */
  24487. var base_dist = new Array(D_CODES);
  24488. zero(base_dist);
  24489. /* First normalized distance for each code (0 = distance of 1) */
  24490. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  24491. this.static_tree = static_tree; /* static tree or NULL */
  24492. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  24493. this.extra_base = extra_base; /* base index for extra_bits */
  24494. this.elems = elems; /* max number of elements in the tree */
  24495. this.max_length = max_length; /* max bit length for the codes */
  24496. // show if `static_tree` has data or dummy - needed for monomorphic objects
  24497. this.has_stree = static_tree && static_tree.length;
  24498. };
  24499. var static_l_desc;
  24500. var static_d_desc;
  24501. var static_bl_desc;
  24502. var TreeDesc = function(dyn_tree, stat_desc) {
  24503. this.dyn_tree = dyn_tree; /* the dynamic tree */
  24504. this.max_code = 0; /* largest code with non zero frequency */
  24505. this.stat_desc = stat_desc; /* the corresponding static tree */
  24506. };
  24507. function d_code(dist) {
  24508. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  24509. }
  24510. /* ===========================================================================
  24511. * Output a short LSB first on the stream.
  24512. * IN assertion: there is enough room in pendingBuf.
  24513. */
  24514. function put_short (s, w) {
  24515. // put_byte(s, (uch)((w) & 0xff));
  24516. // put_byte(s, (uch)((ush)(w) >> 8));
  24517. s.pending_buf[s.pending++] = (w) & 0xff;
  24518. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  24519. }
  24520. /* ===========================================================================
  24521. * Send a value on a given number of bits.
  24522. * IN assertion: length <= 16 and value fits in length bits.
  24523. */
  24524. function send_bits(s, value, length) {
  24525. if (s.bi_valid > (Buf_size - length)) {
  24526. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24527. put_short(s, s.bi_buf);
  24528. s.bi_buf = value >> (Buf_size - s.bi_valid);
  24529. s.bi_valid += length - Buf_size;
  24530. } else {
  24531. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24532. s.bi_valid += length;
  24533. }
  24534. }
  24535. function send_code(s, c, tree) {
  24536. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  24537. }
  24538. /* ===========================================================================
  24539. * Reverse the first len bits of a code, using straightforward code (a faster
  24540. * method would use a table)
  24541. * IN assertion: 1 <= len <= 15
  24542. */
  24543. function bi_reverse(code, len) {
  24544. var res = 0;
  24545. do {
  24546. res |= code & 1;
  24547. code >>>= 1;
  24548. res <<= 1;
  24549. } while (--len > 0);
  24550. return res >>> 1;
  24551. }
  24552. /* ===========================================================================
  24553. * Flush the bit buffer, keeping at most 7 bits in it.
  24554. */
  24555. function bi_flush(s) {
  24556. if (s.bi_valid === 16) {
  24557. put_short(s, s.bi_buf);
  24558. s.bi_buf = 0;
  24559. s.bi_valid = 0;
  24560. } else if (s.bi_valid >= 8) {
  24561. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  24562. s.bi_buf >>= 8;
  24563. s.bi_valid -= 8;
  24564. }
  24565. }
  24566. /* ===========================================================================
  24567. * Compute the optimal bit lengths for a tree and update the total bit length
  24568. * for the current block.
  24569. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  24570. * above are the tree nodes sorted by increasing frequency.
  24571. * OUT assertions: the field len is set to the optimal bit length, the
  24572. * array bl_count contains the frequencies for each bit length.
  24573. * The length opt_len is updated; static_len is also updated if stree is
  24574. * not null.
  24575. */
  24576. function gen_bitlen(s, desc)
  24577. // deflate_state *s;
  24578. // tree_desc *desc; /* the tree descriptor */
  24579. {
  24580. var tree = desc.dyn_tree;
  24581. var max_code = desc.max_code;
  24582. var stree = desc.stat_desc.static_tree;
  24583. var has_stree = desc.stat_desc.has_stree;
  24584. var extra = desc.stat_desc.extra_bits;
  24585. var base = desc.stat_desc.extra_base;
  24586. var max_length = desc.stat_desc.max_length;
  24587. var h; /* heap index */
  24588. var n, m; /* iterate over the tree elements */
  24589. var bits; /* bit length */
  24590. var xbits; /* extra bits */
  24591. var f; /* frequency */
  24592. var overflow = 0; /* number of elements with bit length too large */
  24593. for (bits = 0; bits <= MAX_BITS; bits++) {
  24594. s.bl_count[bits] = 0;
  24595. }
  24596. /* In a first pass, compute the optimal bit lengths (which may
  24597. * overflow in the case of the bit length tree).
  24598. */
  24599. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  24600. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  24601. n = s.heap[h];
  24602. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  24603. if (bits > max_length) {
  24604. bits = max_length;
  24605. overflow++;
  24606. }
  24607. tree[n*2 + 1]/*.Len*/ = bits;
  24608. /* We overwrite tree[n].Dad which is no longer needed */
  24609. if (n > max_code) { continue; } /* not a leaf node */
  24610. s.bl_count[bits]++;
  24611. xbits = 0;
  24612. if (n >= base) {
  24613. xbits = extra[n-base];
  24614. }
  24615. f = tree[n * 2]/*.Freq*/;
  24616. s.opt_len += f * (bits + xbits);
  24617. if (has_stree) {
  24618. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  24619. }
  24620. }
  24621. if (overflow === 0) { return; }
  24622. // Trace((stderr,"\nbit length overflow\n"));
  24623. /* This happens for example on obj2 and pic of the Calgary corpus */
  24624. /* Find the first bit length which could increase: */
  24625. do {
  24626. bits = max_length-1;
  24627. while (s.bl_count[bits] === 0) { bits--; }
  24628. s.bl_count[bits]--; /* move one leaf down the tree */
  24629. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  24630. s.bl_count[max_length]--;
  24631. /* The brother of the overflow item also moves one step up,
  24632. * but this does not affect bl_count[max_length]
  24633. */
  24634. overflow -= 2;
  24635. } while (overflow > 0);
  24636. /* Now recompute all bit lengths, scanning in increasing frequency.
  24637. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  24638. * lengths instead of fixing only the wrong ones. This idea is taken
  24639. * from 'ar' written by Haruhiko Okumura.)
  24640. */
  24641. for (bits = max_length; bits !== 0; bits--) {
  24642. n = s.bl_count[bits];
  24643. while (n !== 0) {
  24644. m = s.heap[--h];
  24645. if (m > max_code) { continue; }
  24646. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  24647. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  24648. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  24649. tree[m*2 + 1]/*.Len*/ = bits;
  24650. }
  24651. n--;
  24652. }
  24653. }
  24654. }
  24655. /* ===========================================================================
  24656. * Generate the codes for a given tree and bit counts (which need not be
  24657. * optimal).
  24658. * IN assertion: the array bl_count contains the bit length statistics for
  24659. * the given tree and the field len is set for all tree elements.
  24660. * OUT assertion: the field code is set for all tree elements of non
  24661. * zero code length.
  24662. */
  24663. function gen_codes(tree, max_code, bl_count)
  24664. // ct_data *tree; /* the tree to decorate */
  24665. // int max_code; /* largest code with non zero frequency */
  24666. // ushf *bl_count; /* number of codes at each bit length */
  24667. {
  24668. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  24669. var code = 0; /* running code value */
  24670. var bits; /* bit index */
  24671. var n; /* code index */
  24672. /* The distribution counts are first used to generate the code values
  24673. * without bit reversal.
  24674. */
  24675. for (bits = 1; bits <= MAX_BITS; bits++) {
  24676. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  24677. }
  24678. /* Check that the bit counts in bl_count are consistent. The last code
  24679. * must be all ones.
  24680. */
  24681. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  24682. // "inconsistent bit counts");
  24683. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  24684. for (n = 0; n <= max_code; n++) {
  24685. var len = tree[n*2 + 1]/*.Len*/;
  24686. if (len === 0) { continue; }
  24687. /* Now reverse the bits */
  24688. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  24689. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  24690. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  24691. }
  24692. }
  24693. /* ===========================================================================
  24694. * Initialize the various 'constant' tables.
  24695. */
  24696. function tr_static_init() {
  24697. var n; /* iterates over tree elements */
  24698. var bits; /* bit counter */
  24699. var length; /* length value */
  24700. var code; /* code value */
  24701. var dist; /* distance index */
  24702. var bl_count = new Array(MAX_BITS+1);
  24703. /* number of codes at each bit length for an optimal tree */
  24704. // do check in _tr_init()
  24705. //if (static_init_done) return;
  24706. /* For some embedded targets, global variables are not initialized: */
  24707. /*#ifdef NO_INIT_GLOBAL_POINTERS
  24708. static_l_desc.static_tree = static_ltree;
  24709. static_l_desc.extra_bits = extra_lbits;
  24710. static_d_desc.static_tree = static_dtree;
  24711. static_d_desc.extra_bits = extra_dbits;
  24712. static_bl_desc.extra_bits = extra_blbits;
  24713. #endif*/
  24714. /* Initialize the mapping length (0..255) -> length code (0..28) */
  24715. length = 0;
  24716. for (code = 0; code < LENGTH_CODES-1; code++) {
  24717. base_length[code] = length;
  24718. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  24719. _length_code[length++] = code;
  24720. }
  24721. }
  24722. //Assert (length == 256, "tr_static_init: length != 256");
  24723. /* Note that the length 255 (match length 258) can be represented
  24724. * in two different ways: code 284 + 5 bits or code 285, so we
  24725. * overwrite length_code[255] to use the best encoding:
  24726. */
  24727. _length_code[length-1] = code;
  24728. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  24729. dist = 0;
  24730. for (code = 0 ; code < 16; code++) {
  24731. base_dist[code] = dist;
  24732. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  24733. _dist_code[dist++] = code;
  24734. }
  24735. }
  24736. //Assert (dist == 256, "tr_static_init: dist != 256");
  24737. dist >>= 7; /* from now on, all distances are divided by 128 */
  24738. for (; code < D_CODES; code++) {
  24739. base_dist[code] = dist << 7;
  24740. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  24741. _dist_code[256 + dist++] = code;
  24742. }
  24743. }
  24744. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  24745. /* Construct the codes of the static literal tree */
  24746. for (bits = 0; bits <= MAX_BITS; bits++) {
  24747. bl_count[bits] = 0;
  24748. }
  24749. n = 0;
  24750. while (n <= 143) {
  24751. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24752. n++;
  24753. bl_count[8]++;
  24754. }
  24755. while (n <= 255) {
  24756. static_ltree[n*2 + 1]/*.Len*/ = 9;
  24757. n++;
  24758. bl_count[9]++;
  24759. }
  24760. while (n <= 279) {
  24761. static_ltree[n*2 + 1]/*.Len*/ = 7;
  24762. n++;
  24763. bl_count[7]++;
  24764. }
  24765. while (n <= 287) {
  24766. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24767. n++;
  24768. bl_count[8]++;
  24769. }
  24770. /* Codes 286 and 287 do not exist, but we must include them in the
  24771. * tree construction to get a canonical Huffman tree (longest code
  24772. * all ones)
  24773. */
  24774. gen_codes(static_ltree, L_CODES+1, bl_count);
  24775. /* The static distance tree is trivial: */
  24776. for (n = 0; n < D_CODES; n++) {
  24777. static_dtree[n*2 + 1]/*.Len*/ = 5;
  24778. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  24779. }
  24780. // Now data ready and we can init static trees
  24781. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  24782. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  24783. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  24784. //static_init_done = true;
  24785. }
  24786. /* ===========================================================================
  24787. * Initialize a new block.
  24788. */
  24789. function init_block(s) {
  24790. var n; /* iterates over tree elements */
  24791. /* Initialize the trees. */
  24792. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  24793. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  24794. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  24795. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  24796. s.opt_len = s.static_len = 0;
  24797. s.last_lit = s.matches = 0;
  24798. }
  24799. /* ===========================================================================
  24800. * Flush the bit buffer and align the output on a byte boundary
  24801. */
  24802. function bi_windup(s)
  24803. {
  24804. if (s.bi_valid > 8) {
  24805. put_short(s, s.bi_buf);
  24806. } else if (s.bi_valid > 0) {
  24807. //put_byte(s, (Byte)s->bi_buf);
  24808. s.pending_buf[s.pending++] = s.bi_buf;
  24809. }
  24810. s.bi_buf = 0;
  24811. s.bi_valid = 0;
  24812. }
  24813. /* ===========================================================================
  24814. * Copy a stored block, storing first the length and its
  24815. * one's complement if requested.
  24816. */
  24817. function copy_block(s, buf, len, header)
  24818. //DeflateState *s;
  24819. //charf *buf; /* the input data */
  24820. //unsigned len; /* its length */
  24821. //int header; /* true if block header must be written */
  24822. {
  24823. bi_windup(s); /* align on byte boundary */
  24824. if (header) {
  24825. put_short(s, len);
  24826. put_short(s, ~len);
  24827. }
  24828. // while (len--) {
  24829. // put_byte(s, *buf++);
  24830. // }
  24831. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  24832. s.pending += len;
  24833. }
  24834. /* ===========================================================================
  24835. * Compares to subtrees, using the tree depth as tie breaker when
  24836. * the subtrees have equal frequency. This minimizes the worst case length.
  24837. */
  24838. function smaller(tree, n, m, depth) {
  24839. var _n2 = n*2;
  24840. var _m2 = m*2;
  24841. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  24842. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  24843. }
  24844. /* ===========================================================================
  24845. * Restore the heap property by moving down the tree starting at node k,
  24846. * exchanging a node with the smallest of its two sons if necessary, stopping
  24847. * when the heap property is re-established (each father smaller than its
  24848. * two sons).
  24849. */
  24850. function pqdownheap(s, tree, k)
  24851. // deflate_state *s;
  24852. // ct_data *tree; /* the tree to restore */
  24853. // int k; /* node to move down */
  24854. {
  24855. var v = s.heap[k];
  24856. var j = k << 1; /* left son of k */
  24857. while (j <= s.heap_len) {
  24858. /* Set j to the smallest of the two sons: */
  24859. if (j < s.heap_len &&
  24860. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  24861. j++;
  24862. }
  24863. /* Exit if v is smaller than both sons */
  24864. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  24865. /* Exchange v with the smallest son */
  24866. s.heap[k] = s.heap[j];
  24867. k = j;
  24868. /* And continue down the tree, setting j to the left son of k */
  24869. j <<= 1;
  24870. }
  24871. s.heap[k] = v;
  24872. }
  24873. // inlined manually
  24874. // var SMALLEST = 1;
  24875. /* ===========================================================================
  24876. * Send the block data compressed using the given Huffman trees
  24877. */
  24878. function compress_block(s, ltree, dtree)
  24879. // deflate_state *s;
  24880. // const ct_data *ltree; /* literal tree */
  24881. // const ct_data *dtree; /* distance tree */
  24882. {
  24883. var dist; /* distance of matched string */
  24884. var lc; /* match length or unmatched char (if dist == 0) */
  24885. var lx = 0; /* running index in l_buf */
  24886. var code; /* the code to send */
  24887. var extra; /* number of extra bits to send */
  24888. if (s.last_lit !== 0) {
  24889. do {
  24890. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  24891. lc = s.pending_buf[s.l_buf + lx];
  24892. lx++;
  24893. if (dist === 0) {
  24894. send_code(s, lc, ltree); /* send a literal byte */
  24895. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  24896. } else {
  24897. /* Here, lc is the match length - MIN_MATCH */
  24898. code = _length_code[lc];
  24899. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  24900. extra = extra_lbits[code];
  24901. if (extra !== 0) {
  24902. lc -= base_length[code];
  24903. send_bits(s, lc, extra); /* send the extra length bits */
  24904. }
  24905. dist--; /* dist is now the match distance - 1 */
  24906. code = d_code(dist);
  24907. //Assert (code < D_CODES, "bad d_code");
  24908. send_code(s, code, dtree); /* send the distance code */
  24909. extra = extra_dbits[code];
  24910. if (extra !== 0) {
  24911. dist -= base_dist[code];
  24912. send_bits(s, dist, extra); /* send the extra distance bits */
  24913. }
  24914. } /* literal or match pair ? */
  24915. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  24916. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  24917. // "pendingBuf overflow");
  24918. } while (lx < s.last_lit);
  24919. }
  24920. send_code(s, END_BLOCK, ltree);
  24921. }
  24922. /* ===========================================================================
  24923. * Construct one Huffman tree and assigns the code bit strings and lengths.
  24924. * Update the total bit length for the current block.
  24925. * IN assertion: the field freq is set for all tree elements.
  24926. * OUT assertions: the fields len and code are set to the optimal bit length
  24927. * and corresponding code. The length opt_len is updated; static_len is
  24928. * also updated if stree is not null. The field max_code is set.
  24929. */
  24930. function build_tree(s, desc)
  24931. // deflate_state *s;
  24932. // tree_desc *desc; /* the tree descriptor */
  24933. {
  24934. var tree = desc.dyn_tree;
  24935. var stree = desc.stat_desc.static_tree;
  24936. var has_stree = desc.stat_desc.has_stree;
  24937. var elems = desc.stat_desc.elems;
  24938. var n, m; /* iterate over heap elements */
  24939. var max_code = -1; /* largest code with non zero frequency */
  24940. var node; /* new node being created */
  24941. /* Construct the initial heap, with least frequent element in
  24942. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  24943. * heap[0] is not used.
  24944. */
  24945. s.heap_len = 0;
  24946. s.heap_max = HEAP_SIZE;
  24947. for (n = 0; n < elems; n++) {
  24948. if (tree[n * 2]/*.Freq*/ !== 0) {
  24949. s.heap[++s.heap_len] = max_code = n;
  24950. s.depth[n] = 0;
  24951. } else {
  24952. tree[n*2 + 1]/*.Len*/ = 0;
  24953. }
  24954. }
  24955. /* The pkzip format requires that at least one distance code exists,
  24956. * and that at least one bit should be sent even if there is only one
  24957. * possible code. So to avoid special checks later on we force at least
  24958. * two codes of non zero frequency.
  24959. */
  24960. while (s.heap_len < 2) {
  24961. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  24962. tree[node * 2]/*.Freq*/ = 1;
  24963. s.depth[node] = 0;
  24964. s.opt_len--;
  24965. if (has_stree) {
  24966. s.static_len -= stree[node*2 + 1]/*.Len*/;
  24967. }
  24968. /* node is 0 or 1 so it does not have extra bits */
  24969. }
  24970. desc.max_code = max_code;
  24971. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  24972. * establish sub-heaps of increasing lengths:
  24973. */
  24974. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  24975. /* Construct the Huffman tree by repeatedly combining the least two
  24976. * frequent nodes.
  24977. */
  24978. node = elems; /* next internal node of the tree */
  24979. do {
  24980. //pqremove(s, tree, n); /* n = node of least frequency */
  24981. /*** pqremove ***/
  24982. n = s.heap[1/*SMALLEST*/];
  24983. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  24984. pqdownheap(s, tree, 1/*SMALLEST*/);
  24985. /***/
  24986. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  24987. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  24988. s.heap[--s.heap_max] = m;
  24989. /* Create a new node father of n and m */
  24990. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  24991. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  24992. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  24993. /* and insert the new node in the heap */
  24994. s.heap[1/*SMALLEST*/] = node++;
  24995. pqdownheap(s, tree, 1/*SMALLEST*/);
  24996. } while (s.heap_len >= 2);
  24997. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  24998. /* At this point, the fields freq and dad are set. We can now
  24999. * generate the bit lengths.
  25000. */
  25001. gen_bitlen(s, desc);
  25002. /* The field len is now set, we can generate the bit codes */
  25003. gen_codes(tree, max_code, s.bl_count);
  25004. }
  25005. /* ===========================================================================
  25006. * Scan a literal or distance tree to determine the frequencies of the codes
  25007. * in the bit length tree.
  25008. */
  25009. function scan_tree(s, tree, max_code)
  25010. // deflate_state *s;
  25011. // ct_data *tree; /* the tree to be scanned */
  25012. // int max_code; /* and its largest code of non zero frequency */
  25013. {
  25014. var n; /* iterates over all tree elements */
  25015. var prevlen = -1; /* last emitted length */
  25016. var curlen; /* length of current code */
  25017. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  25018. var count = 0; /* repeat count of the current code */
  25019. var max_count = 7; /* max repeat count */
  25020. var min_count = 4; /* min repeat count */
  25021. if (nextlen === 0) {
  25022. max_count = 138;
  25023. min_count = 3;
  25024. }
  25025. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  25026. for (n = 0; n <= max_code; n++) {
  25027. curlen = nextlen;
  25028. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  25029. if (++count < max_count && curlen === nextlen) {
  25030. continue;
  25031. } else if (count < min_count) {
  25032. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  25033. } else if (curlen !== 0) {
  25034. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  25035. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  25036. } else if (count <= 10) {
  25037. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  25038. } else {
  25039. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  25040. }
  25041. count = 0;
  25042. prevlen = curlen;
  25043. if (nextlen === 0) {
  25044. max_count = 138;
  25045. min_count = 3;
  25046. } else if (curlen === nextlen) {
  25047. max_count = 6;
  25048. min_count = 3;
  25049. } else {
  25050. max_count = 7;
  25051. min_count = 4;
  25052. }
  25053. }
  25054. }
  25055. /* ===========================================================================
  25056. * Send a literal or distance tree in compressed form, using the codes in
  25057. * bl_tree.
  25058. */
  25059. function send_tree(s, tree, max_code)
  25060. // deflate_state *s;
  25061. // ct_data *tree; /* the tree to be scanned */
  25062. // int max_code; /* and its largest code of non zero frequency */
  25063. {
  25064. var n; /* iterates over all tree elements */
  25065. var prevlen = -1; /* last emitted length */
  25066. var curlen; /* length of current code */
  25067. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  25068. var count = 0; /* repeat count of the current code */
  25069. var max_count = 7; /* max repeat count */
  25070. var min_count = 4; /* min repeat count */
  25071. /* tree[max_code+1].Len = -1; */ /* guard already set */
  25072. if (nextlen === 0) {
  25073. max_count = 138;
  25074. min_count = 3;
  25075. }
  25076. for (n = 0; n <= max_code; n++) {
  25077. curlen = nextlen;
  25078. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  25079. if (++count < max_count && curlen === nextlen) {
  25080. continue;
  25081. } else if (count < min_count) {
  25082. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  25083. } else if (curlen !== 0) {
  25084. if (curlen !== prevlen) {
  25085. send_code(s, curlen, s.bl_tree);
  25086. count--;
  25087. }
  25088. //Assert(count >= 3 && count <= 6, " 3_6?");
  25089. send_code(s, REP_3_6, s.bl_tree);
  25090. send_bits(s, count-3, 2);
  25091. } else if (count <= 10) {
  25092. send_code(s, REPZ_3_10, s.bl_tree);
  25093. send_bits(s, count-3, 3);
  25094. } else {
  25095. send_code(s, REPZ_11_138, s.bl_tree);
  25096. send_bits(s, count-11, 7);
  25097. }
  25098. count = 0;
  25099. prevlen = curlen;
  25100. if (nextlen === 0) {
  25101. max_count = 138;
  25102. min_count = 3;
  25103. } else if (curlen === nextlen) {
  25104. max_count = 6;
  25105. min_count = 3;
  25106. } else {
  25107. max_count = 7;
  25108. min_count = 4;
  25109. }
  25110. }
  25111. }
  25112. /* ===========================================================================
  25113. * Construct the Huffman tree for the bit lengths and return the index in
  25114. * bl_order of the last bit length code to send.
  25115. */
  25116. function build_bl_tree(s) {
  25117. var max_blindex; /* index of last bit length code of non zero freq */
  25118. /* Determine the bit length frequencies for literal and distance trees */
  25119. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  25120. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  25121. /* Build the bit length tree: */
  25122. build_tree(s, s.bl_desc);
  25123. /* opt_len now includes the length of the tree representations, except
  25124. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  25125. */
  25126. /* Determine the number of bit length codes to send. The pkzip format
  25127. * requires that at least 4 bit length codes be sent. (appnote.txt says
  25128. * 3 but the actual value used is 4.)
  25129. */
  25130. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  25131. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  25132. break;
  25133. }
  25134. }
  25135. /* Update opt_len to include the bit length tree and counts */
  25136. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  25137. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  25138. // s->opt_len, s->static_len));
  25139. return max_blindex;
  25140. }
  25141. /* ===========================================================================
  25142. * Send the header for a block using dynamic Huffman trees: the counts, the
  25143. * lengths of the bit length codes, the literal tree and the distance tree.
  25144. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  25145. */
  25146. function send_all_trees(s, lcodes, dcodes, blcodes)
  25147. // deflate_state *s;
  25148. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  25149. {
  25150. var rank; /* index in bl_order */
  25151. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  25152. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  25153. // "too many codes");
  25154. //Tracev((stderr, "\nbl counts: "));
  25155. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  25156. send_bits(s, dcodes-1, 5);
  25157. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  25158. for (rank = 0; rank < blcodes; rank++) {
  25159. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  25160. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  25161. }
  25162. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  25163. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  25164. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  25165. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  25166. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  25167. }
  25168. /* ===========================================================================
  25169. * Check if the data type is TEXT or BINARY, using the following algorithm:
  25170. * - TEXT if the two conditions below are satisfied:
  25171. * a) There are no non-portable control characters belonging to the
  25172. * "black list" (0..6, 14..25, 28..31).
  25173. * b) There is at least one printable character belonging to the
  25174. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  25175. * - BINARY otherwise.
  25176. * - The following partially-portable control characters form a
  25177. * "gray list" that is ignored in this detection algorithm:
  25178. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  25179. * IN assertion: the fields Freq of dyn_ltree are set.
  25180. */
  25181. function detect_data_type(s) {
  25182. /* black_mask is the bit mask of black-listed bytes
  25183. * set bits 0..6, 14..25, and 28..31
  25184. * 0xf3ffc07f = binary 11110011111111111100000001111111
  25185. */
  25186. var black_mask = 0xf3ffc07f;
  25187. var n;
  25188. /* Check for non-textual ("black-listed") bytes. */
  25189. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  25190. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  25191. return Z_BINARY;
  25192. }
  25193. }
  25194. /* Check for textual ("white-listed") bytes. */
  25195. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  25196. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  25197. return Z_TEXT;
  25198. }
  25199. for (n = 32; n < LITERALS; n++) {
  25200. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  25201. return Z_TEXT;
  25202. }
  25203. }
  25204. /* There are no "black-listed" or "white-listed" bytes:
  25205. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  25206. */
  25207. return Z_BINARY;
  25208. }
  25209. var static_init_done = false;
  25210. /* ===========================================================================
  25211. * Initialize the tree data structures for a new zlib stream.
  25212. */
  25213. function _tr_init(s)
  25214. {
  25215. if (!static_init_done) {
  25216. tr_static_init();
  25217. static_init_done = true;
  25218. }
  25219. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  25220. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  25221. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  25222. s.bi_buf = 0;
  25223. s.bi_valid = 0;
  25224. /* Initialize the first block of the first file: */
  25225. init_block(s);
  25226. }
  25227. /* ===========================================================================
  25228. * Send a stored block
  25229. */
  25230. function _tr_stored_block(s, buf, stored_len, last)
  25231. //DeflateState *s;
  25232. //charf *buf; /* input block */
  25233. //ulg stored_len; /* length of input block */
  25234. //int last; /* one if this is the last block for a file */
  25235. {
  25236. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  25237. copy_block(s, buf, stored_len, true); /* with header */
  25238. }
  25239. /* ===========================================================================
  25240. * Send one empty static block to give enough lookahead for inflate.
  25241. * This takes 10 bits, of which 7 may remain in the bit buffer.
  25242. */
  25243. function _tr_align(s) {
  25244. send_bits(s, STATIC_TREES<<1, 3);
  25245. send_code(s, END_BLOCK, static_ltree);
  25246. bi_flush(s);
  25247. }
  25248. /* ===========================================================================
  25249. * Determine the best encoding for the current block: dynamic trees, static
  25250. * trees or store, and output the encoded block to the zip file.
  25251. */
  25252. function _tr_flush_block(s, buf, stored_len, last)
  25253. //DeflateState *s;
  25254. //charf *buf; /* input block, or NULL if too old */
  25255. //ulg stored_len; /* length of input block */
  25256. //int last; /* one if this is the last block for a file */
  25257. {
  25258. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  25259. var max_blindex = 0; /* index of last bit length code of non zero freq */
  25260. /* Build the Huffman trees unless a stored block is forced */
  25261. if (s.level > 0) {
  25262. /* Check if the file is binary or text */
  25263. if (s.strm.data_type === Z_UNKNOWN) {
  25264. s.strm.data_type = detect_data_type(s);
  25265. }
  25266. /* Construct the literal and distance trees */
  25267. build_tree(s, s.l_desc);
  25268. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  25269. // s->static_len));
  25270. build_tree(s, s.d_desc);
  25271. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  25272. // s->static_len));
  25273. /* At this point, opt_len and static_len are the total bit lengths of
  25274. * the compressed block data, excluding the tree representations.
  25275. */
  25276. /* Build the bit length tree for the above two trees, and get the index
  25277. * in bl_order of the last bit length code to send.
  25278. */
  25279. max_blindex = build_bl_tree(s);
  25280. /* Determine the best encoding. Compute the block lengths in bytes. */
  25281. opt_lenb = (s.opt_len+3+7) >>> 3;
  25282. static_lenb = (s.static_len+3+7) >>> 3;
  25283. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  25284. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  25285. // s->last_lit));
  25286. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  25287. } else {
  25288. // Assert(buf != (char*)0, "lost buf");
  25289. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  25290. }
  25291. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  25292. /* 4: two words for the lengths */
  25293. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  25294. * Otherwise we can't have processed more than WSIZE input bytes since
  25295. * the last block flush, because compression would have been
  25296. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  25297. * transform a block into a stored block.
  25298. */
  25299. _tr_stored_block(s, buf, stored_len, last);
  25300. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  25301. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  25302. compress_block(s, static_ltree, static_dtree);
  25303. } else {
  25304. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  25305. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  25306. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  25307. }
  25308. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  25309. /* The above check is made mod 2^32, for files larger than 512 MB
  25310. * and uLong implemented on 32 bits.
  25311. */
  25312. init_block(s);
  25313. if (last) {
  25314. bi_windup(s);
  25315. }
  25316. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  25317. // s->compressed_len-7*last));
  25318. }
  25319. /* ===========================================================================
  25320. * Save the match info and tally the frequency counts. Return true if
  25321. * the current block must be flushed.
  25322. */
  25323. function _tr_tally(s, dist, lc)
  25324. // deflate_state *s;
  25325. // unsigned dist; /* distance of matched string */
  25326. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  25327. {
  25328. //var out_length, in_length, dcode;
  25329. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  25330. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  25331. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  25332. s.last_lit++;
  25333. if (dist === 0) {
  25334. /* lc is the unmatched char */
  25335. s.dyn_ltree[lc*2]/*.Freq*/++;
  25336. } else {
  25337. s.matches++;
  25338. /* Here, lc is the match length - MIN_MATCH */
  25339. dist--; /* dist = match distance - 1 */
  25340. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  25341. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  25342. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  25343. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  25344. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  25345. }
  25346. // (!) This block is disabled in zlib defailts,
  25347. // don't enable it for binary compatibility
  25348. //#ifdef TRUNCATE_BLOCK
  25349. // /* Try to guess if it is profitable to stop the current block here */
  25350. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  25351. // /* Compute an upper bound for the compressed length */
  25352. // out_length = s.last_lit*8;
  25353. // in_length = s.strstart - s.block_start;
  25354. //
  25355. // for (dcode = 0; dcode < D_CODES; dcode++) {
  25356. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  25357. // }
  25358. // out_length >>>= 3;
  25359. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  25360. // // s->last_lit, in_length, out_length,
  25361. // // 100L - out_length*100L/in_length));
  25362. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  25363. // return true;
  25364. // }
  25365. // }
  25366. //#endif
  25367. return (s.last_lit === s.lit_bufsize-1);
  25368. /* We avoid equality with lit_bufsize because of wraparound at 64K
  25369. * on 16 bit machines and because stored blocks are restricted to
  25370. * 64K-1 bytes.
  25371. */
  25372. }
  25373. exports._tr_init = _tr_init;
  25374. exports._tr_stored_block = _tr_stored_block;
  25375. exports._tr_flush_block = _tr_flush_block;
  25376. exports._tr_tally = _tr_tally;
  25377. exports._tr_align = _tr_align;
  25378. },{"../utils/common":75}],87:[function(require,module,exports){
  25379. 'use strict';
  25380. function ZStream() {
  25381. /* next input byte */
  25382. this.input = null; // JS specific, because we have no pointers
  25383. this.next_in = 0;
  25384. /* number of bytes available at input */
  25385. this.avail_in = 0;
  25386. /* total number of input bytes read so far */
  25387. this.total_in = 0;
  25388. /* next output byte should be put there */
  25389. this.output = null; // JS specific, because we have no pointers
  25390. this.next_out = 0;
  25391. /* remaining free space at output */
  25392. this.avail_out = 0;
  25393. /* total number of bytes output so far */
  25394. this.total_out = 0;
  25395. /* last error message, NULL if no error */
  25396. this.msg = ''/*Z_NULL*/;
  25397. /* not visible by applications */
  25398. this.state = null;
  25399. /* best guess about the data type: binary or text */
  25400. this.data_type = 2/*Z_UNKNOWN*/;
  25401. /* adler32 value of the uncompressed data */
  25402. this.adler = 0;
  25403. }
  25404. module.exports = ZStream;
  25405. },{}],88:[function(require,module,exports){
  25406. module.exports = require('./lib/retry');
  25407. },{"./lib/retry":89}],89:[function(require,module,exports){
  25408. var RetryOperation = require('./retry_operation');
  25409. exports.operation = function(options) {
  25410. var timeouts = exports.timeouts(options);
  25411. return new RetryOperation(timeouts);
  25412. };
  25413. exports.timeouts = function(options) {
  25414. if (options instanceof Array) {
  25415. return [].concat(options);
  25416. }
  25417. var opts = {
  25418. retries: 10,
  25419. factor: 2,
  25420. minTimeout: 1 * 1000,
  25421. maxTimeout: Infinity,
  25422. randomize: false
  25423. };
  25424. for (var key in options) {
  25425. opts[key] = options[key];
  25426. }
  25427. if (opts.minTimeout > opts.maxTimeout) {
  25428. throw new Error('minTimeout is greater than maxTimeout');
  25429. }
  25430. var timeouts = [];
  25431. for (var i = 0; i < opts.retries; i++) {
  25432. timeouts.push(this._createTimeout(i, opts));
  25433. }
  25434. // sort the array numerically ascending
  25435. timeouts.sort(function(a,b) {
  25436. return a - b;
  25437. });
  25438. return timeouts;
  25439. };
  25440. exports._createTimeout = function(attempt, opts) {
  25441. var random = (opts.randomize)
  25442. ? (Math.random() + 1)
  25443. : 1;
  25444. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  25445. timeout = Math.min(timeout, opts.maxTimeout);
  25446. return timeout;
  25447. };
  25448. },{"./retry_operation":90}],90:[function(require,module,exports){
  25449. function RetryOperation(timeouts) {
  25450. this._timeouts = timeouts;
  25451. this._fn = null;
  25452. this._errors = [];
  25453. this._attempts = 1;
  25454. this._operationTimeout = null;
  25455. this._operationTimeoutCb = null;
  25456. this._timeout = null;
  25457. }
  25458. module.exports = RetryOperation;
  25459. RetryOperation.prototype.retry = function(err) {
  25460. if (this._timeout) {
  25461. clearTimeout(this._timeout);
  25462. }
  25463. if (!err) {
  25464. return false;
  25465. }
  25466. this._errors.push(err);
  25467. var timeout = this._timeouts.shift();
  25468. if (timeout === undefined) {
  25469. return false;
  25470. }
  25471. this._attempts++;
  25472. var self = this;
  25473. setTimeout(function() {
  25474. self._fn(self._attempts);
  25475. if (self._operationTimeoutCb) {
  25476. self._timeout = setTimeout(function() {
  25477. self._operationTimeoutCb(self._attempts);
  25478. }, self._operationTimeout);
  25479. }
  25480. }, timeout);
  25481. return true;
  25482. };
  25483. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  25484. this._fn = fn;
  25485. if (timeoutOps) {
  25486. if (timeoutOps.timeout) {
  25487. this._operationTimeout = timeoutOps.timeout;
  25488. }
  25489. if (timeoutOps.cb) {
  25490. this._operationTimeoutCb = timeoutOps.cb;
  25491. }
  25492. }
  25493. this._fn(this._attempts);
  25494. var self = this;
  25495. if (this._operationTimeoutCb) {
  25496. this._timeout = setTimeout(function() {
  25497. self._operationTimeoutCb();
  25498. }, self._operationTimeout);
  25499. }
  25500. };
  25501. RetryOperation.prototype.try = function(fn) {
  25502. console.log('Using RetryOperation.try() is deprecated');
  25503. this.attempt(fn);
  25504. };
  25505. RetryOperation.prototype.start = function(fn) {
  25506. console.log('Using RetryOperation.start() is deprecated');
  25507. this.attempt(fn);
  25508. };
  25509. RetryOperation.prototype.start = RetryOperation.prototype.try;
  25510. RetryOperation.prototype.errors = function() {
  25511. return this._errors;
  25512. };
  25513. RetryOperation.prototype.attempts = function() {
  25514. return this._attempts;
  25515. };
  25516. RetryOperation.prototype.mainError = function() {
  25517. if (this._errors.length === 0) {
  25518. return null;
  25519. }
  25520. var counts = {};
  25521. var mainError = null;
  25522. var mainErrorCount = 0;
  25523. for (var i = 0; i < this._errors.length; i++) {
  25524. var error = this._errors[i];
  25525. var message = error.message;
  25526. var count = (counts[message] || 0) + 1;
  25527. counts[message] = count;
  25528. if (count >= mainErrorCount) {
  25529. mainError = error;
  25530. mainErrorCount = count;
  25531. }
  25532. }
  25533. return mainError;
  25534. };
  25535. },{}],91:[function(require,module,exports){
  25536. module.exports = function arrayEquals(array) {
  25537. // if the other array is a falsy value, return
  25538. if (!array)
  25539. return false;
  25540. // compare lengths - can save a lot of time
  25541. if (this.length != array.length)
  25542. return false;
  25543. for (var i = 0, l = this.length; i < l; i++) {
  25544. // Check if we have nested arrays
  25545. if (this[i] instanceof Array && array[i] instanceof Array) {
  25546. // recurse into the nested arrays
  25547. if (!arrayEquals.apply(this[i], [array[i]]))
  25548. return false;
  25549. } else if (this[i] != array[i]) {
  25550. // Warning - two different object instances will never be equal:
  25551. // {x:20} != {x:20}
  25552. return false;
  25553. }
  25554. }
  25555. return true;
  25556. }
  25557. },{}],92:[function(require,module,exports){
  25558. exports.Interop = require('./interop');
  25559. },{"./interop":93}],93:[function(require,module,exports){
  25560. "use strict";
  25561. var transform = require('./transform');
  25562. var arrayEquals = require('./array-equals');
  25563. function Interop() {
  25564. /**
  25565. * This map holds the most recent Unified Plan offer/answer SDP that was
  25566. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  25567. * the SDP string as values.
  25568. *
  25569. * @type {{}}
  25570. */
  25571. this.cache = {};
  25572. }
  25573. module.exports = Interop;
  25574. /**
  25575. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  25576. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  25577. * application.
  25578. *
  25579. * @param desc
  25580. * @returns {*}
  25581. */
  25582. Interop.prototype.toPlanB = function(desc) {
  25583. //#region Preliminary input validation.
  25584. if (typeof desc !== 'object' || desc === null ||
  25585. typeof desc.sdp !== 'string') {
  25586. console.warn('An empty description was passed as an argument.');
  25587. return desc;
  25588. }
  25589. // Objectify the SDP for easier manipulation.
  25590. var session = transform.parse(desc.sdp);
  25591. // If the SDP contains no media, there's nothing to transform.
  25592. if (typeof session.media === 'undefined' ||
  25593. !Array.isArray(session.media) || session.media.length === 0) {
  25594. console.warn('The description has no media.');
  25595. return desc;
  25596. }
  25597. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  25598. // SDP has a video, an audio and a data "channel" at most.
  25599. if (session.media.length <= 3 && session.media.every(function(m) {
  25600. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25601. })) {
  25602. console.warn('This description does not look like Unified Plan.');
  25603. return desc;
  25604. }
  25605. //#endregion
  25606. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  25607. // -> Unified Plan transformation.
  25608. this.cache[desc.type] = desc.sdp;
  25609. //#region Convert from Unified Plan to Plan B.
  25610. // We rebuild the session.media array.
  25611. var media = session.media;
  25612. session.media = [];
  25613. // Associative array that maps channel types to channel objects for fast
  25614. // access to channel objects by their type, e.g. type2bl['audio']->channel
  25615. // obj.
  25616. var type2bl = {};
  25617. // Used to build the group:BUNDLE value after the channels construction
  25618. // loop.
  25619. var types = [];
  25620. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  25621. media.forEach(function(unifiedLine) {
  25622. // rtcp-mux is required in the Plan B SDP.
  25623. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  25624. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  25625. unifiedLine.direction !== 'inactive') {
  25626. throw new Error('Cannot convert to Plan B because m-lines ' +
  25627. 'without the rtcp-mux attribute were found.');
  25628. }
  25629. if (unifiedLine.type === 'application') {
  25630. session.media.push(unifiedLine);
  25631. types.push(unifiedLine.mid);
  25632. return;
  25633. }
  25634. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  25635. // as the channel basis.
  25636. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  25637. type2bl[unifiedLine.type] = unifiedLine;
  25638. }
  25639. // Add sources to the channel and handle a=msid.
  25640. if (typeof unifiedLine.sources === 'object') {
  25641. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  25642. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  25643. type2bl[unifiedLine.type].sources = {};
  25644. // Assign the sources to the channel.
  25645. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  25646. if (typeof unifiedLine.msid !== 'undefined') {
  25647. // In Plan B the msid is an SSRC attribute. Also, we don't
  25648. // care about the obsolete label and mslabel attributes.
  25649. //
  25650. // Note that it is not guaranteed that the unifiedLine will have
  25651. // an msid. recvonly channels in particular don't have one.
  25652. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  25653. }
  25654. // NOTE ssrcs in ssrc groups will share msids, as
  25655. // draft-uberti-rtcweb-plan-00 mandates.
  25656. });
  25657. }
  25658. // Add ssrc groups to the channel.
  25659. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  25660. Array.isArray(unifiedLine.ssrcGroups)) {
  25661. // Create the ssrcGroups array, if it's not defined.
  25662. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  25663. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  25664. type2bl[unifiedLine.type].ssrcGroups = [];
  25665. }
  25666. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  25667. }
  25668. if (type2bl[unifiedLine.type] === unifiedLine) {
  25669. // Copy ICE related stuff from the principal media line.
  25670. unifiedLine.candidates = media[0].candidates;
  25671. unifiedLine.iceUfrag = media[0].iceUfrag;
  25672. unifiedLine.icePwd = media[0].icePwd;
  25673. unifiedLine.fingerprint = media[0].fingerprint;
  25674. // Plan B mids are in ['audio', 'video', 'data']
  25675. unifiedLine.mid = unifiedLine.type;
  25676. // Plan B doesn't support/need the bundle-only attribute.
  25677. delete unifiedLine.bundleOnly;
  25678. // In Plan B the msid is an SSRC attribute.
  25679. delete unifiedLine.msid;
  25680. // Used to build the group:BUNDLE value after this loop.
  25681. types.push(unifiedLine.type);
  25682. // Add the channel to the new media array.
  25683. session.media.push(unifiedLine);
  25684. }
  25685. });
  25686. // We regenerate the BUNDLE group with the new mids.
  25687. session.groups.some(function(group) {
  25688. if (group.type === 'BUNDLE') {
  25689. group.mids = types.join(' ');
  25690. return true;
  25691. }
  25692. });
  25693. // msid semantic
  25694. session.msidSemantic = {
  25695. semantic: 'WMS',
  25696. token: '*'
  25697. };
  25698. var resStr = transform.write(session);
  25699. return new RTCSessionDescription({
  25700. type: desc.type,
  25701. sdp: resStr
  25702. });
  25703. //#endregion
  25704. };
  25705. /**
  25706. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  25707. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  25708. * to FF.
  25709. *
  25710. * @param desc
  25711. * @returns {*}
  25712. */
  25713. Interop.prototype.toUnifiedPlan = function(desc) {
  25714. //#region Preliminary input validation.
  25715. if (typeof desc !== 'object' || desc === null ||
  25716. typeof desc.sdp !== 'string') {
  25717. console.warn('An empty description was passed as an argument.');
  25718. return desc;
  25719. }
  25720. var session = transform.parse(desc.sdp);
  25721. // If the SDP contains no media, there's nothing to transform.
  25722. if (typeof session.media === 'undefined' ||
  25723. !Array.isArray(session.media) || session.media.length === 0) {
  25724. console.warn('The description has no media.');
  25725. return desc;
  25726. }
  25727. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  25728. // a video, an audio and a data "channel" at most.
  25729. if (session.media.length > 3 || !session.media.every(function(m) {
  25730. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25731. })) {
  25732. console.warn('This description does not look like Plan B.');
  25733. return desc;
  25734. }
  25735. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  25736. var mids = [];
  25737. session.media.forEach(function(m) {
  25738. mids.push(m.mid);
  25739. });
  25740. var hasBundle = false;
  25741. if (typeof session.groups !== 'undefined' &&
  25742. Array.isArray(session.groups)) {
  25743. hasBundle = session.groups.every(function(g) {
  25744. return g.type !== 'BUNDLE' ||
  25745. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  25746. });
  25747. }
  25748. if (!hasBundle) {
  25749. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  25750. " are not bundled were found.");
  25751. }
  25752. //#endregion
  25753. //#region Convert from Plan B to Unified Plan.
  25754. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  25755. // rebuild an equivalent Unified Plan offer/answer.
  25756. //
  25757. // For example, if this is a local answer (in Unified Plan style) that we
  25758. // convert to Plan B prior to handing it over to the application (the
  25759. // PeerConnection wrapper called us, for instance, after a successful
  25760. // createAnswer), we want to remember the m-line at which we've seen the
  25761. // (local) SSRC. That's because when the application wants to do call the
  25762. // SLD method, forcing us to do the inverse transformation (from Plan B to
  25763. // Unified Plan), we need to know to which m-line to assign the (local)
  25764. // SSRC. We also need to know all the other m-lines that the original
  25765. // answer had and include them in the transformed answer as well.
  25766. //
  25767. // Another example is if this is a remote offer that we convert to Plan B
  25768. // prior to giving it to the application, we want to remember the mid at
  25769. // which we've seen the (remote) SSRC.
  25770. //
  25771. // In the iteration that follows, we use the cached Unified Plan (if it
  25772. // exists) to assign mids to ssrcs.
  25773. var cached;
  25774. if (typeof this.cache[desc.type] !== 'undefined') {
  25775. cached = transform.parse(this.cache[desc.type]);
  25776. }
  25777. // A helper map that sends mids to m-line objects. We use it later to
  25778. // rebuild the Unified Plan style session.media array.
  25779. var mid2ul = {};
  25780. session.media.forEach(function(bLine) {
  25781. if ((typeof bLine.rtcpMux !== 'string' ||
  25782. bLine.rtcpMux !== 'rtcp-mux') &&
  25783. bLine.direction !== 'inactive') {
  25784. throw new Error("Cannot convert to Unified Plan because m-lines " +
  25785. "without the rtcp-mux attribute were found.");
  25786. }
  25787. if (bLine.type === 'application') {
  25788. mid2ul[bLine.mid] = bLine;
  25789. return;
  25790. }
  25791. // With rtcp-mux and bundle all the channels should have the same ICE
  25792. // stuff.
  25793. var sources = bLine.sources;
  25794. var ssrcGroups = bLine.ssrcGroups;
  25795. var candidates = bLine.candidates;
  25796. var iceUfrag = bLine.iceUfrag;
  25797. var icePwd = bLine.icePwd;
  25798. var fingerprint = bLine.fingerprint;
  25799. var port = bLine.port;
  25800. // We'll use the "bLine" object as a prototype for each new "mLine"
  25801. // that we create, but first we need to clean it up a bit.
  25802. delete bLine.sources;
  25803. delete bLine.ssrcGroups;
  25804. delete bLine.candidates;
  25805. delete bLine.iceUfrag;
  25806. delete bLine.icePwd;
  25807. delete bLine.fingerprint;
  25808. delete bLine.port;
  25809. delete bLine.mid;
  25810. // inverted ssrc group map
  25811. var ssrc2group = {};
  25812. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  25813. ssrcGroups.forEach(function (ssrcGroup) {
  25814. // TODO(gp) find out how to receive simulcast with FF. For the
  25815. // time being, hide it.
  25816. if (ssrcGroup.semantics === 'SIM') {
  25817. return;
  25818. }
  25819. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25820. Array.isArray(ssrcGroup.ssrcs)) {
  25821. ssrcGroup.ssrcs.forEach(function (ssrc) {
  25822. if (typeof ssrc2group[ssrc] === 'undefined') {
  25823. ssrc2group[ssrc] = [];
  25824. }
  25825. ssrc2group[ssrc].push(ssrcGroup);
  25826. });
  25827. }
  25828. });
  25829. }
  25830. // ssrc to m-line index.
  25831. var ssrc2ml = {};
  25832. if (typeof sources === 'object') {
  25833. // Explode the Plan B channel sources with one m-line per source.
  25834. Object.keys(sources).forEach(function(ssrc) {
  25835. // The (unified) m-line for this SSRC. We either create it from
  25836. // scratch or, if it's a grouped SSRC, we re-use a related
  25837. // mline. In other words, if the source is grouped with another
  25838. // source, put the two together in the same m-line.
  25839. var unifiedLine;
  25840. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  25841. Array.isArray(ssrc2group[ssrc])) {
  25842. ssrc2group[ssrc].some(function (ssrcGroup) {
  25843. // ssrcGroup.ssrcs *is* an Array, no need to check
  25844. // again here.
  25845. return ssrcGroup.ssrcs.some(function (related) {
  25846. if (typeof ssrc2ml[related] === 'object') {
  25847. unifiedLine = ssrc2ml[related];
  25848. return true;
  25849. }
  25850. });
  25851. });
  25852. }
  25853. if (typeof unifiedLine === 'object') {
  25854. // the m-line already exists. Just add the source.
  25855. unifiedLine.sources[ssrc] = sources[ssrc];
  25856. delete sources[ssrc].msid;
  25857. } else {
  25858. // Use the "bLine" as a prototype for the "unifiedLine".
  25859. unifiedLine = Object.create(bLine);
  25860. ssrc2ml[ssrc] = unifiedLine;
  25861. if (typeof sources[ssrc].msid !== 'undefined') {
  25862. // Assign the msid of the source to the m-line. Note
  25863. // that it is not guaranteed that the source will have
  25864. // msid. In particular "recvonly" sources don't have an
  25865. // msid. Note that "recvonly" is a term only defined
  25866. // for m-lines.
  25867. unifiedLine.msid = sources[ssrc].msid;
  25868. delete sources[ssrc].msid;
  25869. }
  25870. // We assign one SSRC per media line.
  25871. unifiedLine.sources = {};
  25872. unifiedLine.sources[ssrc] = sources[ssrc];
  25873. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  25874. // Use the cached Unified Plan SDP (if it exists) to assign
  25875. // SSRCs to mids.
  25876. if (typeof cached !== 'undefined' &&
  25877. typeof cached.media !== 'undefined' &&
  25878. Array.isArray(cached.media)) {
  25879. cached.media.forEach(function (m) {
  25880. if (typeof m.sources === 'object') {
  25881. Object.keys(m.sources).forEach(function (s) {
  25882. if (s === ssrc) {
  25883. unifiedLine.mid = m.mid;
  25884. }
  25885. });
  25886. }
  25887. });
  25888. }
  25889. if (typeof unifiedLine.mid === 'undefined') {
  25890. // If this is an SSRC that we see for the first time
  25891. // assign it a new mid. This is typically the case when
  25892. // this method is called to transform a remote
  25893. // description for the first time or when there is a
  25894. // new SSRC in the remote description because a new
  25895. // peer has joined the conference. Local SSRCs should
  25896. // have already been added to the map in the toPlanB
  25897. // method.
  25898. //
  25899. // Because FF generates answers in Unified Plan style,
  25900. // we MUST already have a cached answer with all the
  25901. // local SSRCs mapped to some m-line/mid.
  25902. if (desc.type === 'answer') {
  25903. throw new Error("An unmapped SSRC was found.");
  25904. }
  25905. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  25906. }
  25907. // Include the candidates in the 1st media line.
  25908. unifiedLine.candidates = candidates;
  25909. unifiedLine.iceUfrag = iceUfrag;
  25910. unifiedLine.icePwd = icePwd;
  25911. unifiedLine.fingerprint = fingerprint;
  25912. unifiedLine.port = port;
  25913. mid2ul[unifiedLine.mid] = unifiedLine;
  25914. }
  25915. });
  25916. }
  25917. });
  25918. // Rebuild the media array in the right order and add the missing mLines
  25919. // (missing from the Plan B SDP).
  25920. session.media = [];
  25921. mids = []; // reuse
  25922. if (desc.type === 'answer') {
  25923. // The media lines in the answer must match the media lines in the
  25924. // offer. The order is important too. Here we assume that Firefox is the
  25925. // answerer, so we merely have to use the reconstructed (unified) answer
  25926. // to update the cached (unified) answer accordingly.
  25927. //
  25928. // In the general case, one would have to use the cached (unified) offer
  25929. // to find the m-lines that are missing from the reconstructed answer,
  25930. // potentially grabbing them from the cached (unified) answer. One has
  25931. // to be carefull with this approach because inactive m-lines do not
  25932. // always have an mid, making it tricky (impossible?) to find where
  25933. // exactly and which m-lines are missing from the reconstructed answer.
  25934. for (var i = 0; i < cached.media.length; i++) {
  25935. var unifiedLine = cached.media[i];
  25936. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  25937. // The mid isn't in the reconstructed (unified) answer.
  25938. // This is either a (unified) m-line containing a remote
  25939. // track only, or a (unified) m-line containing a remote
  25940. // track and a local track that has been removed.
  25941. // In either case, it MUST exist in the cached
  25942. // (unified) answer.
  25943. //
  25944. // In case this is a removed local track, clean-up
  25945. // the (unified) m-line and make sure it's 'recvonly' or
  25946. // 'inactive'.
  25947. delete unifiedLine.msid;
  25948. delete unifiedLine.sources;
  25949. delete unifiedLine.ssrcGroups;
  25950. if (!unifiedLine.direction
  25951. || unifiedLine.direction === 'sendrecv')
  25952. unifiedLine.direction = 'recvonly';
  25953. if (!unifiedLine.direction
  25954. || unifiedLine.direction === 'sendonly')
  25955. unifiedLine.direction = 'inactive';
  25956. } else {
  25957. // This is an (unified) m-line/channel that contains a local
  25958. // track (sendrecv or sendonly channel) or it's a unified
  25959. // recvonly m-line/channel. In either case, since we're
  25960. // going from PlanB -> Unified Plan this m-line MUST
  25961. // exist in the cached answer.
  25962. }
  25963. session.media.push(unifiedLine);
  25964. if (typeof unifiedLine.mid === 'string') {
  25965. // inactive lines don't/may not have an mid.
  25966. mids.push(unifiedLine.mid);
  25967. }
  25968. }
  25969. } else {
  25970. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  25971. // under any circumstances. If we are no longer interested in sending a
  25972. // track, we just remove the msid and ssrc attributes and set it to
  25973. // either a=recvonly (as the reofferer, we must use recvonly if the
  25974. // other side was previously sending on the m-section, but we can also
  25975. // leave the possibility open if it wasn't previously in use), or
  25976. // a=inacive.
  25977. if (typeof cached !== 'undefined' &&
  25978. typeof cached.media !== 'undefined' &&
  25979. Array.isArray(cached.media)) {
  25980. cached.media.forEach(function(unifiedLine) {
  25981. mids.push(unifiedLine.mid);
  25982. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  25983. session.media.push(mid2ul[unifiedLine.mid]);
  25984. } else {
  25985. delete unifiedLine.msid;
  25986. delete unifiedLine.sources;
  25987. delete unifiedLine.ssrcGroups;
  25988. if (!unifiedLine.direction
  25989. || unifiedLine.direction === 'sendrecv')
  25990. unifiedLine.direction = 'recvonly';
  25991. if (!unifiedLine.direction
  25992. || unifiedLine.direction === 'sendonly')
  25993. unifiedLine.direction = 'inactive';
  25994. session.media.push(unifiedLine);
  25995. }
  25996. });
  25997. }
  25998. // Add all the remaining (new) m-lines of the transformed SDP.
  25999. Object.keys(mid2ul).forEach(function(mid) {
  26000. if (mids.indexOf(mid) === -1) {
  26001. mids.push(mid);
  26002. if (typeof mid2ul[mid].direction === 'recvonly') {
  26003. // This is a remote recvonly channel. Add its SSRC to the
  26004. // appropriate sendrecv or sendonly channel.
  26005. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  26006. session.media.some(function (unifiedLine) {
  26007. if ((unifiedLine.direction === 'sendrecv' ||
  26008. unifiedLine.direction === 'sendonly') &&
  26009. unifiedLine.type === mid2ul[mid].type) {
  26010. // mid2ul[mid] shouldn't have any ssrc-groups
  26011. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  26012. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  26013. });
  26014. return true;
  26015. }
  26016. });
  26017. } else {
  26018. session.media.push(mid2ul[mid]);
  26019. }
  26020. }
  26021. });
  26022. }
  26023. // We regenerate the BUNDLE group (since we regenerated the mids)
  26024. session.groups.some(function(group) {
  26025. if (group.type === 'BUNDLE') {
  26026. group.mids = mids.join(' ');
  26027. return true;
  26028. }
  26029. });
  26030. // msid semantic
  26031. session.msidSemantic = {
  26032. semantic: 'WMS',
  26033. token: '*'
  26034. };
  26035. var resStr = transform.write(session);
  26036. // Cache the transformed SDP (Unified Plan) for later re-use in this
  26037. // function.
  26038. this.cache[desc.type] = resStr;
  26039. return new RTCSessionDescription({
  26040. type: desc.type,
  26041. sdp: resStr
  26042. });
  26043. //#endregion
  26044. };
  26045. },{"./array-equals":91,"./transform":94}],94:[function(require,module,exports){
  26046. var transform = require('sdp-transform');
  26047. exports.write = function(session, opts) {
  26048. if (typeof session !== 'undefined' &&
  26049. typeof session.media !== 'undefined' &&
  26050. Array.isArray(session.media)) {
  26051. session.media.forEach(function (mLine) {
  26052. // expand sources to ssrcs
  26053. if (typeof mLine.sources !== 'undefined' &&
  26054. Object.keys(mLine.sources).length !== 0) {
  26055. mLine.ssrcs = [];
  26056. Object.keys(mLine.sources).forEach(function (ssrc) {
  26057. var source = mLine.sources[ssrc];
  26058. Object.keys(source).forEach(function (attribute) {
  26059. mLine.ssrcs.push({
  26060. id: ssrc,
  26061. attribute: attribute,
  26062. value: source[attribute]
  26063. });
  26064. });
  26065. });
  26066. delete mLine.sources;
  26067. }
  26068. // join ssrcs in ssrc groups
  26069. if (typeof mLine.ssrcGroups !== 'undefined' &&
  26070. Array.isArray(mLine.ssrcGroups)) {
  26071. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  26072. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  26073. Array.isArray(ssrcGroup.ssrcs)) {
  26074. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  26075. }
  26076. });
  26077. }
  26078. });
  26079. }
  26080. // join group mids
  26081. if (typeof session !== 'undefined' &&
  26082. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  26083. session.groups.forEach(function (g) {
  26084. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  26085. g.mids = g.mids.join(' ');
  26086. }
  26087. });
  26088. }
  26089. return transform.write(session, opts);
  26090. };
  26091. exports.parse = function(sdp) {
  26092. var session = transform.parse(sdp);
  26093. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  26094. Array.isArray(session.media)) {
  26095. session.media.forEach(function (mLine) {
  26096. // group sources attributes by ssrc
  26097. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26098. mLine.sources = {};
  26099. mLine.ssrcs.forEach(function (ssrc) {
  26100. if (!mLine.sources[ssrc.id])
  26101. mLine.sources[ssrc.id] = {};
  26102. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26103. });
  26104. delete mLine.ssrcs;
  26105. }
  26106. // split ssrcs in ssrc groups
  26107. if (typeof mLine.ssrcGroups !== 'undefined' &&
  26108. Array.isArray(mLine.ssrcGroups)) {
  26109. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  26110. if (typeof ssrcGroup.ssrcs === 'string') {
  26111. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  26112. }
  26113. });
  26114. }
  26115. });
  26116. }
  26117. // split group mids
  26118. if (typeof session !== 'undefined' &&
  26119. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  26120. session.groups.forEach(function (g) {
  26121. if (typeof g.mids === 'string') {
  26122. g.mids = g.mids.split(' ');
  26123. }
  26124. });
  26125. }
  26126. return session;
  26127. };
  26128. },{"sdp-transform":98}],95:[function(require,module,exports){
  26129. var transform = require('sdp-transform');
  26130. var transformUtils = require('./transform-utils');
  26131. var parseSsrcs = transformUtils.parseSsrcs;
  26132. var writeSsrcs = transformUtils.writeSsrcs;
  26133. //region Constants
  26134. var DEFAULT_NUM_OF_LAYERS = 3;
  26135. //endregion
  26136. //region Ctor
  26137. function Simulcast(options) {
  26138. this.options = options ? options : {};
  26139. if (!this.options.numOfLayers) {
  26140. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  26141. }
  26142. this.layers = [];
  26143. }
  26144. //endregion
  26145. //region Stateless private utility functions
  26146. /**
  26147. * Returns a random integer between min (included) and max (excluded)
  26148. * Using Math.round() gives a non-uniform distribution!
  26149. * @returns {number}
  26150. */
  26151. function generateSSRC() {
  26152. var min = 0, max = 0xffffffff;
  26153. return Math.floor(Math.random() * (max - min)) + min;
  26154. };
  26155. function processVideo(session, action) {
  26156. if (session == null || !Array.isArray(session.media)) {
  26157. return;
  26158. }
  26159. session.media.forEach(function (mLine) {
  26160. if (mLine.type === 'video') {
  26161. action(mLine);
  26162. }
  26163. });
  26164. }
  26165. function validateDescription(desc)
  26166. {
  26167. return desc && desc != null
  26168. && desc.type && desc.type != ''
  26169. && desc.sdp && desc.sdp != '';
  26170. }
  26171. function explodeRemoteSimulcast(mLine) {
  26172. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26173. return;
  26174. }
  26175. var sources = parseSsrcs(mLine);
  26176. var order = [];
  26177. // Find the SIM group and explode its sources.
  26178. var j = mLine.ssrcGroups.length;
  26179. while (j--) {
  26180. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  26181. continue;
  26182. }
  26183. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  26184. for (var i = 0; i < simulcastSsrcs.length; i++) {
  26185. var ssrc = simulcastSsrcs[i];
  26186. order.push(ssrc);
  26187. var parts = sources[ssrc].msid.split(' ');
  26188. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  26189. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  26190. // Remove all the groups that this SSRC participates in.
  26191. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26192. if (relatedGroup.semantics === 'SIM') {
  26193. return;
  26194. }
  26195. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26196. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26197. return;
  26198. }
  26199. // Nuke all the related SSRCs.
  26200. relatedSsrcs.forEach(function (relatedSSRC) {
  26201. sources[relatedSSRC].msid = sources[ssrc].msid;
  26202. sources[relatedSSRC].cname = sources[ssrc].cname;
  26203. if (relatedSSRC !== ssrc) {
  26204. order.push(relatedSSRC);
  26205. }
  26206. });
  26207. // Schedule the related group for nuking.
  26208. })
  26209. }
  26210. mLine.ssrcs = writeSsrcs(sources, order);
  26211. mLine.ssrcGroups.splice(j, 1);
  26212. };
  26213. }
  26214. function squeezeRemoteSimulcast(mLine) {
  26215. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26216. return;
  26217. }
  26218. var sources = parseSsrcs(mLine);
  26219. // Find the SIM group and nuke it.
  26220. mLine.ssrcGroups.some(function (simulcastGroup) {
  26221. if (simulcastGroup.semantics !== 'SIM') {
  26222. return false;
  26223. }
  26224. // Schedule the SIM group for nuking.
  26225. simulcastGroup.nuke = true;
  26226. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  26227. // Nuke all the higher layer SSRCs.
  26228. for (var i = 1; i < simulcastSsrcs.length; i++) {
  26229. var ssrc = simulcastSsrcs[i];
  26230. delete sources[ssrc];
  26231. // Remove all the groups that this SSRC participates in.
  26232. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26233. if (relatedGroup.semantics === 'SIM') {
  26234. return;
  26235. }
  26236. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26237. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26238. return;
  26239. }
  26240. // Nuke all the related SSRCs.
  26241. relatedSsrcs.forEach(function (relatedSSRC) {
  26242. delete sources[relatedSSRC];
  26243. });
  26244. // Schedule the related group for nuking.
  26245. relatedGroup.nuke = true;
  26246. })
  26247. }
  26248. return true;
  26249. });
  26250. mLine.ssrcs = writeSsrcs(sources);
  26251. // Nuke all the scheduled groups.
  26252. var i = mLine.ssrcGroups.length;
  26253. while (i--) {
  26254. if (mLine.ssrcGroups[i].nuke) {
  26255. mLine.ssrcGroups.splice(i, 1);
  26256. }
  26257. }
  26258. }
  26259. function removeGoogConference(mLine) {
  26260. if (!mLine || !Array.isArray(mLine.invalid)) {
  26261. return;
  26262. }
  26263. var i = mLine.invalid.length;
  26264. while (i--) {
  26265. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  26266. mLine.invalid.splice(i, 1);
  26267. }
  26268. }
  26269. }
  26270. function assertGoogConference(mLine) {
  26271. if (!mLine) {
  26272. return;
  26273. }
  26274. if (!Array.isArray(mLine.invalid)) {
  26275. mLine.invalid = [];
  26276. }
  26277. if (!mLine.invalid.some(
  26278. function (i) { return i.value === 'x-google-flag:conference' })) {
  26279. mLine.invalid.push({'value': 'x-google-flag:conference'});
  26280. }
  26281. }
  26282. //endregion
  26283. //region "Private" functions
  26284. /**
  26285. *
  26286. * @param mLine
  26287. * @private
  26288. */
  26289. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  26290. if (!mLine || mLine.type !== 'video') {
  26291. return;
  26292. }
  26293. var sources = parseSsrcs(mLine);
  26294. if (Object.keys(sources).length === 0) {
  26295. // no sources, disable simulcast.
  26296. if (this.layers.length !== 0) {
  26297. this.layers = [];
  26298. }
  26299. return;
  26300. }
  26301. // find the base layer (we'll reuse its msid and cname).
  26302. var baseLayerSSRC = Object.keys(sources)[0];
  26303. var baseLayer = sources[baseLayerSSRC];
  26304. // todo(gp) handle screen sharing.
  26305. // check if base CNAME has changed and reinitialise layers.
  26306. if (this.layers.length > 0
  26307. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  26308. this.layers = [];
  26309. }
  26310. // (re)initialise layers
  26311. if (this.layers.length < 1) {
  26312. // first push the base layer.
  26313. this.layers.push({
  26314. ssrc: baseLayerSSRC,
  26315. msid: baseLayer.msid,
  26316. cname: baseLayer.cname
  26317. });
  26318. var rtx = false; // RFC 4588
  26319. if (Array.isArray(mLine.rtp)) {
  26320. rtx = mLine.rtp.some(
  26321. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  26322. }
  26323. if (rtx) {
  26324. this.layers[0].rtx = generateSSRC();
  26325. }
  26326. // now push additional layers.
  26327. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  26328. var layer = { ssrc: generateSSRC() };
  26329. if (rtx) {
  26330. layer.rtx = generateSSRC();
  26331. }
  26332. this.layers.push(layer);
  26333. }
  26334. }
  26335. };
  26336. /**
  26337. *
  26338. * @param mLine
  26339. * @private
  26340. */
  26341. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  26342. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  26343. var sources = {};
  26344. var msid = this.layers[0].msid;
  26345. var cname = this.layers[0].cname;
  26346. var simulcastSsrcs = [];
  26347. var ssrcGroups = [];
  26348. for (var i = 0; i < this.layers.length; i++) {
  26349. var layer = this.layers[i];
  26350. sources[layer.ssrc] = { msid: msid, cname: cname };
  26351. simulcastSsrcs.push(layer.ssrc);
  26352. if (layer.rtx) {
  26353. sources[layer.rtx] = {
  26354. msid: msid,
  26355. cname: cname
  26356. }
  26357. ssrcGroups.push({
  26358. semantics: 'FID',
  26359. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  26360. });
  26361. }
  26362. }
  26363. ssrcGroups.push({
  26364. semantics: 'SIM',
  26365. ssrcs: simulcastSsrcs.join(' ')
  26366. });
  26367. mLine.ssrcGroups = ssrcGroups;
  26368. mLine.ssrcs = writeSsrcs(sources);
  26369. }
  26370. }
  26371. //endregion
  26372. //region "Public" functions
  26373. Simulcast.prototype.isSupported = function () {
  26374. return window.chrome;
  26375. // TODO this needs improvements. For example I doubt that Chrome in Android
  26376. // has simulcast support. Also, only recent versions of Chromium have native
  26377. // simulcast support.
  26378. }
  26379. /**
  26380. *
  26381. * @param desc
  26382. * @returns {RTCSessionDescription}
  26383. */
  26384. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  26385. if (!validateDescription(desc)) {
  26386. return desc;
  26387. }
  26388. var session = transform.parse(desc.sdp);
  26389. var self = this;
  26390. processVideo(session, function (mLine) {
  26391. // Handle simulcast reception.
  26392. if (self.options.explodeRemoteSimulcast) {
  26393. explodeRemoteSimulcast(mLine);
  26394. } else {
  26395. squeezeRemoteSimulcast(mLine);
  26396. }
  26397. // If native simulcast is enabled, we must append the x-goog-conference
  26398. // attribute to the SDP.
  26399. if (self.layers.length < 1) {
  26400. removeGoogConference(mLine);
  26401. } else {
  26402. assertGoogConference(mLine);
  26403. }
  26404. });
  26405. return new RTCSessionDescription({
  26406. type: desc.type,
  26407. sdp: transform.write(session)
  26408. });
  26409. };
  26410. /**
  26411. *
  26412. * @param desc
  26413. * @returns {RTCSessionDescription}
  26414. */
  26415. Simulcast.prototype.mungeLocalDescription = function (desc) {
  26416. if (!validateDescription(desc) || !this.isSupported()) {
  26417. return desc;
  26418. }
  26419. var session = transform.parse(desc.sdp);
  26420. var self = this;
  26421. processVideo(session, function (mLine) {
  26422. // Initialize native simulcast layers, if not already done.
  26423. self._maybeInitializeLayers(mLine);
  26424. // Update the SDP with the simulcast layers.
  26425. self._restoreSimulcastView(mLine);
  26426. });
  26427. return new RTCSessionDescription({
  26428. type: desc.type,
  26429. sdp: transform.write(session)
  26430. });
  26431. };
  26432. //endregion
  26433. module.exports = Simulcast;
  26434. },{"./transform-utils":96,"sdp-transform":98}],96:[function(require,module,exports){
  26435. exports.writeSsrcs = function(sources, order) {
  26436. var ssrcs = [];
  26437. // expand sources to ssrcs
  26438. if (typeof sources !== 'undefined' &&
  26439. Object.keys(sources).length !== 0) {
  26440. if (Array.isArray(order)) {
  26441. for (var i = 0; i < order.length; i++) {
  26442. var ssrc = order[i];
  26443. var source = sources[ssrc];
  26444. Object.keys(source).forEach(function (attribute) {
  26445. ssrcs.push({
  26446. id: ssrc,
  26447. attribute: attribute,
  26448. value: source[attribute]
  26449. });
  26450. });
  26451. }
  26452. } else {
  26453. Object.keys(sources).forEach(function (ssrc) {
  26454. var source = sources[ssrc];
  26455. Object.keys(source).forEach(function (attribute) {
  26456. ssrcs.push({
  26457. id: ssrc,
  26458. attribute: attribute,
  26459. value: source[attribute]
  26460. });
  26461. });
  26462. });
  26463. }
  26464. }
  26465. return ssrcs;
  26466. };
  26467. exports.parseSsrcs = function (mLine) {
  26468. var sources = {};
  26469. // group sources attributes by ssrc.
  26470. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26471. mLine.ssrcs.forEach(function (ssrc) {
  26472. if (!sources[ssrc.id])
  26473. sources[ssrc.id] = {};
  26474. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26475. });
  26476. }
  26477. return sources;
  26478. };
  26479. },{}],97:[function(require,module,exports){
  26480. var grammar = module.exports = {
  26481. v: [{
  26482. name: 'version',
  26483. reg: /^(\d*)$/
  26484. }],
  26485. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  26486. // NB: sessionId will be a String in most cases because it is huge
  26487. name: 'origin',
  26488. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  26489. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  26490. format: "%s %s %d %s IP%d %s"
  26491. }],
  26492. // default parsing of these only (though some of these feel outdated)
  26493. s: [{ name: 'name' }],
  26494. i: [{ name: 'description' }],
  26495. u: [{ name: 'uri' }],
  26496. e: [{ name: 'email' }],
  26497. p: [{ name: 'phone' }],
  26498. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  26499. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  26500. //k: [{}], // outdated thing ignored
  26501. t: [{ //t=0 0
  26502. name: 'timing',
  26503. reg: /^(\d*) (\d*)/,
  26504. names: ['start', 'stop'],
  26505. format: "%d %d"
  26506. }],
  26507. c: [{ //c=IN IP4 10.47.197.26
  26508. name: 'connection',
  26509. reg: /^IN IP(\d) (\S*)/,
  26510. names: ['version', 'ip'],
  26511. format: "IN IP%d %s"
  26512. }],
  26513. b: [{ //b=AS:4000
  26514. push: 'bandwidth',
  26515. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  26516. names: ['type', 'limit'],
  26517. format: "%s:%s"
  26518. }],
  26519. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  26520. // NB: special - pushes to session
  26521. // TODO: rtp/fmtp should be filtered by the payloads found here?
  26522. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  26523. names: ['type', 'port', 'protocol', 'payloads'],
  26524. format: "%s %d %s %s"
  26525. }],
  26526. a: [
  26527. { //a=rtpmap:110 opus/48000/2
  26528. push: 'rtp',
  26529. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  26530. names: ['payload', 'codec', 'rate', 'encoding'],
  26531. format: function (o) {
  26532. return (o.encoding) ?
  26533. "rtpmap:%d %s/%s/%s":
  26534. "rtpmap:%d %s/%s";
  26535. }
  26536. },
  26537. {
  26538. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  26539. //a=fmtp:111 minptime=10; useinbandfec=1
  26540. push: 'fmtp',
  26541. reg: /^fmtp:(\d*) ([\S| ]*)/,
  26542. names: ['payload', 'config'],
  26543. format: "fmtp:%d %s"
  26544. },
  26545. { //a=control:streamid=0
  26546. name: 'control',
  26547. reg: /^control:(.*)/,
  26548. format: "control:%s"
  26549. },
  26550. { //a=rtcp:65179 IN IP4 193.84.77.194
  26551. name: 'rtcp',
  26552. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  26553. names: ['port', 'netType', 'ipVer', 'address'],
  26554. format: function (o) {
  26555. return (o.address != null) ?
  26556. "rtcp:%d %s IP%d %s":
  26557. "rtcp:%d";
  26558. }
  26559. },
  26560. { //a=rtcp-fb:98 trr-int 100
  26561. push: 'rtcpFbTrrInt',
  26562. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  26563. names: ['payload', 'value'],
  26564. format: "rtcp-fb:%d trr-int %d"
  26565. },
  26566. { //a=rtcp-fb:98 nack rpsi
  26567. push: 'rtcpFb',
  26568. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  26569. names: ['payload', 'type', 'subtype'],
  26570. format: function (o) {
  26571. return (o.subtype != null) ?
  26572. "rtcp-fb:%s %s %s":
  26573. "rtcp-fb:%s %s";
  26574. }
  26575. },
  26576. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  26577. //a=extmap:1/recvonly URI-gps-string
  26578. push: 'ext',
  26579. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  26580. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  26581. format: function (o) {
  26582. return (o.config != null) ?
  26583. "extmap:%s %s %s":
  26584. "extmap:%s %s";
  26585. }
  26586. },
  26587. {
  26588. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  26589. push: 'crypto',
  26590. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  26591. names: ['id', 'suite', 'config', 'sessionConfig'],
  26592. format: function (o) {
  26593. return (o.sessionConfig != null) ?
  26594. "crypto:%d %s %s %s":
  26595. "crypto:%d %s %s";
  26596. }
  26597. },
  26598. { //a=setup:actpass
  26599. name: 'setup',
  26600. reg: /^setup:(\w*)/,
  26601. format: "setup:%s"
  26602. },
  26603. { //a=mid:1
  26604. name: 'mid',
  26605. reg: /^mid:([^\s]*)/,
  26606. format: "mid:%s"
  26607. },
  26608. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  26609. name: 'msid',
  26610. reg: /^msid:(.*)/,
  26611. format: "msid:%s"
  26612. },
  26613. { //a=ptime:20
  26614. name: 'ptime',
  26615. reg: /^ptime:(\d*)/,
  26616. format: "ptime:%d"
  26617. },
  26618. { //a=maxptime:60
  26619. name: 'maxptime',
  26620. reg: /^maxptime:(\d*)/,
  26621. format: "maxptime:%d"
  26622. },
  26623. { //a=sendrecv
  26624. name: 'direction',
  26625. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  26626. },
  26627. { //a=ice-lite
  26628. name: 'icelite',
  26629. reg: /^(ice-lite)/
  26630. },
  26631. { //a=ice-ufrag:F7gI
  26632. name: 'iceUfrag',
  26633. reg: /^ice-ufrag:(\S*)/,
  26634. format: "ice-ufrag:%s"
  26635. },
  26636. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  26637. name: 'icePwd',
  26638. reg: /^ice-pwd:(\S*)/,
  26639. format: "ice-pwd:%s"
  26640. },
  26641. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  26642. name: 'fingerprint',
  26643. reg: /^fingerprint:(\S*) (\S*)/,
  26644. names: ['type', 'hash'],
  26645. format: "fingerprint:%s %s"
  26646. },
  26647. {
  26648. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  26649. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  26650. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  26651. push:'candidates',
  26652. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  26653. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  26654. format: function (o) {
  26655. var str = "candidate:%s %d %s %d %s %d typ %s";
  26656. // NB: candidate has two optional chunks, so %void middle one if it's missing
  26657. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  26658. if (o.generation != null) {
  26659. str += " generation %d";
  26660. }
  26661. return str;
  26662. }
  26663. },
  26664. { //a=end-of-candidates (keep after the candidates line for readability)
  26665. name: 'endOfCandidates',
  26666. reg: /^(end-of-candidates)/
  26667. },
  26668. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  26669. name: 'remoteCandidates',
  26670. reg: /^remote-candidates:(.*)/,
  26671. format: "remote-candidates:%s"
  26672. },
  26673. { //a=ice-options:google-ice
  26674. name: 'iceOptions',
  26675. reg: /^ice-options:(\S*)/,
  26676. format: "ice-options:%s"
  26677. },
  26678. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  26679. push: "ssrcs",
  26680. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  26681. names: ['id', 'attribute', 'value'],
  26682. format: "ssrc:%d %s:%s"
  26683. },
  26684. { //a=ssrc-group:FEC 1 2
  26685. push: "ssrcGroups",
  26686. reg: /^ssrc-group:(\w*) (.*)/,
  26687. names: ['semantics', 'ssrcs'],
  26688. format: "ssrc-group:%s %s"
  26689. },
  26690. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  26691. name: "msidSemantic",
  26692. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  26693. names: ['semantic', 'token'],
  26694. format: "msid-semantic: %s %s" // space after ":" is not accidental
  26695. },
  26696. { //a=group:BUNDLE audio video
  26697. push: 'groups',
  26698. reg: /^group:(\w*) (.*)/,
  26699. names: ['type', 'mids'],
  26700. format: "group:%s %s"
  26701. },
  26702. { //a=rtcp-mux
  26703. name: 'rtcpMux',
  26704. reg: /^(rtcp-mux)/
  26705. },
  26706. { //a=rtcp-rsize
  26707. name: 'rtcpRsize',
  26708. reg: /^(rtcp-rsize)/
  26709. },
  26710. { // any a= that we don't understand is kepts verbatim on media.invalid
  26711. push: 'invalid',
  26712. names: ["value"]
  26713. }
  26714. ]
  26715. };
  26716. // set sensible defaults to avoid polluting the grammar with boring details
  26717. Object.keys(grammar).forEach(function (key) {
  26718. var objs = grammar[key];
  26719. objs.forEach(function (obj) {
  26720. if (!obj.reg) {
  26721. obj.reg = /(.*)/;
  26722. }
  26723. if (!obj.format) {
  26724. obj.format = "%s";
  26725. }
  26726. });
  26727. });
  26728. },{}],98:[function(require,module,exports){
  26729. var parser = require('./parser');
  26730. var writer = require('./writer');
  26731. exports.write = writer;
  26732. exports.parse = parser.parse;
  26733. exports.parseFmtpConfig = parser.parseFmtpConfig;
  26734. exports.parsePayloads = parser.parsePayloads;
  26735. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  26736. },{"./parser":99,"./writer":100}],99:[function(require,module,exports){
  26737. var toIntIfInt = function (v) {
  26738. return String(Number(v)) === v ? Number(v) : v;
  26739. };
  26740. var attachProperties = function (match, location, names, rawName) {
  26741. if (rawName && !names) {
  26742. location[rawName] = toIntIfInt(match[1]);
  26743. }
  26744. else {
  26745. for (var i = 0; i < names.length; i += 1) {
  26746. if (match[i+1] != null) {
  26747. location[names[i]] = toIntIfInt(match[i+1]);
  26748. }
  26749. }
  26750. }
  26751. };
  26752. var parseReg = function (obj, location, content) {
  26753. var needsBlank = obj.name && obj.names;
  26754. if (obj.push && !location[obj.push]) {
  26755. location[obj.push] = [];
  26756. }
  26757. else if (needsBlank && !location[obj.name]) {
  26758. location[obj.name] = {};
  26759. }
  26760. var keyLocation = obj.push ?
  26761. {} : // blank object that will be pushed
  26762. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  26763. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  26764. if (obj.push) {
  26765. location[obj.push].push(keyLocation);
  26766. }
  26767. };
  26768. var grammar = require('./grammar');
  26769. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  26770. exports.parse = function (sdp) {
  26771. var session = {}
  26772. , media = []
  26773. , location = session; // points at where properties go under (one of the above)
  26774. // parse lines we understand
  26775. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  26776. var type = l[0];
  26777. var content = l.slice(2);
  26778. if (type === 'm') {
  26779. media.push({rtp: [], fmtp: []});
  26780. location = media[media.length-1]; // point at latest media line
  26781. }
  26782. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  26783. var obj = grammar[type][j];
  26784. if (obj.reg.test(content)) {
  26785. return parseReg(obj, location, content);
  26786. }
  26787. }
  26788. });
  26789. session.media = media; // link it up
  26790. return session;
  26791. };
  26792. var fmtpReducer = function (acc, expr) {
  26793. var s = expr.split('=');
  26794. if (s.length === 2) {
  26795. acc[s[0]] = toIntIfInt(s[1]);
  26796. }
  26797. return acc;
  26798. };
  26799. exports.parseFmtpConfig = function (str) {
  26800. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  26801. };
  26802. exports.parsePayloads = function (str) {
  26803. return str.split(' ').map(Number);
  26804. };
  26805. exports.parseRemoteCandidates = function (str) {
  26806. var candidates = [];
  26807. var parts = str.split(' ').map(toIntIfInt);
  26808. for (var i = 0; i < parts.length; i += 3) {
  26809. candidates.push({
  26810. component: parts[i],
  26811. ip: parts[i + 1],
  26812. port: parts[i + 2]
  26813. });
  26814. }
  26815. return candidates;
  26816. };
  26817. },{"./grammar":97}],100:[function(require,module,exports){
  26818. var grammar = require('./grammar');
  26819. // customized util.format - discards excess arguments and can void middle ones
  26820. var formatRegExp = /%[sdv%]/g;
  26821. var format = function (formatStr) {
  26822. var i = 1;
  26823. var args = arguments;
  26824. var len = args.length;
  26825. return formatStr.replace(formatRegExp, function (x) {
  26826. if (i >= len) {
  26827. return x; // missing argument
  26828. }
  26829. var arg = args[i];
  26830. i += 1;
  26831. switch (x) {
  26832. case '%%':
  26833. return '%';
  26834. case '%s':
  26835. return String(arg);
  26836. case '%d':
  26837. return Number(arg);
  26838. case '%v':
  26839. return '';
  26840. }
  26841. });
  26842. // NB: we discard excess arguments - they are typically undefined from makeLine
  26843. };
  26844. var makeLine = function (type, obj, location) {
  26845. var str = obj.format instanceof Function ?
  26846. (obj.format(obj.push ? location : location[obj.name])) :
  26847. obj.format;
  26848. var args = [type + '=' + str];
  26849. if (obj.names) {
  26850. for (var i = 0; i < obj.names.length; i += 1) {
  26851. var n = obj.names[i];
  26852. if (obj.name) {
  26853. args.push(location[obj.name][n]);
  26854. }
  26855. else { // for mLine and push attributes
  26856. args.push(location[obj.names[i]]);
  26857. }
  26858. }
  26859. }
  26860. else {
  26861. args.push(location[obj.name]);
  26862. }
  26863. return format.apply(null, args);
  26864. };
  26865. // RFC specified order
  26866. // TODO: extend this with all the rest
  26867. var defaultOuterOrder = [
  26868. 'v', 'o', 's', 'i',
  26869. 'u', 'e', 'p', 'c',
  26870. 'b', 't', 'r', 'z', 'a'
  26871. ];
  26872. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  26873. module.exports = function (session, opts) {
  26874. opts = opts || {};
  26875. // ensure certain properties exist
  26876. if (session.version == null) {
  26877. session.version = 0; // "v=0" must be there (only defined version atm)
  26878. }
  26879. if (session.name == null) {
  26880. session.name = " "; // "s= " must be there if no meaningful name set
  26881. }
  26882. session.media.forEach(function (mLine) {
  26883. if (mLine.payloads == null) {
  26884. mLine.payloads = "";
  26885. }
  26886. });
  26887. var outerOrder = opts.outerOrder || defaultOuterOrder;
  26888. var innerOrder = opts.innerOrder || defaultInnerOrder;
  26889. var sdp = [];
  26890. // loop through outerOrder for matching properties on session
  26891. outerOrder.forEach(function (type) {
  26892. grammar[type].forEach(function (obj) {
  26893. if (obj.name in session && session[obj.name] != null) {
  26894. sdp.push(makeLine(type, obj, session));
  26895. }
  26896. else if (obj.push in session && session[obj.push] != null) {
  26897. session[obj.push].forEach(function (el) {
  26898. sdp.push(makeLine(type, obj, el));
  26899. });
  26900. }
  26901. });
  26902. });
  26903. // then for each media line, follow the innerOrder
  26904. session.media.forEach(function (mLine) {
  26905. sdp.push(makeLine('m', grammar.m[0], mLine));
  26906. innerOrder.forEach(function (type) {
  26907. grammar[type].forEach(function (obj) {
  26908. if (obj.name in mLine && mLine[obj.name] != null) {
  26909. sdp.push(makeLine(type, obj, mLine));
  26910. }
  26911. else if (obj.push in mLine && mLine[obj.push] != null) {
  26912. mLine[obj.push].forEach(function (el) {
  26913. sdp.push(makeLine(type, obj, el));
  26914. });
  26915. }
  26916. });
  26917. });
  26918. });
  26919. return sdp.join('\r\n') + '\r\n';
  26920. };
  26921. },{"./grammar":97}],101:[function(require,module,exports){
  26922. module.exports = require('./lib/');
  26923. },{"./lib/":102}],102:[function(require,module,exports){
  26924. /**
  26925. * Module dependencies.
  26926. */
  26927. var url = require('./url');
  26928. var parser = require('socket.io-parser');
  26929. var Manager = require('./manager');
  26930. var debug = require('debug')('socket.io-client');
  26931. /**
  26932. * Module exports.
  26933. */
  26934. module.exports = exports = lookup;
  26935. /**
  26936. * Managers cache.
  26937. */
  26938. var cache = exports.managers = {};
  26939. /**
  26940. * Looks up an existing `Manager` for multiplexing.
  26941. * If the user summons:
  26942. *
  26943. * `io('http://localhost/a');`
  26944. * `io('http://localhost/b');`
  26945. *
  26946. * We reuse the existing instance based on same scheme/port/host,
  26947. * and we initialize sockets for each namespace.
  26948. *
  26949. * @api public
  26950. */
  26951. function lookup(uri, opts) {
  26952. if (typeof uri == 'object') {
  26953. opts = uri;
  26954. uri = undefined;
  26955. }
  26956. opts = opts || {};
  26957. var parsed = url(uri);
  26958. var source = parsed.source;
  26959. var id = parsed.id;
  26960. var io;
  26961. if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) {
  26962. debug('ignoring socket cache for %s', source);
  26963. io = Manager(source, opts);
  26964. } else {
  26965. if (!cache[id]) {
  26966. debug('new io instance for %s', source);
  26967. cache[id] = Manager(source, opts);
  26968. }
  26969. io = cache[id];
  26970. }
  26971. return io.socket(parsed.path);
  26972. }
  26973. /**
  26974. * Protocol version.
  26975. *
  26976. * @api public
  26977. */
  26978. exports.protocol = parser.protocol;
  26979. /**
  26980. * `connect`.
  26981. *
  26982. * @param {String} uri
  26983. * @api public
  26984. */
  26985. exports.connect = lookup;
  26986. /**
  26987. * Expose constructors for standalone build.
  26988. *
  26989. * @api public
  26990. */
  26991. exports.Manager = require('./manager');
  26992. exports.Socket = require('./socket');
  26993. },{"./manager":103,"./socket":105,"./url":106,"debug":110,"socket.io-parser":146}],103:[function(require,module,exports){
  26994. /**
  26995. * Module dependencies.
  26996. */
  26997. var url = require('./url');
  26998. var eio = require('engine.io-client');
  26999. var Socket = require('./socket');
  27000. var Emitter = require('component-emitter');
  27001. var parser = require('socket.io-parser');
  27002. var on = require('./on');
  27003. var bind = require('component-bind');
  27004. var object = require('object-component');
  27005. var debug = require('debug')('socket.io-client:manager');
  27006. var indexOf = require('indexof');
  27007. var Backoff = require('backo2');
  27008. /**
  27009. * Module exports
  27010. */
  27011. module.exports = Manager;
  27012. /**
  27013. * `Manager` constructor.
  27014. *
  27015. * @param {String} engine instance or engine uri/opts
  27016. * @param {Object} options
  27017. * @api public
  27018. */
  27019. function Manager(uri, opts){
  27020. if (!(this instanceof Manager)) return new Manager(uri, opts);
  27021. if (uri && ('object' == typeof uri)) {
  27022. opts = uri;
  27023. uri = undefined;
  27024. }
  27025. opts = opts || {};
  27026. opts.path = opts.path || '/socket.io';
  27027. this.nsps = {};
  27028. this.subs = [];
  27029. this.opts = opts;
  27030. this.reconnection(opts.reconnection !== false);
  27031. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  27032. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  27033. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  27034. this.randomizationFactor(opts.randomizationFactor || 0.5);
  27035. this.backoff = new Backoff({
  27036. min: this.reconnectionDelay(),
  27037. max: this.reconnectionDelayMax(),
  27038. jitter: this.randomizationFactor()
  27039. });
  27040. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  27041. this.readyState = 'closed';
  27042. this.uri = uri;
  27043. this.connected = [];
  27044. this.encoding = false;
  27045. this.packetBuffer = [];
  27046. this.encoder = new parser.Encoder();
  27047. this.decoder = new parser.Decoder();
  27048. this.autoConnect = opts.autoConnect !== false;
  27049. if (this.autoConnect) this.open();
  27050. }
  27051. /**
  27052. * Propagate given event to sockets and emit on `this`
  27053. *
  27054. * @api private
  27055. */
  27056. Manager.prototype.emitAll = function() {
  27057. this.emit.apply(this, arguments);
  27058. for (var nsp in this.nsps) {
  27059. this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
  27060. }
  27061. };
  27062. /**
  27063. * Update `socket.id` of all sockets
  27064. *
  27065. * @api private
  27066. */
  27067. Manager.prototype.updateSocketIds = function(){
  27068. for (var nsp in this.nsps) {
  27069. this.nsps[nsp].id = this.engine.id;
  27070. }
  27071. };
  27072. /**
  27073. * Mix in `Emitter`.
  27074. */
  27075. Emitter(Manager.prototype);
  27076. /**
  27077. * Sets the `reconnection` config.
  27078. *
  27079. * @param {Boolean} true/false if it should automatically reconnect
  27080. * @return {Manager} self or value
  27081. * @api public
  27082. */
  27083. Manager.prototype.reconnection = function(v){
  27084. if (!arguments.length) return this._reconnection;
  27085. this._reconnection = !!v;
  27086. return this;
  27087. };
  27088. /**
  27089. * Sets the reconnection attempts config.
  27090. *
  27091. * @param {Number} max reconnection attempts before giving up
  27092. * @return {Manager} self or value
  27093. * @api public
  27094. */
  27095. Manager.prototype.reconnectionAttempts = function(v){
  27096. if (!arguments.length) return this._reconnectionAttempts;
  27097. this._reconnectionAttempts = v;
  27098. return this;
  27099. };
  27100. /**
  27101. * Sets the delay between reconnections.
  27102. *
  27103. * @param {Number} delay
  27104. * @return {Manager} self or value
  27105. * @api public
  27106. */
  27107. Manager.prototype.reconnectionDelay = function(v){
  27108. if (!arguments.length) return this._reconnectionDelay;
  27109. this._reconnectionDelay = v;
  27110. this.backoff && this.backoff.setMin(v);
  27111. return this;
  27112. };
  27113. Manager.prototype.randomizationFactor = function(v){
  27114. if (!arguments.length) return this._randomizationFactor;
  27115. this._randomizationFactor = v;
  27116. this.backoff && this.backoff.setJitter(v);
  27117. return this;
  27118. };
  27119. /**
  27120. * Sets the maximum delay between reconnections.
  27121. *
  27122. * @param {Number} delay
  27123. * @return {Manager} self or value
  27124. * @api public
  27125. */
  27126. Manager.prototype.reconnectionDelayMax = function(v){
  27127. if (!arguments.length) return this._reconnectionDelayMax;
  27128. this._reconnectionDelayMax = v;
  27129. this.backoff && this.backoff.setMax(v);
  27130. return this;
  27131. };
  27132. /**
  27133. * Sets the connection timeout. `false` to disable
  27134. *
  27135. * @return {Manager} self or value
  27136. * @api public
  27137. */
  27138. Manager.prototype.timeout = function(v){
  27139. if (!arguments.length) return this._timeout;
  27140. this._timeout = v;
  27141. return this;
  27142. };
  27143. /**
  27144. * Starts trying to reconnect if reconnection is enabled and we have not
  27145. * started reconnecting yet
  27146. *
  27147. * @api private
  27148. */
  27149. Manager.prototype.maybeReconnectOnOpen = function() {
  27150. // Only try to reconnect if it's the first time we're connecting
  27151. if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
  27152. // keeps reconnection from firing twice for the same reconnection loop
  27153. this.reconnect();
  27154. }
  27155. };
  27156. /**
  27157. * Sets the current transport `socket`.
  27158. *
  27159. * @param {Function} optional, callback
  27160. * @return {Manager} self
  27161. * @api public
  27162. */
  27163. Manager.prototype.open =
  27164. Manager.prototype.connect = function(fn){
  27165. debug('readyState %s', this.readyState);
  27166. if (~this.readyState.indexOf('open')) return this;
  27167. debug('opening %s', this.uri);
  27168. this.engine = eio(this.uri, this.opts);
  27169. var socket = this.engine;
  27170. var self = this;
  27171. this.readyState = 'opening';
  27172. this.skipReconnect = false;
  27173. // emit `open`
  27174. var openSub = on(socket, 'open', function() {
  27175. self.onopen();
  27176. fn && fn();
  27177. });
  27178. // emit `connect_error`
  27179. var errorSub = on(socket, 'error', function(data){
  27180. debug('connect_error');
  27181. self.cleanup();
  27182. self.readyState = 'closed';
  27183. self.emitAll('connect_error', data);
  27184. if (fn) {
  27185. var err = new Error('Connection error');
  27186. err.data = data;
  27187. fn(err);
  27188. } else {
  27189. // Only do this if there is no fn to handle the error
  27190. self.maybeReconnectOnOpen();
  27191. }
  27192. });
  27193. // emit `connect_timeout`
  27194. if (false !== this._timeout) {
  27195. var timeout = this._timeout;
  27196. debug('connect attempt will timeout after %d', timeout);
  27197. // set timer
  27198. var timer = setTimeout(function(){
  27199. debug('connect attempt timed out after %d', timeout);
  27200. openSub.destroy();
  27201. socket.close();
  27202. socket.emit('error', 'timeout');
  27203. self.emitAll('connect_timeout', timeout);
  27204. }, timeout);
  27205. this.subs.push({
  27206. destroy: function(){
  27207. clearTimeout(timer);
  27208. }
  27209. });
  27210. }
  27211. this.subs.push(openSub);
  27212. this.subs.push(errorSub);
  27213. return this;
  27214. };
  27215. /**
  27216. * Called upon transport open.
  27217. *
  27218. * @api private
  27219. */
  27220. Manager.prototype.onopen = function(){
  27221. debug('open');
  27222. // clear old subs
  27223. this.cleanup();
  27224. // mark as open
  27225. this.readyState = 'open';
  27226. this.emit('open');
  27227. // add new subs
  27228. var socket = this.engine;
  27229. this.subs.push(on(socket, 'data', bind(this, 'ondata')));
  27230. this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
  27231. this.subs.push(on(socket, 'error', bind(this, 'onerror')));
  27232. this.subs.push(on(socket, 'close', bind(this, 'onclose')));
  27233. };
  27234. /**
  27235. * Called with data.
  27236. *
  27237. * @api private
  27238. */
  27239. Manager.prototype.ondata = function(data){
  27240. this.decoder.add(data);
  27241. };
  27242. /**
  27243. * Called when parser fully decodes a packet.
  27244. *
  27245. * @api private
  27246. */
  27247. Manager.prototype.ondecoded = function(packet) {
  27248. this.emit('packet', packet);
  27249. };
  27250. /**
  27251. * Called upon socket error.
  27252. *
  27253. * @api private
  27254. */
  27255. Manager.prototype.onerror = function(err){
  27256. debug('error', err);
  27257. this.emitAll('error', err);
  27258. };
  27259. /**
  27260. * Creates a new socket for the given `nsp`.
  27261. *
  27262. * @return {Socket}
  27263. * @api public
  27264. */
  27265. Manager.prototype.socket = function(nsp){
  27266. var socket = this.nsps[nsp];
  27267. if (!socket) {
  27268. socket = new Socket(this, nsp);
  27269. this.nsps[nsp] = socket;
  27270. var self = this;
  27271. socket.on('connect', function(){
  27272. socket.id = self.engine.id;
  27273. if (!~indexOf(self.connected, socket)) {
  27274. self.connected.push(socket);
  27275. }
  27276. });
  27277. }
  27278. return socket;
  27279. };
  27280. /**
  27281. * Called upon a socket close.
  27282. *
  27283. * @param {Socket} socket
  27284. */
  27285. Manager.prototype.destroy = function(socket){
  27286. var index = indexOf(this.connected, socket);
  27287. if (~index) this.connected.splice(index, 1);
  27288. if (this.connected.length) return;
  27289. this.close();
  27290. };
  27291. /**
  27292. * Writes a packet.
  27293. *
  27294. * @param {Object} packet
  27295. * @api private
  27296. */
  27297. Manager.prototype.packet = function(packet){
  27298. debug('writing packet %j', packet);
  27299. var self = this;
  27300. if (!self.encoding) {
  27301. // encode, then write to engine with result
  27302. self.encoding = true;
  27303. this.encoder.encode(packet, function(encodedPackets) {
  27304. for (var i = 0; i < encodedPackets.length; i++) {
  27305. self.engine.write(encodedPackets[i]);
  27306. }
  27307. self.encoding = false;
  27308. self.processPacketQueue();
  27309. });
  27310. } else { // add packet to the queue
  27311. self.packetBuffer.push(packet);
  27312. }
  27313. };
  27314. /**
  27315. * If packet buffer is non-empty, begins encoding the
  27316. * next packet in line.
  27317. *
  27318. * @api private
  27319. */
  27320. Manager.prototype.processPacketQueue = function() {
  27321. if (this.packetBuffer.length > 0 && !this.encoding) {
  27322. var pack = this.packetBuffer.shift();
  27323. this.packet(pack);
  27324. }
  27325. };
  27326. /**
  27327. * Clean up transport subscriptions and packet buffer.
  27328. *
  27329. * @api private
  27330. */
  27331. Manager.prototype.cleanup = function(){
  27332. var sub;
  27333. while (sub = this.subs.shift()) sub.destroy();
  27334. this.packetBuffer = [];
  27335. this.encoding = false;
  27336. this.decoder.destroy();
  27337. };
  27338. /**
  27339. * Close the current socket.
  27340. *
  27341. * @api private
  27342. */
  27343. Manager.prototype.close =
  27344. Manager.prototype.disconnect = function(){
  27345. this.skipReconnect = true;
  27346. this.backoff.reset();
  27347. this.readyState = 'closed';
  27348. this.engine && this.engine.close();
  27349. };
  27350. /**
  27351. * Called upon engine close.
  27352. *
  27353. * @api private
  27354. */
  27355. Manager.prototype.onclose = function(reason){
  27356. debug('close');
  27357. this.cleanup();
  27358. this.backoff.reset();
  27359. this.readyState = 'closed';
  27360. this.emit('close', reason);
  27361. if (this._reconnection && !this.skipReconnect) {
  27362. this.reconnect();
  27363. }
  27364. };
  27365. /**
  27366. * Attempt a reconnection.
  27367. *
  27368. * @api private
  27369. */
  27370. Manager.prototype.reconnect = function(){
  27371. if (this.reconnecting || this.skipReconnect) return this;
  27372. var self = this;
  27373. if (this.backoff.attempts >= this._reconnectionAttempts) {
  27374. debug('reconnect failed');
  27375. this.backoff.reset();
  27376. this.emitAll('reconnect_failed');
  27377. this.reconnecting = false;
  27378. } else {
  27379. var delay = this.backoff.duration();
  27380. debug('will wait %dms before reconnect attempt', delay);
  27381. this.reconnecting = true;
  27382. var timer = setTimeout(function(){
  27383. if (self.skipReconnect) return;
  27384. debug('attempting reconnect');
  27385. self.emitAll('reconnect_attempt', self.backoff.attempts);
  27386. self.emitAll('reconnecting', self.backoff.attempts);
  27387. // check again for the case socket closed in above events
  27388. if (self.skipReconnect) return;
  27389. self.open(function(err){
  27390. if (err) {
  27391. debug('reconnect attempt error');
  27392. self.reconnecting = false;
  27393. self.reconnect();
  27394. self.emitAll('reconnect_error', err.data);
  27395. } else {
  27396. debug('reconnect success');
  27397. self.onreconnect();
  27398. }
  27399. });
  27400. }, delay);
  27401. this.subs.push({
  27402. destroy: function(){
  27403. clearTimeout(timer);
  27404. }
  27405. });
  27406. }
  27407. };
  27408. /**
  27409. * Called upon successful reconnect.
  27410. *
  27411. * @api private
  27412. */
  27413. Manager.prototype.onreconnect = function(){
  27414. var attempt = this.backoff.attempts;
  27415. this.reconnecting = false;
  27416. this.backoff.reset();
  27417. this.updateSocketIds();
  27418. this.emitAll('reconnect', attempt);
  27419. };
  27420. },{"./on":104,"./socket":105,"./url":106,"backo2":107,"component-bind":108,"component-emitter":109,"debug":110,"engine.io-client":111,"indexof":142,"object-component":143,"socket.io-parser":146}],104:[function(require,module,exports){
  27421. /**
  27422. * Module exports.
  27423. */
  27424. module.exports = on;
  27425. /**
  27426. * Helper for subscriptions.
  27427. *
  27428. * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
  27429. * @param {String} event name
  27430. * @param {Function} callback
  27431. * @api public
  27432. */
  27433. function on(obj, ev, fn) {
  27434. obj.on(ev, fn);
  27435. return {
  27436. destroy: function(){
  27437. obj.removeListener(ev, fn);
  27438. }
  27439. };
  27440. }
  27441. },{}],105:[function(require,module,exports){
  27442. /**
  27443. * Module dependencies.
  27444. */
  27445. var parser = require('socket.io-parser');
  27446. var Emitter = require('component-emitter');
  27447. var toArray = require('to-array');
  27448. var on = require('./on');
  27449. var bind = require('component-bind');
  27450. var debug = require('debug')('socket.io-client:socket');
  27451. var hasBin = require('has-binary');
  27452. /**
  27453. * Module exports.
  27454. */
  27455. module.exports = exports = Socket;
  27456. /**
  27457. * Internal events (blacklisted).
  27458. * These events can't be emitted by the user.
  27459. *
  27460. * @api private
  27461. */
  27462. var events = {
  27463. connect: 1,
  27464. connect_error: 1,
  27465. connect_timeout: 1,
  27466. disconnect: 1,
  27467. error: 1,
  27468. reconnect: 1,
  27469. reconnect_attempt: 1,
  27470. reconnect_failed: 1,
  27471. reconnect_error: 1,
  27472. reconnecting: 1
  27473. };
  27474. /**
  27475. * Shortcut to `Emitter#emit`.
  27476. */
  27477. var emit = Emitter.prototype.emit;
  27478. /**
  27479. * `Socket` constructor.
  27480. *
  27481. * @api public
  27482. */
  27483. function Socket(io, nsp){
  27484. this.io = io;
  27485. this.nsp = nsp;
  27486. this.json = this; // compat
  27487. this.ids = 0;
  27488. this.acks = {};
  27489. if (this.io.autoConnect) this.open();
  27490. this.receiveBuffer = [];
  27491. this.sendBuffer = [];
  27492. this.connected = false;
  27493. this.disconnected = true;
  27494. }
  27495. /**
  27496. * Mix in `Emitter`.
  27497. */
  27498. Emitter(Socket.prototype);
  27499. /**
  27500. * Subscribe to open, close and packet events
  27501. *
  27502. * @api private
  27503. */
  27504. Socket.prototype.subEvents = function() {
  27505. if (this.subs) return;
  27506. var io = this.io;
  27507. this.subs = [
  27508. on(io, 'open', bind(this, 'onopen')),
  27509. on(io, 'packet', bind(this, 'onpacket')),
  27510. on(io, 'close', bind(this, 'onclose'))
  27511. ];
  27512. };
  27513. /**
  27514. * "Opens" the socket.
  27515. *
  27516. * @api public
  27517. */
  27518. Socket.prototype.open =
  27519. Socket.prototype.connect = function(){
  27520. if (this.connected) return this;
  27521. this.subEvents();
  27522. this.io.open(); // ensure open
  27523. if ('open' == this.io.readyState) this.onopen();
  27524. return this;
  27525. };
  27526. /**
  27527. * Sends a `message` event.
  27528. *
  27529. * @return {Socket} self
  27530. * @api public
  27531. */
  27532. Socket.prototype.send = function(){
  27533. var args = toArray(arguments);
  27534. args.unshift('message');
  27535. this.emit.apply(this, args);
  27536. return this;
  27537. };
  27538. /**
  27539. * Override `emit`.
  27540. * If the event is in `events`, it's emitted normally.
  27541. *
  27542. * @param {String} event name
  27543. * @return {Socket} self
  27544. * @api public
  27545. */
  27546. Socket.prototype.emit = function(ev){
  27547. if (events.hasOwnProperty(ev)) {
  27548. emit.apply(this, arguments);
  27549. return this;
  27550. }
  27551. var args = toArray(arguments);
  27552. var parserType = parser.EVENT; // default
  27553. if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
  27554. var packet = { type: parserType, data: args };
  27555. // event ack callback
  27556. if ('function' == typeof args[args.length - 1]) {
  27557. debug('emitting packet with ack id %d', this.ids);
  27558. this.acks[this.ids] = args.pop();
  27559. packet.id = this.ids++;
  27560. }
  27561. if (this.connected) {
  27562. this.packet(packet);
  27563. } else {
  27564. this.sendBuffer.push(packet);
  27565. }
  27566. return this;
  27567. };
  27568. /**
  27569. * Sends a packet.
  27570. *
  27571. * @param {Object} packet
  27572. * @api private
  27573. */
  27574. Socket.prototype.packet = function(packet){
  27575. packet.nsp = this.nsp;
  27576. this.io.packet(packet);
  27577. };
  27578. /**
  27579. * Called upon engine `open`.
  27580. *
  27581. * @api private
  27582. */
  27583. Socket.prototype.onopen = function(){
  27584. debug('transport is open - connecting');
  27585. // write connect packet if necessary
  27586. if ('/' != this.nsp) {
  27587. this.packet({ type: parser.CONNECT });
  27588. }
  27589. };
  27590. /**
  27591. * Called upon engine `close`.
  27592. *
  27593. * @param {String} reason
  27594. * @api private
  27595. */
  27596. Socket.prototype.onclose = function(reason){
  27597. debug('close (%s)', reason);
  27598. this.connected = false;
  27599. this.disconnected = true;
  27600. delete this.id;
  27601. this.emit('disconnect', reason);
  27602. };
  27603. /**
  27604. * Called with socket packet.
  27605. *
  27606. * @param {Object} packet
  27607. * @api private
  27608. */
  27609. Socket.prototype.onpacket = function(packet){
  27610. if (packet.nsp != this.nsp) return;
  27611. switch (packet.type) {
  27612. case parser.CONNECT:
  27613. this.onconnect();
  27614. break;
  27615. case parser.EVENT:
  27616. this.onevent(packet);
  27617. break;
  27618. case parser.BINARY_EVENT:
  27619. this.onevent(packet);
  27620. break;
  27621. case parser.ACK:
  27622. this.onack(packet);
  27623. break;
  27624. case parser.BINARY_ACK:
  27625. this.onack(packet);
  27626. break;
  27627. case parser.DISCONNECT:
  27628. this.ondisconnect();
  27629. break;
  27630. case parser.ERROR:
  27631. this.emit('error', packet.data);
  27632. break;
  27633. }
  27634. };
  27635. /**
  27636. * Called upon a server event.
  27637. *
  27638. * @param {Object} packet
  27639. * @api private
  27640. */
  27641. Socket.prototype.onevent = function(packet){
  27642. var args = packet.data || [];
  27643. debug('emitting event %j', args);
  27644. if (null != packet.id) {
  27645. debug('attaching ack callback to event');
  27646. args.push(this.ack(packet.id));
  27647. }
  27648. if (this.connected) {
  27649. emit.apply(this, args);
  27650. } else {
  27651. this.receiveBuffer.push(args);
  27652. }
  27653. };
  27654. /**
  27655. * Produces an ack callback to emit with an event.
  27656. *
  27657. * @api private
  27658. */
  27659. Socket.prototype.ack = function(id){
  27660. var self = this;
  27661. var sent = false;
  27662. return function(){
  27663. // prevent double callbacks
  27664. if (sent) return;
  27665. sent = true;
  27666. var args = toArray(arguments);
  27667. debug('sending ack %j', args);
  27668. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  27669. self.packet({
  27670. type: type,
  27671. id: id,
  27672. data: args
  27673. });
  27674. };
  27675. };
  27676. /**
  27677. * Called upon a server acknowlegement.
  27678. *
  27679. * @param {Object} packet
  27680. * @api private
  27681. */
  27682. Socket.prototype.onack = function(packet){
  27683. debug('calling ack %s with %j', packet.id, packet.data);
  27684. var fn = this.acks[packet.id];
  27685. fn.apply(this, packet.data);
  27686. delete this.acks[packet.id];
  27687. };
  27688. /**
  27689. * Called upon server connect.
  27690. *
  27691. * @api private
  27692. */
  27693. Socket.prototype.onconnect = function(){
  27694. this.connected = true;
  27695. this.disconnected = false;
  27696. this.emit('connect');
  27697. this.emitBuffered();
  27698. };
  27699. /**
  27700. * Emit buffered events (received and emitted).
  27701. *
  27702. * @api private
  27703. */
  27704. Socket.prototype.emitBuffered = function(){
  27705. var i;
  27706. for (i = 0; i < this.receiveBuffer.length; i++) {
  27707. emit.apply(this, this.receiveBuffer[i]);
  27708. }
  27709. this.receiveBuffer = [];
  27710. for (i = 0; i < this.sendBuffer.length; i++) {
  27711. this.packet(this.sendBuffer[i]);
  27712. }
  27713. this.sendBuffer = [];
  27714. };
  27715. /**
  27716. * Called upon server disconnect.
  27717. *
  27718. * @api private
  27719. */
  27720. Socket.prototype.ondisconnect = function(){
  27721. debug('server disconnect (%s)', this.nsp);
  27722. this.destroy();
  27723. this.onclose('io server disconnect');
  27724. };
  27725. /**
  27726. * Called upon forced client/server side disconnections,
  27727. * this method ensures the manager stops tracking us and
  27728. * that reconnections don't get triggered for this.
  27729. *
  27730. * @api private.
  27731. */
  27732. Socket.prototype.destroy = function(){
  27733. if (this.subs) {
  27734. // clean subscriptions to avoid reconnections
  27735. for (var i = 0; i < this.subs.length; i++) {
  27736. this.subs[i].destroy();
  27737. }
  27738. this.subs = null;
  27739. }
  27740. this.io.destroy(this);
  27741. };
  27742. /**
  27743. * Disconnects the socket manually.
  27744. *
  27745. * @return {Socket} self
  27746. * @api public
  27747. */
  27748. Socket.prototype.close =
  27749. Socket.prototype.disconnect = function(){
  27750. if (this.connected) {
  27751. debug('performing disconnect (%s)', this.nsp);
  27752. this.packet({ type: parser.DISCONNECT });
  27753. }
  27754. // remove socket from pool
  27755. this.destroy();
  27756. if (this.connected) {
  27757. // fire events
  27758. this.onclose('io client disconnect');
  27759. }
  27760. return this;
  27761. };
  27762. },{"./on":104,"component-bind":108,"component-emitter":109,"debug":110,"has-binary":140,"socket.io-parser":146,"to-array":150}],106:[function(require,module,exports){
  27763. (function (global){
  27764. /**
  27765. * Module dependencies.
  27766. */
  27767. var parseuri = require('parseuri');
  27768. var debug = require('debug')('socket.io-client:url');
  27769. /**
  27770. * Module exports.
  27771. */
  27772. module.exports = url;
  27773. /**
  27774. * URL parser.
  27775. *
  27776. * @param {String} url
  27777. * @param {Object} An object meant to mimic window.location.
  27778. * Defaults to window.location.
  27779. * @api public
  27780. */
  27781. function url(uri, loc){
  27782. var obj = uri;
  27783. // default to window.location
  27784. var loc = loc || global.location;
  27785. if (null == uri) uri = loc.protocol + '//' + loc.host;
  27786. // relative path support
  27787. if ('string' == typeof uri) {
  27788. if ('/' == uri.charAt(0)) {
  27789. if ('/' == uri.charAt(1)) {
  27790. uri = loc.protocol + uri;
  27791. } else {
  27792. uri = loc.hostname + uri;
  27793. }
  27794. }
  27795. if (!/^(https?|wss?):\/\//.test(uri)) {
  27796. debug('protocol-less url %s', uri);
  27797. if ('undefined' != typeof loc) {
  27798. uri = loc.protocol + '//' + uri;
  27799. } else {
  27800. uri = 'https://' + uri;
  27801. }
  27802. }
  27803. // parse
  27804. debug('parse %s', uri);
  27805. obj = parseuri(uri);
  27806. }
  27807. // make sure we treat `localhost:80` and `localhost` equally
  27808. if (!obj.port) {
  27809. if (/^(http|ws)$/.test(obj.protocol)) {
  27810. obj.port = '80';
  27811. }
  27812. else if (/^(http|ws)s$/.test(obj.protocol)) {
  27813. obj.port = '443';
  27814. }
  27815. }
  27816. obj.path = obj.path || '/';
  27817. // define unique id
  27818. obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
  27819. // define href
  27820. obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
  27821. return obj;
  27822. }
  27823. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  27824. },{"debug":110,"parseuri":144}],107:[function(require,module,exports){
  27825. /**
  27826. * Expose `Backoff`.
  27827. */
  27828. module.exports = Backoff;
  27829. /**
  27830. * Initialize backoff timer with `opts`.
  27831. *
  27832. * - `min` initial timeout in milliseconds [100]
  27833. * - `max` max timeout [10000]
  27834. * - `jitter` [0]
  27835. * - `factor` [2]
  27836. *
  27837. * @param {Object} opts
  27838. * @api public
  27839. */
  27840. function Backoff(opts) {
  27841. opts = opts || {};
  27842. this.ms = opts.min || 100;
  27843. this.max = opts.max || 10000;
  27844. this.factor = opts.factor || 2;
  27845. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  27846. this.attempts = 0;
  27847. }
  27848. /**
  27849. * Return the backoff duration.
  27850. *
  27851. * @return {Number}
  27852. * @api public
  27853. */
  27854. Backoff.prototype.duration = function(){
  27855. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  27856. if (this.jitter) {
  27857. var rand = Math.random();
  27858. var deviation = Math.floor(rand * this.jitter * ms);
  27859. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  27860. }
  27861. return Math.min(ms, this.max) | 0;
  27862. };
  27863. /**
  27864. * Reset the number of attempts.
  27865. *
  27866. * @api public
  27867. */
  27868. Backoff.prototype.reset = function(){
  27869. this.attempts = 0;
  27870. };
  27871. /**
  27872. * Set the minimum duration
  27873. *
  27874. * @api public
  27875. */
  27876. Backoff.prototype.setMin = function(min){
  27877. this.ms = min;
  27878. };
  27879. /**
  27880. * Set the maximum duration
  27881. *
  27882. * @api public
  27883. */
  27884. Backoff.prototype.setMax = function(max){
  27885. this.max = max;
  27886. };
  27887. /**
  27888. * Set the jitter
  27889. *
  27890. * @api public
  27891. */
  27892. Backoff.prototype.setJitter = function(jitter){
  27893. this.jitter = jitter;
  27894. };
  27895. },{}],108:[function(require,module,exports){
  27896. /**
  27897. * Slice reference.
  27898. */
  27899. var slice = [].slice;
  27900. /**
  27901. * Bind `obj` to `fn`.
  27902. *
  27903. * @param {Object} obj
  27904. * @param {Function|String} fn or string
  27905. * @return {Function}
  27906. * @api public
  27907. */
  27908. module.exports = function(obj, fn){
  27909. if ('string' == typeof fn) fn = obj[fn];
  27910. if ('function' != typeof fn) throw new Error('bind() requires a function');
  27911. var args = slice.call(arguments, 2);
  27912. return function(){
  27913. return fn.apply(obj, args.concat(slice.call(arguments)));
  27914. }
  27915. };
  27916. },{}],109:[function(require,module,exports){
  27917. /**
  27918. * Expose `Emitter`.
  27919. */
  27920. module.exports = Emitter;
  27921. /**
  27922. * Initialize a new `Emitter`.
  27923. *
  27924. * @api public
  27925. */
  27926. function Emitter(obj) {
  27927. if (obj) return mixin(obj);
  27928. };
  27929. /**
  27930. * Mixin the emitter properties.
  27931. *
  27932. * @param {Object} obj
  27933. * @return {Object}
  27934. * @api private
  27935. */
  27936. function mixin(obj) {
  27937. for (var key in Emitter.prototype) {
  27938. obj[key] = Emitter.prototype[key];
  27939. }
  27940. return obj;
  27941. }
  27942. /**
  27943. * Listen on the given `event` with `fn`.
  27944. *
  27945. * @param {String} event
  27946. * @param {Function} fn
  27947. * @return {Emitter}
  27948. * @api public
  27949. */
  27950. Emitter.prototype.on =
  27951. Emitter.prototype.addEventListener = function(event, fn){
  27952. this._callbacks = this._callbacks || {};
  27953. (this._callbacks[event] = this._callbacks[event] || [])
  27954. .push(fn);
  27955. return this;
  27956. };
  27957. /**
  27958. * Adds an `event` listener that will be invoked a single
  27959. * time then automatically removed.
  27960. *
  27961. * @param {String} event
  27962. * @param {Function} fn
  27963. * @return {Emitter}
  27964. * @api public
  27965. */
  27966. Emitter.prototype.once = function(event, fn){
  27967. var self = this;
  27968. this._callbacks = this._callbacks || {};
  27969. function on() {
  27970. self.off(event, on);
  27971. fn.apply(this, arguments);
  27972. }
  27973. on.fn = fn;
  27974. this.on(event, on);
  27975. return this;
  27976. };
  27977. /**
  27978. * Remove the given callback for `event` or all
  27979. * registered callbacks.
  27980. *
  27981. * @param {String} event
  27982. * @param {Function} fn
  27983. * @return {Emitter}
  27984. * @api public
  27985. */
  27986. Emitter.prototype.off =
  27987. Emitter.prototype.removeListener =
  27988. Emitter.prototype.removeAllListeners =
  27989. Emitter.prototype.removeEventListener = function(event, fn){
  27990. this._callbacks = this._callbacks || {};
  27991. // all
  27992. if (0 == arguments.length) {
  27993. this._callbacks = {};
  27994. return this;
  27995. }
  27996. // specific event
  27997. var callbacks = this._callbacks[event];
  27998. if (!callbacks) return this;
  27999. // remove all handlers
  28000. if (1 == arguments.length) {
  28001. delete this._callbacks[event];
  28002. return this;
  28003. }
  28004. // remove specific handler
  28005. var cb;
  28006. for (var i = 0; i < callbacks.length; i++) {
  28007. cb = callbacks[i];
  28008. if (cb === fn || cb.fn === fn) {
  28009. callbacks.splice(i, 1);
  28010. break;
  28011. }
  28012. }
  28013. return this;
  28014. };
  28015. /**
  28016. * Emit `event` with the given args.
  28017. *
  28018. * @param {String} event
  28019. * @param {Mixed} ...
  28020. * @return {Emitter}
  28021. */
  28022. Emitter.prototype.emit = function(event){
  28023. this._callbacks = this._callbacks || {};
  28024. var args = [].slice.call(arguments, 1)
  28025. , callbacks = this._callbacks[event];
  28026. if (callbacks) {
  28027. callbacks = callbacks.slice(0);
  28028. for (var i = 0, len = callbacks.length; i < len; ++i) {
  28029. callbacks[i].apply(this, args);
  28030. }
  28031. }
  28032. return this;
  28033. };
  28034. /**
  28035. * Return array of callbacks for `event`.
  28036. *
  28037. * @param {String} event
  28038. * @return {Array}
  28039. * @api public
  28040. */
  28041. Emitter.prototype.listeners = function(event){
  28042. this._callbacks = this._callbacks || {};
  28043. return this._callbacks[event] || [];
  28044. };
  28045. /**
  28046. * Check if this emitter has `event` handlers.
  28047. *
  28048. * @param {String} event
  28049. * @return {Boolean}
  28050. * @api public
  28051. */
  28052. Emitter.prototype.hasListeners = function(event){
  28053. return !! this.listeners(event).length;
  28054. };
  28055. },{}],110:[function(require,module,exports){
  28056. /**
  28057. * Expose `debug()` as the module.
  28058. */
  28059. module.exports = debug;
  28060. /**
  28061. * Create a debugger with the given `name`.
  28062. *
  28063. * @param {String} name
  28064. * @return {Type}
  28065. * @api public
  28066. */
  28067. function debug(name) {
  28068. if (!debug.enabled(name)) return function(){};
  28069. return function(fmt){
  28070. fmt = coerce(fmt);
  28071. var curr = new Date;
  28072. var ms = curr - (debug[name] || curr);
  28073. debug[name] = curr;
  28074. fmt = name
  28075. + ' '
  28076. + fmt
  28077. + ' +' + debug.humanize(ms);
  28078. // This hackery is required for IE8
  28079. // where `console.log` doesn't have 'apply'
  28080. window.console
  28081. && console.log
  28082. && Function.prototype.apply.call(console.log, console, arguments);
  28083. }
  28084. }
  28085. /**
  28086. * The currently active debug mode names.
  28087. */
  28088. debug.names = [];
  28089. debug.skips = [];
  28090. /**
  28091. * Enables a debug mode by name. This can include modes
  28092. * separated by a colon and wildcards.
  28093. *
  28094. * @param {String} name
  28095. * @api public
  28096. */
  28097. debug.enable = function(name) {
  28098. try {
  28099. localStorage.debug = name;
  28100. } catch(e){}
  28101. var split = (name || '').split(/[\s,]+/)
  28102. , len = split.length;
  28103. for (var i = 0; i < len; i++) {
  28104. name = split[i].replace('*', '.*?');
  28105. if (name[0] === '-') {
  28106. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  28107. }
  28108. else {
  28109. debug.names.push(new RegExp('^' + name + '$'));
  28110. }
  28111. }
  28112. };
  28113. /**
  28114. * Disable debug output.
  28115. *
  28116. * @api public
  28117. */
  28118. debug.disable = function(){
  28119. debug.enable('');
  28120. };
  28121. /**
  28122. * Humanize the given `ms`.
  28123. *
  28124. * @param {Number} m
  28125. * @return {String}
  28126. * @api private
  28127. */
  28128. debug.humanize = function(ms) {
  28129. var sec = 1000
  28130. , min = 60 * 1000
  28131. , hour = 60 * min;
  28132. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  28133. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  28134. if (ms >= sec) return (ms / sec | 0) + 's';
  28135. return ms + 'ms';
  28136. };
  28137. /**
  28138. * Returns true if the given mode name is enabled, false otherwise.
  28139. *
  28140. * @param {String} name
  28141. * @return {Boolean}
  28142. * @api public
  28143. */
  28144. debug.enabled = function(name) {
  28145. for (var i = 0, len = debug.skips.length; i < len; i++) {
  28146. if (debug.skips[i].test(name)) {
  28147. return false;
  28148. }
  28149. }
  28150. for (var i = 0, len = debug.names.length; i < len; i++) {
  28151. if (debug.names[i].test(name)) {
  28152. return true;
  28153. }
  28154. }
  28155. return false;
  28156. };
  28157. /**
  28158. * Coerce `val`.
  28159. */
  28160. function coerce(val) {
  28161. if (val instanceof Error) return val.stack || val.message;
  28162. return val;
  28163. }
  28164. // persist
  28165. try {
  28166. if (window.localStorage) debug.enable(localStorage.debug);
  28167. } catch(e){}
  28168. },{}],111:[function(require,module,exports){
  28169. module.exports = require('./lib/');
  28170. },{"./lib/":112}],112:[function(require,module,exports){
  28171. module.exports = require('./socket');
  28172. /**
  28173. * Exports parser
  28174. *
  28175. * @api public
  28176. *
  28177. */
  28178. module.exports.parser = require('engine.io-parser');
  28179. },{"./socket":113,"engine.io-parser":125}],113:[function(require,module,exports){
  28180. (function (global){
  28181. /**
  28182. * Module dependencies.
  28183. */
  28184. var transports = require('./transports');
  28185. var Emitter = require('component-emitter');
  28186. var debug = require('debug')('engine.io-client:socket');
  28187. var index = require('indexof');
  28188. var parser = require('engine.io-parser');
  28189. var parseuri = require('parseuri');
  28190. var parsejson = require('parsejson');
  28191. var parseqs = require('parseqs');
  28192. /**
  28193. * Module exports.
  28194. */
  28195. module.exports = Socket;
  28196. /**
  28197. * Noop function.
  28198. *
  28199. * @api private
  28200. */
  28201. function noop(){}
  28202. /**
  28203. * Socket constructor.
  28204. *
  28205. * @param {String|Object} uri or options
  28206. * @param {Object} options
  28207. * @api public
  28208. */
  28209. function Socket(uri, opts){
  28210. if (!(this instanceof Socket)) return new Socket(uri, opts);
  28211. opts = opts || {};
  28212. if (uri && 'object' == typeof uri) {
  28213. opts = uri;
  28214. uri = null;
  28215. }
  28216. if (uri) {
  28217. uri = parseuri(uri);
  28218. opts.host = uri.host;
  28219. opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
  28220. opts.port = uri.port;
  28221. if (uri.query) opts.query = uri.query;
  28222. }
  28223. this.secure = null != opts.secure ? opts.secure :
  28224. (global.location && 'https:' == location.protocol);
  28225. if (opts.host) {
  28226. var pieces = opts.host.split(':');
  28227. opts.hostname = pieces.shift();
  28228. if (pieces.length) {
  28229. opts.port = pieces.pop();
  28230. } else if (!opts.port) {
  28231. // if no port is specified manually, use the protocol default
  28232. opts.port = this.secure ? '443' : '80';
  28233. }
  28234. }
  28235. this.agent = opts.agent || false;
  28236. this.hostname = opts.hostname ||
  28237. (global.location ? location.hostname : 'localhost');
  28238. this.port = opts.port || (global.location && location.port ?
  28239. location.port :
  28240. (this.secure ? 443 : 80));
  28241. this.query = opts.query || {};
  28242. if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
  28243. this.upgrade = false !== opts.upgrade;
  28244. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  28245. this.forceJSONP = !!opts.forceJSONP;
  28246. this.jsonp = false !== opts.jsonp;
  28247. this.forceBase64 = !!opts.forceBase64;
  28248. this.enablesXDR = !!opts.enablesXDR;
  28249. this.timestampParam = opts.timestampParam || 't';
  28250. this.timestampRequests = opts.timestampRequests;
  28251. this.transports = opts.transports || ['polling', 'websocket'];
  28252. this.readyState = '';
  28253. this.writeBuffer = [];
  28254. this.callbackBuffer = [];
  28255. this.policyPort = opts.policyPort || 843;
  28256. this.rememberUpgrade = opts.rememberUpgrade || false;
  28257. this.binaryType = null;
  28258. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  28259. // SSL options for Node.js client
  28260. this.pfx = opts.pfx || null;
  28261. this.key = opts.key || null;
  28262. this.passphrase = opts.passphrase || null;
  28263. this.cert = opts.cert || null;
  28264. this.ca = opts.ca || null;
  28265. this.ciphers = opts.ciphers || null;
  28266. this.rejectUnauthorized = opts.rejectUnauthorized || null;
  28267. this.open();
  28268. }
  28269. Socket.priorWebsocketSuccess = false;
  28270. /**
  28271. * Mix in `Emitter`.
  28272. */
  28273. Emitter(Socket.prototype);
  28274. /**
  28275. * Protocol version.
  28276. *
  28277. * @api public
  28278. */
  28279. Socket.protocol = parser.protocol; // this is an int
  28280. /**
  28281. * Expose deps for legacy compatibility
  28282. * and standalone browser access.
  28283. */
  28284. Socket.Socket = Socket;
  28285. Socket.Transport = require('./transport');
  28286. Socket.transports = require('./transports');
  28287. Socket.parser = require('engine.io-parser');
  28288. /**
  28289. * Creates transport of the given type.
  28290. *
  28291. * @param {String} transport name
  28292. * @return {Transport}
  28293. * @api private
  28294. */
  28295. Socket.prototype.createTransport = function (name) {
  28296. debug('creating transport "%s"', name);
  28297. var query = clone(this.query);
  28298. // append engine.io protocol identifier
  28299. query.EIO = parser.protocol;
  28300. // transport name
  28301. query.transport = name;
  28302. // session id if we already have one
  28303. if (this.id) query.sid = this.id;
  28304. var transport = new transports[name]({
  28305. agent: this.agent,
  28306. hostname: this.hostname,
  28307. port: this.port,
  28308. secure: this.secure,
  28309. path: this.path,
  28310. query: query,
  28311. forceJSONP: this.forceJSONP,
  28312. jsonp: this.jsonp,
  28313. forceBase64: this.forceBase64,
  28314. enablesXDR: this.enablesXDR,
  28315. timestampRequests: this.timestampRequests,
  28316. timestampParam: this.timestampParam,
  28317. policyPort: this.policyPort,
  28318. socket: this,
  28319. pfx: this.pfx,
  28320. key: this.key,
  28321. passphrase: this.passphrase,
  28322. cert: this.cert,
  28323. ca: this.ca,
  28324. ciphers: this.ciphers,
  28325. rejectUnauthorized: this.rejectUnauthorized
  28326. });
  28327. return transport;
  28328. };
  28329. function clone (obj) {
  28330. var o = {};
  28331. for (var i in obj) {
  28332. if (obj.hasOwnProperty(i)) {
  28333. o[i] = obj[i];
  28334. }
  28335. }
  28336. return o;
  28337. }
  28338. /**
  28339. * Initializes transport to use and starts probe.
  28340. *
  28341. * @api private
  28342. */
  28343. Socket.prototype.open = function () {
  28344. var transport;
  28345. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
  28346. transport = 'websocket';
  28347. } else if (0 == this.transports.length) {
  28348. // Emit error on next tick so it can be listened to
  28349. var self = this;
  28350. setTimeout(function() {
  28351. self.emit('error', 'No transports available');
  28352. }, 0);
  28353. return;
  28354. } else {
  28355. transport = this.transports[0];
  28356. }
  28357. this.readyState = 'opening';
  28358. // Retry with the next transport if the transport is disabled (jsonp: false)
  28359. var transport;
  28360. try {
  28361. transport = this.createTransport(transport);
  28362. } catch (e) {
  28363. this.transports.shift();
  28364. this.open();
  28365. return;
  28366. }
  28367. transport.open();
  28368. this.setTransport(transport);
  28369. };
  28370. /**
  28371. * Sets the current transport. Disables the existing one (if any).
  28372. *
  28373. * @api private
  28374. */
  28375. Socket.prototype.setTransport = function(transport){
  28376. debug('setting transport %s', transport.name);
  28377. var self = this;
  28378. if (this.transport) {
  28379. debug('clearing existing transport %s', this.transport.name);
  28380. this.transport.removeAllListeners();
  28381. }
  28382. // set up transport
  28383. this.transport = transport;
  28384. // set up transport listeners
  28385. transport
  28386. .on('drain', function(){
  28387. self.onDrain();
  28388. })
  28389. .on('packet', function(packet){
  28390. self.onPacket(packet);
  28391. })
  28392. .on('error', function(e){
  28393. self.onError(e);
  28394. })
  28395. .on('close', function(){
  28396. self.onClose('transport close');
  28397. });
  28398. };
  28399. /**
  28400. * Probes a transport.
  28401. *
  28402. * @param {String} transport name
  28403. * @api private
  28404. */
  28405. Socket.prototype.probe = function (name) {
  28406. debug('probing transport "%s"', name);
  28407. var transport = this.createTransport(name, { probe: 1 })
  28408. , failed = false
  28409. , self = this;
  28410. Socket.priorWebsocketSuccess = false;
  28411. function onTransportOpen(){
  28412. if (self.onlyBinaryUpgrades) {
  28413. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  28414. failed = failed || upgradeLosesBinary;
  28415. }
  28416. if (failed) return;
  28417. debug('probe transport "%s" opened', name);
  28418. transport.send([{ type: 'ping', data: 'probe' }]);
  28419. transport.once('packet', function (msg) {
  28420. if (failed) return;
  28421. if ('pong' == msg.type && 'probe' == msg.data) {
  28422. debug('probe transport "%s" pong', name);
  28423. self.upgrading = true;
  28424. self.emit('upgrading', transport);
  28425. if (!transport) return;
  28426. Socket.priorWebsocketSuccess = 'websocket' == transport.name;
  28427. debug('pausing current transport "%s"', self.transport.name);
  28428. self.transport.pause(function () {
  28429. if (failed) return;
  28430. if ('closed' == self.readyState) return;
  28431. debug('changing transport and sending upgrade packet');
  28432. cleanup();
  28433. self.setTransport(transport);
  28434. transport.send([{ type: 'upgrade' }]);
  28435. self.emit('upgrade', transport);
  28436. transport = null;
  28437. self.upgrading = false;
  28438. self.flush();
  28439. });
  28440. } else {
  28441. debug('probe transport "%s" failed', name);
  28442. var err = new Error('probe error');
  28443. err.transport = transport.name;
  28444. self.emit('upgradeError', err);
  28445. }
  28446. });
  28447. }
  28448. function freezeTransport() {
  28449. if (failed) return;
  28450. // Any callback called by transport should be ignored since now
  28451. failed = true;
  28452. cleanup();
  28453. transport.close();
  28454. transport = null;
  28455. }
  28456. //Handle any error that happens while probing
  28457. function onerror(err) {
  28458. var error = new Error('probe error: ' + err);
  28459. error.transport = transport.name;
  28460. freezeTransport();
  28461. debug('probe transport "%s" failed because of error: %s', name, err);
  28462. self.emit('upgradeError', error);
  28463. }
  28464. function onTransportClose(){
  28465. onerror("transport closed");
  28466. }
  28467. //When the socket is closed while we're probing
  28468. function onclose(){
  28469. onerror("socket closed");
  28470. }
  28471. //When the socket is upgraded while we're probing
  28472. function onupgrade(to){
  28473. if (transport && to.name != transport.name) {
  28474. debug('"%s" works - aborting "%s"', to.name, transport.name);
  28475. freezeTransport();
  28476. }
  28477. }
  28478. //Remove all listeners on the transport and on self
  28479. function cleanup(){
  28480. transport.removeListener('open', onTransportOpen);
  28481. transport.removeListener('error', onerror);
  28482. transport.removeListener('close', onTransportClose);
  28483. self.removeListener('close', onclose);
  28484. self.removeListener('upgrading', onupgrade);
  28485. }
  28486. transport.once('open', onTransportOpen);
  28487. transport.once('error', onerror);
  28488. transport.once('close', onTransportClose);
  28489. this.once('close', onclose);
  28490. this.once('upgrading', onupgrade);
  28491. transport.open();
  28492. };
  28493. /**
  28494. * Called when connection is deemed open.
  28495. *
  28496. * @api public
  28497. */
  28498. Socket.prototype.onOpen = function () {
  28499. debug('socket open');
  28500. this.readyState = 'open';
  28501. Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
  28502. this.emit('open');
  28503. this.flush();
  28504. // we check for `readyState` in case an `open`
  28505. // listener already closed the socket
  28506. if ('open' == this.readyState && this.upgrade && this.transport.pause) {
  28507. debug('starting upgrade probes');
  28508. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  28509. this.probe(this.upgrades[i]);
  28510. }
  28511. }
  28512. };
  28513. /**
  28514. * Handles a packet.
  28515. *
  28516. * @api private
  28517. */
  28518. Socket.prototype.onPacket = function (packet) {
  28519. if ('opening' == this.readyState || 'open' == this.readyState) {
  28520. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  28521. this.emit('packet', packet);
  28522. // Socket is live - any packet counts
  28523. this.emit('heartbeat');
  28524. switch (packet.type) {
  28525. case 'open':
  28526. this.onHandshake(parsejson(packet.data));
  28527. break;
  28528. case 'pong':
  28529. this.setPing();
  28530. break;
  28531. case 'error':
  28532. var err = new Error('server error');
  28533. err.code = packet.data;
  28534. this.emit('error', err);
  28535. break;
  28536. case 'message':
  28537. this.emit('data', packet.data);
  28538. this.emit('message', packet.data);
  28539. break;
  28540. }
  28541. } else {
  28542. debug('packet received with socket readyState "%s"', this.readyState);
  28543. }
  28544. };
  28545. /**
  28546. * Called upon handshake completion.
  28547. *
  28548. * @param {Object} handshake obj
  28549. * @api private
  28550. */
  28551. Socket.prototype.onHandshake = function (data) {
  28552. this.emit('handshake', data);
  28553. this.id = data.sid;
  28554. this.transport.query.sid = data.sid;
  28555. this.upgrades = this.filterUpgrades(data.upgrades);
  28556. this.pingInterval = data.pingInterval;
  28557. this.pingTimeout = data.pingTimeout;
  28558. this.onOpen();
  28559. // In case open handler closes socket
  28560. if ('closed' == this.readyState) return;
  28561. this.setPing();
  28562. // Prolong liveness of socket on heartbeat
  28563. this.removeListener('heartbeat', this.onHeartbeat);
  28564. this.on('heartbeat', this.onHeartbeat);
  28565. };
  28566. /**
  28567. * Resets ping timeout.
  28568. *
  28569. * @api private
  28570. */
  28571. Socket.prototype.onHeartbeat = function (timeout) {
  28572. clearTimeout(this.pingTimeoutTimer);
  28573. var self = this;
  28574. self.pingTimeoutTimer = setTimeout(function () {
  28575. if ('closed' == self.readyState) return;
  28576. self.onClose('ping timeout');
  28577. }, timeout || (self.pingInterval + self.pingTimeout));
  28578. };
  28579. /**
  28580. * Pings server every `this.pingInterval` and expects response
  28581. * within `this.pingTimeout` or closes connection.
  28582. *
  28583. * @api private
  28584. */
  28585. Socket.prototype.setPing = function () {
  28586. var self = this;
  28587. clearTimeout(self.pingIntervalTimer);
  28588. self.pingIntervalTimer = setTimeout(function () {
  28589. debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
  28590. self.ping();
  28591. self.onHeartbeat(self.pingTimeout);
  28592. }, self.pingInterval);
  28593. };
  28594. /**
  28595. * Sends a ping packet.
  28596. *
  28597. * @api public
  28598. */
  28599. Socket.prototype.ping = function () {
  28600. this.sendPacket('ping');
  28601. };
  28602. /**
  28603. * Called on `drain` event
  28604. *
  28605. * @api private
  28606. */
  28607. Socket.prototype.onDrain = function() {
  28608. for (var i = 0; i < this.prevBufferLen; i++) {
  28609. if (this.callbackBuffer[i]) {
  28610. this.callbackBuffer[i]();
  28611. }
  28612. }
  28613. this.writeBuffer.splice(0, this.prevBufferLen);
  28614. this.callbackBuffer.splice(0, this.prevBufferLen);
  28615. // setting prevBufferLen = 0 is very important
  28616. // for example, when upgrading, upgrade packet is sent over,
  28617. // and a nonzero prevBufferLen could cause problems on `drain`
  28618. this.prevBufferLen = 0;
  28619. if (this.writeBuffer.length == 0) {
  28620. this.emit('drain');
  28621. } else {
  28622. this.flush();
  28623. }
  28624. };
  28625. /**
  28626. * Flush write buffers.
  28627. *
  28628. * @api private
  28629. */
  28630. Socket.prototype.flush = function () {
  28631. if ('closed' != this.readyState && this.transport.writable &&
  28632. !this.upgrading && this.writeBuffer.length) {
  28633. debug('flushing %d packets in socket', this.writeBuffer.length);
  28634. this.transport.send(this.writeBuffer);
  28635. // keep track of current length of writeBuffer
  28636. // splice writeBuffer and callbackBuffer on `drain`
  28637. this.prevBufferLen = this.writeBuffer.length;
  28638. this.emit('flush');
  28639. }
  28640. };
  28641. /**
  28642. * Sends a message.
  28643. *
  28644. * @param {String} message.
  28645. * @param {Function} callback function.
  28646. * @return {Socket} for chaining.
  28647. * @api public
  28648. */
  28649. Socket.prototype.write =
  28650. Socket.prototype.send = function (msg, fn) {
  28651. this.sendPacket('message', msg, fn);
  28652. return this;
  28653. };
  28654. /**
  28655. * Sends a packet.
  28656. *
  28657. * @param {String} packet type.
  28658. * @param {String} data.
  28659. * @param {Function} callback function.
  28660. * @api private
  28661. */
  28662. Socket.prototype.sendPacket = function (type, data, fn) {
  28663. if ('closing' == this.readyState || 'closed' == this.readyState) {
  28664. return;
  28665. }
  28666. var packet = { type: type, data: data };
  28667. this.emit('packetCreate', packet);
  28668. this.writeBuffer.push(packet);
  28669. this.callbackBuffer.push(fn);
  28670. this.flush();
  28671. };
  28672. /**
  28673. * Closes the connection.
  28674. *
  28675. * @api private
  28676. */
  28677. Socket.prototype.close = function () {
  28678. if ('opening' == this.readyState || 'open' == this.readyState) {
  28679. this.readyState = 'closing';
  28680. var self = this;
  28681. function close() {
  28682. self.onClose('forced close');
  28683. debug('socket closing - telling transport to close');
  28684. self.transport.close();
  28685. }
  28686. function cleanupAndClose() {
  28687. self.removeListener('upgrade', cleanupAndClose);
  28688. self.removeListener('upgradeError', cleanupAndClose);
  28689. close();
  28690. }
  28691. function waitForUpgrade() {
  28692. // wait for upgrade to finish since we can't send packets while pausing a transport
  28693. self.once('upgrade', cleanupAndClose);
  28694. self.once('upgradeError', cleanupAndClose);
  28695. }
  28696. if (this.writeBuffer.length) {
  28697. this.once('drain', function() {
  28698. if (this.upgrading) {
  28699. waitForUpgrade();
  28700. } else {
  28701. close();
  28702. }
  28703. });
  28704. } else if (this.upgrading) {
  28705. waitForUpgrade();
  28706. } else {
  28707. close();
  28708. }
  28709. }
  28710. return this;
  28711. };
  28712. /**
  28713. * Called upon transport error
  28714. *
  28715. * @api private
  28716. */
  28717. Socket.prototype.onError = function (err) {
  28718. debug('socket error %j', err);
  28719. Socket.priorWebsocketSuccess = false;
  28720. this.emit('error', err);
  28721. this.onClose('transport error', err);
  28722. };
  28723. /**
  28724. * Called upon transport close.
  28725. *
  28726. * @api private
  28727. */
  28728. Socket.prototype.onClose = function (reason, desc) {
  28729. if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
  28730. debug('socket close with reason: "%s"', reason);
  28731. var self = this;
  28732. // clear timers
  28733. clearTimeout(this.pingIntervalTimer);
  28734. clearTimeout(this.pingTimeoutTimer);
  28735. // clean buffers in next tick, so developers can still
  28736. // grab the buffers on `close` event
  28737. setTimeout(function() {
  28738. self.writeBuffer = [];
  28739. self.callbackBuffer = [];
  28740. self.prevBufferLen = 0;
  28741. }, 0);
  28742. // stop event from firing again for transport
  28743. this.transport.removeAllListeners('close');
  28744. // ensure transport won't stay open
  28745. this.transport.close();
  28746. // ignore further transport communication
  28747. this.transport.removeAllListeners();
  28748. // set ready state
  28749. this.readyState = 'closed';
  28750. // clear session id
  28751. this.id = null;
  28752. // emit close event
  28753. this.emit('close', reason, desc);
  28754. }
  28755. };
  28756. /**
  28757. * Filters upgrades, returning only those matching client transports.
  28758. *
  28759. * @param {Array} server upgrades
  28760. * @api private
  28761. *
  28762. */
  28763. Socket.prototype.filterUpgrades = function (upgrades) {
  28764. var filteredUpgrades = [];
  28765. for (var i = 0, j = upgrades.length; i<j; i++) {
  28766. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  28767. }
  28768. return filteredUpgrades;
  28769. };
  28770. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  28771. },{"./transport":114,"./transports":115,"component-emitter":109,"debug":122,"engine.io-parser":125,"indexof":142,"parsejson":136,"parseqs":137,"parseuri":138}],114:[function(require,module,exports){
  28772. /**
  28773. * Module dependencies.
  28774. */
  28775. var parser = require('engine.io-parser');
  28776. var Emitter = require('component-emitter');
  28777. /**
  28778. * Module exports.
  28779. */
  28780. module.exports = Transport;
  28781. /**
  28782. * Transport abstract constructor.
  28783. *
  28784. * @param {Object} options.
  28785. * @api private
  28786. */
  28787. function Transport (opts) {
  28788. this.path = opts.path;
  28789. this.hostname = opts.hostname;
  28790. this.port = opts.port;
  28791. this.secure = opts.secure;
  28792. this.query = opts.query;
  28793. this.timestampParam = opts.timestampParam;
  28794. this.timestampRequests = opts.timestampRequests;
  28795. this.readyState = '';
  28796. this.agent = opts.agent || false;
  28797. this.socket = opts.socket;
  28798. this.enablesXDR = opts.enablesXDR;
  28799. // SSL options for Node.js client
  28800. this.pfx = opts.pfx;
  28801. this.key = opts.key;
  28802. this.passphrase = opts.passphrase;
  28803. this.cert = opts.cert;
  28804. this.ca = opts.ca;
  28805. this.ciphers = opts.ciphers;
  28806. this.rejectUnauthorized = opts.rejectUnauthorized;
  28807. }
  28808. /**
  28809. * Mix in `Emitter`.
  28810. */
  28811. Emitter(Transport.prototype);
  28812. /**
  28813. * A counter used to prevent collisions in the timestamps used
  28814. * for cache busting.
  28815. */
  28816. Transport.timestamps = 0;
  28817. /**
  28818. * Emits an error.
  28819. *
  28820. * @param {String} str
  28821. * @return {Transport} for chaining
  28822. * @api public
  28823. */
  28824. Transport.prototype.onError = function (msg, desc) {
  28825. var err = new Error(msg);
  28826. err.type = 'TransportError';
  28827. err.description = desc;
  28828. this.emit('error', err);
  28829. return this;
  28830. };
  28831. /**
  28832. * Opens the transport.
  28833. *
  28834. * @api public
  28835. */
  28836. Transport.prototype.open = function () {
  28837. if ('closed' == this.readyState || '' == this.readyState) {
  28838. this.readyState = 'opening';
  28839. this.doOpen();
  28840. }
  28841. return this;
  28842. };
  28843. /**
  28844. * Closes the transport.
  28845. *
  28846. * @api private
  28847. */
  28848. Transport.prototype.close = function () {
  28849. if ('opening' == this.readyState || 'open' == this.readyState) {
  28850. this.doClose();
  28851. this.onClose();
  28852. }
  28853. return this;
  28854. };
  28855. /**
  28856. * Sends multiple packets.
  28857. *
  28858. * @param {Array} packets
  28859. * @api private
  28860. */
  28861. Transport.prototype.send = function(packets){
  28862. if ('open' == this.readyState) {
  28863. this.write(packets);
  28864. } else {
  28865. throw new Error('Transport not open');
  28866. }
  28867. };
  28868. /**
  28869. * Called upon open
  28870. *
  28871. * @api private
  28872. */
  28873. Transport.prototype.onOpen = function () {
  28874. this.readyState = 'open';
  28875. this.writable = true;
  28876. this.emit('open');
  28877. };
  28878. /**
  28879. * Called with data.
  28880. *
  28881. * @param {String} data
  28882. * @api private
  28883. */
  28884. Transport.prototype.onData = function(data){
  28885. var packet = parser.decodePacket(data, this.socket.binaryType);
  28886. this.onPacket(packet);
  28887. };
  28888. /**
  28889. * Called with a decoded packet.
  28890. */
  28891. Transport.prototype.onPacket = function (packet) {
  28892. this.emit('packet', packet);
  28893. };
  28894. /**
  28895. * Called upon close.
  28896. *
  28897. * @api private
  28898. */
  28899. Transport.prototype.onClose = function () {
  28900. this.readyState = 'closed';
  28901. this.emit('close');
  28902. };
  28903. },{"component-emitter":109,"engine.io-parser":125}],115:[function(require,module,exports){
  28904. (function (global){
  28905. /**
  28906. * Module dependencies
  28907. */
  28908. var XMLHttpRequest = require('xmlhttprequest');
  28909. var XHR = require('./polling-xhr');
  28910. var JSONP = require('./polling-jsonp');
  28911. var websocket = require('./websocket');
  28912. /**
  28913. * Export transports.
  28914. */
  28915. exports.polling = polling;
  28916. exports.websocket = websocket;
  28917. /**
  28918. * Polling transport polymorphic constructor.
  28919. * Decides on xhr vs jsonp based on feature detection.
  28920. *
  28921. * @api private
  28922. */
  28923. function polling(opts){
  28924. var xhr;
  28925. var xd = false;
  28926. var xs = false;
  28927. var jsonp = false !== opts.jsonp;
  28928. if (global.location) {
  28929. var isSSL = 'https:' == location.protocol;
  28930. var port = location.port;
  28931. // some user agents have empty `location.port`
  28932. if (!port) {
  28933. port = isSSL ? 443 : 80;
  28934. }
  28935. xd = opts.hostname != location.hostname || port != opts.port;
  28936. xs = opts.secure != isSSL;
  28937. }
  28938. opts.xdomain = xd;
  28939. opts.xscheme = xs;
  28940. xhr = new XMLHttpRequest(opts);
  28941. if ('open' in xhr && !opts.forceJSONP) {
  28942. return new XHR(opts);
  28943. } else {
  28944. if (!jsonp) throw new Error('JSONP disabled');
  28945. return new JSONP(opts);
  28946. }
  28947. }
  28948. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  28949. },{"./polling-jsonp":116,"./polling-xhr":117,"./websocket":119,"xmlhttprequest":120}],116:[function(require,module,exports){
  28950. (function (global){
  28951. /**
  28952. * Module requirements.
  28953. */
  28954. var Polling = require('./polling');
  28955. var inherit = require('component-inherit');
  28956. /**
  28957. * Module exports.
  28958. */
  28959. module.exports = JSONPPolling;
  28960. /**
  28961. * Cached regular expressions.
  28962. */
  28963. var rNewline = /\n/g;
  28964. var rEscapedNewline = /\\n/g;
  28965. /**
  28966. * Global JSONP callbacks.
  28967. */
  28968. var callbacks;
  28969. /**
  28970. * Callbacks count.
  28971. */
  28972. var index = 0;
  28973. /**
  28974. * Noop.
  28975. */
  28976. function empty () { }
  28977. /**
  28978. * JSONP Polling constructor.
  28979. *
  28980. * @param {Object} opts.
  28981. * @api public
  28982. */
  28983. function JSONPPolling (opts) {
  28984. Polling.call(this, opts);
  28985. this.query = this.query || {};
  28986. // define global callbacks array if not present
  28987. // we do this here (lazily) to avoid unneeded global pollution
  28988. if (!callbacks) {
  28989. // we need to consider multiple engines in the same page
  28990. if (!global.___eio) global.___eio = [];
  28991. callbacks = global.___eio;
  28992. }
  28993. // callback identifier
  28994. this.index = callbacks.length;
  28995. // add callback to jsonp global
  28996. var self = this;
  28997. callbacks.push(function (msg) {
  28998. self.onData(msg);
  28999. });
  29000. // append to query string
  29001. this.query.j = this.index;
  29002. // prevent spurious errors from being emitted when the window is unloaded
  29003. if (global.document && global.addEventListener) {
  29004. global.addEventListener('beforeunload', function () {
  29005. if (self.script) self.script.onerror = empty;
  29006. }, false);
  29007. }
  29008. }
  29009. /**
  29010. * Inherits from Polling.
  29011. */
  29012. inherit(JSONPPolling, Polling);
  29013. /*
  29014. * JSONP only supports binary as base64 encoded strings
  29015. */
  29016. JSONPPolling.prototype.supportsBinary = false;
  29017. /**
  29018. * Closes the socket.
  29019. *
  29020. * @api private
  29021. */
  29022. JSONPPolling.prototype.doClose = function () {
  29023. if (this.script) {
  29024. this.script.parentNode.removeChild(this.script);
  29025. this.script = null;
  29026. }
  29027. if (this.form) {
  29028. this.form.parentNode.removeChild(this.form);
  29029. this.form = null;
  29030. this.iframe = null;
  29031. }
  29032. Polling.prototype.doClose.call(this);
  29033. };
  29034. /**
  29035. * Starts a poll cycle.
  29036. *
  29037. * @api private
  29038. */
  29039. JSONPPolling.prototype.doPoll = function () {
  29040. var self = this;
  29041. var script = document.createElement('script');
  29042. if (this.script) {
  29043. this.script.parentNode.removeChild(this.script);
  29044. this.script = null;
  29045. }
  29046. script.async = true;
  29047. script.src = this.uri();
  29048. script.onerror = function(e){
  29049. self.onError('jsonp poll error',e);
  29050. };
  29051. var insertAt = document.getElementsByTagName('script')[0];
  29052. insertAt.parentNode.insertBefore(script, insertAt);
  29053. this.script = script;
  29054. var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
  29055. if (isUAgecko) {
  29056. setTimeout(function () {
  29057. var iframe = document.createElement('iframe');
  29058. document.body.appendChild(iframe);
  29059. document.body.removeChild(iframe);
  29060. }, 100);
  29061. }
  29062. };
  29063. /**
  29064. * Writes with a hidden iframe.
  29065. *
  29066. * @param {String} data to send
  29067. * @param {Function} called upon flush.
  29068. * @api private
  29069. */
  29070. JSONPPolling.prototype.doWrite = function (data, fn) {
  29071. var self = this;
  29072. if (!this.form) {
  29073. var form = document.createElement('form');
  29074. var area = document.createElement('textarea');
  29075. var id = this.iframeId = 'eio_iframe_' + this.index;
  29076. var iframe;
  29077. form.className = 'socketio';
  29078. form.style.position = 'absolute';
  29079. form.style.top = '-1000px';
  29080. form.style.left = '-1000px';
  29081. form.target = id;
  29082. form.method = 'POST';
  29083. form.setAttribute('accept-charset', 'utf-8');
  29084. area.name = 'd';
  29085. form.appendChild(area);
  29086. document.body.appendChild(form);
  29087. this.form = form;
  29088. this.area = area;
  29089. }
  29090. this.form.action = this.uri();
  29091. function complete () {
  29092. initIframe();
  29093. fn();
  29094. }
  29095. function initIframe () {
  29096. if (self.iframe) {
  29097. try {
  29098. self.form.removeChild(self.iframe);
  29099. } catch (e) {
  29100. self.onError('jsonp polling iframe removal error', e);
  29101. }
  29102. }
  29103. try {
  29104. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  29105. var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
  29106. iframe = document.createElement(html);
  29107. } catch (e) {
  29108. iframe = document.createElement('iframe');
  29109. iframe.name = self.iframeId;
  29110. iframe.src = 'javascript:0';
  29111. }
  29112. iframe.id = self.iframeId;
  29113. self.form.appendChild(iframe);
  29114. self.iframe = iframe;
  29115. }
  29116. initIframe();
  29117. // escape \n to prevent it from being converted into \r\n by some UAs
  29118. // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
  29119. data = data.replace(rEscapedNewline, '\\\n');
  29120. this.area.value = data.replace(rNewline, '\\n');
  29121. try {
  29122. this.form.submit();
  29123. } catch(e) {}
  29124. if (this.iframe.attachEvent) {
  29125. this.iframe.onreadystatechange = function(){
  29126. if (self.iframe.readyState == 'complete') {
  29127. complete();
  29128. }
  29129. };
  29130. } else {
  29131. this.iframe.onload = complete;
  29132. }
  29133. };
  29134. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  29135. },{"./polling":118,"component-inherit":121}],117:[function(require,module,exports){
  29136. (function (global){
  29137. /**
  29138. * Module requirements.
  29139. */
  29140. var XMLHttpRequest = require('xmlhttprequest');
  29141. var Polling = require('./polling');
  29142. var Emitter = require('component-emitter');
  29143. var inherit = require('component-inherit');
  29144. var debug = require('debug')('engine.io-client:polling-xhr');
  29145. /**
  29146. * Module exports.
  29147. */
  29148. module.exports = XHR;
  29149. module.exports.Request = Request;
  29150. /**
  29151. * Empty function
  29152. */
  29153. function empty(){}
  29154. /**
  29155. * XHR Polling constructor.
  29156. *
  29157. * @param {Object} opts
  29158. * @api public
  29159. */
  29160. function XHR(opts){
  29161. Polling.call(this, opts);
  29162. if (global.location) {
  29163. var isSSL = 'https:' == location.protocol;
  29164. var port = location.port;
  29165. // some user agents have empty `location.port`
  29166. if (!port) {
  29167. port = isSSL ? 443 : 80;
  29168. }
  29169. this.xd = opts.hostname != global.location.hostname ||
  29170. port != opts.port;
  29171. this.xs = opts.secure != isSSL;
  29172. }
  29173. }
  29174. /**
  29175. * Inherits from Polling.
  29176. */
  29177. inherit(XHR, Polling);
  29178. /**
  29179. * XHR supports binary
  29180. */
  29181. XHR.prototype.supportsBinary = true;
  29182. /**
  29183. * Creates a request.
  29184. *
  29185. * @param {String} method
  29186. * @api private
  29187. */
  29188. XHR.prototype.request = function(opts){
  29189. opts = opts || {};
  29190. opts.uri = this.uri();
  29191. opts.xd = this.xd;
  29192. opts.xs = this.xs;
  29193. opts.agent = this.agent || false;
  29194. opts.supportsBinary = this.supportsBinary;
  29195. opts.enablesXDR = this.enablesXDR;
  29196. // SSL options for Node.js client
  29197. opts.pfx = this.pfx;
  29198. opts.key = this.key;
  29199. opts.passphrase = this.passphrase;
  29200. opts.cert = this.cert;
  29201. opts.ca = this.ca;
  29202. opts.ciphers = this.ciphers;
  29203. opts.rejectUnauthorized = this.rejectUnauthorized;
  29204. return new Request(opts);
  29205. };
  29206. /**
  29207. * Sends data.
  29208. *
  29209. * @param {String} data to send.
  29210. * @param {Function} called upon flush.
  29211. * @api private
  29212. */
  29213. XHR.prototype.doWrite = function(data, fn){
  29214. var isBinary = typeof data !== 'string' && data !== undefined;
  29215. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  29216. var self = this;
  29217. req.on('success', fn);
  29218. req.on('error', function(err){
  29219. self.onError('xhr post error', err);
  29220. });
  29221. this.sendXhr = req;
  29222. };
  29223. /**
  29224. * Starts a poll cycle.
  29225. *
  29226. * @api private
  29227. */
  29228. XHR.prototype.doPoll = function(){
  29229. debug('xhr poll');
  29230. var req = this.request();
  29231. var self = this;
  29232. req.on('data', function(data){
  29233. self.onData(data);
  29234. });
  29235. req.on('error', function(err){
  29236. self.onError('xhr poll error', err);
  29237. });
  29238. this.pollXhr = req;
  29239. };
  29240. /**
  29241. * Request constructor
  29242. *
  29243. * @param {Object} options
  29244. * @api public
  29245. */
  29246. function Request(opts){
  29247. this.method = opts.method || 'GET';
  29248. this.uri = opts.uri;
  29249. this.xd = !!opts.xd;
  29250. this.xs = !!opts.xs;
  29251. this.async = false !== opts.async;
  29252. this.data = undefined != opts.data ? opts.data : null;
  29253. this.agent = opts.agent;
  29254. this.isBinary = opts.isBinary;
  29255. this.supportsBinary = opts.supportsBinary;
  29256. this.enablesXDR = opts.enablesXDR;
  29257. // SSL options for Node.js client
  29258. this.pfx = opts.pfx;
  29259. this.key = opts.key;
  29260. this.passphrase = opts.passphrase;
  29261. this.cert = opts.cert;
  29262. this.ca = opts.ca;
  29263. this.ciphers = opts.ciphers;
  29264. this.rejectUnauthorized = opts.rejectUnauthorized;
  29265. this.create();
  29266. }
  29267. /**
  29268. * Mix in `Emitter`.
  29269. */
  29270. Emitter(Request.prototype);
  29271. /**
  29272. * Creates the XHR object and sends the request.
  29273. *
  29274. * @api private
  29275. */
  29276. Request.prototype.create = function(){
  29277. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  29278. // SSL options for Node.js client
  29279. opts.pfx = this.pfx;
  29280. opts.key = this.key;
  29281. opts.passphrase = this.passphrase;
  29282. opts.cert = this.cert;
  29283. opts.ca = this.ca;
  29284. opts.ciphers = this.ciphers;
  29285. opts.rejectUnauthorized = this.rejectUnauthorized;
  29286. var xhr = this.xhr = new XMLHttpRequest(opts);
  29287. var self = this;
  29288. try {
  29289. debug('xhr open %s: %s', this.method, this.uri);
  29290. xhr.open(this.method, this.uri, this.async);
  29291. if (this.supportsBinary) {
  29292. // This has to be done after open because Firefox is stupid
  29293. // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
  29294. xhr.responseType = 'arraybuffer';
  29295. }
  29296. if ('POST' == this.method) {
  29297. try {
  29298. if (this.isBinary) {
  29299. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  29300. } else {
  29301. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  29302. }
  29303. } catch (e) {}
  29304. }
  29305. // ie6 check
  29306. if ('withCredentials' in xhr) {
  29307. xhr.withCredentials = true;
  29308. }
  29309. if (this.hasXDR()) {
  29310. xhr.onload = function(){
  29311. self.onLoad();
  29312. };
  29313. xhr.onerror = function(){
  29314. self.onError(xhr.responseText);
  29315. };
  29316. } else {
  29317. xhr.onreadystatechange = function(){
  29318. if (4 != xhr.readyState) return;
  29319. if (200 == xhr.status || 1223 == xhr.status) {
  29320. self.onLoad();
  29321. } else {
  29322. // make sure the `error` event handler that's user-set
  29323. // does not throw in the same tick and gets caught here
  29324. setTimeout(function(){
  29325. self.onError(xhr.status);
  29326. }, 0);
  29327. }
  29328. };
  29329. }
  29330. debug('xhr data %s', this.data);
  29331. xhr.send(this.data);
  29332. } catch (e) {
  29333. // Need to defer since .create() is called directly fhrom the constructor
  29334. // and thus the 'error' event can only be only bound *after* this exception
  29335. // occurs. Therefore, also, we cannot throw here at all.
  29336. setTimeout(function() {
  29337. self.onError(e);
  29338. }, 0);
  29339. return;
  29340. }
  29341. if (global.document) {
  29342. this.index = Request.requestsCount++;
  29343. Request.requests[this.index] = this;
  29344. }
  29345. };
  29346. /**
  29347. * Called upon successful response.
  29348. *
  29349. * @api private
  29350. */
  29351. Request.prototype.onSuccess = function(){
  29352. this.emit('success');
  29353. this.cleanup();
  29354. };
  29355. /**
  29356. * Called if we have data.
  29357. *
  29358. * @api private
  29359. */
  29360. Request.prototype.onData = function(data){
  29361. this.emit('data', data);
  29362. this.onSuccess();
  29363. };
  29364. /**
  29365. * Called upon error.
  29366. *
  29367. * @api private
  29368. */
  29369. Request.prototype.onError = function(err){
  29370. this.emit('error', err);
  29371. this.cleanup(true);
  29372. };
  29373. /**
  29374. * Cleans up house.
  29375. *
  29376. * @api private
  29377. */
  29378. Request.prototype.cleanup = function(fromError){
  29379. if ('undefined' == typeof this.xhr || null === this.xhr) {
  29380. return;
  29381. }
  29382. // xmlhttprequest
  29383. if (this.hasXDR()) {
  29384. this.xhr.onload = this.xhr.onerror = empty;
  29385. } else {
  29386. this.xhr.onreadystatechange = empty;
  29387. }
  29388. if (fromError) {
  29389. try {
  29390. this.xhr.abort();
  29391. } catch(e) {}
  29392. }
  29393. if (global.document) {
  29394. delete Request.requests[this.index];
  29395. }
  29396. this.xhr = null;
  29397. };
  29398. /**
  29399. * Called upon load.
  29400. *
  29401. * @api private
  29402. */
  29403. Request.prototype.onLoad = function(){
  29404. var data;
  29405. try {
  29406. var contentType;
  29407. try {
  29408. contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
  29409. } catch (e) {}
  29410. if (contentType === 'application/octet-stream') {
  29411. data = this.xhr.response;
  29412. } else {
  29413. if (!this.supportsBinary) {
  29414. data = this.xhr.responseText;
  29415. } else {
  29416. data = 'ok';
  29417. }
  29418. }
  29419. } catch (e) {
  29420. this.onError(e);
  29421. }
  29422. if (null != data) {
  29423. this.onData(data);
  29424. }
  29425. };
  29426. /**
  29427. * Check if it has XDomainRequest.
  29428. *
  29429. * @api private
  29430. */
  29431. Request.prototype.hasXDR = function(){
  29432. return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
  29433. };
  29434. /**
  29435. * Aborts the request.
  29436. *
  29437. * @api public
  29438. */
  29439. Request.prototype.abort = function(){
  29440. this.cleanup();
  29441. };
  29442. /**
  29443. * Aborts pending requests when unloading the window. This is needed to prevent
  29444. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  29445. * emitted.
  29446. */
  29447. if (global.document) {
  29448. Request.requestsCount = 0;
  29449. Request.requests = {};
  29450. if (global.attachEvent) {
  29451. global.attachEvent('onunload', unloadHandler);
  29452. } else if (global.addEventListener) {
  29453. global.addEventListener('beforeunload', unloadHandler, false);
  29454. }
  29455. }
  29456. function unloadHandler() {
  29457. for (var i in Request.requests) {
  29458. if (Request.requests.hasOwnProperty(i)) {
  29459. Request.requests[i].abort();
  29460. }
  29461. }
  29462. }
  29463. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  29464. },{"./polling":118,"component-emitter":109,"component-inherit":121,"debug":122,"xmlhttprequest":120}],118:[function(require,module,exports){
  29465. /**
  29466. * Module dependencies.
  29467. */
  29468. var Transport = require('../transport');
  29469. var parseqs = require('parseqs');
  29470. var parser = require('engine.io-parser');
  29471. var inherit = require('component-inherit');
  29472. var debug = require('debug')('engine.io-client:polling');
  29473. /**
  29474. * Module exports.
  29475. */
  29476. module.exports = Polling;
  29477. /**
  29478. * Is XHR2 supported?
  29479. */
  29480. var hasXHR2 = (function() {
  29481. var XMLHttpRequest = require('xmlhttprequest');
  29482. var xhr = new XMLHttpRequest({ xdomain: false });
  29483. return null != xhr.responseType;
  29484. })();
  29485. /**
  29486. * Polling interface.
  29487. *
  29488. * @param {Object} opts
  29489. * @api private
  29490. */
  29491. function Polling(opts){
  29492. var forceBase64 = (opts && opts.forceBase64);
  29493. if (!hasXHR2 || forceBase64) {
  29494. this.supportsBinary = false;
  29495. }
  29496. Transport.call(this, opts);
  29497. }
  29498. /**
  29499. * Inherits from Transport.
  29500. */
  29501. inherit(Polling, Transport);
  29502. /**
  29503. * Transport name.
  29504. */
  29505. Polling.prototype.name = 'polling';
  29506. /**
  29507. * Opens the socket (triggers polling). We write a PING message to determine
  29508. * when the transport is open.
  29509. *
  29510. * @api private
  29511. */
  29512. Polling.prototype.doOpen = function(){
  29513. this.poll();
  29514. };
  29515. /**
  29516. * Pauses polling.
  29517. *
  29518. * @param {Function} callback upon buffers are flushed and transport is paused
  29519. * @api private
  29520. */
  29521. Polling.prototype.pause = function(onPause){
  29522. var pending = 0;
  29523. var self = this;
  29524. this.readyState = 'pausing';
  29525. function pause(){
  29526. debug('paused');
  29527. self.readyState = 'paused';
  29528. onPause();
  29529. }
  29530. if (this.polling || !this.writable) {
  29531. var total = 0;
  29532. if (this.polling) {
  29533. debug('we are currently polling - waiting to pause');
  29534. total++;
  29535. this.once('pollComplete', function(){
  29536. debug('pre-pause polling complete');
  29537. --total || pause();
  29538. });
  29539. }
  29540. if (!this.writable) {
  29541. debug('we are currently writing - waiting to pause');
  29542. total++;
  29543. this.once('drain', function(){
  29544. debug('pre-pause writing complete');
  29545. --total || pause();
  29546. });
  29547. }
  29548. } else {
  29549. pause();
  29550. }
  29551. };
  29552. /**
  29553. * Starts polling cycle.
  29554. *
  29555. * @api public
  29556. */
  29557. Polling.prototype.poll = function(){
  29558. debug('polling');
  29559. this.polling = true;
  29560. this.doPoll();
  29561. this.emit('poll');
  29562. };
  29563. /**
  29564. * Overloads onData to detect payloads.
  29565. *
  29566. * @api private
  29567. */
  29568. Polling.prototype.onData = function(data){
  29569. var self = this;
  29570. debug('polling got data %s', data);
  29571. var callback = function(packet, index, total) {
  29572. // if its the first message we consider the transport open
  29573. if ('opening' == self.readyState) {
  29574. self.onOpen();
  29575. }
  29576. // if its a close packet, we close the ongoing requests
  29577. if ('close' == packet.type) {
  29578. self.onClose();
  29579. return false;
  29580. }
  29581. // otherwise bypass onData and handle the message
  29582. self.onPacket(packet);
  29583. };
  29584. // decode payload
  29585. parser.decodePayload(data, this.socket.binaryType, callback);
  29586. // if an event did not trigger closing
  29587. if ('closed' != this.readyState) {
  29588. // if we got data we're not polling
  29589. this.polling = false;
  29590. this.emit('pollComplete');
  29591. if ('open' == this.readyState) {
  29592. this.poll();
  29593. } else {
  29594. debug('ignoring poll - transport state "%s"', this.readyState);
  29595. }
  29596. }
  29597. };
  29598. /**
  29599. * For polling, send a close packet.
  29600. *
  29601. * @api private
  29602. */
  29603. Polling.prototype.doClose = function(){
  29604. var self = this;
  29605. function close(){
  29606. debug('writing close packet');
  29607. self.write([{ type: 'close' }]);
  29608. }
  29609. if ('open' == this.readyState) {
  29610. debug('transport open - closing');
  29611. close();
  29612. } else {
  29613. // in case we're trying to close while
  29614. // handshaking is in progress (GH-164)
  29615. debug('transport not open - deferring close');
  29616. this.once('open', close);
  29617. }
  29618. };
  29619. /**
  29620. * Writes a packets payload.
  29621. *
  29622. * @param {Array} data packets
  29623. * @param {Function} drain callback
  29624. * @api private
  29625. */
  29626. Polling.prototype.write = function(packets){
  29627. var self = this;
  29628. this.writable = false;
  29629. var callbackfn = function() {
  29630. self.writable = true;
  29631. self.emit('drain');
  29632. };
  29633. var self = this;
  29634. parser.encodePayload(packets, this.supportsBinary, function(data) {
  29635. self.doWrite(data, callbackfn);
  29636. });
  29637. };
  29638. /**
  29639. * Generates uri for connection.
  29640. *
  29641. * @api private
  29642. */
  29643. Polling.prototype.uri = function(){
  29644. var query = this.query || {};
  29645. var schema = this.secure ? 'https' : 'http';
  29646. var port = '';
  29647. // cache busting is forced
  29648. if (false !== this.timestampRequests) {
  29649. query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;
  29650. }
  29651. if (!this.supportsBinary && !query.sid) {
  29652. query.b64 = 1;
  29653. }
  29654. query = parseqs.encode(query);
  29655. // avoid port if default for schema
  29656. if (this.port && (('https' == schema && this.port != 443) ||
  29657. ('http' == schema && this.port != 80))) {
  29658. port = ':' + this.port;
  29659. }
  29660. // prepend ? to query
  29661. if (query.length) {
  29662. query = '?' + query;
  29663. }
  29664. return schema + '://' + this.hostname + port + this.path + query;
  29665. };
  29666. },{"../transport":114,"component-inherit":121,"debug":122,"engine.io-parser":125,"parseqs":137,"xmlhttprequest":120}],119:[function(require,module,exports){
  29667. /**
  29668. * Module dependencies.
  29669. */
  29670. var Transport = require('../transport');
  29671. var parser = require('engine.io-parser');
  29672. var parseqs = require('parseqs');
  29673. var inherit = require('component-inherit');
  29674. var debug = require('debug')('engine.io-client:websocket');
  29675. /**
  29676. * `ws` exposes a WebSocket-compatible interface in
  29677. * Node, or the `WebSocket` or `MozWebSocket` globals
  29678. * in the browser.
  29679. */
  29680. var WebSocket = require('ws');
  29681. /**
  29682. * Module exports.
  29683. */
  29684. module.exports = WS;
  29685. /**
  29686. * WebSocket transport constructor.
  29687. *
  29688. * @api {Object} connection options
  29689. * @api public
  29690. */
  29691. function WS(opts){
  29692. var forceBase64 = (opts && opts.forceBase64);
  29693. if (forceBase64) {
  29694. this.supportsBinary = false;
  29695. }
  29696. Transport.call(this, opts);
  29697. }
  29698. /**
  29699. * Inherits from Transport.
  29700. */
  29701. inherit(WS, Transport);
  29702. /**
  29703. * Transport name.
  29704. *
  29705. * @api public
  29706. */
  29707. WS.prototype.name = 'websocket';
  29708. /*
  29709. * WebSockets support binary
  29710. */
  29711. WS.prototype.supportsBinary = true;
  29712. /**
  29713. * Opens socket.
  29714. *
  29715. * @api private
  29716. */
  29717. WS.prototype.doOpen = function(){
  29718. if (!this.check()) {
  29719. // let probe timeout
  29720. return;
  29721. }
  29722. var self = this;
  29723. var uri = this.uri();
  29724. var protocols = void(0);
  29725. var opts = { agent: this.agent };
  29726. // SSL options for Node.js client
  29727. opts.pfx = this.pfx;
  29728. opts.key = this.key;
  29729. opts.passphrase = this.passphrase;
  29730. opts.cert = this.cert;
  29731. opts.ca = this.ca;
  29732. opts.ciphers = this.ciphers;
  29733. opts.rejectUnauthorized = this.rejectUnauthorized;
  29734. this.ws = new WebSocket(uri, protocols, opts);
  29735. if (this.ws.binaryType === undefined) {
  29736. this.supportsBinary = false;
  29737. }
  29738. this.ws.binaryType = 'arraybuffer';
  29739. this.addEventListeners();
  29740. };
  29741. /**
  29742. * Adds event listeners to the socket
  29743. *
  29744. * @api private
  29745. */
  29746. WS.prototype.addEventListeners = function(){
  29747. var self = this;
  29748. this.ws.onopen = function(){
  29749. self.onOpen();
  29750. };
  29751. this.ws.onclose = function(){
  29752. self.onClose();
  29753. };
  29754. this.ws.onmessage = function(ev){
  29755. self.onData(ev.data);
  29756. };
  29757. this.ws.onerror = function(e){
  29758. self.onError('websocket error', e);
  29759. };
  29760. };
  29761. /**
  29762. * Override `onData` to use a timer on iOS.
  29763. * See: https://gist.github.com/mloughran/2052006
  29764. *
  29765. * @api private
  29766. */
  29767. if ('undefined' != typeof navigator
  29768. && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
  29769. WS.prototype.onData = function(data){
  29770. var self = this;
  29771. setTimeout(function(){
  29772. Transport.prototype.onData.call(self, data);
  29773. }, 0);
  29774. };
  29775. }
  29776. /**
  29777. * Writes data to socket.
  29778. *
  29779. * @param {Array} array of packets.
  29780. * @api private
  29781. */
  29782. WS.prototype.write = function(packets){
  29783. var self = this;
  29784. this.writable = false;
  29785. // encodePacket efficient as it uses WS framing
  29786. // no need for encodePayload
  29787. for (var i = 0, l = packets.length; i < l; i++) {
  29788. parser.encodePacket(packets[i], this.supportsBinary, function(data) {
  29789. //Sometimes the websocket has already been closed but the browser didn't
  29790. //have a chance of informing us about it yet, in that case send will
  29791. //throw an error
  29792. try {
  29793. self.ws.send(data);
  29794. } catch (e){
  29795. debug('websocket closed before onclose event');
  29796. }
  29797. });
  29798. }
  29799. function ondrain() {
  29800. self.writable = true;
  29801. self.emit('drain');
  29802. }
  29803. // fake drain
  29804. // defer to next tick to allow Socket to clear writeBuffer
  29805. setTimeout(ondrain, 0);
  29806. };
  29807. /**
  29808. * Called upon close
  29809. *
  29810. * @api private
  29811. */
  29812. WS.prototype.onClose = function(){
  29813. Transport.prototype.onClose.call(this);
  29814. };
  29815. /**
  29816. * Closes socket.
  29817. *
  29818. * @api private
  29819. */
  29820. WS.prototype.doClose = function(){
  29821. if (typeof this.ws !== 'undefined') {
  29822. this.ws.close();
  29823. }
  29824. };
  29825. /**
  29826. * Generates uri for connection.
  29827. *
  29828. * @api private
  29829. */
  29830. WS.prototype.uri = function(){
  29831. var query = this.query || {};
  29832. var schema = this.secure ? 'wss' : 'ws';
  29833. var port = '';
  29834. // avoid port if default for schema
  29835. if (this.port && (('wss' == schema && this.port != 443)
  29836. || ('ws' == schema && this.port != 80))) {
  29837. port = ':' + this.port;
  29838. }
  29839. // append timestamp to URI
  29840. if (this.timestampRequests) {
  29841. query[this.timestampParam] = +new Date;
  29842. }
  29843. // communicate binary support capabilities
  29844. if (!this.supportsBinary) {
  29845. query.b64 = 1;
  29846. }
  29847. query = parseqs.encode(query);
  29848. // prepend ? to query
  29849. if (query.length) {
  29850. query = '?' + query;
  29851. }
  29852. return schema + '://' + this.hostname + port + this.path + query;
  29853. };
  29854. /**
  29855. * Feature detection for WebSocket.
  29856. *
  29857. * @return {Boolean} whether this transport is available.
  29858. * @api public
  29859. */
  29860. WS.prototype.check = function(){
  29861. return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
  29862. };
  29863. },{"../transport":114,"component-inherit":121,"debug":122,"engine.io-parser":125,"parseqs":137,"ws":139}],120:[function(require,module,exports){
  29864. // browser shim for xmlhttprequest module
  29865. var hasCORS = require('has-cors');
  29866. module.exports = function(opts) {
  29867. var xdomain = opts.xdomain;
  29868. // scheme must be same when usign XDomainRequest
  29869. // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  29870. var xscheme = opts.xscheme;
  29871. // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
  29872. // https://github.com/Automattic/engine.io-client/pull/217
  29873. var enablesXDR = opts.enablesXDR;
  29874. // XMLHttpRequest can be disabled on IE
  29875. try {
  29876. if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  29877. return new XMLHttpRequest();
  29878. }
  29879. } catch (e) { }
  29880. // Use XDomainRequest for IE8 if enablesXDR is true
  29881. // because loading bar keeps flashing when using jsonp-polling
  29882. // https://github.com/yujiosaka/socke.io-ie8-loading-example
  29883. try {
  29884. if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
  29885. return new XDomainRequest();
  29886. }
  29887. } catch (e) { }
  29888. if (!xdomain) {
  29889. try {
  29890. return new ActiveXObject('Microsoft.XMLHTTP');
  29891. } catch(e) { }
  29892. }
  29893. }
  29894. },{"has-cors":134}],121:[function(require,module,exports){
  29895. module.exports = function(a, b){
  29896. var fn = function(){};
  29897. fn.prototype = b.prototype;
  29898. a.prototype = new fn;
  29899. a.prototype.constructor = a;
  29900. };
  29901. },{}],122:[function(require,module,exports){
  29902. /**
  29903. * This is the web browser implementation of `debug()`.
  29904. *
  29905. * Expose `debug()` as the module.
  29906. */
  29907. exports = module.exports = require('./debug');
  29908. exports.log = log;
  29909. exports.formatArgs = formatArgs;
  29910. exports.save = save;
  29911. exports.load = load;
  29912. exports.useColors = useColors;
  29913. /**
  29914. * Colors.
  29915. */
  29916. exports.colors = [
  29917. 'lightseagreen',
  29918. 'forestgreen',
  29919. 'goldenrod',
  29920. 'dodgerblue',
  29921. 'darkorchid',
  29922. 'crimson'
  29923. ];
  29924. /**
  29925. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  29926. * and the Firebug extension (any Firefox version) are known
  29927. * to support "%c" CSS customizations.
  29928. *
  29929. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  29930. */
  29931. function useColors() {
  29932. // is webkit? http://stackoverflow.com/a/16459606/376773
  29933. return ('WebkitAppearance' in document.documentElement.style) ||
  29934. // is firebug? http://stackoverflow.com/a/398120/376773
  29935. (window.console && (console.firebug || (console.exception && console.table))) ||
  29936. // is firefox >= v31?
  29937. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  29938. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  29939. }
  29940. /**
  29941. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  29942. */
  29943. exports.formatters.j = function(v) {
  29944. return JSON.stringify(v);
  29945. };
  29946. /**
  29947. * Colorize log arguments if enabled.
  29948. *
  29949. * @api public
  29950. */
  29951. function formatArgs() {
  29952. var args = arguments;
  29953. var useColors = this.useColors;
  29954. args[0] = (useColors ? '%c' : '')
  29955. + this.namespace
  29956. + (useColors ? ' %c' : ' ')
  29957. + args[0]
  29958. + (useColors ? '%c ' : ' ')
  29959. + '+' + exports.humanize(this.diff);
  29960. if (!useColors) return args;
  29961. var c = 'color: ' + this.color;
  29962. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  29963. // the final "%c" is somewhat tricky, because there could be other
  29964. // arguments passed either before or after the %c, so we need to
  29965. // figure out the correct index to insert the CSS into
  29966. var index = 0;
  29967. var lastC = 0;
  29968. args[0].replace(/%[a-z%]/g, function(match) {
  29969. if ('%%' === match) return;
  29970. index++;
  29971. if ('%c' === match) {
  29972. // we only are interested in the *last* %c
  29973. // (the user may have provided their own)
  29974. lastC = index;
  29975. }
  29976. });
  29977. args.splice(lastC, 0, c);
  29978. return args;
  29979. }
  29980. /**
  29981. * Invokes `console.log()` when available.
  29982. * No-op when `console.log` is not a "function".
  29983. *
  29984. * @api public
  29985. */
  29986. function log() {
  29987. // This hackery is required for IE8,
  29988. // where the `console.log` function doesn't have 'apply'
  29989. return 'object' == typeof console
  29990. && 'function' == typeof console.log
  29991. && Function.prototype.apply.call(console.log, console, arguments);
  29992. }
  29993. /**
  29994. * Save `namespaces`.
  29995. *
  29996. * @param {String} namespaces
  29997. * @api private
  29998. */
  29999. function save(namespaces) {
  30000. try {
  30001. if (null == namespaces) {
  30002. localStorage.removeItem('debug');
  30003. } else {
  30004. localStorage.debug = namespaces;
  30005. }
  30006. } catch(e) {}
  30007. }
  30008. /**
  30009. * Load `namespaces`.
  30010. *
  30011. * @return {String} returns the previously persisted debug modes
  30012. * @api private
  30013. */
  30014. function load() {
  30015. var r;
  30016. try {
  30017. r = localStorage.debug;
  30018. } catch(e) {}
  30019. return r;
  30020. }
  30021. /**
  30022. * Enable namespaces listed in `localStorage.debug` initially.
  30023. */
  30024. exports.enable(load());
  30025. },{"./debug":123}],123:[function(require,module,exports){
  30026. /**
  30027. * This is the common logic for both the Node.js and web browser
  30028. * implementations of `debug()`.
  30029. *
  30030. * Expose `debug()` as the module.
  30031. */
  30032. exports = module.exports = debug;
  30033. exports.coerce = coerce;
  30034. exports.disable = disable;
  30035. exports.enable = enable;
  30036. exports.enabled = enabled;
  30037. exports.humanize = require('ms');
  30038. /**
  30039. * The currently active debug mode names, and names to skip.
  30040. */
  30041. exports.names = [];
  30042. exports.skips = [];
  30043. /**
  30044. * Map of special "%n" handling functions, for the debug "format" argument.
  30045. *
  30046. * Valid key names are a single, lowercased letter, i.e. "n".
  30047. */
  30048. exports.formatters = {};
  30049. /**
  30050. * Previously assigned color.
  30051. */
  30052. var prevColor = 0;
  30053. /**
  30054. * Previous log timestamp.
  30055. */
  30056. var prevTime;
  30057. /**
  30058. * Select a color.
  30059. *
  30060. * @return {Number}
  30061. * @api private
  30062. */
  30063. function selectColor() {
  30064. return exports.colors[prevColor++ % exports.colors.length];
  30065. }
  30066. /**
  30067. * Create a debugger with the given `namespace`.
  30068. *
  30069. * @param {String} namespace
  30070. * @return {Function}
  30071. * @api public
  30072. */
  30073. function debug(namespace) {
  30074. // define the `disabled` version
  30075. function disabled() {
  30076. }
  30077. disabled.enabled = false;
  30078. // define the `enabled` version
  30079. function enabled() {
  30080. var self = enabled;
  30081. // set `diff` timestamp
  30082. var curr = +new Date();
  30083. var ms = curr - (prevTime || curr);
  30084. self.diff = ms;
  30085. self.prev = prevTime;
  30086. self.curr = curr;
  30087. prevTime = curr;
  30088. // add the `color` if not set
  30089. if (null == self.useColors) self.useColors = exports.useColors();
  30090. if (null == self.color && self.useColors) self.color = selectColor();
  30091. var args = Array.prototype.slice.call(arguments);
  30092. args[0] = exports.coerce(args[0]);
  30093. if ('string' !== typeof args[0]) {
  30094. // anything else let's inspect with %o
  30095. args = ['%o'].concat(args);
  30096. }
  30097. // apply any `formatters` transformations
  30098. var index = 0;
  30099. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  30100. // if we encounter an escaped % then don't increase the array index
  30101. if (match === '%%') return match;
  30102. index++;
  30103. var formatter = exports.formatters[format];
  30104. if ('function' === typeof formatter) {
  30105. var val = args[index];
  30106. match = formatter.call(self, val);
  30107. // now we need to remove `args[index]` since it's inlined in the `format`
  30108. args.splice(index, 1);
  30109. index--;
  30110. }
  30111. return match;
  30112. });
  30113. if ('function' === typeof exports.formatArgs) {
  30114. args = exports.formatArgs.apply(self, args);
  30115. }
  30116. var logFn = enabled.log || exports.log || console.log.bind(console);
  30117. logFn.apply(self, args);
  30118. }
  30119. enabled.enabled = true;
  30120. var fn = exports.enabled(namespace) ? enabled : disabled;
  30121. fn.namespace = namespace;
  30122. return fn;
  30123. }
  30124. /**
  30125. * Enables a debug mode by namespaces. This can include modes
  30126. * separated by a colon and wildcards.
  30127. *
  30128. * @param {String} namespaces
  30129. * @api public
  30130. */
  30131. function enable(namespaces) {
  30132. exports.save(namespaces);
  30133. var split = (namespaces || '').split(/[\s,]+/);
  30134. var len = split.length;
  30135. for (var i = 0; i < len; i++) {
  30136. if (!split[i]) continue; // ignore empty strings
  30137. namespaces = split[i].replace(/\*/g, '.*?');
  30138. if (namespaces[0] === '-') {
  30139. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  30140. } else {
  30141. exports.names.push(new RegExp('^' + namespaces + '$'));
  30142. }
  30143. }
  30144. }
  30145. /**
  30146. * Disable debug output.
  30147. *
  30148. * @api public
  30149. */
  30150. function disable() {
  30151. exports.enable('');
  30152. }
  30153. /**
  30154. * Returns true if the given mode name is enabled, false otherwise.
  30155. *
  30156. * @param {String} name
  30157. * @return {Boolean}
  30158. * @api public
  30159. */
  30160. function enabled(name) {
  30161. var i, len;
  30162. for (i = 0, len = exports.skips.length; i < len; i++) {
  30163. if (exports.skips[i].test(name)) {
  30164. return false;
  30165. }
  30166. }
  30167. for (i = 0, len = exports.names.length; i < len; i++) {
  30168. if (exports.names[i].test(name)) {
  30169. return true;
  30170. }
  30171. }
  30172. return false;
  30173. }
  30174. /**
  30175. * Coerce `val`.
  30176. *
  30177. * @param {Mixed} val
  30178. * @return {Mixed}
  30179. * @api private
  30180. */
  30181. function coerce(val) {
  30182. if (val instanceof Error) return val.stack || val.message;
  30183. return val;
  30184. }
  30185. },{"ms":124}],124:[function(require,module,exports){
  30186. /**
  30187. * Helpers.
  30188. */
  30189. var s = 1000;
  30190. var m = s * 60;
  30191. var h = m * 60;
  30192. var d = h * 24;
  30193. var y = d * 365.25;
  30194. /**
  30195. * Parse or format the given `val`.
  30196. *
  30197. * Options:
  30198. *
  30199. * - `long` verbose formatting [false]
  30200. *
  30201. * @param {String|Number} val
  30202. * @param {Object} options
  30203. * @return {String|Number}
  30204. * @api public
  30205. */
  30206. module.exports = function(val, options){
  30207. options = options || {};
  30208. if ('string' == typeof val) return parse(val);
  30209. return options.long
  30210. ? long(val)
  30211. : short(val);
  30212. };
  30213. /**
  30214. * Parse the given `str` and return milliseconds.
  30215. *
  30216. * @param {String} str
  30217. * @return {Number}
  30218. * @api private
  30219. */
  30220. function parse(str) {
  30221. var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
  30222. if (!match) return;
  30223. var n = parseFloat(match[1]);
  30224. var type = (match[2] || 'ms').toLowerCase();
  30225. switch (type) {
  30226. case 'years':
  30227. case 'year':
  30228. case 'y':
  30229. return n * y;
  30230. case 'days':
  30231. case 'day':
  30232. case 'd':
  30233. return n * d;
  30234. case 'hours':
  30235. case 'hour':
  30236. case 'h':
  30237. return n * h;
  30238. case 'minutes':
  30239. case 'minute':
  30240. case 'm':
  30241. return n * m;
  30242. case 'seconds':
  30243. case 'second':
  30244. case 's':
  30245. return n * s;
  30246. case 'ms':
  30247. return n;
  30248. }
  30249. }
  30250. /**
  30251. * Short format for `ms`.
  30252. *
  30253. * @param {Number} ms
  30254. * @return {String}
  30255. * @api private
  30256. */
  30257. function short(ms) {
  30258. if (ms >= d) return Math.round(ms / d) + 'd';
  30259. if (ms >= h) return Math.round(ms / h) + 'h';
  30260. if (ms >= m) return Math.round(ms / m) + 'm';
  30261. if (ms >= s) return Math.round(ms / s) + 's';
  30262. return ms + 'ms';
  30263. }
  30264. /**
  30265. * Long format for `ms`.
  30266. *
  30267. * @param {Number} ms
  30268. * @return {String}
  30269. * @api private
  30270. */
  30271. function long(ms) {
  30272. return plural(ms, d, 'day')
  30273. || plural(ms, h, 'hour')
  30274. || plural(ms, m, 'minute')
  30275. || plural(ms, s, 'second')
  30276. || ms + ' ms';
  30277. }
  30278. /**
  30279. * Pluralization helper.
  30280. */
  30281. function plural(ms, n, name) {
  30282. if (ms < n) return;
  30283. if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  30284. return Math.ceil(ms / n) + ' ' + name + 's';
  30285. }
  30286. },{}],125:[function(require,module,exports){
  30287. (function (global){
  30288. /**
  30289. * Module dependencies.
  30290. */
  30291. var keys = require('./keys');
  30292. var hasBinary = require('has-binary');
  30293. var sliceBuffer = require('arraybuffer.slice');
  30294. var base64encoder = require('base64-arraybuffer');
  30295. var after = require('after');
  30296. var utf8 = require('utf8');
  30297. /**
  30298. * Check if we are running an android browser. That requires us to use
  30299. * ArrayBuffer with polling transports...
  30300. *
  30301. * http://ghinda.net/jpeg-blob-ajax-android/
  30302. */
  30303. var isAndroid = navigator.userAgent.match(/Android/i);
  30304. /**
  30305. * Check if we are running in PhantomJS.
  30306. * Uploading a Blob with PhantomJS does not work correctly, as reported here:
  30307. * https://github.com/ariya/phantomjs/issues/11395
  30308. * @type boolean
  30309. */
  30310. var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
  30311. /**
  30312. * When true, avoids using Blobs to encode payloads.
  30313. * @type boolean
  30314. */
  30315. var dontSendBlobs = isAndroid || isPhantomJS;
  30316. /**
  30317. * Current protocol version.
  30318. */
  30319. exports.protocol = 3;
  30320. /**
  30321. * Packet types.
  30322. */
  30323. var packets = exports.packets = {
  30324. open: 0 // non-ws
  30325. , close: 1 // non-ws
  30326. , ping: 2
  30327. , pong: 3
  30328. , message: 4
  30329. , upgrade: 5
  30330. , noop: 6
  30331. };
  30332. var packetslist = keys(packets);
  30333. /**
  30334. * Premade error packet.
  30335. */
  30336. var err = { type: 'error', data: 'parser error' };
  30337. /**
  30338. * Create a blob api even for blob builder when vendor prefixes exist
  30339. */
  30340. var Blob = require('blob');
  30341. /**
  30342. * Encodes a packet.
  30343. *
  30344. * <packet type id> [ <data> ]
  30345. *
  30346. * Example:
  30347. *
  30348. * 5hello world
  30349. * 3
  30350. * 4
  30351. *
  30352. * Binary is encoded in an identical principle
  30353. *
  30354. * @api private
  30355. */
  30356. exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
  30357. if ('function' == typeof supportsBinary) {
  30358. callback = supportsBinary;
  30359. supportsBinary = false;
  30360. }
  30361. if ('function' == typeof utf8encode) {
  30362. callback = utf8encode;
  30363. utf8encode = null;
  30364. }
  30365. var data = (packet.data === undefined)
  30366. ? undefined
  30367. : packet.data.buffer || packet.data;
  30368. if (global.ArrayBuffer && data instanceof ArrayBuffer) {
  30369. return encodeArrayBuffer(packet, supportsBinary, callback);
  30370. } else if (Blob && data instanceof global.Blob) {
  30371. return encodeBlob(packet, supportsBinary, callback);
  30372. }
  30373. // might be an object with { base64: true, data: dataAsBase64String }
  30374. if (data && data.base64) {
  30375. return encodeBase64Object(packet, callback);
  30376. }
  30377. // Sending data as a utf-8 string
  30378. var encoded = packets[packet.type];
  30379. // data fragment is optional
  30380. if (undefined !== packet.data) {
  30381. encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
  30382. }
  30383. return callback('' + encoded);
  30384. };
  30385. function encodeBase64Object(packet, callback) {
  30386. // packet data is an object { base64: true, data: dataAsBase64String }
  30387. var message = 'b' + exports.packets[packet.type] + packet.data.data;
  30388. return callback(message);
  30389. }
  30390. /**
  30391. * Encode packet helpers for binary types
  30392. */
  30393. function encodeArrayBuffer(packet, supportsBinary, callback) {
  30394. if (!supportsBinary) {
  30395. return exports.encodeBase64Packet(packet, callback);
  30396. }
  30397. var data = packet.data;
  30398. var contentArray = new Uint8Array(data);
  30399. var resultBuffer = new Uint8Array(1 + data.byteLength);
  30400. resultBuffer[0] = packets[packet.type];
  30401. for (var i = 0; i < contentArray.length; i++) {
  30402. resultBuffer[i+1] = contentArray[i];
  30403. }
  30404. return callback(resultBuffer.buffer);
  30405. }
  30406. function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  30407. if (!supportsBinary) {
  30408. return exports.encodeBase64Packet(packet, callback);
  30409. }
  30410. var fr = new FileReader();
  30411. fr.onload = function() {
  30412. packet.data = fr.result;
  30413. exports.encodePacket(packet, supportsBinary, true, callback);
  30414. };
  30415. return fr.readAsArrayBuffer(packet.data);
  30416. }
  30417. function encodeBlob(packet, supportsBinary, callback) {
  30418. if (!supportsBinary) {
  30419. return exports.encodeBase64Packet(packet, callback);
  30420. }
  30421. if (dontSendBlobs) {
  30422. return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  30423. }
  30424. var length = new Uint8Array(1);
  30425. length[0] = packets[packet.type];
  30426. var blob = new Blob([length.buffer, packet.data]);
  30427. return callback(blob);
  30428. }
  30429. /**
  30430. * Encodes a packet with binary data in a base64 string
  30431. *
  30432. * @param {Object} packet, has `type` and `data`
  30433. * @return {String} base64 encoded message
  30434. */
  30435. exports.encodeBase64Packet = function(packet, callback) {
  30436. var message = 'b' + exports.packets[packet.type];
  30437. if (Blob && packet.data instanceof Blob) {
  30438. var fr = new FileReader();
  30439. fr.onload = function() {
  30440. var b64 = fr.result.split(',')[1];
  30441. callback(message + b64);
  30442. };
  30443. return fr.readAsDataURL(packet.data);
  30444. }
  30445. var b64data;
  30446. try {
  30447. b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  30448. } catch (e) {
  30449. // iPhone Safari doesn't let you apply with typed arrays
  30450. var typed = new Uint8Array(packet.data);
  30451. var basic = new Array(typed.length);
  30452. for (var i = 0; i < typed.length; i++) {
  30453. basic[i] = typed[i];
  30454. }
  30455. b64data = String.fromCharCode.apply(null, basic);
  30456. }
  30457. message += global.btoa(b64data);
  30458. return callback(message);
  30459. };
  30460. /**
  30461. * Decodes a packet. Changes format to Blob if requested.
  30462. *
  30463. * @return {Object} with `type` and `data` (if any)
  30464. * @api private
  30465. */
  30466. exports.decodePacket = function (data, binaryType, utf8decode) {
  30467. // String data
  30468. if (typeof data == 'string' || data === undefined) {
  30469. if (data.charAt(0) == 'b') {
  30470. return exports.decodeBase64Packet(data.substr(1), binaryType);
  30471. }
  30472. if (utf8decode) {
  30473. try {
  30474. data = utf8.decode(data);
  30475. } catch (e) {
  30476. return err;
  30477. }
  30478. }
  30479. var type = data.charAt(0);
  30480. if (Number(type) != type || !packetslist[type]) {
  30481. return err;
  30482. }
  30483. if (data.length > 1) {
  30484. return { type: packetslist[type], data: data.substring(1) };
  30485. } else {
  30486. return { type: packetslist[type] };
  30487. }
  30488. }
  30489. var asArray = new Uint8Array(data);
  30490. var type = asArray[0];
  30491. var rest = sliceBuffer(data, 1);
  30492. if (Blob && binaryType === 'blob') {
  30493. rest = new Blob([rest]);
  30494. }
  30495. return { type: packetslist[type], data: rest };
  30496. };
  30497. /**
  30498. * Decodes a packet encoded in a base64 string
  30499. *
  30500. * @param {String} base64 encoded message
  30501. * @return {Object} with `type` and `data` (if any)
  30502. */
  30503. exports.decodeBase64Packet = function(msg, binaryType) {
  30504. var type = packetslist[msg.charAt(0)];
  30505. if (!global.ArrayBuffer) {
  30506. return { type: type, data: { base64: true, data: msg.substr(1) } };
  30507. }
  30508. var data = base64encoder.decode(msg.substr(1));
  30509. if (binaryType === 'blob' && Blob) {
  30510. data = new Blob([data]);
  30511. }
  30512. return { type: type, data: data };
  30513. };
  30514. /**
  30515. * Encodes multiple messages (payload).
  30516. *
  30517. * <length>:data
  30518. *
  30519. * Example:
  30520. *
  30521. * 11:hello world2:hi
  30522. *
  30523. * If any contents are binary, they will be encoded as base64 strings. Base64
  30524. * encoded strings are marked with a b before the length specifier
  30525. *
  30526. * @param {Array} packets
  30527. * @api private
  30528. */
  30529. exports.encodePayload = function (packets, supportsBinary, callback) {
  30530. if (typeof supportsBinary == 'function') {
  30531. callback = supportsBinary;
  30532. supportsBinary = null;
  30533. }
  30534. var isBinary = hasBinary(packets);
  30535. if (supportsBinary && isBinary) {
  30536. if (Blob && !dontSendBlobs) {
  30537. return exports.encodePayloadAsBlob(packets, callback);
  30538. }
  30539. return exports.encodePayloadAsArrayBuffer(packets, callback);
  30540. }
  30541. if (!packets.length) {
  30542. return callback('0:');
  30543. }
  30544. function setLengthHeader(message) {
  30545. return message.length + ':' + message;
  30546. }
  30547. function encodeOne(packet, doneCallback) {
  30548. exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
  30549. doneCallback(null, setLengthHeader(message));
  30550. });
  30551. }
  30552. map(packets, encodeOne, function(err, results) {
  30553. return callback(results.join(''));
  30554. });
  30555. };
  30556. /**
  30557. * Async array map using after
  30558. */
  30559. function map(ary, each, done) {
  30560. var result = new Array(ary.length);
  30561. var next = after(ary.length, done);
  30562. var eachWithIndex = function(i, el, cb) {
  30563. each(el, function(error, msg) {
  30564. result[i] = msg;
  30565. cb(error, result);
  30566. });
  30567. };
  30568. for (var i = 0; i < ary.length; i++) {
  30569. eachWithIndex(i, ary[i], next);
  30570. }
  30571. }
  30572. /*
  30573. * Decodes data when a payload is maybe expected. Possible binary contents are
  30574. * decoded from their base64 representation
  30575. *
  30576. * @param {String} data, callback method
  30577. * @api public
  30578. */
  30579. exports.decodePayload = function (data, binaryType, callback) {
  30580. if (typeof data != 'string') {
  30581. return exports.decodePayloadAsBinary(data, binaryType, callback);
  30582. }
  30583. if (typeof binaryType === 'function') {
  30584. callback = binaryType;
  30585. binaryType = null;
  30586. }
  30587. var packet;
  30588. if (data == '') {
  30589. // parser error - ignoring payload
  30590. return callback(err, 0, 1);
  30591. }
  30592. var length = ''
  30593. , n, msg;
  30594. for (var i = 0, l = data.length; i < l; i++) {
  30595. var chr = data.charAt(i);
  30596. if (':' != chr) {
  30597. length += chr;
  30598. } else {
  30599. if ('' == length || (length != (n = Number(length)))) {
  30600. // parser error - ignoring payload
  30601. return callback(err, 0, 1);
  30602. }
  30603. msg = data.substr(i + 1, n);
  30604. if (length != msg.length) {
  30605. // parser error - ignoring payload
  30606. return callback(err, 0, 1);
  30607. }
  30608. if (msg.length) {
  30609. packet = exports.decodePacket(msg, binaryType, true);
  30610. if (err.type == packet.type && err.data == packet.data) {
  30611. // parser error in individual packet - ignoring payload
  30612. return callback(err, 0, 1);
  30613. }
  30614. var ret = callback(packet, i + n, l);
  30615. if (false === ret) return;
  30616. }
  30617. // advance cursor
  30618. i += n;
  30619. length = '';
  30620. }
  30621. }
  30622. if (length != '') {
  30623. // parser error - ignoring payload
  30624. return callback(err, 0, 1);
  30625. }
  30626. };
  30627. /**
  30628. * Encodes multiple messages (payload) as binary.
  30629. *
  30630. * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
  30631. * 255><data>
  30632. *
  30633. * Example:
  30634. * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
  30635. *
  30636. * @param {Array} packets
  30637. * @return {ArrayBuffer} encoded payload
  30638. * @api private
  30639. */
  30640. exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  30641. if (!packets.length) {
  30642. return callback(new ArrayBuffer(0));
  30643. }
  30644. function encodeOne(packet, doneCallback) {
  30645. exports.encodePacket(packet, true, true, function(data) {
  30646. return doneCallback(null, data);
  30647. });
  30648. }
  30649. map(packets, encodeOne, function(err, encodedPackets) {
  30650. var totalLength = encodedPackets.reduce(function(acc, p) {
  30651. var len;
  30652. if (typeof p === 'string'){
  30653. len = p.length;
  30654. } else {
  30655. len = p.byteLength;
  30656. }
  30657. return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
  30658. }, 0);
  30659. var resultArray = new Uint8Array(totalLength);
  30660. var bufferIndex = 0;
  30661. encodedPackets.forEach(function(p) {
  30662. var isString = typeof p === 'string';
  30663. var ab = p;
  30664. if (isString) {
  30665. var view = new Uint8Array(p.length);
  30666. for (var i = 0; i < p.length; i++) {
  30667. view[i] = p.charCodeAt(i);
  30668. }
  30669. ab = view.buffer;
  30670. }
  30671. if (isString) { // not true binary
  30672. resultArray[bufferIndex++] = 0;
  30673. } else { // true binary
  30674. resultArray[bufferIndex++] = 1;
  30675. }
  30676. var lenStr = ab.byteLength.toString();
  30677. for (var i = 0; i < lenStr.length; i++) {
  30678. resultArray[bufferIndex++] = parseInt(lenStr[i]);
  30679. }
  30680. resultArray[bufferIndex++] = 255;
  30681. var view = new Uint8Array(ab);
  30682. for (var i = 0; i < view.length; i++) {
  30683. resultArray[bufferIndex++] = view[i];
  30684. }
  30685. });
  30686. return callback(resultArray.buffer);
  30687. });
  30688. };
  30689. /**
  30690. * Encode as Blob
  30691. */
  30692. exports.encodePayloadAsBlob = function(packets, callback) {
  30693. function encodeOne(packet, doneCallback) {
  30694. exports.encodePacket(packet, true, true, function(encoded) {
  30695. var binaryIdentifier = new Uint8Array(1);
  30696. binaryIdentifier[0] = 1;
  30697. if (typeof encoded === 'string') {
  30698. var view = new Uint8Array(encoded.length);
  30699. for (var i = 0; i < encoded.length; i++) {
  30700. view[i] = encoded.charCodeAt(i);
  30701. }
  30702. encoded = view.buffer;
  30703. binaryIdentifier[0] = 0;
  30704. }
  30705. var len = (encoded instanceof ArrayBuffer)
  30706. ? encoded.byteLength
  30707. : encoded.size;
  30708. var lenStr = len.toString();
  30709. var lengthAry = new Uint8Array(lenStr.length + 1);
  30710. for (var i = 0; i < lenStr.length; i++) {
  30711. lengthAry[i] = parseInt(lenStr[i]);
  30712. }
  30713. lengthAry[lenStr.length] = 255;
  30714. if (Blob) {
  30715. var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
  30716. doneCallback(null, blob);
  30717. }
  30718. });
  30719. }
  30720. map(packets, encodeOne, function(err, results) {
  30721. return callback(new Blob(results));
  30722. });
  30723. };
  30724. /*
  30725. * Decodes data when a payload is maybe expected. Strings are decoded by
  30726. * interpreting each byte as a key code for entries marked to start with 0. See
  30727. * description of encodePayloadAsBinary
  30728. *
  30729. * @param {ArrayBuffer} data, callback method
  30730. * @api public
  30731. */
  30732. exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  30733. if (typeof binaryType === 'function') {
  30734. callback = binaryType;
  30735. binaryType = null;
  30736. }
  30737. var bufferTail = data;
  30738. var buffers = [];
  30739. var numberTooLong = false;
  30740. while (bufferTail.byteLength > 0) {
  30741. var tailArray = new Uint8Array(bufferTail);
  30742. var isString = tailArray[0] === 0;
  30743. var msgLength = '';
  30744. for (var i = 1; ; i++) {
  30745. if (tailArray[i] == 255) break;
  30746. if (msgLength.length > 310) {
  30747. numberTooLong = true;
  30748. break;
  30749. }
  30750. msgLength += tailArray[i];
  30751. }
  30752. if(numberTooLong) return callback(err, 0, 1);
  30753. bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
  30754. msgLength = parseInt(msgLength);
  30755. var msg = sliceBuffer(bufferTail, 0, msgLength);
  30756. if (isString) {
  30757. try {
  30758. msg = String.fromCharCode.apply(null, new Uint8Array(msg));
  30759. } catch (e) {
  30760. // iPhone Safari doesn't let you apply to typed arrays
  30761. var typed = new Uint8Array(msg);
  30762. msg = '';
  30763. for (var i = 0; i < typed.length; i++) {
  30764. msg += String.fromCharCode(typed[i]);
  30765. }
  30766. }
  30767. }
  30768. buffers.push(msg);
  30769. bufferTail = sliceBuffer(bufferTail, msgLength);
  30770. }
  30771. var total = buffers.length;
  30772. buffers.forEach(function(buffer, i) {
  30773. callback(exports.decodePacket(buffer, binaryType, true), i, total);
  30774. });
  30775. };
  30776. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  30777. },{"./keys":126,"after":127,"arraybuffer.slice":128,"base64-arraybuffer":129,"blob":130,"has-binary":131,"utf8":133}],126:[function(require,module,exports){
  30778. /**
  30779. * Gets the keys for an object.
  30780. *
  30781. * @return {Array} keys
  30782. * @api private
  30783. */
  30784. module.exports = Object.keys || function keys (obj){
  30785. var arr = [];
  30786. var has = Object.prototype.hasOwnProperty;
  30787. for (var i in obj) {
  30788. if (has.call(obj, i)) {
  30789. arr.push(i);
  30790. }
  30791. }
  30792. return arr;
  30793. };
  30794. },{}],127:[function(require,module,exports){
  30795. module.exports = after
  30796. function after(count, callback, err_cb) {
  30797. var bail = false
  30798. err_cb = err_cb || noop
  30799. proxy.count = count
  30800. return (count === 0) ? callback() : proxy
  30801. function proxy(err, result) {
  30802. if (proxy.count <= 0) {
  30803. throw new Error('after called too many times')
  30804. }
  30805. --proxy.count
  30806. // after first error, rest are passed to err_cb
  30807. if (err) {
  30808. bail = true
  30809. callback(err)
  30810. // future error callbacks will go to error handler
  30811. callback = err_cb
  30812. } else if (proxy.count === 0 && !bail) {
  30813. callback(null, result)
  30814. }
  30815. }
  30816. }
  30817. function noop() {}
  30818. },{}],128:[function(require,module,exports){
  30819. /**
  30820. * An abstraction for slicing an arraybuffer even when
  30821. * ArrayBuffer.prototype.slice is not supported
  30822. *
  30823. * @api public
  30824. */
  30825. module.exports = function(arraybuffer, start, end) {
  30826. var bytes = arraybuffer.byteLength;
  30827. start = start || 0;
  30828. end = end || bytes;
  30829. if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
  30830. if (start < 0) { start += bytes; }
  30831. if (end < 0) { end += bytes; }
  30832. if (end > bytes) { end = bytes; }
  30833. if (start >= bytes || start >= end || bytes === 0) {
  30834. return new ArrayBuffer(0);
  30835. }
  30836. var abv = new Uint8Array(arraybuffer);
  30837. var result = new Uint8Array(end - start);
  30838. for (var i = start, ii = 0; i < end; i++, ii++) {
  30839. result[ii] = abv[i];
  30840. }
  30841. return result.buffer;
  30842. };
  30843. },{}],129:[function(require,module,exports){
  30844. /*
  30845. * base64-arraybuffer
  30846. * https://github.com/niklasvh/base64-arraybuffer
  30847. *
  30848. * Copyright (c) 2012 Niklas von Hertzen
  30849. * Licensed under the MIT license.
  30850. */
  30851. (function(chars){
  30852. "use strict";
  30853. exports.encode = function(arraybuffer) {
  30854. var bytes = new Uint8Array(arraybuffer),
  30855. i, len = bytes.length, base64 = "";
  30856. for (i = 0; i < len; i+=3) {
  30857. base64 += chars[bytes[i] >> 2];
  30858. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  30859. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  30860. base64 += chars[bytes[i + 2] & 63];
  30861. }
  30862. if ((len % 3) === 2) {
  30863. base64 = base64.substring(0, base64.length - 1) + "=";
  30864. } else if (len % 3 === 1) {
  30865. base64 = base64.substring(0, base64.length - 2) + "==";
  30866. }
  30867. return base64;
  30868. };
  30869. exports.decode = function(base64) {
  30870. var bufferLength = base64.length * 0.75,
  30871. len = base64.length, i, p = 0,
  30872. encoded1, encoded2, encoded3, encoded4;
  30873. if (base64[base64.length - 1] === "=") {
  30874. bufferLength--;
  30875. if (base64[base64.length - 2] === "=") {
  30876. bufferLength--;
  30877. }
  30878. }
  30879. var arraybuffer = new ArrayBuffer(bufferLength),
  30880. bytes = new Uint8Array(arraybuffer);
  30881. for (i = 0; i < len; i+=4) {
  30882. encoded1 = chars.indexOf(base64[i]);
  30883. encoded2 = chars.indexOf(base64[i+1]);
  30884. encoded3 = chars.indexOf(base64[i+2]);
  30885. encoded4 = chars.indexOf(base64[i+3]);
  30886. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  30887. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  30888. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  30889. }
  30890. return arraybuffer;
  30891. };
  30892. })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  30893. },{}],130:[function(require,module,exports){
  30894. (function (global){
  30895. /**
  30896. * Create a blob builder even when vendor prefixes exist
  30897. */
  30898. var BlobBuilder = global.BlobBuilder
  30899. || global.WebKitBlobBuilder
  30900. || global.MSBlobBuilder
  30901. || global.MozBlobBuilder;
  30902. /**
  30903. * Check if Blob constructor is supported
  30904. */
  30905. var blobSupported = (function() {
  30906. try {
  30907. var b = new Blob(['hi']);
  30908. return b.size == 2;
  30909. } catch(e) {
  30910. return false;
  30911. }
  30912. })();
  30913. /**
  30914. * Check if BlobBuilder is supported
  30915. */
  30916. var blobBuilderSupported = BlobBuilder
  30917. && BlobBuilder.prototype.append
  30918. && BlobBuilder.prototype.getBlob;
  30919. function BlobBuilderConstructor(ary, options) {
  30920. options = options || {};
  30921. var bb = new BlobBuilder();
  30922. for (var i = 0; i < ary.length; i++) {
  30923. bb.append(ary[i]);
  30924. }
  30925. return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
  30926. };
  30927. module.exports = (function() {
  30928. if (blobSupported) {
  30929. return global.Blob;
  30930. } else if (blobBuilderSupported) {
  30931. return BlobBuilderConstructor;
  30932. } else {
  30933. return undefined;
  30934. }
  30935. })();
  30936. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  30937. },{}],131:[function(require,module,exports){
  30938. (function (global){
  30939. /*
  30940. * Module requirements.
  30941. */
  30942. var isArray = require('isarray');
  30943. /**
  30944. * Module exports.
  30945. */
  30946. module.exports = hasBinary;
  30947. /**
  30948. * Checks for binary data.
  30949. *
  30950. * Right now only Buffer and ArrayBuffer are supported..
  30951. *
  30952. * @param {Object} anything
  30953. * @api public
  30954. */
  30955. function hasBinary(data) {
  30956. function _hasBinary(obj) {
  30957. if (!obj) return false;
  30958. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  30959. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  30960. (global.Blob && obj instanceof Blob) ||
  30961. (global.File && obj instanceof File)
  30962. ) {
  30963. return true;
  30964. }
  30965. if (isArray(obj)) {
  30966. for (var i = 0; i < obj.length; i++) {
  30967. if (_hasBinary(obj[i])) {
  30968. return true;
  30969. }
  30970. }
  30971. } else if (obj && 'object' == typeof obj) {
  30972. if (obj.toJSON) {
  30973. obj = obj.toJSON();
  30974. }
  30975. for (var key in obj) {
  30976. if (obj.hasOwnProperty(key) && _hasBinary(obj[key])) {
  30977. return true;
  30978. }
  30979. }
  30980. }
  30981. return false;
  30982. }
  30983. return _hasBinary(data);
  30984. }
  30985. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  30986. },{"isarray":132}],132:[function(require,module,exports){
  30987. module.exports = Array.isArray || function (arr) {
  30988. return Object.prototype.toString.call(arr) == '[object Array]';
  30989. };
  30990. },{}],133:[function(require,module,exports){
  30991. (function (global){
  30992. /*! http://mths.be/utf8js v2.0.0 by @mathias */
  30993. ;(function(root) {
  30994. // Detect free variables `exports`
  30995. var freeExports = typeof exports == 'object' && exports;
  30996. // Detect free variable `module`
  30997. var freeModule = typeof module == 'object' && module &&
  30998. module.exports == freeExports && module;
  30999. // Detect free variable `global`, from Node.js or Browserified code,
  31000. // and use it as `root`
  31001. var freeGlobal = typeof global == 'object' && global;
  31002. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  31003. root = freeGlobal;
  31004. }
  31005. /*--------------------------------------------------------------------------*/
  31006. var stringFromCharCode = String.fromCharCode;
  31007. // Taken from http://mths.be/punycode
  31008. function ucs2decode(string) {
  31009. var output = [];
  31010. var counter = 0;
  31011. var length = string.length;
  31012. var value;
  31013. var extra;
  31014. while (counter < length) {
  31015. value = string.charCodeAt(counter++);
  31016. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  31017. // high surrogate, and there is a next character
  31018. extra = string.charCodeAt(counter++);
  31019. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  31020. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  31021. } else {
  31022. // unmatched surrogate; only append this code unit, in case the next
  31023. // code unit is the high surrogate of a surrogate pair
  31024. output.push(value);
  31025. counter--;
  31026. }
  31027. } else {
  31028. output.push(value);
  31029. }
  31030. }
  31031. return output;
  31032. }
  31033. // Taken from http://mths.be/punycode
  31034. function ucs2encode(array) {
  31035. var length = array.length;
  31036. var index = -1;
  31037. var value;
  31038. var output = '';
  31039. while (++index < length) {
  31040. value = array[index];
  31041. if (value > 0xFFFF) {
  31042. value -= 0x10000;
  31043. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  31044. value = 0xDC00 | value & 0x3FF;
  31045. }
  31046. output += stringFromCharCode(value);
  31047. }
  31048. return output;
  31049. }
  31050. /*--------------------------------------------------------------------------*/
  31051. function createByte(codePoint, shift) {
  31052. return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
  31053. }
  31054. function encodeCodePoint(codePoint) {
  31055. if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
  31056. return stringFromCharCode(codePoint);
  31057. }
  31058. var symbol = '';
  31059. if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
  31060. symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
  31061. }
  31062. else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
  31063. symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
  31064. symbol += createByte(codePoint, 6);
  31065. }
  31066. else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
  31067. symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
  31068. symbol += createByte(codePoint, 12);
  31069. symbol += createByte(codePoint, 6);
  31070. }
  31071. symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
  31072. return symbol;
  31073. }
  31074. function utf8encode(string) {
  31075. var codePoints = ucs2decode(string);
  31076. // console.log(JSON.stringify(codePoints.map(function(x) {
  31077. // return 'U+' + x.toString(16).toUpperCase();
  31078. // })));
  31079. var length = codePoints.length;
  31080. var index = -1;
  31081. var codePoint;
  31082. var byteString = '';
  31083. while (++index < length) {
  31084. codePoint = codePoints[index];
  31085. byteString += encodeCodePoint(codePoint);
  31086. }
  31087. return byteString;
  31088. }
  31089. /*--------------------------------------------------------------------------*/
  31090. function readContinuationByte() {
  31091. if (byteIndex >= byteCount) {
  31092. throw Error('Invalid byte index');
  31093. }
  31094. var continuationByte = byteArray[byteIndex] & 0xFF;
  31095. byteIndex++;
  31096. if ((continuationByte & 0xC0) == 0x80) {
  31097. return continuationByte & 0x3F;
  31098. }
  31099. // If we end up here, it’s not a continuation byte
  31100. throw Error('Invalid continuation byte');
  31101. }
  31102. function decodeSymbol() {
  31103. var byte1;
  31104. var byte2;
  31105. var byte3;
  31106. var byte4;
  31107. var codePoint;
  31108. if (byteIndex > byteCount) {
  31109. throw Error('Invalid byte index');
  31110. }
  31111. if (byteIndex == byteCount) {
  31112. return false;
  31113. }
  31114. // Read first byte
  31115. byte1 = byteArray[byteIndex] & 0xFF;
  31116. byteIndex++;
  31117. // 1-byte sequence (no continuation bytes)
  31118. if ((byte1 & 0x80) == 0) {
  31119. return byte1;
  31120. }
  31121. // 2-byte sequence
  31122. if ((byte1 & 0xE0) == 0xC0) {
  31123. var byte2 = readContinuationByte();
  31124. codePoint = ((byte1 & 0x1F) << 6) | byte2;
  31125. if (codePoint >= 0x80) {
  31126. return codePoint;
  31127. } else {
  31128. throw Error('Invalid continuation byte');
  31129. }
  31130. }
  31131. // 3-byte sequence (may include unpaired surrogates)
  31132. if ((byte1 & 0xF0) == 0xE0) {
  31133. byte2 = readContinuationByte();
  31134. byte3 = readContinuationByte();
  31135. codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
  31136. if (codePoint >= 0x0800) {
  31137. return codePoint;
  31138. } else {
  31139. throw Error('Invalid continuation byte');
  31140. }
  31141. }
  31142. // 4-byte sequence
  31143. if ((byte1 & 0xF8) == 0xF0) {
  31144. byte2 = readContinuationByte();
  31145. byte3 = readContinuationByte();
  31146. byte4 = readContinuationByte();
  31147. codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
  31148. (byte3 << 0x06) | byte4;
  31149. if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
  31150. return codePoint;
  31151. }
  31152. }
  31153. throw Error('Invalid UTF-8 detected');
  31154. }
  31155. var byteArray;
  31156. var byteCount;
  31157. var byteIndex;
  31158. function utf8decode(byteString) {
  31159. byteArray = ucs2decode(byteString);
  31160. byteCount = byteArray.length;
  31161. byteIndex = 0;
  31162. var codePoints = [];
  31163. var tmp;
  31164. while ((tmp = decodeSymbol()) !== false) {
  31165. codePoints.push(tmp);
  31166. }
  31167. return ucs2encode(codePoints);
  31168. }
  31169. /*--------------------------------------------------------------------------*/
  31170. var utf8 = {
  31171. 'version': '2.0.0',
  31172. 'encode': utf8encode,
  31173. 'decode': utf8decode
  31174. };
  31175. // Some AMD build optimizers, like r.js, check for specific condition patterns
  31176. // like the following:
  31177. if (
  31178. typeof define == 'function' &&
  31179. typeof define.amd == 'object' &&
  31180. define.amd
  31181. ) {
  31182. define(function() {
  31183. return utf8;
  31184. });
  31185. } else if (freeExports && !freeExports.nodeType) {
  31186. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  31187. freeModule.exports = utf8;
  31188. } else { // in Narwhal or RingoJS v0.7.0-
  31189. var object = {};
  31190. var hasOwnProperty = object.hasOwnProperty;
  31191. for (var key in utf8) {
  31192. hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
  31193. }
  31194. }
  31195. } else { // in Rhino or a web browser
  31196. root.utf8 = utf8;
  31197. }
  31198. }(this));
  31199. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31200. },{}],134:[function(require,module,exports){
  31201. /**
  31202. * Module dependencies.
  31203. */
  31204. var global = require('global');
  31205. /**
  31206. * Module exports.
  31207. *
  31208. * Logic borrowed from Modernizr:
  31209. *
  31210. * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
  31211. */
  31212. try {
  31213. module.exports = 'XMLHttpRequest' in global &&
  31214. 'withCredentials' in new global.XMLHttpRequest();
  31215. } catch (err) {
  31216. // if XMLHttp support is disabled in IE then it will throw
  31217. // when trying to create
  31218. module.exports = false;
  31219. }
  31220. },{"global":135}],135:[function(require,module,exports){
  31221. /**
  31222. * Returns `this`. Execute this without a "context" (i.e. without it being
  31223. * attached to an object of the left-hand side), and `this` points to the
  31224. * "global" scope of the current JS execution.
  31225. */
  31226. module.exports = (function () { return this; })();
  31227. },{}],136:[function(require,module,exports){
  31228. (function (global){
  31229. /**
  31230. * JSON parse.
  31231. *
  31232. * @see Based on jQuery#parseJSON (MIT) and JSON2
  31233. * @api private
  31234. */
  31235. var rvalidchars = /^[\],:{}\s]*$/;
  31236. var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  31237. var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  31238. var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
  31239. var rtrimLeft = /^\s+/;
  31240. var rtrimRight = /\s+$/;
  31241. module.exports = function parsejson(data) {
  31242. if ('string' != typeof data || !data) {
  31243. return null;
  31244. }
  31245. data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
  31246. // Attempt to parse using the native JSON parser first
  31247. if (global.JSON && JSON.parse) {
  31248. return JSON.parse(data);
  31249. }
  31250. if (rvalidchars.test(data.replace(rvalidescape, '@')
  31251. .replace(rvalidtokens, ']')
  31252. .replace(rvalidbraces, ''))) {
  31253. return (new Function('return ' + data))();
  31254. }
  31255. };
  31256. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31257. },{}],137:[function(require,module,exports){
  31258. /**
  31259. * Compiles a querystring
  31260. * Returns string representation of the object
  31261. *
  31262. * @param {Object}
  31263. * @api private
  31264. */
  31265. exports.encode = function (obj) {
  31266. var str = '';
  31267. for (var i in obj) {
  31268. if (obj.hasOwnProperty(i)) {
  31269. if (str.length) str += '&';
  31270. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  31271. }
  31272. }
  31273. return str;
  31274. };
  31275. /**
  31276. * Parses a simple querystring into an object
  31277. *
  31278. * @param {String} qs
  31279. * @api private
  31280. */
  31281. exports.decode = function(qs){
  31282. var qry = {};
  31283. var pairs = qs.split('&');
  31284. for (var i = 0, l = pairs.length; i < l; i++) {
  31285. var pair = pairs[i].split('=');
  31286. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  31287. }
  31288. return qry;
  31289. };
  31290. },{}],138:[function(require,module,exports){
  31291. /**
  31292. * Parses an URI
  31293. *
  31294. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  31295. * @api private
  31296. */
  31297. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  31298. var parts = [
  31299. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  31300. ];
  31301. module.exports = function parseuri(str) {
  31302. var src = str,
  31303. b = str.indexOf('['),
  31304. e = str.indexOf(']');
  31305. if (b != -1 && e != -1) {
  31306. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  31307. }
  31308. var m = re.exec(str || ''),
  31309. uri = {},
  31310. i = 14;
  31311. while (i--) {
  31312. uri[parts[i]] = m[i] || '';
  31313. }
  31314. if (b != -1 && e != -1) {
  31315. uri.source = src;
  31316. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  31317. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  31318. uri.ipv6uri = true;
  31319. }
  31320. return uri;
  31321. };
  31322. },{}],139:[function(require,module,exports){
  31323. /**
  31324. * Module dependencies.
  31325. */
  31326. var global = (function() { return this; })();
  31327. /**
  31328. * WebSocket constructor.
  31329. */
  31330. var WebSocket = global.WebSocket || global.MozWebSocket;
  31331. /**
  31332. * Module exports.
  31333. */
  31334. module.exports = WebSocket ? ws : null;
  31335. /**
  31336. * WebSocket constructor.
  31337. *
  31338. * The third `opts` options object gets ignored in web browsers, since it's
  31339. * non-standard, and throws a TypeError if passed to the constructor.
  31340. * See: https://github.com/einaros/ws/issues/227
  31341. *
  31342. * @param {String} uri
  31343. * @param {Array} protocols (optional)
  31344. * @param {Object) opts (optional)
  31345. * @api public
  31346. */
  31347. function ws(uri, protocols, opts) {
  31348. var instance;
  31349. if (protocols) {
  31350. instance = new WebSocket(uri, protocols);
  31351. } else {
  31352. instance = new WebSocket(uri);
  31353. }
  31354. return instance;
  31355. }
  31356. if (WebSocket) ws.prototype = WebSocket.prototype;
  31357. },{}],140:[function(require,module,exports){
  31358. (function (global){
  31359. /*
  31360. * Module requirements.
  31361. */
  31362. var isArray = require('isarray');
  31363. /**
  31364. * Module exports.
  31365. */
  31366. module.exports = hasBinary;
  31367. /**
  31368. * Checks for binary data.
  31369. *
  31370. * Right now only Buffer and ArrayBuffer are supported..
  31371. *
  31372. * @param {Object} anything
  31373. * @api public
  31374. */
  31375. function hasBinary(data) {
  31376. function _hasBinary(obj) {
  31377. if (!obj) return false;
  31378. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  31379. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  31380. (global.Blob && obj instanceof Blob) ||
  31381. (global.File && obj instanceof File)
  31382. ) {
  31383. return true;
  31384. }
  31385. if (isArray(obj)) {
  31386. for (var i = 0; i < obj.length; i++) {
  31387. if (_hasBinary(obj[i])) {
  31388. return true;
  31389. }
  31390. }
  31391. } else if (obj && 'object' == typeof obj) {
  31392. if (obj.toJSON) {
  31393. obj = obj.toJSON();
  31394. }
  31395. for (var key in obj) {
  31396. if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
  31397. return true;
  31398. }
  31399. }
  31400. }
  31401. return false;
  31402. }
  31403. return _hasBinary(data);
  31404. }
  31405. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31406. },{"isarray":141}],141:[function(require,module,exports){
  31407. arguments[4][132][0].apply(exports,arguments)
  31408. },{"dup":132}],142:[function(require,module,exports){
  31409. var indexOf = [].indexOf;
  31410. module.exports = function(arr, obj){
  31411. if (indexOf) return arr.indexOf(obj);
  31412. for (var i = 0; i < arr.length; ++i) {
  31413. if (arr[i] === obj) return i;
  31414. }
  31415. return -1;
  31416. };
  31417. },{}],143:[function(require,module,exports){
  31418. /**
  31419. * HOP ref.
  31420. */
  31421. var has = Object.prototype.hasOwnProperty;
  31422. /**
  31423. * Return own keys in `obj`.
  31424. *
  31425. * @param {Object} obj
  31426. * @return {Array}
  31427. * @api public
  31428. */
  31429. exports.keys = Object.keys || function(obj){
  31430. var keys = [];
  31431. for (var key in obj) {
  31432. if (has.call(obj, key)) {
  31433. keys.push(key);
  31434. }
  31435. }
  31436. return keys;
  31437. };
  31438. /**
  31439. * Return own values in `obj`.
  31440. *
  31441. * @param {Object} obj
  31442. * @return {Array}
  31443. * @api public
  31444. */
  31445. exports.values = function(obj){
  31446. var vals = [];
  31447. for (var key in obj) {
  31448. if (has.call(obj, key)) {
  31449. vals.push(obj[key]);
  31450. }
  31451. }
  31452. return vals;
  31453. };
  31454. /**
  31455. * Merge `b` into `a`.
  31456. *
  31457. * @param {Object} a
  31458. * @param {Object} b
  31459. * @return {Object} a
  31460. * @api public
  31461. */
  31462. exports.merge = function(a, b){
  31463. for (var key in b) {
  31464. if (has.call(b, key)) {
  31465. a[key] = b[key];
  31466. }
  31467. }
  31468. return a;
  31469. };
  31470. /**
  31471. * Return length of `obj`.
  31472. *
  31473. * @param {Object} obj
  31474. * @return {Number}
  31475. * @api public
  31476. */
  31477. exports.length = function(obj){
  31478. return exports.keys(obj).length;
  31479. };
  31480. /**
  31481. * Check if `obj` is empty.
  31482. *
  31483. * @param {Object} obj
  31484. * @return {Boolean}
  31485. * @api public
  31486. */
  31487. exports.isEmpty = function(obj){
  31488. return 0 == exports.length(obj);
  31489. };
  31490. },{}],144:[function(require,module,exports){
  31491. /**
  31492. * Parses an URI
  31493. *
  31494. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  31495. * @api private
  31496. */
  31497. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  31498. var parts = [
  31499. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'
  31500. , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  31501. ];
  31502. module.exports = function parseuri(str) {
  31503. var m = re.exec(str || '')
  31504. , uri = {}
  31505. , i = 14;
  31506. while (i--) {
  31507. uri[parts[i]] = m[i] || '';
  31508. }
  31509. return uri;
  31510. };
  31511. },{}],145:[function(require,module,exports){
  31512. (function (global){
  31513. /*global Blob,File*/
  31514. /**
  31515. * Module requirements
  31516. */
  31517. var isArray = require('isarray');
  31518. var isBuf = require('./is-buffer');
  31519. /**
  31520. * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
  31521. * Anything with blobs or files should be fed through removeBlobs before coming
  31522. * here.
  31523. *
  31524. * @param {Object} packet - socket.io event packet
  31525. * @return {Object} with deconstructed packet and list of buffers
  31526. * @api public
  31527. */
  31528. exports.deconstructPacket = function(packet){
  31529. var buffers = [];
  31530. var packetData = packet.data;
  31531. function _deconstructPacket(data) {
  31532. if (!data) return data;
  31533. if (isBuf(data)) {
  31534. var placeholder = { _placeholder: true, num: buffers.length };
  31535. buffers.push(data);
  31536. return placeholder;
  31537. } else if (isArray(data)) {
  31538. var newData = new Array(data.length);
  31539. for (var i = 0; i < data.length; i++) {
  31540. newData[i] = _deconstructPacket(data[i]);
  31541. }
  31542. return newData;
  31543. } else if ('object' == typeof data && !(data instanceof Date)) {
  31544. var newData = {};
  31545. for (var key in data) {
  31546. newData[key] = _deconstructPacket(data[key]);
  31547. }
  31548. return newData;
  31549. }
  31550. return data;
  31551. }
  31552. var pack = packet;
  31553. pack.data = _deconstructPacket(packetData);
  31554. pack.attachments = buffers.length; // number of binary 'attachments'
  31555. return {packet: pack, buffers: buffers};
  31556. };
  31557. /**
  31558. * Reconstructs a binary packet from its placeholder packet and buffers
  31559. *
  31560. * @param {Object} packet - event packet with placeholders
  31561. * @param {Array} buffers - binary buffers to put in placeholder positions
  31562. * @return {Object} reconstructed packet
  31563. * @api public
  31564. */
  31565. exports.reconstructPacket = function(packet, buffers) {
  31566. var curPlaceHolder = 0;
  31567. function _reconstructPacket(data) {
  31568. if (data && data._placeholder) {
  31569. var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
  31570. return buf;
  31571. } else if (isArray(data)) {
  31572. for (var i = 0; i < data.length; i++) {
  31573. data[i] = _reconstructPacket(data[i]);
  31574. }
  31575. return data;
  31576. } else if (data && 'object' == typeof data) {
  31577. for (var key in data) {
  31578. data[key] = _reconstructPacket(data[key]);
  31579. }
  31580. return data;
  31581. }
  31582. return data;
  31583. }
  31584. packet.data = _reconstructPacket(packet.data);
  31585. packet.attachments = undefined; // no longer useful
  31586. return packet;
  31587. };
  31588. /**
  31589. * Asynchronously removes Blobs or Files from data via
  31590. * FileReader's readAsArrayBuffer method. Used before encoding
  31591. * data as msgpack. Calls callback with the blobless data.
  31592. *
  31593. * @param {Object} data
  31594. * @param {Function} callback
  31595. * @api private
  31596. */
  31597. exports.removeBlobs = function(data, callback) {
  31598. function _removeBlobs(obj, curKey, containingObject) {
  31599. if (!obj) return obj;
  31600. // convert any blob
  31601. if ((global.Blob && obj instanceof Blob) ||
  31602. (global.File && obj instanceof File)) {
  31603. pendingBlobs++;
  31604. // async filereader
  31605. var fileReader = new FileReader();
  31606. fileReader.onload = function() { // this.result == arraybuffer
  31607. if (containingObject) {
  31608. containingObject[curKey] = this.result;
  31609. }
  31610. else {
  31611. bloblessData = this.result;
  31612. }
  31613. // if nothing pending its callback time
  31614. if(! --pendingBlobs) {
  31615. callback(bloblessData);
  31616. }
  31617. };
  31618. fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
  31619. } else if (isArray(obj)) { // handle array
  31620. for (var i = 0; i < obj.length; i++) {
  31621. _removeBlobs(obj[i], i, obj);
  31622. }
  31623. } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
  31624. for (var key in obj) {
  31625. _removeBlobs(obj[key], key, obj);
  31626. }
  31627. }
  31628. }
  31629. var pendingBlobs = 0;
  31630. var bloblessData = data;
  31631. _removeBlobs(bloblessData);
  31632. if (!pendingBlobs) {
  31633. callback(bloblessData);
  31634. }
  31635. };
  31636. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31637. },{"./is-buffer":147,"isarray":148}],146:[function(require,module,exports){
  31638. /**
  31639. * Module dependencies.
  31640. */
  31641. var debug = require('debug')('socket.io-parser');
  31642. var json = require('json3');
  31643. var isArray = require('isarray');
  31644. var Emitter = require('component-emitter');
  31645. var binary = require('./binary');
  31646. var isBuf = require('./is-buffer');
  31647. /**
  31648. * Protocol version.
  31649. *
  31650. * @api public
  31651. */
  31652. exports.protocol = 4;
  31653. /**
  31654. * Packet types.
  31655. *
  31656. * @api public
  31657. */
  31658. exports.types = [
  31659. 'CONNECT',
  31660. 'DISCONNECT',
  31661. 'EVENT',
  31662. 'BINARY_EVENT',
  31663. 'ACK',
  31664. 'BINARY_ACK',
  31665. 'ERROR'
  31666. ];
  31667. /**
  31668. * Packet type `connect`.
  31669. *
  31670. * @api public
  31671. */
  31672. exports.CONNECT = 0;
  31673. /**
  31674. * Packet type `disconnect`.
  31675. *
  31676. * @api public
  31677. */
  31678. exports.DISCONNECT = 1;
  31679. /**
  31680. * Packet type `event`.
  31681. *
  31682. * @api public
  31683. */
  31684. exports.EVENT = 2;
  31685. /**
  31686. * Packet type `ack`.
  31687. *
  31688. * @api public
  31689. */
  31690. exports.ACK = 3;
  31691. /**
  31692. * Packet type `error`.
  31693. *
  31694. * @api public
  31695. */
  31696. exports.ERROR = 4;
  31697. /**
  31698. * Packet type 'binary event'
  31699. *
  31700. * @api public
  31701. */
  31702. exports.BINARY_EVENT = 5;
  31703. /**
  31704. * Packet type `binary ack`. For acks with binary arguments.
  31705. *
  31706. * @api public
  31707. */
  31708. exports.BINARY_ACK = 6;
  31709. /**
  31710. * Encoder constructor.
  31711. *
  31712. * @api public
  31713. */
  31714. exports.Encoder = Encoder;
  31715. /**
  31716. * Decoder constructor.
  31717. *
  31718. * @api public
  31719. */
  31720. exports.Decoder = Decoder;
  31721. /**
  31722. * A socket.io Encoder instance
  31723. *
  31724. * @api public
  31725. */
  31726. function Encoder() {}
  31727. /**
  31728. * Encode a packet as a single string if non-binary, or as a
  31729. * buffer sequence, depending on packet type.
  31730. *
  31731. * @param {Object} obj - packet object
  31732. * @param {Function} callback - function to handle encodings (likely engine.write)
  31733. * @return Calls callback with Array of encodings
  31734. * @api public
  31735. */
  31736. Encoder.prototype.encode = function(obj, callback){
  31737. debug('encoding packet %j', obj);
  31738. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  31739. encodeAsBinary(obj, callback);
  31740. }
  31741. else {
  31742. var encoding = encodeAsString(obj);
  31743. callback([encoding]);
  31744. }
  31745. };
  31746. /**
  31747. * Encode packet as string.
  31748. *
  31749. * @param {Object} packet
  31750. * @return {String} encoded
  31751. * @api private
  31752. */
  31753. function encodeAsString(obj) {
  31754. var str = '';
  31755. var nsp = false;
  31756. // first is type
  31757. str += obj.type;
  31758. // attachments if we have them
  31759. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  31760. str += obj.attachments;
  31761. str += '-';
  31762. }
  31763. // if we have a namespace other than `/`
  31764. // we append it followed by a comma `,`
  31765. if (obj.nsp && '/' != obj.nsp) {
  31766. nsp = true;
  31767. str += obj.nsp;
  31768. }
  31769. // immediately followed by the id
  31770. if (null != obj.id) {
  31771. if (nsp) {
  31772. str += ',';
  31773. nsp = false;
  31774. }
  31775. str += obj.id;
  31776. }
  31777. // json data
  31778. if (null != obj.data) {
  31779. if (nsp) str += ',';
  31780. str += json.stringify(obj.data);
  31781. }
  31782. debug('encoded %j as %s', obj, str);
  31783. return str;
  31784. }
  31785. /**
  31786. * Encode packet as 'buffer sequence' by removing blobs, and
  31787. * deconstructing packet into object with placeholders and
  31788. * a list of buffers.
  31789. *
  31790. * @param {Object} packet
  31791. * @return {Buffer} encoded
  31792. * @api private
  31793. */
  31794. function encodeAsBinary(obj, callback) {
  31795. function writeEncoding(bloblessData) {
  31796. var deconstruction = binary.deconstructPacket(bloblessData);
  31797. var pack = encodeAsString(deconstruction.packet);
  31798. var buffers = deconstruction.buffers;
  31799. buffers.unshift(pack); // add packet info to beginning of data list
  31800. callback(buffers); // write all the buffers
  31801. }
  31802. binary.removeBlobs(obj, writeEncoding);
  31803. }
  31804. /**
  31805. * A socket.io Decoder instance
  31806. *
  31807. * @return {Object} decoder
  31808. * @api public
  31809. */
  31810. function Decoder() {
  31811. this.reconstructor = null;
  31812. }
  31813. /**
  31814. * Mix in `Emitter` with Decoder.
  31815. */
  31816. Emitter(Decoder.prototype);
  31817. /**
  31818. * Decodes an ecoded packet string into packet JSON.
  31819. *
  31820. * @param {String} obj - encoded packet
  31821. * @return {Object} packet
  31822. * @api public
  31823. */
  31824. Decoder.prototype.add = function(obj) {
  31825. var packet;
  31826. if ('string' == typeof obj) {
  31827. packet = decodeString(obj);
  31828. if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
  31829. this.reconstructor = new BinaryReconstructor(packet);
  31830. // no attachments, labeled binary but no binary data to follow
  31831. if (this.reconstructor.reconPack.attachments === 0) {
  31832. this.emit('decoded', packet);
  31833. }
  31834. } else { // non-binary full packet
  31835. this.emit('decoded', packet);
  31836. }
  31837. }
  31838. else if (isBuf(obj) || obj.base64) { // raw binary data
  31839. if (!this.reconstructor) {
  31840. throw new Error('got binary data when not reconstructing a packet');
  31841. } else {
  31842. packet = this.reconstructor.takeBinaryData(obj);
  31843. if (packet) { // received final buffer
  31844. this.reconstructor = null;
  31845. this.emit('decoded', packet);
  31846. }
  31847. }
  31848. }
  31849. else {
  31850. throw new Error('Unknown type: ' + obj);
  31851. }
  31852. };
  31853. /**
  31854. * Decode a packet String (JSON data)
  31855. *
  31856. * @param {String} str
  31857. * @return {Object} packet
  31858. * @api private
  31859. */
  31860. function decodeString(str) {
  31861. var p = {};
  31862. var i = 0;
  31863. // look up type
  31864. p.type = Number(str.charAt(0));
  31865. if (null == exports.types[p.type]) return error();
  31866. // look up attachments if type binary
  31867. if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
  31868. var buf = '';
  31869. while (str.charAt(++i) != '-') {
  31870. buf += str.charAt(i);
  31871. if (i == str.length) break;
  31872. }
  31873. if (buf != Number(buf) || str.charAt(i) != '-') {
  31874. throw new Error('Illegal attachments');
  31875. }
  31876. p.attachments = Number(buf);
  31877. }
  31878. // look up namespace (if any)
  31879. if ('/' == str.charAt(i + 1)) {
  31880. p.nsp = '';
  31881. while (++i) {
  31882. var c = str.charAt(i);
  31883. if (',' == c) break;
  31884. p.nsp += c;
  31885. if (i == str.length) break;
  31886. }
  31887. } else {
  31888. p.nsp = '/';
  31889. }
  31890. // look up id
  31891. var next = str.charAt(i + 1);
  31892. if ('' !== next && Number(next) == next) {
  31893. p.id = '';
  31894. while (++i) {
  31895. var c = str.charAt(i);
  31896. if (null == c || Number(c) != c) {
  31897. --i;
  31898. break;
  31899. }
  31900. p.id += str.charAt(i);
  31901. if (i == str.length) break;
  31902. }
  31903. p.id = Number(p.id);
  31904. }
  31905. // look up json data
  31906. if (str.charAt(++i)) {
  31907. try {
  31908. p.data = json.parse(str.substr(i));
  31909. } catch(e){
  31910. return error();
  31911. }
  31912. }
  31913. debug('decoded %s as %j', str, p);
  31914. return p;
  31915. }
  31916. /**
  31917. * Deallocates a parser's resources
  31918. *
  31919. * @api public
  31920. */
  31921. Decoder.prototype.destroy = function() {
  31922. if (this.reconstructor) {
  31923. this.reconstructor.finishedReconstruction();
  31924. }
  31925. };
  31926. /**
  31927. * A manager of a binary event's 'buffer sequence'. Should
  31928. * be constructed whenever a packet of type BINARY_EVENT is
  31929. * decoded.
  31930. *
  31931. * @param {Object} packet
  31932. * @return {BinaryReconstructor} initialized reconstructor
  31933. * @api private
  31934. */
  31935. function BinaryReconstructor(packet) {
  31936. this.reconPack = packet;
  31937. this.buffers = [];
  31938. }
  31939. /**
  31940. * Method to be called when binary data received from connection
  31941. * after a BINARY_EVENT packet.
  31942. *
  31943. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  31944. * @return {null | Object} returns null if more binary data is expected or
  31945. * a reconstructed packet object if all buffers have been received.
  31946. * @api private
  31947. */
  31948. BinaryReconstructor.prototype.takeBinaryData = function(binData) {
  31949. this.buffers.push(binData);
  31950. if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
  31951. var packet = binary.reconstructPacket(this.reconPack, this.buffers);
  31952. this.finishedReconstruction();
  31953. return packet;
  31954. }
  31955. return null;
  31956. };
  31957. /**
  31958. * Cleans up binary packet reconstruction variables.
  31959. *
  31960. * @api private
  31961. */
  31962. BinaryReconstructor.prototype.finishedReconstruction = function() {
  31963. this.reconPack = null;
  31964. this.buffers = [];
  31965. };
  31966. function error(data){
  31967. return {
  31968. type: exports.ERROR,
  31969. data: 'parser error'
  31970. };
  31971. }
  31972. },{"./binary":145,"./is-buffer":147,"component-emitter":109,"debug":110,"isarray":148,"json3":149}],147:[function(require,module,exports){
  31973. (function (global){
  31974. module.exports = isBuf;
  31975. /**
  31976. * Returns true if obj is a buffer or an arraybuffer.
  31977. *
  31978. * @api private
  31979. */
  31980. function isBuf(obj) {
  31981. return (global.Buffer && global.Buffer.isBuffer(obj)) ||
  31982. (global.ArrayBuffer && obj instanceof ArrayBuffer);
  31983. }
  31984. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31985. },{}],148:[function(require,module,exports){
  31986. arguments[4][132][0].apply(exports,arguments)
  31987. },{"dup":132}],149:[function(require,module,exports){
  31988. /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */
  31989. ;(function (window) {
  31990. // Convenience aliases.
  31991. var getClass = {}.toString, isProperty, forEach, undef;
  31992. // Detect the `define` function exposed by asynchronous module loaders. The
  31993. // strict `define` check is necessary for compatibility with `r.js`.
  31994. var isLoader = typeof define === "function" && define.amd;
  31995. // Detect native implementations.
  31996. var nativeJSON = typeof JSON == "object" && JSON;
  31997. // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if
  31998. // available.
  31999. var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;
  32000. if (JSON3 && nativeJSON) {
  32001. // Explicitly delegate to the native `stringify` and `parse`
  32002. // implementations in CommonJS environments.
  32003. JSON3.stringify = nativeJSON.stringify;
  32004. JSON3.parse = nativeJSON.parse;
  32005. } else {
  32006. // Export for web browsers, JavaScript engines, and asynchronous module
  32007. // loaders, using the global `JSON` object if available.
  32008. JSON3 = window.JSON = nativeJSON || {};
  32009. }
  32010. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  32011. var isExtended = new Date(-3509827334573292);
  32012. try {
  32013. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  32014. // results for certain dates in Opera >= 10.53.
  32015. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  32016. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  32017. // but clips the values returned by the date methods to the range of
  32018. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  32019. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  32020. } catch (exception) {}
  32021. // Internal: Determines whether the native `JSON.stringify` and `parse`
  32022. // implementations are spec-compliant. Based on work by Ken Snyder.
  32023. function has(name) {
  32024. if (has[name] !== undef) {
  32025. // Return cached feature test result.
  32026. return has[name];
  32027. }
  32028. var isSupported;
  32029. if (name == "bug-string-char-index") {
  32030. // IE <= 7 doesn't support accessing string characters using square
  32031. // bracket notation. IE 8 only supports this for primitives.
  32032. isSupported = "a"[0] != "a";
  32033. } else if (name == "json") {
  32034. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  32035. // supported.
  32036. isSupported = has("json-stringify") && has("json-parse");
  32037. } else {
  32038. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  32039. // Test `JSON.stringify`.
  32040. if (name == "json-stringify") {
  32041. var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  32042. if (stringifySupported) {
  32043. // A test function object with a custom `toJSON` method.
  32044. (value = function () {
  32045. return 1;
  32046. }).toJSON = value;
  32047. try {
  32048. stringifySupported =
  32049. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  32050. // primitives as object literals.
  32051. stringify(0) === "0" &&
  32052. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  32053. // literals.
  32054. stringify(new Number()) === "0" &&
  32055. stringify(new String()) == '""' &&
  32056. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  32057. // does not define a canonical JSON representation (this applies to
  32058. // objects with `toJSON` properties as well, *unless* they are nested
  32059. // within an object or array).
  32060. stringify(getClass) === undef &&
  32061. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  32062. // FF 3.1b3 pass this test.
  32063. stringify(undef) === undef &&
  32064. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  32065. // respectively, if the value is omitted entirely.
  32066. stringify() === undef &&
  32067. // FF 3.1b1, 2 throw an error if the given value is not a number,
  32068. // string, array, object, Boolean, or `null` literal. This applies to
  32069. // objects with custom `toJSON` methods as well, unless they are nested
  32070. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  32071. // methods entirely.
  32072. stringify(value) === "1" &&
  32073. stringify([value]) == "[1]" &&
  32074. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  32075. // `"[null]"`.
  32076. stringify([undef]) == "[null]" &&
  32077. // YUI 3.0.0b1 fails to serialize `null` literals.
  32078. stringify(null) == "null" &&
  32079. // FF 3.1b1, 2 halts serialization if an array contains a function:
  32080. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  32081. // elides non-JSON values from objects and arrays, unless they
  32082. // define custom `toJSON` methods.
  32083. stringify([undef, getClass, null]) == "[null,null,null]" &&
  32084. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  32085. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  32086. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  32087. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  32088. stringify(null, value) === "1" &&
  32089. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  32090. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  32091. // serialize extended years.
  32092. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  32093. // The milliseconds are optional in ES 5, but required in 5.1.
  32094. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  32095. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  32096. // four-digit years instead of six-digit years. Credits: @Yaffle.
  32097. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  32098. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  32099. // values less than 1000. Credits: @Yaffle.
  32100. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  32101. } catch (exception) {
  32102. stringifySupported = false;
  32103. }
  32104. }
  32105. isSupported = stringifySupported;
  32106. }
  32107. // Test `JSON.parse`.
  32108. if (name == "json-parse") {
  32109. var parse = JSON3.parse;
  32110. if (typeof parse == "function") {
  32111. try {
  32112. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  32113. // Conforming implementations should also coerce the initial argument to
  32114. // a string prior to parsing.
  32115. if (parse("0") === 0 && !parse(false)) {
  32116. // Simple parsing test.
  32117. value = parse(serialized);
  32118. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  32119. if (parseSupported) {
  32120. try {
  32121. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  32122. parseSupported = !parse('"\t"');
  32123. } catch (exception) {}
  32124. if (parseSupported) {
  32125. try {
  32126. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  32127. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  32128. // certain octal literals.
  32129. parseSupported = parse("01") !== 1;
  32130. } catch (exception) {}
  32131. }
  32132. if (parseSupported) {
  32133. try {
  32134. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  32135. // points. These environments, along with FF 3.1b1 and 2,
  32136. // also allow trailing commas in JSON objects and arrays.
  32137. parseSupported = parse("1.") !== 1;
  32138. } catch (exception) {}
  32139. }
  32140. }
  32141. }
  32142. } catch (exception) {
  32143. parseSupported = false;
  32144. }
  32145. }
  32146. isSupported = parseSupported;
  32147. }
  32148. }
  32149. return has[name] = !!isSupported;
  32150. }
  32151. if (!has("json")) {
  32152. // Common `[[Class]]` name aliases.
  32153. var functionClass = "[object Function]";
  32154. var dateClass = "[object Date]";
  32155. var numberClass = "[object Number]";
  32156. var stringClass = "[object String]";
  32157. var arrayClass = "[object Array]";
  32158. var booleanClass = "[object Boolean]";
  32159. // Detect incomplete support for accessing string characters by index.
  32160. var charIndexBuggy = has("bug-string-char-index");
  32161. // Define additional utility methods if the `Date` methods are buggy.
  32162. if (!isExtended) {
  32163. var floor = Math.floor;
  32164. // A mapping between the months of the year and the number of days between
  32165. // January 1st and the first of the respective month.
  32166. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  32167. // Internal: Calculates the number of days between the Unix epoch and the
  32168. // first day of the given month.
  32169. var getDay = function (year, month) {
  32170. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  32171. };
  32172. }
  32173. // Internal: Determines if a property is a direct property of the given
  32174. // object. Delegates to the native `Object#hasOwnProperty` method.
  32175. if (!(isProperty = {}.hasOwnProperty)) {
  32176. isProperty = function (property) {
  32177. var members = {}, constructor;
  32178. if ((members.__proto__ = null, members.__proto__ = {
  32179. // The *proto* property cannot be set multiple times in recent
  32180. // versions of Firefox and SeaMonkey.
  32181. "toString": 1
  32182. }, members).toString != getClass) {
  32183. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  32184. // supports the mutable *proto* property.
  32185. isProperty = function (property) {
  32186. // Capture and break the object's prototype chain (see section 8.6.2
  32187. // of the ES 5.1 spec). The parenthesized expression prevents an
  32188. // unsafe transformation by the Closure Compiler.
  32189. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  32190. // Restore the original prototype chain.
  32191. this.__proto__ = original;
  32192. return result;
  32193. };
  32194. } else {
  32195. // Capture a reference to the top-level `Object` constructor.
  32196. constructor = members.constructor;
  32197. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  32198. // other environments.
  32199. isProperty = function (property) {
  32200. var parent = (this.constructor || constructor).prototype;
  32201. return property in this && !(property in parent && this[property] === parent[property]);
  32202. };
  32203. }
  32204. members = null;
  32205. return isProperty.call(this, property);
  32206. };
  32207. }
  32208. // Internal: A set of primitive types used by `isHostType`.
  32209. var PrimitiveTypes = {
  32210. 'boolean': 1,
  32211. 'number': 1,
  32212. 'string': 1,
  32213. 'undefined': 1
  32214. };
  32215. // Internal: Determines if the given object `property` value is a
  32216. // non-primitive.
  32217. var isHostType = function (object, property) {
  32218. var type = typeof object[property];
  32219. return type == 'object' ? !!object[property] : !PrimitiveTypes[type];
  32220. };
  32221. // Internal: Normalizes the `for...in` iteration algorithm across
  32222. // environments. Each enumerated key is yielded to a `callback` function.
  32223. forEach = function (object, callback) {
  32224. var size = 0, Properties, members, property;
  32225. // Tests for bugs in the current environment's `for...in` algorithm. The
  32226. // `valueOf` property inherits the non-enumerable flag from
  32227. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  32228. (Properties = function () {
  32229. this.valueOf = 0;
  32230. }).prototype.valueOf = 0;
  32231. // Iterate over a new instance of the `Properties` class.
  32232. members = new Properties();
  32233. for (property in members) {
  32234. // Ignore all properties inherited from `Object.prototype`.
  32235. if (isProperty.call(members, property)) {
  32236. size++;
  32237. }
  32238. }
  32239. Properties = members = null;
  32240. // Normalize the iteration algorithm.
  32241. if (!size) {
  32242. // A list of non-enumerable properties inherited from `Object.prototype`.
  32243. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  32244. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  32245. // properties.
  32246. forEach = function (object, callback) {
  32247. var isFunction = getClass.call(object) == functionClass, property, length;
  32248. var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;
  32249. for (property in object) {
  32250. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  32251. // certain conditions; IE does not.
  32252. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  32253. callback(property);
  32254. }
  32255. }
  32256. // Manually invoke the callback for each non-enumerable property.
  32257. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  32258. };
  32259. } else if (size == 2) {
  32260. // Safari <= 2.0.4 enumerates shadowed properties twice.
  32261. forEach = function (object, callback) {
  32262. // Create a set of iterated properties.
  32263. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  32264. for (property in object) {
  32265. // Store each property name to prevent double enumeration. The
  32266. // `prototype` property of functions is not enumerated due to cross-
  32267. // environment inconsistencies.
  32268. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  32269. callback(property);
  32270. }
  32271. }
  32272. };
  32273. } else {
  32274. // No bugs detected; use the standard `for...in` algorithm.
  32275. forEach = function (object, callback) {
  32276. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  32277. for (property in object) {
  32278. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  32279. callback(property);
  32280. }
  32281. }
  32282. // Manually invoke the callback for the `constructor` property due to
  32283. // cross-environment inconsistencies.
  32284. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  32285. callback(property);
  32286. }
  32287. };
  32288. }
  32289. return forEach(object, callback);
  32290. };
  32291. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  32292. // `filter` argument may specify either a function that alters how object and
  32293. // array members are serialized, or an array of strings and numbers that
  32294. // indicates which properties should be serialized. The optional `width`
  32295. // argument may be either a string or number that specifies the indentation
  32296. // level of the output.
  32297. if (!has("json-stringify")) {
  32298. // Internal: A map of control characters and their escaped equivalents.
  32299. var Escapes = {
  32300. 92: "\\\\",
  32301. 34: '\\"',
  32302. 8: "\\b",
  32303. 12: "\\f",
  32304. 10: "\\n",
  32305. 13: "\\r",
  32306. 9: "\\t"
  32307. };
  32308. // Internal: Converts `value` into a zero-padded string such that its
  32309. // length is at least equal to `width`. The `width` must be <= 6.
  32310. var leadingZeroes = "000000";
  32311. var toPaddedString = function (width, value) {
  32312. // The `|| 0` expression is necessary to work around a bug in
  32313. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  32314. return (leadingZeroes + (value || 0)).slice(-width);
  32315. };
  32316. // Internal: Double-quotes a string `value`, replacing all ASCII control
  32317. // characters (characters with code unit values between 0 and 31) with
  32318. // their escaped equivalents. This is an implementation of the
  32319. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  32320. var unicodePrefix = "\\u00";
  32321. var quote = function (value) {
  32322. var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;
  32323. if (isLarge) {
  32324. symbols = value.split("");
  32325. }
  32326. for (; index < length; index++) {
  32327. var charCode = value.charCodeAt(index);
  32328. // If the character is a control character, append its Unicode or
  32329. // shorthand escape sequence; otherwise, append the character as-is.
  32330. switch (charCode) {
  32331. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  32332. result += Escapes[charCode];
  32333. break;
  32334. default:
  32335. if (charCode < 32) {
  32336. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  32337. break;
  32338. }
  32339. result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];
  32340. }
  32341. }
  32342. return result + '"';
  32343. };
  32344. // Internal: Recursively serializes an object. Implements the
  32345. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  32346. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  32347. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  32348. try {
  32349. // Necessary for host object support.
  32350. value = object[property];
  32351. } catch (exception) {}
  32352. if (typeof value == "object" && value) {
  32353. className = getClass.call(value);
  32354. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  32355. if (value > -1 / 0 && value < 1 / 0) {
  32356. // Dates are serialized according to the `Date#toJSON` method
  32357. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  32358. // for the ISO 8601 date time string format.
  32359. if (getDay) {
  32360. // Manually compute the year, month, date, hours, minutes,
  32361. // seconds, and milliseconds if the `getUTC*` methods are
  32362. // buggy. Adapted from @Yaffle's `date-shim` project.
  32363. date = floor(value / 864e5);
  32364. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  32365. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  32366. date = 1 + date - getDay(year, month);
  32367. // The `time` value specifies the time within the day (see ES
  32368. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  32369. // to compute `A modulo B`, as the `%` operator does not
  32370. // correspond to the `modulo` operation for negative numbers.
  32371. time = (value % 864e5 + 864e5) % 864e5;
  32372. // The hours, minutes, seconds, and milliseconds are obtained by
  32373. // decomposing the time within the day. See section 15.9.1.10.
  32374. hours = floor(time / 36e5) % 24;
  32375. minutes = floor(time / 6e4) % 60;
  32376. seconds = floor(time / 1e3) % 60;
  32377. milliseconds = time % 1e3;
  32378. } else {
  32379. year = value.getUTCFullYear();
  32380. month = value.getUTCMonth();
  32381. date = value.getUTCDate();
  32382. hours = value.getUTCHours();
  32383. minutes = value.getUTCMinutes();
  32384. seconds = value.getUTCSeconds();
  32385. milliseconds = value.getUTCMilliseconds();
  32386. }
  32387. // Serialize extended years correctly.
  32388. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  32389. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  32390. // Months, dates, hours, minutes, and seconds should have two
  32391. // digits; milliseconds should have three.
  32392. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  32393. // Milliseconds are optional in ES 5.0, but required in 5.1.
  32394. "." + toPaddedString(3, milliseconds) + "Z";
  32395. } else {
  32396. value = null;
  32397. }
  32398. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  32399. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  32400. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  32401. // ignores all `toJSON` methods on these objects unless they are
  32402. // defined directly on an instance.
  32403. value = value.toJSON(property);
  32404. }
  32405. }
  32406. if (callback) {
  32407. // If a replacement function was provided, call it to obtain the value
  32408. // for serialization.
  32409. value = callback.call(object, property, value);
  32410. }
  32411. if (value === null) {
  32412. return "null";
  32413. }
  32414. className = getClass.call(value);
  32415. if (className == booleanClass) {
  32416. // Booleans are represented literally.
  32417. return "" + value;
  32418. } else if (className == numberClass) {
  32419. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  32420. // `"null"`.
  32421. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  32422. } else if (className == stringClass) {
  32423. // Strings are double-quoted and escaped.
  32424. return quote("" + value);
  32425. }
  32426. // Recursively serialize objects and arrays.
  32427. if (typeof value == "object") {
  32428. // Check for cyclic structures. This is a linear search; performance
  32429. // is inversely proportional to the number of unique nested objects.
  32430. for (length = stack.length; length--;) {
  32431. if (stack[length] === value) {
  32432. // Cyclic structures cannot be serialized by `JSON.stringify`.
  32433. throw TypeError();
  32434. }
  32435. }
  32436. // Add the object to the stack of traversed objects.
  32437. stack.push(value);
  32438. results = [];
  32439. // Save the current indentation level and indent one additional level.
  32440. prefix = indentation;
  32441. indentation += whitespace;
  32442. if (className == arrayClass) {
  32443. // Recursively serialize array elements.
  32444. for (index = 0, length = value.length; index < length; index++) {
  32445. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  32446. results.push(element === undef ? "null" : element);
  32447. }
  32448. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  32449. } else {
  32450. // Recursively serialize object members. Members are selected from
  32451. // either a user-specified list of property names, or the object
  32452. // itself.
  32453. forEach(properties || value, function (property) {
  32454. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  32455. if (element !== undef) {
  32456. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  32457. // is not the empty string, let `member` {quote(property) + ":"}
  32458. // be the concatenation of `member` and the `space` character."
  32459. // The "`space` character" refers to the literal space
  32460. // character, not the `space` {width} argument provided to
  32461. // `JSON.stringify`.
  32462. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  32463. }
  32464. });
  32465. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  32466. }
  32467. // Remove the object from the traversed object stack.
  32468. stack.pop();
  32469. return result;
  32470. }
  32471. };
  32472. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  32473. JSON3.stringify = function (source, filter, width) {
  32474. var whitespace, callback, properties, className;
  32475. if (typeof filter == "function" || typeof filter == "object" && filter) {
  32476. if ((className = getClass.call(filter)) == functionClass) {
  32477. callback = filter;
  32478. } else if (className == arrayClass) {
  32479. // Convert the property names array into a makeshift set.
  32480. properties = {};
  32481. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  32482. }
  32483. }
  32484. if (width) {
  32485. if ((className = getClass.call(width)) == numberClass) {
  32486. // Convert the `width` to an integer and create a string containing
  32487. // `width` number of space characters.
  32488. if ((width -= width % 1) > 0) {
  32489. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  32490. }
  32491. } else if (className == stringClass) {
  32492. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  32493. }
  32494. }
  32495. // Opera <= 7.54u2 discards the values associated with empty string keys
  32496. // (`""`) only if they are used directly within an object member list
  32497. // (e.g., `!("" in { "": 1})`).
  32498. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  32499. };
  32500. }
  32501. // Public: Parses a JSON source string.
  32502. if (!has("json-parse")) {
  32503. var fromCharCode = String.fromCharCode;
  32504. // Internal: A map of escaped control characters and their unescaped
  32505. // equivalents.
  32506. var Unescapes = {
  32507. 92: "\\",
  32508. 34: '"',
  32509. 47: "/",
  32510. 98: "\b",
  32511. 116: "\t",
  32512. 110: "\n",
  32513. 102: "\f",
  32514. 114: "\r"
  32515. };
  32516. // Internal: Stores the parser state.
  32517. var Index, Source;
  32518. // Internal: Resets the parser state and throws a `SyntaxError`.
  32519. var abort = function() {
  32520. Index = Source = null;
  32521. throw SyntaxError();
  32522. };
  32523. // Internal: Returns the next token, or `"$"` if the parser has reached
  32524. // the end of the source string. A token may be a string, number, `null`
  32525. // literal, or Boolean literal.
  32526. var lex = function () {
  32527. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  32528. while (Index < length) {
  32529. charCode = source.charCodeAt(Index);
  32530. switch (charCode) {
  32531. case 9: case 10: case 13: case 32:
  32532. // Skip whitespace tokens, including tabs, carriage returns, line
  32533. // feeds, and space characters.
  32534. Index++;
  32535. break;
  32536. case 123: case 125: case 91: case 93: case 58: case 44:
  32537. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  32538. // the current position.
  32539. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  32540. Index++;
  32541. return value;
  32542. case 34:
  32543. // `"` delimits a JSON string; advance to the next character and
  32544. // begin parsing the string. String tokens are prefixed with the
  32545. // sentinel `@` character to distinguish them from punctuators and
  32546. // end-of-string tokens.
  32547. for (value = "@", Index++; Index < length;) {
  32548. charCode = source.charCodeAt(Index);
  32549. if (charCode < 32) {
  32550. // Unescaped ASCII control characters (those with a code unit
  32551. // less than the space character) are not permitted.
  32552. abort();
  32553. } else if (charCode == 92) {
  32554. // A reverse solidus (`\`) marks the beginning of an escaped
  32555. // control character (including `"`, `\`, and `/`) or Unicode
  32556. // escape sequence.
  32557. charCode = source.charCodeAt(++Index);
  32558. switch (charCode) {
  32559. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  32560. // Revive escaped control characters.
  32561. value += Unescapes[charCode];
  32562. Index++;
  32563. break;
  32564. case 117:
  32565. // `\u` marks the beginning of a Unicode escape sequence.
  32566. // Advance to the first character and validate the
  32567. // four-digit code point.
  32568. begin = ++Index;
  32569. for (position = Index + 4; Index < position; Index++) {
  32570. charCode = source.charCodeAt(Index);
  32571. // A valid sequence comprises four hexdigits (case-
  32572. // insensitive) that form a single hexadecimal value.
  32573. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  32574. // Invalid Unicode escape sequence.
  32575. abort();
  32576. }
  32577. }
  32578. // Revive the escaped character.
  32579. value += fromCharCode("0x" + source.slice(begin, Index));
  32580. break;
  32581. default:
  32582. // Invalid escape sequence.
  32583. abort();
  32584. }
  32585. } else {
  32586. if (charCode == 34) {
  32587. // An unescaped double-quote character marks the end of the
  32588. // string.
  32589. break;
  32590. }
  32591. charCode = source.charCodeAt(Index);
  32592. begin = Index;
  32593. // Optimize for the common case where a string is valid.
  32594. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  32595. charCode = source.charCodeAt(++Index);
  32596. }
  32597. // Append the string as-is.
  32598. value += source.slice(begin, Index);
  32599. }
  32600. }
  32601. if (source.charCodeAt(Index) == 34) {
  32602. // Advance to the next character and return the revived string.
  32603. Index++;
  32604. return value;
  32605. }
  32606. // Unterminated string.
  32607. abort();
  32608. default:
  32609. // Parse numbers and literals.
  32610. begin = Index;
  32611. // Advance past the negative sign, if one is specified.
  32612. if (charCode == 45) {
  32613. isSigned = true;
  32614. charCode = source.charCodeAt(++Index);
  32615. }
  32616. // Parse an integer or floating-point value.
  32617. if (charCode >= 48 && charCode <= 57) {
  32618. // Leading zeroes are interpreted as octal literals.
  32619. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  32620. // Illegal octal literal.
  32621. abort();
  32622. }
  32623. isSigned = false;
  32624. // Parse the integer component.
  32625. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  32626. // Floats cannot contain a leading decimal point; however, this
  32627. // case is already accounted for by the parser.
  32628. if (source.charCodeAt(Index) == 46) {
  32629. position = ++Index;
  32630. // Parse the decimal component.
  32631. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  32632. if (position == Index) {
  32633. // Illegal trailing decimal.
  32634. abort();
  32635. }
  32636. Index = position;
  32637. }
  32638. // Parse exponents. The `e` denoting the exponent is
  32639. // case-insensitive.
  32640. charCode = source.charCodeAt(Index);
  32641. if (charCode == 101 || charCode == 69) {
  32642. charCode = source.charCodeAt(++Index);
  32643. // Skip past the sign following the exponent, if one is
  32644. // specified.
  32645. if (charCode == 43 || charCode == 45) {
  32646. Index++;
  32647. }
  32648. // Parse the exponential component.
  32649. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  32650. if (position == Index) {
  32651. // Illegal empty exponent.
  32652. abort();
  32653. }
  32654. Index = position;
  32655. }
  32656. // Coerce the parsed value to a JavaScript number.
  32657. return +source.slice(begin, Index);
  32658. }
  32659. // A negative sign may only precede numbers.
  32660. if (isSigned) {
  32661. abort();
  32662. }
  32663. // `true`, `false`, and `null` literals.
  32664. if (source.slice(Index, Index + 4) == "true") {
  32665. Index += 4;
  32666. return true;
  32667. } else if (source.slice(Index, Index + 5) == "false") {
  32668. Index += 5;
  32669. return false;
  32670. } else if (source.slice(Index, Index + 4) == "null") {
  32671. Index += 4;
  32672. return null;
  32673. }
  32674. // Unrecognized token.
  32675. abort();
  32676. }
  32677. }
  32678. // Return the sentinel `$` character if the parser has reached the end
  32679. // of the source string.
  32680. return "$";
  32681. };
  32682. // Internal: Parses a JSON `value` token.
  32683. var get = function (value) {
  32684. var results, hasMembers;
  32685. if (value == "$") {
  32686. // Unexpected end of input.
  32687. abort();
  32688. }
  32689. if (typeof value == "string") {
  32690. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  32691. // Remove the sentinel `@` character.
  32692. return value.slice(1);
  32693. }
  32694. // Parse object and array literals.
  32695. if (value == "[") {
  32696. // Parses a JSON array, returning a new JavaScript array.
  32697. results = [];
  32698. for (;; hasMembers || (hasMembers = true)) {
  32699. value = lex();
  32700. // A closing square bracket marks the end of the array literal.
  32701. if (value == "]") {
  32702. break;
  32703. }
  32704. // If the array literal contains elements, the current token
  32705. // should be a comma separating the previous element from the
  32706. // next.
  32707. if (hasMembers) {
  32708. if (value == ",") {
  32709. value = lex();
  32710. if (value == "]") {
  32711. // Unexpected trailing `,` in array literal.
  32712. abort();
  32713. }
  32714. } else {
  32715. // A `,` must separate each array element.
  32716. abort();
  32717. }
  32718. }
  32719. // Elisions and leading commas are not permitted.
  32720. if (value == ",") {
  32721. abort();
  32722. }
  32723. results.push(get(value));
  32724. }
  32725. return results;
  32726. } else if (value == "{") {
  32727. // Parses a JSON object, returning a new JavaScript object.
  32728. results = {};
  32729. for (;; hasMembers || (hasMembers = true)) {
  32730. value = lex();
  32731. // A closing curly brace marks the end of the object literal.
  32732. if (value == "}") {
  32733. break;
  32734. }
  32735. // If the object literal contains members, the current token
  32736. // should be a comma separator.
  32737. if (hasMembers) {
  32738. if (value == ",") {
  32739. value = lex();
  32740. if (value == "}") {
  32741. // Unexpected trailing `,` in object literal.
  32742. abort();
  32743. }
  32744. } else {
  32745. // A `,` must separate each object member.
  32746. abort();
  32747. }
  32748. }
  32749. // Leading commas are not permitted, object property names must be
  32750. // double-quoted strings, and a `:` must separate each property
  32751. // name and value.
  32752. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  32753. abort();
  32754. }
  32755. results[value.slice(1)] = get(lex());
  32756. }
  32757. return results;
  32758. }
  32759. // Unexpected token encountered.
  32760. abort();
  32761. }
  32762. return value;
  32763. };
  32764. // Internal: Updates a traversed object member.
  32765. var update = function(source, property, callback) {
  32766. var element = walk(source, property, callback);
  32767. if (element === undef) {
  32768. delete source[property];
  32769. } else {
  32770. source[property] = element;
  32771. }
  32772. };
  32773. // Internal: Recursively traverses a parsed JSON object, invoking the
  32774. // `callback` function for each value. This is an implementation of the
  32775. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  32776. var walk = function (source, property, callback) {
  32777. var value = source[property], length;
  32778. if (typeof value == "object" && value) {
  32779. // `forEach` can't be used to traverse an array in Opera <= 8.54
  32780. // because its `Object#hasOwnProperty` implementation returns `false`
  32781. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  32782. if (getClass.call(value) == arrayClass) {
  32783. for (length = value.length; length--;) {
  32784. update(value, length, callback);
  32785. }
  32786. } else {
  32787. forEach(value, function (property) {
  32788. update(value, property, callback);
  32789. });
  32790. }
  32791. }
  32792. return callback.call(source, property, value);
  32793. };
  32794. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  32795. JSON3.parse = function (source, callback) {
  32796. var result, value;
  32797. Index = 0;
  32798. Source = "" + source;
  32799. result = get(lex());
  32800. // If a JSON string contains multiple tokens, it is invalid.
  32801. if (lex() != "$") {
  32802. abort();
  32803. }
  32804. // Reset the parser state.
  32805. Index = Source = null;
  32806. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  32807. };
  32808. }
  32809. }
  32810. // Export for asynchronous module loaders.
  32811. if (isLoader) {
  32812. define(function () {
  32813. return JSON3;
  32814. });
  32815. }
  32816. }(this));
  32817. },{}],150:[function(require,module,exports){
  32818. module.exports = toArray
  32819. function toArray(list, index) {
  32820. var array = []
  32821. index = index || 0
  32822. for (var i = index || 0; i < list.length; i++) {
  32823. array[i - index] = list[i]
  32824. }
  32825. return array
  32826. }
  32827. },{}],151:[function(require,module,exports){
  32828. var MediaStreamType = {
  32829. VIDEO_TYPE: "Video",
  32830. AUDIO_TYPE: "Audio"
  32831. };
  32832. module.exports = MediaStreamType;
  32833. },{}],152:[function(require,module,exports){
  32834. var RTCEvents = {
  32835. RTC_READY: "rtc.ready",
  32836. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  32837. LASTN_CHANGED: "rtc.lastn_changed",
  32838. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  32839. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  32840. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  32841. AUDIO_MUTE: "rtc.audio_mute",
  32842. VIDEO_MUTE: "rtc.video_mute"
  32843. };
  32844. module.exports = RTCEvents;
  32845. },{}],153:[function(require,module,exports){
  32846. var Resolutions = {
  32847. "1080": {
  32848. width: 1920,
  32849. height: 1080,
  32850. order: 7
  32851. },
  32852. "fullhd": {
  32853. width: 1920,
  32854. height: 1080,
  32855. order: 7
  32856. },
  32857. "720": {
  32858. width: 1280,
  32859. height: 720,
  32860. order: 6
  32861. },
  32862. "hd": {
  32863. width: 1280,
  32864. height: 720,
  32865. order: 6
  32866. },
  32867. "960": {
  32868. width: 960,
  32869. height: 720,
  32870. order: 5
  32871. },
  32872. "640": {
  32873. width: 640,
  32874. height: 480,
  32875. order: 4
  32876. },
  32877. "vga": {
  32878. width: 640,
  32879. height: 480,
  32880. order: 4
  32881. },
  32882. "360": {
  32883. width: 640,
  32884. height: 360,
  32885. order: 3
  32886. },
  32887. "320": {
  32888. width: 320,
  32889. height: 240,
  32890. order: 2
  32891. },
  32892. "180": {
  32893. width: 320,
  32894. height: 180,
  32895. order: 1
  32896. }
  32897. };
  32898. module.exports = Resolutions;
  32899. },{}],154:[function(require,module,exports){
  32900. var StreamEventTypes = {
  32901. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  32902. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  32903. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  32904. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  32905. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  32906. };
  32907. module.exports = StreamEventTypes;
  32908. },{}],155:[function(require,module,exports){
  32909. var UIEvents = {
  32910. NICKNAME_CHANGED: "UI.nickname_changed",
  32911. SELECTED_ENDPOINT: "UI.selected_endpoint",
  32912. PINNED_ENDPOINT: "UI.pinned_endpoint",
  32913. LARGEVIDEO_INIT: "UI.largevideo_init"
  32914. };
  32915. module.exports = UIEvents;
  32916. },{}],156:[function(require,module,exports){
  32917. var AuthenticationEvents = {
  32918. /**
  32919. * Event callback arguments:
  32920. * function(authenticationEnabled, userIdentity)
  32921. * authenticationEnabled - indicates whether authentication has been enabled
  32922. * in this session
  32923. * userIdentity - if user has been logged in then it contains user name. If
  32924. * contains 'null' or 'undefined' then user is not logged in.
  32925. */
  32926. IDENTITY_UPDATED: "authentication.identity_updated"
  32927. };
  32928. module.exports = AuthenticationEvents;
  32929. },{}],157:[function(require,module,exports){
  32930. var CQEvents = {
  32931. LOCALSTATS_UPDATED: "cq.localstats_updated",
  32932. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  32933. STOP: "cq.stop"
  32934. };
  32935. module.exports = CQEvents;
  32936. },{}],158:[function(require,module,exports){
  32937. var DesktopSharingEventTypes = {
  32938. INIT: "ds.init",
  32939. SWITCHING_DONE: "ds.switching_done",
  32940. NEW_STREAM_CREATED: "ds.new_stream_created"
  32941. };
  32942. module.exports = DesktopSharingEventTypes;
  32943. },{}],159:[function(require,module,exports){
  32944. var Events = {
  32945. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  32946. };
  32947. module.exports = Events;
  32948. },{}],160:[function(require,module,exports){
  32949. module.exports = {
  32950. getLanguages : function () {
  32951. var languages = [];
  32952. for(var lang in this)
  32953. {
  32954. if(typeof this[lang] === "string")
  32955. languages.push(this[lang]);
  32956. }
  32957. return languages;
  32958. },
  32959. EN: "en",
  32960. BG: "bg",
  32961. DE: "de",
  32962. TR: "tr",
  32963. FR: "fr"
  32964. }
  32965. },{}],161:[function(require,module,exports){
  32966. var XMPPEvents = {
  32967. // Designates an event indicating that the connection to the XMPP server
  32968. // failed.
  32969. CONNECTION_FAILED: "xmpp.connection.failed",
  32970. // Designates an event indicating that the media (ICE) connection was
  32971. // interrupted. This should go to the RTC module.
  32972. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  32973. // Designates an event indicating that the media (ICE) connection was
  32974. // restored. This should go to the RTC module.
  32975. CONNECTION_RESTORED: "xmpp.connection.restored",
  32976. // Designates an event indicating that an offer (e.g. Jingle
  32977. // session-initiate) was received.
  32978. CALL_INCOMING: "xmpp.callincoming.jingle",
  32979. // Designates an event indicating that we were kicked from the XMPP MUC.
  32980. KICKED: "xmpp.kicked",
  32981. // Designates an event indicating that the userID for a specific JID has
  32982. // changed.
  32983. USER_ID_CHANGED: "xmpp.user_id_changed",
  32984. // Designates an event indicating that we have joined the XMPP MUC.
  32985. MUC_JOINED: "xmpp.muc_joined",
  32986. // Designates an event indicating that a participant joined the XMPP MUC.
  32987. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  32988. // Designates an event indicating that a participant left the XMPP MUC.
  32989. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  32990. // Designates an event indicating that the MUC role of a participant has
  32991. // changed.
  32992. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  32993. // Designates an event indicating that the XMPP MUC was destroyed.
  32994. MUC_DESTROYED: "xmpp.muc_destroyed",
  32995. // Designates an event indicating that the display name of a participant
  32996. // has changed.
  32997. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  32998. // Designates an event indicating that we received statistics from a
  32999. // participant in the MUC.
  33000. REMOTE_STATS: "xmpp.remote_stats",
  33001. // Designates an event indicating that our role in the XMPP MUC has changed.
  33002. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  33003. // Designates an event indicating that the subject of the XMPP MUC has
  33004. // changed.
  33005. SUBJECT_CHANGED: "xmpp.subject_changed",
  33006. // Designates an event indicating that an XMPP message in the MUC was
  33007. // received.
  33008. MESSAGE_RECEIVED: "xmpp.message_received",
  33009. // Designates an event indicating that we sent an XMPP message to the MUC.
  33010. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  33011. // Designates an event indicating that the video type (e.g. 'camera' or
  33012. // 'screen') for a participant has changed.
  33013. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  33014. // Designates an event indicating that a participant in the XMPP MUC has
  33015. // advertised that they have audio muted (or unmuted).
  33016. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  33017. // Designates an event indicating that a participant in the XMPP MUC has
  33018. // advertised that they have video muted (or unmuted).
  33019. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  33020. // Designates an event indicating that the focus has asked us to mute our
  33021. // audio.
  33022. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  33023. // Designates an event indicating that a moderator in the room changed the
  33024. // "start muted" settings for the conference.
  33025. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  33026. // Designates an event indicating that we should join the conference with
  33027. // audio and/or video muted.
  33028. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  33029. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  33030. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  33031. PASSWORD_REQUIRED: "xmpp.password_required",
  33032. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  33033. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  33034. ETHERPAD: "xmpp.etherpad",
  33035. DEVICE_AVAILABLE: "xmpp.device_available",
  33036. BRIDGE_DOWN: "xmpp.bridge_down",
  33037. PRESENCE_STATUS: "xmpp.presence_status",
  33038. RESERVATION_ERROR: "xmpp.room_reservation_error",
  33039. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  33040. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  33041. // TODO: only used in a hack, should probably be removed.
  33042. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  33043. // TODO: only used in a hack, should probably be removed.
  33044. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  33045. // TODO: only used in a hack, should probably be removed.
  33046. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  33047. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  33048. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  33049. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  33050. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  33051. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  33052. // xmpp is connected and obtained user media
  33053. READY_TO_JOIN: 'xmpp.ready_to_join'
  33054. };
  33055. module.exports = XMPPEvents;
  33056. },{}],162:[function(require,module,exports){
  33057. // Copyright Joyent, Inc. and other Node contributors.
  33058. //
  33059. // Permission is hereby granted, free of charge, to any person obtaining a
  33060. // copy of this software and associated documentation files (the
  33061. // "Software"), to deal in the Software without restriction, including
  33062. // without limitation the rights to use, copy, modify, merge, publish,
  33063. // distribute, sublicense, and/or sell copies of the Software, and to permit
  33064. // persons to whom the Software is furnished to do so, subject to the
  33065. // following conditions:
  33066. //
  33067. // The above copyright notice and this permission notice shall be included
  33068. // in all copies or substantial portions of the Software.
  33069. //
  33070. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  33071. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  33072. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  33073. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  33074. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  33075. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  33076. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  33077. function EventEmitter() {
  33078. this._events = this._events || {};
  33079. this._maxListeners = this._maxListeners || undefined;
  33080. }
  33081. module.exports = EventEmitter;
  33082. // Backwards-compat with node 0.10.x
  33083. EventEmitter.EventEmitter = EventEmitter;
  33084. EventEmitter.prototype._events = undefined;
  33085. EventEmitter.prototype._maxListeners = undefined;
  33086. // By default EventEmitters will print a warning if more than 10 listeners are
  33087. // added to it. This is a useful default which helps finding memory leaks.
  33088. EventEmitter.defaultMaxListeners = 10;
  33089. // Obviously not all Emitters should be limited to 10. This function allows
  33090. // that to be increased. Set to zero for unlimited.
  33091. EventEmitter.prototype.setMaxListeners = function(n) {
  33092. if (!isNumber(n) || n < 0 || isNaN(n))
  33093. throw TypeError('n must be a positive number');
  33094. this._maxListeners = n;
  33095. return this;
  33096. };
  33097. EventEmitter.prototype.emit = function(type) {
  33098. var er, handler, len, args, i, listeners;
  33099. if (!this._events)
  33100. this._events = {};
  33101. // If there is no 'error' event listener then throw.
  33102. if (type === 'error') {
  33103. if (!this._events.error ||
  33104. (isObject(this._events.error) && !this._events.error.length)) {
  33105. er = arguments[1];
  33106. if (er instanceof Error) {
  33107. throw er; // Unhandled 'error' event
  33108. }
  33109. throw TypeError('Uncaught, unspecified "error" event.');
  33110. }
  33111. }
  33112. handler = this._events[type];
  33113. if (isUndefined(handler))
  33114. return false;
  33115. if (isFunction(handler)) {
  33116. switch (arguments.length) {
  33117. // fast cases
  33118. case 1:
  33119. handler.call(this);
  33120. break;
  33121. case 2:
  33122. handler.call(this, arguments[1]);
  33123. break;
  33124. case 3:
  33125. handler.call(this, arguments[1], arguments[2]);
  33126. break;
  33127. // slower
  33128. default:
  33129. len = arguments.length;
  33130. args = new Array(len - 1);
  33131. for (i = 1; i < len; i++)
  33132. args[i - 1] = arguments[i];
  33133. handler.apply(this, args);
  33134. }
  33135. } else if (isObject(handler)) {
  33136. len = arguments.length;
  33137. args = new Array(len - 1);
  33138. for (i = 1; i < len; i++)
  33139. args[i - 1] = arguments[i];
  33140. listeners = handler.slice();
  33141. len = listeners.length;
  33142. for (i = 0; i < len; i++)
  33143. listeners[i].apply(this, args);
  33144. }
  33145. return true;
  33146. };
  33147. EventEmitter.prototype.addListener = function(type, listener) {
  33148. var m;
  33149. if (!isFunction(listener))
  33150. throw TypeError('listener must be a function');
  33151. if (!this._events)
  33152. this._events = {};
  33153. // To avoid recursion in the case that type === "newListener"! Before
  33154. // adding it to the listeners, first emit "newListener".
  33155. if (this._events.newListener)
  33156. this.emit('newListener', type,
  33157. isFunction(listener.listener) ?
  33158. listener.listener : listener);
  33159. if (!this._events[type])
  33160. // Optimize the case of one listener. Don't need the extra array object.
  33161. this._events[type] = listener;
  33162. else if (isObject(this._events[type]))
  33163. // If we've already got an array, just append.
  33164. this._events[type].push(listener);
  33165. else
  33166. // Adding the second element, need to change to array.
  33167. this._events[type] = [this._events[type], listener];
  33168. // Check for listener leak
  33169. if (isObject(this._events[type]) && !this._events[type].warned) {
  33170. var m;
  33171. if (!isUndefined(this._maxListeners)) {
  33172. m = this._maxListeners;
  33173. } else {
  33174. m = EventEmitter.defaultMaxListeners;
  33175. }
  33176. if (m && m > 0 && this._events[type].length > m) {
  33177. this._events[type].warned = true;
  33178. console.error('(node) warning: possible EventEmitter memory ' +
  33179. 'leak detected. %d listeners added. ' +
  33180. 'Use emitter.setMaxListeners() to increase limit.',
  33181. this._events[type].length);
  33182. if (typeof console.trace === 'function') {
  33183. // not supported in IE 10
  33184. console.trace();
  33185. }
  33186. }
  33187. }
  33188. return this;
  33189. };
  33190. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  33191. EventEmitter.prototype.once = function(type, listener) {
  33192. if (!isFunction(listener))
  33193. throw TypeError('listener must be a function');
  33194. var fired = false;
  33195. function g() {
  33196. this.removeListener(type, g);
  33197. if (!fired) {
  33198. fired = true;
  33199. listener.apply(this, arguments);
  33200. }
  33201. }
  33202. g.listener = listener;
  33203. this.on(type, g);
  33204. return this;
  33205. };
  33206. // emits a 'removeListener' event iff the listener was removed
  33207. EventEmitter.prototype.removeListener = function(type, listener) {
  33208. var list, position, length, i;
  33209. if (!isFunction(listener))
  33210. throw TypeError('listener must be a function');
  33211. if (!this._events || !this._events[type])
  33212. return this;
  33213. list = this._events[type];
  33214. length = list.length;
  33215. position = -1;
  33216. if (list === listener ||
  33217. (isFunction(list.listener) && list.listener === listener)) {
  33218. delete this._events[type];
  33219. if (this._events.removeListener)
  33220. this.emit('removeListener', type, listener);
  33221. } else if (isObject(list)) {
  33222. for (i = length; i-- > 0;) {
  33223. if (list[i] === listener ||
  33224. (list[i].listener && list[i].listener === listener)) {
  33225. position = i;
  33226. break;
  33227. }
  33228. }
  33229. if (position < 0)
  33230. return this;
  33231. if (list.length === 1) {
  33232. list.length = 0;
  33233. delete this._events[type];
  33234. } else {
  33235. list.splice(position, 1);
  33236. }
  33237. if (this._events.removeListener)
  33238. this.emit('removeListener', type, listener);
  33239. }
  33240. return this;
  33241. };
  33242. EventEmitter.prototype.removeAllListeners = function(type) {
  33243. var key, listeners;
  33244. if (!this._events)
  33245. return this;
  33246. // not listening for removeListener, no need to emit
  33247. if (!this._events.removeListener) {
  33248. if (arguments.length === 0)
  33249. this._events = {};
  33250. else if (this._events[type])
  33251. delete this._events[type];
  33252. return this;
  33253. }
  33254. // emit removeListener for all listeners on all events
  33255. if (arguments.length === 0) {
  33256. for (key in this._events) {
  33257. if (key === 'removeListener') continue;
  33258. this.removeAllListeners(key);
  33259. }
  33260. this.removeAllListeners('removeListener');
  33261. this._events = {};
  33262. return this;
  33263. }
  33264. listeners = this._events[type];
  33265. if (isFunction(listeners)) {
  33266. this.removeListener(type, listeners);
  33267. } else {
  33268. // LIFO order
  33269. while (listeners.length)
  33270. this.removeListener(type, listeners[listeners.length - 1]);
  33271. }
  33272. delete this._events[type];
  33273. return this;
  33274. };
  33275. EventEmitter.prototype.listeners = function(type) {
  33276. var ret;
  33277. if (!this._events || !this._events[type])
  33278. ret = [];
  33279. else if (isFunction(this._events[type]))
  33280. ret = [this._events[type]];
  33281. else
  33282. ret = this._events[type].slice();
  33283. return ret;
  33284. };
  33285. EventEmitter.listenerCount = function(emitter, type) {
  33286. var ret;
  33287. if (!emitter._events || !emitter._events[type])
  33288. ret = 0;
  33289. else if (isFunction(emitter._events[type]))
  33290. ret = 1;
  33291. else
  33292. ret = emitter._events[type].length;
  33293. return ret;
  33294. };
  33295. function isFunction(arg) {
  33296. return typeof arg === 'function';
  33297. }
  33298. function isNumber(arg) {
  33299. return typeof arg === 'number';
  33300. }
  33301. function isObject(arg) {
  33302. return typeof arg === 'object' && arg !== null;
  33303. }
  33304. function isUndefined(arg) {
  33305. return arg === void 0;
  33306. }
  33307. },{}],163:[function(require,module,exports){
  33308. // shim for using process in browser
  33309. var process = module.exports = {};
  33310. var queue = [];
  33311. var draining = false;
  33312. var currentQueue;
  33313. var queueIndex = -1;
  33314. function cleanUpNextTick() {
  33315. draining = false;
  33316. if (currentQueue.length) {
  33317. queue = currentQueue.concat(queue);
  33318. } else {
  33319. queueIndex = -1;
  33320. }
  33321. if (queue.length) {
  33322. drainQueue();
  33323. }
  33324. }
  33325. function drainQueue() {
  33326. if (draining) {
  33327. return;
  33328. }
  33329. var timeout = setTimeout(cleanUpNextTick);
  33330. draining = true;
  33331. var len = queue.length;
  33332. while(len) {
  33333. currentQueue = queue;
  33334. queue = [];
  33335. while (++queueIndex < len) {
  33336. currentQueue[queueIndex].run();
  33337. }
  33338. queueIndex = -1;
  33339. len = queue.length;
  33340. }
  33341. currentQueue = null;
  33342. draining = false;
  33343. clearTimeout(timeout);
  33344. }
  33345. process.nextTick = function (fun) {
  33346. var args = new Array(arguments.length - 1);
  33347. if (arguments.length > 1) {
  33348. for (var i = 1; i < arguments.length; i++) {
  33349. args[i - 1] = arguments[i];
  33350. }
  33351. }
  33352. queue.push(new Item(fun, args));
  33353. if (queue.length === 1 && !draining) {
  33354. setTimeout(drainQueue, 0);
  33355. }
  33356. };
  33357. // v8 likes predictible objects
  33358. function Item(fun, array) {
  33359. this.fun = fun;
  33360. this.array = array;
  33361. }
  33362. Item.prototype.run = function () {
  33363. this.fun.apply(null, this.array);
  33364. };
  33365. process.title = 'browser';
  33366. process.browser = true;
  33367. process.env = {};
  33368. process.argv = [];
  33369. process.version = ''; // empty string to avoid regexp issues
  33370. process.versions = {};
  33371. function noop() {}
  33372. process.on = noop;
  33373. process.addListener = noop;
  33374. process.once = noop;
  33375. process.off = noop;
  33376. process.removeListener = noop;
  33377. process.removeAllListeners = noop;
  33378. process.emit = noop;
  33379. process.binding = function (name) {
  33380. throw new Error('process.binding is not supported');
  33381. };
  33382. // TODO(shtylman)
  33383. process.cwd = function () { return '/' };
  33384. process.chdir = function (dir) {
  33385. throw new Error('process.chdir is not supported');
  33386. };
  33387. process.umask = function() { return 0; };
  33388. },{}]},{},[1])(1)
  33389. });