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 867KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.APP=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. // Copyright Joyent, Inc. and other Node contributors.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a
  5. // copy of this software and associated documentation files (the
  6. // "Software"), to deal in the Software without restriction, including
  7. // without limitation the rights to use, copy, modify, merge, publish,
  8. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9. // persons to whom the Software is furnished to do so, subject to the
  10. // following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included
  13. // in all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  18. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  20. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  21. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. function EventEmitter() {
  23. this._events = this._events || {};
  24. this._maxListeners = this._maxListeners || undefined;
  25. }
  26. module.exports = EventEmitter;
  27. // Backwards-compat with node 0.10.x
  28. EventEmitter.EventEmitter = EventEmitter;
  29. EventEmitter.prototype._events = undefined;
  30. EventEmitter.prototype._maxListeners = undefined;
  31. // By default EventEmitters will print a warning if more than 10 listeners are
  32. // added to it. This is a useful default which helps finding memory leaks.
  33. EventEmitter.defaultMaxListeners = 10;
  34. // Obviously not all Emitters should be limited to 10. This function allows
  35. // that to be increased. Set to zero for unlimited.
  36. EventEmitter.prototype.setMaxListeners = function(n) {
  37. if (!isNumber(n) || n < 0 || isNaN(n))
  38. throw TypeError('n must be a positive number');
  39. this._maxListeners = n;
  40. return this;
  41. };
  42. EventEmitter.prototype.emit = function(type) {
  43. var er, handler, len, args, i, listeners;
  44. if (!this._events)
  45. this._events = {};
  46. // If there is no 'error' event listener then throw.
  47. if (type === 'error') {
  48. if (!this._events.error ||
  49. (isObject(this._events.error) && !this._events.error.length)) {
  50. er = arguments[1];
  51. if (er instanceof Error) {
  52. throw er; // Unhandled 'error' event
  53. }
  54. throw TypeError('Uncaught, unspecified "error" event.');
  55. }
  56. }
  57. handler = this._events[type];
  58. if (isUndefined(handler))
  59. return false;
  60. if (isFunction(handler)) {
  61. switch (arguments.length) {
  62. // fast cases
  63. case 1:
  64. handler.call(this);
  65. break;
  66. case 2:
  67. handler.call(this, arguments[1]);
  68. break;
  69. case 3:
  70. handler.call(this, arguments[1], arguments[2]);
  71. break;
  72. // slower
  73. default:
  74. len = arguments.length;
  75. args = new Array(len - 1);
  76. for (i = 1; i < len; i++)
  77. args[i - 1] = arguments[i];
  78. handler.apply(this, args);
  79. }
  80. } else if (isObject(handler)) {
  81. len = arguments.length;
  82. args = new Array(len - 1);
  83. for (i = 1; i < len; i++)
  84. args[i - 1] = arguments[i];
  85. listeners = handler.slice();
  86. len = listeners.length;
  87. for (i = 0; i < len; i++)
  88. listeners[i].apply(this, args);
  89. }
  90. return true;
  91. };
  92. EventEmitter.prototype.addListener = function(type, listener) {
  93. var m;
  94. if (!isFunction(listener))
  95. throw TypeError('listener must be a function');
  96. if (!this._events)
  97. this._events = {};
  98. // To avoid recursion in the case that type === "newListener"! Before
  99. // adding it to the listeners, first emit "newListener".
  100. if (this._events.newListener)
  101. this.emit('newListener', type,
  102. isFunction(listener.listener) ?
  103. listener.listener : listener);
  104. if (!this._events[type])
  105. // Optimize the case of one listener. Don't need the extra array object.
  106. this._events[type] = listener;
  107. else if (isObject(this._events[type]))
  108. // If we've already got an array, just append.
  109. this._events[type].push(listener);
  110. else
  111. // Adding the second element, need to change to array.
  112. this._events[type] = [this._events[type], listener];
  113. // Check for listener leak
  114. if (isObject(this._events[type]) && !this._events[type].warned) {
  115. var m;
  116. if (!isUndefined(this._maxListeners)) {
  117. m = this._maxListeners;
  118. } else {
  119. m = EventEmitter.defaultMaxListeners;
  120. }
  121. if (m && m > 0 && this._events[type].length > m) {
  122. this._events[type].warned = true;
  123. console.error('(node) warning: possible EventEmitter memory ' +
  124. 'leak detected. %d listeners added. ' +
  125. 'Use emitter.setMaxListeners() to increase limit.',
  126. this._events[type].length);
  127. if (typeof console.trace === 'function') {
  128. // not supported in IE 10
  129. console.trace();
  130. }
  131. }
  132. }
  133. return this;
  134. };
  135. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  136. EventEmitter.prototype.once = function(type, listener) {
  137. if (!isFunction(listener))
  138. throw TypeError('listener must be a function');
  139. var fired = false;
  140. function g() {
  141. this.removeListener(type, g);
  142. if (!fired) {
  143. fired = true;
  144. listener.apply(this, arguments);
  145. }
  146. }
  147. g.listener = listener;
  148. this.on(type, g);
  149. return this;
  150. };
  151. // emits a 'removeListener' event iff the listener was removed
  152. EventEmitter.prototype.removeListener = function(type, listener) {
  153. var list, position, length, i;
  154. if (!isFunction(listener))
  155. throw TypeError('listener must be a function');
  156. if (!this._events || !this._events[type])
  157. return this;
  158. list = this._events[type];
  159. length = list.length;
  160. position = -1;
  161. if (list === listener ||
  162. (isFunction(list.listener) && list.listener === listener)) {
  163. delete this._events[type];
  164. if (this._events.removeListener)
  165. this.emit('removeListener', type, listener);
  166. } else if (isObject(list)) {
  167. for (i = length; i-- > 0;) {
  168. if (list[i] === listener ||
  169. (list[i].listener && list[i].listener === listener)) {
  170. position = i;
  171. break;
  172. }
  173. }
  174. if (position < 0)
  175. return this;
  176. if (list.length === 1) {
  177. list.length = 0;
  178. delete this._events[type];
  179. } else {
  180. list.splice(position, 1);
  181. }
  182. if (this._events.removeListener)
  183. this.emit('removeListener', type, listener);
  184. }
  185. return this;
  186. };
  187. EventEmitter.prototype.removeAllListeners = function(type) {
  188. var key, listeners;
  189. if (!this._events)
  190. return this;
  191. // not listening for removeListener, no need to emit
  192. if (!this._events.removeListener) {
  193. if (arguments.length === 0)
  194. this._events = {};
  195. else if (this._events[type])
  196. delete this._events[type];
  197. return this;
  198. }
  199. // emit removeListener for all listeners on all events
  200. if (arguments.length === 0) {
  201. for (key in this._events) {
  202. if (key === 'removeListener') continue;
  203. this.removeAllListeners(key);
  204. }
  205. this.removeAllListeners('removeListener');
  206. this._events = {};
  207. return this;
  208. }
  209. listeners = this._events[type];
  210. if (isFunction(listeners)) {
  211. this.removeListener(type, listeners);
  212. } else {
  213. // LIFO order
  214. while (listeners.length)
  215. this.removeListener(type, listeners[listeners.length - 1]);
  216. }
  217. delete this._events[type];
  218. return this;
  219. };
  220. EventEmitter.prototype.listeners = function(type) {
  221. var ret;
  222. if (!this._events || !this._events[type])
  223. ret = [];
  224. else if (isFunction(this._events[type]))
  225. ret = [this._events[type]];
  226. else
  227. ret = this._events[type].slice();
  228. return ret;
  229. };
  230. EventEmitter.listenerCount = function(emitter, type) {
  231. var ret;
  232. if (!emitter._events || !emitter._events[type])
  233. ret = 0;
  234. else if (isFunction(emitter._events[type]))
  235. ret = 1;
  236. else
  237. ret = emitter._events[type].length;
  238. return ret;
  239. };
  240. function isFunction(arg) {
  241. return typeof arg === 'function';
  242. }
  243. function isNumber(arg) {
  244. return typeof arg === 'number';
  245. }
  246. function isObject(arg) {
  247. return typeof arg === 'object' && arg !== null;
  248. }
  249. function isUndefined(arg) {
  250. return arg === void 0;
  251. }
  252. },{}],2:[function(require,module,exports){
  253. /* jshint -W117 */
  254. /* application specific logic */
  255. var APP =
  256. {
  257. init: function () {
  258. this.UI = require("./modules/UI/UI");
  259. this.API = require("./modules/API/API");
  260. this.connectionquality = require("./modules/connectionquality/connectionquality");
  261. this.statistics = require("./modules/statistics/statistics");
  262. this.RTC = require("./modules/RTC/RTC");
  263. this.simulcast = require("./modules/simulcast/simulcast");
  264. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  265. this.xmpp = require("./modules/xmpp/xmpp");
  266. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  267. this.translation = require("./modules/translation/translation");
  268. }
  269. };
  270. function init() {
  271. APP.RTC.start();
  272. APP.xmpp.start(APP.UI.getCredentials());
  273. APP.statistics.start();
  274. APP.connectionquality.init();
  275. // Set default desktop sharing method
  276. APP.desktopsharing.init();
  277. APP.keyboardshortcut.init();
  278. }
  279. $(document).ready(function () {
  280. APP.init();
  281. APP.translation.init();
  282. if(APP.API.isEnabled())
  283. APP.API.init();
  284. APP.UI.start(init);
  285. });
  286. $(window).bind('beforeunload', function () {
  287. if(APP.API.isEnabled())
  288. APP.API.dispose();
  289. });
  290. module.exports = APP;
  291. },{"./modules/API/API":3,"./modules/RTC/RTC":7,"./modules/UI/UI":9,"./modules/connectionquality/connectionquality":35,"./modules/desktopsharing/desktopsharing":36,"./modules/keyboardshortcut/keyboardshortcut":37,"./modules/simulcast/simulcast":43,"./modules/statistics/statistics":46,"./modules/translation/translation":47,"./modules/xmpp/xmpp":61}],3:[function(require,module,exports){
  292. /**
  293. * Implements API class that communicates with external api class
  294. * and provides interface to access Jitsi Meet features by external
  295. * applications that embed Jitsi Meet
  296. */
  297. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  298. /**
  299. * List of the available commands.
  300. * @type {{
  301. * displayName: inputDisplayNameHandler,
  302. * muteAudio: toggleAudio,
  303. * muteVideo: toggleVideo,
  304. * filmStrip: toggleFilmStrip
  305. * }}
  306. */
  307. var commands =
  308. {
  309. displayName: APP.UI.inputDisplayNameHandler,
  310. muteAudio: APP.UI.toggleAudio,
  311. muteVideo: APP.UI.toggleVideo,
  312. toggleFilmStrip: APP.UI.toggleFilmStrip,
  313. toggleChat: APP.UI.toggleChat,
  314. toggleContactList: APP.UI.toggleContactList
  315. };
  316. /**
  317. * Maps the supported events and their status
  318. * (true it the event is enabled and false if it is disabled)
  319. * @type {{
  320. * incomingMessage: boolean,
  321. * outgoingMessage: boolean,
  322. * displayNameChange: boolean,
  323. * participantJoined: boolean,
  324. * participantLeft: boolean
  325. * }}
  326. */
  327. var events =
  328. {
  329. incomingMessage: false,
  330. outgoingMessage:false,
  331. displayNameChange: false,
  332. participantJoined: false,
  333. participantLeft: false
  334. };
  335. var displayName = {};
  336. /**
  337. * Processes commands from external applicaiton.
  338. * @param message the object with the command
  339. */
  340. function processCommand(message)
  341. {
  342. if(message.action != "execute")
  343. {
  344. console.error("Unknown action of the message");
  345. return;
  346. }
  347. for(var key in message)
  348. {
  349. if(commands[key])
  350. commands[key].apply(null, message[key]);
  351. }
  352. }
  353. /**
  354. * Processes events objects from external applications
  355. * @param event the event
  356. */
  357. function processEvent(event) {
  358. if(!event.action)
  359. {
  360. console.error("Event with no action is received.");
  361. return;
  362. }
  363. var i = 0;
  364. switch(event.action)
  365. {
  366. case "add":
  367. for(; i < event.events.length; i++)
  368. {
  369. events[event.events[i]] = true;
  370. }
  371. break;
  372. case "remove":
  373. for(; i < event.events.length; i++)
  374. {
  375. events[event.events[i]] = false;
  376. }
  377. break;
  378. default:
  379. console.error("Unknown action for event.");
  380. }
  381. }
  382. /**
  383. * Sends message to the external application.
  384. * @param object
  385. */
  386. function sendMessage(object) {
  387. window.parent.postMessage(JSON.stringify(object), "*");
  388. }
  389. /**
  390. * Processes a message event from the external application
  391. * @param event the message event
  392. */
  393. function processMessage(event)
  394. {
  395. var message;
  396. try {
  397. message = JSON.parse(event.data);
  398. } catch (e) {}
  399. if(!message.type)
  400. return;
  401. switch (message.type)
  402. {
  403. case "command":
  404. processCommand(message);
  405. break;
  406. case "event":
  407. processEvent(message);
  408. break;
  409. default:
  410. console.error("Unknown type of the message");
  411. return;
  412. }
  413. }
  414. function setupListeners() {
  415. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, function (from) {
  416. API.triggerEvent("participantJoined", {jid: from});
  417. });
  418. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid) {
  419. if (from != myjid)
  420. API.triggerEvent("incomingMessage",
  421. {"from": from, "nick": nick, "message": txt});
  422. });
  423. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, function (jid) {
  424. API.triggerEvent("participantLeft", {jid: jid});
  425. });
  426. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  427. name = displayName[jid];
  428. if(!name || name != newDisplayName) {
  429. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  430. displayName[jid] = newDisplayName;
  431. }
  432. });
  433. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  434. APP.API.triggerEvent("outgoingMessage", {"message": body});
  435. });
  436. }
  437. var API = {
  438. /**
  439. * Check whether the API should be enabled or not.
  440. * @returns {boolean}
  441. */
  442. isEnabled: function () {
  443. var hash = location.hash;
  444. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  445. return true;
  446. return false;
  447. },
  448. /**
  449. * Initializes the APIConnector. Setups message event listeners that will
  450. * receive information from external applications that embed Jitsi Meet.
  451. * It also sends a message to the external application that APIConnector
  452. * is initialized.
  453. */
  454. init: function () {
  455. if (window.addEventListener)
  456. {
  457. window.addEventListener('message',
  458. processMessage, false);
  459. }
  460. else
  461. {
  462. window.attachEvent('onmessage', processMessage);
  463. }
  464. sendMessage({type: "system", loaded: true});
  465. setupListeners();
  466. },
  467. /**
  468. * Checks whether the event is enabled ot not.
  469. * @param name the name of the event.
  470. * @returns {*}
  471. */
  472. isEventEnabled: function (name) {
  473. return events[name];
  474. },
  475. /**
  476. * Sends event object to the external application that has been subscribed
  477. * for that event.
  478. * @param name the name event
  479. * @param object data associated with the event
  480. */
  481. triggerEvent: function (name, object) {
  482. if(this.isEnabled() && this.isEventEnabled(name))
  483. sendMessage({
  484. type: "event", action: "result", event: name, result: object});
  485. },
  486. /**
  487. * Removes the listeners.
  488. */
  489. dispose: function () {
  490. if(window.removeEventListener)
  491. {
  492. window.removeEventListener("message",
  493. processMessage, false);
  494. }
  495. else
  496. {
  497. window.detachEvent('onmessage', processMessage);
  498. }
  499. }
  500. };
  501. module.exports = API;
  502. },{"../../service/xmpp/XMPPEvents":89}],4:[function(require,module,exports){
  503. /* global Strophe, updateLargeVideo, focusedVideoSrc*/
  504. // cache datachannels to avoid garbage collection
  505. // https://code.google.com/p/chromium/issues/detail?id=405545
  506. var RTCEvents = require("../../service/RTC/RTCEvents");
  507. var _dataChannels = [];
  508. var eventEmitter = null;
  509. var DataChannels =
  510. {
  511. /**
  512. * Callback triggered by PeerConnection when new data channel is opened
  513. * on the bridge.
  514. * @param event the event info object.
  515. */
  516. onDataChannel: function (event)
  517. {
  518. var dataChannel = event.channel;
  519. dataChannel.onopen = function () {
  520. console.info("Data channel opened by the Videobridge!", dataChannel);
  521. // Code sample for sending string and/or binary data
  522. // Sends String message to the bridge
  523. //dataChannel.send("Hello bridge!");
  524. // Sends 12 bytes binary message to the bridge
  525. //dataChannel.send(new ArrayBuffer(12));
  526. // when the data channel becomes available, tell the bridge about video
  527. // selections so that it can do adaptive simulcast,
  528. // we want the notification to trigger even if userJid is undefined,
  529. // or null.
  530. var userJid = APP.UI.getLargeVideoState().userResourceJid;
  531. // we want the notification to trigger even if userJid is undefined,
  532. // or null.
  533. onSelectedEndpointChanged(userJid);
  534. };
  535. dataChannel.onerror = function (error) {
  536. console.error("Data Channel Error:", error, dataChannel);
  537. };
  538. dataChannel.onmessage = function (event) {
  539. var data = event.data;
  540. // JSON
  541. var obj;
  542. try {
  543. obj = JSON.parse(data);
  544. }
  545. catch (e) {
  546. console.error(
  547. "Failed to parse data channel message as JSON: ",
  548. data,
  549. dataChannel);
  550. }
  551. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  552. var colibriClass = obj.colibriClass;
  553. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  554. // Endpoint ID from the Videobridge.
  555. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  556. console.info(
  557. "Data channel new dominant speaker event: ",
  558. dominantSpeakerEndpoint);
  559. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  560. }
  561. else if ("InLastNChangeEvent" === colibriClass)
  562. {
  563. var oldValue = obj.oldValue;
  564. var newValue = obj.newValue;
  565. // Make sure that oldValue and newValue are of type boolean.
  566. var type;
  567. if ((type = typeof oldValue) !== 'boolean') {
  568. if (type === 'string') {
  569. oldValue = (oldValue == "true");
  570. } else {
  571. oldValue = new Boolean(oldValue).valueOf();
  572. }
  573. }
  574. if ((type = typeof newValue) !== 'boolean') {
  575. if (type === 'string') {
  576. newValue = (newValue == "true");
  577. } else {
  578. newValue = new Boolean(newValue).valueOf();
  579. }
  580. }
  581. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  582. }
  583. else if ("LastNEndpointsChangeEvent" === colibriClass)
  584. {
  585. // The new/latest list of last-n endpoint IDs.
  586. var lastNEndpoints = obj.lastNEndpoints;
  587. // The list of endpoint IDs which are entering the list of
  588. // last-n at this time i.e. were not in the old list of last-n
  589. // endpoint IDs.
  590. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  591. var stream = obj.stream;
  592. console.log(
  593. "Data channel new last-n event: ",
  594. lastNEndpoints, endpointsEnteringLastN, obj);
  595. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  596. lastNEndpoints, endpointsEnteringLastN, obj);
  597. }
  598. else if ("SimulcastLayersChangedEvent" === colibriClass)
  599. {
  600. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGED,
  601. obj.endpointSimulcastLayers);
  602. }
  603. else if ("SimulcastLayersChangingEvent" === colibriClass)
  604. {
  605. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGING,
  606. obj.endpointSimulcastLayers);
  607. }
  608. else if ("StartSimulcastLayerEvent" === colibriClass)
  609. {
  610. eventEmitter.emit(RTCEvents.SIMULCAST_START, obj.simulcastLayer);
  611. }
  612. else if ("StopSimulcastLayerEvent" === colibriClass)
  613. {
  614. eventEmitter.emit(RTCEvents.SIMULCAST_STOP, obj.simulcastLayer);
  615. }
  616. else
  617. {
  618. console.debug("Data channel JSON-formatted message: ", obj);
  619. }
  620. }
  621. };
  622. dataChannel.onclose = function ()
  623. {
  624. console.info("The Data Channel closed", dataChannel);
  625. var idx = _dataChannels.indexOf(dataChannel);
  626. if (idx > -1)
  627. _dataChannels = _dataChannels.splice(idx, 1);
  628. };
  629. _dataChannels.push(dataChannel);
  630. },
  631. /**
  632. * Binds "ondatachannel" event listener to given PeerConnection instance.
  633. * @param peerConnection WebRTC peer connection instance.
  634. */
  635. init: function (peerConnection, emitter) {
  636. if(!config.openSctp)
  637. return;
  638. peerConnection.ondatachannel = this.onDataChannel;
  639. eventEmitter = emitter;
  640. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  641. // Although it's not a requirement to open separate channels from both bridge
  642. // and peer as single channel can be used for sending and receiving data.
  643. // So either channel opened by the bridge or the one opened here is enough
  644. // for communication with the bridge.
  645. /*var dataChannelOptions =
  646. {
  647. reliable: true
  648. };
  649. var dataChannel
  650. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  651. // Can be used only when is in open state
  652. dataChannel.onopen = function ()
  653. {
  654. dataChannel.send("My channel !!!");
  655. };
  656. dataChannel.onmessage = function (event)
  657. {
  658. var msgData = event.data;
  659. console.info("Got My Data Channel Message:", msgData, dataChannel);
  660. };*/
  661. },
  662. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  663. handlePinnedEndpointEvent: onPinnedEndpointChanged
  664. };
  665. function onSelectedEndpointChanged(userResource)
  666. {
  667. console.log('selected endpoint changed: ', userResource);
  668. if (_dataChannels && _dataChannels.length != 0)
  669. {
  670. _dataChannels.some(function (dataChannel) {
  671. if (dataChannel.readyState == 'open')
  672. {
  673. console.log('sending selected endpoint changed '
  674. + 'notification to the bridge: ', userResource);
  675. dataChannel.send(JSON.stringify({
  676. 'colibriClass': 'SelectedEndpointChangedEvent',
  677. 'selectedEndpoint':
  678. (!userResource || userResource === null)?
  679. null : userResource
  680. }));
  681. return true;
  682. }
  683. });
  684. }
  685. }
  686. function onPinnedEndpointChanged(userResource)
  687. {
  688. console.log('pinned endpoint changed: ', userResource);
  689. if (_dataChannels && _dataChannels.length != 0)
  690. {
  691. _dataChannels.some(function (dataChannel) {
  692. if (dataChannel.readyState == 'open')
  693. {
  694. dataChannel.send(JSON.stringify({
  695. 'colibriClass': 'PinnedEndpointChangedEvent',
  696. 'pinnedEndpoint':
  697. (!userResource || userResource == null)?
  698. null : userResource
  699. }));
  700. return true;
  701. }
  702. });
  703. }
  704. }
  705. module.exports = DataChannels;
  706. },{"../../service/RTC/RTCEvents":81}],5:[function(require,module,exports){
  707. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  708. function LocalStream(stream, type, eventEmitter, videoType)
  709. {
  710. this.stream = stream;
  711. this.eventEmitter = eventEmitter;
  712. this.type = type;
  713. this.videoType = videoType;
  714. var self = this;
  715. if(type == "audio")
  716. {
  717. this.getTracks = function () {
  718. return self.stream.getAudioTracks();
  719. };
  720. }
  721. else
  722. {
  723. this.getTracks = function () {
  724. return self.stream.getVideoTracks();
  725. };
  726. }
  727. this.stream.onended = function()
  728. {
  729. self.streamEnded();
  730. };
  731. }
  732. LocalStream.prototype.streamEnded = function () {
  733. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  734. }
  735. LocalStream.prototype.getOriginalStream = function()
  736. {
  737. return this.stream;
  738. }
  739. LocalStream.prototype.isAudioStream = function () {
  740. return (this.stream.getAudioTracks() && this.stream.getAudioTracks().length > 0);
  741. };
  742. LocalStream.prototype.mute = function()
  743. {
  744. var ismuted = false;
  745. var tracks = this.getTracks();
  746. for (var idx = 0; idx < tracks.length; idx++) {
  747. ismuted = !tracks[idx].enabled;
  748. tracks[idx].enabled = ismuted;
  749. }
  750. return ismuted;
  751. };
  752. LocalStream.prototype.setMute = function(mute)
  753. {
  754. var tracks = this.getTracks();
  755. for (var idx = 0; idx < tracks.length; idx++) {
  756. tracks[idx].enabled = mute;
  757. }
  758. };
  759. LocalStream.prototype.isMuted = function () {
  760. var tracks = [];
  761. if(this.type == "audio")
  762. {
  763. tracks = this.stream.getAudioTracks();
  764. }
  765. else
  766. {
  767. tracks = this.stream.getVideoTracks();
  768. }
  769. for (var idx = 0; idx < tracks.length; idx++) {
  770. if(tracks[idx].enabled)
  771. return false;
  772. }
  773. return true;
  774. }
  775. LocalStream.prototype.getId = function () {
  776. return this.stream.getTracks()[0].id;
  777. }
  778. module.exports = LocalStream;
  779. },{"../../service/RTC/StreamEventTypes.js":83}],6:[function(require,module,exports){
  780. ////These lines should be uncommented when require works in app.js
  781. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  782. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  783. /**
  784. * Creates a MediaStream object for the given data, session id and ssrc.
  785. * It is a wrapper class for the MediaStream.
  786. *
  787. * @param data the data object from which we obtain the stream,
  788. * the peerjid, etc.
  789. * @param sid the session id
  790. * @param ssrc the ssrc corresponding to this MediaStream
  791. *
  792. * @constructor
  793. */
  794. function MediaStream(data, sid, ssrc, browser) {
  795. // XXX(gp) to minimize headaches in the future, we should build our
  796. // abstractions around tracks and not streams. ORTC is track based API.
  797. // Mozilla expects m-lines to represent media tracks.
  798. //
  799. // Practically, what I'm saying is that we should have a MediaTrack class
  800. // and not a MediaStream class.
  801. //
  802. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  803. // a track might have an associated RTX and FEC sources.
  804. this.sid = sid;
  805. this.stream = data.stream;
  806. this.peerjid = data.peerjid;
  807. this.ssrc = ssrc;
  808. this.type = (this.stream.getVideoTracks().length > 0)?
  809. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  810. this.videoType = null;
  811. this.muted = false;
  812. if(browser == RTCBrowserType.RTC_BROWSER_FIREFOX)
  813. {
  814. if (!this.getVideoTracks)
  815. this.getVideoTracks = function () { return []; };
  816. if (!this.getAudioTracks)
  817. this.getAudioTracks = function () { return []; };
  818. }
  819. }
  820. MediaStream.prototype.getOriginalStream = function()
  821. {
  822. return this.stream;
  823. }
  824. MediaStream.prototype.setMute = function (value)
  825. {
  826. this.stream.muted = value;
  827. this.muted = value;
  828. }
  829. module.exports = MediaStream;
  830. },{"../../service/RTC/MediaStreamTypes":79,"../../service/RTC/RTCBrowserType.js":80}],7:[function(require,module,exports){
  831. var EventEmitter = require("events");
  832. var RTCUtils = require("./RTCUtils.js");
  833. var LocalStream = require("./LocalStream.js");
  834. var DataChannels = require("./DataChannels");
  835. var MediaStream = require("./MediaStream.js");
  836. var DesktopSharingEventTypes
  837. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  838. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  839. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  840. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  841. var UIEvents = require("../../service/UI/UIEvents");
  842. var eventEmitter = new EventEmitter();
  843. var RTC = {
  844. rtcUtils: null,
  845. localStreams: [],
  846. remoteStreams: {},
  847. localAudio: null,
  848. localVideo: null,
  849. addStreamListener: function (listener, eventType) {
  850. eventEmitter.on(eventType, listener);
  851. },
  852. addListener: function (type, listener) {
  853. eventEmitter.on(type, listener);
  854. },
  855. removeStreamListener: function (listener, eventType) {
  856. if(!(eventType instanceof StreamEventTypes))
  857. throw "Illegal argument";
  858. eventEmitter.removeListener(eventType, listener);
  859. },
  860. createLocalStream: function (stream, type, change) {
  861. var localStream = new LocalStream(stream, type, eventEmitter);
  862. //in firefox we have only one stream object
  863. if(this.localStreams.length == 0 ||
  864. this.localStreams[0].getOriginalStream() != stream)
  865. this.localStreams.push(localStream);
  866. if(type == "audio")
  867. {
  868. this.localAudio = localStream;
  869. }
  870. else
  871. {
  872. this.localVideo = localStream;
  873. }
  874. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  875. if(change)
  876. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  877. eventEmitter.emit(eventType, localStream);
  878. return localStream;
  879. },
  880. removeLocalStream: function (stream) {
  881. for(var i = 0; i < this.localStreams.length; i++)
  882. {
  883. if(this.localStreams[i].getOriginalStream() === stream) {
  884. delete this.localStreams[i];
  885. return;
  886. }
  887. }
  888. },
  889. createRemoteStream: function (data, sid, thessrc) {
  890. var remoteStream = new MediaStream(data, sid, thessrc,
  891. this.getBrowserType());
  892. var jid = data.peerjid || APP.xmpp.myJid();
  893. if(!this.remoteStreams[jid]) {
  894. this.remoteStreams[jid] = {};
  895. }
  896. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  897. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  898. console.debug("ADD remote stream ", remoteStream.type, " ", jid, " ", thessrc);
  899. return remoteStream;
  900. },
  901. getBrowserType: function () {
  902. return this.rtcUtils.browser;
  903. },
  904. getPCConstraints: function () {
  905. return this.rtcUtils.pc_constraints;
  906. },
  907. getUserMediaWithConstraints:function(um, success_callback,
  908. failure_callback, resolution,
  909. bandwidth, fps, desktopStream)
  910. {
  911. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  912. failure_callback, resolution, bandwidth, fps, desktopStream);
  913. },
  914. attachMediaStream: function (element, stream) {
  915. this.rtcUtils.attachMediaStream(element, stream);
  916. },
  917. getStreamID: function (stream) {
  918. return this.rtcUtils.getStreamID(stream);
  919. },
  920. getVideoSrc: function (element) {
  921. return this.rtcUtils.getVideoSrc(element);
  922. },
  923. setVideoSrc: function (element, src) {
  924. this.rtcUtils.setVideoSrc(element, src);
  925. },
  926. dispose: function() {
  927. if (this.rtcUtils) {
  928. this.rtcUtils = null;
  929. }
  930. },
  931. stop: function () {
  932. this.dispose();
  933. },
  934. start: function () {
  935. var self = this;
  936. APP.desktopsharing.addListener(
  937. function (stream, isUsingScreenStream, callback) {
  938. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  939. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  940. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  941. for(var i = 0; i < changedStreams.length; i++) {
  942. var type = changedStreams[i].type;
  943. if (type != "audio") {
  944. var peerStreams = self.remoteStreams[jid];
  945. if(!peerStreams)
  946. continue;
  947. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  948. if(!videoStream)
  949. continue;
  950. videoStream.videoType = changedStreams[i].type;
  951. }
  952. }
  953. });
  954. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  955. DataChannels.init(event.peerconnection, eventEmitter);
  956. });
  957. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  958. DataChannels.handleSelectedEndpointEvent);
  959. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  960. DataChannels.handlePinnedEndpointEvent);
  961. this.rtcUtils = new RTCUtils(this);
  962. this.rtcUtils.obtainAudioAndVideoPermissions();
  963. },
  964. muteRemoteVideoStream: function (jid, value) {
  965. var stream;
  966. if(this.remoteStreams[jid] &&
  967. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  968. {
  969. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  970. }
  971. if(!stream)
  972. return false;
  973. if (value != stream.muted) {
  974. stream.setMute(value);
  975. return true;
  976. }
  977. return false;
  978. },
  979. switchVideoStreams: function (new_stream) {
  980. this.localVideo.stream = new_stream;
  981. this.localStreams = [];
  982. //in firefox we have only one stream object
  983. if (this.localAudio.getOriginalStream() != new_stream)
  984. this.localStreams.push(this.localAudio);
  985. this.localStreams.push(this.localVideo);
  986. },
  987. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  988. var oldStream = this.localVideo.getOriginalStream();
  989. var type = (isUsingScreenStream? "screen" : "video");
  990. this.localVideo = this.createLocalStream(stream, "video", true, type);
  991. // Stop the stream to trigger onended event for old stream
  992. oldStream.stop();
  993. APP.xmpp.switchStreams(stream, oldStream,callback);
  994. },
  995. /**
  996. * Checks if video identified by given src is desktop stream.
  997. * @param videoSrc eg.
  998. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  999. * @returns {boolean}
  1000. */
  1001. isVideoSrcDesktop: function (jid) {
  1002. if(!jid)
  1003. return false;
  1004. var isDesktop = false;
  1005. var stream = null;
  1006. if (APP.xmpp.myJid() &&
  1007. APP.xmpp.myResource() === jid) {
  1008. // local video
  1009. stream = this.localVideo;
  1010. } else {
  1011. var peerStreams = this.remoteStreams[jid];
  1012. if(!peerStreams)
  1013. return false;
  1014. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  1015. }
  1016. if(stream)
  1017. isDesktop = (stream.videoType === "screen");
  1018. return isDesktop;
  1019. }
  1020. };
  1021. module.exports = RTC;
  1022. },{"../../service/RTC/MediaStreamTypes":79,"../../service/RTC/StreamEventTypes.js":83,"../../service/UI/UIEvents":84,"../../service/desktopsharing/DesktopSharingEventTypes":87,"../../service/xmpp/XMPPEvents":89,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCUtils.js":8,"events":1}],8:[function(require,module,exports){
  1023. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  1024. var Resolutions = require("../../service/RTC/Resolutions");
  1025. var currentResolution = null;
  1026. function getPreviousResolution(resolution) {
  1027. if(!Resolutions[resolution])
  1028. return null;
  1029. var order = Resolutions[resolution].order;
  1030. var res = null;
  1031. var resName = null;
  1032. for(var i in Resolutions)
  1033. {
  1034. var tmp = Resolutions[i];
  1035. if(res == null || (res.order < tmp.order && tmp.order < order))
  1036. {
  1037. resName = i;
  1038. res = tmp;
  1039. }
  1040. }
  1041. return resName;
  1042. }
  1043. function setResolutionConstraints(constraints, resolution, isAndroid)
  1044. {
  1045. if (resolution && !constraints.video || isAndroid) {
  1046. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1047. }
  1048. if(Resolutions[resolution])
  1049. {
  1050. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1051. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1052. }
  1053. else
  1054. {
  1055. if (isAndroid) {
  1056. constraints.video.mandatory.minWidth = 320;
  1057. constraints.video.mandatory.minHeight = 240;
  1058. constraints.video.mandatory.maxFrameRate = 15;
  1059. }
  1060. }
  1061. if (constraints.video.mandatory.minWidth)
  1062. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  1063. if (constraints.video.mandatory.minHeight)
  1064. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  1065. }
  1066. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1067. {
  1068. var constraints = {audio: false, video: false};
  1069. if (um.indexOf('video') >= 0) {
  1070. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1071. }
  1072. if (um.indexOf('audio') >= 0) {
  1073. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  1074. }
  1075. if (um.indexOf('screen') >= 0) {
  1076. constraints.video = {
  1077. mandatory: {
  1078. chromeMediaSource: "screen",
  1079. googLeakyBucket: true,
  1080. maxWidth: window.screen.width,
  1081. maxHeight: window.screen.height,
  1082. maxFrameRate: 3
  1083. },
  1084. optional: []
  1085. };
  1086. }
  1087. if (um.indexOf('desktop') >= 0) {
  1088. constraints.video = {
  1089. mandatory: {
  1090. chromeMediaSource: "desktop",
  1091. chromeMediaSourceId: desktopStream,
  1092. googLeakyBucket: true,
  1093. maxWidth: window.screen.width,
  1094. maxHeight: window.screen.height,
  1095. maxFrameRate: 3
  1096. },
  1097. optional: []
  1098. };
  1099. }
  1100. if (constraints.audio) {
  1101. // if it is good enough for hangouts...
  1102. constraints.audio.optional.push(
  1103. {googEchoCancellation: true},
  1104. {googAutoGainControl: true},
  1105. {googNoiseSupression: true},
  1106. {googHighpassFilter: true},
  1107. {googNoisesuppression2: true},
  1108. {googEchoCancellation2: true},
  1109. {googAutoGainControl2: true}
  1110. );
  1111. }
  1112. if (constraints.video) {
  1113. constraints.video.optional.push(
  1114. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  1115. );
  1116. if (um.indexOf('video') >= 0) {
  1117. constraints.video.optional.push(
  1118. {googLeakyBucket: true}
  1119. );
  1120. }
  1121. }
  1122. if (um.indexOf('video') >= 0) {
  1123. setResolutionConstraints(constraints, resolution, isAndroid);
  1124. }
  1125. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  1126. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  1127. constraints.video.optional.push({bandwidth: bandwidth});
  1128. }
  1129. if (fps) { // for some cameras it might be necessary to request 30fps
  1130. // so they choose 30fps mjpg over 10fps yuy2
  1131. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  1132. constraints.video.mandatory.minFrameRate = fps;
  1133. }
  1134. return constraints;
  1135. }
  1136. function RTCUtils(RTCService)
  1137. {
  1138. this.service = RTCService;
  1139. if (navigator.mozGetUserMedia) {
  1140. console.log('This appears to be Firefox');
  1141. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1142. if (version >= 22) {
  1143. this.peerconnection = mozRTCPeerConnection;
  1144. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1145. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1146. this.pc_constraints = {};
  1147. this.attachMediaStream = function (element, stream) {
  1148. element[0].mozSrcObject = stream;
  1149. element[0].play();
  1150. };
  1151. this.getStreamID = function (stream) {
  1152. var tracks = stream.getVideoTracks();
  1153. if(!tracks || tracks.length == 0)
  1154. {
  1155. tracks = stream.getAudioTracks();
  1156. }
  1157. return tracks[0].id.replace(/[\{,\}]/g,"");
  1158. };
  1159. this.getVideoSrc = function (element) {
  1160. return element.mozSrcObject;
  1161. };
  1162. this.setVideoSrc = function (element, src) {
  1163. element.mozSrcObject = src;
  1164. };
  1165. RTCSessionDescription = mozRTCSessionDescription;
  1166. RTCIceCandidate = mozRTCIceCandidate;
  1167. }
  1168. } else if (navigator.webkitGetUserMedia) {
  1169. console.log('This appears to be Chrome');
  1170. this.peerconnection = webkitRTCPeerConnection;
  1171. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  1172. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1173. this.attachMediaStream = function (element, stream) {
  1174. element.attr('src', webkitURL.createObjectURL(stream));
  1175. };
  1176. this.getStreamID = function (stream) {
  1177. // streams from FF endpoints have the characters '{' and '}'
  1178. // that make jQuery choke.
  1179. return stream.id.replace(/[\{,\}]/g,"");
  1180. };
  1181. this.getVideoSrc = function (element) {
  1182. return element.getAttribute("src");
  1183. };
  1184. this.setVideoSrc = function (element, src) {
  1185. element.setAttribute("src", src);
  1186. };
  1187. // DTLS should now be enabled by default but..
  1188. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1189. if (navigator.userAgent.indexOf('Android') != -1) {
  1190. this.pc_constraints = {}; // disable DTLS on Android
  1191. }
  1192. if (!webkitMediaStream.prototype.getVideoTracks) {
  1193. webkitMediaStream.prototype.getVideoTracks = function () {
  1194. return this.videoTracks;
  1195. };
  1196. }
  1197. if (!webkitMediaStream.prototype.getAudioTracks) {
  1198. webkitMediaStream.prototype.getAudioTracks = function () {
  1199. return this.audioTracks;
  1200. };
  1201. }
  1202. }
  1203. else
  1204. {
  1205. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  1206. window.location.href = 'webrtcrequired.html';
  1207. return;
  1208. }
  1209. if (this.browser !== RTCBrowserType.RTC_BROWSER_CHROME &&
  1210. config.enableFirefoxSupport !== true) {
  1211. window.location.href = 'chromeonly.html';
  1212. return;
  1213. }
  1214. }
  1215. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1216. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1217. desktopStream)
  1218. {
  1219. currentResolution = resolution;
  1220. // Check if we are running on Android device
  1221. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1222. var constraints = getConstraints(
  1223. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1224. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  1225. try {
  1226. if (config.enableSimulcast
  1227. && constraints.video
  1228. && constraints.video.chromeMediaSource !== 'screen'
  1229. && constraints.video.chromeMediaSource !== 'desktop'
  1230. && !isAndroid
  1231. // We currently do not support FF, as it doesn't have multistream support.
  1232. && !isFF) {
  1233. APP.simulcast.getUserMedia(constraints, function (stream) {
  1234. console.log('onUserMediaSuccess');
  1235. success_callback(stream);
  1236. },
  1237. function (error) {
  1238. console.warn('Failed to get access to local media. Error ', error);
  1239. if (failure_callback) {
  1240. failure_callback(error);
  1241. }
  1242. });
  1243. } else {
  1244. this.getUserMedia(constraints,
  1245. function (stream) {
  1246. console.log('onUserMediaSuccess');
  1247. success_callback(stream);
  1248. },
  1249. function (error) {
  1250. console.warn('Failed to get access to local media. Error ',
  1251. error, constraints);
  1252. if (failure_callback) {
  1253. failure_callback(error);
  1254. }
  1255. });
  1256. }
  1257. } catch (e) {
  1258. console.error('GUM failed: ', e);
  1259. if(failure_callback) {
  1260. failure_callback(e);
  1261. }
  1262. }
  1263. };
  1264. /**
  1265. * We ask for audio and video combined stream in order to get permissions and
  1266. * not to ask twice.
  1267. */
  1268. RTCUtils.prototype.obtainAudioAndVideoPermissions = function() {
  1269. var self = this;
  1270. // Get AV
  1271. this.getUserMediaWithConstraints(
  1272. ['audio', 'video'],
  1273. function (stream) {
  1274. self.successCallback(stream);
  1275. },
  1276. function (error) {
  1277. self.errorCallback(error);
  1278. },
  1279. config.resolution || '360');
  1280. }
  1281. RTCUtils.prototype.successCallback = function (stream) {
  1282. console.log('got', stream, stream.getAudioTracks().length,
  1283. stream.getVideoTracks().length);
  1284. this.handleLocalStream(stream);
  1285. };
  1286. RTCUtils.prototype.errorCallback = function (error) {
  1287. var self = this;
  1288. console.error('failed to obtain audio/video stream - trying audio only', error);
  1289. var resolution = getPreviousResolution(currentResolution);
  1290. if(typeof error == "object" && error.constraintName && error.name
  1291. && (error.name == "ConstraintNotSatisfiedError" ||
  1292. error.name == "OverconstrainedError") &&
  1293. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1294. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1295. && resolution != null)
  1296. {
  1297. self.getUserMediaWithConstraints(['audio', 'video'],
  1298. function (stream) {
  1299. return self.successCallback(stream);
  1300. }, function (error) {
  1301. return self.errorCallback(error);
  1302. }, resolution);
  1303. }
  1304. else
  1305. {
  1306. self.getUserMediaWithConstraints(
  1307. ['audio'],
  1308. function (stream) {
  1309. return self.successCallback(stream);
  1310. },
  1311. function (error) {
  1312. console.error('failed to obtain audio/video stream - stop',
  1313. error);
  1314. APP.UI.messageHandler.showError("dialog.error", "Error",
  1315. "dialog.failedpermissions",
  1316. "Failed to obtain permissions to use the local microphone " +
  1317. "and/or camera.");
  1318. }
  1319. );
  1320. }
  1321. }
  1322. RTCUtils.prototype.handleLocalStream = function(stream)
  1323. {
  1324. if(window.webkitMediaStream)
  1325. {
  1326. var audioStream = new webkitMediaStream();
  1327. var videoStream = new webkitMediaStream();
  1328. var audioTracks = stream.getAudioTracks();
  1329. var videoTracks = stream.getVideoTracks();
  1330. for (var i = 0; i < audioTracks.length; i++) {
  1331. audioStream.addTrack(audioTracks[i]);
  1332. }
  1333. this.service.createLocalStream(audioStream, "audio");
  1334. for (i = 0; i < videoTracks.length; i++) {
  1335. videoStream.addTrack(videoTracks[i]);
  1336. }
  1337. this.service.createLocalStream(videoStream, "video");
  1338. }
  1339. else
  1340. {//firefox
  1341. this.service.createLocalStream(stream, "stream");
  1342. }
  1343. };
  1344. module.exports = RTCUtils;
  1345. },{"../../service/RTC/RTCBrowserType.js":80,"../../service/RTC/Resolutions":82}],9:[function(require,module,exports){
  1346. var UI = {};
  1347. var VideoLayout = require("./videolayout/VideoLayout.js");
  1348. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1349. var Prezi = require("./prezi/Prezi.js");
  1350. var Etherpad = require("./etherpad/Etherpad.js");
  1351. var Chat = require("./side_pannels/chat/Chat.js");
  1352. var Toolbar = require("./toolbars/Toolbar");
  1353. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1354. var BottomToolbar = require("./toolbars/BottomToolbar");
  1355. var ContactList = require("./side_pannels/contactlist/ContactList");
  1356. var Avatar = require("./avatar/Avatar");
  1357. var EventEmitter = require("events");
  1358. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1359. var Settings = require("./../settings/Settings");
  1360. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1361. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1362. UI.messageHandler = require("./util/MessageHandler");
  1363. var messageHandler = UI.messageHandler;
  1364. var Authentication = require("./authentication/Authentication");
  1365. var UIUtil = require("./util/UIUtil");
  1366. var NicknameHandler = require("./util/NicknameHandler");
  1367. var CQEvents = require("../../service/connectionquality/CQEvents");
  1368. var DesktopSharingEventTypes
  1369. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1370. var RTCEvents = require("../../service/RTC/RTCEvents");
  1371. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1372. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1373. var eventEmitter = new EventEmitter();
  1374. var roomName = null;
  1375. function setupPrezi()
  1376. {
  1377. $("#reloadPresentationLink").click(function()
  1378. {
  1379. Prezi.reloadPresentation();
  1380. });
  1381. }
  1382. function setupChat()
  1383. {
  1384. Chat.init();
  1385. $("#toggle_smileys").click(function() {
  1386. Chat.toggleSmileys();
  1387. });
  1388. }
  1389. function setupToolbars() {
  1390. Toolbar.init(UI);
  1391. Toolbar.setupButtonsFromConfig();
  1392. BottomToolbar.init();
  1393. }
  1394. function streamHandler(stream) {
  1395. switch (stream.type)
  1396. {
  1397. case "audio":
  1398. VideoLayout.changeLocalAudio(stream);
  1399. break;
  1400. case "video":
  1401. VideoLayout.changeLocalVideo(stream);
  1402. break;
  1403. case "stream":
  1404. VideoLayout.changeLocalStream(stream);
  1405. break;
  1406. }
  1407. }
  1408. function onDisposeConference(unload) {
  1409. Toolbar.showAuthenticateButton(false);
  1410. };
  1411. function onDisplayNameChanged(jid, displayName) {
  1412. ContactList.onDisplayNameChange(jid, displayName);
  1413. SettingsMenu.onDisplayNameChange(jid, displayName);
  1414. VideoLayout.onDisplayNameChanged(jid, displayName);
  1415. }
  1416. function registerListeners() {
  1417. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1418. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1419. APP.RTC.addStreamListener(function (stream) {
  1420. VideoLayout.onRemoteStreamAdded(stream);
  1421. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1422. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1423. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1424. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1425. });
  1426. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1427. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1428. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1429. endpointsEnteringLastN, stream);
  1430. });
  1431. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  1432. function (endpointSimulcastLayers) {
  1433. VideoLayout.onSimulcastLayersChanged(endpointSimulcastLayers);
  1434. });
  1435. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGING,
  1436. function (endpointSimulcastLayers) {
  1437. VideoLayout.onSimulcastLayersChanging(endpointSimulcastLayers);
  1438. });
  1439. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1440. {
  1441. var resourceJid;
  1442. if(jid === APP.statistics.LOCAL_JID)
  1443. {
  1444. resourceJid = AudioLevels.LOCAL_LEVEL;
  1445. if(APP.RTC.localAudio.isMuted())
  1446. {
  1447. audioLevel = 0;
  1448. }
  1449. }
  1450. else
  1451. {
  1452. resourceJid = Strophe.getResourceFromJid(jid);
  1453. }
  1454. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1455. UI.getLargeVideoState().userResourceJid);
  1456. });
  1457. APP.desktopsharing.addListener(function () {
  1458. ToolbarToggler.showDesktopSharingButton();
  1459. }, DesktopSharingEventTypes.INIT);
  1460. APP.desktopsharing.addListener(
  1461. Toolbar.changeDesktopSharingButtonState,
  1462. DesktopSharingEventTypes.SWITCHING_DONE);
  1463. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1464. VideoLayout.updateLocalConnectionStats);
  1465. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1466. VideoLayout.updateConnectionStats);
  1467. APP.connectionquality.addListener(CQEvents.STOP,
  1468. VideoLayout.onStatsStop);
  1469. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1470. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1471. messageHandler.openMessageDialog("dialog.sessTerminated", "Session Terminated",
  1472. "dialog.kickMessage", "Ouch! You have been kicked out of the meet!");
  1473. });
  1474. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1475. //FIXME: use Session Terminated from translation, but
  1476. // 'reason' text comes from XMPP packet and is not translated
  1477. messageHandler.openDialog(
  1478. "Session Terminated", reason, true, {},
  1479. function (event, value, message, formVals)
  1480. {
  1481. return false;
  1482. }
  1483. );
  1484. });
  1485. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1486. messageHandler.showError("dialog.error","Error",
  1487. "dialog.bridgeUnavailable",
  1488. "Jitsi Videobridge is currently unavailable. Please try again later!");
  1489. });
  1490. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1491. Avatar.setUserAvatar(from, id);
  1492. });
  1493. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  1494. for(stream in changedStreams)
  1495. {
  1496. // might need to update the direction if participant just went from sendrecv to recvonly
  1497. if (stream.type === 'video' || stream.type === 'screen') {
  1498. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1499. switch (stream.direction) {
  1500. case 'sendrecv':
  1501. el.show();
  1502. break;
  1503. case 'recvonly':
  1504. el.hide();
  1505. // FIXME: Check if we have to change large video
  1506. //VideoLayout.updateLargeVideo(el);
  1507. break;
  1508. }
  1509. }
  1510. }
  1511. });
  1512. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1513. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1514. APP.xmpp.addListener(XMPPEvents.LOCALROLE_CHANGED, onLocalRoleChange);
  1515. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, onMucEntered);
  1516. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1517. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1518. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1519. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1520. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1521. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordReqiured);
  1522. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1523. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1524. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, onAuthenticationRequired);
  1525. }
  1526. /**
  1527. * Mutes/unmutes the local video.
  1528. *
  1529. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1530. * @param options an object which specifies optional arguments such as the
  1531. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1532. * specifies whether the method was initiated in response to a user command (in
  1533. * contrast to an automatic decision taken by the application logic)
  1534. */
  1535. function setVideoMute(mute, options) {
  1536. APP.xmpp.setVideoMute(
  1537. mute,
  1538. function (mute) {
  1539. var video = $('#video');
  1540. var communicativeClass = "icon-camera";
  1541. var muteClass = "icon-camera icon-camera-disabled";
  1542. if (mute) {
  1543. video.removeClass(communicativeClass);
  1544. video.addClass(muteClass);
  1545. } else {
  1546. video.removeClass(muteClass);
  1547. video.addClass(communicativeClass);
  1548. }
  1549. },
  1550. options);
  1551. }
  1552. function bindEvents()
  1553. {
  1554. /**
  1555. * Resizes and repositions videos in full screen mode.
  1556. */
  1557. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1558. function () {
  1559. VideoLayout.resizeLargeVideoContainer();
  1560. VideoLayout.positionLarge();
  1561. }
  1562. );
  1563. $(window).resize(function () {
  1564. VideoLayout.resizeLargeVideoContainer();
  1565. VideoLayout.positionLarge();
  1566. });
  1567. }
  1568. UI.start = function (init) {
  1569. document.title = interfaceConfig.APP_NAME;
  1570. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1571. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1572. {
  1573. $("#videoconference_page").hide();
  1574. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1575. setupWelcomePage();
  1576. return;
  1577. }
  1578. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1579. var leftWatermarkDiv
  1580. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1581. leftWatermarkDiv.css({display: 'block'});
  1582. leftWatermarkDiv.parent().get(0).href
  1583. = interfaceConfig.JITSI_WATERMARK_LINK;
  1584. }
  1585. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1586. var rightWatermarkDiv
  1587. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1588. rightWatermarkDiv.css({display: 'block'});
  1589. rightWatermarkDiv.parent().get(0).href
  1590. = interfaceConfig.BRAND_WATERMARK_LINK;
  1591. rightWatermarkDiv.get(0).style.backgroundImage
  1592. = "url(images/rightwatermark.png)";
  1593. }
  1594. if (interfaceConfig.SHOW_POWERED_BY) {
  1595. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1596. }
  1597. $("#welcome_page").hide();
  1598. VideoLayout.resizeLargeVideoContainer();
  1599. $("#videospace").mousemove(function () {
  1600. return ToolbarToggler.showToolbar();
  1601. });
  1602. // Set the defaults for prompt dialogs.
  1603. jQuery.prompt.setDefaults({persistent: false});
  1604. VideoLayout.init(eventEmitter);
  1605. AudioLevels.init();
  1606. NicknameHandler.init(eventEmitter);
  1607. registerListeners();
  1608. bindEvents();
  1609. setupPrezi();
  1610. setupToolbars();
  1611. setupChat();
  1612. document.title = interfaceConfig.APP_NAME;
  1613. $("#downloadlog").click(function (event) {
  1614. dump(event.target);
  1615. });
  1616. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1617. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1618. {
  1619. $("#videoconference_page").hide();
  1620. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1621. setupWelcomePage();
  1622. return;
  1623. }
  1624. $("#welcome_page").hide();
  1625. document.getElementById('largeVideo').volume = 0;
  1626. if (!$('#settings').is(':visible')) {
  1627. console.log('init');
  1628. init();
  1629. } else {
  1630. loginInfo.onsubmit = function (e) {
  1631. if (e.preventDefault) e.preventDefault();
  1632. $('#settings').hide();
  1633. init();
  1634. };
  1635. }
  1636. toastr.options = {
  1637. "closeButton": true,
  1638. "debug": false,
  1639. "positionClass": "notification-bottom-right",
  1640. "onclick": null,
  1641. "showDuration": "300",
  1642. "hideDuration": "1000",
  1643. "timeOut": "2000",
  1644. "extendedTimeOut": "1000",
  1645. "showEasing": "swing",
  1646. "hideEasing": "linear",
  1647. "showMethod": "fadeIn",
  1648. "hideMethod": "fadeOut",
  1649. "reposition": function() {
  1650. if(PanelToggler.isVisible()) {
  1651. $("#toast-container").addClass("notification-bottom-right-center");
  1652. } else {
  1653. $("#toast-container").removeClass("notification-bottom-right-center");
  1654. }
  1655. },
  1656. "newestOnTop": false
  1657. };
  1658. SettingsMenu.init();
  1659. };
  1660. function chatAddError(errorMessage, originalText)
  1661. {
  1662. return Chat.chatAddError(errorMessage, originalText);
  1663. };
  1664. function chatSetSubject(text)
  1665. {
  1666. return Chat.chatSetSubject(text);
  1667. };
  1668. function updateChatConversation(from, displayName, message) {
  1669. return Chat.updateChatConversation(from, displayName, message);
  1670. };
  1671. function onMucJoined(jid, info) {
  1672. Toolbar.updateRoomUrl(window.location.href);
  1673. document.getElementById('localNick').appendChild(
  1674. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  1675. );
  1676. var settings = Settings.getSettings();
  1677. // Add myself to the contact list.
  1678. ContactList.addContact(jid, settings.email || settings.uid);
  1679. // Once we've joined the muc show the toolbar
  1680. ToolbarToggler.showToolbar();
  1681. var displayName = !config.displayJids
  1682. ? info.displayName : Strophe.getResourceFromJid(jid);
  1683. if (displayName)
  1684. onDisplayNameChanged('localVideoContainer', displayName + ' (me)');
  1685. }
  1686. function initEtherpad(name) {
  1687. Etherpad.init(name);
  1688. };
  1689. function onMucLeft(jid) {
  1690. console.log('left.muc', jid);
  1691. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1692. '>.displayname').html();
  1693. messageHandler.notify(displayName,'notify.somebody', "Somebody",
  1694. 'disconnected',
  1695. 'notify.disconnected', "disconnected");
  1696. // Need to call this with a slight delay, otherwise the element couldn't be
  1697. // found for some reason.
  1698. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1699. window.setTimeout(function () {
  1700. var container = document.getElementById(
  1701. 'participant_' + Strophe.getResourceFromJid(jid));
  1702. if (container) {
  1703. ContactList.removeContact(jid);
  1704. VideoLayout.removeConnectionIndicator(jid);
  1705. // hide here, wait for video to close before removing
  1706. $(container).hide();
  1707. VideoLayout.resizeThumbnails();
  1708. }
  1709. }, 10);
  1710. VideoLayout.participantLeft(jid);
  1711. };
  1712. function onLocalRoleChange(jid, info, pres, isModerator)
  1713. {
  1714. console.info("My role changed, new role: " + info.role);
  1715. onModeratorStatusChanged(isModerator);
  1716. VideoLayout.showModeratorIndicator();
  1717. if (isModerator) {
  1718. Authentication.closeAuthenticationWindow();
  1719. messageHandler.notify(null, "notify.me",
  1720. 'Me', 'connected', "notify.moderator",
  1721. 'Moderator rights granted !');
  1722. }
  1723. }
  1724. function onModeratorStatusChanged(isModerator) {
  1725. Toolbar.showSipCallButton(isModerator);
  1726. Toolbar.showRecordingButton(
  1727. isModerator); //&&
  1728. // FIXME:
  1729. // Recording visible if
  1730. // there are at least 2(+ 1 focus) participants
  1731. //Object.keys(connection.emuc.members).length >= 3);
  1732. if (isModerator && config.etherpad_base) {
  1733. Etherpad.init();
  1734. }
  1735. };
  1736. function onPasswordReqiured(callback) {
  1737. // password is required
  1738. Toolbar.lockLockButton();
  1739. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1740. message += APP.translation.translateString(
  1741. "dialog.passwordRequired", null, "Password required");
  1742. message += '</h2>' +
  1743. '<input id="lockKey" type="text" placeholder="password" autofocus>';
  1744. messageHandler.openTwoButtonDialog(null, null, null, message,
  1745. true,
  1746. "dialog.Ok",
  1747. function (e, v, m, f) {},
  1748. function (event) {
  1749. document.getElementById('lockKey').focus();
  1750. },
  1751. function (e, v, m, f) {
  1752. if (v) {
  1753. var lockKey = document.getElementById('lockKey');
  1754. if (lockKey.value !== null) {
  1755. Toolbar.setSharedKey(lockKey.value);
  1756. callback(lockKey.value);
  1757. }
  1758. }
  1759. }
  1760. );
  1761. }
  1762. function onMucEntered(jid, id, displayName) {
  1763. messageHandler.notify(displayName,'notify.somebody', "Somebody",
  1764. 'connected',
  1765. 'notify.connected', "connected");
  1766. // Add Peer's container
  1767. VideoLayout.ensurePeerContainerExists(jid,id);
  1768. }
  1769. function onMucPresenceStatus( jid, info) {
  1770. VideoLayout.setPresenceStatus(
  1771. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1772. }
  1773. function onMucRoleChanged(role, displayName) {
  1774. VideoLayout.showModeratorIndicator();
  1775. if (role === 'moderator') {
  1776. var messageKey, messageOptions = {};
  1777. var lDisplayName = displayName;
  1778. if (!lDisplayName) {
  1779. lDisplayName = 'Somebody';
  1780. messageKey = "notify.grantedToUnknown";
  1781. }
  1782. else
  1783. {
  1784. messageKey = "notify.grantedTo";
  1785. messageOptions = {to: displayName};
  1786. }
  1787. messageHandler.notify(
  1788. displayName,'notify.somebody', "Somebody",
  1789. 'connected', messageKey,
  1790. 'Moderator rights granted to ' + lDisplayName + '!',
  1791. messageOptions);
  1792. }
  1793. }
  1794. function onAuthenticationRequired(intervalCallback) {
  1795. Authentication.openAuthenticationDialog(
  1796. roomName, intervalCallback, function () {
  1797. Toolbar.authenticateClicked();
  1798. });
  1799. };
  1800. function onLastNChanged(oldValue, newValue) {
  1801. if (config.muteLocalVideoIfNotInLastN) {
  1802. setVideoMute(!newValue, { 'byUser': false });
  1803. }
  1804. }
  1805. UI.toggleSmileys = function () {
  1806. Chat.toggleSmileys();
  1807. };
  1808. UI.getSettings = function () {
  1809. return Settings.getSettings();
  1810. };
  1811. UI.toggleFilmStrip = function () {
  1812. return BottomToolbar.toggleFilmStrip();
  1813. };
  1814. UI.toggleChat = function () {
  1815. return BottomToolbar.toggleChat();
  1816. };
  1817. UI.toggleContactList = function () {
  1818. return BottomToolbar.toggleContactList();
  1819. };
  1820. UI.inputDisplayNameHandler = function (value) {
  1821. VideoLayout.inputDisplayNameHandler(value);
  1822. };
  1823. UI.getLargeVideoState = function()
  1824. {
  1825. return VideoLayout.getLargeVideoState();
  1826. };
  1827. UI.generateRoomName = function() {
  1828. if(roomName)
  1829. return roomName;
  1830. var roomnode = null;
  1831. var path = window.location.pathname;
  1832. // determinde the room node from the url
  1833. // TODO: just the roomnode or the whole bare jid?
  1834. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1835. // custom function might be responsible for doing the pushstate
  1836. roomnode = config.getroomnode(path);
  1837. } else {
  1838. /* fall back to default strategy
  1839. * this is making assumptions about how the URL->room mapping happens.
  1840. * It currently assumes deployment at root, with a rewrite like the
  1841. * following one (for nginx):
  1842. location ~ ^/([a-zA-Z0-9]+)$ {
  1843. rewrite ^/(.*)$ / break;
  1844. }
  1845. */
  1846. if (path.length > 1) {
  1847. roomnode = path.substr(1).toLowerCase();
  1848. } else {
  1849. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1850. roomnode = word.toLowerCase();
  1851. window.history.pushState('VideoChat',
  1852. 'Room: ' + word, window.location.pathname + word);
  1853. }
  1854. }
  1855. roomName = roomnode + '@' + config.hosts.muc;
  1856. return roomName;
  1857. };
  1858. UI.connectionIndicatorShowMore = function(id)
  1859. {
  1860. return VideoLayout.connectionIndicators[id].showMore();
  1861. };
  1862. UI.getCredentials = function () {
  1863. var settings = this.getSettings();
  1864. return {
  1865. bosh: document.getElementById('boshURL').value,
  1866. password: document.getElementById('password').value,
  1867. jid: document.getElementById('jid').value,
  1868. email: settings.email,
  1869. displayName: settings.displayName,
  1870. uid: settings.uid
  1871. };
  1872. };
  1873. UI.disableConnect = function () {
  1874. document.getElementById('connect').disabled = true;
  1875. };
  1876. UI.showLoginPopup = function(callback)
  1877. {
  1878. console.log('password is required');
  1879. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1880. message += APP.translation.translateString(
  1881. "dialog.passwordRequired", null, "Password required");
  1882. message += '</h2>' +
  1883. '<input id="passwordrequired.username" type="text" ' +
  1884. 'placeholder="user@domain.net" autofocus>' +
  1885. '<input id="passwordrequired.password" ' +
  1886. 'type="password" placeholder="user password">';
  1887. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  1888. true,
  1889. "dialog.Ok",
  1890. function (e, v, m, f) {
  1891. if (v) {
  1892. var username = document.getElementById('passwordrequired.username');
  1893. var password = document.getElementById('passwordrequired.password');
  1894. if (username.value !== null && password.value != null) {
  1895. callback(username.value, password.value);
  1896. }
  1897. }
  1898. },
  1899. function (event) {
  1900. document.getElementById('passwordrequired.username').focus();
  1901. }
  1902. );
  1903. }
  1904. UI.checkForNicknameAndJoin = function () {
  1905. Authentication.closeAuthenticationDialog();
  1906. Authentication.stopInterval();
  1907. var nick = null;
  1908. if (config.useNicks) {
  1909. nick = window.prompt('Your nickname (optional)');
  1910. }
  1911. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1912. };
  1913. function dump(elem, filename) {
  1914. elem = elem.parentNode;
  1915. elem.download = filename || 'meetlog.json';
  1916. elem.href = 'data:application/json;charset=utf-8,\n';
  1917. var data = APP.xmpp.populateData();
  1918. var metadata = {};
  1919. metadata.time = new Date();
  1920. metadata.url = window.location.href;
  1921. metadata.ua = navigator.userAgent;
  1922. var log = APP.xmpp.getLogger();
  1923. if (log) {
  1924. metadata.xmpp = log;
  1925. }
  1926. data.metadata = metadata;
  1927. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1928. return false;
  1929. }
  1930. UI.getRoomName = function () {
  1931. return roomName;
  1932. };
  1933. /**
  1934. * Mutes/unmutes the local video.
  1935. */
  1936. UI.toggleVideo = function () {
  1937. UIUtil.buttonClick("#video", "icon-camera icon-camera-disabled");
  1938. setVideoMute(!APP.RTC.localVideo.isMuted());
  1939. };
  1940. /**
  1941. * Mutes / unmutes audio for the local participant.
  1942. */
  1943. UI.toggleAudio = function() {
  1944. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  1945. };
  1946. /**
  1947. * Sets muted audio state for the local participant.
  1948. */
  1949. UI.setAudioMuted = function (mute) {
  1950. if(!APP.xmpp.setAudioMute(mute, function () {
  1951. VideoLayout.showLocalAudioIndicator(mute);
  1952. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1953. }))
  1954. {
  1955. // We still click the button.
  1956. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1957. return;
  1958. }
  1959. }
  1960. UI.addListener = function (type, listener) {
  1961. eventEmitter.on(type, listener);
  1962. }
  1963. UI.clickOnVideo = function (videoNumber) {
  1964. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  1965. if (remoteVideos.length > videoNumber) {
  1966. remoteVideos[videoNumber].click();
  1967. }
  1968. }
  1969. //Used by torture
  1970. UI.showToolbar = function () {
  1971. return ToolbarToggler.showToolbar();
  1972. }
  1973. //Used by torture
  1974. UI.dockToolbar = function (isDock) {
  1975. return ToolbarToggler.dockToolbar(isDock);
  1976. }
  1977. module.exports = UI;
  1978. },{"../../service/RTC/RTCEvents":81,"../../service/RTC/StreamEventTypes":83,"../../service/connectionquality/CQEvents":86,"../../service/desktopsharing/DesktopSharingEventTypes":87,"../../service/xmpp/XMPPEvents":89,"./../settings/Settings":38,"./audio_levels/AudioLevels.js":10,"./authentication/Authentication":12,"./avatar/Avatar":13,"./etherpad/Etherpad.js":14,"./prezi/Prezi.js":15,"./side_pannels/SidePanelToggler":17,"./side_pannels/chat/Chat.js":18,"./side_pannels/contactlist/ContactList":22,"./side_pannels/settings/SettingsMenu":23,"./toolbars/BottomToolbar":24,"./toolbars/Toolbar":25,"./toolbars/ToolbarToggler":26,"./util/MessageHandler":28,"./util/NicknameHandler":29,"./util/UIUtil":30,"./videolayout/VideoLayout.js":32,"./welcome_page/RoomnameGenerator":33,"./welcome_page/WelcomePage":34,"events":1}],10:[function(require,module,exports){
  1979. var CanvasUtil = require("./CanvasUtils");
  1980. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  1981. function initActiveSpeakerAudioLevels() {
  1982. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  1983. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  1984. // Draw a circle.
  1985. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  1986. // Add a shadow around the circle
  1987. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  1988. ASDrawContext.shadowOffsetX = 0;
  1989. ASDrawContext.shadowOffsetY = 0;
  1990. }
  1991. /**
  1992. * The audio Levels plugin.
  1993. */
  1994. var AudioLevels = (function(my) {
  1995. var audioLevelCanvasCache = {};
  1996. my.LOCAL_LEVEL = 'local';
  1997. my.init = function () {
  1998. initActiveSpeakerAudioLevels();
  1999. }
  2000. /**
  2001. * Updates the audio level canvas for the given peerJid. If the canvas
  2002. * didn't exist we create it.
  2003. */
  2004. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  2005. var resourceJid = null;
  2006. var videoSpanId = null;
  2007. if (!peerJid)
  2008. videoSpanId = 'localVideoContainer';
  2009. else {
  2010. resourceJid = Strophe.getResourceFromJid(peerJid);
  2011. videoSpanId = 'participant_' + resourceJid;
  2012. }
  2013. var videoSpan = document.getElementById(videoSpanId);
  2014. if (!videoSpan) {
  2015. if (resourceJid)
  2016. console.error("No video element for jid", resourceJid);
  2017. else
  2018. console.error("No video element for local video.");
  2019. return;
  2020. }
  2021. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  2022. var videoSpaceWidth = $('#remoteVideos').width();
  2023. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  2024. var thumbnailWidth = thumbnailSize[0];
  2025. var thumbnailHeight = thumbnailSize[1];
  2026. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  2027. audioLevelCanvas = document.createElement('canvas');
  2028. audioLevelCanvas.className = "audiolevel";
  2029. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  2030. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  2031. resizeAudioLevelCanvas( audioLevelCanvas,
  2032. thumbnailWidth,
  2033. thumbnailHeight);
  2034. videoSpan.appendChild(audioLevelCanvas);
  2035. } else {
  2036. audioLevelCanvas = audioLevelCanvas.get(0);
  2037. resizeAudioLevelCanvas( audioLevelCanvas,
  2038. thumbnailWidth,
  2039. thumbnailHeight);
  2040. }
  2041. };
  2042. /**
  2043. * Updates the audio level UI for the given resourceJid.
  2044. *
  2045. * @param resourceJid the resource jid indicating the video element for
  2046. * which we draw the audio level
  2047. * @param audioLevel the newAudio level to render
  2048. */
  2049. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  2050. drawAudioLevelCanvas(resourceJid, audioLevel);
  2051. var videoSpanId = getVideoSpanId(resourceJid);
  2052. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  2053. if (!audioLevelCanvas)
  2054. return;
  2055. var drawContext = audioLevelCanvas.getContext('2d');
  2056. var canvasCache = audioLevelCanvasCache[resourceJid];
  2057. drawContext.clearRect (0, 0,
  2058. audioLevelCanvas.width, audioLevelCanvas.height);
  2059. drawContext.drawImage(canvasCache, 0, 0);
  2060. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  2061. if(!APP.xmpp.myJid()) {
  2062. return;
  2063. }
  2064. resourceJid = APP.xmpp.myResource();
  2065. }
  2066. if(resourceJid === largeVideoResourceJid) {
  2067. window.requestAnimationFrame(function () {
  2068. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  2069. });
  2070. }
  2071. };
  2072. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  2073. if($("#activeSpeaker").css("visibility") == "hidden")
  2074. return;
  2075. ASDrawContext.clearRect(0, 0, 300, 300);
  2076. if(audioLevel == 0)
  2077. return;
  2078. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  2079. // Fill the shape.
  2080. ASDrawContext.fill();
  2081. };
  2082. /**
  2083. * Resizes the given audio level canvas to match the given thumbnail size.
  2084. */
  2085. function resizeAudioLevelCanvas(audioLevelCanvas,
  2086. thumbnailWidth,
  2087. thumbnailHeight) {
  2088. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  2089. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  2090. }
  2091. /**
  2092. * Draws the audio level canvas into the cached canvas object.
  2093. *
  2094. * @param resourceJid the resource jid indicating the video element for
  2095. * which we draw the audio level
  2096. * @param audioLevel the newAudio level to render
  2097. */
  2098. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  2099. if (!audioLevelCanvasCache[resourceJid]) {
  2100. var videoSpanId = getVideoSpanId(resourceJid);
  2101. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  2102. /*
  2103. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  2104. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  2105. * error. Since audio levels are frequently updated, the errors have
  2106. * been observed to pile into the console, strain the CPU.
  2107. */
  2108. if (audioLevelCanvasOrig)
  2109. {
  2110. audioLevelCanvasCache[resourceJid]
  2111. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  2112. }
  2113. }
  2114. var canvas = audioLevelCanvasCache[resourceJid];
  2115. if (!canvas)
  2116. return;
  2117. var drawContext = canvas.getContext('2d');
  2118. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  2119. var shadowLevel = getShadowLevel(audioLevel);
  2120. if (shadowLevel > 0)
  2121. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  2122. CanvasUtil.drawRoundRectGlow( drawContext,
  2123. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  2124. canvas.width - interfaceConfig.CANVAS_EXTRA,
  2125. canvas.height - interfaceConfig.CANVAS_EXTRA,
  2126. interfaceConfig.CANVAS_RADIUS,
  2127. interfaceConfig.SHADOW_COLOR,
  2128. shadowLevel);
  2129. }
  2130. /**
  2131. * Returns the shadow/glow level for the given audio level.
  2132. *
  2133. * @param audioLevel the audio level from which we determine the shadow
  2134. * level
  2135. */
  2136. function getShadowLevel (audioLevel) {
  2137. var shadowLevel = 0;
  2138. if (audioLevel <= 0.3) {
  2139. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  2140. }
  2141. else if (audioLevel <= 0.6) {
  2142. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  2143. }
  2144. else {
  2145. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  2146. }
  2147. return shadowLevel;
  2148. }
  2149. /**
  2150. * Returns the video span id corresponding to the given resourceJid or local
  2151. * user.
  2152. */
  2153. function getVideoSpanId(resourceJid) {
  2154. var videoSpanId = null;
  2155. if (resourceJid === AudioLevels.LOCAL_LEVEL
  2156. || (APP.xmpp.myResource() && resourceJid
  2157. === APP.xmpp.myResource()))
  2158. videoSpanId = 'localVideoContainer';
  2159. else
  2160. videoSpanId = 'participant_' + resourceJid;
  2161. return videoSpanId;
  2162. }
  2163. /**
  2164. * Indicates that the remote video has been resized.
  2165. */
  2166. $(document).bind('remotevideo.resized', function (event, width, height) {
  2167. var resized = false;
  2168. $('#remoteVideos>span>canvas').each(function() {
  2169. var canvas = $(this).get(0);
  2170. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  2171. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  2172. resized = true;
  2173. }
  2174. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  2175. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  2176. resized = true;
  2177. }
  2178. });
  2179. if (resized)
  2180. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  2181. audioLevelCanvasCache[resourceJid].width
  2182. = width + interfaceConfig.CANVAS_EXTRA;
  2183. audioLevelCanvasCache[resourceJid].height
  2184. = height + interfaceConfig.CANVAS_EXTRA;
  2185. });
  2186. });
  2187. return my;
  2188. })(AudioLevels || {});
  2189. module.exports = AudioLevels;
  2190. },{"./CanvasUtils":11}],11:[function(require,module,exports){
  2191. /**
  2192. * Utility class for drawing canvas shapes.
  2193. */
  2194. var CanvasUtil = (function(my) {
  2195. /**
  2196. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  2197. * of the glow.
  2198. *
  2199. * @param drawContext the context of the canvas to draw to
  2200. * @param x the x coordinate of the round rectangle
  2201. * @param y the y coordinate of the round rectangle
  2202. * @param w the width of the round rectangle
  2203. * @param h the height of the round rectangle
  2204. * @param glowColor the color of the glow
  2205. * @param glowWidth the width of the glow
  2206. */
  2207. my.drawRoundRectGlow
  2208. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  2209. // Save the previous state of the context.
  2210. drawContext.save();
  2211. if (w < 2 * r) r = w / 2;
  2212. if (h < 2 * r) r = h / 2;
  2213. // Draw a round rectangle.
  2214. drawContext.beginPath();
  2215. drawContext.moveTo(x+r, y);
  2216. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2217. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2218. drawContext.arcTo(x, y+h, x, y, r);
  2219. drawContext.arcTo(x, y, x+w, y, r);
  2220. drawContext.closePath();
  2221. // Add a shadow around the rectangle
  2222. drawContext.shadowColor = glowColor;
  2223. drawContext.shadowBlur = glowWidth;
  2224. drawContext.shadowOffsetX = 0;
  2225. drawContext.shadowOffsetY = 0;
  2226. // Fill the shape.
  2227. drawContext.fill();
  2228. drawContext.save();
  2229. drawContext.restore();
  2230. // 1) Uncomment this line to use Composite Operation, which is doing the
  2231. // same as the clip function below and is also antialiasing the round
  2232. // border, but is said to be less fast performance wise.
  2233. // drawContext.globalCompositeOperation='destination-out';
  2234. drawContext.beginPath();
  2235. drawContext.moveTo(x+r, y);
  2236. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2237. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2238. drawContext.arcTo(x, y+h, x, y, r);
  2239. drawContext.arcTo(x, y, x+w, y, r);
  2240. drawContext.closePath();
  2241. // 2) Uncomment this line to use Composite Operation, which is doing the
  2242. // same as the clip function below and is also antialiasing the round
  2243. // border, but is said to be less fast performance wise.
  2244. // drawContext.fill();
  2245. // Comment these two lines if choosing to do the same with composite
  2246. // operation above 1 and 2.
  2247. drawContext.clip();
  2248. drawContext.clearRect(0, 0, 277, 200);
  2249. // Restore the previous context state.
  2250. drawContext.restore();
  2251. };
  2252. /**
  2253. * Clones the given canvas.
  2254. *
  2255. * @return the new cloned canvas.
  2256. */
  2257. my.cloneCanvas = function (oldCanvas) {
  2258. /*
  2259. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2260. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2261. * levels are frequently updated, the errors have been observed to pile
  2262. * into the console, strain the CPU.
  2263. */
  2264. if (!oldCanvas)
  2265. return oldCanvas;
  2266. //create a new canvas
  2267. var newCanvas = document.createElement('canvas');
  2268. var context = newCanvas.getContext('2d');
  2269. //set dimensions
  2270. newCanvas.width = oldCanvas.width;
  2271. newCanvas.height = oldCanvas.height;
  2272. //apply the old canvas to the new one
  2273. context.drawImage(oldCanvas, 0, 0);
  2274. //return the new canvas
  2275. return newCanvas;
  2276. };
  2277. return my;
  2278. })(CanvasUtil || {});
  2279. module.exports = CanvasUtil;
  2280. },{}],12:[function(require,module,exports){
  2281. /* Initial "authentication required" dialog */
  2282. var authDialog = null;
  2283. /* Loop retry ID that wits for other user to create the room */
  2284. var authRetryId = null;
  2285. var authenticationWindow = null;
  2286. var Authentication = {
  2287. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2288. // This is the loop that will wait for the room to be created by
  2289. // someone else. 'auth_required.moderator' will bring us back here.
  2290. authRetryId = window.setTimeout(intervalCallback , 5000);
  2291. // Show prompt only if it's not open
  2292. if (authDialog !== null) {
  2293. return;
  2294. }
  2295. // extract room name from 'room@muc.server.net'
  2296. var room = roomName.substr(0, roomName.indexOf('@'));
  2297. var title = APP.translation.generateTranslatonHTML("dialog.Stop",
  2298. "Stop");
  2299. var defMsg = 'Authentication is required to create room:<br/><b>' +
  2300. room +
  2301. '</b></br> You can either authenticate to create the room or ' +
  2302. 'just wait for someone else to do so.';
  2303. var msg = APP.translation.generateTranslatonHTML("dialog.AuthMsg",
  2304. defMsg, {room: room});
  2305. var button = APP.translation.generateTranslatonHTML(
  2306. "dialog.Authenticate", "Authenticate");
  2307. var buttons = {};
  2308. buttons.authenticate = {title: button, value: "authNow"};
  2309. authDialog = APP.UI.messageHandler.openDialog(
  2310. title,
  2311. msg,
  2312. true,
  2313. buttons,
  2314. function (onSubmitEvent, submitValue) {
  2315. // Do not close the dialog yet
  2316. onSubmitEvent.preventDefault();
  2317. // Open login popup
  2318. if (submitValue === 'authNow') {
  2319. callback();
  2320. }
  2321. }
  2322. );
  2323. },
  2324. closeAuthenticationWindow:function () {
  2325. if (authenticationWindow) {
  2326. authenticationWindow.close();
  2327. authenticationWindow = null;
  2328. }
  2329. },
  2330. focusAuthenticationWindow: function () {
  2331. // If auth window exists just bring it to the front
  2332. if (authenticationWindow) {
  2333. authenticationWindow.focus();
  2334. return;
  2335. }
  2336. },
  2337. closeAuthenticationDialog: function () {
  2338. // Close authentication dialog if opened
  2339. if (authDialog) {
  2340. APP.UI.messageHandler.closeDialog();
  2341. authDialog = null;
  2342. }
  2343. },
  2344. createAuthenticationWindow: function (callback, url) {
  2345. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2346. url, 910, 660,
  2347. // On closed
  2348. function () {
  2349. // Close authentication dialog if opened
  2350. if (authDialog) {
  2351. messageHandler.closeDialog();
  2352. authDialog = null;
  2353. }
  2354. callback();
  2355. authenticationWindow = null;
  2356. });
  2357. return authenticationWindow;
  2358. },
  2359. stopInterval: function () {
  2360. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2361. if (authRetryId) {
  2362. window.clearTimeout(authRetryId);
  2363. authRetryId = null;
  2364. }
  2365. }
  2366. };
  2367. module.exports = Authentication;
  2368. },{}],13:[function(require,module,exports){
  2369. var Settings = require("../../settings/Settings");
  2370. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2371. var users = {};
  2372. var activeSpeakerJid;
  2373. function setVisibility(selector, show) {
  2374. if (selector && selector.length > 0) {
  2375. selector.css("visibility", show ? "visible" : "hidden");
  2376. }
  2377. }
  2378. function isUserMuted(jid) {
  2379. // XXX(gp) we may want to rename this method to something like
  2380. // isUserStreaming, for example.
  2381. if (jid && jid != APP.xmpp.myJid()) {
  2382. var resource = Strophe.getResourceFromJid(jid);
  2383. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2384. return true;
  2385. }
  2386. }
  2387. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2388. return null;
  2389. }
  2390. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2391. }
  2392. function getGravatarUrl(id, size) {
  2393. if(id === APP.xmpp.myJid() || !id) {
  2394. id = Settings.getSettings().uid;
  2395. }
  2396. return 'https://www.gravatar.com/avatar/' +
  2397. MD5.hexdigest(id.trim().toLowerCase()) +
  2398. "?d=wavatar&size=" + (size || "30");
  2399. }
  2400. var Avatar = {
  2401. /**
  2402. * Sets the user's avatar in the settings menu(if local user), contact list
  2403. * and thumbnail
  2404. * @param jid jid of the user
  2405. * @param id email or userID to be used as a hash
  2406. */
  2407. setUserAvatar: function (jid, id) {
  2408. if (id) {
  2409. if (users[jid] === id) {
  2410. return;
  2411. }
  2412. users[jid] = id;
  2413. }
  2414. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2415. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2416. var resourceJid = Strophe.getResourceFromJid(jid);
  2417. var thumbnail = $('#participant_' + resourceJid);
  2418. var avatar = $('#avatar_' + resourceJid);
  2419. // set the avatar in the settings menu if it is local user and get the
  2420. // local video container
  2421. if (jid === APP.xmpp.myJid()) {
  2422. $('#avatar').get(0).src = thumbUrl;
  2423. thumbnail = $('#localVideoContainer');
  2424. }
  2425. // set the avatar in the contact list
  2426. var contact = $('#' + resourceJid + '>img');
  2427. if (contact && contact.length > 0) {
  2428. contact.get(0).src = contactListUrl;
  2429. }
  2430. // set the avatar in the thumbnail
  2431. if (avatar && avatar.length > 0) {
  2432. avatar[0].src = thumbUrl;
  2433. } else {
  2434. if (thumbnail && thumbnail.length > 0) {
  2435. avatar = document.createElement('img');
  2436. avatar.id = 'avatar_' + resourceJid;
  2437. avatar.className = 'userAvatar';
  2438. avatar.src = thumbUrl;
  2439. thumbnail.append(avatar);
  2440. }
  2441. }
  2442. //if the user is the current active speaker - update the active speaker
  2443. // avatar
  2444. if (jid === activeSpeakerJid) {
  2445. this.updateActiveSpeakerAvatarSrc(jid);
  2446. }
  2447. },
  2448. /**
  2449. * Hides or shows the user's avatar
  2450. * @param jid jid of the user
  2451. * @param show whether we should show the avatar or not
  2452. * video because there is no dominant speaker and no focused speaker
  2453. */
  2454. showUserAvatar: function (jid, show) {
  2455. if (users[jid]) {
  2456. var resourceJid = Strophe.getResourceFromJid(jid);
  2457. var video = $('#participant_' + resourceJid + '>video');
  2458. var avatar = $('#avatar_' + resourceJid);
  2459. if (jid === APP.xmpp.myJid()) {
  2460. video = $('#localVideoWrapper>video');
  2461. }
  2462. if (show === undefined || show === null) {
  2463. show = isUserMuted(jid);
  2464. }
  2465. //if the user is the currently focused, the dominant speaker or if
  2466. //there is no focused and no dominant speaker and the large video is
  2467. //currently shown
  2468. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2469. setVisibility($("#largeVideo"), !show);
  2470. setVisibility($('#activeSpeaker'), show);
  2471. setVisibility(avatar, false);
  2472. setVisibility(video, false);
  2473. } else {
  2474. if (video && video.length > 0) {
  2475. setVisibility(video, !show);
  2476. setVisibility(avatar, show);
  2477. }
  2478. }
  2479. }
  2480. },
  2481. /**
  2482. * Updates the src of the active speaker avatar
  2483. * @param jid of the current active speaker
  2484. */
  2485. updateActiveSpeakerAvatarSrc: function (jid) {
  2486. if (!jid) {
  2487. jid = APP.xmpp.findJidFromResource(
  2488. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2489. }
  2490. var avatar = $("#activeSpeakerAvatar")[0];
  2491. var url = getGravatarUrl(users[jid],
  2492. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2493. if (jid === activeSpeakerJid && avatar.src === url) {
  2494. return;
  2495. }
  2496. activeSpeakerJid = jid;
  2497. var isMuted = isUserMuted(jid);
  2498. if (jid && isMuted !== null) {
  2499. avatar.src = url;
  2500. setVisibility($("#largeVideo"), !isMuted);
  2501. Avatar.showUserAvatar(jid, isMuted);
  2502. }
  2503. }
  2504. };
  2505. module.exports = Avatar;
  2506. },{"../../../service/RTC/MediaStreamTypes":79,"../../settings/Settings":38,"../videolayout/VideoLayout":32}],14:[function(require,module,exports){
  2507. /* global $, config,
  2508. setLargeVideoVisible, Util */
  2509. var VideoLayout = require("../videolayout/VideoLayout");
  2510. var Prezi = require("../prezi/Prezi");
  2511. var UIUtil = require("../util/UIUtil");
  2512. var etherpadName = null;
  2513. var etherpadIFrame = null;
  2514. var domain = null;
  2515. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2516. /**
  2517. * Resizes the etherpad.
  2518. */
  2519. function resize() {
  2520. if ($('#etherpad>iframe').length) {
  2521. var remoteVideos = $('#remoteVideos');
  2522. var availableHeight
  2523. = window.innerHeight - remoteVideos.outerHeight();
  2524. var availableWidth = UIUtil.getAvailableVideoWidth();
  2525. $('#etherpad>iframe').width(availableWidth);
  2526. $('#etherpad>iframe').height(availableHeight);
  2527. }
  2528. }
  2529. /**
  2530. * Shares the Etherpad name with other participants.
  2531. */
  2532. function shareEtherpad() {
  2533. APP.xmpp.addToPresence("etherpad", etherpadName);
  2534. }
  2535. /**
  2536. * Creates the Etherpad button and adds it to the toolbar.
  2537. */
  2538. function enableEtherpadButton() {
  2539. if (!$('#etherpadButton').is(":visible"))
  2540. $('#etherpadButton').css({display: 'inline-block'});
  2541. }
  2542. /**
  2543. * Creates the IFrame for the etherpad.
  2544. */
  2545. function createIFrame() {
  2546. etherpadIFrame = document.createElement('iframe');
  2547. etherpadIFrame.src = domain + etherpadName + options;
  2548. etherpadIFrame.frameBorder = 0;
  2549. etherpadIFrame.scrolling = "no";
  2550. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2551. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2552. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2553. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2554. etherpadIFrame.onload = function() {
  2555. document.domain = document.domain;
  2556. bubbleIframeMouseMove(etherpadIFrame);
  2557. setTimeout(function() {
  2558. // the iframes inside of the etherpad are
  2559. // not yet loaded when the etherpad iframe is loaded
  2560. var outer = etherpadIFrame.
  2561. contentDocument.getElementsByName("ace_outer")[0];
  2562. bubbleIframeMouseMove(outer);
  2563. var inner = outer.
  2564. contentDocument.getElementsByName("ace_inner")[0];
  2565. bubbleIframeMouseMove(inner);
  2566. }, 2000);
  2567. };
  2568. }
  2569. function bubbleIframeMouseMove(iframe){
  2570. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2571. iframe.contentWindow.onmousemove = function(e){
  2572. if(existingOnMouseMove) existingOnMouseMove(e);
  2573. var evt = document.createEvent("MouseEvents");
  2574. var boundingClientRect = iframe.getBoundingClientRect();
  2575. evt.initMouseEvent(
  2576. "mousemove",
  2577. true, // bubbles
  2578. false, // not cancelable
  2579. window,
  2580. e.detail,
  2581. e.screenX,
  2582. e.screenY,
  2583. e.clientX + boundingClientRect.left,
  2584. e.clientY + boundingClientRect.top,
  2585. e.ctrlKey,
  2586. e.altKey,
  2587. e.shiftKey,
  2588. e.metaKey,
  2589. e.button,
  2590. null // no related element
  2591. );
  2592. iframe.dispatchEvent(evt);
  2593. };
  2594. }
  2595. /**
  2596. * On video selected event.
  2597. */
  2598. $(document).bind('video.selected', function (event, isPresentation) {
  2599. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2600. Etherpad.toggleEtherpad(isPresentation);
  2601. });
  2602. var Etherpad = {
  2603. /**
  2604. * Initializes the etherpad.
  2605. */
  2606. init: function (name) {
  2607. if (config.etherpad_base && !etherpadName) {
  2608. domain = config.etherpad_base;
  2609. if (!name) {
  2610. // In case we're the focus we generate the name.
  2611. etherpadName = Math.random().toString(36).substring(7) +
  2612. '_' + (new Date().getTime()).toString();
  2613. shareEtherpad();
  2614. }
  2615. else
  2616. etherpadName = name;
  2617. enableEtherpadButton();
  2618. /**
  2619. * Resizes the etherpad, when the window is resized.
  2620. */
  2621. $(window).resize(function () {
  2622. resize();
  2623. });
  2624. }
  2625. },
  2626. /**
  2627. * Opens/hides the Etherpad.
  2628. */
  2629. toggleEtherpad: function (isPresentation) {
  2630. if (!etherpadIFrame)
  2631. createIFrame();
  2632. var largeVideo = null;
  2633. if (Prezi.isPresentationVisible())
  2634. largeVideo = $('#presentation>iframe');
  2635. else
  2636. largeVideo = $('#largeVideo');
  2637. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2638. $('#activeSpeaker').css('visibility', 'hidden');
  2639. largeVideo.fadeOut(300, function () {
  2640. if (Prezi.isPresentationVisible()) {
  2641. largeVideo.css({opacity: '0'});
  2642. } else {
  2643. VideoLayout.setLargeVideoVisible(false);
  2644. }
  2645. });
  2646. $('#etherpad>iframe').fadeIn(300, function () {
  2647. document.body.style.background = '#eeeeee';
  2648. $('#etherpad>iframe').css({visibility: 'visible'});
  2649. $('#etherpad').css({zIndex: 2});
  2650. });
  2651. }
  2652. else if ($('#etherpad>iframe')) {
  2653. $('#etherpad>iframe').fadeOut(300, function () {
  2654. $('#etherpad>iframe').css({visibility: 'hidden'});
  2655. $('#etherpad').css({zIndex: 0});
  2656. document.body.style.background = 'black';
  2657. });
  2658. if (!isPresentation) {
  2659. $('#largeVideo').fadeIn(300, function () {
  2660. VideoLayout.setLargeVideoVisible(true);
  2661. });
  2662. }
  2663. }
  2664. resize();
  2665. },
  2666. isVisible: function() {
  2667. var etherpadIframe = $('#etherpad>iframe');
  2668. return etherpadIframe && etherpadIframe.is(':visible');
  2669. }
  2670. };
  2671. module.exports = Etherpad;
  2672. },{"../prezi/Prezi":15,"../util/UIUtil":30,"../videolayout/VideoLayout":32}],15:[function(require,module,exports){
  2673. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2674. var UIUtil = require("../util/UIUtil");
  2675. var VideoLayout = require("../videolayout/VideoLayout");
  2676. var messageHandler = require("../util/MessageHandler");
  2677. var PreziPlayer = require("./PreziPlayer");
  2678. var preziPlayer = null;
  2679. var Prezi = {
  2680. /**
  2681. * Reloads the current presentation.
  2682. */
  2683. reloadPresentation: function() {
  2684. var iframe = document.getElementById(preziPlayer.options.preziId);
  2685. iframe.src = iframe.src;
  2686. },
  2687. /**
  2688. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2689. * otherwise.
  2690. */
  2691. isPresentationVisible: function () {
  2692. return ($('#presentation>iframe') != null
  2693. && $('#presentation>iframe').css('opacity') == 1);
  2694. },
  2695. /**
  2696. * Opens the Prezi dialog, from which the user could choose a presentation
  2697. * to load.
  2698. */
  2699. openPreziDialog: function() {
  2700. var myprezi = APP.xmpp.getPrezi();
  2701. if (myprezi) {
  2702. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  2703. "Remove Prezi", "dialog.removePreziMsg",
  2704. "Are you sure you would like to remove your Prezi?",
  2705. false,
  2706. "dialog.Remove",
  2707. function(e,v,m,f) {
  2708. if(v) {
  2709. APP.xmpp.removePreziFromPresence();
  2710. }
  2711. }
  2712. );
  2713. }
  2714. else if (preziPlayer != null) {
  2715. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  2716. "Share a Prezi", "dialog.sharePreziMsg",
  2717. "Another participant is already sharing a Prezi." +
  2718. "This conference allows only one Prezi at a time.",
  2719. false,
  2720. "dialog.Ok",
  2721. function(e,v,m,f) {
  2722. $.prompt.close();
  2723. }
  2724. );
  2725. }
  2726. else {
  2727. var html = APP.translation.generateTranslatonHTML(
  2728. "dialog.sharePreziTitle", "Share a Prezi");
  2729. var cancelButton = APP.translation.generateTranslatonHTML(
  2730. "dialog.Cancel", "Cancel");
  2731. var shareButton = APP.translation.generateTranslatonHTML(
  2732. "dialog.Share", "Share");
  2733. var backButton = APP.translation.generateTranslatonHTML(
  2734. "dialog.Back", "Back");
  2735. var buttons = {};
  2736. var buttons1 = {};
  2737. buttons1.Cancel = buttons.Cancel = {title: cancelButton, value: false};
  2738. buttons.share = {title: shareButton, value: true};
  2739. buttons1.Back = {title: backButton, value: true};
  2740. var linkError = APP.translation.generateTranslatonHTML(
  2741. "dialog.preziLinkError", "Please provide a correct prezi link.")
  2742. var openPreziState = {
  2743. state0: {
  2744. html: '<h2>' + html + '</h2>' +
  2745. '<input id="preziUrl" type="text" ' +
  2746. 'placeholder="e.g. ' +
  2747. 'http://prezi.com/wz7vhjycl7e6/my-prezi" autofocus>',
  2748. persistent: false,
  2749. buttons: buttons,
  2750. defaultButton: 1,
  2751. submit: function(e,v,m,f){
  2752. e.preventDefault();
  2753. if(v)
  2754. {
  2755. var preziUrl = document.getElementById('preziUrl');
  2756. if (preziUrl.value)
  2757. {
  2758. var urlValue
  2759. = encodeURI(UIUtil.escapeHtml(preziUrl.value));
  2760. if (urlValue.indexOf('http://prezi.com/') != 0
  2761. && urlValue.indexOf('https://prezi.com/') != 0)
  2762. {
  2763. $.prompt.goToState('state1');
  2764. return false;
  2765. }
  2766. else {
  2767. var presIdTmp = urlValue.substring(
  2768. urlValue.indexOf("prezi.com/") + 10);
  2769. if (!isAlphanumeric(presIdTmp)
  2770. || presIdTmp.indexOf('/') < 2) {
  2771. $.prompt.goToState('state1');
  2772. return false;
  2773. }
  2774. else {
  2775. APP.xmpp.addToPresence("prezi", urlValue);
  2776. $.prompt.close();
  2777. }
  2778. }
  2779. }
  2780. }
  2781. else
  2782. $.prompt.close();
  2783. }
  2784. },
  2785. state1: {
  2786. html: '<h2>' + html + '</h2>' +
  2787. linkError,
  2788. persistent: false,
  2789. buttons: buttons1,
  2790. defaultButton: 1,
  2791. submit:function(e,v,m,f) {
  2792. e.preventDefault();
  2793. if(v==0)
  2794. $.prompt.close();
  2795. else
  2796. $.prompt.goToState('state0');
  2797. }
  2798. }
  2799. };
  2800. var focusPreziUrl = function(e) {
  2801. document.getElementById('preziUrl').focus();
  2802. };
  2803. messageHandler.openDialogWithStates(openPreziState, focusPreziUrl, focusPreziUrl);
  2804. }
  2805. }
  2806. };
  2807. /**
  2808. * A new presentation has been added.
  2809. *
  2810. * @param event the event indicating the add of a presentation
  2811. * @param jid the jid from which the presentation was added
  2812. * @param presUrl url of the presentation
  2813. * @param currentSlide the current slide to which we should move
  2814. */
  2815. function presentationAdded(event, jid, presUrl, currentSlide) {
  2816. console.log("presentation added", presUrl);
  2817. var presId = getPresentationId(presUrl);
  2818. var elementId = 'participant_'
  2819. + Strophe.getResourceFromJid(jid)
  2820. + '_' + presId;
  2821. // We explicitly don't specify the peer jid here, because we don't want
  2822. // this video to be dealt with as a peer related one (for example we
  2823. // don't want to show a mute/kick menu for this one, etc.).
  2824. VideoLayout.addRemoteVideoContainer(null, elementId);
  2825. VideoLayout.resizeThumbnails();
  2826. var controlsEnabled = false;
  2827. if (jid === APP.xmpp.myJid())
  2828. controlsEnabled = true;
  2829. setPresentationVisible(true);
  2830. $('#largeVideoContainer').hover(
  2831. function (event) {
  2832. if (Prezi.isPresentationVisible()) {
  2833. var reloadButtonRight = window.innerWidth
  2834. - $('#presentation>iframe').offset().left
  2835. - $('#presentation>iframe').width();
  2836. $('#reloadPresentation').css({ right: reloadButtonRight,
  2837. display:'inline-block'});
  2838. }
  2839. },
  2840. function (event) {
  2841. if (!Prezi.isPresentationVisible())
  2842. $('#reloadPresentation').css({display:'none'});
  2843. else {
  2844. var e = event.toElement || event.relatedTarget;
  2845. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  2846. $('#reloadPresentation').css({display:'none'});
  2847. }
  2848. });
  2849. preziPlayer = new PreziPlayer(
  2850. 'presentation',
  2851. {preziId: presId,
  2852. width: getPresentationWidth(),
  2853. height: getPresentationHeihgt(),
  2854. controls: controlsEnabled,
  2855. debug: true
  2856. });
  2857. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  2858. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  2859. console.log("prezi status", event.value);
  2860. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  2861. if (jid != APP.xmpp.myJid())
  2862. preziPlayer.flyToStep(currentSlide);
  2863. }
  2864. });
  2865. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  2866. console.log("event value", event.value);
  2867. APP.xmpp.addToPresence("preziSlide", event.value);
  2868. });
  2869. $("#" + elementId).css( 'background-image',
  2870. 'url(../images/avatarprezi.png)');
  2871. $("#" + elementId).click(
  2872. function () {
  2873. setPresentationVisible(true);
  2874. }
  2875. );
  2876. };
  2877. /**
  2878. * A presentation has been removed.
  2879. *
  2880. * @param event the event indicating the remove of a presentation
  2881. * @param jid the jid for which the presentation was removed
  2882. * @param the url of the presentation
  2883. */
  2884. function presentationRemoved(event, jid, presUrl) {
  2885. console.log('presentation removed', presUrl);
  2886. var presId = getPresentationId(presUrl);
  2887. setPresentationVisible(false);
  2888. $('#participant_'
  2889. + Strophe.getResourceFromJid(jid)
  2890. + '_' + presId).remove();
  2891. $('#presentation>iframe').remove();
  2892. if (preziPlayer != null) {
  2893. preziPlayer.destroy();
  2894. preziPlayer = null;
  2895. }
  2896. };
  2897. /**
  2898. * Indicates if the given string is an alphanumeric string.
  2899. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  2900. * purpose of checking URIs.
  2901. */
  2902. function isAlphanumeric(unsafeText) {
  2903. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  2904. return regex.test(unsafeText);
  2905. }
  2906. /**
  2907. * Returns the presentation id from the given url.
  2908. */
  2909. function getPresentationId (presUrl) {
  2910. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  2911. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  2912. }
  2913. /**
  2914. * Returns the presentation width.
  2915. */
  2916. function getPresentationWidth() {
  2917. var availableWidth = UIUtil.getAvailableVideoWidth();
  2918. var availableHeight = getPresentationHeihgt();
  2919. var aspectRatio = 16.0 / 9.0;
  2920. if (availableHeight < availableWidth / aspectRatio) {
  2921. availableWidth = Math.floor(availableHeight * aspectRatio);
  2922. }
  2923. return availableWidth;
  2924. }
  2925. /**
  2926. * Returns the presentation height.
  2927. */
  2928. function getPresentationHeihgt() {
  2929. var remoteVideos = $('#remoteVideos');
  2930. return window.innerHeight - remoteVideos.outerHeight();
  2931. }
  2932. /**
  2933. * Resizes the presentation iframe.
  2934. */
  2935. function resize() {
  2936. if ($('#presentation>iframe')) {
  2937. $('#presentation>iframe').width(getPresentationWidth());
  2938. $('#presentation>iframe').height(getPresentationHeihgt());
  2939. }
  2940. }
  2941. /**
  2942. * Shows/hides a presentation.
  2943. */
  2944. function setPresentationVisible(visible) {
  2945. var prezi = $('#presentation>iframe');
  2946. if (visible) {
  2947. // Trigger the video.selected event to indicate a change in the
  2948. // large video.
  2949. $(document).trigger("video.selected", [true]);
  2950. $('#largeVideo').fadeOut(300);
  2951. prezi.fadeIn(300, function() {
  2952. prezi.css({opacity:'1'});
  2953. ToolbarToggler.dockToolbar(true);
  2954. VideoLayout.setLargeVideoVisible(false);
  2955. });
  2956. $('#activeSpeaker').css('visibility', 'hidden');
  2957. }
  2958. else {
  2959. if (prezi.css('opacity') == '1') {
  2960. prezi.fadeOut(300, function () {
  2961. prezi.css({opacity:'0'});
  2962. $('#reloadPresentation').css({display:'none'});
  2963. $('#largeVideo').fadeIn(300, function() {
  2964. VideoLayout.setLargeVideoVisible(true);
  2965. ToolbarToggler.dockToolbar(false);
  2966. });
  2967. });
  2968. }
  2969. }
  2970. }
  2971. /**
  2972. * Presentation has been removed.
  2973. */
  2974. $(document).bind('presentationremoved.muc', presentationRemoved);
  2975. /**
  2976. * Presentation has been added.
  2977. */
  2978. $(document).bind('presentationadded.muc', presentationAdded);
  2979. /*
  2980. * Indicates presentation slide change.
  2981. */
  2982. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  2983. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  2984. preziPlayer.flyToStep(current);
  2985. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  2986. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  2987. preziPlayer.flyToStep(current, i);
  2988. }
  2989. }
  2990. });
  2991. /**
  2992. * On video selected event.
  2993. */
  2994. $(document).bind('video.selected', function (event, isPresentation) {
  2995. if (!isPresentation && $('#presentation>iframe')) {
  2996. setPresentationVisible(false);
  2997. }
  2998. });
  2999. $(window).resize(function () {
  3000. resize();
  3001. });
  3002. module.exports = Prezi;
  3003. },{"../toolbars/ToolbarToggler":26,"../util/MessageHandler":28,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./PreziPlayer":16}],16:[function(require,module,exports){
  3004. (function() {
  3005. "use strict";
  3006. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  3007. window.PreziPlayer = (function() {
  3008. PreziPlayer.API_VERSION = 1;
  3009. PreziPlayer.CURRENT_STEP = 'currentStep';
  3010. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  3011. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  3012. PreziPlayer.STATUS_LOADING = 'loading';
  3013. PreziPlayer.STATUS_READY = 'ready';
  3014. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  3015. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  3016. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  3017. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  3018. PreziPlayer.EVENT_STATUS = "statusChange";
  3019. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  3020. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  3021. PreziPlayer.domain = "https://prezi.com";
  3022. PreziPlayer.path = "/player/";
  3023. PreziPlayer.players = {};
  3024. PreziPlayer.binded_methods = ['changesHandler'];
  3025. PreziPlayer.createMultiplePlayers = function(optionArray){
  3026. for(var i=0; i<optionArray.length; i++) {
  3027. var optionSet = optionArray[i];
  3028. new PreziPlayer(optionSet.id, optionSet);
  3029. };
  3030. };
  3031. PreziPlayer.messageReceived = function(event){
  3032. var message, item, player;
  3033. try {
  3034. message = JSON.parse(event.data);
  3035. if (message.id && (player = PreziPlayer.players[message.id])) {
  3036. if (player.options.debug === true) {
  3037. if (console && console.log)
  3038. console.log('received', message);
  3039. }
  3040. if (message.type === "changes") {
  3041. player.changesHandler(message);
  3042. }
  3043. for (var i = 0; i < player.callbacks.length; i++) {
  3044. item = player.callbacks[i];
  3045. if (item && message.type === item.event) {
  3046. item.callback(message);
  3047. }
  3048. }
  3049. }
  3050. } catch (e) { }
  3051. };
  3052. function PreziPlayer(id, options) {
  3053. var params, paramString = "", _this = this;
  3054. if (PreziPlayer.players[id]){
  3055. PreziPlayer.players[id].destroy();
  3056. }
  3057. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  3058. var method_name = PreziPlayer.binded_methods[i];
  3059. _this[method_name] = __bind(_this[method_name], _this);
  3060. };
  3061. options = options || {};
  3062. this.options = options;
  3063. this.values = {'status': PreziPlayer.STATUS_LOADING};
  3064. this.values[PreziPlayer.CURRENT_STEP] = 0;
  3065. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  3066. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  3067. this.callbacks = [];
  3068. this.id = id;
  3069. this.embedTo = document.getElementById(id);
  3070. if (!this.embedTo) {
  3071. throw "The element id is not available.";
  3072. }
  3073. this.iframe = document.createElement('iframe');
  3074. params = [
  3075. { name: 'oid', value: options.preziId },
  3076. { name: 'explorable', value: options.explorable ? 1 : 0 },
  3077. { name: 'controls', value: options.controls ? 1 : 0 }
  3078. ];
  3079. for(var i=0; i<params.length; i++) {
  3080. var param = params[i];
  3081. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  3082. };
  3083. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  3084. this.iframe.frameBorder = 0;
  3085. this.iframe.scrolling = "no";
  3086. this.iframe.width = options.width || 640;
  3087. this.iframe.height = options.height || 480;
  3088. this.embedTo.innerHTML = '';
  3089. // JITSI: IN CASE SOMETHING GOES WRONG.
  3090. try {
  3091. this.embedTo.appendChild(this.iframe);
  3092. }
  3093. catch (err) {
  3094. console.log("CATCH ERROR");
  3095. }
  3096. // JITSI: Increase interval from 200 to 500, which fixes prezi
  3097. // crashes for us.
  3098. this.initPollInterval = setInterval(function(){
  3099. _this.sendMessage({'action': 'init'});
  3100. }, 500);
  3101. PreziPlayer.players[id] = this;
  3102. }
  3103. PreziPlayer.prototype.changesHandler = function(message) {
  3104. var key, value, j, item;
  3105. if (this.initPollInterval) {
  3106. clearInterval(this.initPollInterval);
  3107. this.initPollInterval = false;
  3108. }
  3109. for (key in message.data) {
  3110. if (message.data.hasOwnProperty(key)){
  3111. value = message.data[key];
  3112. this.values[key] = value;
  3113. for (j=0; j<this.callbacks.length; j++) {
  3114. item = this.callbacks[j];
  3115. if (item && item.event === key + "Change"){
  3116. item.callback({type: item.event, value: value});
  3117. }
  3118. }
  3119. }
  3120. }
  3121. };
  3122. PreziPlayer.prototype.destroy = function() {
  3123. if (this.initPollInterval) {
  3124. clearInterval(this.initPollInterval);
  3125. this.initPollInterval = false;
  3126. }
  3127. this.embedTo.innerHTML = '';
  3128. };
  3129. PreziPlayer.prototype.sendMessage = function(message) {
  3130. if (this.options.debug === true) {
  3131. if (console && console.log) console.log('sent', message);
  3132. }
  3133. message.version = PreziPlayer.API_VERSION;
  3134. message.id = this.id;
  3135. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  3136. };
  3137. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  3138. PreziPlayer.prototype.flyToNextStep = function() {
  3139. return this.sendMessage({
  3140. 'action': 'present',
  3141. 'data': ['moveToNextStep']
  3142. });
  3143. };
  3144. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  3145. PreziPlayer.prototype.flyToPreviousStep = function() {
  3146. return this.sendMessage({
  3147. 'action': 'present',
  3148. 'data': ['moveToPrevStep']
  3149. });
  3150. };
  3151. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  3152. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  3153. var obj = this;
  3154. // check animation_step
  3155. if (animation_step > 0 &&
  3156. obj.values.animationCountOnSteps &&
  3157. obj.values.animationCountOnSteps[step] <= animation_step) {
  3158. animation_step = obj.values.animationCountOnSteps[step];
  3159. }
  3160. // jump to animation steps by calling flyToNextStep()
  3161. function doAnimationSteps() {
  3162. if (obj.values.isMoving == true) {
  3163. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  3164. return;
  3165. }
  3166. while (animation_step-- > 0) {
  3167. obj.flyToNextStep(); // do the animation steps
  3168. }
  3169. }
  3170. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  3171. // jump to the step
  3172. return this.sendMessage({
  3173. 'action': 'present',
  3174. 'data': ['moveToStep', step]
  3175. });
  3176. };
  3177. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  3178. PreziPlayer.prototype.flyToObject = function(objectId) {
  3179. return this.sendMessage({
  3180. 'action': 'present',
  3181. 'data': ['moveToObject', objectId]
  3182. });
  3183. };
  3184. PreziPlayer.prototype.play = function(defaultDelay) {
  3185. return this.sendMessage({
  3186. 'action': 'present',
  3187. 'data': ['startAutoPlay', defaultDelay]
  3188. });
  3189. };
  3190. PreziPlayer.prototype.stop = function() {
  3191. return this.sendMessage({
  3192. 'action': 'present',
  3193. 'data': ['stopAutoPlay']
  3194. });
  3195. };
  3196. PreziPlayer.prototype.pause = function(defaultDelay) {
  3197. return this.sendMessage({
  3198. 'action': 'present',
  3199. 'data': ['pauseAutoPlay', defaultDelay]
  3200. });
  3201. };
  3202. PreziPlayer.prototype.getCurrentStep = function() {
  3203. return this.values.currentStep;
  3204. };
  3205. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  3206. return this.values.currentAnimationStep;
  3207. };
  3208. PreziPlayer.prototype.getCurrentObject = function() {
  3209. return this.values.currentObject;
  3210. };
  3211. PreziPlayer.prototype.getStatus = function() {
  3212. return this.values.status;
  3213. };
  3214. PreziPlayer.prototype.isPlaying = function() {
  3215. return this.values.isAutoPlaying;
  3216. };
  3217. PreziPlayer.prototype.getStepCount = function() {
  3218. return this.values.stepCount;
  3219. };
  3220. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  3221. return this.values.animationCountOnSteps;
  3222. };
  3223. PreziPlayer.prototype.getTitle = function() {
  3224. return this.values.title;
  3225. };
  3226. PreziPlayer.prototype.setDimensions = function(dims) {
  3227. for (var parameter in dims) {
  3228. this.iframe[parameter] = dims[parameter];
  3229. }
  3230. }
  3231. PreziPlayer.prototype.getDimensions = function() {
  3232. return {
  3233. width: parseInt(this.iframe.width, 10),
  3234. height: parseInt(this.iframe.height, 10)
  3235. }
  3236. }
  3237. PreziPlayer.prototype.on = function(event, callback) {
  3238. this.callbacks.push({
  3239. event: event,
  3240. callback: callback
  3241. });
  3242. };
  3243. PreziPlayer.prototype.off = function(event, callback) {
  3244. var j, item;
  3245. if (event === undefined) {
  3246. this.callbacks = [];
  3247. }
  3248. j = this.callbacks.length;
  3249. while (j--) {
  3250. item = this.callbacks[j];
  3251. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3252. this.callbacks.splice(j, 1);
  3253. }
  3254. }
  3255. };
  3256. if (window.addEventListener) {
  3257. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3258. } else {
  3259. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3260. }
  3261. return PreziPlayer;
  3262. })();
  3263. })();
  3264. module.exports = PreziPlayer;
  3265. },{}],17:[function(require,module,exports){
  3266. var Chat = require("./chat/Chat");
  3267. var ContactList = require("./contactlist/ContactList");
  3268. var Settings = require("./../../settings/Settings");
  3269. var SettingsMenu = require("./settings/SettingsMenu");
  3270. var VideoLayout = require("../videolayout/VideoLayout");
  3271. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3272. var UIUtil = require("../util/UIUtil");
  3273. /**
  3274. * Toggler for the chat, contact list, settings menu, etc..
  3275. */
  3276. var PanelToggler = (function(my) {
  3277. var currentlyOpen = null;
  3278. var buttons = {
  3279. '#chatspace': '#chatBottomButton',
  3280. '#contactlist': '#contactListButton',
  3281. '#settingsmenu': '#settingsButton'
  3282. };
  3283. /**
  3284. * Resizes the video area
  3285. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3286. * @param completeFunction a function to be called when the video space is resized
  3287. */
  3288. var resizeVideoArea = function(isClosing, completeFunction) {
  3289. var videospace = $('#videospace');
  3290. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3291. var videospaceWidth = window.innerWidth - panelSize[0];
  3292. var videospaceHeight = window.innerHeight;
  3293. var videoSize
  3294. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3295. var videoWidth = videoSize[0];
  3296. var videoHeight = videoSize[1];
  3297. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3298. videoHeight,
  3299. videospaceWidth,
  3300. videospaceHeight);
  3301. var horizontalIndent = videoPosition[0];
  3302. var verticalIndent = videoPosition[1];
  3303. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3304. var thumbnailsWidth = thumbnailSize[0];
  3305. var thumbnailsHeight = thumbnailSize[1];
  3306. //for chat
  3307. videospace.animate({
  3308. right: panelSize[0],
  3309. width: videospaceWidth,
  3310. height: videospaceHeight
  3311. },
  3312. {
  3313. queue: false,
  3314. duration: 500,
  3315. complete: completeFunction
  3316. });
  3317. $('#remoteVideos').animate({
  3318. height: thumbnailsHeight
  3319. },
  3320. {
  3321. queue: false,
  3322. duration: 500
  3323. });
  3324. $('#remoteVideos>span').animate({
  3325. height: thumbnailsHeight,
  3326. width: thumbnailsWidth
  3327. },
  3328. {
  3329. queue: false,
  3330. duration: 500,
  3331. complete: function () {
  3332. $(document).trigger(
  3333. "remotevideo.resized",
  3334. [thumbnailsWidth,
  3335. thumbnailsHeight]);
  3336. }
  3337. });
  3338. $('#largeVideoContainer').animate({
  3339. width: videospaceWidth,
  3340. height: videospaceHeight
  3341. },
  3342. {
  3343. queue: false,
  3344. duration: 500
  3345. });
  3346. $('#largeVideo').animate({
  3347. width: videoWidth,
  3348. height: videoHeight,
  3349. top: verticalIndent,
  3350. bottom: verticalIndent,
  3351. left: horizontalIndent,
  3352. right: horizontalIndent
  3353. },
  3354. {
  3355. queue: false,
  3356. duration: 500
  3357. });
  3358. };
  3359. /**
  3360. * Toggles the windows in the side panel
  3361. * @param object the window that should be shown
  3362. * @param selector the selector for the element containing the panel
  3363. * @param onOpenComplete function to be called when the panel is opened
  3364. * @param onOpen function to be called if the window is going to be opened
  3365. * @param onClose function to be called if the window is going to be closed
  3366. */
  3367. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3368. UIUtil.buttonClick(buttons[selector], "active");
  3369. if (object.isVisible()) {
  3370. $("#toast-container").animate({
  3371. right: '5px'
  3372. },
  3373. {
  3374. queue: false,
  3375. duration: 500
  3376. });
  3377. $(selector).hide("slide", {
  3378. direction: "right",
  3379. queue: false,
  3380. duration: 500
  3381. });
  3382. if(typeof onClose === "function") {
  3383. onClose();
  3384. }
  3385. currentlyOpen = null;
  3386. }
  3387. else {
  3388. // Undock the toolbar when the chat is shown and if we're in a
  3389. // video mode.
  3390. if (VideoLayout.isLargeVideoVisible()) {
  3391. ToolbarToggler.dockToolbar(false);
  3392. }
  3393. if(currentlyOpen) {
  3394. var current = $(currentlyOpen);
  3395. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3396. current.css('z-index', 4);
  3397. setTimeout(function () {
  3398. current.css('display', 'none');
  3399. current.css('z-index', 5);
  3400. }, 500);
  3401. }
  3402. $("#toast-container").animate({
  3403. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3404. },
  3405. {
  3406. queue: false,
  3407. duration: 500
  3408. });
  3409. $(selector).show("slide", {
  3410. direction: "right",
  3411. queue: false,
  3412. duration: 500,
  3413. complete: onOpenComplete
  3414. });
  3415. if(typeof onOpen === "function") {
  3416. onOpen();
  3417. }
  3418. currentlyOpen = selector;
  3419. }
  3420. };
  3421. /**
  3422. * Opens / closes the chat area.
  3423. */
  3424. my.toggleChat = function() {
  3425. var chatCompleteFunction = Chat.isVisible() ?
  3426. function() {} : function () {
  3427. Chat.scrollChatToBottom();
  3428. $('#chatspace').trigger('shown');
  3429. };
  3430. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3431. toggle(Chat,
  3432. '#chatspace',
  3433. function () {
  3434. // Request the focus in the nickname field or the chat input field.
  3435. if ($('#nickname').css('visibility') === 'visible') {
  3436. $('#nickinput').focus();
  3437. } else {
  3438. $('#usermsg').focus();
  3439. }
  3440. },
  3441. null,
  3442. Chat.resizeChat,
  3443. null);
  3444. };
  3445. /**
  3446. * Opens / closes the contact list area.
  3447. */
  3448. my.toggleContactList = function () {
  3449. var completeFunction = ContactList.isVisible() ?
  3450. function() {} : function () { $('#contactlist').trigger('shown');};
  3451. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3452. toggle(ContactList,
  3453. '#contactlist',
  3454. null,
  3455. function() {
  3456. ContactList.setVisualNotification(false);
  3457. },
  3458. null);
  3459. };
  3460. /**
  3461. * Opens / closes the settings menu
  3462. */
  3463. my.toggleSettingsMenu = function() {
  3464. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3465. toggle(SettingsMenu,
  3466. '#settingsmenu',
  3467. null,
  3468. function() {
  3469. var settings = Settings.getSettings();
  3470. $('#setDisplayName').get(0).value = settings.displayName;
  3471. $('#setEmail').get(0).value = settings.email;
  3472. },
  3473. null);
  3474. };
  3475. /**
  3476. * Returns the size of the side panel.
  3477. */
  3478. my.getPanelSize = function () {
  3479. var availableHeight = window.innerHeight;
  3480. var availableWidth = window.innerWidth;
  3481. var panelWidth = 200;
  3482. if (availableWidth * 0.2 < 200) {
  3483. panelWidth = availableWidth * 0.2;
  3484. }
  3485. return [panelWidth, availableHeight];
  3486. };
  3487. my.isVisible = function() {
  3488. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3489. };
  3490. return my;
  3491. }(PanelToggler || {}));
  3492. module.exports = PanelToggler;
  3493. },{"../toolbars/ToolbarToggler":26,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./../../settings/Settings":38,"./chat/Chat":18,"./contactlist/ContactList":22,"./settings/SettingsMenu":23}],18:[function(require,module,exports){
  3494. /* global $, Util, nickname:true */
  3495. var Replacement = require("./Replacement");
  3496. var CommandsProcessor = require("./Commands");
  3497. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3498. var smileys = require("./smileys.json").smileys;
  3499. var NicknameHandler = require("../../util/NicknameHandler");
  3500. var UIUtil = require("../../util/UIUtil");
  3501. var UIEvents = require("../../../../service/UI/UIEvents");
  3502. var notificationInterval = false;
  3503. var unreadMessages = 0;
  3504. /**
  3505. * Shows/hides a visual notification, indicating that a message has arrived.
  3506. */
  3507. function setVisualNotification(show) {
  3508. var unreadMsgElement = document.getElementById('unreadMessages');
  3509. var unreadMsgBottomElement
  3510. = document.getElementById('bottomUnreadMessages');
  3511. var glower = $('#chatButton');
  3512. var bottomGlower = $('#chatBottomButton');
  3513. if (unreadMessages) {
  3514. unreadMsgElement.innerHTML = unreadMessages.toString();
  3515. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3516. ToolbarToggler.dockToolbar(true);
  3517. var chatButtonElement
  3518. = document.getElementById('chatButton').parentNode;
  3519. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3520. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3521. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3522. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3523. unreadMsgElement.setAttribute(
  3524. 'style',
  3525. 'top:' + topIndent +
  3526. '; left:' + leftIndent + ';');
  3527. var chatBottomButtonElement
  3528. = document.getElementById('chatBottomButton').parentNode;
  3529. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3530. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3531. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3532. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3533. unreadMsgBottomElement.setAttribute(
  3534. 'style',
  3535. 'top:' + bottomTopIndent +
  3536. '; left:' + bottomLeftIndent + ';');
  3537. if (!glower.hasClass('icon-chat-simple')) {
  3538. glower.removeClass('icon-chat');
  3539. glower.addClass('icon-chat-simple');
  3540. }
  3541. }
  3542. else {
  3543. unreadMsgElement.innerHTML = '';
  3544. unreadMsgBottomElement.innerHTML = '';
  3545. glower.removeClass('icon-chat-simple');
  3546. glower.addClass('icon-chat');
  3547. }
  3548. if (show && !notificationInterval) {
  3549. notificationInterval = window.setInterval(function () {
  3550. glower.toggleClass('active');
  3551. bottomGlower.toggleClass('active glowing');
  3552. }, 800);
  3553. }
  3554. else if (!show && notificationInterval) {
  3555. window.clearInterval(notificationInterval);
  3556. notificationInterval = false;
  3557. glower.removeClass('active');
  3558. bottomGlower.removeClass('glowing');
  3559. bottomGlower.addClass('active');
  3560. }
  3561. }
  3562. /**
  3563. * Returns the current time in the format it is shown to the user
  3564. * @returns {string}
  3565. */
  3566. function getCurrentTime() {
  3567. var now = new Date();
  3568. var hour = now.getHours();
  3569. var minute = now.getMinutes();
  3570. var second = now.getSeconds();
  3571. if(hour.toString().length === 1) {
  3572. hour = '0'+hour;
  3573. }
  3574. if(minute.toString().length === 1) {
  3575. minute = '0'+minute;
  3576. }
  3577. if(second.toString().length === 1) {
  3578. second = '0'+second;
  3579. }
  3580. return hour+':'+minute+':'+second;
  3581. }
  3582. function toggleSmileys()
  3583. {
  3584. var smileys = $('#smileysContainer');
  3585. if(!smileys.is(':visible')) {
  3586. smileys.show("slide", { direction: "down", duration: 300});
  3587. } else {
  3588. smileys.hide("slide", { direction: "down", duration: 300});
  3589. }
  3590. $('#usermsg').focus();
  3591. }
  3592. function addClickFunction(smiley, number) {
  3593. smiley.onclick = function addSmileyToMessage() {
  3594. var usermsg = $('#usermsg');
  3595. var message = usermsg.val();
  3596. message += smileys['smiley' + number];
  3597. usermsg.val(message);
  3598. usermsg.get(0).setSelectionRange(message.length, message.length);
  3599. toggleSmileys();
  3600. usermsg.focus();
  3601. };
  3602. }
  3603. /**
  3604. * Adds the smileys container to the chat
  3605. */
  3606. function addSmileys() {
  3607. var smileysContainer = document.createElement('div');
  3608. smileysContainer.id = 'smileysContainer';
  3609. for(var i = 1; i <= 21; i++) {
  3610. var smileyContainer = document.createElement('div');
  3611. smileyContainer.id = 'smiley' + i;
  3612. smileyContainer.className = 'smileyContainer';
  3613. var smiley = document.createElement('img');
  3614. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3615. smiley.className = 'smiley';
  3616. addClickFunction(smiley, i);
  3617. smileyContainer.appendChild(smiley);
  3618. smileysContainer.appendChild(smileyContainer);
  3619. }
  3620. $("#chatspace").append(smileysContainer);
  3621. }
  3622. /**
  3623. * Resizes the chat conversation.
  3624. */
  3625. function resizeChatConversation() {
  3626. var msgareaHeight = $('#usermsg').outerHeight();
  3627. var chatspace = $('#chatspace');
  3628. var width = chatspace.width();
  3629. var chat = $('#chatconversation');
  3630. var smileys = $('#smileysarea');
  3631. smileys.height(msgareaHeight);
  3632. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3633. $('#smileysContainer').css('bottom', msgareaHeight);
  3634. chat.width(width - 10);
  3635. chat.height(window.innerHeight - 15 - msgareaHeight);
  3636. }
  3637. /**
  3638. * Chat related user interface.
  3639. */
  3640. var Chat = (function (my) {
  3641. /**
  3642. * Initializes chat related interface.
  3643. */
  3644. my.init = function () {
  3645. if(NicknameHandler.getNickname())
  3646. Chat.setChatConversationMode(true);
  3647. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3648. function (nickname) {
  3649. Chat.setChatConversationMode(true);
  3650. });
  3651. $('#nickinput').keydown(function (event) {
  3652. if (event.keyCode === 13) {
  3653. event.preventDefault();
  3654. var val = UIUtil.escapeHtml(this.value);
  3655. this.value = '';
  3656. if (!NicknameHandler.getNickname()) {
  3657. NicknameHandler.setNickname(val);
  3658. return;
  3659. }
  3660. }
  3661. });
  3662. $('#usermsg').keydown(function (event) {
  3663. if (event.keyCode === 13) {
  3664. event.preventDefault();
  3665. var value = this.value;
  3666. $('#usermsg').val('').trigger('autosize.resize');
  3667. this.focus();
  3668. var command = new CommandsProcessor(value);
  3669. if(command.isCommand())
  3670. {
  3671. command.processCommand();
  3672. }
  3673. else
  3674. {
  3675. var message = UIUtil.escapeHtml(value);
  3676. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3677. }
  3678. }
  3679. });
  3680. var onTextAreaResize = function () {
  3681. resizeChatConversation();
  3682. Chat.scrollChatToBottom();
  3683. };
  3684. $('#usermsg').autosize({callback: onTextAreaResize});
  3685. $("#chatspace").bind("shown",
  3686. function () {
  3687. unreadMessages = 0;
  3688. setVisualNotification(false);
  3689. });
  3690. addSmileys();
  3691. };
  3692. /**
  3693. * Appends the given message to the chat conversation.
  3694. */
  3695. my.updateChatConversation = function (from, displayName, message) {
  3696. var divClassName = '';
  3697. if (APP.xmpp.myJid() === from) {
  3698. divClassName = "localuser";
  3699. }
  3700. else {
  3701. divClassName = "remoteuser";
  3702. if (!Chat.isVisible()) {
  3703. unreadMessages++;
  3704. UIUtil.playSoundNotification('chatNotification');
  3705. setVisualNotification(true);
  3706. }
  3707. }
  3708. // replace links and smileys
  3709. // Strophe already escapes special symbols on sending,
  3710. // so we escape here only tags to avoid double &amp;
  3711. var escMessage = message.replace(/</g, '&lt;').
  3712. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  3713. var escDisplayName = UIUtil.escapeHtml(displayName);
  3714. message = Replacement.processReplacements(escMessage);
  3715. var messageContainer =
  3716. '<div class="chatmessage">'+
  3717. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  3718. '<div class="username ' + divClassName +'">' + escDisplayName +
  3719. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  3720. '</div>' + '<div class="usermessage">' + message + '</div>' +
  3721. '</div>';
  3722. $('#chatconversation').append(messageContainer);
  3723. $('#chatconversation').animate(
  3724. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3725. };
  3726. /**
  3727. * Appends error message to the conversation
  3728. * @param errorMessage the received error message.
  3729. * @param originalText the original message.
  3730. */
  3731. my.chatAddError = function(errorMessage, originalText)
  3732. {
  3733. errorMessage = UIUtil.escapeHtml(errorMessage);
  3734. originalText = UIUtil.escapeHtml(originalText);
  3735. $('#chatconversation').append(
  3736. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  3737. (originalText? (' \"'+ originalText + '\"') : "") +
  3738. ' was not sent.' +
  3739. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  3740. $('#chatconversation').animate(
  3741. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3742. };
  3743. /**
  3744. * Sets the subject to the UI
  3745. * @param subject the subject
  3746. */
  3747. my.chatSetSubject = function(subject)
  3748. {
  3749. if(subject)
  3750. subject = subject.trim();
  3751. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  3752. if(subject === "")
  3753. {
  3754. $("#subject").css({display: "none"});
  3755. }
  3756. else
  3757. {
  3758. $("#subject").css({display: "block"});
  3759. }
  3760. };
  3761. /**
  3762. * Sets the chat conversation mode.
  3763. */
  3764. my.setChatConversationMode = function (isConversationMode) {
  3765. if (isConversationMode) {
  3766. $('#nickname').css({visibility: 'hidden'});
  3767. $('#chatconversation').css({visibility: 'visible'});
  3768. $('#usermsg').css({visibility: 'visible'});
  3769. $('#smileysarea').css({visibility: 'visible'});
  3770. $('#usermsg').focus();
  3771. }
  3772. };
  3773. /**
  3774. * Resizes the chat area.
  3775. */
  3776. my.resizeChat = function () {
  3777. var chatSize = require("../SidePanelToggler").getPanelSize();
  3778. $('#chatspace').width(chatSize[0]);
  3779. $('#chatspace').height(chatSize[1]);
  3780. resizeChatConversation();
  3781. };
  3782. /**
  3783. * Indicates if the chat is currently visible.
  3784. */
  3785. my.isVisible = function () {
  3786. return $('#chatspace').is(":visible");
  3787. };
  3788. /**
  3789. * Shows and hides the window with the smileys
  3790. */
  3791. my.toggleSmileys = toggleSmileys;
  3792. /**
  3793. * Scrolls chat to the bottom.
  3794. */
  3795. my.scrollChatToBottom = function() {
  3796. setTimeout(function () {
  3797. $('#chatconversation').scrollTop(
  3798. $('#chatconversation')[0].scrollHeight);
  3799. }, 5);
  3800. };
  3801. return my;
  3802. }(Chat || {}));
  3803. module.exports = Chat;
  3804. },{"../../../../service/UI/UIEvents":84,"../../toolbars/ToolbarToggler":26,"../../util/NicknameHandler":29,"../../util/UIUtil":30,"../SidePanelToggler":17,"./Commands":19,"./Replacement":20,"./smileys.json":21}],19:[function(require,module,exports){
  3805. var UIUtil = require("../../util/UIUtil");
  3806. /**
  3807. * List with supported commands. The keys are the names of the commands and
  3808. * the value is the function that processes the message.
  3809. * @type {{String: function}}
  3810. */
  3811. var commands = {
  3812. "topic" : processTopic
  3813. };
  3814. /**
  3815. * Extracts the command from the message.
  3816. * @param message the received message
  3817. * @returns {string} the command
  3818. */
  3819. function getCommand(message)
  3820. {
  3821. if(message)
  3822. {
  3823. for(var command in commands)
  3824. {
  3825. if(message.indexOf("/" + command) == 0)
  3826. return command;
  3827. }
  3828. }
  3829. return "";
  3830. };
  3831. /**
  3832. * Processes the data for topic command.
  3833. * @param commandArguments the arguments of the topic command.
  3834. */
  3835. function processTopic(commandArguments)
  3836. {
  3837. var topic = UIUtil.escapeHtml(commandArguments);
  3838. APP.xmpp.setSubject(topic);
  3839. }
  3840. /**
  3841. * Constructs new CommandProccessor instance from a message that
  3842. * handles commands received via chat messages.
  3843. * @param message the message
  3844. * @constructor
  3845. */
  3846. function CommandsProcessor(message)
  3847. {
  3848. var command = getCommand(message);
  3849. /**
  3850. * Returns the name of the command.
  3851. * @returns {String} the command
  3852. */
  3853. this.getCommand = function()
  3854. {
  3855. return command;
  3856. };
  3857. var messageArgument = message.substr(command.length + 2);
  3858. /**
  3859. * Returns the arguments of the command.
  3860. * @returns {string}
  3861. */
  3862. this.getArgument = function()
  3863. {
  3864. return messageArgument;
  3865. };
  3866. }
  3867. /**
  3868. * Checks whether this instance is valid command or not.
  3869. * @returns {boolean}
  3870. */
  3871. CommandsProcessor.prototype.isCommand = function()
  3872. {
  3873. if(this.getCommand())
  3874. return true;
  3875. return false;
  3876. };
  3877. /**
  3878. * Processes the command.
  3879. */
  3880. CommandsProcessor.prototype.processCommand = function()
  3881. {
  3882. if(!this.isCommand())
  3883. return;
  3884. commands[this.getCommand()](this.getArgument());
  3885. };
  3886. module.exports = CommandsProcessor;
  3887. },{"../../util/UIUtil":30}],20:[function(require,module,exports){
  3888. var Smileys = require("./smileys.json");
  3889. /**
  3890. * Processes links and smileys in "body"
  3891. */
  3892. function processReplacements(body)
  3893. {
  3894. //make links clickable
  3895. body = linkify(body);
  3896. //add smileys
  3897. body = smilify(body);
  3898. return body;
  3899. }
  3900. /**
  3901. * Finds and replaces all links in the links in "body"
  3902. * with their <a href=""></a>
  3903. */
  3904. function linkify(inputText)
  3905. {
  3906. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  3907. //URLs starting with http://, https://, or ftp://
  3908. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  3909. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  3910. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  3911. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  3912. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  3913. //Change email addresses to mailto:: links.
  3914. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  3915. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  3916. return replacedText;
  3917. }
  3918. /**
  3919. * Replaces common smiley strings with images
  3920. */
  3921. function smilify(body)
  3922. {
  3923. if(!body) {
  3924. return body;
  3925. }
  3926. var regexs = Smileys["regexs"];
  3927. for(var smiley in regexs) {
  3928. if(regexs.hasOwnProperty(smiley)) {
  3929. body = body.replace(regexs[smiley],
  3930. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  3931. }
  3932. }
  3933. return body;
  3934. }
  3935. module.exports = {
  3936. processReplacements: processReplacements,
  3937. linkify: linkify
  3938. };
  3939. },{"./smileys.json":21}],21:[function(require,module,exports){
  3940. module.exports={
  3941. "smileys": {
  3942. "smiley1": ":)",
  3943. "smiley2": ":(",
  3944. "smiley3": ":D",
  3945. "smiley4": "(y)",
  3946. "smiley5": " :P",
  3947. "smiley6": "(wave)",
  3948. "smiley7": "(blush)",
  3949. "smiley8": "(chuckle)",
  3950. "smiley9": "(shocked)",
  3951. "smiley10": ":*",
  3952. "smiley11": "(n)",
  3953. "smiley12": "(search)",
  3954. "smiley13": " <3",
  3955. "smiley14": "(oops)",
  3956. "smiley15": "(angry)",
  3957. "smiley16": "(angel)",
  3958. "smiley17": "(sick)",
  3959. "smiley18": ";(",
  3960. "smiley19": "(bomb)",
  3961. "smiley20": "(clap)",
  3962. "smiley21": " ;)"
  3963. },
  3964. "regexs": {
  3965. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  3966. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  3967. "smiley1": /(:-\)|:\))/gi,
  3968. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  3969. "smiley5": /(:-P|:P|:-p|:p)/gi,
  3970. "smiley6": /(\(wave\))/gi,
  3971. "smiley7": /(\(blush\))/gi,
  3972. "smiley8": /(\(chuckle\))/gi,
  3973. "smiley9": /(:-0|\(shocked\))/gi,
  3974. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  3975. "smiley11": /(\(n\))/gi,
  3976. "smiley12": /(\(search\))/g,
  3977. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  3978. "smiley14": /(\(oops\))/gi,
  3979. "smiley15": /(\(angry\))/gi,
  3980. "smiley16": /(\(angel\))/gi,
  3981. "smiley17": /(\(sick\))/gi,
  3982. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  3983. "smiley19": /(\(bomb\))/gi,
  3984. "smiley20": /(\(clap\))/gi,
  3985. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  3986. }
  3987. }
  3988. },{}],22:[function(require,module,exports){
  3989. var numberOfContacts = 0;
  3990. var notificationInterval;
  3991. /**
  3992. * Updates the number of participants in the contact list button and sets
  3993. * the glow
  3994. * @param delta indicates whether a new user has joined (1) or someone has
  3995. * left(-1)
  3996. */
  3997. function updateNumberOfParticipants(delta) {
  3998. //when the user is alone we don't show the number of participants
  3999. if(numberOfContacts === 0) {
  4000. $("#numberOfParticipants").text('');
  4001. numberOfContacts += delta;
  4002. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  4003. ContactList.setVisualNotification(true);
  4004. numberOfContacts += delta;
  4005. $("#numberOfParticipants").text(numberOfContacts);
  4006. }
  4007. }
  4008. /**
  4009. * Creates the avatar element.
  4010. *
  4011. * @return the newly created avatar element
  4012. */
  4013. function createAvatar(id) {
  4014. var avatar = document.createElement('img');
  4015. avatar.className = "icon-avatar avatar";
  4016. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  4017. return avatar;
  4018. }
  4019. /**
  4020. * Creates the display name paragraph.
  4021. *
  4022. * @param displayName the display name to set
  4023. */
  4024. function createDisplayNameParagraph(displayName) {
  4025. var p = document.createElement('p');
  4026. p.innerText = displayName;
  4027. return p;
  4028. }
  4029. function stopGlowing(glower) {
  4030. window.clearInterval(notificationInterval);
  4031. notificationInterval = false;
  4032. glower.removeClass('glowing');
  4033. if (!ContactList.isVisible()) {
  4034. glower.removeClass('active');
  4035. }
  4036. }
  4037. /**
  4038. * Contact list.
  4039. */
  4040. var ContactList = {
  4041. /**
  4042. * Indicates if the chat is currently visible.
  4043. *
  4044. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  4045. * otherwise
  4046. */
  4047. isVisible: function () {
  4048. return $('#contactlist').is(":visible");
  4049. },
  4050. /**
  4051. * Adds a contact for the given peerJid if such doesn't yet exist.
  4052. *
  4053. * @param peerJid the peerJid corresponding to the contact
  4054. * @param id the user's email or userId used to get the user's avatar
  4055. */
  4056. ensureAddContact: function (peerJid, id) {
  4057. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4058. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4059. if (!contact || contact.length <= 0)
  4060. ContactList.addContact(peerJid, id);
  4061. },
  4062. /**
  4063. * Adds a contact for the given peer jid.
  4064. *
  4065. * @param peerJid the jid of the contact to add
  4066. * @param id the email or userId of the user
  4067. */
  4068. addContact: function (peerJid, id) {
  4069. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4070. var contactlist = $('#contactlist>ul');
  4071. var newContact = document.createElement('li');
  4072. newContact.id = resourceJid;
  4073. newContact.className = "clickable";
  4074. newContact.onclick = function (event) {
  4075. if (event.currentTarget.className === "clickable") {
  4076. $(ContactList).trigger('contactclicked', [peerJid]);
  4077. }
  4078. };
  4079. newContact.appendChild(createAvatar(id));
  4080. newContact.appendChild(createDisplayNameParagraph("Participant"));
  4081. var clElement = contactlist.get(0);
  4082. if (resourceJid === APP.xmpp.myResource()
  4083. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  4084. clElement.insertBefore(newContact,
  4085. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  4086. }
  4087. else {
  4088. clElement.appendChild(newContact);
  4089. }
  4090. updateNumberOfParticipants(1);
  4091. },
  4092. /**
  4093. * Removes a contact for the given peer jid.
  4094. *
  4095. * @param peerJid the peerJid corresponding to the contact to remove
  4096. */
  4097. removeContact: function (peerJid) {
  4098. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4099. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4100. if (contact && contact.length > 0) {
  4101. var contactlist = $('#contactlist>ul');
  4102. contactlist.get(0).removeChild(contact.get(0));
  4103. updateNumberOfParticipants(-1);
  4104. }
  4105. },
  4106. setVisualNotification: function (show, stopGlowingIn) {
  4107. var glower = $('#contactListButton');
  4108. if (show && !notificationInterval) {
  4109. notificationInterval = window.setInterval(function () {
  4110. glower.toggleClass('active glowing');
  4111. }, 800);
  4112. }
  4113. else if (!show && notificationInterval) {
  4114. stopGlowing(glower);
  4115. }
  4116. if (stopGlowingIn) {
  4117. setTimeout(function () {
  4118. stopGlowing(glower);
  4119. }, stopGlowingIn);
  4120. }
  4121. },
  4122. setClickable: function (resourceJid, isClickable) {
  4123. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4124. if (isClickable) {
  4125. contact.addClass('clickable');
  4126. } else {
  4127. contact.removeClass('clickable');
  4128. }
  4129. },
  4130. onDisplayNameChange: function (peerJid, displayName) {
  4131. if (peerJid === 'localVideoContainer')
  4132. peerJid = APP.xmpp.myJid();
  4133. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4134. var contactName = $('#contactlist #' + resourceJid + '>p');
  4135. if (contactName && displayName && displayName.length > 0)
  4136. contactName.html(displayName);
  4137. }
  4138. };
  4139. module.exports = ContactList;
  4140. },{}],23:[function(require,module,exports){
  4141. var Avatar = require("../../avatar/Avatar");
  4142. var Settings = require("./../../../settings/Settings");
  4143. var UIUtil = require("../../util/UIUtil");
  4144. var languages = require("../../../../service/translation/languages");
  4145. function generateLanguagesSelectBox()
  4146. {
  4147. var currentLang = APP.translation.getCurrentLanguage();
  4148. var html = "<select id=\"languages_selectbox\">";
  4149. var langArray = languages.getLanguages();
  4150. for(var i = 0; i < langArray.length; i++)
  4151. {
  4152. var lang = langArray[i];
  4153. html += "<option ";
  4154. if(lang === currentLang)
  4155. html += "selected ";
  4156. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  4157. html += "</option>";
  4158. }
  4159. return html + "</select>";
  4160. }
  4161. var SettingsMenu = {
  4162. init: function () {
  4163. $("#updateSettings").before(generateLanguagesSelectBox());
  4164. $('#settingsmenu>input').keyup(function(event){
  4165. if(event.keyCode === 13) {//enter
  4166. SettingsMenu.update();
  4167. }
  4168. });
  4169. $("#updateSettings").click(function () {
  4170. SettingsMenu.update();
  4171. });
  4172. },
  4173. update: function() {
  4174. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  4175. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  4176. if(newDisplayName) {
  4177. var displayName = Settings.setDisplayName(newDisplayName);
  4178. APP.xmpp.addToPresence("displayName", displayName, true);
  4179. }
  4180. APP.translation.setLanguage($("#languages_selectbox").val());
  4181. APP.xmpp.addToPresence("email", newEmail);
  4182. var email = Settings.setEmail(newEmail);
  4183. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  4184. },
  4185. isVisible: function() {
  4186. return $('#settingsmenu').is(':visible');
  4187. },
  4188. setDisplayName: function(newDisplayName) {
  4189. var displayName = Settings.setDisplayName(newDisplayName);
  4190. $('#setDisplayName').get(0).value = displayName;
  4191. },
  4192. onDisplayNameChange: function(peerJid, newDisplayName) {
  4193. if(peerJid === 'localVideoContainer' ||
  4194. peerJid === APP.xmpp.myJid()) {
  4195. this.setDisplayName(newDisplayName);
  4196. }
  4197. }
  4198. };
  4199. module.exports = SettingsMenu;
  4200. },{"../../../../service/translation/languages":88,"../../avatar/Avatar":13,"../../util/UIUtil":30,"./../../../settings/Settings":38}],24:[function(require,module,exports){
  4201. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4202. var buttonHandlers = {
  4203. "bottom_toolbar_contact_list": function () {
  4204. BottomToolbar.toggleContactList();
  4205. },
  4206. "bottom_toolbar_film_strip": function () {
  4207. BottomToolbar.toggleFilmStrip();
  4208. },
  4209. "bottom_toolbar_chat": function () {
  4210. BottomToolbar.toggleChat();
  4211. }
  4212. };
  4213. var BottomToolbar = (function (my) {
  4214. my.init = function () {
  4215. for(var k in buttonHandlers)
  4216. $("#" + k).click(buttonHandlers[k]);
  4217. };
  4218. my.toggleChat = function() {
  4219. PanelToggler.toggleChat();
  4220. };
  4221. my.toggleContactList = function() {
  4222. PanelToggler.toggleContactList();
  4223. };
  4224. my.toggleFilmStrip = function() {
  4225. var filmstrip = $("#remoteVideos");
  4226. filmstrip.toggleClass("hidden");
  4227. };
  4228. $(document).bind("remotevideo.resized", function (event, width, height) {
  4229. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  4230. $('#bottomToolbar').css({bottom: bottom + 'px'});
  4231. });
  4232. return my;
  4233. }(BottomToolbar || {}));
  4234. module.exports = BottomToolbar;
  4235. },{"../side_pannels/SidePanelToggler":17}],25:[function(require,module,exports){
  4236. /* global APP,$, buttonClick, config, lockRoom,
  4237. setSharedKey, Util */
  4238. var messageHandler = require("../util/MessageHandler");
  4239. var BottomToolbar = require("./BottomToolbar");
  4240. var Prezi = require("../prezi/Prezi");
  4241. var Etherpad = require("../etherpad/Etherpad");
  4242. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4243. var Authentication = require("../authentication/Authentication");
  4244. var UIUtil = require("../util/UIUtil");
  4245. var AuthenticationEvents
  4246. = require("../../../service/authentication/AuthenticationEvents");
  4247. var roomUrl = null;
  4248. var sharedKey = '';
  4249. var UI = null;
  4250. var buttonHandlers =
  4251. {
  4252. "toolbar_button_mute": function () {
  4253. return APP.UI.toggleAudio();
  4254. },
  4255. "toolbar_button_camera": function () {
  4256. return APP.UI.toggleVideo();
  4257. },
  4258. /*"toolbar_button_authentication": function () {
  4259. return Toolbar.authenticateClicked();
  4260. },*/
  4261. "toolbar_button_record": function () {
  4262. return toggleRecording();
  4263. },
  4264. "toolbar_button_security": function () {
  4265. return Toolbar.openLockDialog();
  4266. },
  4267. "toolbar_button_link": function () {
  4268. return Toolbar.openLinkDialog();
  4269. },
  4270. "toolbar_button_chat": function () {
  4271. return BottomToolbar.toggleChat();
  4272. },
  4273. "toolbar_button_prezi": function () {
  4274. return Prezi.openPreziDialog();
  4275. },
  4276. "toolbar_button_etherpad": function () {
  4277. return Etherpad.toggleEtherpad(0);
  4278. },
  4279. "toolbar_button_desktopsharing": function () {
  4280. return APP.desktopsharing.toggleScreenSharing();
  4281. },
  4282. "toolbar_button_fullScreen": function()
  4283. {
  4284. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4285. return Toolbar.toggleFullScreen();
  4286. },
  4287. "toolbar_button_sip": function () {
  4288. return callSipButtonClicked();
  4289. },
  4290. "toolbar_button_settings": function () {
  4291. PanelToggler.toggleSettingsMenu();
  4292. },
  4293. "toolbar_button_hangup": function () {
  4294. return hangup();
  4295. },
  4296. "toolbar_button_login": function () {
  4297. Toolbar.authenticateClicked();
  4298. },
  4299. "toolbar_button_logout": function () {
  4300. // Ask for confirmation
  4301. messageHandler.openTwoButtonDialog(
  4302. "dialog.logoutTitle", "Logout",
  4303. "dialog.logoutQuestion",
  4304. "Are you sure you want to logout and stop the conference ?",
  4305. false, "Yes",
  4306. function (evt, yes) {
  4307. if (yes) {
  4308. APP.xmpp.logout(function (url) {
  4309. if (url) {
  4310. window.location.href = url;
  4311. } else {
  4312. hangup();
  4313. }
  4314. });
  4315. }
  4316. });
  4317. }
  4318. };
  4319. function hangup() {
  4320. APP.xmpp.disposeConference();
  4321. if(config.enableWelcomePage)
  4322. {
  4323. setTimeout(function()
  4324. {
  4325. window.localStorage.welcomePageDisabled = false;
  4326. window.location.pathname = "/";
  4327. }, 10000);
  4328. }
  4329. var title = APP.translation.generateTranslatonHTML(
  4330. "dialog.sessTerminated", "Session Terminated");
  4331. var msg = APP.translation.generateTranslatonHTML(
  4332. "dialog.hungUp","You hung up the call");
  4333. var button = APP.translation.generateTranslatonHTML(
  4334. "dialog.joinAgain", "Join again");
  4335. var buttons = {};
  4336. buttons.joinAgain = {title: button, value: true};
  4337. UI.messageHandler.openDialog(
  4338. title,
  4339. msg,
  4340. true,
  4341. buttons,
  4342. function(event, value, message, formVals)
  4343. {
  4344. window.location.reload();
  4345. return false;
  4346. }
  4347. );
  4348. }
  4349. /**
  4350. * Starts or stops the recording for the conference.
  4351. */
  4352. function toggleRecording() {
  4353. APP.xmpp.toggleRecording(function (callback) {
  4354. var msg = APP.translation.generateTranslatonHTML(
  4355. "dialog.recordingToken", "Enter recording token");
  4356. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  4357. '<h2>' + msg + '</h2>' +
  4358. '<input id="recordingToken" type="text" ' +
  4359. 'placeholder="token" autofocus>',
  4360. false,
  4361. "dialog.Save",
  4362. function (e, v, m, f) {
  4363. if (v) {
  4364. var token = document.getElementById('recordingToken');
  4365. if (token.value) {
  4366. callback(UIUtil.escapeHtml(token.value));
  4367. }
  4368. }
  4369. },
  4370. function (event) {
  4371. document.getElementById('recordingToken').focus();
  4372. },
  4373. function () {
  4374. }
  4375. );
  4376. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4377. }
  4378. /**
  4379. * Locks / unlocks the room.
  4380. */
  4381. function lockRoom(lock) {
  4382. var currentSharedKey = '';
  4383. if (lock)
  4384. currentSharedKey = sharedKey;
  4385. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4386. // password is required
  4387. if (sharedKey)
  4388. {
  4389. console.log('set room password');
  4390. Toolbar.lockLockButton();
  4391. }
  4392. else
  4393. {
  4394. console.log('removed room password');
  4395. Toolbar.unlockLockButton();
  4396. }
  4397. }, function (err) {
  4398. console.warn('setting password failed', err);
  4399. messageHandler.showError("dialog.lockTitle", 'Lock failed',
  4400. "dialog.lockMessage",
  4401. 'Failed to lock conference.',
  4402. err);
  4403. Toolbar.setSharedKey('');
  4404. }, function () {
  4405. console.warn('room passwords not supported');
  4406. messageHandler.showError("dialog.warning", 'Warning',
  4407. "dialog.passwordNotSupported",
  4408. 'Room passwords are currently not supported.');
  4409. Toolbar.setSharedKey('');
  4410. });
  4411. };
  4412. /**
  4413. * Invite participants to conference.
  4414. */
  4415. function inviteParticipants() {
  4416. if (roomUrl === null)
  4417. return;
  4418. var sharedKeyText = "";
  4419. if (sharedKey && sharedKey.length > 0) {
  4420. sharedKeyText =
  4421. "This conference is password protected. Please use the " +
  4422. "following pin when joining:%0D%0A%0D%0A" +
  4423. sharedKey + "%0D%0A%0D%0A";
  4424. }
  4425. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4426. var subject = "Invitation to a " + interfaceConfig.APP_NAME + " (" + conferenceName + ")";
  4427. var body = "Hey there, I%27d like to invite you to a " + interfaceConfig.APP_NAME +
  4428. " conference I%27ve just set up.%0D%0A%0D%0A" +
  4429. "Please click on the following link in order" +
  4430. " to join the conference.%0D%0A%0D%0A" +
  4431. roomUrl +
  4432. "%0D%0A%0D%0A" +
  4433. sharedKeyText +
  4434. "Note that " + interfaceConfig.APP_NAME + " is currently" +
  4435. " only supported by Chromium," +
  4436. " Google Chrome and Opera, so you need" +
  4437. " to be using one of these browsers.%0D%0A%0D%0A" +
  4438. "Talk to you in a sec!";
  4439. if (window.localStorage.displayname) {
  4440. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4441. }
  4442. if (interfaceConfig.INVITATION_POWERED_BY) {
  4443. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4444. }
  4445. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4446. }
  4447. function callSipButtonClicked()
  4448. {
  4449. var defaultNumber
  4450. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4451. var sipMsg = APP.translation.generateTranslatonHTML(
  4452. "dialog.sipMsg", "Enter SIP number");
  4453. messageHandler.openTwoButtonDialog(null, null, null,
  4454. '<h2>' + sipMsg + '</h2>' +
  4455. '<input id="sipNumber" type="text"' +
  4456. ' value="' + defaultNumber + '" autofocus>',
  4457. false,
  4458. "dialog.Dial",
  4459. function (e, v, m, f) {
  4460. if (v) {
  4461. var numberInput = document.getElementById('sipNumber');
  4462. if (numberInput.value) {
  4463. APP.xmpp.dial(numberInput.value, 'fromnumber',
  4464. UI.getRoomName(), sharedKey);
  4465. }
  4466. }
  4467. },
  4468. function (event) {
  4469. document.getElementById('sipNumber').focus();
  4470. }
  4471. );
  4472. }
  4473. var Toolbar = (function (my) {
  4474. my.init = function (ui) {
  4475. for(var k in buttonHandlers)
  4476. $("#" + k).click(buttonHandlers[k]);
  4477. UI = ui;
  4478. // Update login info
  4479. APP.xmpp.addListener(
  4480. AuthenticationEvents.IDENTITY_UPDATED,
  4481. function (authenticationEnabled, userIdentity) {
  4482. var loggedIn = false;
  4483. if (userIdentity) {
  4484. loggedIn = true;
  4485. }
  4486. //FIXME: XMPP authentication need improvements for "live" login
  4487. if (!APP.xmpp.isExternalAuthEnabled() && !loggedIn)
  4488. {
  4489. authenticationEnabled = false;
  4490. }
  4491. Toolbar.showAuthenticateButton(authenticationEnabled);
  4492. if (authenticationEnabled) {
  4493. Toolbar.setAuthenticatedIdentity(userIdentity);
  4494. Toolbar.showLoginButton(!loggedIn);
  4495. Toolbar.showLogoutButton(loggedIn);
  4496. }
  4497. }
  4498. );
  4499. },
  4500. /**
  4501. * Sets shared key
  4502. * @param sKey the shared key
  4503. */
  4504. my.setSharedKey = function (sKey) {
  4505. sharedKey = sKey;
  4506. };
  4507. my.authenticateClicked = function () {
  4508. Authentication.focusAuthenticationWindow();
  4509. // Get authentication URL
  4510. if (!APP.xmpp.getMUCJoined()) {
  4511. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4512. // If conference has not been started yet - redirect to login page
  4513. window.location.href = url;
  4514. });
  4515. } else {
  4516. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4517. // Otherwise - open popup with authentication URL
  4518. var authenticationWindow = Authentication.createAuthenticationWindow(
  4519. function () {
  4520. // On popup closed - retry room allocation
  4521. APP.xmpp.allocateConferenceFocus(
  4522. APP.UI.getRoomName(),
  4523. function () { console.info("AUTH DONE"); }
  4524. );
  4525. }, url);
  4526. if (!authenticationWindow) {
  4527. messageHandler.openMessageDialog(
  4528. null, null, "dialog.popupError",
  4529. "Your browser is blocking popup windows from this site." +
  4530. " Please enable popups in your browser security settings" +
  4531. " and try again.");
  4532. }
  4533. });
  4534. }
  4535. };
  4536. /**
  4537. * Updates the room invite url.
  4538. */
  4539. my.updateRoomUrl = function (newRoomUrl) {
  4540. roomUrl = newRoomUrl;
  4541. // If the invite dialog has been already opened we update the information.
  4542. var inviteLink = document.getElementById('inviteLinkRef');
  4543. if (inviteLink) {
  4544. inviteLink.value = roomUrl;
  4545. inviteLink.select();
  4546. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  4547. }
  4548. };
  4549. /**
  4550. * Disables and enables some of the buttons.
  4551. */
  4552. my.setupButtonsFromConfig = function () {
  4553. if (config.disablePrezi)
  4554. {
  4555. $("#prezi_button").css({display: "none"});
  4556. }
  4557. };
  4558. /**
  4559. * Opens the lock room dialog.
  4560. */
  4561. my.openLockDialog = function () {
  4562. // Only the focus is able to set a shared key.
  4563. if (!APP.xmpp.isModerator()) {
  4564. if (sharedKey) {
  4565. messageHandler.openMessageDialog(null, null,
  4566. "dialog.passwordError",
  4567. "This conversation is currently protected by" +
  4568. " a password. Only the owner of the conference" +
  4569. " could set a password.",
  4570. false,
  4571. "Password");
  4572. } else {
  4573. messageHandler.openMessageDialog(null, null, "dialog.passwordError2",
  4574. "This conversation isn't currently protected by" +
  4575. " a password. Only the owner of the conference" +
  4576. " could set a password.",
  4577. false,
  4578. "Password");
  4579. }
  4580. } else {
  4581. if (sharedKey) {
  4582. messageHandler.openTwoButtonDialog(null, null,
  4583. "dialog.passwordCheck",
  4584. "Are you sure you would like to remove your password?",
  4585. false,
  4586. "dialog.Remove",
  4587. function (e, v) {
  4588. if (v) {
  4589. Toolbar.setSharedKey('');
  4590. lockRoom(false);
  4591. }
  4592. });
  4593. } else {
  4594. var msg = APP.translation.generateTranslatonHTML(
  4595. "dialog.passwordMsg", "Set a password to lock your room");
  4596. var yourPassword = APP.translation.translateString(
  4597. "dialog.yourPassword", null, "your password");
  4598. messageHandler.openTwoButtonDialog(null, null, null,
  4599. '<h2>' + msg + '</h2>' +
  4600. '<input id="lockKey" type="text"' +
  4601. 'placeholder="' + yourPassword + '" autofocus>',
  4602. false,
  4603. "dialog.Save",
  4604. function (e, v) {
  4605. if (v) {
  4606. var lockKey = document.getElementById('lockKey');
  4607. if (lockKey.value) {
  4608. Toolbar.setSharedKey(UIUtil.escapeHtml(lockKey.value));
  4609. lockRoom(true);
  4610. }
  4611. }
  4612. },
  4613. function () {
  4614. document.getElementById('lockKey').focus();
  4615. }
  4616. );
  4617. }
  4618. }
  4619. };
  4620. /**
  4621. * Opens the invite link dialog.
  4622. */
  4623. my.openLinkDialog = function () {
  4624. var inviteLink;
  4625. if (roomUrl === null) {
  4626. inviteLink = "Your conference is currently being created...";
  4627. } else {
  4628. inviteLink = encodeURI(roomUrl);
  4629. }
  4630. messageHandler.openTwoButtonDialog("dialog.shareLink",
  4631. "Share this link with everyone you want to invite", null,
  4632. '<input id="inviteLinkRef" type="text" value="' +
  4633. inviteLink + '" onclick="this.select();" readonly>',
  4634. false,
  4635. "dialog.Invite",
  4636. function (e, v) {
  4637. if (v) {
  4638. if (roomUrl) {
  4639. inviteParticipants();
  4640. }
  4641. }
  4642. },
  4643. function () {
  4644. if (roomUrl) {
  4645. document.getElementById('inviteLinkRef').select();
  4646. } else {
  4647. document.getElementById('jqi_state0_buttonInvite')
  4648. .disabled = true;
  4649. }
  4650. }
  4651. );
  4652. };
  4653. /**
  4654. * Opens the settings dialog.
  4655. */
  4656. my.openSettingsDialog = function () {
  4657. var settings1 = APP.translation.generateTranslatonHTML(
  4658. "dialog.settings1", "Configure your conference");
  4659. var settings2 = APP.translation.generateTranslatonHTML(
  4660. "dialog.settings2", "Participants join muted");
  4661. var settings3 = APP.translation.generateTranslatonHTML(
  4662. "dialog.settings3", "Require nicknames<br/><br/>" +
  4663. "Set a password to lock your room:");
  4664. var yourPassword = APP.translation.translateString(
  4665. "dialog.yourPassword", null, "your password");
  4666. messageHandler.openTwoButtonDialog(null,
  4667. '<h2>' + settings1 + '</h2>' +
  4668. '<input type="checkbox" id="initMuted">' +
  4669. settings2 + '<br/>' +
  4670. '<input type="checkbox" id="requireNicknames">' +
  4671. settings3 +
  4672. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  4673. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  4674. null,
  4675. null,
  4676. false,
  4677. "dialog.Save",
  4678. function () {
  4679. document.getElementById('lockKey').focus();
  4680. },
  4681. function (e, v) {
  4682. if (v) {
  4683. if ($('#initMuted').is(":checked")) {
  4684. // it is checked
  4685. }
  4686. if ($('#requireNicknames').is(":checked")) {
  4687. // it is checked
  4688. }
  4689. /*
  4690. var lockKey = document.getElementById('lockKey');
  4691. if (lockKey.value) {
  4692. setSharedKey(lockKey.value);
  4693. lockRoom(true);
  4694. }
  4695. */
  4696. }
  4697. }
  4698. );
  4699. };
  4700. /**
  4701. * Toggles the application in and out of full screen mode
  4702. * (a.k.a. presentation mode in Chrome).
  4703. */
  4704. my.toggleFullScreen = function () {
  4705. var fsElement = document.documentElement;
  4706. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  4707. //Enter Full Screen
  4708. if (fsElement.mozRequestFullScreen) {
  4709. fsElement.mozRequestFullScreen();
  4710. }
  4711. else {
  4712. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  4713. }
  4714. } else {
  4715. //Exit Full Screen
  4716. if (document.mozCancelFullScreen) {
  4717. document.mozCancelFullScreen();
  4718. } else {
  4719. document.webkitCancelFullScreen();
  4720. }
  4721. }
  4722. };
  4723. /**
  4724. * Unlocks the lock button state.
  4725. */
  4726. my.unlockLockButton = function () {
  4727. if ($("#lockIcon").hasClass("icon-security-locked"))
  4728. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4729. };
  4730. /**
  4731. * Updates the lock button state to locked.
  4732. */
  4733. my.lockLockButton = function () {
  4734. if ($("#lockIcon").hasClass("icon-security"))
  4735. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4736. };
  4737. /**
  4738. * Shows or hides authentication button
  4739. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  4740. */
  4741. my.showAuthenticateButton = function (show) {
  4742. if (show) {
  4743. $('#authentication').css({display: "inline"});
  4744. }
  4745. else {
  4746. $('#authentication').css({display: "none"});
  4747. }
  4748. };
  4749. // Shows or hides the 'recording' button.
  4750. my.showRecordingButton = function (show) {
  4751. if (!config.enableRecording) {
  4752. return;
  4753. }
  4754. if (show) {
  4755. $('#recording').css({display: "inline"});
  4756. }
  4757. else {
  4758. $('#recording').css({display: "none"});
  4759. }
  4760. };
  4761. // Sets the state of the recording button
  4762. my.setRecordingButtonState = function (isRecording) {
  4763. if (isRecording) {
  4764. $('#recordButton').removeClass("icon-recEnable");
  4765. $('#recordButton').addClass("icon-recEnable active");
  4766. } else {
  4767. $('#recordButton').removeClass("icon-recEnable active");
  4768. $('#recordButton').addClass("icon-recEnable");
  4769. }
  4770. };
  4771. // Shows or hides SIP calls button
  4772. my.showSipCallButton = function (show) {
  4773. if (APP.xmpp.isSipGatewayEnabled() && show) {
  4774. $('#sipCallButton').css({display: "inline-block"});
  4775. } else {
  4776. $('#sipCallButton').css({display: "none"});
  4777. }
  4778. };
  4779. /**
  4780. * Displays user authenticated identity name(login).
  4781. * @param authIdentity identity name to be displayed.
  4782. */
  4783. my.setAuthenticatedIdentity = function (authIdentity) {
  4784. if (authIdentity) {
  4785. $('#toolbar_auth_identity').css({display: "list-item"});
  4786. $('#toolbar_auth_identity').text(authIdentity);
  4787. } else {
  4788. $('#toolbar_auth_identity').css({display: "none"});
  4789. }
  4790. };
  4791. /**
  4792. * Shows/hides login button.
  4793. * @param show <tt>true</tt> to show
  4794. */
  4795. my.showLoginButton = function (show) {
  4796. if (show) {
  4797. $('#toolbar_button_login').css({display: "list-item"});
  4798. } else {
  4799. $('#toolbar_button_login').css({display: "none"});
  4800. }
  4801. };
  4802. /**
  4803. * Shows/hides logout button.
  4804. * @param show <tt>true</tt> to show
  4805. */
  4806. my.showLogoutButton = function (show) {
  4807. if (show) {
  4808. $('#toolbar_button_logout').css({display: "list-item"});
  4809. } else {
  4810. $('#toolbar_button_logout').css({display: "none"});
  4811. }
  4812. };
  4813. /**
  4814. * Sets the state of the button. The button has blue glow if desktop
  4815. * streaming is active.
  4816. * @param active the state of the desktop streaming.
  4817. */
  4818. my.changeDesktopSharingButtonState = function (active) {
  4819. var button = $("#desktopsharing > a");
  4820. if (active)
  4821. {
  4822. button.addClass("glow");
  4823. }
  4824. else
  4825. {
  4826. button.removeClass("glow");
  4827. }
  4828. };
  4829. return my;
  4830. }(Toolbar || {}));
  4831. module.exports = Toolbar;
  4832. },{"../../../service/authentication/AuthenticationEvents":85,"../authentication/Authentication":12,"../etherpad/Etherpad":14,"../prezi/Prezi":15,"../side_pannels/SidePanelToggler":17,"../util/MessageHandler":28,"../util/UIUtil":30,"./BottomToolbar":24}],26:[function(require,module,exports){
  4833. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  4834. var toolbarTimeoutObject,
  4835. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  4836. function showDesktopSharingButton() {
  4837. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  4838. $('#desktopsharing').css({display: "inline"});
  4839. } else {
  4840. $('#desktopsharing').css({display: "none"});
  4841. }
  4842. }
  4843. /**
  4844. * Hides the toolbar.
  4845. */
  4846. function hideToolbar() {
  4847. var header = $("#header"),
  4848. bottomToolbar = $("#bottomToolbar");
  4849. var isToolbarHover = false;
  4850. header.find('*').each(function () {
  4851. var id = $(this).attr('id');
  4852. if ($("#" + id + ":hover").length > 0) {
  4853. isToolbarHover = true;
  4854. }
  4855. });
  4856. if ($("#bottomToolbar:hover").length > 0) {
  4857. isToolbarHover = true;
  4858. }
  4859. clearTimeout(toolbarTimeoutObject);
  4860. toolbarTimeoutObject = null;
  4861. if (!isToolbarHover) {
  4862. header.hide("slide", { direction: "up", duration: 300});
  4863. $('#subject').animate({top: "-=40"}, 300);
  4864. if ($("#remoteVideos").hasClass("hidden")) {
  4865. bottomToolbar.hide(
  4866. "slide", {direction: "right", duration: 300});
  4867. }
  4868. }
  4869. else {
  4870. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4871. }
  4872. }
  4873. var ToolbarToggler = {
  4874. /**
  4875. * Shows the main toolbar.
  4876. */
  4877. showToolbar: function () {
  4878. var header = $("#header"),
  4879. bottomToolbar = $("#bottomToolbar");
  4880. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  4881. header.show("slide", { direction: "up", duration: 300});
  4882. $('#subject').animate({top: "+=40"}, 300);
  4883. if (!bottomToolbar.is(":visible")) {
  4884. bottomToolbar.show(
  4885. "slide", {direction: "right", duration: 300});
  4886. }
  4887. if (toolbarTimeoutObject) {
  4888. clearTimeout(toolbarTimeoutObject);
  4889. toolbarTimeoutObject = null;
  4890. }
  4891. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4892. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  4893. }
  4894. if (APP.xmpp.isModerator())
  4895. {
  4896. // TODO: Enable settings functionality.
  4897. // Need to uncomment the settings button in index.html.
  4898. // $('#settingsButton').css({visibility:"visible"});
  4899. }
  4900. // Show/hide desktop sharing button
  4901. showDesktopSharingButton();
  4902. },
  4903. /**
  4904. * Docks/undocks the toolbar.
  4905. *
  4906. * @param isDock indicates what operation to perform
  4907. */
  4908. dockToolbar: function (isDock) {
  4909. if (isDock) {
  4910. // First make sure the toolbar is shown.
  4911. if (!$('#header').is(':visible')) {
  4912. this.showToolbar();
  4913. }
  4914. // Then clear the time out, to dock the toolbar.
  4915. if (toolbarTimeoutObject) {
  4916. clearTimeout(toolbarTimeoutObject);
  4917. toolbarTimeoutObject = null;
  4918. }
  4919. }
  4920. else {
  4921. if (!$('#header').is(':visible')) {
  4922. this.showToolbar();
  4923. }
  4924. else {
  4925. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4926. }
  4927. }
  4928. },
  4929. showDesktopSharingButton: showDesktopSharingButton
  4930. };
  4931. module.exports = ToolbarToggler;
  4932. },{}],27:[function(require,module,exports){
  4933. var JitsiPopover = (function () {
  4934. /**
  4935. * Constructs new JitsiPopover and attaches it to the element
  4936. * @param element jquery selector
  4937. * @param options the options for the popover.
  4938. * @constructor
  4939. */
  4940. function JitsiPopover(element, options)
  4941. {
  4942. this.options = {
  4943. skin: "white",
  4944. content: ""
  4945. };
  4946. if(options)
  4947. {
  4948. if(options.skin)
  4949. this.options.skin = options.skin;
  4950. if(options.content)
  4951. this.options.content = options.content;
  4952. }
  4953. this.elementIsHovered = false;
  4954. this.popoverIsHovered = false;
  4955. this.popoverShown = false;
  4956. element.data("jitsi_popover", this);
  4957. this.element = element;
  4958. this.template = ' <div class="jitsipopover ' + this.options.skin +
  4959. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  4960. '<div class="jitsiPopupmenuPadding"></div></div>';
  4961. var self = this;
  4962. this.element.on("mouseenter", function () {
  4963. self.elementIsHovered = true;
  4964. self.show();
  4965. }).on("mouseleave", function () {
  4966. self.elementIsHovered = false;
  4967. setTimeout(function () {
  4968. self.hide();
  4969. }, 10);
  4970. });
  4971. }
  4972. /**
  4973. * Shows the popover
  4974. */
  4975. JitsiPopover.prototype.show = function () {
  4976. this.createPopover();
  4977. this.popoverShown = true;
  4978. };
  4979. /**
  4980. * Hides the popover
  4981. */
  4982. JitsiPopover.prototype.hide = function () {
  4983. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  4984. {
  4985. this.forceHide();
  4986. }
  4987. };
  4988. /**
  4989. * Hides the popover
  4990. */
  4991. JitsiPopover.prototype.forceHide = function () {
  4992. $(".jitsipopover").remove();
  4993. this.popoverShown = false;
  4994. };
  4995. /**
  4996. * Creates the popover html
  4997. */
  4998. JitsiPopover.prototype.createPopover = function () {
  4999. $("body").append(this.template);
  5000. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  5001. var self = this;
  5002. $(".jitsipopover").on("mouseenter", function () {
  5003. self.popoverIsHovered = true;
  5004. }).on("mouseleave", function () {
  5005. self.popoverIsHovered = false;
  5006. self.hide();
  5007. });
  5008. this.refreshPosition();
  5009. };
  5010. /**
  5011. * Refreshes the position of the popover
  5012. */
  5013. JitsiPopover.prototype.refreshPosition = function () {
  5014. $(".jitsipopover").position({
  5015. my: "bottom",
  5016. at: "top",
  5017. collision: "fit",
  5018. of: this.element,
  5019. using: function (position, elements) {
  5020. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  5021. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  5022. $(".jitsipopover > .arrow").css({left: calcLeft});
  5023. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  5024. }
  5025. });
  5026. };
  5027. /**
  5028. * Updates the content of popover.
  5029. * @param content new content
  5030. */
  5031. JitsiPopover.prototype.updateContent = function (content) {
  5032. this.options.content = content;
  5033. if(!this.popoverShown)
  5034. return;
  5035. $(".jitsipopover").remove();
  5036. this.createPopover();
  5037. };
  5038. return JitsiPopover;
  5039. })();
  5040. module.exports = JitsiPopover;
  5041. },{}],28:[function(require,module,exports){
  5042. /* global $, jQuery */
  5043. var messageHandler = (function(my) {
  5044. /**
  5045. * Shows a message to the user.
  5046. *
  5047. * @param titleString the title of the message
  5048. * @param messageString the text of the message
  5049. */
  5050. my.openMessageDialog = function(titleKey, titleString,
  5051. messageKey, messageString) {
  5052. var title = null;
  5053. if(titleKey)
  5054. {
  5055. title = APP.translation.generateTranslatonHTML(titleKey,
  5056. titleString);
  5057. }
  5058. var message = APP.translation.generateTranslatonHTML(messageKey,
  5059. messageString);
  5060. $.prompt(message,
  5061. {
  5062. title: title,
  5063. persistent: false
  5064. }
  5065. );
  5066. };
  5067. /**
  5068. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5069. *
  5070. * @param titleString the title of the message
  5071. * @param msgString the text of the message
  5072. * @param persistent boolean value which determines whether the message is persistent or not
  5073. * @param leftButton the fist button's text
  5074. * @param submitFunction function to be called on submit
  5075. * @param loadedFunction function to be called after the prompt is fully loaded
  5076. * @param closeFunction function to be called after the prompt is closed
  5077. */
  5078. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  5079. persistent, leftButtonKey, submitFunction, loadedFunction,
  5080. closeFunction)
  5081. {
  5082. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  5083. var buttons = {};
  5084. buttons.leftButton = {title: leftButton, value: true};
  5085. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel",
  5086. "Cancel");
  5087. buttons.Cancel = {title: cancelButton, value: false};
  5088. var message = msgString, title = titleString;
  5089. if(titleKey)
  5090. {
  5091. title = APP.translation.generateTranslatonHTML(titleKey, titleString);
  5092. }
  5093. if(msgKey) {
  5094. message = APP.translation.generateTranslatonHTML(msgKey, msgString);
  5095. }
  5096. $.prompt(message, {
  5097. title: title,
  5098. persistent: false,
  5099. buttons: buttons,
  5100. defaultButton: 1,
  5101. loaded: loadedFunction,
  5102. submit: submitFunction,
  5103. close: closeFunction
  5104. });
  5105. };
  5106. /**
  5107. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5108. *
  5109. * @param titleString the title of the message
  5110. * @param msgString the text of the message
  5111. * @param persistent boolean value which determines whether the message is persistent or not
  5112. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  5113. * that will be passed to submitFunction
  5114. * @param submitFunction function to be called on submit
  5115. * @param loadedFunction function to be called after the prompt is fully loaded
  5116. */
  5117. my.openDialog = function (titleString, msgString, persistent, buttons,
  5118. submitFunction, loadedFunction) {
  5119. var args = {
  5120. title: titleString,
  5121. persistent: persistent,
  5122. buttons: buttons,
  5123. defaultButton: 1,
  5124. loaded: loadedFunction,
  5125. submit: submitFunction
  5126. };
  5127. if (persistent) {
  5128. args.closeText = '';
  5129. }
  5130. return $.prompt(msgString, args);
  5131. };
  5132. /**
  5133. * Closes currently opened dialog.
  5134. */
  5135. my.closeDialog = function () {
  5136. $.prompt.close();
  5137. };
  5138. /**
  5139. * Shows a dialog with different states to the user.
  5140. *
  5141. * @param statesObject object containing all the states of the dialog
  5142. * @param loadedFunction function to be called after the prompt is fully loaded
  5143. * @param stateChangedFunction function to be called when the state of the dialog is changed
  5144. */
  5145. my.openDialogWithStates = function(statesObject, loadedFunction, stateChangedFunction) {
  5146. var myPrompt = $.prompt(statesObject);
  5147. myPrompt.on('impromptu:loaded', loadedFunction);
  5148. myPrompt.on('impromptu:statechanged', stateChangedFunction);
  5149. };
  5150. /**
  5151. * Opens new popup window for given <tt>url</tt> centered over current
  5152. * window.
  5153. *
  5154. * @param url the URL to be displayed in the popup window
  5155. * @param w the width of the popup window
  5156. * @param h the height of the popup window
  5157. * @param onPopupClosed optional callback function called when popup window
  5158. * has been closed.
  5159. *
  5160. * @returns popup window object if opened successfully or undefined
  5161. * in case we failed to open it(popup blocked)
  5162. */
  5163. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  5164. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  5165. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  5166. var popup = window.open(
  5167. url, '_blank',
  5168. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  5169. if (popup && onPopupClosed) {
  5170. var pollTimer = window.setInterval(function () {
  5171. if (popup.closed !== false) {
  5172. window.clearInterval(pollTimer);
  5173. onPopupClosed();
  5174. }
  5175. }, 200);
  5176. }
  5177. return popup;
  5178. };
  5179. /**
  5180. * Shows a dialog prompting the user to send an error report.
  5181. *
  5182. * @param titleString the title of the message
  5183. * @param msgString the text of the message
  5184. * @param error the error that is being reported
  5185. */
  5186. my.openReportDialog = function(titleKey, titleString, msgKey,
  5187. msgString, error) {
  5188. my.openMessageDialog(titleKey, titleString, msgKey, msgString);
  5189. console.log(error);
  5190. //FIXME send the error to the server
  5191. };
  5192. /**
  5193. * Shows an error dialog to the user.
  5194. * @param title the title of the message
  5195. * @param message the text of the messafe
  5196. */
  5197. my.showError = function(titleKey, title, msgKey, message) {
  5198. if(!titleKey) {
  5199. title = "Oops!";
  5200. titleKey = "dialog.oops";
  5201. }
  5202. if(!msgKey)
  5203. {
  5204. message = "There was some kind of error";
  5205. msgKey = "dialog.defaultError";
  5206. }
  5207. messageHandler.openMessageDialog(titleKey, title, msgKey, message);
  5208. };
  5209. my.notify = function(displayName, displayNameKey, displayNameDefault,
  5210. cls, messageKey, messageDefault, messageArguments) {
  5211. var displayNameSpan = '<span class="nickname" ';
  5212. if(displayName)
  5213. {
  5214. displayNameSpan += ">" + displayName;
  5215. }
  5216. else
  5217. {
  5218. displayNameSpan += "data-i18n='" + displayNameKey +
  5219. "'>" + APP.translation.translateString(displayNameKey, null,
  5220. {defaultValue: displayNameDefault});
  5221. }
  5222. displayNameSpan += "</span>";
  5223. var lMessageArguments = messageArguments;
  5224. if(!messageArguments)
  5225. lMessageArguments = {};
  5226. lMessageArguments.defaultValue = messageDefault;
  5227. toastr.info(
  5228. displayNameSpan + '<br>' +
  5229. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  5230. (messageArguments?
  5231. " i18n-options='" + JSON.stringify(messageArguments) + "'"
  5232. : "") + ">" +
  5233. APP.translation.translateString(messageKey, null,
  5234. lMessageArguments) +
  5235. '</span>');
  5236. };
  5237. return my;
  5238. }(messageHandler || {}));
  5239. module.exports = messageHandler;
  5240. },{}],29:[function(require,module,exports){
  5241. var UIEvents = require("../../../service/UI/UIEvents");
  5242. var nickname = null;
  5243. var eventEmitter = null;
  5244. var NickanameHandler = {
  5245. init: function (emitter) {
  5246. eventEmitter = emitter;
  5247. var storedDisplayName = window.localStorage.displayname;
  5248. if (storedDisplayName) {
  5249. nickname = storedDisplayName;
  5250. }
  5251. },
  5252. setNickname: function (newNickname) {
  5253. if (!newNickname || nickname === newNickname)
  5254. return;
  5255. nickname = newNickname;
  5256. window.localStorage.displayname = nickname;
  5257. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  5258. },
  5259. getNickname: function () {
  5260. return nickname;
  5261. },
  5262. addListener: function (type, listener) {
  5263. eventEmitter.on(type, listener);
  5264. }
  5265. };
  5266. module.exports = NickanameHandler;
  5267. },{"../../../service/UI/UIEvents":84}],30:[function(require,module,exports){
  5268. /**
  5269. * Created by hristo on 12/22/14.
  5270. */
  5271. module.exports = {
  5272. /**
  5273. * Returns the available video width.
  5274. */
  5275. getAvailableVideoWidth: function () {
  5276. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5277. var rightPanelWidth
  5278. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5279. return window.innerWidth - rightPanelWidth;
  5280. },
  5281. /**
  5282. * Changes the style class of the element given by id.
  5283. */
  5284. buttonClick: function(id, classname) {
  5285. $(id).toggleClass(classname); // add the class to the clicked element
  5286. },
  5287. /**
  5288. * Returns the text width for the given element.
  5289. *
  5290. * @param el the element
  5291. */
  5292. getTextWidth: function (el) {
  5293. return (el.clientWidth + 1);
  5294. },
  5295. /**
  5296. * Returns the text height for the given element.
  5297. *
  5298. * @param el the element
  5299. */
  5300. getTextHeight: function (el) {
  5301. return (el.clientHeight + 1);
  5302. },
  5303. /**
  5304. * Plays the sound given by id.
  5305. *
  5306. * @param id the identifier of the audio element.
  5307. */
  5308. playSoundNotification: function (id) {
  5309. document.getElementById(id).play();
  5310. },
  5311. /**
  5312. * Escapes the given text.
  5313. */
  5314. escapeHtml: function (unsafeText) {
  5315. return $('<div/>').text(unsafeText).html();
  5316. },
  5317. imageToGrayScale: function (canvas) {
  5318. var context = canvas.getContext('2d');
  5319. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5320. var pixels = imgData.data;
  5321. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5322. var grayscale
  5323. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5324. pixels[i ] = grayscale; // red
  5325. pixels[i+1] = grayscale; // green
  5326. pixels[i+2] = grayscale; // blue
  5327. // pixels[i+3] is alpha
  5328. }
  5329. // redraw the image in black & white
  5330. context.putImageData(imgData, 0, 0);
  5331. },
  5332. setTooltip: function (element, key, position) {
  5333. element.setAttribute("data-i18n", "[data-content]" + key);
  5334. element.setAttribute("data-toggle", "popover");
  5335. element.setAttribute("data-placement", position);
  5336. element.setAttribute("data-html", true);
  5337. element.setAttribute("data-container", "body");
  5338. }
  5339. };
  5340. },{"../side_pannels/SidePanelToggler":17}],31:[function(require,module,exports){
  5341. var JitsiPopover = require("../util/JitsiPopover");
  5342. /**
  5343. * Constructs new connection indicator.
  5344. * @param videoContainer the video container associated with the indicator.
  5345. * @constructor
  5346. */
  5347. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5348. {
  5349. this.videoContainer = videoContainer;
  5350. this.bandwidth = null;
  5351. this.packetLoss = null;
  5352. this.bitrate = null;
  5353. this.showMoreValue = false;
  5354. this.resolution = null;
  5355. this.transport = [];
  5356. this.popover = null;
  5357. this.jid = jid;
  5358. this.create();
  5359. this.videoLayout = VideoLayout;
  5360. }
  5361. /**
  5362. * Values for the connection quality
  5363. * @type {{98: string,
  5364. * 81: string,
  5365. * 64: string,
  5366. * 47: string,
  5367. * 30: string,
  5368. * 0: string}}
  5369. */
  5370. ConnectionIndicator.connectionQualityValues = {
  5371. 98: "18px", //full
  5372. 81: "15px",//4 bars
  5373. 64: "11px",//3 bars
  5374. 47: "7px",//2 bars
  5375. 30: "3px",//1 bar
  5376. 0: "0px"//empty
  5377. };
  5378. ConnectionIndicator.getIP = function(value)
  5379. {
  5380. return value.substring(0, value.lastIndexOf(":"));
  5381. };
  5382. ConnectionIndicator.getPort = function(value)
  5383. {
  5384. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5385. };
  5386. ConnectionIndicator.getStringFromArray = function (array) {
  5387. var res = "";
  5388. for(var i = 0; i < array.length; i++)
  5389. {
  5390. res += (i === 0? "" : ", ") + array[i];
  5391. }
  5392. return res;
  5393. };
  5394. /**
  5395. * Generates the html content.
  5396. * @returns {string} the html content.
  5397. */
  5398. ConnectionIndicator.prototype.generateText = function () {
  5399. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5400. var translate = APP.translation.translateString;
  5401. if(this.bitrate === null)
  5402. {
  5403. downloadBitrate = "N/A";
  5404. uploadBitrate = "N/A";
  5405. }
  5406. else
  5407. {
  5408. downloadBitrate =
  5409. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5410. uploadBitrate =
  5411. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5412. }
  5413. if(this.packetLoss === null)
  5414. {
  5415. packetLoss = "N/A";
  5416. }
  5417. else
  5418. {
  5419. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5420. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5421. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5422. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5423. }
  5424. var resolutionValue = null;
  5425. if(this.resolution && this.jid != null)
  5426. {
  5427. var keys = Object.keys(this.resolution);
  5428. if(keys.length == 1)
  5429. {
  5430. for(var ssrc in this.resolution)
  5431. {
  5432. resolutionValue = this.resolution[ssrc];
  5433. }
  5434. }
  5435. else if(keys.length > 1)
  5436. {
  5437. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  5438. resolutionValue = this.resolution[displayedSsrc];
  5439. }
  5440. }
  5441. if(this.jid === null)
  5442. {
  5443. resolution = "";
  5444. if(this.resolution === null || !Object.keys(this.resolution) ||
  5445. Object.keys(this.resolution).length === 0)
  5446. {
  5447. resolution = "N/A";
  5448. }
  5449. else
  5450. for(i in this.resolution)
  5451. {
  5452. resolutionValue = this.resolution[i];
  5453. if(resolutionValue)
  5454. {
  5455. if(resolutionValue.height &&
  5456. resolutionValue.width)
  5457. {
  5458. resolution += (resolution === ""? "" : ", ") +
  5459. resolutionValue.width + "x" +
  5460. resolutionValue.height;
  5461. }
  5462. }
  5463. }
  5464. }
  5465. else if(!resolutionValue ||
  5466. !resolutionValue.height ||
  5467. !resolutionValue.width)
  5468. {
  5469. resolution = "N/A";
  5470. }
  5471. else
  5472. {
  5473. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5474. }
  5475. var result = "<table style='width:100%'>" +
  5476. "<tr>" +
  5477. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5478. translate("connectionindicator.bitrate") + "</span></td>" +
  5479. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5480. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5481. uploadBitrate + "</td>" +
  5482. "</tr><tr>" +
  5483. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5484. translate("connectionindicator.packetloss") + "</span></td>" +
  5485. "<td>" + packetLoss + "</td>" +
  5486. "</tr><tr>" +
  5487. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5488. translate("connectionindicator.resolution") + "</span></td>" +
  5489. "<td>" + resolution + "</td></tr></table>";
  5490. if(this.videoContainer.id == "localVideoContainer") {
  5491. result += "<div class=\"jitsipopover_showmore\" " +
  5492. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5493. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5494. (this.showMoreValue ? "less" : "more") + "'>" +
  5495. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5496. "</div><br />";
  5497. }
  5498. if(this.showMoreValue)
  5499. {
  5500. var downloadBandwidth, uploadBandwidth, transport;
  5501. if(this.bandwidth === null)
  5502. {
  5503. downloadBandwidth = "N/A";
  5504. uploadBandwidth = "N/A";
  5505. }
  5506. else
  5507. {
  5508. downloadBandwidth = this.bandwidth.download?
  5509. this.bandwidth.download + " Kbps" :
  5510. "N/A";
  5511. uploadBandwidth = this.bandwidth.upload?
  5512. this.bandwidth.upload + " Kbps" :
  5513. "N/A";
  5514. }
  5515. if(!this.transport || this.transport.length === 0)
  5516. {
  5517. transport = "<tr>" +
  5518. "<td><span class='jitsipopover_blue' " +
  5519. "data-i18n='connectionindicator.address'>" +
  5520. translate("connectionindicator.address") + "</span></td>" +
  5521. "<td> N/A</td></tr>";
  5522. }
  5523. else
  5524. {
  5525. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5526. for(i = 0; i < this.transport.length; i++)
  5527. {
  5528. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5529. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5530. var localIP =
  5531. ConnectionIndicator.getIP(this.transport[i].localip);
  5532. var localPort =
  5533. ConnectionIndicator.getPort(this.transport[i].localip);
  5534. if(data.remoteIP.indexOf(ip) == -1)
  5535. {
  5536. data.remoteIP.push(ip);
  5537. }
  5538. if(data.remotePort.indexOf(port) == -1)
  5539. {
  5540. data.remotePort.push(port);
  5541. }
  5542. if(data.localIP.indexOf(localIP) == -1)
  5543. {
  5544. data.localIP.push(localIP);
  5545. }
  5546. if(data.localPort.indexOf(localPort) == -1)
  5547. {
  5548. data.localPort.push(localPort);
  5549. }
  5550. }
  5551. var local_address_key = "connectionindicator." +
  5552. (data.localIP.length > 1? "localaddresses" : "localaddress");
  5553. var remote_address_key = "connectionindicator." +
  5554. (data.remoteIP.length > 1? "remoteaddresses" : "remoteaddress");
  5555. var localTransport =
  5556. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5557. local_address_key +"'>" +
  5558. translate(local_address_key) + "</span></td><td> " +
  5559. ConnectionIndicator.getStringFromArray(data.localIP) +
  5560. "</td></tr>";
  5561. transport =
  5562. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5563. remote_address_key + "'>" +
  5564. translate(remote_address_key) + "</span></td><td> " +
  5565. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5566. "</td></tr>";
  5567. var key_remote = "connectionindicator.",
  5568. key_local = "connectionindicator.";
  5569. if(this.transport.length > 1)
  5570. {
  5571. key_remote += "remoteports";
  5572. key_local += "localports";
  5573. }
  5574. else
  5575. {
  5576. key_remote += "remoteport";
  5577. key_local += "localport";
  5578. }
  5579. transport += "<tr>" +
  5580. "<td>" +
  5581. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5582. "'>" +
  5583. translate(key_remote) + "</span></td><td>";
  5584. localTransport += "<tr>" +
  5585. "<td>" +
  5586. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5587. "'>" +
  5588. translate(key_local) + "</span></td><td>";
  5589. transport +=
  5590. ConnectionIndicator.getStringFromArray(data.remotePort);
  5591. localTransport +=
  5592. ConnectionIndicator.getStringFromArray(data.localPort);
  5593. transport += "</td></tr>";
  5594. transport += localTransport + "</td></tr>";
  5595. transport +="<tr>" +
  5596. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5597. translate("connectionindicator.transport") + "</span></td>" +
  5598. "<td>" + this.transport[0].type + "</td></tr>";
  5599. }
  5600. result += "<table style='width:100%'>" +
  5601. "<tr>" +
  5602. "<td>" +
  5603. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5604. translate("connectionindicator.bandwidth") + "</span>" +
  5605. "</td><td>" +
  5606. "<span class='jitsipopover_green'>&darr;</span>" +
  5607. downloadBandwidth +
  5608. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5609. uploadBandwidth + "</td></tr>";
  5610. result += transport + "</table>";
  5611. }
  5612. return result;
  5613. };
  5614. /**
  5615. * Shows or hide the additional information.
  5616. */
  5617. ConnectionIndicator.prototype.showMore = function () {
  5618. this.showMoreValue = !this.showMoreValue;
  5619. this.updatePopoverData();
  5620. };
  5621. function createIcon(classes)
  5622. {
  5623. var icon = document.createElement("span");
  5624. for(var i in classes)
  5625. {
  5626. icon.classList.add(classes[i]);
  5627. }
  5628. icon.appendChild(
  5629. document.createElement("i")).classList.add("icon-connection");
  5630. return icon;
  5631. }
  5632. /**
  5633. * Creates the indicator
  5634. */
  5635. ConnectionIndicator.prototype.create = function () {
  5636. this.connectionIndicatorContainer = document.createElement("div");
  5637. this.connectionIndicatorContainer.className = "connectionindicator";
  5638. this.connectionIndicatorContainer.style.display = "none";
  5639. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5640. this.popover = new JitsiPopover(
  5641. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5642. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5643. APP.translation.translateString("connectionindicator.na") + "</div>",
  5644. skin: "black"});
  5645. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5646. createIcon(["connection", "connection_empty"]));
  5647. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5648. createIcon(["connection", "connection_full"]));
  5649. };
  5650. /**
  5651. * Removes the indicator
  5652. */
  5653. ConnectionIndicator.prototype.remove = function()
  5654. {
  5655. this.connectionIndicatorContainer.remove();
  5656. this.popover.forceHide();
  5657. };
  5658. /**
  5659. * Updates the data of the indicator
  5660. * @param percent the percent of connection quality
  5661. * @param object the statistics data.
  5662. */
  5663. ConnectionIndicator.prototype.updateConnectionQuality =
  5664. function (percent, object) {
  5665. if(percent === null)
  5666. {
  5667. this.connectionIndicatorContainer.style.display = "none";
  5668. this.popover.forceHide();
  5669. return;
  5670. }
  5671. else
  5672. {
  5673. if(this.connectionIndicatorContainer.style.display == "none") {
  5674. this.connectionIndicatorContainer.style.display = "block";
  5675. this.videoLayout.updateMutePosition(this.videoContainer.id);
  5676. }
  5677. }
  5678. this.bandwidth = object.bandwidth;
  5679. this.bitrate = object.bitrate;
  5680. this.packetLoss = object.packetLoss;
  5681. this.transport = object.transport;
  5682. if(object.resolution)
  5683. {
  5684. this.resolution = object.resolution;
  5685. }
  5686. for(var quality in ConnectionIndicator.connectionQualityValues)
  5687. {
  5688. if(percent >= quality)
  5689. {
  5690. this.fullIcon.style.width =
  5691. ConnectionIndicator.connectionQualityValues[quality];
  5692. }
  5693. }
  5694. this.updatePopoverData();
  5695. };
  5696. /**
  5697. * Updates the resolution
  5698. * @param resolution the new resolution
  5699. */
  5700. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  5701. this.resolution = resolution;
  5702. this.updatePopoverData();
  5703. };
  5704. /**
  5705. * Updates the content of the popover
  5706. */
  5707. ConnectionIndicator.prototype.updatePopoverData = function () {
  5708. this.popover.updateContent(
  5709. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  5710. APP.translation.translateElement($(".connection_info"));
  5711. };
  5712. /**
  5713. * Hides the popover
  5714. */
  5715. ConnectionIndicator.prototype.hide = function () {
  5716. this.popover.forceHide();
  5717. };
  5718. /**
  5719. * Hides the indicator
  5720. */
  5721. ConnectionIndicator.prototype.hideIndicator = function () {
  5722. this.connectionIndicatorContainer.style.display = "none";
  5723. if(this.popover)
  5724. this.popover.forceHide();
  5725. };
  5726. module.exports = ConnectionIndicator;
  5727. },{"../util/JitsiPopover":27}],32:[function(require,module,exports){
  5728. var AudioLevels = require("../audio_levels/AudioLevels");
  5729. var Avatar = require("../avatar/Avatar");
  5730. var Chat = require("../side_pannels/chat/Chat");
  5731. var ContactList = require("../side_pannels/contactlist/ContactList");
  5732. var UIUtil = require("../util/UIUtil");
  5733. var ConnectionIndicator = require("./ConnectionIndicator");
  5734. var NicknameHandler = require("../util/NicknameHandler");
  5735. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  5736. var UIEvents = require("../../../service/UI/UIEvents");
  5737. var currentDominantSpeaker = null;
  5738. var lastNCount = config.channelLastN;
  5739. var localLastNCount = config.channelLastN;
  5740. var localLastNSet = [];
  5741. var lastNEndpointsCache = [];
  5742. var lastNPickupJid = null;
  5743. var largeVideoState = {
  5744. updateInProgress: false,
  5745. newSrc: ''
  5746. };
  5747. var eventEmitter = null;
  5748. /**
  5749. * Currently focused video "src"(displayed in large video).
  5750. * @type {String}
  5751. */
  5752. var focusedVideoInfo = null;
  5753. /**
  5754. * Indicates if we have muted our audio before the conference has started.
  5755. * @type {boolean}
  5756. */
  5757. var preMuted = false;
  5758. var mutedAudios = {};
  5759. var flipXLocalVideo = true;
  5760. var currentVideoWidth = null;
  5761. var currentVideoHeight = null;
  5762. var localVideoSrc = null;
  5763. function videoactive( videoelem) {
  5764. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  5765. // ignore mixedmslabela0 and v0
  5766. videoelem.show();
  5767. VideoLayout.resizeThumbnails();
  5768. var videoParent = videoelem.parent();
  5769. var parentResourceJid = null;
  5770. if (videoParent)
  5771. parentResourceJid
  5772. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  5773. // Update the large video to the last added video only if there's no
  5774. // current dominant, focused speaker or prezi playing or update it to
  5775. // the current dominant speaker.
  5776. if ((!focusedVideoInfo &&
  5777. !VideoLayout.getDominantSpeakerResourceJid() &&
  5778. !require("../prezi/Prezi").isPresentationVisible()) ||
  5779. (parentResourceJid &&
  5780. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  5781. VideoLayout.updateLargeVideo(
  5782. APP.RTC.getVideoSrc(videoelem[0]),
  5783. 1,
  5784. parentResourceJid);
  5785. }
  5786. VideoLayout.showModeratorIndicator();
  5787. }
  5788. }
  5789. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  5790. // XXX(gp) so, every call to this function is *always* preceded by a call
  5791. // to the RTC.attachMediaStream() function but that call is *not* followed
  5792. // by an update to the videoSrcToSsrc map!
  5793. //
  5794. // The above way of doing things results in video SRCs that don't correspond
  5795. // to any SSRC for a short period of time (to be more precise, for as long
  5796. // the waitForRemoteVideo takes to complete). This causes problems (see
  5797. // bellow).
  5798. //
  5799. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  5800. // a second time in here and only then update the videoSrcToSsrc map? Why
  5801. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  5802. // is called the first time? I actually do that in the lastN changed event
  5803. // handler because the "orphan" video SRC is causing troubles there. The
  5804. // purpose of this method would then be to fire the "videoactive.jingle".
  5805. //
  5806. // Food for though I guess :-)
  5807. if (selector.removed || !selector.parent().is(":visible")) {
  5808. console.warn("Media removed before had started", selector);
  5809. return;
  5810. }
  5811. if (stream.id === 'mixedmslabel') return;
  5812. if (selector[0].currentTime > 0) {
  5813. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  5814. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  5815. videoactive(selector);
  5816. } else {
  5817. setTimeout(function () {
  5818. waitForRemoteVideo(selector, ssrc, stream, jid);
  5819. }, 250);
  5820. }
  5821. }
  5822. /**
  5823. * Returns an array of the video horizontal and vertical indents,
  5824. * so that if fits its parent.
  5825. *
  5826. * @return an array with 2 elements, the horizontal indent and the vertical
  5827. * indent
  5828. */
  5829. function getCameraVideoPosition(videoWidth,
  5830. videoHeight,
  5831. videoSpaceWidth,
  5832. videoSpaceHeight) {
  5833. // Parent height isn't completely calculated when we position the video in
  5834. // full screen mode and this is why we use the screen height in this case.
  5835. // Need to think it further at some point and implement it properly.
  5836. var isFullScreen = document.fullScreen ||
  5837. document.mozFullScreen ||
  5838. document.webkitIsFullScreen;
  5839. if (isFullScreen)
  5840. videoSpaceHeight = window.innerHeight;
  5841. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5842. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  5843. return [horizontalIndent, verticalIndent];
  5844. }
  5845. /**
  5846. * Returns an array of the video horizontal and vertical indents.
  5847. * Centers horizontally and top aligns vertically.
  5848. *
  5849. * @return an array with 2 elements, the horizontal indent and the vertical
  5850. * indent
  5851. */
  5852. function getDesktopVideoPosition(videoWidth,
  5853. videoHeight,
  5854. videoSpaceWidth,
  5855. videoSpaceHeight) {
  5856. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5857. var verticalIndent = 0;// Top aligned
  5858. return [horizontalIndent, verticalIndent];
  5859. }
  5860. /**
  5861. * Returns an array of the video dimensions, so that it covers the screen.
  5862. * It leaves no empty areas, but some parts of the video might not be visible.
  5863. *
  5864. * @return an array with 2 elements, the video width and the video height
  5865. */
  5866. function getCameraVideoSize(videoWidth,
  5867. videoHeight,
  5868. videoSpaceWidth,
  5869. videoSpaceHeight) {
  5870. if (!videoWidth)
  5871. videoWidth = currentVideoWidth;
  5872. if (!videoHeight)
  5873. videoHeight = currentVideoHeight;
  5874. var aspectRatio = videoWidth / videoHeight;
  5875. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5876. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5877. if (availableWidth / aspectRatio < videoSpaceHeight) {
  5878. availableHeight = videoSpaceHeight;
  5879. availableWidth = availableHeight * aspectRatio;
  5880. }
  5881. if (availableHeight * aspectRatio < videoSpaceWidth) {
  5882. availableWidth = videoSpaceWidth;
  5883. availableHeight = availableWidth / aspectRatio;
  5884. }
  5885. return [availableWidth, availableHeight];
  5886. }
  5887. /**
  5888. * Sets the display name for the given video span id.
  5889. */
  5890. function setDisplayName(videoSpanId, displayName) {
  5891. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  5892. var defaultLocalDisplayName = interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME;
  5893. // If we already have a display name for this video.
  5894. if (nameSpan.length > 0) {
  5895. var nameSpanElement = nameSpan.get(0);
  5896. if (nameSpanElement.id === 'localDisplayName' &&
  5897. $('#localDisplayName').text() !== displayName) {
  5898. if (displayName && displayName.length > 0)
  5899. $('#localDisplayName').html(displayName + ' (me)');
  5900. else
  5901. $('#localDisplayName').text(defaultLocalDisplayName);
  5902. } else {
  5903. if (displayName && displayName.length > 0)
  5904. $('#' + videoSpanId + '_name').html(displayName);
  5905. else
  5906. $('#' + videoSpanId + '_name').text(interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  5907. }
  5908. } else {
  5909. var editButton = null;
  5910. nameSpan = document.createElement('span');
  5911. nameSpan.className = 'displayname';
  5912. $('#' + videoSpanId)[0].appendChild(nameSpan);
  5913. if (videoSpanId === 'localVideoContainer') {
  5914. editButton = createEditDisplayNameButton();
  5915. nameSpan.innerText = defaultLocalDisplayName;
  5916. }
  5917. else {
  5918. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  5919. }
  5920. if (displayName && displayName.length > 0) {
  5921. nameSpan.innerText = displayName;
  5922. }
  5923. if (!editButton) {
  5924. nameSpan.id = videoSpanId + '_name';
  5925. } else {
  5926. nameSpan.id = 'localDisplayName';
  5927. $('#' + videoSpanId)[0].appendChild(editButton);
  5928. //translates popover of edit button
  5929. APP.translation.translateElement($("a.displayname"));
  5930. var editableText = document.createElement('input');
  5931. editableText.className = 'displayname';
  5932. editableText.type = 'text';
  5933. editableText.id = 'editDisplayName';
  5934. if (displayName && displayName.length) {
  5935. editableText.value
  5936. = displayName.substring(0, displayName.indexOf(' (me)'));
  5937. }
  5938. editableText.setAttribute('style', 'display:none;');
  5939. editableText.setAttribute('placeholder', 'ex. Jane Pink');
  5940. $('#' + videoSpanId)[0].appendChild(editableText);
  5941. $('#localVideoContainer .displayname')
  5942. .bind("click", function (e) {
  5943. e.preventDefault();
  5944. e.stopPropagation();
  5945. $('#localDisplayName').hide();
  5946. $('#editDisplayName').show();
  5947. $('#editDisplayName').focus();
  5948. $('#editDisplayName').select();
  5949. $('#editDisplayName').one("focusout", function (e) {
  5950. VideoLayout.inputDisplayNameHandler(this.value);
  5951. });
  5952. $('#editDisplayName').on('keydown', function (e) {
  5953. if (e.keyCode === 13) {
  5954. e.preventDefault();
  5955. VideoLayout.inputDisplayNameHandler(this.value);
  5956. }
  5957. });
  5958. });
  5959. }
  5960. }
  5961. }
  5962. /**
  5963. * Gets the selector of video thumbnail container for the user identified by
  5964. * given <tt>userJid</tt>
  5965. * @param resourceJid user's Jid for whom we want to get the video container.
  5966. */
  5967. function getParticipantContainer(resourceJid)
  5968. {
  5969. if (!resourceJid)
  5970. return null;
  5971. if (resourceJid === APP.xmpp.myResource())
  5972. return $("#localVideoContainer");
  5973. else
  5974. return $("#participant_" + resourceJid);
  5975. }
  5976. /**
  5977. * Sets the size and position of the given video element.
  5978. *
  5979. * @param video the video element to position
  5980. * @param width the desired video width
  5981. * @param height the desired video height
  5982. * @param horizontalIndent the left and right indent
  5983. * @param verticalIndent the top and bottom indent
  5984. */
  5985. function positionVideo(video,
  5986. width,
  5987. height,
  5988. horizontalIndent,
  5989. verticalIndent) {
  5990. video.width(width);
  5991. video.height(height);
  5992. video.css({ top: verticalIndent + 'px',
  5993. bottom: verticalIndent + 'px',
  5994. left: horizontalIndent + 'px',
  5995. right: horizontalIndent + 'px'});
  5996. }
  5997. /**
  5998. * Adds the remote video menu element for the given <tt>jid</tt> in the
  5999. * given <tt>parentElement</tt>.
  6000. *
  6001. * @param jid the jid indicating the video for which we're adding a menu.
  6002. * @param parentElement the parent element where this menu will be added
  6003. */
  6004. function addRemoteVideoMenu(jid, parentElement) {
  6005. var spanElement = document.createElement('span');
  6006. spanElement.className = 'remotevideomenu';
  6007. parentElement.appendChild(spanElement);
  6008. var menuElement = document.createElement('i');
  6009. menuElement.className = 'fa fa-angle-down';
  6010. menuElement.title = 'Remote user controls';
  6011. spanElement.appendChild(menuElement);
  6012. // <ul class="popupmenu">
  6013. // <li><a href="#">Mute</a></li>
  6014. // <li><a href="#">Eject</a></li>
  6015. // </ul>
  6016. var popupmenuElement = document.createElement('ul');
  6017. popupmenuElement.className = 'popupmenu';
  6018. popupmenuElement.id
  6019. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  6020. spanElement.appendChild(popupmenuElement);
  6021. var muteMenuItem = document.createElement('li');
  6022. var muteLinkItem = document.createElement('a');
  6023. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  6024. if (!mutedAudios[jid]) {
  6025. muteLinkItem.innerHTML = mutedIndicator +
  6026. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6027. muteLinkItem.className = 'mutelink';
  6028. }
  6029. else {
  6030. muteLinkItem.innerHTML = mutedIndicator +
  6031. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6032. muteLinkItem.className = 'mutelink disabled';
  6033. }
  6034. muteLinkItem.onclick = function(){
  6035. if ($(this).attr('disabled') != undefined) {
  6036. event.preventDefault();
  6037. }
  6038. var isMute = mutedAudios[jid] == true;
  6039. APP.xmpp.setMute(jid, !isMute);
  6040. popupmenuElement.setAttribute('style', 'display:none;');
  6041. if (isMute) {
  6042. this.innerHTML = mutedIndicator +
  6043. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6044. this.className = 'mutelink disabled';
  6045. }
  6046. else {
  6047. this.innerHTML = mutedIndicator +
  6048. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6049. this.className = 'mutelink';
  6050. }
  6051. };
  6052. muteMenuItem.appendChild(muteLinkItem);
  6053. popupmenuElement.appendChild(muteMenuItem);
  6054. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  6055. var ejectMenuItem = document.createElement('li');
  6056. var ejectLinkItem = document.createElement('a');
  6057. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  6058. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  6059. ejectLinkItem.onclick = function(){
  6060. APP.xmpp.eject(jid);
  6061. popupmenuElement.setAttribute('style', 'display:none;');
  6062. };
  6063. ejectMenuItem.appendChild(ejectLinkItem);
  6064. popupmenuElement.appendChild(ejectMenuItem);
  6065. var paddingSpan = document.createElement('span');
  6066. paddingSpan.className = 'popupmenuPadding';
  6067. popupmenuElement.appendChild(paddingSpan);
  6068. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  6069. }
  6070. /**
  6071. * Removes remote video menu element from video element identified by
  6072. * given <tt>videoElementId</tt>.
  6073. *
  6074. * @param videoElementId the id of local or remote video element.
  6075. */
  6076. function removeRemoteVideoMenu(videoElementId) {
  6077. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  6078. if (menuSpan.length) {
  6079. menuSpan.remove();
  6080. }
  6081. }
  6082. /**
  6083. * Updates the data for the indicator
  6084. * @param id the id of the indicator
  6085. * @param percent the percent for connection quality
  6086. * @param object the data
  6087. */
  6088. function updateStatsIndicator(id, percent, object) {
  6089. if(VideoLayout.connectionIndicators[id])
  6090. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  6091. }
  6092. /**
  6093. * Returns an array of the video dimensions, so that it keeps it's aspect
  6094. * ratio and fits available area with it's larger dimension. This method
  6095. * ensures that whole video will be visible and can leave empty areas.
  6096. *
  6097. * @return an array with 2 elements, the video width and the video height
  6098. */
  6099. function getDesktopVideoSize(videoWidth,
  6100. videoHeight,
  6101. videoSpaceWidth,
  6102. videoSpaceHeight) {
  6103. if (!videoWidth)
  6104. videoWidth = currentVideoWidth;
  6105. if (!videoHeight)
  6106. videoHeight = currentVideoHeight;
  6107. var aspectRatio = videoWidth / videoHeight;
  6108. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6109. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6110. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  6111. if (availableWidth / aspectRatio >= videoSpaceHeight)
  6112. {
  6113. availableHeight = videoSpaceHeight;
  6114. availableWidth = availableHeight * aspectRatio;
  6115. }
  6116. if (availableHeight * aspectRatio >= videoSpaceWidth)
  6117. {
  6118. availableWidth = videoSpaceWidth;
  6119. availableHeight = availableWidth / aspectRatio;
  6120. }
  6121. return [availableWidth, availableHeight];
  6122. }
  6123. /**
  6124. * Creates the edit display name button.
  6125. *
  6126. * @returns the edit button
  6127. */
  6128. function createEditDisplayNameButton() {
  6129. var editButton = document.createElement('a');
  6130. editButton.className = 'displayname';
  6131. UIUtil.setTooltip(editButton,
  6132. "videothumbnail.editnickname",
  6133. "top");
  6134. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  6135. return editButton;
  6136. }
  6137. /**
  6138. * Creates the element indicating the moderator(owner) of the conference.
  6139. *
  6140. * @param parentElement the parent element where the owner indicator will
  6141. * be added
  6142. */
  6143. function createModeratorIndicatorElement(parentElement) {
  6144. var moderatorIndicator = document.createElement('i');
  6145. moderatorIndicator.className = 'fa fa-star';
  6146. parentElement.appendChild(moderatorIndicator);
  6147. UIUtil.setTooltip(parentElement,
  6148. "videothumbnail.moderator",
  6149. "top");
  6150. }
  6151. var VideoLayout = (function (my) {
  6152. my.connectionIndicators = {};
  6153. // By default we use camera
  6154. my.getVideoSize = getCameraVideoSize;
  6155. my.getVideoPosition = getCameraVideoPosition;
  6156. my.init = function (emitter) {
  6157. // Listen for large video size updates
  6158. document.getElementById('largeVideo')
  6159. .addEventListener('loadedmetadata', function (e) {
  6160. currentVideoWidth = this.videoWidth;
  6161. currentVideoHeight = this.videoHeight;
  6162. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6163. });
  6164. eventEmitter = emitter;
  6165. };
  6166. my.isInLastN = function(resource) {
  6167. return lastNCount < 0 // lastN is disabled, return true
  6168. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  6169. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  6170. };
  6171. my.changeLocalStream = function (stream) {
  6172. VideoLayout.changeLocalVideo(stream);
  6173. };
  6174. my.changeLocalAudio = function(stream) {
  6175. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  6176. document.getElementById('localAudio').autoplay = true;
  6177. document.getElementById('localAudio').volume = 0;
  6178. if (preMuted) {
  6179. if(!APP.UI.setAudioMuted(true))
  6180. {
  6181. preMuted = mute;
  6182. }
  6183. preMuted = false;
  6184. }
  6185. };
  6186. my.changeLocalVideo = function(stream) {
  6187. var flipX = true;
  6188. if(stream.videoType == "screen")
  6189. flipX = false;
  6190. var localVideo = document.createElement('video');
  6191. localVideo.id = 'localVideo_' +
  6192. APP.RTC.getStreamID(stream.getOriginalStream());
  6193. localVideo.autoplay = true;
  6194. localVideo.volume = 0; // is it required if audio is separated ?
  6195. localVideo.oncontextmenu = function () { return false; };
  6196. var localVideoContainer = document.getElementById('localVideoWrapper');
  6197. localVideoContainer.appendChild(localVideo);
  6198. // Set default display name.
  6199. setDisplayName('localVideoContainer');
  6200. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  6201. VideoLayout.connectionIndicators["localVideoContainer"]
  6202. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  6203. }
  6204. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  6205. var localVideoSelector = $('#' + localVideo.id);
  6206. function localVideoClick(event) {
  6207. event.stopPropagation();
  6208. VideoLayout.handleVideoThumbClicked(
  6209. APP.RTC.getVideoSrc(localVideo),
  6210. false,
  6211. APP.xmpp.myResource());
  6212. }
  6213. // Add click handler to both video and video wrapper elements in case
  6214. // there's no video.
  6215. localVideoSelector.click(localVideoClick);
  6216. $('#localVideoContainer').click(localVideoClick);
  6217. // Add hover handler
  6218. $('#localVideoContainer').hover(
  6219. function() {
  6220. VideoLayout.showDisplayName('localVideoContainer', true);
  6221. },
  6222. function() {
  6223. if (!VideoLayout.isLargeVideoVisible()
  6224. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6225. VideoLayout.showDisplayName('localVideoContainer', false);
  6226. }
  6227. );
  6228. // Add stream ended handler
  6229. stream.getOriginalStream().onended = function () {
  6230. localVideoContainer.removeChild(localVideo);
  6231. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  6232. };
  6233. // Flip video x axis if needed
  6234. flipXLocalVideo = flipX;
  6235. if (flipX) {
  6236. localVideoSelector.addClass("flipVideoX");
  6237. }
  6238. // Attach WebRTC stream
  6239. var videoStream = APP.simulcast.getLocalVideoStream();
  6240. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  6241. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  6242. var myResourceJid = APP.xmpp.myResource();
  6243. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  6244. myResourceJid);
  6245. };
  6246. /**
  6247. * Checks if removed video is currently displayed and tries to display
  6248. * another one instead.
  6249. * @param removedVideoSrc src stream identifier of the video.
  6250. */
  6251. my.updateRemovedVideo = function(removedVideoSrc) {
  6252. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  6253. // this is currently displayed as large
  6254. // pick the last visible video in the row
  6255. // if nobody else is left, this picks the local video
  6256. var pick
  6257. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  6258. .get(0);
  6259. if (!pick) {
  6260. console.info("Last visible video no longer exists");
  6261. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  6262. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  6263. // Try local video
  6264. console.info("Fallback to local video...");
  6265. pick = $('#remoteVideos>span>span>video').get(0);
  6266. }
  6267. }
  6268. // mute if localvideo
  6269. if (pick) {
  6270. var container = pick.parentNode;
  6271. var jid = null;
  6272. if(container)
  6273. {
  6274. if(container.id == "localVideoWrapper")
  6275. {
  6276. jid = APP.xmpp.myResource();
  6277. }
  6278. else
  6279. {
  6280. jid = VideoLayout.getPeerContainerResourceJid(container);
  6281. }
  6282. }
  6283. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(pick), pick.volume, jid);
  6284. } else {
  6285. console.warn("Failed to elect large video");
  6286. }
  6287. }
  6288. };
  6289. my.onRemoteStreamAdded = function (stream) {
  6290. var container;
  6291. var remotes = document.getElementById('remoteVideos');
  6292. if (stream.peerjid) {
  6293. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6294. container = document.getElementById(
  6295. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6296. } else {
  6297. var id = stream.getOriginalStream().id;
  6298. if (id !== 'mixedmslabel'
  6299. // FIXME: default stream is added always with new focus
  6300. // (to be investigated)
  6301. && id !== 'default') {
  6302. console.error('can not associate stream',
  6303. id,
  6304. 'with a participant');
  6305. // We don't want to add it here since it will cause troubles
  6306. return;
  6307. }
  6308. // FIXME: for the mixed ms we dont need a video -- currently
  6309. container = document.createElement('span');
  6310. container.id = 'mixedstream';
  6311. container.className = 'videocontainer';
  6312. remotes.appendChild(container);
  6313. UIUtil.playSoundNotification('userJoined');
  6314. }
  6315. if (container) {
  6316. VideoLayout.addRemoteStreamElement( container,
  6317. stream.sid,
  6318. stream.getOriginalStream(),
  6319. stream.peerjid,
  6320. stream.ssrc);
  6321. }
  6322. }
  6323. my.getLargeVideoState = function () {
  6324. return largeVideoState;
  6325. };
  6326. /**
  6327. * Updates the large video with the given new video source.
  6328. */
  6329. my.updateLargeVideo = function(newSrc, vol, resourceJid) {
  6330. console.log('hover in', newSrc);
  6331. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc) {
  6332. $('#activeSpeaker').css('visibility', 'hidden');
  6333. // Due to the simulcast the localVideoSrc may have changed when the
  6334. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6335. // isVideoSrcDesktop methods will not function correctly.
  6336. //
  6337. // Also, again due to the simulcast, the updateLargeVideo method can
  6338. // be called multiple times almost simultaneously. Therefore, we
  6339. // store the state here and update only once.
  6340. largeVideoState.newSrc = newSrc;
  6341. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6342. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(resourceJid);
  6343. if(largeVideoState.userResourceJid) {
  6344. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6345. } else {
  6346. largeVideoState.oldResourceJid = null;
  6347. }
  6348. largeVideoState.userResourceJid = resourceJid;
  6349. // Screen stream is already rotated
  6350. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6351. var userChanged = false;
  6352. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6353. userChanged = true;
  6354. // we want the notification to trigger even if userJid is undefined,
  6355. // or null.
  6356. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6357. largeVideoState.userResourceJid);
  6358. }
  6359. if (!largeVideoState.updateInProgress) {
  6360. largeVideoState.updateInProgress = true;
  6361. var doUpdate = function () {
  6362. Avatar.updateActiveSpeakerAvatarSrc(
  6363. APP.xmpp.findJidFromResource(
  6364. largeVideoState.userResourceJid));
  6365. if (!userChanged && largeVideoState.preload &&
  6366. largeVideoState.preload !== null &&
  6367. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  6368. {
  6369. console.info('Switching to preloaded video');
  6370. var attributes = $('#largeVideo').prop("attributes");
  6371. // loop through largeVideo attributes and apply them on
  6372. // preload.
  6373. $.each(attributes, function () {
  6374. if (this.name !== 'id' && this.name !== 'src') {
  6375. largeVideoState.preload.attr(this.name, this.value);
  6376. }
  6377. });
  6378. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  6379. $('#largeVideo').attr('id', 'previousLargeVideo');
  6380. largeVideoState.preload.attr('id', 'largeVideo');
  6381. $('#previousLargeVideo').remove();
  6382. largeVideoState.preload.on('loadedmetadata', function (e) {
  6383. currentVideoWidth = this.videoWidth;
  6384. currentVideoHeight = this.videoHeight;
  6385. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6386. });
  6387. largeVideoState.preload = null;
  6388. largeVideoState.preload_ssrc = 0;
  6389. } else {
  6390. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6391. }
  6392. var videoTransform = document.getElementById('largeVideo')
  6393. .style.webkitTransform;
  6394. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6395. document.getElementById('largeVideo').style.webkitTransform
  6396. = "scaleX(-1)";
  6397. }
  6398. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6399. document.getElementById('largeVideo').style.webkitTransform
  6400. = "none";
  6401. }
  6402. // Change the way we'll be measuring and positioning large video
  6403. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6404. ? getDesktopVideoSize
  6405. : getCameraVideoSize;
  6406. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6407. ? getDesktopVideoPosition
  6408. : getCameraVideoPosition;
  6409. // Only if the large video is currently visible.
  6410. // Disable previous dominant speaker video.
  6411. if (largeVideoState.oldResourceJid) {
  6412. VideoLayout.enableDominantSpeaker(
  6413. largeVideoState.oldResourceJid,
  6414. false);
  6415. }
  6416. // Enable new dominant speaker in the remote videos section.
  6417. if (largeVideoState.userResourceJid) {
  6418. VideoLayout.enableDominantSpeaker(
  6419. largeVideoState.userResourceJid,
  6420. true);
  6421. }
  6422. if (userChanged && largeVideoState.isVisible) {
  6423. // using "this" should be ok because we're called
  6424. // from within the fadeOut event.
  6425. $(this).fadeIn(300);
  6426. }
  6427. if(userChanged) {
  6428. Avatar.showUserAvatar(
  6429. APP.xmpp.findJidFromResource(
  6430. largeVideoState.oldResourceJid));
  6431. }
  6432. largeVideoState.updateInProgress = false;
  6433. };
  6434. if (userChanged) {
  6435. $('#largeVideo').fadeOut(300, doUpdate);
  6436. } else {
  6437. doUpdate();
  6438. }
  6439. }
  6440. } else {
  6441. Avatar.showUserAvatar(
  6442. APP.xmpp.findJidFromResource(
  6443. largeVideoState.userResourceJid));
  6444. }
  6445. };
  6446. my.handleVideoThumbClicked = function(videoSrc,
  6447. noPinnedEndpointChangedEvent,
  6448. resourceJid) {
  6449. // Restore style for previously focused video
  6450. var oldContainer = null;
  6451. if(focusedVideoInfo) {
  6452. var focusResourceJid = focusedVideoInfo.resourceJid;
  6453. oldContainer = getParticipantContainer(focusResourceJid);
  6454. }
  6455. if (oldContainer) {
  6456. oldContainer.removeClass("videoContainerFocused");
  6457. }
  6458. // Unlock current focused.
  6459. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6460. {
  6461. focusedVideoInfo = null;
  6462. var dominantSpeakerVideo = null;
  6463. // Enable the currently set dominant speaker.
  6464. if (currentDominantSpeaker) {
  6465. dominantSpeakerVideo
  6466. = $('#participant_' + currentDominantSpeaker + '>video')
  6467. .get(0);
  6468. if (dominantSpeakerVideo) {
  6469. VideoLayout.updateLargeVideo(
  6470. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6471. 1,
  6472. currentDominantSpeaker);
  6473. }
  6474. }
  6475. if (!noPinnedEndpointChangedEvent) {
  6476. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6477. }
  6478. return;
  6479. }
  6480. // Lock new video
  6481. focusedVideoInfo = {
  6482. src: videoSrc,
  6483. resourceJid: resourceJid
  6484. };
  6485. // Update focused/pinned interface.
  6486. if (resourceJid)
  6487. {
  6488. var container = getParticipantContainer(resourceJid);
  6489. container.addClass("videoContainerFocused");
  6490. if (!noPinnedEndpointChangedEvent) {
  6491. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6492. }
  6493. }
  6494. if ($('#largeVideo').attr('src') === videoSrc &&
  6495. VideoLayout.isLargeVideoOnTop()) {
  6496. return;
  6497. }
  6498. // Triggers a "video.selected" event. The "false" parameter indicates
  6499. // this isn't a prezi.
  6500. $(document).trigger("video.selected", [false]);
  6501. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6502. $('audio').each(function (idx, el) {
  6503. if (el.id.indexOf('mixedmslabel') !== -1) {
  6504. el.volume = 0;
  6505. el.volume = 1;
  6506. }
  6507. });
  6508. };
  6509. /**
  6510. * Positions the large video.
  6511. *
  6512. * @param videoWidth the stream video width
  6513. * @param videoHeight the stream video height
  6514. */
  6515. my.positionLarge = function (videoWidth, videoHeight) {
  6516. var videoSpaceWidth = $('#videospace').width();
  6517. var videoSpaceHeight = window.innerHeight;
  6518. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6519. videoHeight,
  6520. videoSpaceWidth,
  6521. videoSpaceHeight);
  6522. var largeVideoWidth = videoSize[0];
  6523. var largeVideoHeight = videoSize[1];
  6524. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6525. largeVideoHeight,
  6526. videoSpaceWidth,
  6527. videoSpaceHeight);
  6528. var horizontalIndent = videoPosition[0];
  6529. var verticalIndent = videoPosition[1];
  6530. positionVideo($('#largeVideo'),
  6531. largeVideoWidth,
  6532. largeVideoHeight,
  6533. horizontalIndent, verticalIndent);
  6534. };
  6535. /**
  6536. * Shows/hides the large video.
  6537. */
  6538. my.setLargeVideoVisible = function(isVisible) {
  6539. var resourceJid = largeVideoState.userResourceJid;
  6540. if (isVisible) {
  6541. $('#largeVideo').css({visibility: 'visible'});
  6542. $('.watermark').css({visibility: 'visible'});
  6543. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6544. }
  6545. else {
  6546. $('#largeVideo').css({visibility: 'hidden'});
  6547. $('#activeSpeaker').css('visibility', 'hidden');
  6548. $('.watermark').css({visibility: 'hidden'});
  6549. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6550. if(focusedVideoInfo) {
  6551. var focusResourceJid = focusedVideoInfo.resourceJid;
  6552. var oldContainer = getParticipantContainer(focusResourceJid);
  6553. if (oldContainer && oldContainer.length > 0) {
  6554. oldContainer.removeClass("videoContainerFocused");
  6555. }
  6556. focusedVideoInfo = null;
  6557. if(focusResourceJid) {
  6558. Avatar.showUserAvatar(
  6559. APP.xmpp.findJidFromResource(focusResourceJid));
  6560. }
  6561. }
  6562. }
  6563. };
  6564. /**
  6565. * Indicates if the large video is currently visible.
  6566. *
  6567. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6568. */
  6569. my.isLargeVideoVisible = function() {
  6570. return $('#largeVideo').is(':visible');
  6571. };
  6572. my.isLargeVideoOnTop = function () {
  6573. var Etherpad = require("../etherpad/Etherpad");
  6574. var Prezi = require("../prezi/Prezi");
  6575. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6576. };
  6577. /**
  6578. * Checks if container for participant identified by given peerJid exists
  6579. * in the document and creates it eventually.
  6580. *
  6581. * @param peerJid peer Jid to check.
  6582. * @param userId user email or id for setting the avatar
  6583. *
  6584. * @return Returns <tt>true</tt> if the peer container exists,
  6585. * <tt>false</tt> - otherwise
  6586. */
  6587. my.ensurePeerContainerExists = function(peerJid, userId) {
  6588. ContactList.ensureAddContact(peerJid, userId);
  6589. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6590. var videoSpanId = 'participant_' + resourceJid;
  6591. if (!$('#' + videoSpanId).length) {
  6592. var container =
  6593. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6594. Avatar.setUserAvatar(peerJid, userId);
  6595. // Set default display name.
  6596. setDisplayName(videoSpanId);
  6597. VideoLayout.connectionIndicators[videoSpanId] =
  6598. new ConnectionIndicator(container, peerJid, VideoLayout);
  6599. var nickfield = document.createElement('span');
  6600. nickfield.className = "nick";
  6601. nickfield.appendChild(document.createTextNode(resourceJid));
  6602. container.appendChild(nickfield);
  6603. // In case this is not currently in the last n we don't show it.
  6604. if (localLastNCount
  6605. && localLastNCount > 0
  6606. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  6607. showPeerContainer(resourceJid, 'hide');
  6608. }
  6609. else
  6610. VideoLayout.resizeThumbnails();
  6611. }
  6612. };
  6613. my.addRemoteVideoContainer = function(peerJid, spanId) {
  6614. var container = document.createElement('span');
  6615. container.id = spanId;
  6616. container.className = 'videocontainer';
  6617. var remotes = document.getElementById('remoteVideos');
  6618. remotes.appendChild(container);
  6619. // If the peerJid is null then this video span couldn't be directly
  6620. // associated with a participant (this could happen in the case of prezi).
  6621. if (APP.xmpp.isModerator() && peerJid !== null)
  6622. addRemoteVideoMenu(peerJid, container);
  6623. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  6624. return container;
  6625. };
  6626. /**
  6627. * Creates an audio or video stream element.
  6628. */
  6629. my.createStreamElement = function (sid, stream) {
  6630. var isVideo = stream.getVideoTracks().length > 0;
  6631. var element = isVideo
  6632. ? document.createElement('video')
  6633. : document.createElement('audio');
  6634. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  6635. + sid + '_' + APP.RTC.getStreamID(stream);
  6636. element.id = id;
  6637. element.autoplay = true;
  6638. element.oncontextmenu = function () { return false; };
  6639. return element;
  6640. };
  6641. my.addRemoteStreamElement
  6642. = function (container, sid, stream, peerJid, thessrc) {
  6643. var newElementId = null;
  6644. var isVideo = stream.getVideoTracks().length > 0;
  6645. if (container) {
  6646. var streamElement = VideoLayout.createStreamElement(sid, stream);
  6647. newElementId = streamElement.id;
  6648. container.appendChild(streamElement);
  6649. var sel = $('#' + newElementId);
  6650. sel.hide();
  6651. // If the container is currently visible we attach the stream.
  6652. if (!isVideo
  6653. || (container.offsetParent !== null && isVideo)) {
  6654. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6655. APP.RTC.attachMediaStream(sel, videoStream);
  6656. if (isVideo)
  6657. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  6658. }
  6659. stream.onended = function () {
  6660. console.log('stream ended', this);
  6661. VideoLayout.removeRemoteStreamElement(
  6662. stream, isVideo, container);
  6663. // NOTE(gp) it seems that under certain circumstances, the
  6664. // onended event is not fired and thus the contact list is not
  6665. // updated.
  6666. //
  6667. // The onended event of a stream should be fired when the SSRCs
  6668. // corresponding to that stream are removed from the SDP; but
  6669. // this doesn't seem to always be the case, resulting in ghost
  6670. // contacts.
  6671. //
  6672. // In an attempt to fix the ghost contacts problem, I'm moving
  6673. // the removeContact() method call in app.js, inside the
  6674. // 'muc.left' event handler.
  6675. //if (peerJid)
  6676. // ContactList.removeContact(peerJid);
  6677. };
  6678. // Add click handler.
  6679. container.onclick = function (event) {
  6680. /*
  6681. * FIXME It turns out that videoThumb may not exist (if there is
  6682. * no actual video).
  6683. */
  6684. var videoThumb = $('#' + container.id + '>video').get(0);
  6685. if (videoThumb) {
  6686. VideoLayout.handleVideoThumbClicked(
  6687. APP.RTC.getVideoSrc(videoThumb),
  6688. false,
  6689. Strophe.getResourceFromJid(peerJid));
  6690. }
  6691. event.stopPropagation();
  6692. event.preventDefault();
  6693. return false;
  6694. };
  6695. // Add hover handler
  6696. $(container).hover(
  6697. function() {
  6698. VideoLayout.showDisplayName(container.id, true);
  6699. },
  6700. function() {
  6701. var videoSrc = null;
  6702. if ($('#' + container.id + '>video')
  6703. && $('#' + container.id + '>video').length > 0) {
  6704. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  6705. }
  6706. // If the video has been "pinned" by the user we want to
  6707. // keep the display name on place.
  6708. if (!VideoLayout.isLargeVideoVisible()
  6709. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6710. VideoLayout.showDisplayName(container.id, false);
  6711. }
  6712. );
  6713. }
  6714. return newElementId;
  6715. };
  6716. /**
  6717. * Removes the remote stream element corresponding to the given stream and
  6718. * parent container.
  6719. *
  6720. * @param stream the stream
  6721. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  6722. * @param container
  6723. */
  6724. my.removeRemoteStreamElement = function (stream, isVideo, container) {
  6725. if (!container)
  6726. return;
  6727. var select = null;
  6728. var removedVideoSrc = null;
  6729. if (isVideo) {
  6730. select = $('#' + container.id + '>video');
  6731. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  6732. }
  6733. else
  6734. select = $('#' + container.id + '>audio');
  6735. // Mark video as removed to cancel waiting loop(if video is removed
  6736. // before has started)
  6737. select.removed = true;
  6738. select.remove();
  6739. var audioCount = $('#' + container.id + '>audio').length;
  6740. var videoCount = $('#' + container.id + '>video').length;
  6741. if (!audioCount && !videoCount) {
  6742. console.log("Remove whole user", container.id);
  6743. if(VideoLayout.connectionIndicators[container.id])
  6744. VideoLayout.connectionIndicators[container.id].remove();
  6745. // Remove whole container
  6746. container.remove();
  6747. UIUtil.playSoundNotification('userLeft');
  6748. VideoLayout.resizeThumbnails();
  6749. }
  6750. if (removedVideoSrc)
  6751. VideoLayout.updateRemovedVideo(removedVideoSrc);
  6752. };
  6753. /**
  6754. * Show/hide peer container for the given resourceJid.
  6755. */
  6756. function showPeerContainer(resourceJid, state) {
  6757. var peerContainer = $('#participant_' + resourceJid);
  6758. if (!peerContainer)
  6759. return;
  6760. var isHide = state === 'hide';
  6761. var resizeThumbnails = false;
  6762. if (!isHide) {
  6763. if (!peerContainer.is(':visible')) {
  6764. resizeThumbnails = true;
  6765. peerContainer.show();
  6766. }
  6767. var jid = APP.xmpp.findJidFromResource(resourceJid);
  6768. if (state == 'show')
  6769. {
  6770. // peerContainer.css('-webkit-filter', '');
  6771. Avatar.showUserAvatar(jid, false);
  6772. }
  6773. else // if (state == 'avatar')
  6774. {
  6775. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  6776. Avatar.showUserAvatar(jid, true);
  6777. }
  6778. }
  6779. else if (peerContainer.is(':visible') && isHide)
  6780. {
  6781. resizeThumbnails = true;
  6782. peerContainer.hide();
  6783. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  6784. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  6785. }
  6786. if (resizeThumbnails) {
  6787. VideoLayout.resizeThumbnails();
  6788. }
  6789. // We want to be able to pin a participant from the contact list, even
  6790. // if he's not in the lastN set!
  6791. // ContactList.setClickable(resourceJid, !isHide);
  6792. };
  6793. my.inputDisplayNameHandler = function (name) {
  6794. NicknameHandler.setNickname(name);
  6795. if (!$('#localDisplayName').is(":visible")) {
  6796. if (NicknameHandler.getNickname())
  6797. $('#localDisplayName').text(NicknameHandler.getNickname() + " (me)");
  6798. else
  6799. $('#localDisplayName')
  6800. .text(interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6801. $('#localDisplayName').show();
  6802. }
  6803. $('#editDisplayName').hide();
  6804. };
  6805. /**
  6806. * Shows/hides the display name on the remote video.
  6807. * @param videoSpanId the identifier of the video span element
  6808. * @param isShow indicates if the display name should be shown or hidden
  6809. */
  6810. my.showDisplayName = function(videoSpanId, isShow) {
  6811. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  6812. if (isShow) {
  6813. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  6814. nameSpan.setAttribute("style", "display:inline-block;");
  6815. }
  6816. else {
  6817. if (nameSpan)
  6818. nameSpan.setAttribute("style", "display:none;");
  6819. }
  6820. };
  6821. /**
  6822. * Shows the presence status message for the given video.
  6823. */
  6824. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  6825. if (!$('#' + videoSpanId).length) {
  6826. // No container
  6827. return;
  6828. }
  6829. var statusSpan = $('#' + videoSpanId + '>span.status');
  6830. if (!statusSpan.length) {
  6831. //Add status span
  6832. statusSpan = document.createElement('span');
  6833. statusSpan.className = 'status';
  6834. statusSpan.id = videoSpanId + '_status';
  6835. $('#' + videoSpanId)[0].appendChild(statusSpan);
  6836. statusSpan = $('#' + videoSpanId + '>span.status');
  6837. }
  6838. // Display status
  6839. if (statusMsg && statusMsg.length) {
  6840. $('#' + videoSpanId + '_status').text(statusMsg);
  6841. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  6842. }
  6843. else {
  6844. // Hide
  6845. statusSpan.get(0).setAttribute("style", "display:none;");
  6846. }
  6847. };
  6848. /**
  6849. * Shows a visual indicator for the moderator of the conference.
  6850. */
  6851. my.showModeratorIndicator = function () {
  6852. var isModerator = APP.xmpp.isModerator();
  6853. if (isModerator) {
  6854. var indicatorSpan = $('#localVideoContainer .focusindicator');
  6855. if (indicatorSpan.children().length === 0)
  6856. {
  6857. createModeratorIndicatorElement(indicatorSpan[0]);
  6858. //translates text in focus indicator
  6859. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  6860. }
  6861. }
  6862. var members = APP.xmpp.getMembers();
  6863. Object.keys(members).forEach(function (jid) {
  6864. if (Strophe.getResourceFromJid(jid) === 'focus') {
  6865. // Skip server side focus
  6866. return;
  6867. }
  6868. var resourceJid = Strophe.getResourceFromJid(jid);
  6869. var videoSpanId = 'participant_' + resourceJid;
  6870. var videoContainer = document.getElementById(videoSpanId);
  6871. if (!videoContainer) {
  6872. console.error("No video container for " + jid);
  6873. return;
  6874. }
  6875. var member = members[jid];
  6876. if (member.role === 'moderator') {
  6877. // Remove menu if peer is moderator
  6878. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  6879. if (menuSpan.length) {
  6880. removeRemoteVideoMenu(videoSpanId);
  6881. }
  6882. // Show moderator indicator
  6883. var indicatorSpan
  6884. = $('#' + videoSpanId + ' .focusindicator');
  6885. if (!indicatorSpan || indicatorSpan.length === 0) {
  6886. indicatorSpan = document.createElement('span');
  6887. indicatorSpan.className = 'focusindicator';
  6888. videoContainer.appendChild(indicatorSpan);
  6889. createModeratorIndicatorElement(indicatorSpan);
  6890. //translates text in focus indicators
  6891. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  6892. }
  6893. } else if (isModerator) {
  6894. // We are moderator, but user is not - add menu
  6895. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  6896. addRemoteVideoMenu(
  6897. jid,
  6898. document.getElementById('participant_' + resourceJid));
  6899. }
  6900. }
  6901. });
  6902. };
  6903. /**
  6904. * Shows video muted indicator over small videos.
  6905. */
  6906. my.showVideoIndicator = function(videoSpanId, isMuted) {
  6907. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6908. if (isMuted === 'false') {
  6909. if (videoMutedSpan.length > 0) {
  6910. videoMutedSpan.remove();
  6911. }
  6912. }
  6913. else {
  6914. if(videoMutedSpan.length == 0) {
  6915. videoMutedSpan = document.createElement('span');
  6916. videoMutedSpan.className = 'videoMuted';
  6917. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  6918. var mutedIndicator = document.createElement('i');
  6919. mutedIndicator.className = 'icon-camera-disabled';
  6920. UIUtil.setTooltip(mutedIndicator,
  6921. "videothumbnail.videomute",
  6922. "top");
  6923. videoMutedSpan.appendChild(mutedIndicator);
  6924. //translate texts for muted indicator
  6925. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  6926. }
  6927. VideoLayout.updateMutePosition(videoSpanId);
  6928. }
  6929. };
  6930. my.updateMutePosition = function (videoSpanId) {
  6931. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6932. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  6933. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6934. if(connectionIndicator.length > 0
  6935. && connectionIndicator[0].style.display != "none") {
  6936. audioMutedSpan.css({right: "23px"});
  6937. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  6938. }
  6939. else
  6940. {
  6941. audioMutedSpan.css({right: "0px"});
  6942. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  6943. }
  6944. }
  6945. /**
  6946. * Shows audio muted indicator over small videos.
  6947. * @param {string} isMuted
  6948. */
  6949. my.showAudioIndicator = function(videoSpanId, isMuted) {
  6950. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6951. if (isMuted === 'false') {
  6952. if (audioMutedSpan.length > 0) {
  6953. audioMutedSpan.popover('hide');
  6954. audioMutedSpan.remove();
  6955. }
  6956. }
  6957. else {
  6958. if(audioMutedSpan.length == 0 ) {
  6959. audioMutedSpan = document.createElement('span');
  6960. audioMutedSpan.className = 'audioMuted';
  6961. UIUtil.setTooltip(audioMutedSpan,
  6962. "videothumbnail.mute",
  6963. "top");
  6964. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  6965. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  6966. var mutedIndicator = document.createElement('i');
  6967. mutedIndicator.className = 'icon-mic-disabled';
  6968. audioMutedSpan.appendChild(mutedIndicator);
  6969. }
  6970. VideoLayout.updateMutePosition(videoSpanId);
  6971. }
  6972. };
  6973. /*
  6974. * Shows or hides the audio muted indicator over the local thumbnail video.
  6975. * @param {boolean} isMuted
  6976. */
  6977. my.showLocalAudioIndicator = function(isMuted) {
  6978. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  6979. };
  6980. /**
  6981. * Resizes the large video container.
  6982. */
  6983. my.resizeLargeVideoContainer = function () {
  6984. Chat.resizeChat();
  6985. var availableHeight = window.innerHeight;
  6986. var availableWidth = UIUtil.getAvailableVideoWidth();
  6987. if (availableWidth < 0 || availableHeight < 0) return;
  6988. $('#videospace').width(availableWidth);
  6989. $('#videospace').height(availableHeight);
  6990. $('#largeVideoContainer').width(availableWidth);
  6991. $('#largeVideoContainer').height(availableHeight);
  6992. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  6993. var top = availableHeight / 2 - avatarSize / 4 * 3;
  6994. $('#activeSpeaker').css('top', top);
  6995. VideoLayout.resizeThumbnails();
  6996. };
  6997. /**
  6998. * Resizes thumbnails.
  6999. */
  7000. my.resizeThumbnails = function() {
  7001. var videoSpaceWidth = $('#remoteVideos').width();
  7002. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  7003. var width = thumbnailSize[0];
  7004. var height = thumbnailSize[1];
  7005. // size videos so that while keeping AR and max height, we have a
  7006. // nice fit
  7007. $('#remoteVideos').height(height);
  7008. $('#remoteVideos>span').width(width);
  7009. $('#remoteVideos>span').height(height);
  7010. $('.userAvatar').css('left', (width - height) / 2);
  7011. $(document).trigger("remotevideo.resized", [width, height]);
  7012. };
  7013. /**
  7014. * Enables the dominant speaker UI.
  7015. *
  7016. * @param resourceJid the jid indicating the video element to
  7017. * activate/deactivate
  7018. * @param isEnable indicates if the dominant speaker should be enabled or
  7019. * disabled
  7020. */
  7021. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  7022. var videoSpanId = null;
  7023. var videoContainerId = null;
  7024. if (resourceJid
  7025. === APP.xmpp.myResource()) {
  7026. videoSpanId = 'localVideoWrapper';
  7027. videoContainerId = 'localVideoContainer';
  7028. }
  7029. else {
  7030. videoSpanId = 'participant_' + resourceJid;
  7031. videoContainerId = videoSpanId;
  7032. }
  7033. var displayName = resourceJid;
  7034. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  7035. if (nameSpan.length > 0)
  7036. displayName = nameSpan.html();
  7037. console.log("UI enable dominant speaker",
  7038. displayName,
  7039. resourceJid,
  7040. isEnable);
  7041. videoSpan = document.getElementById(videoContainerId);
  7042. if (!videoSpan) {
  7043. return;
  7044. }
  7045. var video = $('#' + videoSpanId + '>video');
  7046. if (video && video.length > 0) {
  7047. if (isEnable) {
  7048. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  7049. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  7050. if (!videoSpan.classList.contains("dominantspeaker"))
  7051. videoSpan.classList.add("dominantspeaker");
  7052. }
  7053. else {
  7054. VideoLayout.showDisplayName(videoContainerId, false);
  7055. if (videoSpan.classList.contains("dominantspeaker"))
  7056. videoSpan.classList.remove("dominantspeaker");
  7057. }
  7058. Avatar.showUserAvatar(
  7059. APP.xmpp.findJidFromResource(resourceJid));
  7060. }
  7061. };
  7062. /**
  7063. * Calculates the thumbnail size.
  7064. *
  7065. * @param videoSpaceWidth the width of the video space
  7066. */
  7067. my.calculateThumbnailSize = function (videoSpaceWidth) {
  7068. // Calculate the available height, which is the inner window height minus
  7069. // 39px for the header minus 2px for the delimiter lines on the top and
  7070. // bottom of the large video, minus the 36px space inside the remoteVideos
  7071. // container used for highlighting shadow.
  7072. var availableHeight = 100;
  7073. var numvids = $('#remoteVideos>span:visible').length;
  7074. if (localLastNCount && localLastNCount > 0) {
  7075. numvids = Math.min(localLastNCount + 1, numvids);
  7076. }
  7077. // Remove the 3px borders arround videos and border around the remote
  7078. // videos area and the 4 pixels between the local video and the others
  7079. //TODO: Find out where the 4 pixels come from and remove them
  7080. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  7081. var availableWidth = availableWinWidth / numvids;
  7082. var aspectRatio = 16.0 / 9.0;
  7083. var maxHeight = Math.min(160, availableHeight);
  7084. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  7085. if (availableHeight < availableWidth / aspectRatio) {
  7086. availableWidth = Math.floor(availableHeight * aspectRatio);
  7087. }
  7088. return [availableWidth, availableHeight];
  7089. };
  7090. /**
  7091. * Updates the remote video menu.
  7092. *
  7093. * @param jid the jid indicating the video for which we're adding a menu.
  7094. * @param isMuted indicates the current mute state
  7095. */
  7096. my.updateRemoteVideoMenu = function(jid, isMuted) {
  7097. var muteMenuItem
  7098. = $('#remote_popupmenu_'
  7099. + Strophe.getResourceFromJid(jid)
  7100. + '>li>a.mutelink');
  7101. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  7102. if (muteMenuItem.length) {
  7103. var muteLink = muteMenuItem.get(0);
  7104. if (isMuted === 'true') {
  7105. muteLink.innerHTML = mutedIndicator + ' Muted';
  7106. muteLink.className = 'mutelink disabled';
  7107. }
  7108. else {
  7109. muteLink.innerHTML = mutedIndicator + ' Mute';
  7110. muteLink.className = 'mutelink';
  7111. }
  7112. }
  7113. };
  7114. /**
  7115. * Returns the current dominant speaker resource jid.
  7116. */
  7117. my.getDominantSpeakerResourceJid = function () {
  7118. return currentDominantSpeaker;
  7119. };
  7120. /**
  7121. * Returns the corresponding resource jid to the given peer container
  7122. * DOM element.
  7123. *
  7124. * @return the corresponding resource jid to the given peer container
  7125. * DOM element
  7126. */
  7127. my.getPeerContainerResourceJid = function (containerElement) {
  7128. var i = containerElement.id.indexOf('participant_');
  7129. if (i >= 0)
  7130. return containerElement.id.substring(i + 12);
  7131. };
  7132. /**
  7133. * On contact list item clicked.
  7134. */
  7135. $(ContactList).bind('contactclicked', function(event, jid) {
  7136. if (!jid) {
  7137. return;
  7138. }
  7139. var resource = Strophe.getResourceFromJid(jid);
  7140. var videoContainer = $("#participant_" + resource);
  7141. if (videoContainer.length > 0) {
  7142. var videoThumb = $('video', videoContainer).get(0);
  7143. // It is not always the case that a videoThumb exists (if there is
  7144. // no actual video).
  7145. if (videoThumb) {
  7146. if (videoThumb.src && videoThumb.src != '') {
  7147. // We have a video src, great! Let's update the large video
  7148. // now.
  7149. VideoLayout.handleVideoThumbClicked(
  7150. videoThumb.src,
  7151. false,
  7152. Strophe.getResourceFromJid(jid));
  7153. } else {
  7154. // If we don't have a video src for jid, there's absolutely
  7155. // no point in calling handleVideoThumbClicked; Quite
  7156. // simply, it won't work because it needs an src to attach
  7157. // to the large video.
  7158. //
  7159. // Instead, we trigger the pinned endpoint changed event to
  7160. // let the bridge adjust its lastN set for myjid and store
  7161. // the pinned user in the lastNPickupJid variable to be
  7162. // picked up later by the lastN changed event handler.
  7163. lastNPickupJid = jid;
  7164. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  7165. Strophe.getResourceFromJid(jid));
  7166. }
  7167. } else if (jid == APP.xmpp.myJid()) {
  7168. $("#localVideoContainer").click();
  7169. }
  7170. }
  7171. });
  7172. /**
  7173. * On audio muted event.
  7174. */
  7175. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  7176. /*
  7177. // FIXME: but focus can not mute in this case ? - check
  7178. if (jid === xmpp.myJid()) {
  7179. // The local mute indicator is controlled locally
  7180. return;
  7181. }*/
  7182. var videoSpanId = null;
  7183. if (jid === APP.xmpp.myJid()) {
  7184. videoSpanId = 'localVideoContainer';
  7185. } else {
  7186. VideoLayout.ensurePeerContainerExists(jid);
  7187. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7188. }
  7189. mutedAudios[jid] = isMuted;
  7190. if (APP.xmpp.isModerator()) {
  7191. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  7192. }
  7193. if (videoSpanId)
  7194. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  7195. });
  7196. /**
  7197. * On video muted event.
  7198. */
  7199. $(document).bind('videomuted.muc', function (event, jid, value) {
  7200. var isMuted = (value === "true");
  7201. if(!APP.RTC.muteRemoteVideoStream(jid, isMuted))
  7202. return;
  7203. Avatar.showUserAvatar(jid, isMuted);
  7204. var videoSpanId = null;
  7205. if (jid === APP.xmpp.myJid()) {
  7206. videoSpanId = 'localVideoContainer';
  7207. } else {
  7208. VideoLayout.ensurePeerContainerExists(jid);
  7209. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7210. }
  7211. if (videoSpanId)
  7212. VideoLayout.showVideoIndicator(videoSpanId, value);
  7213. });
  7214. /**
  7215. * Display name changed.
  7216. */
  7217. my.onDisplayNameChanged =
  7218. function (jid, displayName, status) {
  7219. if (jid === 'localVideoContainer'
  7220. || jid === APP.xmpp.myJid()) {
  7221. setDisplayName('localVideoContainer',
  7222. displayName);
  7223. } else {
  7224. VideoLayout.ensurePeerContainerExists(jid);
  7225. setDisplayName(
  7226. 'participant_' + Strophe.getResourceFromJid(jid),
  7227. displayName,
  7228. status);
  7229. }
  7230. };
  7231. /**
  7232. * On dominant speaker changed event.
  7233. */
  7234. my.onDominantSpeakerChanged = function (resourceJid) {
  7235. // We ignore local user events.
  7236. if (resourceJid
  7237. === APP.xmpp.myResource())
  7238. return;
  7239. // Update the current dominant speaker.
  7240. if (resourceJid !== currentDominantSpeaker) {
  7241. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  7242. newSpeakerVideoSpanId = "participant_" + resourceJid;
  7243. if($("#" + oldSpeakerVideoSpanId + ">span.displayname").text() ===
  7244. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME) {
  7245. setDisplayName(oldSpeakerVideoSpanId, null);
  7246. }
  7247. if($("#" + newSpeakerVideoSpanId + ">span.displayname").text() ===
  7248. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME) {
  7249. setDisplayName(newSpeakerVideoSpanId,
  7250. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  7251. }
  7252. currentDominantSpeaker = resourceJid;
  7253. } else {
  7254. return;
  7255. }
  7256. // Obtain container for new dominant speaker.
  7257. var container = document.getElementById(
  7258. 'participant_' + resourceJid);
  7259. // Local video will not have container found, but that's ok
  7260. // since we don't want to switch to local video.
  7261. if (container && !focusedVideoInfo)
  7262. {
  7263. var video = container.getElementsByTagName("video");
  7264. // Update the large video if the video source is already available,
  7265. // otherwise wait for the "videoactive.jingle" event.
  7266. if (video.length && video[0].currentTime > 0)
  7267. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  7268. }
  7269. };
  7270. /**
  7271. * On last N change event.
  7272. *
  7273. * @param lastNEndpoints the list of last N endpoints
  7274. * @param endpointsEnteringLastN the list currently entering last N
  7275. * endpoints
  7276. */
  7277. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7278. endpointsEnteringLastN,
  7279. stream) {
  7280. if (lastNCount !== lastNEndpoints.length)
  7281. lastNCount = lastNEndpoints.length;
  7282. lastNEndpointsCache = lastNEndpoints;
  7283. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7284. //
  7285. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7286. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7287. // so E sees them. C is only in E's local LastN set.
  7288. //
  7289. // If F starts talking and LastN = 3, then E should see thumbnails for
  7290. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7291. // enters E's local LastN ejecting C.
  7292. // Increase the local LastN set size, if necessary.
  7293. if (lastNCount > localLastNCount) {
  7294. localLastNCount = lastNCount;
  7295. }
  7296. // Update the local LastN set preserving the order in which the
  7297. // endpoints appeared in the LastN/local LastN set.
  7298. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7299. for (var i = 0; i < localLastNSet.length; i++) {
  7300. if (nextLocalLastNSet.length >= localLastNCount) {
  7301. break;
  7302. }
  7303. var resourceJid = localLastNSet[i];
  7304. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7305. nextLocalLastNSet.push(resourceJid);
  7306. }
  7307. }
  7308. localLastNSet = nextLocalLastNSet;
  7309. var updateLargeVideo = false;
  7310. // Handle LastN/local LastN changes.
  7311. $('#remoteVideos>span').each(function( index, element ) {
  7312. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7313. var isReceived = true;
  7314. if (resourceJid
  7315. && lastNEndpoints.indexOf(resourceJid) < 0
  7316. && localLastNSet.indexOf(resourceJid) < 0) {
  7317. console.log("Remove from last N", resourceJid);
  7318. showPeerContainer(resourceJid, 'hide');
  7319. isReceived = false;
  7320. } else if (resourceJid
  7321. && $('#participant_' + resourceJid).is(':visible')
  7322. && lastNEndpoints.indexOf(resourceJid) < 0
  7323. && localLastNSet.indexOf(resourceJid) >= 0) {
  7324. showPeerContainer(resourceJid, 'avatar');
  7325. isReceived = false;
  7326. }
  7327. if (!isReceived) {
  7328. // resourceJid has dropped out of the server side lastN set, so
  7329. // it is no longer being received. If resourceJid was being
  7330. // displayed in the large video we have to switch to another
  7331. // user.
  7332. var largeVideoResource = largeVideoState.userResourceJid;
  7333. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7334. updateLargeVideo = true;
  7335. }
  7336. }
  7337. });
  7338. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7339. endpointsEnteringLastN = lastNEndpoints;
  7340. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7341. endpointsEnteringLastN.forEach(function (resourceJid) {
  7342. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7343. showPeerContainer(resourceJid, 'show');
  7344. if (!isVisible) {
  7345. console.log("Add to last N", resourceJid);
  7346. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7347. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7348. var sel = $('#participant_' + resourceJid + '>video');
  7349. var videoStream = APP.simulcast.getReceivingVideoStream(
  7350. mediaStream.stream);
  7351. APP.RTC.attachMediaStream(sel, videoStream);
  7352. if (lastNPickupJid == mediaStream.peerjid) {
  7353. // Clean up the lastN pickup jid.
  7354. lastNPickupJid = null;
  7355. // Don't fire the events again, they've already
  7356. // been fired in the contact list click handler.
  7357. VideoLayout.handleVideoThumbClicked(
  7358. $(sel).attr('src'),
  7359. false,
  7360. Strophe.getResourceFromJid(mediaStream.peerjid));
  7361. updateLargeVideo = false;
  7362. }
  7363. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7364. }
  7365. })
  7366. }
  7367. // The endpoint that was being shown in the large video has dropped out
  7368. // of the lastN set and there was no lastN pickup jid. We need to update
  7369. // the large video now.
  7370. if (updateLargeVideo) {
  7371. var resource, container, src;
  7372. var myResource
  7373. = APP.xmpp.myResource();
  7374. // Find out which endpoint to show in the large video.
  7375. for (var i = 0; i < lastNEndpoints.length; i++) {
  7376. resource = lastNEndpoints[i];
  7377. if (!resource || resource === myResource)
  7378. continue;
  7379. container = $("#participant_" + resource);
  7380. if (container.length == 0)
  7381. continue;
  7382. src = $('video', container).attr('src');
  7383. if (!src)
  7384. continue;
  7385. // videoSrcToSsrc needs to be update for this call to succeed.
  7386. VideoLayout.updateLargeVideo(src);
  7387. break;
  7388. }
  7389. }
  7390. };
  7391. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  7392. endpointSimulcastLayers.forEach(function (esl) {
  7393. var resource = esl.endpoint;
  7394. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7395. // then ignore the event (= do not preload anything).
  7396. //
  7397. // The bridge could probably stop sending this message if it's for
  7398. // an endpoint that's not in lastN.
  7399. if (lastNCount != -1
  7400. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7401. return;
  7402. }
  7403. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7404. // Get session and stream from primary ssrc.
  7405. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7406. var sid = res.sid;
  7407. var electedStream = res.stream;
  7408. if (sid && electedStream) {
  7409. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7410. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7411. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  7412. if (preload) {
  7413. if (largeVideoState.preload)
  7414. {
  7415. $(largeVideoState.preload).remove();
  7416. }
  7417. console.info('Preloading remote video');
  7418. largeVideoState.preload = $('<video autoplay></video>');
  7419. // ssrcs are unique in an rtp session
  7420. largeVideoState.preload_ssrc = primarySSRC;
  7421. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  7422. }
  7423. } else {
  7424. console.error('Could not find a stream or a session.', sid, electedStream);
  7425. }
  7426. });
  7427. };
  7428. /**
  7429. * On simulcast layers changed event.
  7430. */
  7431. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  7432. endpointSimulcastLayers.forEach(function (esl) {
  7433. var resource = esl.endpoint;
  7434. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7435. // then ignore the event (= do not change large video/thumbnail
  7436. // SRCs).
  7437. //
  7438. // Note that even if we ignore the "changed" event in this event
  7439. // handler, the bridge must continue sending these events because
  7440. // the simulcast code in simulcast.js uses it to know what's going
  7441. // to be streamed by the bridge when/if the endpoint gets back into
  7442. // the lastN set.
  7443. if (lastNCount != -1
  7444. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7445. return;
  7446. }
  7447. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7448. // Get session and stream from primary ssrc.
  7449. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7450. var sid = res.sid;
  7451. var electedStream = res.stream;
  7452. if (sid && electedStream) {
  7453. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7454. console.info('Switching simulcast substream.');
  7455. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7456. var msidParts = msid.split(' ');
  7457. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  7458. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  7459. == largeVideoState.userResourceJid);
  7460. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  7461. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  7462. var electedStreamUrl;
  7463. if (largeVideoState.preload_ssrc == primarySSRC)
  7464. {
  7465. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  7466. }
  7467. else
  7468. {
  7469. if (largeVideoState.preload
  7470. && largeVideoState.preload != null) {
  7471. $(largeVideoState.preload).remove();
  7472. }
  7473. largeVideoState.preload_ssrc = 0;
  7474. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  7475. }
  7476. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  7477. if (updateLargeVideo) {
  7478. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  7479. Strophe.getResourceFromJid(jid));
  7480. }
  7481. if (updateFocusedVideoSrc) {
  7482. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  7483. }
  7484. var videoId;
  7485. if(resource == APP.xmpp.myResource())
  7486. {
  7487. videoId = "localVideoContainer";
  7488. }
  7489. else
  7490. {
  7491. videoId = "participant_" + resource;
  7492. }
  7493. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  7494. if(connectionIndicator)
  7495. connectionIndicator.updatePopoverData();
  7496. } else {
  7497. console.error('Could not find a stream or a sid.', sid, electedStream);
  7498. }
  7499. });
  7500. };
  7501. /**
  7502. * Updates local stats
  7503. * @param percent
  7504. * @param object
  7505. */
  7506. my.updateLocalConnectionStats = function (percent, object) {
  7507. var resolution = null;
  7508. if(object.resolution !== null)
  7509. {
  7510. resolution = object.resolution;
  7511. object.resolution = resolution[APP.xmpp.myJid()];
  7512. delete resolution[APP.xmpp.myJid()];
  7513. }
  7514. updateStatsIndicator("localVideoContainer", percent, object);
  7515. for(var jid in resolution)
  7516. {
  7517. if(resolution[jid] === null)
  7518. continue;
  7519. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7520. if(VideoLayout.connectionIndicators[id])
  7521. {
  7522. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7523. }
  7524. }
  7525. };
  7526. /**
  7527. * Updates remote stats.
  7528. * @param jid the jid associated with the stats
  7529. * @param percent the connection quality percent
  7530. * @param object the stats data
  7531. */
  7532. my.updateConnectionStats = function (jid, percent, object) {
  7533. var resourceJid = Strophe.getResourceFromJid(jid);
  7534. var videoSpanId = 'participant_' + resourceJid;
  7535. updateStatsIndicator(videoSpanId, percent, object);
  7536. };
  7537. /**
  7538. * Removes the connection
  7539. * @param jid
  7540. */
  7541. my.removeConnectionIndicator = function (jid) {
  7542. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7543. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7544. };
  7545. /**
  7546. * Hides the connection indicator
  7547. * @param jid
  7548. */
  7549. my.hideConnectionIndicator = function (jid) {
  7550. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7551. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7552. };
  7553. /**
  7554. * Hides all the indicators
  7555. */
  7556. my.onStatsStop = function () {
  7557. for(var indicator in VideoLayout.connectionIndicators)
  7558. {
  7559. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7560. }
  7561. };
  7562. my.participantLeft = function (jid) {
  7563. // Unlock large video
  7564. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7565. {
  7566. console.info("Focused video owner has left the conference");
  7567. focusedVideoInfo = null;
  7568. }
  7569. }
  7570. return my;
  7571. }(VideoLayout || {}));
  7572. module.exports = VideoLayout;
  7573. },{"../../../service/RTC/MediaStreamTypes":79,"../../../service/UI/UIEvents":84,"../audio_levels/AudioLevels":10,"../avatar/Avatar":13,"../etherpad/Etherpad":14,"../prezi/Prezi":15,"../side_pannels/chat/Chat":18,"../side_pannels/contactlist/ContactList":22,"../util/NicknameHandler":29,"../util/UIUtil":30,"./ConnectionIndicator":31}],33:[function(require,module,exports){
  7574. //var nouns = [
  7575. //];
  7576. var pluralNouns = [
  7577. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7578. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  7579. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  7580. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  7581. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  7582. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  7583. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  7584. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  7585. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  7586. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  7587. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  7588. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  7589. ];
  7590. //var places = [
  7591. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  7592. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  7593. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  7594. // "Bridge"
  7595. //];
  7596. var verbs = [
  7597. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  7598. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  7599. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  7600. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  7601. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  7602. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  7603. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  7604. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  7605. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  7606. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  7607. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  7608. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  7609. ];
  7610. var adverbs = [
  7611. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  7612. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  7613. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  7614. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  7615. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  7616. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  7617. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  7618. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  7619. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  7620. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  7621. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  7622. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  7623. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  7624. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  7625. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  7626. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  7627. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  7628. ];
  7629. var adjectives = [
  7630. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  7631. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  7632. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  7633. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  7634. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  7635. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  7636. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  7637. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  7638. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  7639. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  7640. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  7641. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  7642. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  7643. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  7644. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  7645. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  7646. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  7647. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  7648. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  7649. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  7650. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  7651. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  7652. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  7653. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  7654. "Zealous"
  7655. ];
  7656. //var pronouns = [
  7657. //];
  7658. //var conjunctions = [
  7659. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  7660. //];
  7661. /*
  7662. * Maps a string (category name) to the array of words from that category.
  7663. */
  7664. var CATEGORIES =
  7665. {
  7666. //"_NOUN_": nouns,
  7667. "_PLURALNOUN_": pluralNouns,
  7668. //"_PLACE_": places,
  7669. "_VERB_": verbs,
  7670. "_ADVERB_": adverbs,
  7671. "_ADJECTIVE_": adjectives
  7672. //"_PRONOUN_": pronouns,
  7673. //"_CONJUNCTION_": conjunctions,
  7674. };
  7675. var PATTERNS = [
  7676. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  7677. // BeautifulFungiOrSpaghetti
  7678. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  7679. // AmazinglyScaryToy
  7680. //"_ADVERB__ADJECTIVE__NOUN_",
  7681. // NeitherTrashNorRifle
  7682. //"Neither_NOUN_Nor_NOUN_",
  7683. //"Either_NOUN_Or_NOUN_",
  7684. // EitherCopulateOrInvestigate
  7685. //"Either_VERB_Or_VERB_",
  7686. //"Neither_VERB_Nor_VERB_",
  7687. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  7688. //"The_ADVERB__ADJECTIVE__NOUN_",
  7689. //"The_ADVERB__ADJECTIVE__NOUN_s",
  7690. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  7691. // WolvesComputeBadly
  7692. //"_PLURALNOUN__VERB__ADVERB_",
  7693. // UniteFacilitateAndMerge
  7694. //"_VERB__VERB_And_VERB_",
  7695. //NastyWitchesAtThePub
  7696. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  7697. ];
  7698. /*
  7699. * Returns a random element from the array 'arr'
  7700. */
  7701. function randomElement(arr)
  7702. {
  7703. return arr[Math.floor(Math.random() * arr.length)];
  7704. }
  7705. /*
  7706. * Returns true if the string 's' contains one of the
  7707. * template strings.
  7708. */
  7709. function hasTemplate(s)
  7710. {
  7711. for (var template in CATEGORIES){
  7712. if (s.indexOf(template) >= 0){
  7713. return true;
  7714. }
  7715. }
  7716. }
  7717. /**
  7718. * Generates new room name.
  7719. */
  7720. var RoomNameGenerator = {
  7721. generateRoomWithoutSeparator: function()
  7722. {
  7723. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  7724. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  7725. var name = randomElement(PATTERNS);
  7726. var word;
  7727. while (hasTemplate(name)){
  7728. for (var template in CATEGORIES){
  7729. word = randomElement(CATEGORIES[template]);
  7730. name = name.replace(template, word);
  7731. }
  7732. }
  7733. return name;
  7734. }
  7735. }
  7736. module.exports = RoomNameGenerator;
  7737. },{}],34:[function(require,module,exports){
  7738. var animateTimeout, updateTimeout;
  7739. var RoomNameGenerator = require("./RoomnameGenerator");
  7740. function enter_room()
  7741. {
  7742. var val = $("#enter_room_field").val();
  7743. if(!val) {
  7744. val = $("#enter_room_field").attr("room_name");
  7745. }
  7746. if (val) {
  7747. window.location.pathname = "/" + val;
  7748. }
  7749. }
  7750. function animate(word) {
  7751. var currentVal = $("#enter_room_field").attr("placeholder");
  7752. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  7753. animateTimeout = setTimeout(function() {
  7754. animate(word.substring(1, word.length))
  7755. }, 70);
  7756. }
  7757. function update_roomname()
  7758. {
  7759. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  7760. $("#enter_room_field").attr("room_name", word);
  7761. $("#enter_room_field").attr("placeholder", "");
  7762. clearTimeout(animateTimeout);
  7763. animate(word);
  7764. updateTimeout = setTimeout(update_roomname, 10000);
  7765. }
  7766. function setupWelcomePage()
  7767. {
  7768. $("#videoconference_page").hide();
  7769. $("#domain_name").text(
  7770. window.location.protocol + "//" + window.location.host + "/");
  7771. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7772. var leftWatermarkDiv
  7773. = $("#welcome_page_header div[class='watermark leftwatermark']");
  7774. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  7775. {
  7776. leftWatermarkDiv.css({display: 'block'});
  7777. leftWatermarkDiv.parent().get(0).href
  7778. = interfaceConfig.JITSI_WATERMARK_LINK;
  7779. }
  7780. }
  7781. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7782. var rightWatermarkDiv
  7783. = $("#welcome_page_header div[class='watermark rightwatermark']");
  7784. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  7785. rightWatermarkDiv.css({display: 'block'});
  7786. rightWatermarkDiv.parent().get(0).href
  7787. = interfaceConfig.BRAND_WATERMARK_LINK;
  7788. rightWatermarkDiv.get(0).style.backgroundImage
  7789. = "url(images/rightwatermark.png)";
  7790. }
  7791. }
  7792. if (interfaceConfig.SHOW_POWERED_BY) {
  7793. $("#welcome_page_header>a[class='poweredby']")
  7794. .css({display: 'block'});
  7795. }
  7796. $("#enter_room_button").click(function()
  7797. {
  7798. enter_room();
  7799. });
  7800. $("#enter_room_field").keydown(function (event) {
  7801. if (event.keyCode === 13 /* enter */) {
  7802. enter_room();
  7803. }
  7804. });
  7805. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  7806. var updateTimeout;
  7807. var animateTimeout;
  7808. $("#reload_roomname").click(function () {
  7809. clearTimeout(updateTimeout);
  7810. clearTimeout(animateTimeout);
  7811. update_roomname();
  7812. });
  7813. $("#reload_roomname").show();
  7814. update_roomname();
  7815. }
  7816. $("#disable_welcome").click(function () {
  7817. window.localStorage.welcomePageDisabled
  7818. = $("#disable_welcome").is(":checked");
  7819. });
  7820. }
  7821. module.exports = setupWelcomePage;
  7822. },{"./RoomnameGenerator":33}],35:[function(require,module,exports){
  7823. var EventEmitter = require("events");
  7824. var eventEmitter = new EventEmitter();
  7825. var CQEvents = require("../../service/connectionquality/CQEvents");
  7826. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7827. /**
  7828. * local stats
  7829. * @type {{}}
  7830. */
  7831. var stats = {};
  7832. /**
  7833. * remote stats
  7834. * @type {{}}
  7835. */
  7836. var remoteStats = {};
  7837. /**
  7838. * Interval for sending statistics to other participants
  7839. * @type {null}
  7840. */
  7841. var sendIntervalId = null;
  7842. /**
  7843. * Start statistics sending.
  7844. */
  7845. function startSendingStats() {
  7846. sendStats();
  7847. sendIntervalId = setInterval(sendStats, 10000);
  7848. }
  7849. /**
  7850. * Sends statistics to other participants
  7851. */
  7852. function sendStats() {
  7853. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  7854. }
  7855. /**
  7856. * Converts statistics to format for sending through XMPP
  7857. * @param stats the statistics
  7858. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  7859. */
  7860. function convertToMUCStats(stats) {
  7861. return {
  7862. "bitrate_download": stats.bitrate.download,
  7863. "bitrate_upload": stats.bitrate.upload,
  7864. "packetLoss_total": stats.packetLoss.total,
  7865. "packetLoss_download": stats.packetLoss.download,
  7866. "packetLoss_upload": stats.packetLoss.upload
  7867. };
  7868. }
  7869. /**
  7870. * Converts statitistics to format used by VideoLayout
  7871. * @param stats
  7872. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  7873. */
  7874. function parseMUCStats(stats) {
  7875. return {
  7876. bitrate: {
  7877. download: stats.bitrate_download,
  7878. upload: stats.bitrate_upload
  7879. },
  7880. packetLoss: {
  7881. total: stats.packetLoss_total,
  7882. download: stats.packetLoss_download,
  7883. upload: stats.packetLoss_upload
  7884. }
  7885. };
  7886. }
  7887. var ConnectionQuality = {
  7888. init: function () {
  7889. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  7890. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  7891. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  7892. },
  7893. /**
  7894. * Updates the local statistics
  7895. * @param data new statistics
  7896. */
  7897. updateLocalStats: function (data) {
  7898. stats = data;
  7899. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  7900. if (sendIntervalId == null) {
  7901. startSendingStats();
  7902. }
  7903. },
  7904. /**
  7905. * Updates remote statistics
  7906. * @param jid the jid associated with the statistics
  7907. * @param data the statistics
  7908. */
  7909. updateRemoteStats: function (jid, data) {
  7910. if (data == null || data.packetLoss_total == null) {
  7911. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  7912. return;
  7913. }
  7914. remoteStats[jid] = parseMUCStats(data);
  7915. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  7916. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  7917. },
  7918. /**
  7919. * Stops statistics sending.
  7920. */
  7921. stopSendingStats: function () {
  7922. clearInterval(sendIntervalId);
  7923. sendIntervalId = null;
  7924. //notify UI about stopping statistics gathering
  7925. eventEmitter.emit(CQEvents.STOP);
  7926. },
  7927. /**
  7928. * Returns the local statistics.
  7929. */
  7930. getStats: function () {
  7931. return stats;
  7932. },
  7933. addListener: function (type, listener) {
  7934. eventEmitter.on(type, listener);
  7935. }
  7936. };
  7937. module.exports = ConnectionQuality;
  7938. },{"../../service/connectionquality/CQEvents":86,"../../service/xmpp/XMPPEvents":89,"events":1}],36:[function(require,module,exports){
  7939. /* global $, alert, changeLocalVideo, chrome, config, getConferenceHandler, getUserMediaWithConstraints */
  7940. /**
  7941. * Indicates that desktop stream is currently in use(for toggle purpose).
  7942. * @type {boolean}
  7943. */
  7944. var isUsingScreenStream = false;
  7945. /**
  7946. * Indicates that switch stream operation is in progress and prevent from triggering new events.
  7947. * @type {boolean}
  7948. */
  7949. var switchInProgress = false;
  7950. /**
  7951. * Method used to get screen sharing stream.
  7952. *
  7953. * @type {function (stream_callback, failure_callback}
  7954. */
  7955. var obtainDesktopStream = null;
  7956. /**
  7957. * Flag used to cache desktop sharing enabled state. Do not use directly as it can be <tt>null</tt>.
  7958. * @type {null|boolean}
  7959. */
  7960. var _desktopSharingEnabled = null;
  7961. var EventEmitter = require("events");
  7962. var eventEmitter = new EventEmitter();
  7963. var DesktopSharingEventTypes = require("../../service/desktopsharing/DesktopSharingEventTypes");
  7964. /**
  7965. * Method obtains desktop stream from WebRTC 'screen' source.
  7966. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  7967. */
  7968. function obtainWebRTCScreen(streamCallback, failCallback) {
  7969. APP.RTC.getUserMediaWithConstraints(
  7970. ['screen'],
  7971. streamCallback,
  7972. failCallback
  7973. );
  7974. }
  7975. /**
  7976. * Constructs inline install URL for Chrome desktop streaming extension.
  7977. * The 'chromeExtensionId' must be defined in config.js.
  7978. * @returns {string}
  7979. */
  7980. function getWebStoreInstallUrl()
  7981. {
  7982. return "https://chrome.google.com/webstore/detail/" + config.chromeExtensionId;
  7983. }
  7984. /**
  7985. * Checks whether extension update is required.
  7986. * @param minVersion minimal required version
  7987. * @param extVersion current extension version
  7988. * @returns {boolean}
  7989. */
  7990. function isUpdateRequired(minVersion, extVersion)
  7991. {
  7992. try
  7993. {
  7994. var s1 = minVersion.split('.');
  7995. var s2 = extVersion.split('.');
  7996. var len = Math.max(s1.length, s2.length);
  7997. for (var i = 0; i < len; i++)
  7998. {
  7999. var n1 = 0,
  8000. n2 = 0;
  8001. if (i < s1.length)
  8002. n1 = parseInt(s1[i]);
  8003. if (i < s2.length)
  8004. n2 = parseInt(s2[i]);
  8005. if (isNaN(n1) || isNaN(n2))
  8006. {
  8007. return true;
  8008. }
  8009. else if (n1 !== n2)
  8010. {
  8011. return n1 > n2;
  8012. }
  8013. }
  8014. // will happen if boths version has identical numbers in
  8015. // their components (even if one of them is longer, has more components)
  8016. return false;
  8017. }
  8018. catch (e)
  8019. {
  8020. console.error("Failed to parse extension version", e);
  8021. APP.UI.messageHandler.showError("dialog.error", 'Error',
  8022. "dialod.detectext",
  8023. 'Error when trying to detect desktopsharing extension.');
  8024. return true;
  8025. }
  8026. }
  8027. function checkExtInstalled(isInstalledCallback) {
  8028. if (!chrome.runtime) {
  8029. // No API, so no extension for sure
  8030. isInstalledCallback(false);
  8031. return;
  8032. }
  8033. chrome.runtime.sendMessage(
  8034. config.chromeExtensionId,
  8035. { getVersion: true },
  8036. function (response) {
  8037. if (!response || !response.version) {
  8038. // Communication failure - assume that no endpoint exists
  8039. console.warn("Extension not installed?: " + chrome.runtime.lastError);
  8040. isInstalledCallback(false);
  8041. } else {
  8042. // Check installed extension version
  8043. var extVersion = response.version;
  8044. console.log('Extension version is: ' + extVersion);
  8045. var updateRequired = isUpdateRequired(config.minChromeExtVersion, extVersion);
  8046. if (updateRequired) {
  8047. alert(
  8048. 'Jitsi Desktop Streamer requires update. ' +
  8049. 'Changes will take effect after next Chrome restart.');
  8050. }
  8051. isInstalledCallback(!updateRequired);
  8052. }
  8053. }
  8054. );
  8055. }
  8056. function doGetStreamFromExtension(streamCallback, failCallback) {
  8057. // Sends 'getStream' msg to the extension. Extension id must be defined in the config.
  8058. chrome.runtime.sendMessage(
  8059. config.chromeExtensionId,
  8060. { getStream: true, sources: config.desktopSharingSources },
  8061. function (response) {
  8062. if (!response) {
  8063. failCallback(chrome.runtime.lastError);
  8064. return;
  8065. }
  8066. console.log("Response from extension: " + response);
  8067. if (response.streamId) {
  8068. APP.RTC.getUserMediaWithConstraints(
  8069. ['desktop'],
  8070. function (stream) {
  8071. streamCallback(stream);
  8072. },
  8073. failCallback,
  8074. null, null, null,
  8075. response.streamId);
  8076. } else {
  8077. failCallback("Extension failed to get the stream");
  8078. }
  8079. }
  8080. );
  8081. }
  8082. /**
  8083. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop' stream for returned stream token.
  8084. */
  8085. function obtainScreenFromExtension(streamCallback, failCallback) {
  8086. checkExtInstalled(
  8087. function (isInstalled) {
  8088. if (isInstalled) {
  8089. doGetStreamFromExtension(streamCallback, failCallback);
  8090. } else {
  8091. chrome.webstore.install(
  8092. getWebStoreInstallUrl(),
  8093. function (arg) {
  8094. console.log("Extension installed successfully", arg);
  8095. // We need to reload the page in order to get the access to chrome.runtime
  8096. window.location.reload(false);
  8097. },
  8098. function (arg) {
  8099. console.log("Failed to install the extension", arg);
  8100. failCallback(arg);
  8101. APP.UI.messageHandler.showError("dialog.error", 'Error',
  8102. "dialog.failtoinstall",
  8103. 'Failed to install desktop sharing extension');
  8104. }
  8105. );
  8106. }
  8107. }
  8108. );
  8109. }
  8110. /**
  8111. * Call this method to toggle desktop sharing feature.
  8112. * @param method pass "ext" to use chrome extension for desktop capture(chrome extension required),
  8113. * pass "webrtc" to use WebRTC "screen" desktop source('chrome://flags/#enable-usermedia-screen-capture'
  8114. * must be enabled), pass any other string or nothing in order to disable this feature completely.
  8115. */
  8116. function setDesktopSharing(method) {
  8117. // Check if we are running chrome
  8118. if (!navigator.webkitGetUserMedia) {
  8119. obtainDesktopStream = null;
  8120. console.info("Desktop sharing disabled");
  8121. } else if (method == "ext") {
  8122. obtainDesktopStream = obtainScreenFromExtension;
  8123. console.info("Using Chrome extension for desktop sharing");
  8124. } else if (method == "webrtc") {
  8125. obtainDesktopStream = obtainWebRTCScreen;
  8126. console.info("Using Chrome WebRTC for desktop sharing");
  8127. }
  8128. // Reset enabled cache
  8129. _desktopSharingEnabled = null;
  8130. }
  8131. /**
  8132. * Initializes <link rel=chrome-webstore-item /> with extension id set in config.js to support inline installs.
  8133. * Host site must be selected as main website of published extension.
  8134. */
  8135. function initInlineInstalls()
  8136. {
  8137. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  8138. }
  8139. function getSwitchStreamFailed(error) {
  8140. console.error("Failed to obtain the stream to switch to", error);
  8141. switchInProgress = false;
  8142. }
  8143. function streamSwitchDone() {
  8144. switchInProgress = false;
  8145. eventEmitter.emit(
  8146. DesktopSharingEventTypes.SWITCHING_DONE,
  8147. isUsingScreenStream);
  8148. }
  8149. function newStreamCreated(stream)
  8150. {
  8151. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  8152. stream, isUsingScreenStream, streamSwitchDone);
  8153. }
  8154. module.exports = {
  8155. isUsingScreenStream: function () {
  8156. return isUsingScreenStream;
  8157. },
  8158. /**
  8159. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available and enabled.
  8160. */
  8161. isDesktopSharingEnabled: function () {
  8162. if (_desktopSharingEnabled === null) {
  8163. if (obtainDesktopStream === obtainScreenFromExtension) {
  8164. // Parse chrome version
  8165. var userAgent = navigator.userAgent.toLowerCase();
  8166. // We can assume that user agent is chrome, because it's enforced when 'ext' streaming method is set
  8167. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  8168. console.log("Chrome version" + userAgent, ver);
  8169. _desktopSharingEnabled = ver >= 34;
  8170. } else {
  8171. _desktopSharingEnabled = obtainDesktopStream === obtainWebRTCScreen;
  8172. }
  8173. }
  8174. return _desktopSharingEnabled;
  8175. },
  8176. init: function () {
  8177. setDesktopSharing(config.desktopSharing);
  8178. // Initialize Chrome extension inline installs
  8179. if (config.chromeExtensionId) {
  8180. initInlineInstalls();
  8181. }
  8182. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  8183. },
  8184. addListener: function(listener, type)
  8185. {
  8186. eventEmitter.on(type, listener);
  8187. },
  8188. removeListener: function (listener,type) {
  8189. eventEmitter.removeListener(type, listener);
  8190. },
  8191. /*
  8192. * Toggles screen sharing.
  8193. */
  8194. toggleScreenSharing: function () {
  8195. if (switchInProgress || !obtainDesktopStream) {
  8196. console.warn("Switch in progress or no method defined");
  8197. return;
  8198. }
  8199. switchInProgress = true;
  8200. if (!isUsingScreenStream)
  8201. {
  8202. // Switch to desktop stream
  8203. obtainDesktopStream(
  8204. function (stream) {
  8205. // We now use screen stream
  8206. isUsingScreenStream = true;
  8207. // Hook 'ended' event to restore camera when screen stream stops
  8208. stream.addEventListener('ended',
  8209. function (e) {
  8210. if (!switchInProgress && isUsingScreenStream) {
  8211. toggleScreenSharing();
  8212. }
  8213. }
  8214. );
  8215. newStreamCreated(stream);
  8216. },
  8217. getSwitchStreamFailed);
  8218. } else {
  8219. // Disable screen stream
  8220. APP.RTC.getUserMediaWithConstraints(
  8221. ['video'],
  8222. function (stream) {
  8223. // We are now using camera stream
  8224. isUsingScreenStream = false;
  8225. newStreamCreated(stream);
  8226. },
  8227. getSwitchStreamFailed, config.resolution || '360'
  8228. );
  8229. }
  8230. }
  8231. };
  8232. },{"../../service/desktopsharing/DesktopSharingEventTypes":87,"events":1}],37:[function(require,module,exports){
  8233. //maps keycode to character, id of popover for given function and function
  8234. var shortcuts = {
  8235. 67: {
  8236. character: "C",
  8237. id: "toggleChatPopover",
  8238. function: APP.UI.toggleChat
  8239. },
  8240. 70: {
  8241. character: "F",
  8242. id: "filmstripPopover",
  8243. function: APP.UI.toggleFilmStrip
  8244. },
  8245. 77: {
  8246. character: "M",
  8247. id: "mutePopover",
  8248. function: APP.UI.toggleAudio
  8249. },
  8250. 84: {
  8251. character: "T",
  8252. function: function() {
  8253. if(!APP.RTC.localAudio.isMuted()) {
  8254. APP.UI.toggleAudio();
  8255. }
  8256. }
  8257. },
  8258. 86: {
  8259. character: "V",
  8260. id: "toggleVideoPopover",
  8261. function: APP.UI.toggleVideo
  8262. }
  8263. };
  8264. var KeyboardShortcut = {
  8265. init: function () {
  8266. window.onkeyup = function(e) {
  8267. var keycode = e.which;
  8268. if(!($(":focus").is("input[type=text]") ||
  8269. $(":focus").is("input[type=password]") ||
  8270. $(":focus").is("textarea"))) {
  8271. if (typeof shortcuts[keycode] === "object") {
  8272. shortcuts[keycode].function();
  8273. }
  8274. else if (keycode >= "0".charCodeAt(0) &&
  8275. keycode <= "9".charCodeAt(0)) {
  8276. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8277. }
  8278. //esc while the smileys are visible hides them
  8279. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8280. APP.UI.toggleSmileys();
  8281. }
  8282. };
  8283. window.onkeydown = function(e) {
  8284. if(!($(":focus").is("input[type=text]") ||
  8285. $(":focus").is("input[type=password]") ||
  8286. $(":focus").is("textarea"))) {
  8287. if(e.which === "T".charCodeAt(0)) {
  8288. if(APP.RTC.localAudio.isMuted()) {
  8289. APP.UI.toggleAudio();
  8290. }
  8291. }
  8292. }
  8293. };
  8294. var self = this;
  8295. $('body').popover({ selector: '[data-toggle=popover]',
  8296. trigger: 'click hover',
  8297. content: function() {
  8298. return this.getAttribute("content") +
  8299. self.getShortcut(this.getAttribute("shortcut"));
  8300. }
  8301. });
  8302. },
  8303. /**
  8304. *
  8305. * @param id indicates the popover associated with the shortcut
  8306. * @returns {string} the keyboard shortcut used for the id given
  8307. */
  8308. getShortcut: function (id) {
  8309. for (var keycode in shortcuts) {
  8310. if (shortcuts.hasOwnProperty(keycode)) {
  8311. if (shortcuts[keycode].id === id) {
  8312. return " (" + shortcuts[keycode].character + ")";
  8313. }
  8314. }
  8315. }
  8316. return "";
  8317. }
  8318. };
  8319. module.exports = KeyboardShortcut;
  8320. },{}],38:[function(require,module,exports){
  8321. var email = '';
  8322. var displayName = '';
  8323. var userId;
  8324. function supportsLocalStorage() {
  8325. try {
  8326. return 'localStorage' in window && window.localStorage !== null;
  8327. } catch (e) {
  8328. console.log("localstorage is not supported");
  8329. return false;
  8330. }
  8331. }
  8332. function generateUniqueId() {
  8333. function _p8() {
  8334. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8335. }
  8336. return _p8() + _p8() + _p8() + _p8();
  8337. }
  8338. if (supportsLocalStorage()) {
  8339. if (!window.localStorage.jitsiMeetId) {
  8340. window.localStorage.jitsiMeetId = generateUniqueId();
  8341. console.log("generated id", window.localStorage.jitsiMeetId);
  8342. }
  8343. userId = window.localStorage.jitsiMeetId || '';
  8344. email = window.localStorage.email || '';
  8345. displayName = window.localStorage.displayname || '';
  8346. } else {
  8347. console.log("local storage is not supported");
  8348. userId = generateUniqueId();
  8349. }
  8350. var Settings =
  8351. {
  8352. setDisplayName: function (newDisplayName) {
  8353. displayName = newDisplayName;
  8354. window.localStorage.displayname = displayName;
  8355. return displayName;
  8356. },
  8357. setEmail: function (newEmail)
  8358. {
  8359. email = newEmail;
  8360. window.localStorage.email = newEmail;
  8361. return email;
  8362. },
  8363. getSettings: function () {
  8364. return {
  8365. email: email,
  8366. displayName: displayName,
  8367. uid: userId
  8368. };
  8369. }
  8370. };
  8371. module.exports = Settings;
  8372. },{}],39:[function(require,module,exports){
  8373. /**
  8374. *
  8375. * @constructor
  8376. */
  8377. function SimulcastLogger(name, lvl) {
  8378. this.name = name;
  8379. this.lvl = lvl;
  8380. }
  8381. SimulcastLogger.prototype.log = function (text) {
  8382. if (this.lvl) {
  8383. console.log(text);
  8384. }
  8385. };
  8386. SimulcastLogger.prototype.info = function (text) {
  8387. if (this.lvl > 1) {
  8388. console.info(text);
  8389. }
  8390. };
  8391. SimulcastLogger.prototype.fine = function (text) {
  8392. if (this.lvl > 2) {
  8393. console.log(text);
  8394. }
  8395. };
  8396. SimulcastLogger.prototype.error = function (text) {
  8397. console.error(text);
  8398. };
  8399. module.exports = SimulcastLogger;
  8400. },{}],40:[function(require,module,exports){
  8401. var SimulcastLogger = require("./SimulcastLogger");
  8402. var SimulcastUtils = require("./SimulcastUtils");
  8403. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  8404. function SimulcastReceiver() {
  8405. this.simulcastUtils = new SimulcastUtils();
  8406. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  8407. }
  8408. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  8409. SimulcastReceiver.prototype._remoteMaps = {
  8410. msid2Quality: {},
  8411. ssrc2Msid: {},
  8412. msid2ssrc: {},
  8413. receivingVideoStreams: {}
  8414. };
  8415. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  8416. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8417. };
  8418. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  8419. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  8420. };
  8421. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  8422. var sb;
  8423. this.logger.info('Ensuring x-google-conference flag...')
  8424. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8425. // TODO(gp) do that for the audio as well as suggested by fippo.
  8426. // Add the google conference flag
  8427. sb = this.simulcastUtils._getVideoSources(lines);
  8428. sb = ['a=x-google-flag:conference'].concat(sb);
  8429. this.simulcastUtils._replaceVideoSources(lines, sb);
  8430. }
  8431. };
  8432. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  8433. this._restoreRemoteVideoSources(sb);
  8434. };
  8435. /**
  8436. * Restores the simulcast groups of the remote description. In
  8437. * transformRemoteDescription we remove those in order for the set remote
  8438. * description to succeed. The focus needs the signal the groups to new
  8439. * participants.
  8440. *
  8441. * @param desc
  8442. * @returns {*}
  8443. */
  8444. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  8445. var sb;
  8446. if (!this.simulcastUtils.isValidDescription(desc)) {
  8447. return desc;
  8448. }
  8449. if (config.enableSimulcast) {
  8450. sb = desc.sdp.split('\r\n');
  8451. this._restoreSimulcastGroups(sb);
  8452. desc = new RTCSessionDescription({
  8453. type: desc.type,
  8454. sdp: sb.join('\r\n')
  8455. });
  8456. }
  8457. return desc;
  8458. };
  8459. SimulcastUtils.prototype._ensureOrder = function (lines) {
  8460. var videoSources, sb;
  8461. videoSources = this.parseMedia(lines, ['video'])[0];
  8462. sb = this._compileVideoSources(videoSources);
  8463. this._replaceVideoSources(lines, sb);
  8464. };
  8465. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  8466. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  8467. videoSource, quality;
  8468. // (re) initialize the remote maps.
  8469. this._remoteMaps.msid2Quality = {};
  8470. this._remoteMaps.ssrc2Msid = {};
  8471. this._remoteMaps.msid2ssrc = {};
  8472. var self = this;
  8473. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  8474. remoteVideoSources.groups.forEach(function (group) {
  8475. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  8476. quality = 0;
  8477. group.ssrcs.forEach(function (ssrc) {
  8478. videoSource = remoteVideoSources.sources[ssrc];
  8479. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  8480. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  8481. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  8482. });
  8483. }
  8484. });
  8485. }
  8486. };
  8487. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  8488. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  8489. };
  8490. /**
  8491. * Returns a stream with single video track, the one currently being
  8492. * received by this endpoint.
  8493. *
  8494. * @param stream the remote simulcast stream.
  8495. * @returns {webkitMediaStream}
  8496. */
  8497. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  8498. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  8499. var self = this;
  8500. if (config.enableSimulcast) {
  8501. stream.getVideoTracks().some(function (track) {
  8502. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  8503. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  8504. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  8505. if (msid == [stream.id, track.id].join(' ')) {
  8506. electedTrack = track;
  8507. return true;
  8508. }
  8509. });
  8510. });
  8511. if (!electedTrack) {
  8512. // we don't have an elected track, choose by initial quality.
  8513. tracks = stream.getVideoTracks();
  8514. for (i = 0; i < tracks.length; i++) {
  8515. msid = [stream.id, tracks[i].id].join(' ');
  8516. if (this._remoteMaps.msid2Quality[msid] === quality) {
  8517. electedTrack = tracks[i];
  8518. break;
  8519. }
  8520. }
  8521. // TODO(gp) if the initialQuality could not be satisfied, lower
  8522. // the requirement and try again.
  8523. }
  8524. }
  8525. return (electedTrack)
  8526. ? new webkitMediaStream([electedTrack])
  8527. : stream;
  8528. };
  8529. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  8530. var resource = Strophe.getResourceFromJid(jid);
  8531. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  8532. // If we haven't receiving a "changed" event yet, then we must be receiving
  8533. // low quality (that the sender always streams).
  8534. if(!ssrc)
  8535. {
  8536. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8537. var remoteStream = remoteStreamObject.getOriginalStream();
  8538. var tracks = remoteStream.getVideoTracks();
  8539. if (tracks) {
  8540. for (var k = 0; k < tracks.length; k++) {
  8541. var track = tracks[k];
  8542. var msid = [remoteStream.id, track.id].join(' ');
  8543. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  8544. var quality = this._remoteMaps.msid2Quality[msid];
  8545. if (quality == 0) {
  8546. ssrc = _ssrc;
  8547. }
  8548. }
  8549. }
  8550. }
  8551. return ssrc;
  8552. };
  8553. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  8554. {
  8555. var sid, electedStream;
  8556. var i, j, k;
  8557. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  8558. if(jid && APP.RTC.remoteStreams[jid])
  8559. {
  8560. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8561. var remoteStream = remoteStreamObject.getOriginalStream();
  8562. var tracks = remoteStream.getVideoTracks();
  8563. if (tracks) {
  8564. for (k = 0; k < tracks.length; k++) {
  8565. var track = tracks[k];
  8566. var msid = [remoteStream.id, track.id].join(' ');
  8567. var tmp = this._remoteMaps.msid2ssrc[msid];
  8568. if (tmp == ssrc) {
  8569. electedStream = new webkitMediaStream([track]);
  8570. sid = remoteStreamObject.sid;
  8571. // stream found, stop.
  8572. break;
  8573. }
  8574. }
  8575. }
  8576. }
  8577. else
  8578. {
  8579. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  8580. }
  8581. return {
  8582. sid: sid,
  8583. stream: electedStream
  8584. };
  8585. };
  8586. /**
  8587. * Gets the fully qualified msid (stream.id + track.id) associated to the
  8588. * SSRC.
  8589. *
  8590. * @param ssrc
  8591. * @returns {*}
  8592. */
  8593. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  8594. return this._remoteMaps.ssrc2Msid[ssrc];
  8595. };
  8596. /**
  8597. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  8598. * either gets confused and thinks this is an FID group or, if an FID group
  8599. * is already present, it fails to set the remote description.
  8600. *
  8601. * @param desc
  8602. * @returns {*}
  8603. */
  8604. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  8605. if (desc && desc.sdp) {
  8606. var sb = desc.sdp.split('\r\n');
  8607. this._updateRemoteMaps(sb);
  8608. this._cacheRemoteVideoSources(sb);
  8609. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  8610. // need the simulcast group in the _updateRemoteMaps() method.
  8611. this.simulcastUtils._removeSimulcastGroup(sb);
  8612. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  8613. // We don't need the goog conference flag if we're not doing
  8614. // simulcast.
  8615. this._ensureGoogConference(sb);
  8616. }
  8617. desc = new RTCSessionDescription({
  8618. type: desc.type,
  8619. sdp: sb.join('\r\n')
  8620. });
  8621. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  8622. }
  8623. return desc;
  8624. };
  8625. module.exports = SimulcastReceiver;
  8626. },{"../../service/RTC/MediaStreamTypes":79,"./SimulcastLogger":39,"./SimulcastUtils":42}],41:[function(require,module,exports){
  8627. var SimulcastLogger = require("./SimulcastLogger");
  8628. var SimulcastUtils = require("./SimulcastUtils");
  8629. function SimulcastSender() {
  8630. this.simulcastUtils = new SimulcastUtils();
  8631. this.logger = new SimulcastLogger('SimulcastSender', 1);
  8632. }
  8633. SimulcastSender.prototype.displayedLocalVideoStream = null;
  8634. SimulcastSender.prototype._generateGuid = (function () {
  8635. function s4() {
  8636. return Math.floor((1 + Math.random()) * 0x10000)
  8637. .toString(16)
  8638. .substring(1);
  8639. }
  8640. return function () {
  8641. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  8642. s4() + '-' + s4() + s4() + s4();
  8643. };
  8644. }());
  8645. // Returns a random integer between min (included) and max (excluded)
  8646. // Using Math.round() gives a non-uniform distribution!
  8647. SimulcastSender.prototype._generateRandomSSRC = function () {
  8648. var min = 0, max = 0xffffffff;
  8649. return Math.floor(Math.random() * (max - min)) + min;
  8650. };
  8651. SimulcastSender.prototype.getLocalVideoStream = function () {
  8652. return (this.displayedLocalVideoStream != null)
  8653. ? this.displayedLocalVideoStream
  8654. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  8655. : APP.RTC.localVideo.getOriginalStream();
  8656. };
  8657. function NativeSimulcastSender() {
  8658. SimulcastSender.call(this); // call the super constructor.
  8659. }
  8660. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8661. NativeSimulcastSender.prototype._localExplosionMap = {};
  8662. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  8663. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  8664. NativeSimulcastSender.prototype.reset = function () {
  8665. this._localExplosionMap = {};
  8666. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  8667. };
  8668. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  8669. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8670. };
  8671. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  8672. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  8673. };
  8674. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  8675. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  8676. this.logger.info('Appending simulcast group...');
  8677. // Get the primary SSRC information.
  8678. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8679. // Start building the SIM SSRC group.
  8680. ssrcGroup = ['a=ssrc-group:SIM'];
  8681. // The video source buffer.
  8682. sb = [];
  8683. // Create the simulcast sub-streams.
  8684. for (i = 0; i < numOfSubs; i++) {
  8685. // TODO(gp) prevent SSRC collision.
  8686. simSSRC = this._generateRandomSSRC();
  8687. ssrcGroup.push(simSSRC);
  8688. if (videoSources.base) {
  8689. sb.splice.apply(sb, [sb.length, 0].concat(
  8690. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  8691. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  8692. ));
  8693. }
  8694. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  8695. }
  8696. // Add the group sim layers.
  8697. sb.splice(0, 0, ssrcGroup.join(' '))
  8698. this.simulcastUtils._replaceVideoSources(lines, sb);
  8699. };
  8700. // Does the actual patching.
  8701. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  8702. this.logger.info('Ensuring simulcast group...');
  8703. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8704. this._appendSimulcastGroup(lines);
  8705. this._cacheLocalVideoSources(lines);
  8706. } else {
  8707. // verify that the ssrcs participating in the SIM group are present
  8708. // in the SDP (needed for presence).
  8709. this._restoreLocalVideoSources(lines);
  8710. }
  8711. };
  8712. /**
  8713. * Produces a single stream with multiple tracks for local video sources.
  8714. *
  8715. * @param lines
  8716. * @private
  8717. */
  8718. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  8719. var sb, msid, sid, tid, videoSources, self;
  8720. this.logger.info('Exploding local video sources...');
  8721. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8722. self = this;
  8723. if (videoSources.groups && videoSources.groups.length !== 0) {
  8724. videoSources.groups.forEach(function (group) {
  8725. if (group.semantics === 'SIM') {
  8726. group.ssrcs.forEach(function (ssrc) {
  8727. // Get the msid for this ssrc..
  8728. if (self._localExplosionMap[ssrc]) {
  8729. // .. either from the explosion map..
  8730. msid = self._localExplosionMap[ssrc];
  8731. } else {
  8732. // .. or generate a new one (msid).
  8733. sid = videoSources.sources[ssrc].msid
  8734. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  8735. tid = self._generateGuid();
  8736. msid = [sid, tid].join(' ');
  8737. self._localExplosionMap[ssrc] = msid;
  8738. }
  8739. // Assign it to the source object.
  8740. videoSources.sources[ssrc].msid = msid;
  8741. // TODO(gp) Change the msid of associated sources.
  8742. });
  8743. }
  8744. });
  8745. }
  8746. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8747. this.simulcastUtils._replaceVideoSources(lines, sb);
  8748. };
  8749. /**
  8750. * GUM for simulcast.
  8751. *
  8752. * @param constraints
  8753. * @param success
  8754. * @param err
  8755. */
  8756. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8757. // There's nothing special to do for native simulcast, so just do a normal GUM.
  8758. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8759. success(hqStream);
  8760. }, err);
  8761. };
  8762. /**
  8763. * Prepares the local description for public usage (i.e. to be signaled
  8764. * through Jingle to the focus).
  8765. *
  8766. * @param desc
  8767. * @returns {RTCSessionDescription}
  8768. */
  8769. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8770. var sb;
  8771. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8772. return desc;
  8773. }
  8774. sb = desc.sdp.split('\r\n');
  8775. this._explodeSimulcastSenderSources(sb);
  8776. desc = new RTCSessionDescription({
  8777. type: desc.type,
  8778. sdp: sb.join('\r\n')
  8779. });
  8780. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  8781. return desc;
  8782. };
  8783. /**
  8784. * Ensures that the simulcast group is present in the answer, _if_ native
  8785. * simulcast is enabled,
  8786. *
  8787. * @param desc
  8788. * @returns {*}
  8789. */
  8790. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  8791. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8792. return desc;
  8793. }
  8794. var sb = desc.sdp.split('\r\n');
  8795. // Even if we have enabled native simulcasting previously
  8796. // (with a call to SLD with an appropriate SDP, for example),
  8797. // createAnswer seems to consistently generate incomplete SDP
  8798. // with missing SSRCS.
  8799. //
  8800. // So, subsequent calls to SLD will have missing SSRCS and presence
  8801. // won't have the complete list of SRCs.
  8802. this._ensureSimulcastGroup(sb);
  8803. desc = new RTCSessionDescription({
  8804. type: desc.type,
  8805. sdp: sb.join('\r\n')
  8806. });
  8807. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  8808. return desc;
  8809. };
  8810. /**
  8811. *
  8812. *
  8813. * @param desc
  8814. * @returns {*}
  8815. */
  8816. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8817. return desc;
  8818. };
  8819. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8820. // Nothing to do here, native simulcast does that auto-magically.
  8821. };
  8822. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  8823. function SimpleSimulcastSender() {
  8824. SimulcastSender.call(this);
  8825. }
  8826. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8827. SimpleSimulcastSender.prototype.localStream = null;
  8828. SimpleSimulcastSender.prototype._localMaps = {
  8829. msids: [],
  8830. msid2ssrc: {}
  8831. };
  8832. /**
  8833. * Groups local video sources together in the ssrc-group:SIM group.
  8834. *
  8835. * @param lines
  8836. * @private
  8837. */
  8838. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  8839. var sb, videoSources, ssrcs = [], ssrc;
  8840. this.logger.info('Grouping local video sources...');
  8841. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8842. for (ssrc in videoSources.sources) {
  8843. // jitsi-meet destroys/creates streams at various places causing
  8844. // the original local stream ids to change. The only thing that
  8845. // remains unchanged is the trackid.
  8846. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  8847. }
  8848. var self = this;
  8849. // TODO(gp) add only "free" sources.
  8850. this._localMaps.msids.forEach(function (msid) {
  8851. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  8852. });
  8853. if (!videoSources.groups) {
  8854. videoSources.groups = [];
  8855. }
  8856. videoSources.groups.push({
  8857. 'semantics': 'SIM',
  8858. 'ssrcs': ssrcs
  8859. });
  8860. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8861. this.simulcastUtils._replaceVideoSources(lines, sb);
  8862. };
  8863. /**
  8864. * GUM for simulcast.
  8865. *
  8866. * @param constraints
  8867. * @param success
  8868. * @param err
  8869. */
  8870. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8871. // TODO(gp) what if we request a resolution not supported by the hardware?
  8872. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  8873. var lqConstraints = {
  8874. audio: false,
  8875. video: {
  8876. mandatory: {
  8877. maxWidth: 320,
  8878. maxHeight: 180,
  8879. maxFrameRate: 15
  8880. }
  8881. }
  8882. };
  8883. this.logger.info('HQ constraints: ', constraints);
  8884. this.logger.info('LQ constraints: ', lqConstraints);
  8885. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  8886. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  8887. // reason appears to be that Chrome only acquires the cam once and
  8888. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  8889. var self = this;
  8890. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8891. self.localStream = hqStream;
  8892. // reset local maps.
  8893. self._localMaps.msids = [];
  8894. self._localMaps.msid2ssrc = {};
  8895. // add hq trackid to local map
  8896. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  8897. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  8898. self.displayedLocalVideoStream = lqStream;
  8899. // NOTE(gp) The specification says Array.forEach() will visit
  8900. // the array elements in numeric order, and that it doesn't
  8901. // visit elements that don't exist.
  8902. // add lq trackid to local map
  8903. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  8904. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  8905. success(self.localStream);
  8906. }, err);
  8907. }, err);
  8908. };
  8909. /**
  8910. * Prepares the local description for public usage (i.e. to be signaled
  8911. * through Jingle to the focus).
  8912. *
  8913. * @param desc
  8914. * @returns {RTCSessionDescription}
  8915. */
  8916. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8917. var sb;
  8918. if (!this.simulcastUtils.isValidDescription(desc)) {
  8919. return desc;
  8920. }
  8921. sb = desc.sdp.split('\r\n');
  8922. this._groupLocalVideoSources(sb);
  8923. desc = new RTCSessionDescription({
  8924. type: desc.type,
  8925. sdp: sb.join('\r\n')
  8926. });
  8927. this.logger.fine('Grouped local video sources');
  8928. this.logger.fine(desc.sdp);
  8929. return desc;
  8930. };
  8931. /**
  8932. * Ensures that the simulcast group is present in the answer, _if_ native
  8933. * simulcast is enabled,
  8934. *
  8935. * @param desc
  8936. * @returns {*}
  8937. */
  8938. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  8939. return desc;
  8940. };
  8941. /**
  8942. *
  8943. *
  8944. * @param desc
  8945. * @returns {*}
  8946. */
  8947. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8948. var sb = desc.sdp.split('\r\n');
  8949. this.simulcastUtils._removeSimulcastGroup(sb);
  8950. desc = new RTCSessionDescription({
  8951. type: desc.type,
  8952. sdp: sb.join('\r\n')
  8953. });
  8954. this.logger.fine('Transformed local description');
  8955. this.logger.fine(desc.sdp);
  8956. return desc;
  8957. };
  8958. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8959. var trackid;
  8960. var self = this;
  8961. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  8962. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  8963. // Search for the track id that corresponds to the ssrc
  8964. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  8965. trackid = tid;
  8966. return true;
  8967. }
  8968. }) && self.localStream.getVideoTracks().some(function (track) {
  8969. // Start/stop the track that corresponds to the track id
  8970. if (track.id === trackid) {
  8971. track.enabled = enabled;
  8972. return true;
  8973. }
  8974. })) {
  8975. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  8976. $(document).trigger(enabled
  8977. ? 'simulcastlayerstarted'
  8978. : 'simulcastlayerstopped');
  8979. } else {
  8980. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  8981. }
  8982. };
  8983. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  8984. function NoSimulcastSender() {
  8985. SimulcastSender.call(this);
  8986. }
  8987. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8988. /**
  8989. * GUM for simulcast.
  8990. *
  8991. * @param constraints
  8992. * @param success
  8993. * @param err
  8994. */
  8995. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8996. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8997. success(hqStream);
  8998. }, err);
  8999. };
  9000. /**
  9001. * Prepares the local description for public usage (i.e. to be signaled
  9002. * through Jingle to the focus).
  9003. *
  9004. * @param desc
  9005. * @returns {RTCSessionDescription}
  9006. */
  9007. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9008. return desc;
  9009. };
  9010. /**
  9011. * Ensures that the simulcast group is present in the answer, _if_ native
  9012. * simulcast is enabled,
  9013. *
  9014. * @param desc
  9015. * @returns {*}
  9016. */
  9017. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  9018. return desc;
  9019. };
  9020. /**
  9021. *
  9022. *
  9023. * @param desc
  9024. * @returns {*}
  9025. */
  9026. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9027. return desc;
  9028. };
  9029. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9030. };
  9031. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  9032. module.exports = {
  9033. "native": NativeSimulcastSender,
  9034. "no": NoSimulcastSender
  9035. }
  9036. },{"./SimulcastLogger":39,"./SimulcastUtils":42}],42:[function(require,module,exports){
  9037. var SimulcastLogger = require("./SimulcastLogger");
  9038. /**
  9039. *
  9040. * @constructor
  9041. */
  9042. function SimulcastUtils() {
  9043. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  9044. }
  9045. /**
  9046. *
  9047. * @type {{}}
  9048. * @private
  9049. */
  9050. SimulcastUtils.prototype._emptyCompoundIndex = {};
  9051. /**
  9052. *
  9053. * @param lines
  9054. * @param videoSources
  9055. * @private
  9056. */
  9057. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  9058. var i, inVideo = false, index = -1, howMany = 0;
  9059. this.logger.info('Replacing video sources...');
  9060. for (i = 0; i < lines.length; i++) {
  9061. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9062. // Out of video.
  9063. break;
  9064. }
  9065. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9066. // In video.
  9067. inVideo = true;
  9068. }
  9069. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  9070. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  9071. if (index === -1) {
  9072. index = i;
  9073. }
  9074. howMany++;
  9075. }
  9076. }
  9077. // efficiency baby ;)
  9078. lines.splice.apply(lines,
  9079. [index, howMany].concat(videoSources));
  9080. };
  9081. SimulcastUtils.prototype.isValidDescription = function (desc)
  9082. {
  9083. return desc && desc != null
  9084. && desc.type && desc.type != ''
  9085. && desc.sdp && desc.sdp != '';
  9086. };
  9087. SimulcastUtils.prototype._getVideoSources = function (lines) {
  9088. var i, inVideo = false, sb = [];
  9089. this.logger.info('Getting video sources...');
  9090. for (i = 0; i < lines.length; i++) {
  9091. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9092. // Out of video.
  9093. break;
  9094. }
  9095. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9096. // In video.
  9097. inVideo = true;
  9098. }
  9099. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9100. // In SSRC.
  9101. sb.push(lines[i]);
  9102. }
  9103. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9104. sb.push(lines[i]);
  9105. }
  9106. }
  9107. return sb;
  9108. };
  9109. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  9110. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  9111. ssrc_attribute, group, semantics, skip = true;
  9112. this.logger.info('Parsing media sources...');
  9113. for (i = 0; i < lines.length; i++) {
  9114. if (lines[i].substring(0, 'm='.length) === 'm=') {
  9115. type = lines[i]
  9116. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  9117. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  9118. if (!skip) {
  9119. cur_media = {
  9120. 'type': type,
  9121. 'sources': {},
  9122. 'groups': []
  9123. };
  9124. res.push(cur_media);
  9125. }
  9126. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9127. idx = lines[i].indexOf(' ');
  9128. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  9129. if (cur_media.sources[ssrc] === undefined) {
  9130. cur_ssrc = {'ssrc': ssrc};
  9131. cur_media.sources[ssrc] = cur_ssrc;
  9132. }
  9133. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  9134. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  9135. if (cur_media.base === undefined) {
  9136. cur_media.base = cur_ssrc;
  9137. }
  9138. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9139. idx = lines[i].indexOf(' ');
  9140. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  9141. ssrcs = lines[i].substr(idx).trim().split(' ');
  9142. group = {
  9143. 'semantics': semantics,
  9144. 'ssrcs': ssrcs
  9145. };
  9146. cur_media.groups.push(group);
  9147. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  9148. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  9149. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  9150. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  9151. cur_media.direction = lines[i].substring('a='.length);
  9152. }
  9153. }
  9154. return res;
  9155. };
  9156. /**
  9157. * The _indexOfArray() method returns the first a CompoundIndex at which a
  9158. * given element can be found in the array, or _emptyCompoundIndex if it is
  9159. * not present.
  9160. *
  9161. * Example:
  9162. *
  9163. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  9164. *
  9165. * returns {row: 2, column: 14}
  9166. *
  9167. * @param needle
  9168. * @param haystack
  9169. * @param start
  9170. * @returns {}
  9171. * @private
  9172. */
  9173. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  9174. var length = haystack.length, idx, i;
  9175. if (!start) {
  9176. start = 0;
  9177. }
  9178. for (i = start; i < length; i++) {
  9179. idx = haystack[i].indexOf(needle);
  9180. if (idx !== -1) {
  9181. return {row: i, column: idx};
  9182. }
  9183. }
  9184. return this._emptyCompoundIndex;
  9185. };
  9186. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  9187. var i;
  9188. for (i = lines.length - 1; i >= 0; i--) {
  9189. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  9190. lines.splice(i, 1);
  9191. }
  9192. }
  9193. };
  9194. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  9195. var sb = [], ssrc, addedSSRCs = [];
  9196. this.logger.info('Compiling video sources...');
  9197. // Add the groups
  9198. if (videoSources.groups && videoSources.groups.length !== 0) {
  9199. videoSources.groups.forEach(function (group) {
  9200. if (group.ssrcs && group.ssrcs.length !== 0) {
  9201. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  9202. // if (group.semantics !== 'SIM') {
  9203. group.ssrcs.forEach(function (ssrc) {
  9204. addedSSRCs.push(ssrc);
  9205. sb.splice.apply(sb, [sb.length, 0].concat([
  9206. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9207. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9208. });
  9209. //}
  9210. }
  9211. });
  9212. }
  9213. // Then add any free sources.
  9214. if (videoSources.sources) {
  9215. for (ssrc in videoSources.sources) {
  9216. if (addedSSRCs.indexOf(ssrc) === -1) {
  9217. sb.splice.apply(sb, [sb.length, 0].concat([
  9218. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9219. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9220. }
  9221. }
  9222. }
  9223. return sb;
  9224. };
  9225. module.exports = SimulcastUtils;
  9226. },{"./SimulcastLogger":39}],43:[function(require,module,exports){
  9227. /*jslint plusplus: true */
  9228. /*jslint nomen: true*/
  9229. var SimulcastSender = require("./SimulcastSender");
  9230. var NoSimulcastSender = SimulcastSender["no"];
  9231. var NativeSimulcastSender = SimulcastSender["native"];
  9232. var SimulcastReceiver = require("./SimulcastReceiver");
  9233. var SimulcastUtils = require("./SimulcastUtils");
  9234. var RTCEvents = require("../../service/RTC/RTCEvents");
  9235. /**
  9236. *
  9237. * @constructor
  9238. */
  9239. function SimulcastManager() {
  9240. // Create the simulcast utilities.
  9241. this.simulcastUtils = new SimulcastUtils();
  9242. // Create remote simulcast.
  9243. this.simulcastReceiver = new SimulcastReceiver();
  9244. // Initialize local simulcast.
  9245. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  9246. // account constraints.
  9247. if (!config.enableSimulcast) {
  9248. this.simulcastSender = new NoSimulcastSender();
  9249. } else {
  9250. var isChromium = window.chrome,
  9251. vendorName = window.navigator.vendor;
  9252. if(isChromium !== null && isChromium !== undefined
  9253. /* skip opera */
  9254. && vendorName === "Google Inc."
  9255. /* skip Chromium as suggested by fippo */
  9256. && !window.navigator.appVersion.match(/Chromium\//) ) {
  9257. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  9258. if (ver > 37) {
  9259. this.simulcastSender = new NativeSimulcastSender();
  9260. } else {
  9261. this.simulcastSender = new NoSimulcastSender();
  9262. }
  9263. } else {
  9264. this.simulcastSender = new NoSimulcastSender();
  9265. }
  9266. }
  9267. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  9268. function (endpointSimulcastLayers) {
  9269. endpointSimulcastLayers.forEach(function (esl) {
  9270. var ssrc = esl.simulcastLayer.primarySSRC;
  9271. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  9272. });
  9273. });
  9274. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  9275. var ssrc = simulcastLayer.primarySSRC;
  9276. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  9277. });
  9278. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  9279. var ssrc = simulcastLayer.primarySSRC;
  9280. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  9281. });
  9282. }
  9283. /**
  9284. * Restores the simulcast groups of the remote description. In
  9285. * transformRemoteDescription we remove those in order for the set remote
  9286. * description to succeed. The focus needs the signal the groups to new
  9287. * participants.
  9288. *
  9289. * @param desc
  9290. * @returns {*}
  9291. */
  9292. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  9293. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  9294. };
  9295. /**
  9296. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9297. * either gets confused and thinks this is an FID group or, if an FID group
  9298. * is already present, it fails to set the remote description.
  9299. *
  9300. * @param desc
  9301. * @returns {*}
  9302. */
  9303. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  9304. return this.simulcastReceiver.transformRemoteDescription(desc);
  9305. };
  9306. /**
  9307. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9308. * SSRC.
  9309. *
  9310. * @param ssrc
  9311. * @returns {*}
  9312. */
  9313. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9314. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  9315. };
  9316. /**
  9317. * Returns a stream with single video track, the one currently being
  9318. * received by this endpoint.
  9319. *
  9320. * @param stream the remote simulcast stream.
  9321. * @returns {webkitMediaStream}
  9322. */
  9323. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  9324. return this.simulcastReceiver.getReceivingVideoStream(stream);
  9325. };
  9326. /**
  9327. *
  9328. *
  9329. * @param desc
  9330. * @returns {*}
  9331. */
  9332. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  9333. return this.simulcastSender.transformLocalDescription(desc);
  9334. };
  9335. /**
  9336. *
  9337. * @returns {*}
  9338. */
  9339. SimulcastManager.prototype.getLocalVideoStream = function() {
  9340. return this.simulcastSender.getLocalVideoStream();
  9341. };
  9342. /**
  9343. * GUM for simulcast.
  9344. *
  9345. * @param constraints
  9346. * @param success
  9347. * @param err
  9348. */
  9349. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  9350. this.simulcastSender.getUserMedia(constraints, success, err);
  9351. };
  9352. /**
  9353. * Prepares the local description for public usage (i.e. to be signaled
  9354. * through Jingle to the focus).
  9355. *
  9356. * @param desc
  9357. * @returns {RTCSessionDescription}
  9358. */
  9359. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  9360. return this.simulcastSender.reverseTransformLocalDescription(desc);
  9361. };
  9362. /**
  9363. * Ensures that the simulcast group is present in the answer, _if_ native
  9364. * simulcast is enabled,
  9365. *
  9366. * @param desc
  9367. * @returns {*}
  9368. */
  9369. SimulcastManager.prototype.transformAnswer = function (desc) {
  9370. return this.simulcastSender.transformAnswer(desc);
  9371. };
  9372. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  9373. return this.simulcastReceiver.getReceivingSSRC(jid);
  9374. };
  9375. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  9376. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  9377. };
  9378. /**
  9379. *
  9380. * @param lines
  9381. * @param mediatypes
  9382. * @returns {*}
  9383. */
  9384. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  9385. var sb = lines.sdp.split('\r\n');
  9386. return this.simulcastUtils.parseMedia(sb, mediatypes);
  9387. };
  9388. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  9389. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  9390. };
  9391. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  9392. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  9393. };
  9394. SimulcastManager.prototype.resetSender = function() {
  9395. if (typeof this.simulcastSender.reset === 'function'){
  9396. this.simulcastSender.reset();
  9397. }
  9398. };
  9399. var simulcast = new SimulcastManager();
  9400. module.exports = simulcast;
  9401. },{"../../service/RTC/RTCEvents":81,"./SimulcastReceiver":40,"./SimulcastSender":41,"./SimulcastUtils":42}],44:[function(require,module,exports){
  9402. /**
  9403. * Provides statistics for the local stream.
  9404. */
  9405. /**
  9406. * Size of the webaudio analizer buffer.
  9407. * @type {number}
  9408. */
  9409. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  9410. /**
  9411. * Value of the webaudio analizer smoothing time parameter.
  9412. * @type {number}
  9413. */
  9414. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  9415. /**
  9416. * Converts time domain data array to audio level.
  9417. * @param array the time domain data array.
  9418. * @returns {number} the audio level
  9419. */
  9420. function timeDomainDataToAudioLevel(samples) {
  9421. var maxVolume = 0;
  9422. var length = samples.length;
  9423. for (var i = 0; i < length; i++) {
  9424. if (maxVolume < samples[i])
  9425. maxVolume = samples[i];
  9426. }
  9427. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  9428. };
  9429. /**
  9430. * Animates audio level change
  9431. * @param newLevel the new audio level
  9432. * @param lastLevel the last audio level
  9433. * @returns {Number} the audio level to be set
  9434. */
  9435. function animateLevel(newLevel, lastLevel)
  9436. {
  9437. var value = 0;
  9438. var diff = lastLevel - newLevel;
  9439. if(diff > 0.2)
  9440. {
  9441. value = lastLevel - 0.2;
  9442. }
  9443. else if(diff < -0.4)
  9444. {
  9445. value = lastLevel + 0.4;
  9446. }
  9447. else
  9448. {
  9449. value = newLevel;
  9450. }
  9451. return parseFloat(value.toFixed(3));
  9452. }
  9453. /**
  9454. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  9455. *
  9456. * @param stream the local stream
  9457. * @param interval stats refresh interval given in ms.
  9458. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  9459. * update.
  9460. * @constructor
  9461. */
  9462. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  9463. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  9464. this.stream = stream;
  9465. this.intervalId = null;
  9466. this.intervalMilis = interval;
  9467. this.eventEmitter = eventEmitter;
  9468. this.audioLevel = 0;
  9469. this.statisticsService = statisticsService;
  9470. }
  9471. /**
  9472. * Starts the collecting the statistics.
  9473. */
  9474. LocalStatsCollector.prototype.start = function () {
  9475. if (config.disableAudioLevels || !window.AudioContext)
  9476. return;
  9477. var context = new AudioContext();
  9478. var analyser = context.createAnalyser();
  9479. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  9480. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  9481. var source = context.createMediaStreamSource(this.stream);
  9482. source.connect(analyser);
  9483. var self = this;
  9484. this.intervalId = setInterval(
  9485. function () {
  9486. var array = new Uint8Array(analyser.frequencyBinCount);
  9487. analyser.getByteTimeDomainData(array);
  9488. var audioLevel = timeDomainDataToAudioLevel(array);
  9489. if(audioLevel != self.audioLevel) {
  9490. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  9491. self.eventEmitter.emit(
  9492. "statistics.audioLevel",
  9493. self.statisticsService.LOCAL_JID,
  9494. self.audioLevel);
  9495. }
  9496. },
  9497. this.intervalMilis
  9498. );
  9499. };
  9500. /**
  9501. * Stops collecting the statistics.
  9502. */
  9503. LocalStatsCollector.prototype.stop = function () {
  9504. if (this.intervalId) {
  9505. clearInterval(this.intervalId);
  9506. this.intervalId = null;
  9507. }
  9508. };
  9509. module.exports = LocalStatsCollector;
  9510. },{}],45:[function(require,module,exports){
  9511. /* global ssrc2jid */
  9512. /* jshint -W117 */
  9513. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9514. /**
  9515. * Calculates packet lost percent using the number of lost packets and the
  9516. * number of all packet.
  9517. * @param lostPackets the number of lost packets
  9518. * @param totalPackets the number of all packets.
  9519. * @returns {number} packet loss percent
  9520. */
  9521. function calculatePacketLoss(lostPackets, totalPackets) {
  9522. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  9523. return 0;
  9524. return Math.round((lostPackets/totalPackets)*100);
  9525. }
  9526. function getStatValue(item, name) {
  9527. if(!keyMap[APP.RTC.getBrowserType()][name])
  9528. throw "The property isn't supported!";
  9529. var key = keyMap[APP.RTC.getBrowserType()][name];
  9530. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  9531. }
  9532. /**
  9533. * Peer statistics data holder.
  9534. * @constructor
  9535. */
  9536. function PeerStats()
  9537. {
  9538. this.ssrc2Loss = {};
  9539. this.ssrc2AudioLevel = {};
  9540. this.ssrc2bitrate = {};
  9541. this.ssrc2resolution = {};
  9542. }
  9543. /**
  9544. * The bandwidth
  9545. * @type {{}}
  9546. */
  9547. PeerStats.bandwidth = {};
  9548. /**
  9549. * The bit rate
  9550. * @type {{}}
  9551. */
  9552. PeerStats.bitrate = {};
  9553. /**
  9554. * The packet loss rate
  9555. * @type {{}}
  9556. */
  9557. PeerStats.packetLoss = null;
  9558. /**
  9559. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  9560. * represented by this instance.
  9561. * @param ssrc audio or video RTP stream SSRC.
  9562. * @param lossRate new packet loss rate value to be set.
  9563. */
  9564. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  9565. {
  9566. this.ssrc2Loss[ssrc] = lossRate;
  9567. };
  9568. /**
  9569. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  9570. * represented by this instance.
  9571. * @param ssrc audio or video RTP stream SSRC.
  9572. * @param resolution new resolution value to be set.
  9573. */
  9574. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  9575. {
  9576. if(resolution === null && this.ssrc2resolution[ssrc])
  9577. {
  9578. delete this.ssrc2resolution[ssrc];
  9579. }
  9580. else if(resolution !== null)
  9581. this.ssrc2resolution[ssrc] = resolution;
  9582. };
  9583. /**
  9584. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  9585. * represented by this instance.
  9586. * @param ssrc audio or video RTP stream SSRC.
  9587. * @param bitrate new bitrate value to be set.
  9588. */
  9589. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  9590. {
  9591. if(this.ssrc2bitrate[ssrc])
  9592. {
  9593. this.ssrc2bitrate[ssrc].download += bitrate.download;
  9594. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  9595. }
  9596. else {
  9597. this.ssrc2bitrate[ssrc] = bitrate;
  9598. }
  9599. };
  9600. /**
  9601. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  9602. * the stream which belongs to the peer represented by this instance.
  9603. * @param ssrc RTP stream SSRC for which current audio level value will be
  9604. * updated.
  9605. * @param audioLevel the new audio level value to be set. Value is truncated to
  9606. * fit the range from 0 to 1.
  9607. */
  9608. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  9609. {
  9610. // Range limit 0 - 1
  9611. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  9612. };
  9613. function formatAudioLevel(audioLevel) {
  9614. return Math.min(Math.max(audioLevel, 0), 1);
  9615. }
  9616. /**
  9617. * Array with the transport information.
  9618. * @type {Array}
  9619. */
  9620. PeerStats.transport = [];
  9621. /**
  9622. * <tt>StatsCollector</tt> registers for stats updates of given
  9623. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  9624. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  9625. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9626. * instance as an event source.
  9627. *
  9628. * @param peerconnection webRTC peer connection object.
  9629. * @param interval stats refresh interval given in ms.
  9630. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  9631. * called on stats update.
  9632. * @constructor
  9633. */
  9634. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  9635. {
  9636. this.peerconnection = peerconnection;
  9637. this.baselineAudioLevelsReport = null;
  9638. this.currentAudioLevelsReport = null;
  9639. this.currentStatsReport = null;
  9640. this.baselineStatsReport = null;
  9641. this.audioLevelsIntervalId = null;
  9642. this.eventEmitter = eventEmitter;
  9643. /**
  9644. * Gather PeerConnection stats once every this many milliseconds.
  9645. */
  9646. this.GATHER_INTERVAL = 10000;
  9647. /**
  9648. * Log stats via the focus once every this many milliseconds.
  9649. */
  9650. this.LOG_INTERVAL = 60000;
  9651. /**
  9652. * Gather stats and store them in this.statsToBeLogged.
  9653. */
  9654. this.gatherStatsIntervalId = null;
  9655. /**
  9656. * Send the stats already saved in this.statsToBeLogged to be logged via
  9657. * the focus.
  9658. */
  9659. this.logStatsIntervalId = null;
  9660. /**
  9661. * Stores the statistics which will be send to the focus to be logged.
  9662. */
  9663. this.statsToBeLogged =
  9664. {
  9665. timestamps: [],
  9666. stats: {}
  9667. };
  9668. // Updates stats interval
  9669. this.audioLevelsIntervalMilis = audioLevelsInterval;
  9670. this.statsIntervalId = null;
  9671. this.statsIntervalMilis = statsInterval;
  9672. // Map of jids to PeerStats
  9673. this.jid2stats = {};
  9674. }
  9675. module.exports = StatsCollector;
  9676. /**
  9677. * Stops stats updates.
  9678. */
  9679. StatsCollector.prototype.stop = function () {
  9680. if (this.audioLevelsIntervalId) {
  9681. clearInterval(this.audioLevelsIntervalId);
  9682. this.audioLevelsIntervalId = null;
  9683. }
  9684. if (this.statsIntervalId)
  9685. {
  9686. clearInterval(this.statsIntervalId);
  9687. this.statsIntervalId = null;
  9688. }
  9689. if(this.logStatsIntervalId)
  9690. {
  9691. clearInterval(this.logStatsIntervalId);
  9692. this.logStatsIntervalId = null;
  9693. }
  9694. if(this.gatherStatsIntervalId)
  9695. {
  9696. clearInterval(this.gatherStatsIntervalId);
  9697. this.gatherStatsIntervalId = null;
  9698. }
  9699. };
  9700. /**
  9701. * Callback passed to <tt>getStats</tt> method.
  9702. * @param error an error that occurred on <tt>getStats</tt> call.
  9703. */
  9704. StatsCollector.prototype.errorCallback = function (error)
  9705. {
  9706. console.error("Get stats error", error);
  9707. this.stop();
  9708. };
  9709. /**
  9710. * Starts stats updates.
  9711. */
  9712. StatsCollector.prototype.start = function ()
  9713. {
  9714. var self = this;
  9715. if(!config.disableAudioLevels) {
  9716. console.debug("set audio levels interval");
  9717. this.audioLevelsIntervalId = setInterval(
  9718. function () {
  9719. // Interval updates
  9720. self.peerconnection.getStats(
  9721. function (report) {
  9722. var results = null;
  9723. if (!report || !report.result ||
  9724. typeof report.result != 'function') {
  9725. results = report;
  9726. }
  9727. else {
  9728. results = report.result();
  9729. }
  9730. //console.error("Got interval report", results);
  9731. self.currentAudioLevelsReport = results;
  9732. self.processAudioLevelReport();
  9733. self.baselineAudioLevelsReport =
  9734. self.currentAudioLevelsReport;
  9735. },
  9736. self.errorCallback
  9737. );
  9738. },
  9739. self.audioLevelsIntervalMilis
  9740. );
  9741. }
  9742. if(!config.disableStats) {
  9743. console.debug("set stats interval");
  9744. this.statsIntervalId = setInterval(
  9745. function () {
  9746. // Interval updates
  9747. self.peerconnection.getStats(
  9748. function (report) {
  9749. var results = null;
  9750. if (!report || !report.result ||
  9751. typeof report.result != 'function') {
  9752. //firefox
  9753. results = report;
  9754. }
  9755. else {
  9756. //chrome
  9757. results = report.result();
  9758. }
  9759. //console.error("Got interval report", results);
  9760. self.currentStatsReport = results;
  9761. try {
  9762. self.processStatsReport();
  9763. }
  9764. catch (e) {
  9765. console.error("Unsupported key:" + e, e);
  9766. }
  9767. self.baselineStatsReport = self.currentStatsReport;
  9768. },
  9769. self.errorCallback
  9770. );
  9771. },
  9772. self.statsIntervalMilis
  9773. );
  9774. }
  9775. if (config.logStats) {
  9776. this.gatherStatsIntervalId = setInterval(
  9777. function () {
  9778. self.peerconnection.getStats(
  9779. function (report) {
  9780. self.addStatsToBeLogged(report.result());
  9781. },
  9782. function () {
  9783. }
  9784. );
  9785. },
  9786. this.GATHER_INTERVAL
  9787. );
  9788. this.logStatsIntervalId = setInterval(
  9789. function() { self.logStats(); },
  9790. this.LOG_INTERVAL);
  9791. }
  9792. };
  9793. /**
  9794. * Converts the stats to the format used for logging, and saves the data in
  9795. * this.statsToBeLogged.
  9796. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  9797. */
  9798. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  9799. var self = this;
  9800. var num_records = this.statsToBeLogged.timestamps.length;
  9801. this.statsToBeLogged.timestamps.push(new Date().getTime());
  9802. reports.map(function (report) {
  9803. var stat = self.statsToBeLogged.stats[report.id];
  9804. if (!stat) {
  9805. stat = self.statsToBeLogged.stats[report.id] = {};
  9806. }
  9807. stat.type = report.type;
  9808. report.names().map(function (name) {
  9809. var values = stat[name];
  9810. if (!values) {
  9811. values = stat[name] = [];
  9812. }
  9813. while (values.length < num_records) {
  9814. values.push(null);
  9815. }
  9816. values.push(report.stat(name));
  9817. });
  9818. });
  9819. };
  9820. StatsCollector.prototype.logStats = function () {
  9821. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  9822. return;
  9823. // Reset the stats
  9824. this.statsToBeLogged.stats = {};
  9825. this.statsToBeLogged.timestamps = [];
  9826. };
  9827. var keyMap = {};
  9828. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  9829. "ssrc": "ssrc",
  9830. "packetsReceived": "packetsReceived",
  9831. "packetsLost": "packetsLost",
  9832. "packetsSent": "packetsSent",
  9833. "bytesReceived": "bytesReceived",
  9834. "bytesSent": "bytesSent"
  9835. };
  9836. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  9837. "receiveBandwidth": "googAvailableReceiveBandwidth",
  9838. "sendBandwidth": "googAvailableSendBandwidth",
  9839. "remoteAddress": "googRemoteAddress",
  9840. "transportType": "googTransportType",
  9841. "localAddress": "googLocalAddress",
  9842. "activeConnection": "googActiveConnection",
  9843. "ssrc": "ssrc",
  9844. "packetsReceived": "packetsReceived",
  9845. "packetsSent": "packetsSent",
  9846. "packetsLost": "packetsLost",
  9847. "bytesReceived": "bytesReceived",
  9848. "bytesSent": "bytesSent",
  9849. "googFrameHeightReceived": "googFrameHeightReceived",
  9850. "googFrameWidthReceived": "googFrameWidthReceived",
  9851. "googFrameHeightSent": "googFrameHeightSent",
  9852. "googFrameWidthSent": "googFrameWidthSent",
  9853. "audioInputLevel": "audioInputLevel",
  9854. "audioOutputLevel": "audioOutputLevel"
  9855. };
  9856. /**
  9857. * Stats processing logic.
  9858. */
  9859. StatsCollector.prototype.processStatsReport = function () {
  9860. if (!this.baselineStatsReport) {
  9861. return;
  9862. }
  9863. for (var idx in this.currentStatsReport) {
  9864. var now = this.currentStatsReport[idx];
  9865. try {
  9866. if (getStatValue(now, 'receiveBandwidth') ||
  9867. getStatValue(now, 'sendBandwidth')) {
  9868. PeerStats.bandwidth = {
  9869. "download": Math.round(
  9870. (getStatValue(now, 'receiveBandwidth')) / 1000),
  9871. "upload": Math.round(
  9872. (getStatValue(now, 'sendBandwidth')) / 1000)
  9873. };
  9874. }
  9875. }
  9876. catch(e){/*not supported*/}
  9877. if(now.type == 'googCandidatePair')
  9878. {
  9879. var ip, type, localIP, active;
  9880. try {
  9881. ip = getStatValue(now, 'remoteAddress');
  9882. type = getStatValue(now, "transportType");
  9883. localIP = getStatValue(now, "localAddress");
  9884. active = getStatValue(now, "activeConnection");
  9885. }
  9886. catch(e){/*not supported*/}
  9887. if(!ip || !type || !localIP || active != "true")
  9888. continue;
  9889. var addressSaved = false;
  9890. for(var i = 0; i < PeerStats.transport.length; i++)
  9891. {
  9892. if(PeerStats.transport[i].ip == ip &&
  9893. PeerStats.transport[i].type == type &&
  9894. PeerStats.transport[i].localip == localIP)
  9895. {
  9896. addressSaved = true;
  9897. }
  9898. }
  9899. if(addressSaved)
  9900. continue;
  9901. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  9902. continue;
  9903. }
  9904. if(now.type == "candidatepair")
  9905. {
  9906. if(now.state == "succeeded")
  9907. continue;
  9908. var local = this.currentStatsReport[now.localCandidateId];
  9909. var remote = this.currentStatsReport[now.remoteCandidateId];
  9910. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  9911. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  9912. }
  9913. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  9914. now.type != "inboundrtp") {
  9915. continue;
  9916. }
  9917. var before = this.baselineStatsReport[idx];
  9918. if (!before) {
  9919. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9920. continue;
  9921. }
  9922. var ssrc = getStatValue(now, 'ssrc');
  9923. if(!ssrc)
  9924. continue;
  9925. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9926. if (!jid && (Date.now() - now.timestamp) < 3000) {
  9927. console.warn("No jid for ssrc: " + ssrc);
  9928. continue;
  9929. }
  9930. var jidStats = this.jid2stats[jid];
  9931. if (!jidStats) {
  9932. jidStats = new PeerStats();
  9933. this.jid2stats[jid] = jidStats;
  9934. }
  9935. var isDownloadStream = true;
  9936. var key = 'packetsReceived';
  9937. if (!getStatValue(now, key))
  9938. {
  9939. isDownloadStream = false;
  9940. key = 'packetsSent';
  9941. if (!getStatValue(now, key))
  9942. {
  9943. console.warn("No packetsReceived nor packetSent stat found");
  9944. continue;
  9945. }
  9946. }
  9947. var packetsNow = getStatValue(now, key);
  9948. if(!packetsNow || packetsNow < 0)
  9949. packetsNow = 0;
  9950. var packetsBefore = getStatValue(before, key);
  9951. if(!packetsBefore || packetsBefore < 0)
  9952. packetsBefore = 0;
  9953. var packetRate = packetsNow - packetsBefore;
  9954. if(!packetRate || packetRate < 0)
  9955. packetRate = 0;
  9956. var currentLoss = getStatValue(now, 'packetsLost');
  9957. if(!currentLoss || currentLoss < 0)
  9958. currentLoss = 0;
  9959. var previousLoss = getStatValue(before, 'packetsLost');
  9960. if(!previousLoss || previousLoss < 0)
  9961. previousLoss = 0;
  9962. var lossRate = currentLoss - previousLoss;
  9963. if(!lossRate || lossRate < 0)
  9964. lossRate = 0;
  9965. var packetsTotal = (packetRate + lossRate);
  9966. jidStats.setSsrcLoss(ssrc,
  9967. {"packetsTotal": packetsTotal,
  9968. "packetsLost": lossRate,
  9969. "isDownloadStream": isDownloadStream});
  9970. var bytesReceived = 0, bytesSent = 0;
  9971. if(getStatValue(now, "bytesReceived"))
  9972. {
  9973. bytesReceived = getStatValue(now, "bytesReceived") -
  9974. getStatValue(before, "bytesReceived");
  9975. }
  9976. if(getStatValue(now, "bytesSent"))
  9977. {
  9978. bytesSent = getStatValue(now, "bytesSent") -
  9979. getStatValue(before, "bytesSent");
  9980. }
  9981. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  9982. if(bytesReceived <= 0 || time <= 0)
  9983. {
  9984. bytesReceived = 0;
  9985. }
  9986. else
  9987. {
  9988. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  9989. }
  9990. if(bytesSent <= 0 || time <= 0)
  9991. {
  9992. bytesSent = 0;
  9993. }
  9994. else
  9995. {
  9996. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  9997. }
  9998. jidStats.setSsrcBitrate(ssrc, {
  9999. "download": bytesReceived,
  10000. "upload": bytesSent});
  10001. var resolution = {height: null, width: null};
  10002. try {
  10003. if (getStatValue(now, "googFrameHeightReceived") &&
  10004. getStatValue(now, "googFrameWidthReceived")) {
  10005. resolution.height = getStatValue(now, "googFrameHeightReceived");
  10006. resolution.width = getStatValue(now, "googFrameWidthReceived");
  10007. }
  10008. else if (getStatValue(now, "googFrameHeightSent") &&
  10009. getStatValue(now, "googFrameWidthSent")) {
  10010. resolution.height = getStatValue(now, "googFrameHeightSent");
  10011. resolution.width = getStatValue(now, "googFrameWidthSent");
  10012. }
  10013. }
  10014. catch(e){/*not supported*/}
  10015. if(resolution.height && resolution.width)
  10016. {
  10017. jidStats.setSsrcResolution(ssrc, resolution);
  10018. }
  10019. else
  10020. {
  10021. jidStats.setSsrcResolution(ssrc, null);
  10022. }
  10023. }
  10024. var self = this;
  10025. // Jid stats
  10026. var totalPackets = {download: 0, upload: 0};
  10027. var lostPackets = {download: 0, upload: 0};
  10028. var bitrateDownload = 0;
  10029. var bitrateUpload = 0;
  10030. var resolutions = {};
  10031. Object.keys(this.jid2stats).forEach(
  10032. function (jid)
  10033. {
  10034. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  10035. function (ssrc)
  10036. {
  10037. var type = "upload";
  10038. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  10039. type = "download";
  10040. totalPackets[type] +=
  10041. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  10042. lostPackets[type] +=
  10043. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  10044. }
  10045. );
  10046. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  10047. function (ssrc) {
  10048. bitrateDownload +=
  10049. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  10050. bitrateUpload +=
  10051. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  10052. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  10053. }
  10054. );
  10055. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  10056. }
  10057. );
  10058. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  10059. PeerStats.packetLoss = {
  10060. total:
  10061. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  10062. totalPackets.download + totalPackets.upload),
  10063. download:
  10064. calculatePacketLoss(lostPackets.download, totalPackets.download),
  10065. upload:
  10066. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  10067. };
  10068. this.eventEmitter.emit("statistics.connectionstats",
  10069. {
  10070. "bitrate": PeerStats.bitrate,
  10071. "packetLoss": PeerStats.packetLoss,
  10072. "bandwidth": PeerStats.bandwidth,
  10073. "resolution": resolutions,
  10074. "transport": PeerStats.transport
  10075. });
  10076. PeerStats.transport = [];
  10077. };
  10078. /**
  10079. * Stats processing logic.
  10080. */
  10081. StatsCollector.prototype.processAudioLevelReport = function ()
  10082. {
  10083. if (!this.baselineAudioLevelsReport)
  10084. {
  10085. return;
  10086. }
  10087. for (var idx in this.currentAudioLevelsReport)
  10088. {
  10089. var now = this.currentAudioLevelsReport[idx];
  10090. if (now.type != 'ssrc')
  10091. {
  10092. continue;
  10093. }
  10094. var before = this.baselineAudioLevelsReport[idx];
  10095. if (!before)
  10096. {
  10097. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10098. continue;
  10099. }
  10100. var ssrc = getStatValue(now, 'ssrc');
  10101. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10102. if (!jid && (Date.now() - now.timestamp) < 3000)
  10103. {
  10104. console.warn("No jid for ssrc: " + ssrc);
  10105. continue;
  10106. }
  10107. var jidStats = this.jid2stats[jid];
  10108. if (!jidStats)
  10109. {
  10110. jidStats = new PeerStats();
  10111. this.jid2stats[jid] = jidStats;
  10112. }
  10113. // Audio level
  10114. var audioLevel = null;
  10115. try {
  10116. audioLevel = getStatValue(now, 'audioInputLevel');
  10117. if (!audioLevel)
  10118. audioLevel = getStatValue(now, 'audioOutputLevel');
  10119. }
  10120. catch(e) {/*not supported*/
  10121. console.warn("Audio Levels are not available in the statistics.");
  10122. clearInterval(this.audioLevelsIntervalId);
  10123. return;
  10124. }
  10125. if (audioLevel)
  10126. {
  10127. // TODO: can't find specs about what this value really is,
  10128. // but it seems to vary between 0 and around 32k.
  10129. audioLevel = formatAudioLevel(audioLevel / 32767);
  10130. var oldLevel = jidStats.ssrc2AudioLevel[ssrc];
  10131. if(jid != APP.xmpp.myJid() && (!oldLevel || oldLevel != audioLevel))
  10132. {
  10133. jidStats.ssrc2AudioLevel[ssrc] = audioLevel;
  10134. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  10135. }
  10136. }
  10137. }
  10138. };
  10139. },{"../../service/RTC/RTCBrowserType":80}],46:[function(require,module,exports){
  10140. /**
  10141. * Created by hristo on 8/4/14.
  10142. */
  10143. var LocalStats = require("./LocalStatsCollector.js");
  10144. var RTPStats = require("./RTPStatsCollector.js");
  10145. var EventEmitter = require("events");
  10146. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  10147. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10148. var eventEmitter = new EventEmitter();
  10149. var localStats = null;
  10150. var rtpStats = null;
  10151. function stopLocal()
  10152. {
  10153. if(localStats)
  10154. {
  10155. localStats.stop();
  10156. localStats = null;
  10157. }
  10158. }
  10159. function stopRemote()
  10160. {
  10161. if(rtpStats)
  10162. {
  10163. rtpStats.stop();
  10164. eventEmitter.emit("statistics.stop");
  10165. rtpStats = null;
  10166. }
  10167. }
  10168. function startRemoteStats (peerconnection) {
  10169. if(rtpStats)
  10170. {
  10171. rtpStats.stop();
  10172. rtpStats = null;
  10173. }
  10174. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  10175. rtpStats.start();
  10176. }
  10177. function onStreamCreated(stream)
  10178. {
  10179. if(stream.getOriginalStream().getAudioTracks().length === 0)
  10180. return;
  10181. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  10182. eventEmitter);
  10183. localStats.start();
  10184. }
  10185. function onDisposeConference(onUnload) {
  10186. stopRemote();
  10187. if(onUnload) {
  10188. stopLocal();
  10189. eventEmitter.removeAllListeners();
  10190. }
  10191. }
  10192. var statistics =
  10193. {
  10194. /**
  10195. * Indicates that this audio level is for local jid.
  10196. * @type {string}
  10197. */
  10198. LOCAL_JID: 'local',
  10199. addAudioLevelListener: function(listener)
  10200. {
  10201. eventEmitter.on("statistics.audioLevel", listener);
  10202. },
  10203. removeAudioLevelListener: function(listener)
  10204. {
  10205. eventEmitter.removeListener("statistics.audioLevel", listener);
  10206. },
  10207. addConnectionStatsListener: function(listener)
  10208. {
  10209. eventEmitter.on("statistics.connectionstats", listener);
  10210. },
  10211. removeConnectionStatsListener: function(listener)
  10212. {
  10213. eventEmitter.removeListener("statistics.connectionstats", listener);
  10214. },
  10215. addRemoteStatsStopListener: function(listener)
  10216. {
  10217. eventEmitter.on("statistics.stop", listener);
  10218. },
  10219. removeRemoteStatsStopListener: function(listener)
  10220. {
  10221. eventEmitter.removeListener("statistics.stop", listener);
  10222. },
  10223. stop: function () {
  10224. stopLocal();
  10225. stopRemote();
  10226. if(eventEmitter)
  10227. {
  10228. eventEmitter.removeAllListeners();
  10229. }
  10230. },
  10231. stopRemoteStatistics: function()
  10232. {
  10233. stopRemote();
  10234. },
  10235. start: function () {
  10236. APP.RTC.addStreamListener(onStreamCreated,
  10237. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10238. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10239. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10240. startRemoteStats(event.peerconnection);
  10241. });
  10242. }
  10243. };
  10244. module.exports = statistics;
  10245. },{"../../service/RTC/StreamEventTypes.js":83,"../../service/xmpp/XMPPEvents":89,"./LocalStatsCollector.js":44,"./RTPStatsCollector.js":45,"events":1}],47:[function(require,module,exports){
  10246. var i18n = require("i18next-client");
  10247. var languages = require("../../service/translation/languages");
  10248. var DEFAULT_LANG = languages.EN;
  10249. var initialized = false;
  10250. var waitingForInit = [];
  10251. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10252. return value.replace("__app__", interfaceConfig.APP_NAME);
  10253. });
  10254. var defaultOptions = {
  10255. detectLngQS: "lang",
  10256. useCookie: false,
  10257. fallbackLng: DEFAULT_LANG,
  10258. shortcutFunction: 'defaultValue',
  10259. load: "unspecific",
  10260. resGetPath: 'lang/__ns__-__lng__.json',
  10261. ns: {
  10262. namespaces: ['main', 'languages'],
  10263. defaultNs: 'main'
  10264. },
  10265. lngWhitelist : languages.getLanguages(),
  10266. fallbackOnNull: true,
  10267. useDataAttrOptions: true,
  10268. app: interfaceConfig.APP_NAME,
  10269. getAsync: true,
  10270. customLoad: function(lng, ns, options, done) {
  10271. var resPath = "lang/__ns__-__lng__.json";
  10272. if(lng === languages.EN)
  10273. resPath = "lang/__ns__.json";
  10274. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10275. initialized = false;
  10276. i18n.functions.ajax({
  10277. url: url,
  10278. success: function(data, status, xhr) {
  10279. i18n.functions.log('loaded: ' + url);
  10280. done(null, data);
  10281. },
  10282. error : function(xhr, status, error) {
  10283. if ((status && status == 200) ||
  10284. (xhr && xhr.status && xhr.status == 200)) {
  10285. // file loaded but invalid json, stop waste time !
  10286. i18n.functions.error('There is a typo in: ' + url);
  10287. } else if ((status && status == 404) ||
  10288. (xhr && xhr.status && xhr.status == 404)) {
  10289. i18n.functions.log('Does not exist: ' + url);
  10290. } else {
  10291. var theStatus = status ? status :
  10292. ((xhr && xhr.status) ? xhr.status : null);
  10293. i18n.functions.log(theStatus + ' when loading ' + url);
  10294. }
  10295. done(error, {});
  10296. },
  10297. dataType: "json",
  10298. async : options.getAsync
  10299. });
  10300. }
  10301. // options for caching
  10302. // useLocalStorage: true,
  10303. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10304. };
  10305. function initCompleted(t)
  10306. {
  10307. initialized = true;
  10308. $("[data-i18n]").i18n();
  10309. for(var i = 0; i < waitingForInit.length; i++)
  10310. {
  10311. var obj = waitingForInit[i];
  10312. obj.callback(i18n.t(obj.key));
  10313. }
  10314. waitingForInit = [];
  10315. }
  10316. module.exports = {
  10317. init: function (lang) {
  10318. initialized = false;
  10319. var options = defaultOptions;
  10320. if(lang)
  10321. options.lng = lang;
  10322. i18n.init(options, initCompleted);
  10323. },
  10324. translateString: function (key, cb, options) {
  10325. if(!cb)
  10326. return i18n.t(key, options);
  10327. if(initialized)
  10328. {
  10329. cb(i18n.t(key, options));
  10330. }
  10331. else
  10332. {
  10333. waitingForInit.push({"callback": cb, "key": key});
  10334. }
  10335. },
  10336. setLanguage: function (lang) {
  10337. initialized = false;
  10338. if(!lang)
  10339. lang = DEFAULT_LANG;
  10340. i18n.setLng(lang, defaultOptions, initCompleted);
  10341. },
  10342. getCurrentLanguage: function () {
  10343. return i18n.lng();
  10344. },
  10345. translateElement: function (selector) {
  10346. selector.i18n();
  10347. },
  10348. generateTranslatonHTML: function (key, defaultString, options) {
  10349. var str = "<span data-i18n=\"" + key + "\"";
  10350. if(options)
  10351. {
  10352. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10353. }
  10354. str += ">";
  10355. if(!options)
  10356. options = {};
  10357. if(defaultString)
  10358. {
  10359. options.defaultValue = defaultString;
  10360. }
  10361. str += this.translateString(key, null, options);
  10362. str += "</span>";
  10363. return str;
  10364. }
  10365. };
  10366. },{"../../service/translation/languages":88,"i18next-client":62}],48:[function(require,module,exports){
  10367. /* jshint -W117 */
  10368. var TraceablePeerConnection = require("./TraceablePeerConnection");
  10369. var SDPDiffer = require("./SDPDiffer");
  10370. var SDPUtil = require("./SDPUtil");
  10371. var SDP = require("./SDP");
  10372. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10373. // Jingle stuff
  10374. function JingleSession(me, sid, connection, service) {
  10375. this.me = me;
  10376. this.sid = sid;
  10377. this.connection = connection;
  10378. this.initiator = null;
  10379. this.responder = null;
  10380. this.isInitiator = null;
  10381. this.peerjid = null;
  10382. this.state = null;
  10383. this.localSDP = null;
  10384. this.remoteSDP = null;
  10385. this.relayedStreams = [];
  10386. this.startTime = null;
  10387. this.stopTime = null;
  10388. this.media_constraints = null;
  10389. this.pc_constraints = null;
  10390. this.ice_config = {};
  10391. this.drip_container = [];
  10392. this.service = service;
  10393. this.usetrickle = true;
  10394. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  10395. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  10396. this.hadstuncandidate = false;
  10397. this.hadturncandidate = false;
  10398. this.lasticecandidate = false;
  10399. this.statsinterval = null;
  10400. this.reason = null;
  10401. this.addssrc = [];
  10402. this.removessrc = [];
  10403. this.pendingop = null;
  10404. this.switchstreams = false;
  10405. this.wait = true;
  10406. this.localStreamsSSRC = null;
  10407. /**
  10408. * The indicator which determines whether the (local) video has been muted
  10409. * in response to a user command in contrast to an automatic decision made
  10410. * by the application logic.
  10411. */
  10412. this.videoMuteByUser = false;
  10413. }
  10414. //TODO: this array must be removed when firefox implement multistream support
  10415. JingleSession.notReceivedSSRCs = [];
  10416. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  10417. var self = this;
  10418. if (this.state !== null) {
  10419. console.error('attempt to initiate on session ' + this.sid +
  10420. 'in state ' + this.state);
  10421. return;
  10422. }
  10423. this.isInitiator = isInitiator;
  10424. this.state = 'pending';
  10425. this.initiator = isInitiator ? this.me : peerjid;
  10426. this.responder = !isInitiator ? this.me : peerjid;
  10427. this.peerjid = peerjid;
  10428. this.hadstuncandidate = false;
  10429. this.hadturncandidate = false;
  10430. this.lasticecandidate = false;
  10431. this.peerconnection
  10432. = new TraceablePeerConnection(
  10433. this.connection.jingle.ice_config,
  10434. this.connection.jingle.pc_constraints );
  10435. this.peerconnection.onicecandidate = function (event) {
  10436. self.sendIceCandidate(event.candidate);
  10437. };
  10438. this.peerconnection.onaddstream = function (event) {
  10439. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  10440. self.remoteStreamAdded(event);
  10441. };
  10442. this.peerconnection.onremovestream = function (event) {
  10443. // Remove the stream from remoteStreams
  10444. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  10445. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  10446. };
  10447. this.peerconnection.onsignalingstatechange = function (event) {
  10448. if (!(self && self.peerconnection)) return;
  10449. };
  10450. this.peerconnection.oniceconnectionstatechange = function (event) {
  10451. if (!(self && self.peerconnection)) return;
  10452. switch (self.peerconnection.iceConnectionState) {
  10453. case 'connected':
  10454. this.startTime = new Date();
  10455. break;
  10456. case 'disconnected':
  10457. this.stopTime = new Date();
  10458. break;
  10459. }
  10460. onIceConnectionStateChange(self.sid, self);
  10461. };
  10462. // add any local and relayed stream
  10463. APP.RTC.localStreams.forEach(function(stream) {
  10464. self.peerconnection.addStream(stream.getOriginalStream());
  10465. });
  10466. this.relayedStreams.forEach(function(stream) {
  10467. self.peerconnection.addStream(stream);
  10468. });
  10469. };
  10470. function onIceConnectionStateChange(sid, session) {
  10471. switch (session.peerconnection.iceConnectionState) {
  10472. case 'checking':
  10473. session.timeChecking = (new Date()).getTime();
  10474. session.firstconnect = true;
  10475. break;
  10476. case 'completed': // on caller side
  10477. case 'connected':
  10478. if (session.firstconnect) {
  10479. session.firstconnect = false;
  10480. var metadata = {};
  10481. metadata.setupTime
  10482. = (new Date()).getTime() - session.timeChecking;
  10483. session.peerconnection.getStats(function (res) {
  10484. if(res && res.result) {
  10485. res.result().forEach(function (report) {
  10486. if (report.type == 'googCandidatePair' &&
  10487. report.stat('googActiveConnection') == 'true') {
  10488. metadata.localCandidateType
  10489. = report.stat('googLocalCandidateType');
  10490. metadata.remoteCandidateType
  10491. = report.stat('googRemoteCandidateType');
  10492. // log pair as well so we can get nice pie
  10493. // charts
  10494. metadata.candidatePair
  10495. = report.stat('googLocalCandidateType') +
  10496. ';' +
  10497. report.stat('googRemoteCandidateType');
  10498. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  10499. {
  10500. metadata.ipv6 = true;
  10501. }
  10502. }
  10503. });
  10504. }
  10505. });
  10506. }
  10507. break;
  10508. }
  10509. }
  10510. JingleSession.prototype.accept = function () {
  10511. var self = this;
  10512. this.state = 'active';
  10513. var pranswer = this.peerconnection.localDescription;
  10514. if (!pranswer || pranswer.type != 'pranswer') {
  10515. return;
  10516. }
  10517. console.log('going from pranswer to answer');
  10518. if (this.usetrickle) {
  10519. // remove candidates already sent from session-accept
  10520. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  10521. for (var i = 0; i < lines.length; i++) {
  10522. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  10523. }
  10524. }
  10525. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  10526. // FIXME: change any inactive to sendrecv or whatever they were originally
  10527. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  10528. }
  10529. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  10530. var prsdp = new SDP(pranswer.sdp);
  10531. var accept = $iq({to: this.peerjid,
  10532. type: 'set'})
  10533. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10534. action: 'session-accept',
  10535. initiator: this.initiator,
  10536. responder: this.responder,
  10537. sid: this.sid });
  10538. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10539. var sdp = this.peerconnection.localDescription.sdp;
  10540. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  10541. // FIXME: change any inactive to sendrecv or whatever they were originally
  10542. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  10543. }
  10544. var self = this;
  10545. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  10546. function () {
  10547. //console.log('setLocalDescription success');
  10548. self.setLocalDescription();
  10549. self.connection.sendIQ(accept,
  10550. function () {
  10551. var ack = {};
  10552. ack.source = 'answer';
  10553. $(document).trigger('ack.jingle', [self.sid, ack]);
  10554. },
  10555. function (stanza) {
  10556. var error = ($(stanza).find('error').length) ? {
  10557. code: $(stanza).find('error').attr('code'),
  10558. reason: $(stanza).find('error :first')[0].tagName
  10559. }:{};
  10560. error.source = 'answer';
  10561. JingleSession.onJingleError(self.sid, error);
  10562. },
  10563. 10000);
  10564. },
  10565. function (e) {
  10566. console.error('setLocalDescription failed', e);
  10567. }
  10568. );
  10569. };
  10570. JingleSession.prototype.terminate = function (reason) {
  10571. this.state = 'ended';
  10572. this.reason = reason;
  10573. this.peerconnection.close();
  10574. if (this.statsinterval !== null) {
  10575. window.clearInterval(this.statsinterval);
  10576. this.statsinterval = null;
  10577. }
  10578. };
  10579. JingleSession.prototype.active = function () {
  10580. return this.state == 'active';
  10581. };
  10582. JingleSession.prototype.sendIceCandidate = function (candidate) {
  10583. var self = this;
  10584. if (candidate && !this.lasticecandidate) {
  10585. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  10586. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  10587. if (!(ice && jcand)) {
  10588. console.error('failed to get ice && jcand');
  10589. return;
  10590. }
  10591. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10592. if (jcand.type === 'srflx') {
  10593. this.hadstuncandidate = true;
  10594. } else if (jcand.type === 'relay') {
  10595. this.hadturncandidate = true;
  10596. }
  10597. if (this.usetrickle) {
  10598. if (this.usedrip) {
  10599. if (this.drip_container.length === 0) {
  10600. // start 20ms callout
  10601. window.setTimeout(function () {
  10602. if (self.drip_container.length === 0) return;
  10603. self.sendIceCandidates(self.drip_container);
  10604. self.drip_container = [];
  10605. }, 20);
  10606. }
  10607. this.drip_container.push(candidate);
  10608. return;
  10609. } else {
  10610. self.sendIceCandidate([candidate]);
  10611. }
  10612. }
  10613. } else {
  10614. //console.log('sendIceCandidate: last candidate.');
  10615. if (!this.usetrickle) {
  10616. //console.log('should send full offer now...');
  10617. var init = $iq({to: this.peerjid,
  10618. type: 'set'})
  10619. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10620. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  10621. initiator: this.initiator,
  10622. sid: this.sid});
  10623. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  10624. var self = this;
  10625. var sendJingle = function (ssrc) {
  10626. if(!ssrc)
  10627. ssrc = {};
  10628. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  10629. self.connection.sendIQ(init,
  10630. function () {
  10631. //console.log('session initiate ack');
  10632. var ack = {};
  10633. ack.source = 'offer';
  10634. $(document).trigger('ack.jingle', [self.sid, ack]);
  10635. },
  10636. function (stanza) {
  10637. self.state = 'error';
  10638. self.peerconnection.close();
  10639. var error = ($(stanza).find('error').length) ? {
  10640. code: $(stanza).find('error').attr('code'),
  10641. reason: $(stanza).find('error :first')[0].tagName,
  10642. }:{};
  10643. error.source = 'offer';
  10644. JingleSession.onJingleError(self.sid, error);
  10645. },
  10646. 10000);
  10647. }
  10648. sendJingle();
  10649. }
  10650. this.lasticecandidate = true;
  10651. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  10652. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  10653. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  10654. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  10655. }
  10656. }
  10657. };
  10658. JingleSession.prototype.sendIceCandidates = function (candidates) {
  10659. console.log('sendIceCandidates', candidates);
  10660. var cand = $iq({to: this.peerjid, type: 'set'})
  10661. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10662. action: 'transport-info',
  10663. initiator: this.initiator,
  10664. sid: this.sid});
  10665. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  10666. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  10667. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  10668. if (cands.length > 0) {
  10669. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  10670. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10671. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  10672. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  10673. }).c('transport', ice);
  10674. for (var i = 0; i < cands.length; i++) {
  10675. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  10676. }
  10677. // add fingerprint
  10678. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  10679. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  10680. tmp.required = true;
  10681. cand.c(
  10682. 'fingerprint',
  10683. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  10684. .t(tmp.fingerprint);
  10685. delete tmp.fingerprint;
  10686. cand.attrs(tmp);
  10687. cand.up();
  10688. }
  10689. cand.up(); // transport
  10690. cand.up(); // content
  10691. }
  10692. }
  10693. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  10694. //console.log('was this the last candidate', this.lasticecandidate);
  10695. this.connection.sendIQ(cand,
  10696. function () {
  10697. var ack = {};
  10698. ack.source = 'transportinfo';
  10699. $(document).trigger('ack.jingle', [this.sid, ack]);
  10700. },
  10701. function (stanza) {
  10702. var error = ($(stanza).find('error').length) ? {
  10703. code: $(stanza).find('error').attr('code'),
  10704. reason: $(stanza).find('error :first')[0].tagName,
  10705. }:{};
  10706. error.source = 'transportinfo';
  10707. JingleSession.onJingleError(this.sid, error);
  10708. },
  10709. 10000);
  10710. };
  10711. JingleSession.prototype.sendOffer = function () {
  10712. //console.log('sendOffer...');
  10713. var self = this;
  10714. this.peerconnection.createOffer(function (sdp) {
  10715. self.createdOffer(sdp);
  10716. },
  10717. function (e) {
  10718. console.error('createOffer failed', e);
  10719. },
  10720. this.media_constraints
  10721. );
  10722. };
  10723. JingleSession.prototype.createdOffer = function (sdp) {
  10724. //console.log('createdOffer', sdp);
  10725. var self = this;
  10726. this.localSDP = new SDP(sdp.sdp);
  10727. //this.localSDP.mangle();
  10728. var sendJingle = function () {
  10729. var init = $iq({to: this.peerjid,
  10730. type: 'set'})
  10731. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10732. action: 'session-initiate',
  10733. initiator: this.initiator,
  10734. sid: this.sid});
  10735. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10736. self.connection.sendIQ(init,
  10737. function () {
  10738. var ack = {};
  10739. ack.source = 'offer';
  10740. $(document).trigger('ack.jingle', [self.sid, ack]);
  10741. },
  10742. function (stanza) {
  10743. self.state = 'error';
  10744. self.peerconnection.close();
  10745. var error = ($(stanza).find('error').length) ? {
  10746. code: $(stanza).find('error').attr('code'),
  10747. reason: $(stanza).find('error :first')[0].tagName,
  10748. }:{};
  10749. error.source = 'offer';
  10750. JingleSession.onJingleError(self.sid, error);
  10751. },
  10752. 10000);
  10753. }
  10754. sdp.sdp = this.localSDP.raw;
  10755. this.peerconnection.setLocalDescription(sdp,
  10756. function () {
  10757. if(self.usetrickle)
  10758. {
  10759. sendJingle();
  10760. }
  10761. self.setLocalDescription();
  10762. //console.log('setLocalDescription success');
  10763. },
  10764. function (e) {
  10765. console.error('setLocalDescription failed', e);
  10766. }
  10767. );
  10768. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10769. for (var i = 0; i < cands.length; i++) {
  10770. var cand = SDPUtil.parse_icecandidate(cands[i]);
  10771. if (cand.type == 'srflx') {
  10772. this.hadstuncandidate = true;
  10773. } else if (cand.type == 'relay') {
  10774. this.hadturncandidate = true;
  10775. }
  10776. }
  10777. };
  10778. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  10779. //console.log('setting remote description... ', desctype);
  10780. this.remoteSDP = new SDP('');
  10781. this.remoteSDP.fromJingle(elem);
  10782. if (this.peerconnection.remoteDescription !== null) {
  10783. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  10784. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  10785. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  10786. for (var i = 0; i < pranswer.media.length; i++) {
  10787. // make sure we have ice ufrag and pwd
  10788. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  10789. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  10790. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  10791. } else {
  10792. console.warn('no ice ufrag?');
  10793. }
  10794. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  10795. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  10796. } else {
  10797. console.warn('no ice pwd?');
  10798. }
  10799. }
  10800. // copy over candidates
  10801. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  10802. for (var j = 0; j < lines.length; j++) {
  10803. this.remoteSDP.media[i] += lines[j] + '\r\n';
  10804. }
  10805. }
  10806. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10807. }
  10808. }
  10809. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  10810. this.peerconnection.setRemoteDescription(remotedesc,
  10811. function () {
  10812. //console.log('setRemoteDescription success');
  10813. },
  10814. function (e) {
  10815. console.error('setRemoteDescription error', e);
  10816. JingleSession.onJingleFatalError(self, e);
  10817. }
  10818. );
  10819. };
  10820. JingleSession.prototype.addIceCandidate = function (elem) {
  10821. var self = this;
  10822. if (this.peerconnection.signalingState == 'closed') {
  10823. return;
  10824. }
  10825. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  10826. console.log('trickle ice candidate arriving before session accept...');
  10827. // create a PRANSWER for setRemoteDescription
  10828. if (!this.remoteSDP) {
  10829. var cobbled = 'v=0\r\n' +
  10830. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  10831. 's=-\r\n' +
  10832. 't=0 0\r\n';
  10833. // first, take some things from the local description
  10834. for (var i = 0; i < this.localSDP.media.length; i++) {
  10835. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  10836. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  10837. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  10838. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  10839. }
  10840. cobbled += 'a=inactive\r\n';
  10841. }
  10842. this.remoteSDP = new SDP(cobbled);
  10843. }
  10844. // then add things like ice and dtls from remote candidate
  10845. elem.each(function () {
  10846. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  10847. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10848. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10849. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  10850. var tmp = $(this).find('transport');
  10851. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  10852. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  10853. tmp = $(this).find('transport>fingerprint');
  10854. if (tmp.length) {
  10855. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  10856. } else {
  10857. console.log('no dtls fingerprint (webrtc issue #1718?)');
  10858. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  10859. }
  10860. break;
  10861. }
  10862. }
  10863. }
  10864. });
  10865. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10866. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  10867. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  10868. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  10869. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  10870. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  10871. }).length == this.remoteSDP.media.length;
  10872. if (iscomplete) {
  10873. console.log('setting pranswer');
  10874. try {
  10875. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  10876. function() {
  10877. },
  10878. function(e) {
  10879. console.log('setRemoteDescription pranswer failed', e.toString());
  10880. });
  10881. } catch (e) {
  10882. console.error('setting pranswer failed', e);
  10883. }
  10884. } else {
  10885. //console.log('not yet setting pranswer');
  10886. }
  10887. }
  10888. // operate on each content element
  10889. elem.each(function () {
  10890. // would love to deactivate this, but firefox still requires it
  10891. var idx = -1;
  10892. var i;
  10893. for (i = 0; i < self.remoteSDP.media.length; i++) {
  10894. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10895. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10896. idx = i;
  10897. break;
  10898. }
  10899. }
  10900. if (idx == -1) { // fall back to localdescription
  10901. for (i = 0; i < self.localSDP.media.length; i++) {
  10902. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10903. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10904. idx = i;
  10905. break;
  10906. }
  10907. }
  10908. }
  10909. var name = $(this).attr('name');
  10910. // TODO: check ice-pwd and ice-ufrag?
  10911. $(this).find('transport>candidate').each(function () {
  10912. var line, candidate;
  10913. line = SDPUtil.candidateFromJingle(this);
  10914. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  10915. sdpMid: name,
  10916. candidate: line});
  10917. try {
  10918. self.peerconnection.addIceCandidate(candidate);
  10919. } catch (e) {
  10920. console.error('addIceCandidate failed', e.toString(), line);
  10921. }
  10922. });
  10923. });
  10924. };
  10925. JingleSession.prototype.sendAnswer = function (provisional) {
  10926. //console.log('createAnswer', provisional);
  10927. var self = this;
  10928. this.peerconnection.createAnswer(
  10929. function (sdp) {
  10930. self.createdAnswer(sdp, provisional);
  10931. },
  10932. function (e) {
  10933. console.error('createAnswer failed', e);
  10934. },
  10935. this.media_constraints
  10936. );
  10937. };
  10938. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  10939. //console.log('createAnswer callback');
  10940. var self = this;
  10941. this.localSDP = new SDP(sdp.sdp);
  10942. //this.localSDP.mangle();
  10943. this.usepranswer = provisional === true;
  10944. if (this.usetrickle) {
  10945. if (this.usepranswer) {
  10946. sdp.type = 'pranswer';
  10947. for (var i = 0; i < this.localSDP.media.length; i++) {
  10948. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  10949. }
  10950. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  10951. }
  10952. }
  10953. var self = this;
  10954. var sendJingle = function (ssrcs) {
  10955. var accept = $iq({to: self.peerjid,
  10956. type: 'set'})
  10957. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10958. action: 'session-accept',
  10959. initiator: self.initiator,
  10960. responder: self.responder,
  10961. sid: self.sid });
  10962. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  10963. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  10964. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  10965. self.connection.sendIQ(accept,
  10966. function () {
  10967. var ack = {};
  10968. ack.source = 'answer';
  10969. $(document).trigger('ack.jingle', [self.sid, ack]);
  10970. },
  10971. function (stanza) {
  10972. var error = ($(stanza).find('error').length) ? {
  10973. code: $(stanza).find('error').attr('code'),
  10974. reason: $(stanza).find('error :first')[0].tagName,
  10975. }:{};
  10976. error.source = 'answer';
  10977. JingleSession.onJingleError(self.sid, error);
  10978. },
  10979. 10000);
  10980. }
  10981. sdp.sdp = this.localSDP.raw;
  10982. this.peerconnection.setLocalDescription(sdp,
  10983. function () {
  10984. //console.log('setLocalDescription success');
  10985. if (self.usetrickle && !self.usepranswer) {
  10986. sendJingle();
  10987. }
  10988. self.setLocalDescription();
  10989. },
  10990. function (e) {
  10991. console.error('setLocalDescription failed', e);
  10992. }
  10993. );
  10994. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10995. for (var j = 0; j < cands.length; j++) {
  10996. var cand = SDPUtil.parse_icecandidate(cands[j]);
  10997. if (cand.type == 'srflx') {
  10998. this.hadstuncandidate = true;
  10999. } else if (cand.type == 'relay') {
  11000. this.hadturncandidate = true;
  11001. }
  11002. }
  11003. };
  11004. JingleSession.prototype.sendTerminate = function (reason, text) {
  11005. var self = this,
  11006. term = $iq({to: this.peerjid,
  11007. type: 'set'})
  11008. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11009. action: 'session-terminate',
  11010. initiator: this.initiator,
  11011. sid: this.sid})
  11012. .c('reason')
  11013. .c(reason || 'success');
  11014. if (text) {
  11015. term.up().c('text').t(text);
  11016. }
  11017. this.connection.sendIQ(term,
  11018. function () {
  11019. self.peerconnection.close();
  11020. self.peerconnection = null;
  11021. self.terminate();
  11022. var ack = {};
  11023. ack.source = 'terminate';
  11024. $(document).trigger('ack.jingle', [self.sid, ack]);
  11025. },
  11026. function (stanza) {
  11027. var error = ($(stanza).find('error').length) ? {
  11028. code: $(stanza).find('error').attr('code'),
  11029. reason: $(stanza).find('error :first')[0].tagName,
  11030. }:{};
  11031. $(document).trigger('ack.jingle', [self.sid, error]);
  11032. },
  11033. 10000);
  11034. if (this.statsinterval !== null) {
  11035. window.clearInterval(this.statsinterval);
  11036. this.statsinterval = null;
  11037. }
  11038. };
  11039. JingleSession.prototype.addSource = function (elem, fromJid) {
  11040. var self = this;
  11041. // FIXME: dirty waiting
  11042. if (!this.peerconnection.localDescription)
  11043. {
  11044. console.warn("addSource - localDescription not ready yet")
  11045. setTimeout(function()
  11046. {
  11047. self.addSource(elem, fromJid);
  11048. },
  11049. 200
  11050. );
  11051. return;
  11052. }
  11053. console.log('addssrc', new Date().getTime());
  11054. console.log('ice', this.peerconnection.iceConnectionState);
  11055. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11056. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11057. $(elem).each(function (idx, content) {
  11058. var name = $(content).attr('name');
  11059. var lines = '';
  11060. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11061. var semantics = this.getAttribute('semantics');
  11062. var ssrcs = $(this).find('>source').map(function () {
  11063. return this.getAttribute('ssrc');
  11064. }).get();
  11065. if (ssrcs.length != 0) {
  11066. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11067. }
  11068. });
  11069. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11070. tmp.each(function () {
  11071. var ssrc = $(this).attr('ssrc');
  11072. if(mySdp.containsSSRC(ssrc)){
  11073. /**
  11074. * This happens when multiple participants change their streams at the same time and
  11075. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  11076. * addssrc are scheduled for update IQ. See
  11077. */
  11078. console.warn("Got add stream request for my own ssrc: "+ssrc);
  11079. return;
  11080. }
  11081. $(this).find('>parameter').each(function () {
  11082. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11083. if ($(this).attr('value') && $(this).attr('value').length)
  11084. lines += ':' + $(this).attr('value');
  11085. lines += '\r\n';
  11086. });
  11087. });
  11088. sdp.media.forEach(function(media, idx) {
  11089. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11090. return;
  11091. sdp.media[idx] += lines;
  11092. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  11093. self.addssrc[idx] += lines;
  11094. });
  11095. sdp.raw = sdp.session + sdp.media.join('');
  11096. });
  11097. this.modifySources();
  11098. };
  11099. JingleSession.prototype.removeSource = function (elem, fromJid) {
  11100. var self = this;
  11101. // FIXME: dirty waiting
  11102. if (!this.peerconnection.localDescription)
  11103. {
  11104. console.warn("removeSource - localDescription not ready yet")
  11105. setTimeout(function()
  11106. {
  11107. self.removeSource(elem, fromJid);
  11108. },
  11109. 200
  11110. );
  11111. return;
  11112. }
  11113. console.log('removessrc', new Date().getTime());
  11114. console.log('ice', this.peerconnection.iceConnectionState);
  11115. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11116. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11117. $(elem).each(function (idx, content) {
  11118. var name = $(content).attr('name');
  11119. var lines = '';
  11120. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11121. var semantics = this.getAttribute('semantics');
  11122. var ssrcs = $(this).find('>source').map(function () {
  11123. return this.getAttribute('ssrc');
  11124. }).get();
  11125. if (ssrcs.length != 0) {
  11126. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11127. }
  11128. });
  11129. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11130. tmp.each(function () {
  11131. var ssrc = $(this).attr('ssrc');
  11132. // This should never happen, but can be useful for bug detection
  11133. if(mySdp.containsSSRC(ssrc)){
  11134. console.error("Got remove stream request for my own ssrc: "+ssrc);
  11135. return;
  11136. }
  11137. $(this).find('>parameter').each(function () {
  11138. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11139. if ($(this).attr('value') && $(this).attr('value').length)
  11140. lines += ':' + $(this).attr('value');
  11141. lines += '\r\n';
  11142. });
  11143. });
  11144. sdp.media.forEach(function(media, idx) {
  11145. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11146. return;
  11147. sdp.media[idx] += lines;
  11148. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  11149. self.removessrc[idx] += lines;
  11150. });
  11151. sdp.raw = sdp.session + sdp.media.join('');
  11152. });
  11153. this.modifySources();
  11154. };
  11155. JingleSession.prototype.modifySources = function (successCallback) {
  11156. var self = this;
  11157. if (this.peerconnection.signalingState == 'closed') return;
  11158. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  11159. // There is nothing to do since scheduled job might have been executed by another succeeding call
  11160. this.setLocalDescription();
  11161. if(successCallback){
  11162. successCallback();
  11163. }
  11164. return;
  11165. }
  11166. // FIXME: this is a big hack
  11167. // https://code.google.com/p/webrtc/issues/detail?id=2688
  11168. // ^ has been fixed.
  11169. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
  11170. console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
  11171. this.wait = true;
  11172. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  11173. return;
  11174. }
  11175. if (this.wait) {
  11176. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  11177. this.wait = false;
  11178. return;
  11179. }
  11180. // Reset switch streams flag
  11181. this.switchstreams = false;
  11182. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11183. // add sources
  11184. this.addssrc.forEach(function(lines, idx) {
  11185. sdp.media[idx] += lines;
  11186. });
  11187. this.addssrc = [];
  11188. // remove sources
  11189. this.removessrc.forEach(function(lines, idx) {
  11190. lines = lines.split('\r\n');
  11191. lines.pop(); // remove empty last element;
  11192. lines.forEach(function(line) {
  11193. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  11194. });
  11195. });
  11196. this.removessrc = [];
  11197. // FIXME:
  11198. // this was a hack for the situation when only one peer exists
  11199. // in the conference.
  11200. // check if still required and remove
  11201. if (sdp.media[0])
  11202. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  11203. if (sdp.media[1])
  11204. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11205. sdp.raw = sdp.session + sdp.media.join('');
  11206. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  11207. function() {
  11208. if(self.signalingState == 'closed') {
  11209. console.error("createAnswer attempt on closed state");
  11210. return;
  11211. }
  11212. self.peerconnection.createAnswer(
  11213. function(modifiedAnswer) {
  11214. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  11215. if (self.pendingop !== null) {
  11216. var sdp = new SDP(modifiedAnswer.sdp);
  11217. if (sdp.media.length > 1) {
  11218. switch(self.pendingop) {
  11219. case 'mute':
  11220. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  11221. break;
  11222. case 'unmute':
  11223. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11224. break;
  11225. }
  11226. sdp.raw = sdp.session + sdp.media.join('');
  11227. modifiedAnswer.sdp = sdp.raw;
  11228. }
  11229. self.pendingop = null;
  11230. }
  11231. // FIXME: pushing down an answer while ice connection state
  11232. // is still checking is bad...
  11233. //console.log(self.peerconnection.iceConnectionState);
  11234. // trying to work around another chrome bug
  11235. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11236. self.peerconnection.setLocalDescription(modifiedAnswer,
  11237. function() {
  11238. //console.log('modified setLocalDescription ok');
  11239. self.setLocalDescription();
  11240. if(successCallback){
  11241. successCallback();
  11242. }
  11243. },
  11244. function(error) {
  11245. console.error('modified setLocalDescription failed', error);
  11246. }
  11247. );
  11248. },
  11249. function(error) {
  11250. console.error('modified answer failed', error);
  11251. }
  11252. );
  11253. },
  11254. function(error) {
  11255. console.error('modify failed', error);
  11256. }
  11257. );
  11258. };
  11259. /**
  11260. * Switches video streams.
  11261. * @param new_stream new stream that will be used as video of this session.
  11262. * @param oldStream old video stream of this session.
  11263. * @param success_callback callback executed after successful stream switch.
  11264. */
  11265. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback) {
  11266. var self = this;
  11267. // Remember SDP to figure out added/removed SSRCs
  11268. var oldSdp = null;
  11269. if(self.peerconnection) {
  11270. if(self.peerconnection.localDescription) {
  11271. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11272. }
  11273. self.peerconnection.removeStream(oldStream, true);
  11274. self.peerconnection.addStream(new_stream);
  11275. }
  11276. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11277. // Conference is not active
  11278. if(!oldSdp || !self.peerconnection) {
  11279. success_callback();
  11280. return;
  11281. }
  11282. self.switchstreams = true;
  11283. self.modifySources(function() {
  11284. console.log('modify sources done');
  11285. success_callback();
  11286. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11287. console.log("SDPs", oldSdp, newSdp);
  11288. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11289. });
  11290. };
  11291. /**
  11292. * Figures out added/removed ssrcs and send update IQs.
  11293. * @param old_sdp SDP object for old description.
  11294. * @param new_sdp SDP object for new description.
  11295. */
  11296. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11297. if (!(this.peerconnection.signalingState == 'stable' &&
  11298. this.peerconnection.iceConnectionState == 'connected')){
  11299. console.log("Too early to send updates");
  11300. return;
  11301. }
  11302. // send source-remove IQ.
  11303. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11304. var remove = $iq({to: this.peerjid, type: 'set'})
  11305. .c('jingle', {
  11306. xmlns: 'urn:xmpp:jingle:1',
  11307. action: 'source-remove',
  11308. initiator: this.initiator,
  11309. sid: this.sid
  11310. }
  11311. );
  11312. var removed = sdpDiffer.toJingle(remove);
  11313. if (removed) {
  11314. this.connection.sendIQ(remove,
  11315. function (res) {
  11316. console.info('got remove result', res);
  11317. },
  11318. function (err) {
  11319. console.error('got remove error', err);
  11320. }
  11321. );
  11322. } else {
  11323. console.log('removal not necessary');
  11324. }
  11325. // send source-add IQ.
  11326. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11327. var add = $iq({to: this.peerjid, type: 'set'})
  11328. .c('jingle', {
  11329. xmlns: 'urn:xmpp:jingle:1',
  11330. action: 'source-add',
  11331. initiator: this.initiator,
  11332. sid: this.sid
  11333. }
  11334. );
  11335. var added = sdpDiffer.toJingle(add);
  11336. if (added) {
  11337. this.connection.sendIQ(add,
  11338. function (res) {
  11339. console.info('got add result', res);
  11340. },
  11341. function (err) {
  11342. console.error('got add error', err);
  11343. }
  11344. );
  11345. } else {
  11346. console.log('addition not necessary');
  11347. }
  11348. };
  11349. /**
  11350. * Determines whether the (local) video is mute i.e. all video tracks are
  11351. * disabled.
  11352. *
  11353. * @return <tt>true</tt> if the (local) video is mute i.e. all video tracks are
  11354. * disabled; otherwise, <tt>false</tt>
  11355. */
  11356. JingleSession.prototype.isVideoMute = function () {
  11357. var tracks = APP.RTC.localVideo.getVideoTracks();
  11358. var mute = true;
  11359. for (var i = 0; i < tracks.length; ++i) {
  11360. if (tracks[i].enabled) {
  11361. mute = false;
  11362. break;
  11363. }
  11364. }
  11365. return mute;
  11366. };
  11367. /**
  11368. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  11369. *
  11370. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  11371. * tracks; otherwise, <tt>false</tt>
  11372. * @param callback a function to be invoked with <tt>mute</tt> after all video
  11373. * tracks have been enabled/disabled. The function may, optionally, return
  11374. * another function which is to be invoked after the whole mute/unmute operation
  11375. * has completed successfully.
  11376. * @param options an object which specifies optional arguments such as the
  11377. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  11378. * specifies whether the method was initiated in response to a user command (in
  11379. * contrast to an automatic decision made by the application logic)
  11380. */
  11381. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  11382. var byUser;
  11383. if (options) {
  11384. byUser = options.byUser;
  11385. if (typeof byUser === 'undefined') {
  11386. byUser = true;
  11387. }
  11388. } else {
  11389. byUser = true;
  11390. }
  11391. // The user's command to mute the (local) video takes precedence over any
  11392. // automatic decision made by the application logic.
  11393. if (byUser) {
  11394. this.videoMuteByUser = mute;
  11395. } else if (this.videoMuteByUser) {
  11396. return;
  11397. }
  11398. var self = this;
  11399. var localCallback = function (mute) {
  11400. self.connection.emuc.addVideoInfoToPresence(mute);
  11401. self.connection.emuc.sendPresence();
  11402. return callback(mute)
  11403. };
  11404. if (mute == APP.RTC.localVideo.isMuted())
  11405. {
  11406. // Even if no change occurs, the specified callback is to be executed.
  11407. // The specified callback may, optionally, return a successCallback
  11408. // which is to be executed as well.
  11409. var successCallback = localCallback(mute);
  11410. if (successCallback) {
  11411. successCallback();
  11412. }
  11413. } else {
  11414. APP.RTC.localVideo.setMute(!mute);
  11415. this.hardMuteVideo(mute);
  11416. this.modifySources(localCallback(mute));
  11417. }
  11418. };
  11419. // SDP-based mute by going recvonly/sendrecv
  11420. // FIXME: should probably black out the screen as well
  11421. JingleSession.prototype.toggleVideoMute = function (callback) {
  11422. this.service.setVideoMute(APP.RTC.localVideo.isMuted(), callback);
  11423. };
  11424. JingleSession.prototype.hardMuteVideo = function (muted) {
  11425. this.pendingop = muted ? 'mute' : 'unmute';
  11426. };
  11427. JingleSession.prototype.sendMute = function (muted, content) {
  11428. var info = $iq({to: this.peerjid,
  11429. type: 'set'})
  11430. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11431. action: 'session-info',
  11432. initiator: this.initiator,
  11433. sid: this.sid });
  11434. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11435. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  11436. if (content) {
  11437. info.attrs({'name': content});
  11438. }
  11439. this.connection.send(info);
  11440. };
  11441. JingleSession.prototype.sendRinging = function () {
  11442. var info = $iq({to: this.peerjid,
  11443. type: 'set'})
  11444. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11445. action: 'session-info',
  11446. initiator: this.initiator,
  11447. sid: this.sid });
  11448. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11449. this.connection.send(info);
  11450. };
  11451. JingleSession.prototype.getStats = function (interval) {
  11452. var self = this;
  11453. var recv = {audio: 0, video: 0};
  11454. var lost = {audio: 0, video: 0};
  11455. var lastrecv = {audio: 0, video: 0};
  11456. var lastlost = {audio: 0, video: 0};
  11457. var loss = {audio: 0, video: 0};
  11458. var delta = {audio: 0, video: 0};
  11459. this.statsinterval = window.setInterval(function () {
  11460. if (self && self.peerconnection && self.peerconnection.getStats) {
  11461. self.peerconnection.getStats(function (stats) {
  11462. var results = stats.result();
  11463. // TODO: there are so much statistics you can get from this..
  11464. for (var i = 0; i < results.length; ++i) {
  11465. if (results[i].type == 'ssrc') {
  11466. var packetsrecv = results[i].stat('packetsReceived');
  11467. var packetslost = results[i].stat('packetsLost');
  11468. if (packetsrecv && packetslost) {
  11469. packetsrecv = parseInt(packetsrecv, 10);
  11470. packetslost = parseInt(packetslost, 10);
  11471. if (results[i].stat('googFrameRateReceived')) {
  11472. lastlost.video = lost.video;
  11473. lastrecv.video = recv.video;
  11474. recv.video = packetsrecv;
  11475. lost.video = packetslost;
  11476. } else {
  11477. lastlost.audio = lost.audio;
  11478. lastrecv.audio = recv.audio;
  11479. recv.audio = packetsrecv;
  11480. lost.audio = packetslost;
  11481. }
  11482. }
  11483. }
  11484. }
  11485. delta.audio = recv.audio - lastrecv.audio;
  11486. delta.video = recv.video - lastrecv.video;
  11487. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  11488. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  11489. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  11490. });
  11491. }
  11492. }, interval || 3000);
  11493. return this.statsinterval;
  11494. };
  11495. JingleSession.onJingleError = function (session, error)
  11496. {
  11497. console.error("Jingle error", error);
  11498. }
  11499. JingleSession.onJingleFatalError = function (session, error)
  11500. {
  11501. this.service.sessionTerminated = true;
  11502. this.connection.emuc.doLeave();
  11503. APP.UI.messageHandler.showError("dialog.sorry", "Sorry",
  11504. "dialog.internalError",
  11505. "Internal application error[setRemoteDescription]");
  11506. }
  11507. JingleSession.prototype.setLocalDescription = function () {
  11508. // put our ssrcs into presence so other clients can identify our stream
  11509. var newssrcs = [];
  11510. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  11511. media.forEach(function (media) {
  11512. if(Object.keys(media.sources).length > 0) {
  11513. // TODO(gp) maybe exclude FID streams?
  11514. Object.keys(media.sources).forEach(function (ssrc) {
  11515. newssrcs.push({
  11516. 'ssrc': ssrc,
  11517. 'type': media.type,
  11518. 'direction': media.direction
  11519. });
  11520. });
  11521. }
  11522. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  11523. {
  11524. newssrcs.push({
  11525. 'ssrc': this.localStreamsSSRC[media.type],
  11526. 'type': media.type,
  11527. 'direction': media.direction
  11528. });
  11529. }
  11530. });
  11531. console.log('new ssrcs', newssrcs);
  11532. // Have to clear presence map to get rid of removed streams
  11533. this.connection.emuc.clearPresenceMedia();
  11534. if (newssrcs.length > 0) {
  11535. for (var i = 1; i <= newssrcs.length; i ++) {
  11536. // Change video type to screen
  11537. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  11538. newssrcs[i-1].type = 'screen';
  11539. }
  11540. this.connection.emuc.addMediaToPresence(i,
  11541. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  11542. }
  11543. this.connection.emuc.sendPresence();
  11544. }
  11545. }
  11546. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11547. function sendKeyframe(pc) {
  11548. console.log('sendkeyframe', pc.iceConnectionState);
  11549. if (pc.iceConnectionState !== 'connected') return; // safe...
  11550. pc.setRemoteDescription(
  11551. pc.remoteDescription,
  11552. function () {
  11553. pc.createAnswer(
  11554. function (modifiedAnswer) {
  11555. pc.setLocalDescription(
  11556. modifiedAnswer,
  11557. function () {
  11558. // noop
  11559. },
  11560. function (error) {
  11561. console.log('triggerKeyframe setLocalDescription failed', error);
  11562. APP.UI.messageHandler.showError();
  11563. }
  11564. );
  11565. },
  11566. function (error) {
  11567. console.log('triggerKeyframe createAnswer failed', error);
  11568. APP.UI.messageHandler.showError();
  11569. }
  11570. );
  11571. },
  11572. function (error) {
  11573. console.log('triggerKeyframe setRemoteDescription failed', error);
  11574. APP.UI.messageHandler.showError();
  11575. }
  11576. );
  11577. }
  11578. JingleSession.prototype.remoteStreamAdded = function (data) {
  11579. var self = this;
  11580. var thessrc;
  11581. var ssrc2jid = this.connection.emuc.ssrc2jid;
  11582. // look up an associated JID for a stream id
  11583. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  11584. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  11585. var ssrclines
  11586. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  11587. ssrclines = ssrclines.filter(function (line) {
  11588. // NOTE(gp) previously we filtered on the mslabel, but that property
  11589. // is not always present.
  11590. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  11591. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  11592. });
  11593. if (ssrclines.length) {
  11594. thessrc = ssrclines[0].substring(7).split(' ')[0];
  11595. // We signal our streams (through Jingle to the focus) before we set
  11596. // our presence (through which peers associate remote streams to
  11597. // jids). So, it might arrive that a remote stream is added but
  11598. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  11599. // successfully set. Here we wait for up to a second for the
  11600. // presence to arrive.
  11601. if (!ssrc2jid[thessrc]) {
  11602. // TODO(gp) limit wait duration to 1 sec.
  11603. setTimeout(function(d) {
  11604. return function() {
  11605. self.remoteStreamAdded(d);
  11606. }
  11607. }(data), 250);
  11608. return;
  11609. }
  11610. // ok to overwrite the one from focus? might save work in colibri.js
  11611. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  11612. if (ssrc2jid[thessrc]) {
  11613. data.peerjid = ssrc2jid[thessrc];
  11614. }
  11615. }
  11616. }
  11617. //TODO: this code should be removed when firefox implement multistream support
  11618. if(APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_FIREFOX)
  11619. {
  11620. if((JingleSession.notReceivedSSRCs.length == 0) ||
  11621. !ssrc2jid[JingleSession.notReceivedSSRCs[JingleSession.notReceivedSSRCs.length - 1]])
  11622. {
  11623. // TODO(gp) limit wait duration to 1 sec.
  11624. setTimeout(function(d) {
  11625. return function() {
  11626. self.remoteStreamAdded(d);
  11627. }
  11628. }(data), 250);
  11629. return;
  11630. }
  11631. thessrc = JingleSession.notReceivedSSRCs.pop();
  11632. if (ssrc2jid[thessrc]) {
  11633. data.peerjid = ssrc2jid[thessrc];
  11634. }
  11635. }
  11636. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  11637. var isVideo = data.stream.getVideoTracks().length > 0;
  11638. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11639. if (isVideo &&
  11640. data.peerjid && this.peerjid === data.peerjid &&
  11641. data.stream.getVideoTracks().length === 0 &&
  11642. APP.RTC.localVideo.getTracks().length > 0) {
  11643. window.setTimeout(function () {
  11644. sendKeyframe(self.peerconnection);
  11645. }, 3000);
  11646. }
  11647. }
  11648. module.exports = JingleSession;
  11649. },{"../../service/RTC/RTCBrowserType":80,"./SDP":49,"./SDPDiffer":50,"./SDPUtil":51,"./TraceablePeerConnection":52}],49:[function(require,module,exports){
  11650. /* jshint -W117 */
  11651. var SDPUtil = require("./SDPUtil");
  11652. // SDP STUFF
  11653. function SDP(sdp) {
  11654. this.media = sdp.split('\r\nm=');
  11655. for (var i = 1; i < this.media.length; i++) {
  11656. this.media[i] = 'm=' + this.media[i];
  11657. if (i != this.media.length - 1) {
  11658. this.media[i] += '\r\n';
  11659. }
  11660. }
  11661. this.session = this.media.shift() + '\r\n';
  11662. this.raw = this.session + this.media.join('');
  11663. }
  11664. /**
  11665. * Returns map of MediaChannel mapped per channel idx.
  11666. */
  11667. SDP.prototype.getMediaSsrcMap = function() {
  11668. var self = this;
  11669. var media_ssrcs = {};
  11670. var tmp;
  11671. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  11672. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  11673. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  11674. var media = {
  11675. mediaindex: mediaindex,
  11676. mid: mid,
  11677. ssrcs: {},
  11678. ssrcGroups: []
  11679. };
  11680. media_ssrcs[mediaindex] = media;
  11681. tmp.forEach(function (line) {
  11682. var linessrc = line.substring(7).split(' ')[0];
  11683. // allocate new ChannelSsrc
  11684. if(!media.ssrcs[linessrc]) {
  11685. media.ssrcs[linessrc] = {
  11686. ssrc: linessrc,
  11687. lines: []
  11688. };
  11689. }
  11690. media.ssrcs[linessrc].lines.push(line);
  11691. });
  11692. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  11693. tmp.forEach(function(line){
  11694. var semantics = line.substr(0, idx).substr(13);
  11695. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11696. if (ssrcs.length != 0) {
  11697. media.ssrcGroups.push({
  11698. semantics: semantics,
  11699. ssrcs: ssrcs
  11700. });
  11701. }
  11702. });
  11703. }
  11704. return media_ssrcs;
  11705. };
  11706. /**
  11707. * Returns <tt>true</tt> if this SDP contains given SSRC.
  11708. * @param ssrc the ssrc to check.
  11709. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  11710. */
  11711. SDP.prototype.containsSSRC = function(ssrc) {
  11712. var medias = this.getMediaSsrcMap();
  11713. var contains = false;
  11714. Object.keys(medias).forEach(function(mediaindex){
  11715. var media = medias[mediaindex];
  11716. //console.log("Check", channel, ssrc);
  11717. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  11718. contains = true;
  11719. }
  11720. });
  11721. return contains;
  11722. };
  11723. // remove iSAC and CN from SDP
  11724. SDP.prototype.mangle = function () {
  11725. var i, j, mline, lines, rtpmap, newdesc;
  11726. for (i = 0; i < this.media.length; i++) {
  11727. lines = this.media[i].split('\r\n');
  11728. lines.pop(); // remove empty last element
  11729. mline = SDPUtil.parse_mline(lines.shift());
  11730. if (mline.media != 'audio')
  11731. continue;
  11732. newdesc = '';
  11733. mline.fmt.length = 0;
  11734. for (j = 0; j < lines.length; j++) {
  11735. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  11736. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  11737. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  11738. continue;
  11739. mline.fmt.push(rtpmap.id);
  11740. newdesc += lines[j] + '\r\n';
  11741. } else {
  11742. newdesc += lines[j] + '\r\n';
  11743. }
  11744. }
  11745. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  11746. this.media[i] += newdesc;
  11747. }
  11748. this.raw = this.session + this.media.join('');
  11749. };
  11750. // remove lines matching prefix from session section
  11751. SDP.prototype.removeSessionLines = function(prefix) {
  11752. var self = this;
  11753. var lines = SDPUtil.find_lines(this.session, prefix);
  11754. lines.forEach(function(line) {
  11755. self.session = self.session.replace(line + '\r\n', '');
  11756. });
  11757. this.raw = this.session + this.media.join('');
  11758. return lines;
  11759. }
  11760. // remove lines matching prefix from a media section specified by mediaindex
  11761. // TODO: non-numeric mediaindex could match mid
  11762. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  11763. var self = this;
  11764. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  11765. lines.forEach(function(line) {
  11766. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  11767. });
  11768. this.raw = this.session + this.media.join('');
  11769. return lines;
  11770. }
  11771. // add content's to a jingle element
  11772. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  11773. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  11774. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  11775. var self = this;
  11776. // new bundle plan
  11777. if (SDPUtil.find_line(this.session, 'a=group:')) {
  11778. lines = SDPUtil.find_lines(this.session, 'a=group:');
  11779. for (i = 0; i < lines.length; i++) {
  11780. tmp = lines[i].split(' ');
  11781. var semantics = tmp.shift().substr(8);
  11782. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  11783. for (j = 0; j < tmp.length; j++) {
  11784. elem.c('content', {name: tmp[j]}).up();
  11785. }
  11786. elem.up();
  11787. }
  11788. }
  11789. for (i = 0; i < this.media.length; i++) {
  11790. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  11791. if (!(mline.media === 'audio' ||
  11792. mline.media === 'video' ||
  11793. mline.media === 'application'))
  11794. {
  11795. continue;
  11796. }
  11797. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  11798. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  11799. } else {
  11800. if(ssrcs && ssrcs[mline.media])
  11801. {
  11802. ssrc = ssrcs[mline.media];
  11803. }
  11804. else
  11805. ssrc = false;
  11806. }
  11807. elem.c('content', {creator: thecreator, name: mline.media});
  11808. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  11809. // prefer identifier from a=mid if present
  11810. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  11811. elem.attrs({ name: mid });
  11812. }
  11813. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  11814. {
  11815. elem.c('description',
  11816. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  11817. media: mline.media });
  11818. if (ssrc) {
  11819. elem.attrs({ssrc: ssrc});
  11820. }
  11821. for (j = 0; j < mline.fmt.length; j++) {
  11822. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  11823. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  11824. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  11825. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  11826. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  11827. for (k = 0; k < tmp.length; k++) {
  11828. elem.c('parameter', tmp[k]).up();
  11829. }
  11830. }
  11831. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  11832. elem.up();
  11833. }
  11834. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  11835. elem.c('encryption', {required: 1});
  11836. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  11837. crypto.forEach(function(line) {
  11838. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  11839. });
  11840. elem.up(); // end of encryption
  11841. }
  11842. if (ssrc) {
  11843. // new style mapping
  11844. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11845. // FIXME: group by ssrc and support multiple different ssrcs
  11846. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  11847. if(ssrclines.length > 0) {
  11848. ssrclines.forEach(function (line) {
  11849. idx = line.indexOf(' ');
  11850. var linessrc = line.substr(0, idx).substr(7);
  11851. if (linessrc != ssrc) {
  11852. elem.up();
  11853. ssrc = linessrc;
  11854. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11855. }
  11856. var kv = line.substr(idx + 1);
  11857. elem.c('parameter');
  11858. if (kv.indexOf(':') == -1) {
  11859. elem.attrs({ name: kv });
  11860. } else {
  11861. elem.attrs({ name: kv.split(':', 2)[0] });
  11862. elem.attrs({ value: kv.split(':', 2)[1] });
  11863. }
  11864. elem.up();
  11865. });
  11866. elem.up();
  11867. }
  11868. else
  11869. {
  11870. elem.up();
  11871. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11872. elem.c('parameter');
  11873. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  11874. elem.up();
  11875. var msid = null;
  11876. if(mline.media == "audio")
  11877. {
  11878. msid = APP.RTC.localAudio.getId();
  11879. }
  11880. else
  11881. {
  11882. msid = APP.RTC.localVideo.getId();
  11883. }
  11884. if(msid != null)
  11885. {
  11886. msid = msid.replace(/[\{,\}]/g,"");
  11887. elem.c('parameter');
  11888. elem.attrs({name: "msid", value:msid});
  11889. elem.up();
  11890. elem.c('parameter');
  11891. elem.attrs({name: "mslabel", value:msid});
  11892. elem.up();
  11893. elem.c('parameter');
  11894. elem.attrs({name: "label", value:msid});
  11895. elem.up();
  11896. elem.up();
  11897. }
  11898. }
  11899. // XEP-0339 handle ssrc-group attributes
  11900. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  11901. ssrc_group_lines.forEach(function(line) {
  11902. idx = line.indexOf(' ');
  11903. var semantics = line.substr(0, idx).substr(13);
  11904. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11905. if (ssrcs.length != 0) {
  11906. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11907. ssrcs.forEach(function(ssrc) {
  11908. elem.c('source', { ssrc: ssrc })
  11909. .up();
  11910. });
  11911. elem.up();
  11912. }
  11913. });
  11914. }
  11915. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  11916. elem.c('rtcp-mux').up();
  11917. }
  11918. // XEP-0293 -- map a=rtcp-fb:*
  11919. this.RtcpFbToJingle(i, elem, '*');
  11920. // XEP-0294
  11921. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  11922. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  11923. for (j = 0; j < lines.length; j++) {
  11924. tmp = SDPUtil.parse_extmap(lines[j]);
  11925. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  11926. uri: tmp.uri,
  11927. id: tmp.value });
  11928. if (tmp.hasOwnProperty('direction')) {
  11929. switch (tmp.direction) {
  11930. case 'sendonly':
  11931. elem.attrs({senders: 'responder'});
  11932. break;
  11933. case 'recvonly':
  11934. elem.attrs({senders: 'initiator'});
  11935. break;
  11936. case 'sendrecv':
  11937. elem.attrs({senders: 'both'});
  11938. break;
  11939. case 'inactive':
  11940. elem.attrs({senders: 'none'});
  11941. break;
  11942. }
  11943. }
  11944. // TODO: handle params
  11945. elem.up();
  11946. }
  11947. }
  11948. elem.up(); // end of description
  11949. }
  11950. // map ice-ufrag/pwd, dtls fingerprint, candidates
  11951. this.TransportToJingle(i, elem);
  11952. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  11953. elem.attrs({senders: 'both'});
  11954. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  11955. elem.attrs({senders: 'initiator'});
  11956. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  11957. elem.attrs({senders: 'responder'});
  11958. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  11959. elem.attrs({senders: 'none'});
  11960. }
  11961. if (mline.port == '0') {
  11962. // estos hack to reject an m-line
  11963. elem.attrs({senders: 'rejected'});
  11964. }
  11965. elem.up(); // end of content
  11966. }
  11967. elem.up();
  11968. return elem;
  11969. };
  11970. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  11971. var i = mediaindex;
  11972. var tmp;
  11973. var self = this;
  11974. elem.c('transport');
  11975. // XEP-0343 DTLS/SCTP
  11976. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  11977. {
  11978. var sctpmap = SDPUtil.find_line(
  11979. this.media[i], 'a=sctpmap:', self.session);
  11980. if (sctpmap)
  11981. {
  11982. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  11983. elem.c('sctpmap',
  11984. {
  11985. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  11986. number: sctpAttrs[0], /* SCTP port */
  11987. protocol: sctpAttrs[1], /* protocol */
  11988. });
  11989. // Optional stream count attribute
  11990. if (sctpAttrs.length > 2)
  11991. elem.attrs({ streams: sctpAttrs[2]});
  11992. elem.up();
  11993. }
  11994. }
  11995. // XEP-0320
  11996. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  11997. fingerprints.forEach(function(line) {
  11998. tmp = SDPUtil.parse_fingerprint(line);
  11999. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  12000. elem.c('fingerprint').t(tmp.fingerprint);
  12001. delete tmp.fingerprint;
  12002. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  12003. if (line) {
  12004. tmp.setup = line.substr(8);
  12005. }
  12006. elem.attrs(tmp);
  12007. elem.up(); // end of fingerprint
  12008. });
  12009. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  12010. if (tmp) {
  12011. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12012. elem.attrs(tmp);
  12013. // XEP-0176
  12014. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  12015. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  12016. lines.forEach(function (line) {
  12017. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  12018. });
  12019. }
  12020. }
  12021. elem.up(); // end of transport
  12022. }
  12023. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  12024. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  12025. lines.forEach(function (line) {
  12026. var tmp = SDPUtil.parse_rtcpfb(line);
  12027. if (tmp.type == 'trr-int') {
  12028. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  12029. elem.up();
  12030. } else {
  12031. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  12032. if (tmp.params.length > 0) {
  12033. elem.attrs({'subtype': tmp.params[0]});
  12034. }
  12035. elem.up();
  12036. }
  12037. });
  12038. };
  12039. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  12040. var media = '';
  12041. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12042. if (tmp.length) {
  12043. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  12044. if (tmp.attr('value')) {
  12045. media += tmp.attr('value');
  12046. } else {
  12047. media += '0';
  12048. }
  12049. media += '\r\n';
  12050. }
  12051. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12052. tmp.each(function () {
  12053. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  12054. if ($(this).attr('subtype')) {
  12055. media += ' ' + $(this).attr('subtype');
  12056. }
  12057. media += '\r\n';
  12058. });
  12059. return media;
  12060. };
  12061. // construct an SDP from a jingle stanza
  12062. SDP.prototype.fromJingle = function (jingle) {
  12063. var self = this;
  12064. this.raw = 'v=0\r\n' +
  12065. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12066. 's=-\r\n' +
  12067. 't=0 0\r\n';
  12068. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  12069. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  12070. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  12071. var contents = $(group).find('>content').map(function (idx, content) {
  12072. return content.getAttribute('name');
  12073. }).get();
  12074. if (contents.length > 0) {
  12075. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  12076. }
  12077. });
  12078. }
  12079. this.session = this.raw;
  12080. jingle.find('>content').each(function () {
  12081. var m = self.jingle2media($(this));
  12082. self.media.push(m);
  12083. });
  12084. // reconstruct msid-semantic -- apparently not necessary
  12085. /*
  12086. var msid = SDPUtil.parse_ssrc(this.raw);
  12087. if (msid.hasOwnProperty('mslabel')) {
  12088. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  12089. }
  12090. */
  12091. this.raw = this.session + this.media.join('');
  12092. };
  12093. // translate a jingle content element into an an SDP media part
  12094. SDP.prototype.jingle2media = function (content) {
  12095. var media = '',
  12096. desc = content.find('description'),
  12097. ssrc = desc.attr('ssrc'),
  12098. self = this,
  12099. tmp;
  12100. var sctp = content.find(
  12101. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  12102. tmp = { media: desc.attr('media') };
  12103. tmp.port = '1';
  12104. if (content.attr('senders') == 'rejected') {
  12105. // estos hack to reject an m-line.
  12106. tmp.port = '0';
  12107. }
  12108. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  12109. if (sctp.length)
  12110. tmp.proto = 'DTLS/SCTP';
  12111. else
  12112. tmp.proto = 'RTP/SAVPF';
  12113. } else {
  12114. tmp.proto = 'RTP/AVPF';
  12115. }
  12116. if (!sctp.length)
  12117. {
  12118. tmp.fmt = desc.find('payload-type').map(
  12119. function () { return this.getAttribute('id'); }).get();
  12120. media += SDPUtil.build_mline(tmp) + '\r\n';
  12121. }
  12122. else
  12123. {
  12124. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  12125. media += 'a=sctpmap:' + sctp.attr('number') +
  12126. ' ' + sctp.attr('protocol');
  12127. var streamCount = sctp.attr('streams');
  12128. if (streamCount)
  12129. media += ' ' + streamCount + '\r\n';
  12130. else
  12131. media += '\r\n';
  12132. }
  12133. media += 'c=IN IP4 0.0.0.0\r\n';
  12134. if (!sctp.length)
  12135. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  12136. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  12137. if (tmp.length) {
  12138. if (tmp.attr('ufrag')) {
  12139. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  12140. }
  12141. if (tmp.attr('pwd')) {
  12142. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  12143. }
  12144. tmp.find('>fingerprint').each(function () {
  12145. // FIXME: check namespace at some point
  12146. media += 'a=fingerprint:' + this.getAttribute('hash');
  12147. media += ' ' + $(this).text();
  12148. media += '\r\n';
  12149. if (this.getAttribute('setup')) {
  12150. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  12151. }
  12152. });
  12153. }
  12154. switch (content.attr('senders')) {
  12155. case 'initiator':
  12156. media += 'a=sendonly\r\n';
  12157. break;
  12158. case 'responder':
  12159. media += 'a=recvonly\r\n';
  12160. break;
  12161. case 'none':
  12162. media += 'a=inactive\r\n';
  12163. break;
  12164. case 'both':
  12165. media += 'a=sendrecv\r\n';
  12166. break;
  12167. }
  12168. media += 'a=mid:' + content.attr('name') + '\r\n';
  12169. // <description><rtcp-mux/></description>
  12170. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  12171. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  12172. if (desc.find('rtcp-mux').length) {
  12173. media += 'a=rtcp-mux\r\n';
  12174. }
  12175. if (desc.find('encryption').length) {
  12176. desc.find('encryption>crypto').each(function () {
  12177. media += 'a=crypto:' + this.getAttribute('tag');
  12178. media += ' ' + this.getAttribute('crypto-suite');
  12179. media += ' ' + this.getAttribute('key-params');
  12180. if (this.getAttribute('session-params')) {
  12181. media += ' ' + this.getAttribute('session-params');
  12182. }
  12183. media += '\r\n';
  12184. });
  12185. }
  12186. desc.find('payload-type').each(function () {
  12187. media += SDPUtil.build_rtpmap(this) + '\r\n';
  12188. if ($(this).find('>parameter').length) {
  12189. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  12190. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  12191. media += '\r\n';
  12192. }
  12193. // xep-0293
  12194. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  12195. });
  12196. // xep-0293
  12197. media += self.RtcpFbFromJingle(desc, '*');
  12198. // xep-0294
  12199. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  12200. tmp.each(function () {
  12201. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  12202. });
  12203. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  12204. media += SDPUtil.candidateFromJingle(this);
  12205. });
  12206. // XEP-0339 handle ssrc-group attributes
  12207. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12208. var semantics = this.getAttribute('semantics');
  12209. var ssrcs = $(this).find('>source').map(function() {
  12210. return this.getAttribute('ssrc');
  12211. }).get();
  12212. if (ssrcs.length != 0) {
  12213. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12214. }
  12215. });
  12216. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12217. tmp.each(function () {
  12218. var ssrc = this.getAttribute('ssrc');
  12219. $(this).find('>parameter').each(function () {
  12220. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  12221. if (this.getAttribute('value') && this.getAttribute('value').length)
  12222. media += ':' + this.getAttribute('value');
  12223. media += '\r\n';
  12224. });
  12225. });
  12226. return media;
  12227. };
  12228. module.exports = SDP;
  12229. },{"./SDPUtil":51}],50:[function(require,module,exports){
  12230. function SDPDiffer(mySDP, otherSDP) {
  12231. this.mySDP = mySDP;
  12232. this.otherSDP = otherSDP;
  12233. }
  12234. /**
  12235. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  12236. * @param otherSdp the other SDP to check ssrc with.
  12237. */
  12238. SDPDiffer.prototype.getNewMedia = function() {
  12239. // this could be useful in Array.prototype.
  12240. function arrayEquals(array) {
  12241. // if the other array is a falsy value, return
  12242. if (!array)
  12243. return false;
  12244. // compare lengths - can save a lot of time
  12245. if (this.length != array.length)
  12246. return false;
  12247. for (var i = 0, l=this.length; i < l; i++) {
  12248. // Check if we have nested arrays
  12249. if (this[i] instanceof Array && array[i] instanceof Array) {
  12250. // recurse into the nested arrays
  12251. if (!this[i].equals(array[i]))
  12252. return false;
  12253. }
  12254. else if (this[i] != array[i]) {
  12255. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12256. return false;
  12257. }
  12258. }
  12259. return true;
  12260. }
  12261. var myMedias = this.mySDP.getMediaSsrcMap();
  12262. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12263. var newMedia = {};
  12264. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12265. var myMedia = myMedias[othersMediaIdx];
  12266. var othersMedia = othersMedias[othersMediaIdx];
  12267. if(!myMedia && othersMedia) {
  12268. // Add whole channel
  12269. newMedia[othersMediaIdx] = othersMedia;
  12270. return;
  12271. }
  12272. // Look for new ssrcs accross the channel
  12273. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12274. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12275. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12276. if(!newMedia[othersMediaIdx]){
  12277. newMedia[othersMediaIdx] = {
  12278. mediaindex: othersMedia.mediaindex,
  12279. mid: othersMedia.mid,
  12280. ssrcs: {},
  12281. ssrcGroups: []
  12282. };
  12283. }
  12284. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12285. }
  12286. });
  12287. // Look for new ssrc groups across the channels
  12288. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12289. // try to match the other ssrc-group with an ssrc-group of ours
  12290. var matched = false;
  12291. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12292. var mySsrcGroup = myMedia.ssrcGroups[i];
  12293. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12294. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12295. matched = true;
  12296. break;
  12297. }
  12298. }
  12299. if (!matched) {
  12300. // Allocate channel if we've found an ssrc-group that doesn't
  12301. // exist in our channel
  12302. if(!newMedia[othersMediaIdx]){
  12303. newMedia[othersMediaIdx] = {
  12304. mediaindex: othersMedia.mediaindex,
  12305. mid: othersMedia.mid,
  12306. ssrcs: {},
  12307. ssrcGroups: []
  12308. };
  12309. }
  12310. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12311. }
  12312. });
  12313. });
  12314. return newMedia;
  12315. };
  12316. /**
  12317. * Sends SSRC update IQ.
  12318. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12319. * @param sid session identifier that will be put into the IQ.
  12320. * @param initiator initiator identifier.
  12321. * @param toJid destination Jid
  12322. * @param isAdd indicates if this is remove or add operation.
  12323. */
  12324. SDPDiffer.prototype.toJingle = function(modify) {
  12325. var sdpMediaSsrcs = this.getNewMedia();
  12326. var self = this;
  12327. // FIXME: only announce video ssrcs since we mix audio and dont need
  12328. // the audio ssrcs therefore
  12329. var modified = false;
  12330. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12331. modified = true;
  12332. var media = sdpMediaSsrcs[mediaindex];
  12333. modify.c('content', {name: media.mid});
  12334. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12335. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12336. // generate sources from lines
  12337. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12338. var mediaSsrc = media.ssrcs[ssrcNum];
  12339. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12340. modify.attrs({ssrc: mediaSsrc.ssrc});
  12341. // iterate over ssrc lines
  12342. mediaSsrc.lines.forEach(function (line) {
  12343. var idx = line.indexOf(' ');
  12344. var kv = line.substr(idx + 1);
  12345. modify.c('parameter');
  12346. if (kv.indexOf(':') == -1) {
  12347. modify.attrs({ name: kv });
  12348. } else {
  12349. modify.attrs({ name: kv.split(':', 2)[0] });
  12350. modify.attrs({ value: kv.split(':', 2)[1] });
  12351. }
  12352. modify.up(); // end of parameter
  12353. });
  12354. modify.up(); // end of source
  12355. });
  12356. // generate source groups from lines
  12357. media.ssrcGroups.forEach(function(ssrcGroup) {
  12358. if (ssrcGroup.ssrcs.length != 0) {
  12359. modify.c('ssrc-group', {
  12360. semantics: ssrcGroup.semantics,
  12361. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12362. });
  12363. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12364. modify.c('source', { ssrc: ssrc })
  12365. .up(); // end of source
  12366. });
  12367. modify.up(); // end of ssrc-group
  12368. }
  12369. });
  12370. modify.up(); // end of description
  12371. modify.up(); // end of content
  12372. });
  12373. return modified;
  12374. };
  12375. module.exports = SDPDiffer;
  12376. },{}],51:[function(require,module,exports){
  12377. SDPUtil = {
  12378. iceparams: function (mediadesc, sessiondesc) {
  12379. var data = null;
  12380. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  12381. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  12382. data = {
  12383. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  12384. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  12385. };
  12386. }
  12387. return data;
  12388. },
  12389. parse_iceufrag: function (line) {
  12390. return line.substring(12);
  12391. },
  12392. build_iceufrag: function (frag) {
  12393. return 'a=ice-ufrag:' + frag;
  12394. },
  12395. parse_icepwd: function (line) {
  12396. return line.substring(10);
  12397. },
  12398. build_icepwd: function (pwd) {
  12399. return 'a=ice-pwd:' + pwd;
  12400. },
  12401. parse_mid: function (line) {
  12402. return line.substring(6);
  12403. },
  12404. parse_mline: function (line) {
  12405. var parts = line.substring(2).split(' '),
  12406. data = {};
  12407. data.media = parts.shift();
  12408. data.port = parts.shift();
  12409. data.proto = parts.shift();
  12410. if (parts[parts.length - 1] === '') { // trailing whitespace
  12411. parts.pop();
  12412. }
  12413. data.fmt = parts;
  12414. return data;
  12415. },
  12416. build_mline: function (mline) {
  12417. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  12418. },
  12419. parse_rtpmap: function (line) {
  12420. var parts = line.substring(9).split(' '),
  12421. data = {};
  12422. data.id = parts.shift();
  12423. parts = parts[0].split('/');
  12424. data.name = parts.shift();
  12425. data.clockrate = parts.shift();
  12426. data.channels = parts.length ? parts.shift() : '1';
  12427. return data;
  12428. },
  12429. /**
  12430. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  12431. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  12432. * @returns [SCTP port number, protocol, streams]
  12433. */
  12434. parse_sctpmap: function (line)
  12435. {
  12436. var parts = line.substring(10).split(' ');
  12437. var sctpPort = parts[0];
  12438. var protocol = parts[1];
  12439. // Stream count is optional
  12440. var streamCount = parts.length > 2 ? parts[2] : null;
  12441. return [sctpPort, protocol, streamCount];// SCTP port
  12442. },
  12443. build_rtpmap: function (el) {
  12444. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  12445. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  12446. line += '/' + el.getAttribute('channels');
  12447. }
  12448. return line;
  12449. },
  12450. parse_crypto: function (line) {
  12451. var parts = line.substring(9).split(' '),
  12452. data = {};
  12453. data.tag = parts.shift();
  12454. data['crypto-suite'] = parts.shift();
  12455. data['key-params'] = parts.shift();
  12456. if (parts.length) {
  12457. data['session-params'] = parts.join(' ');
  12458. }
  12459. return data;
  12460. },
  12461. parse_fingerprint: function (line) { // RFC 4572
  12462. var parts = line.substring(14).split(' '),
  12463. data = {};
  12464. data.hash = parts.shift();
  12465. data.fingerprint = parts.shift();
  12466. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  12467. return data;
  12468. },
  12469. parse_fmtp: function (line) {
  12470. var parts = line.split(' '),
  12471. i, key, value,
  12472. data = [];
  12473. parts.shift();
  12474. parts = parts.join(' ').split(';');
  12475. for (i = 0; i < parts.length; i++) {
  12476. key = parts[i].split('=')[0];
  12477. while (key.length && key[0] == ' ') {
  12478. key = key.substring(1);
  12479. }
  12480. value = parts[i].split('=')[1];
  12481. if (key && value) {
  12482. data.push({name: key, value: value});
  12483. } else if (key) {
  12484. // rfc 4733 (DTMF) style stuff
  12485. data.push({name: '', value: key});
  12486. }
  12487. }
  12488. return data;
  12489. },
  12490. parse_icecandidate: function (line) {
  12491. var candidate = {},
  12492. elems = line.split(' ');
  12493. candidate.foundation = elems[0].substring(12);
  12494. candidate.component = elems[1];
  12495. candidate.protocol = elems[2].toLowerCase();
  12496. candidate.priority = elems[3];
  12497. candidate.ip = elems[4];
  12498. candidate.port = elems[5];
  12499. // elems[6] => "typ"
  12500. candidate.type = elems[7];
  12501. candidate.generation = 0; // default value, may be overwritten below
  12502. for (var i = 8; i < elems.length; i += 2) {
  12503. switch (elems[i]) {
  12504. case 'raddr':
  12505. candidate['rel-addr'] = elems[i + 1];
  12506. break;
  12507. case 'rport':
  12508. candidate['rel-port'] = elems[i + 1];
  12509. break;
  12510. case 'generation':
  12511. candidate.generation = elems[i + 1];
  12512. break;
  12513. case 'tcptype':
  12514. candidate.tcptype = elems[i + 1];
  12515. break;
  12516. default: // TODO
  12517. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12518. }
  12519. }
  12520. candidate.network = '1';
  12521. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12522. return candidate;
  12523. },
  12524. build_icecandidate: function (cand) {
  12525. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  12526. line += ' ';
  12527. switch (cand.type) {
  12528. case 'srflx':
  12529. case 'prflx':
  12530. case 'relay':
  12531. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  12532. line += 'raddr';
  12533. line += ' ';
  12534. line += cand['rel-addr'];
  12535. line += ' ';
  12536. line += 'rport';
  12537. line += ' ';
  12538. line += cand['rel-port'];
  12539. line += ' ';
  12540. }
  12541. break;
  12542. }
  12543. if (cand.hasOwnAttribute('tcptype')) {
  12544. line += 'tcptype';
  12545. line += ' ';
  12546. line += cand.tcptype;
  12547. line += ' ';
  12548. }
  12549. line += 'generation';
  12550. line += ' ';
  12551. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  12552. return line;
  12553. },
  12554. parse_ssrc: function (desc) {
  12555. // proprietary mapping of a=ssrc lines
  12556. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  12557. // and parse according to that
  12558. var lines = desc.split('\r\n'),
  12559. data = {};
  12560. for (var i = 0; i < lines.length; i++) {
  12561. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  12562. var idx = lines[i].indexOf(' ');
  12563. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  12564. }
  12565. }
  12566. return data;
  12567. },
  12568. parse_rtcpfb: function (line) {
  12569. var parts = line.substr(10).split(' ');
  12570. var data = {};
  12571. data.pt = parts.shift();
  12572. data.type = parts.shift();
  12573. data.params = parts;
  12574. return data;
  12575. },
  12576. parse_extmap: function (line) {
  12577. var parts = line.substr(9).split(' ');
  12578. var data = {};
  12579. data.value = parts.shift();
  12580. if (data.value.indexOf('/') != -1) {
  12581. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  12582. data.value = data.value.substr(0, data.value.indexOf('/'));
  12583. } else {
  12584. data.direction = 'both';
  12585. }
  12586. data.uri = parts.shift();
  12587. data.params = parts;
  12588. return data;
  12589. },
  12590. find_line: function (haystack, needle, sessionpart) {
  12591. var lines = haystack.split('\r\n');
  12592. for (var i = 0; i < lines.length; i++) {
  12593. if (lines[i].substring(0, needle.length) == needle) {
  12594. return lines[i];
  12595. }
  12596. }
  12597. if (!sessionpart) {
  12598. return false;
  12599. }
  12600. // search session part
  12601. lines = sessionpart.split('\r\n');
  12602. for (var j = 0; j < lines.length; j++) {
  12603. if (lines[j].substring(0, needle.length) == needle) {
  12604. return lines[j];
  12605. }
  12606. }
  12607. return false;
  12608. },
  12609. find_lines: function (haystack, needle, sessionpart) {
  12610. var lines = haystack.split('\r\n'),
  12611. needles = [];
  12612. for (var i = 0; i < lines.length; i++) {
  12613. if (lines[i].substring(0, needle.length) == needle)
  12614. needles.push(lines[i]);
  12615. }
  12616. if (needles.length || !sessionpart) {
  12617. return needles;
  12618. }
  12619. // search session part
  12620. lines = sessionpart.split('\r\n');
  12621. for (var j = 0; j < lines.length; j++) {
  12622. if (lines[j].substring(0, needle.length) == needle) {
  12623. needles.push(lines[j]);
  12624. }
  12625. }
  12626. return needles;
  12627. },
  12628. candidateToJingle: function (line) {
  12629. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  12630. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  12631. if (line.indexOf('candidate:') === 0) {
  12632. line = 'a=' + line;
  12633. } else if (line.substring(0, 12) != 'a=candidate:') {
  12634. console.log('parseCandidate called with a line that is not a candidate line');
  12635. console.log(line);
  12636. return null;
  12637. }
  12638. if (line.substring(line.length - 2) == '\r\n') // chomp it
  12639. line = line.substring(0, line.length - 2);
  12640. var candidate = {},
  12641. elems = line.split(' '),
  12642. i;
  12643. if (elems[6] != 'typ') {
  12644. console.log('did not find typ in the right place');
  12645. console.log(line);
  12646. return null;
  12647. }
  12648. candidate.foundation = elems[0].substring(12);
  12649. candidate.component = elems[1];
  12650. candidate.protocol = elems[2].toLowerCase();
  12651. candidate.priority = elems[3];
  12652. candidate.ip = elems[4];
  12653. candidate.port = elems[5];
  12654. // elems[6] => "typ"
  12655. candidate.type = elems[7];
  12656. candidate.generation = '0'; // default, may be overwritten below
  12657. for (i = 8; i < elems.length; i += 2) {
  12658. switch (elems[i]) {
  12659. case 'raddr':
  12660. candidate['rel-addr'] = elems[i + 1];
  12661. break;
  12662. case 'rport':
  12663. candidate['rel-port'] = elems[i + 1];
  12664. break;
  12665. case 'generation':
  12666. candidate.generation = elems[i + 1];
  12667. break;
  12668. case 'tcptype':
  12669. candidate.tcptype = elems[i + 1];
  12670. break;
  12671. default: // TODO
  12672. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12673. }
  12674. }
  12675. candidate.network = '1';
  12676. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12677. return candidate;
  12678. },
  12679. candidateFromJingle: function (cand) {
  12680. var line = 'a=candidate:';
  12681. line += cand.getAttribute('foundation');
  12682. line += ' ';
  12683. line += cand.getAttribute('component');
  12684. line += ' ';
  12685. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  12686. line += ' ';
  12687. line += cand.getAttribute('priority');
  12688. line += ' ';
  12689. line += cand.getAttribute('ip');
  12690. line += ' ';
  12691. line += cand.getAttribute('port');
  12692. line += ' ';
  12693. line += 'typ';
  12694. line += ' ' + cand.getAttribute('type');
  12695. line += ' ';
  12696. switch (cand.getAttribute('type')) {
  12697. case 'srflx':
  12698. case 'prflx':
  12699. case 'relay':
  12700. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  12701. line += 'raddr';
  12702. line += ' ';
  12703. line += cand.getAttribute('rel-addr');
  12704. line += ' ';
  12705. line += 'rport';
  12706. line += ' ';
  12707. line += cand.getAttribute('rel-port');
  12708. line += ' ';
  12709. }
  12710. break;
  12711. }
  12712. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  12713. line += 'tcptype';
  12714. line += ' ';
  12715. line += cand.getAttribute('tcptype');
  12716. line += ' ';
  12717. }
  12718. line += 'generation';
  12719. line += ' ';
  12720. line += cand.getAttribute('generation') || '0';
  12721. return line + '\r\n';
  12722. }
  12723. };
  12724. module.exports = SDPUtil;
  12725. },{}],52:[function(require,module,exports){
  12726. function TraceablePeerConnection(ice_config, constraints) {
  12727. var self = this;
  12728. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  12729. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  12730. this.updateLog = [];
  12731. this.stats = {};
  12732. this.statsinterval = null;
  12733. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  12734. // override as desired
  12735. this.trace = function (what, info) {
  12736. //console.warn('WTRACE', what, info);
  12737. self.updateLog.push({
  12738. time: new Date(),
  12739. type: what,
  12740. value: info || ""
  12741. });
  12742. };
  12743. this.onicecandidate = null;
  12744. this.peerconnection.onicecandidate = function (event) {
  12745. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  12746. if (self.onicecandidate !== null) {
  12747. self.onicecandidate(event);
  12748. }
  12749. };
  12750. this.onaddstream = null;
  12751. this.peerconnection.onaddstream = function (event) {
  12752. self.trace('onaddstream', event.stream.id);
  12753. if (self.onaddstream !== null) {
  12754. self.onaddstream(event);
  12755. }
  12756. };
  12757. this.onremovestream = null;
  12758. this.peerconnection.onremovestream = function (event) {
  12759. self.trace('onremovestream', event.stream.id);
  12760. if (self.onremovestream !== null) {
  12761. self.onremovestream(event);
  12762. }
  12763. };
  12764. this.onsignalingstatechange = null;
  12765. this.peerconnection.onsignalingstatechange = function (event) {
  12766. self.trace('onsignalingstatechange', self.signalingState);
  12767. if (self.onsignalingstatechange !== null) {
  12768. self.onsignalingstatechange(event);
  12769. }
  12770. };
  12771. this.oniceconnectionstatechange = null;
  12772. this.peerconnection.oniceconnectionstatechange = function (event) {
  12773. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12774. if (self.oniceconnectionstatechange !== null) {
  12775. self.oniceconnectionstatechange(event);
  12776. }
  12777. };
  12778. this.onnegotiationneeded = null;
  12779. this.peerconnection.onnegotiationneeded = function (event) {
  12780. self.trace('onnegotiationneeded');
  12781. if (self.onnegotiationneeded !== null) {
  12782. self.onnegotiationneeded(event);
  12783. }
  12784. };
  12785. self.ondatachannel = null;
  12786. this.peerconnection.ondatachannel = function (event) {
  12787. self.trace('ondatachannel', event);
  12788. if (self.ondatachannel !== null) {
  12789. self.ondatachannel(event);
  12790. }
  12791. };
  12792. if (!navigator.mozGetUserMedia && this.maxstats) {
  12793. this.statsinterval = window.setInterval(function() {
  12794. self.peerconnection.getStats(function(stats) {
  12795. var results = stats.result();
  12796. for (var i = 0; i < results.length; ++i) {
  12797. //console.log(results[i].type, results[i].id, results[i].names())
  12798. var now = new Date();
  12799. results[i].names().forEach(function (name) {
  12800. var id = results[i].id + '-' + name;
  12801. if (!self.stats[id]) {
  12802. self.stats[id] = {
  12803. startTime: now,
  12804. endTime: now,
  12805. values: [],
  12806. times: []
  12807. };
  12808. }
  12809. self.stats[id].values.push(results[i].stat(name));
  12810. self.stats[id].times.push(now.getTime());
  12811. if (self.stats[id].values.length > self.maxstats) {
  12812. self.stats[id].values.shift();
  12813. self.stats[id].times.shift();
  12814. }
  12815. self.stats[id].endTime = now;
  12816. });
  12817. }
  12818. });
  12819. }, 1000);
  12820. }
  12821. };
  12822. dumpSDP = function(description) {
  12823. return 'type: ' + description.type + '\r\n' + description.sdp;
  12824. }
  12825. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  12826. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  12827. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  12828. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  12829. var publicLocalDescription = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  12830. return publicLocalDescription;
  12831. });
  12832. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  12833. var publicRemoteDescription = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  12834. return publicRemoteDescription;
  12835. });
  12836. }
  12837. TraceablePeerConnection.prototype.addStream = function (stream) {
  12838. this.trace('addStream', stream.id);
  12839. APP.simulcast.resetSender();
  12840. try
  12841. {
  12842. this.peerconnection.addStream(stream);
  12843. }
  12844. catch (e)
  12845. {
  12846. console.error(e);
  12847. return;
  12848. }
  12849. };
  12850. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  12851. this.trace('removeStream', stream.id);
  12852. APP.simulcast.resetSender();
  12853. if(stopStreams) {
  12854. stream.getAudioTracks().forEach(function (track) {
  12855. track.stop();
  12856. });
  12857. stream.getVideoTracks().forEach(function (track) {
  12858. track.stop();
  12859. });
  12860. }
  12861. this.peerconnection.removeStream(stream);
  12862. };
  12863. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  12864. this.trace('createDataChannel', label, opts);
  12865. return this.peerconnection.createDataChannel(label, opts);
  12866. };
  12867. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  12868. var self = this;
  12869. description = APP.simulcast.transformLocalDescription(description);
  12870. this.trace('setLocalDescription', dumpSDP(description));
  12871. this.peerconnection.setLocalDescription(description,
  12872. function () {
  12873. self.trace('setLocalDescriptionOnSuccess');
  12874. successCallback();
  12875. },
  12876. function (err) {
  12877. self.trace('setLocalDescriptionOnFailure', err);
  12878. failureCallback(err);
  12879. }
  12880. );
  12881. /*
  12882. if (this.statsinterval === null && this.maxstats > 0) {
  12883. // start gathering stats
  12884. }
  12885. */
  12886. };
  12887. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  12888. var self = this;
  12889. description = APP.simulcast.transformRemoteDescription(description);
  12890. this.trace('setRemoteDescription', dumpSDP(description));
  12891. this.peerconnection.setRemoteDescription(description,
  12892. function () {
  12893. self.trace('setRemoteDescriptionOnSuccess');
  12894. successCallback();
  12895. },
  12896. function (err) {
  12897. self.trace('setRemoteDescriptionOnFailure', err);
  12898. failureCallback(err);
  12899. }
  12900. );
  12901. /*
  12902. if (this.statsinterval === null && this.maxstats > 0) {
  12903. // start gathering stats
  12904. }
  12905. */
  12906. };
  12907. TraceablePeerConnection.prototype.close = function () {
  12908. this.trace('stop');
  12909. if (this.statsinterval !== null) {
  12910. window.clearInterval(this.statsinterval);
  12911. this.statsinterval = null;
  12912. }
  12913. this.peerconnection.close();
  12914. };
  12915. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  12916. var self = this;
  12917. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  12918. this.peerconnection.createOffer(
  12919. function (offer) {
  12920. self.trace('createOfferOnSuccess', dumpSDP(offer));
  12921. successCallback(offer);
  12922. },
  12923. function(err) {
  12924. self.trace('createOfferOnFailure', err);
  12925. failureCallback(err);
  12926. },
  12927. constraints
  12928. );
  12929. };
  12930. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  12931. var self = this;
  12932. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  12933. this.peerconnection.createAnswer(
  12934. function (answer) {
  12935. answer = APP.simulcast.transformAnswer(answer);
  12936. self.trace('createAnswerOnSuccess', dumpSDP(answer));
  12937. successCallback(answer);
  12938. },
  12939. function(err) {
  12940. self.trace('createAnswerOnFailure', err);
  12941. failureCallback(err);
  12942. },
  12943. constraints
  12944. );
  12945. };
  12946. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  12947. var self = this;
  12948. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  12949. this.peerconnection.addIceCandidate(candidate);
  12950. /* maybe later
  12951. this.peerconnection.addIceCandidate(candidate,
  12952. function () {
  12953. self.trace('addIceCandidateOnSuccess');
  12954. successCallback();
  12955. },
  12956. function (err) {
  12957. self.trace('addIceCandidateOnFailure', err);
  12958. failureCallback(err);
  12959. }
  12960. );
  12961. */
  12962. };
  12963. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  12964. if (navigator.mozGetUserMedia) {
  12965. // ignore for now...
  12966. if(!errback)
  12967. errback = function () {
  12968. }
  12969. this.peerconnection.getStats(null,callback,errback);
  12970. } else {
  12971. this.peerconnection.getStats(callback);
  12972. }
  12973. };
  12974. module.exports = TraceablePeerConnection;
  12975. },{}],53:[function(require,module,exports){
  12976. /* global $, $iq, APP, config, connection, UI, messageHandler,
  12977. roomName, sessionTerminated, Strophe, Util */
  12978. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  12979. var Settings = require("../settings/Settings");
  12980. var AuthenticationEvents
  12981. = require("../../service/authentication/AuthenticationEvents");
  12982. /**
  12983. * Contains logic responsible for enabling/disabling functionality available
  12984. * only to moderator users.
  12985. */
  12986. var connection = null;
  12987. var focusUserJid;
  12988. function createExpBackoffTimer(step) {
  12989. var count = 1;
  12990. return function (reset) {
  12991. // Reset call
  12992. if (reset) {
  12993. count = 1;
  12994. return;
  12995. }
  12996. // Calculate next timeout
  12997. var timeout = Math.pow(2, count - 1);
  12998. count += 1;
  12999. return timeout * step;
  13000. };
  13001. }
  13002. var getNextTimeout = createExpBackoffTimer(1000);
  13003. var getNextErrorTimeout = createExpBackoffTimer(1000);
  13004. // External authentication stuff
  13005. var externalAuthEnabled = false;
  13006. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  13007. // it will be enabled automatically if focus detects the component through
  13008. // service discovery.
  13009. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  13010. var eventEmitter = null;
  13011. var Moderator = {
  13012. isModerator: function () {
  13013. return connection && connection.emuc.isModerator();
  13014. },
  13015. isPeerModerator: function (peerJid) {
  13016. return connection &&
  13017. connection.emuc.getMemberRole(peerJid) === 'moderator';
  13018. },
  13019. isExternalAuthEnabled: function () {
  13020. return externalAuthEnabled;
  13021. },
  13022. isSipGatewayEnabled: function () {
  13023. return sipGatewayEnabled;
  13024. },
  13025. setConnection: function (con) {
  13026. connection = con;
  13027. },
  13028. init: function (xmpp, emitter) {
  13029. this.xmppService = xmpp;
  13030. eventEmitter = emitter;
  13031. // Message listener that talks to POPUP window
  13032. function listener(event) {
  13033. if (event.data && event.data.sessionId) {
  13034. if (event.origin !== window.location.origin) {
  13035. console.warn(
  13036. "Ignoring sessionId from different origin: " + event.origin);
  13037. return;
  13038. }
  13039. localStorage.setItem('sessionId', event.data.sessionId);
  13040. // After popup is closed we will authenticate
  13041. }
  13042. }
  13043. // Register
  13044. if (window.addEventListener) {
  13045. window.addEventListener("message", listener, false);
  13046. } else {
  13047. window.attachEvent("onmessage", listener);
  13048. }
  13049. },
  13050. onMucLeft: function (jid) {
  13051. console.info("Someone left is it focus ? " + jid);
  13052. var resource = Strophe.getResourceFromJid(jid);
  13053. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  13054. console.info(
  13055. "Focus has left the room - leaving conference");
  13056. //hangUp();
  13057. // We'd rather reload to have everything re-initialized
  13058. // FIXME: show some message before reload
  13059. location.reload();
  13060. }
  13061. },
  13062. setFocusUserJid: function (focusJid) {
  13063. if (!focusUserJid) {
  13064. focusUserJid = focusJid;
  13065. console.info("Focus jid set to: " + focusUserJid);
  13066. }
  13067. },
  13068. getFocusUserJid: function () {
  13069. return focusUserJid;
  13070. },
  13071. getFocusComponent: function () {
  13072. // Get focus component address
  13073. var focusComponent = config.hosts.focus;
  13074. // If not specified use default: 'focus.domain'
  13075. if (!focusComponent) {
  13076. focusComponent = 'focus.' + config.hosts.domain;
  13077. }
  13078. return focusComponent;
  13079. },
  13080. createConferenceIq: function (roomName) {
  13081. // Generate create conference IQ
  13082. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13083. // Session Id used for authentication
  13084. var sessionId = localStorage.getItem('sessionId');
  13085. var machineUID = Settings.getSettings().uid;
  13086. console.info(
  13087. "Session ID: " + sessionId + " machine UID: " + machineUID);
  13088. elem.c('conference', {
  13089. xmlns: 'http://jitsi.org/protocol/focus',
  13090. room: roomName,
  13091. 'machine-uid': machineUID
  13092. });
  13093. if (sessionId) {
  13094. elem.attrs({ 'session-id': sessionId});
  13095. }
  13096. if (config.hosts.bridge !== undefined) {
  13097. elem.c(
  13098. 'property',
  13099. { name: 'bridge', value: config.hosts.bridge})
  13100. .up();
  13101. }
  13102. // Tell the focus we have Jigasi configured
  13103. if (config.hosts.call_control !== undefined) {
  13104. elem.c(
  13105. 'property',
  13106. { name: 'call_control', value: config.hosts.call_control})
  13107. .up();
  13108. }
  13109. if (config.channelLastN !== undefined) {
  13110. elem.c(
  13111. 'property',
  13112. { name: 'channelLastN', value: config.channelLastN})
  13113. .up();
  13114. }
  13115. if (config.adaptiveLastN !== undefined) {
  13116. elem.c(
  13117. 'property',
  13118. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  13119. .up();
  13120. }
  13121. if (config.adaptiveSimulcast !== undefined) {
  13122. elem.c(
  13123. 'property',
  13124. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  13125. .up();
  13126. }
  13127. if (config.openSctp !== undefined) {
  13128. elem.c(
  13129. 'property',
  13130. { name: 'openSctp', value: config.openSctp})
  13131. .up();
  13132. }
  13133. if (config.enableFirefoxSupport !== undefined) {
  13134. elem.c(
  13135. 'property',
  13136. { name: 'enableFirefoxHacks',
  13137. value: config.enableFirefoxSupport})
  13138. .up();
  13139. }
  13140. elem.up();
  13141. return elem;
  13142. },
  13143. parseConfigOptions: function (resultIq) {
  13144. Moderator.setFocusUserJid(
  13145. $(resultIq).find('conference').attr('focusjid'));
  13146. var authenticationEnabled
  13147. = $(resultIq).find(
  13148. '>conference>property' +
  13149. '[name=\'authentication\'][value=\'true\']').length > 0;
  13150. console.info("Authentication enabled: " + authenticationEnabled);
  13151. externalAuthEnabled
  13152. = $(resultIq).find(
  13153. '>conference>property' +
  13154. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  13155. console.info('External authentication enabled: ' + externalAuthEnabled);
  13156. if (!externalAuthEnabled) {
  13157. // We expect to receive sessionId in 'internal' authentication mode
  13158. var sessionId
  13159. = $(resultIq).find('conference').attr('session-id');
  13160. if (sessionId) {
  13161. console.info('Received sessionId: ' + sessionId);
  13162. localStorage.setItem('sessionId', sessionId);
  13163. }
  13164. }
  13165. var authIdentity = $(resultIq).find('>conference').attr('identity');
  13166. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  13167. authenticationEnabled, authIdentity);
  13168. // Check if focus has auto-detected Jigasi component(this will be also
  13169. // included if we have passed our host from the config)
  13170. if ($(resultIq).find(
  13171. '>conference>property' +
  13172. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  13173. sipGatewayEnabled = true;
  13174. }
  13175. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  13176. },
  13177. // FIXME: we need to show the fact that we're waiting for the focus
  13178. // to the user(or that focus is not available)
  13179. allocateConferenceFocus: function (roomName, callback) {
  13180. // Try to use focus user JID from the config
  13181. Moderator.setFocusUserJid(config.focusUserJid);
  13182. // Send create conference IQ
  13183. var iq = Moderator.createConferenceIq(roomName);
  13184. var self = this;
  13185. connection.sendIQ(
  13186. iq,
  13187. function (result) {
  13188. // Setup config options
  13189. Moderator.parseConfigOptions(result);
  13190. if ('true' === $(result).find('conference').attr('ready')) {
  13191. // Reset both timers
  13192. getNextTimeout(true);
  13193. getNextErrorTimeout(true);
  13194. // Exec callback
  13195. callback();
  13196. } else {
  13197. var waitMs = getNextTimeout();
  13198. console.info("Waiting for the focus... " + waitMs);
  13199. // Reset error timeout
  13200. getNextErrorTimeout(true);
  13201. window.setTimeout(
  13202. function () {
  13203. Moderator.allocateConferenceFocus(
  13204. roomName, callback);
  13205. }, waitMs);
  13206. }
  13207. },
  13208. function (error) {
  13209. // Invalid session ? remove and try again
  13210. // without session ID to get a new one
  13211. var invalidSession
  13212. = $(error).find('>error>session-invalid').length;
  13213. if (invalidSession) {
  13214. console.info("Session expired! - removing");
  13215. localStorage.removeItem("sessionId");
  13216. }
  13217. // Not authorized to create new room
  13218. if ($(error).find('>error>not-authorized').length) {
  13219. console.warn("Unauthorized to start the conference", error);
  13220. var toDomain
  13221. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13222. if (toDomain === config.hosts.anonymousdomain) {
  13223. // we are connected with anonymous domain and
  13224. // only non anonymous users can create rooms
  13225. // we must authorize the user
  13226. self.xmppService.promptLogin();
  13227. } else {
  13228. // External authentication mode
  13229. eventEmitter.emit(
  13230. XMPPEvents.AUTHENTICATION_REQUIRED,
  13231. function () {
  13232. Moderator.allocateConferenceFocus(
  13233. roomName, callback);
  13234. });
  13235. }
  13236. return;
  13237. }
  13238. var waitMs = getNextErrorTimeout();
  13239. console.error("Focus error, retry after " + waitMs, error);
  13240. // Show message
  13241. var focusComponent = Moderator.getFocusComponent();
  13242. var retrySec = waitMs / 1000;
  13243. // FIXME: message is duplicated ?
  13244. // Do not show in case of session invalid
  13245. // which means just a retry
  13246. if (!invalidSession) {
  13247. APP.UI.messageHandler.notify(
  13248. null, "notify.focus",
  13249. 'Conference focus', 'disconnected', "notify.focusFail",
  13250. focusComponent + " not available - retry in " +
  13251. retrySec + " sec",
  13252. {component: focusComponent, ms: retrySec});
  13253. }
  13254. // Reset response timeout
  13255. getNextTimeout(true);
  13256. window.setTimeout(
  13257. function () {
  13258. Moderator.allocateConferenceFocus(roomName, callback);
  13259. }, waitMs);
  13260. }
  13261. );
  13262. },
  13263. getLoginUrl: function (roomName, urlCallback) {
  13264. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13265. iq.c('login-url', {
  13266. xmlns: 'http://jitsi.org/protocol/focus',
  13267. room: roomName,
  13268. 'machine-uid': Settings.getSettings().uid
  13269. });
  13270. connection.sendIQ(
  13271. iq,
  13272. function (result) {
  13273. var url = $(result).find('login-url').attr('url');
  13274. url = url = decodeURIComponent(url);
  13275. if (url) {
  13276. console.info("Got auth url: " + url);
  13277. urlCallback(url);
  13278. } else {
  13279. console.error(
  13280. "Failed to get auth url from the focus", result);
  13281. }
  13282. },
  13283. function (error) {
  13284. console.error("Get auth url error", error);
  13285. }
  13286. );
  13287. },
  13288. getPopupLoginUrl: function (roomName, urlCallback) {
  13289. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13290. iq.c('login-url', {
  13291. xmlns: 'http://jitsi.org/protocol/focus',
  13292. room: roomName,
  13293. 'machine-uid': Settings.getSettings().uid,
  13294. popup: true
  13295. });
  13296. connection.sendIQ(
  13297. iq,
  13298. function (result) {
  13299. var url = $(result).find('login-url').attr('url');
  13300. url = url = decodeURIComponent(url);
  13301. if (url) {
  13302. console.info("Got POPUP auth url: " + url);
  13303. urlCallback(url);
  13304. } else {
  13305. console.error(
  13306. "Failed to get POPUP auth url from the focus", result);
  13307. }
  13308. },
  13309. function (error) {
  13310. console.error('Get POPUP auth url error', error);
  13311. }
  13312. );
  13313. },
  13314. logout: function (callback) {
  13315. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13316. var sessionId = localStorage.getItem('sessionId');
  13317. if (!sessionId) {
  13318. callback();
  13319. return;
  13320. }
  13321. iq.c('logout', {
  13322. xmlns: 'http://jitsi.org/protocol/focus',
  13323. 'session-id': sessionId
  13324. });
  13325. connection.sendIQ(
  13326. iq,
  13327. function (result) {
  13328. var logoutUrl = $(result).find('logout').attr('logout-url');
  13329. if (logoutUrl) {
  13330. logoutUrl = decodeURIComponent(logoutUrl);
  13331. }
  13332. console.info("Log out OK, url: " + logoutUrl, result);
  13333. localStorage.removeItem('sessionId');
  13334. callback(logoutUrl);
  13335. },
  13336. function (error) {
  13337. console.error("Logout error", error);
  13338. }
  13339. );
  13340. }
  13341. };
  13342. module.exports = Moderator;
  13343. },{"../../service/authentication/AuthenticationEvents":85,"../../service/xmpp/XMPPEvents":89,"../settings/Settings":38}],54:[function(require,module,exports){
  13344. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  13345. Toolbar, Util */
  13346. var Moderator = require("./moderator");
  13347. var recordingToken = null;
  13348. var recordingEnabled;
  13349. /**
  13350. * Whether to use a jirecon component for recording, or use the videobridge
  13351. * through COLIBRI.
  13352. */
  13353. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  13354. /**
  13355. * The ID of the jirecon recording session. Jirecon generates it when we
  13356. * initially start recording, and it needs to be used in subsequent requests
  13357. * to jirecon.
  13358. */
  13359. var jireconRid = null;
  13360. function setRecordingToken(token) {
  13361. recordingToken = token;
  13362. }
  13363. function setRecording(state, token, callback, connection) {
  13364. if (useJirecon){
  13365. setRecordingJirecon(state, token, callback, connection);
  13366. } else {
  13367. setRecordingColibri(state, token, callback, connection);
  13368. }
  13369. }
  13370. function setRecordingJirecon(state, token, callback, connection) {
  13371. if (state == recordingEnabled){
  13372. return;
  13373. }
  13374. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  13375. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  13376. action: state ? 'start' : 'stop',
  13377. mucjid: connection.emuc.roomjid});
  13378. if (!state){
  13379. iq.attrs({rid: jireconRid});
  13380. }
  13381. console.log('Start recording');
  13382. connection.sendIQ(
  13383. iq,
  13384. function (result) {
  13385. // TODO wait for an IQ with the real status, since this is
  13386. // provisional?
  13387. jireconRid = $(result).find('recording').attr('rid');
  13388. console.log('Recording ' + (state ? 'started' : 'stopped') +
  13389. '(jirecon)' + result);
  13390. recordingEnabled = state;
  13391. if (!state){
  13392. jireconRid = null;
  13393. }
  13394. callback(state);
  13395. },
  13396. function (error) {
  13397. console.log('Failed to start recording, error: ', error);
  13398. callback(recordingEnabled);
  13399. });
  13400. }
  13401. // Sends a COLIBRI message which enables or disables (according to 'state')
  13402. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  13403. // with the new recording state, according to the IQ.
  13404. function setRecordingColibri(state, token, callback, connection) {
  13405. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  13406. elem.c('conference', {
  13407. xmlns: 'http://jitsi.org/protocol/colibri'
  13408. });
  13409. elem.c('recording', {state: state, token: token});
  13410. connection.sendIQ(elem,
  13411. function (result) {
  13412. console.log('Set recording "', state, '". Result:', result);
  13413. var recordingElem = $(result).find('>conference>recording');
  13414. var newState = ('true' === recordingElem.attr('state'));
  13415. recordingEnabled = newState;
  13416. callback(newState);
  13417. },
  13418. function (error) {
  13419. console.warn(error);
  13420. callback(recordingEnabled);
  13421. }
  13422. );
  13423. }
  13424. var Recording = {
  13425. toggleRecording: function (tokenEmptyCallback,
  13426. startingCallback, startedCallback, connection) {
  13427. if (!Moderator.isModerator()) {
  13428. console.log(
  13429. 'non-focus, or conference not yet organized:' +
  13430. ' not enabling recording');
  13431. return;
  13432. }
  13433. var self = this;
  13434. // Jirecon does not (currently) support a token.
  13435. if (!recordingToken && !useJirecon) {
  13436. tokenEmptyCallback(function (value) {
  13437. setRecordingToken(value);
  13438. self.toggleRecording(tokenEmptyCallback,
  13439. startingCallback, startedCallback, connection);
  13440. });
  13441. return;
  13442. }
  13443. var oldState = recordingEnabled;
  13444. startingCallback(!oldState);
  13445. setRecording(!oldState,
  13446. recordingToken,
  13447. function (state) {
  13448. console.log("New recording state: ", state);
  13449. if (state === oldState) {
  13450. // FIXME: new focus:
  13451. // this will not work when moderator changes
  13452. // during active session. Then it will assume that
  13453. // recording status has changed to true, but it might have
  13454. // been already true(and we only received actual status from
  13455. // the focus).
  13456. //
  13457. // SO we start with status null, so that it is initialized
  13458. // here and will fail only after second click, so if invalid
  13459. // token was used we have to press the button twice before
  13460. // current status will be fetched and token will be reset.
  13461. //
  13462. // Reliable way would be to return authentication error.
  13463. // Or status update when moderator connects.
  13464. // Or we have to stop recording session when current
  13465. // moderator leaves the room.
  13466. // Failed to change, reset the token because it might
  13467. // have been wrong
  13468. setRecordingToken(null);
  13469. }
  13470. startedCallback(state);
  13471. },
  13472. connection
  13473. );
  13474. }
  13475. }
  13476. module.exports = Recording;
  13477. },{"./moderator":53}],55:[function(require,module,exports){
  13478. /* jshint -W117 */
  13479. /* a simple MUC connection plugin
  13480. * can only handle a single MUC room
  13481. */
  13482. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13483. var Moderator = require("./moderator");
  13484. var JingleSession = require("./JingleSession");
  13485. var bridgeIsDown = false;
  13486. module.exports = function(XMPP, eventEmitter) {
  13487. Strophe.addConnectionPlugin('emuc', {
  13488. connection: null,
  13489. roomjid: null,
  13490. myroomjid: null,
  13491. members: {},
  13492. list_members: [], // so we can elect a new focus
  13493. presMap: {},
  13494. preziMap: {},
  13495. joined: false,
  13496. isOwner: false,
  13497. role: null,
  13498. focusMucJid: null,
  13499. ssrc2jid: {},
  13500. init: function (conn) {
  13501. this.connection = conn;
  13502. },
  13503. initPresenceMap: function (myroomjid) {
  13504. this.presMap['to'] = myroomjid;
  13505. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  13506. },
  13507. doJoin: function (jid, password) {
  13508. this.myroomjid = jid;
  13509. console.info("Joined MUC as " + this.myroomjid);
  13510. this.initPresenceMap(this.myroomjid);
  13511. if (!this.roomjid) {
  13512. this.roomjid = Strophe.getBareJidFromJid(jid);
  13513. // add handlers (just once)
  13514. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  13515. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  13516. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  13517. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  13518. }
  13519. if (password !== undefined) {
  13520. this.presMap['password'] = password;
  13521. }
  13522. this.sendPresence();
  13523. },
  13524. doLeave: function () {
  13525. console.log("do leave", this.myroomjid);
  13526. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  13527. this.presMap.length = 0;
  13528. this.connection.send(pres);
  13529. },
  13530. createNonAnonymousRoom: function () {
  13531. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  13532. var getForm = $iq({type: 'get', to: this.roomjid})
  13533. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  13534. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13535. var self = this;
  13536. this.connection.sendIQ(getForm, function (form) {
  13537. if (!$(form).find(
  13538. '>query>x[xmlns="jabber:x:data"]' +
  13539. '>field[var="muc#roomconfig_whois"]').length) {
  13540. console.error('non-anonymous rooms not supported');
  13541. return;
  13542. }
  13543. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  13544. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13545. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13546. formSubmit.c('field', {'var': 'FORM_TYPE'})
  13547. .c('value')
  13548. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13549. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  13550. .c('value').t('anyone').up().up();
  13551. self.connection.sendIQ(formSubmit);
  13552. }, function (error) {
  13553. console.error("Error getting room configuration form");
  13554. });
  13555. },
  13556. onPresence: function (pres) {
  13557. var from = pres.getAttribute('from');
  13558. // What is this for? A workaround for something?
  13559. if (pres.getAttribute('type')) {
  13560. return true;
  13561. }
  13562. // Parse etherpad tag.
  13563. var etherpad = $(pres).find('>etherpad');
  13564. if (etherpad.length) {
  13565. if (config.etherpad_base && !Moderator.isModerator()) {
  13566. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  13567. }
  13568. }
  13569. // Parse prezi tag.
  13570. var presentation = $(pres).find('>prezi');
  13571. if (presentation.length) {
  13572. var url = presentation.attr('url');
  13573. var current = presentation.find('>current').text();
  13574. console.log('presentation info received from', from, url);
  13575. if (this.preziMap[from] == null) {
  13576. this.preziMap[from] = url;
  13577. $(document).trigger('presentationadded.muc', [from, url, current]);
  13578. }
  13579. else {
  13580. $(document).trigger('gotoslide.muc', [from, url, current]);
  13581. }
  13582. }
  13583. else if (this.preziMap[from] != null) {
  13584. var url = this.preziMap[from];
  13585. delete this.preziMap[from];
  13586. $(document).trigger('presentationremoved.muc', [from, url]);
  13587. }
  13588. // Parse audio info tag.
  13589. var audioMuted = $(pres).find('>audiomuted');
  13590. if (audioMuted.length) {
  13591. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  13592. }
  13593. // Parse video info tag.
  13594. var videoMuted = $(pres).find('>videomuted');
  13595. if (videoMuted.length) {
  13596. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  13597. }
  13598. var stats = $(pres).find('>stats');
  13599. if (stats.length) {
  13600. var statsObj = {};
  13601. Strophe.forEachChild(stats[0], "stat", function (el) {
  13602. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  13603. });
  13604. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  13605. }
  13606. // Parse status.
  13607. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  13608. this.isOwner = true;
  13609. this.createNonAnonymousRoom();
  13610. }
  13611. // Parse roles.
  13612. var member = {};
  13613. member.show = $(pres).find('>show').text();
  13614. member.status = $(pres).find('>status').text();
  13615. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  13616. member.affiliation = tmp.attr('affiliation');
  13617. member.role = tmp.attr('role');
  13618. // Focus recognition
  13619. member.jid = tmp.attr('jid');
  13620. member.isFocus = false;
  13621. if (member.jid
  13622. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  13623. member.isFocus = true;
  13624. }
  13625. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  13626. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  13627. if (from == this.myroomjid) {
  13628. if (member.affiliation == 'owner') this.isOwner = true;
  13629. if (this.role !== member.role) {
  13630. this.role = member.role;
  13631. eventEmitter.emit(XMPPEvents.LOCALROLE_CHANGED,
  13632. from, member, pres, Moderator.isModerator());
  13633. }
  13634. if (!this.joined) {
  13635. this.joined = true;
  13636. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  13637. this.list_members.push(from);
  13638. }
  13639. } else if (this.members[from] === undefined) {
  13640. // new participant
  13641. this.members[from] = member;
  13642. this.list_members.push(from);
  13643. console.log('entered', from, member);
  13644. if (member.isFocus) {
  13645. this.focusMucJid = from;
  13646. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  13647. }
  13648. else {
  13649. var id = $(pres).find('>userID').text();
  13650. var email = $(pres).find('>email');
  13651. if (email.length > 0) {
  13652. id = email.text();
  13653. }
  13654. eventEmitter.emit(XMPPEvents.MUC_ENTER, from, id, member.displayName);
  13655. }
  13656. } else {
  13657. // Presence update for existing participant
  13658. // Watch role change:
  13659. if (this.members[from].role != member.role) {
  13660. this.members[from].role = member.role;
  13661. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  13662. member.role, member.displayName);
  13663. }
  13664. }
  13665. // Always trigger presence to update bindings
  13666. this.parsePresence(from, member, pres);
  13667. // Trigger status message update
  13668. if (member.status) {
  13669. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  13670. }
  13671. return true;
  13672. },
  13673. onPresenceUnavailable: function (pres) {
  13674. var from = pres.getAttribute('from');
  13675. // room destroyed ?
  13676. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13677. '>destroy').length) {
  13678. var reason;
  13679. var reasonSelect = $(pres).find(
  13680. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13681. '>destroy>reason');
  13682. if (reasonSelect.length) {
  13683. reason = reasonSelect.text();
  13684. }
  13685. XMPP.disposeConference(false);
  13686. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  13687. return true;
  13688. }
  13689. // Status code 110 indicates that this notification is "self-presence".
  13690. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  13691. delete this.members[from];
  13692. this.list_members.splice(this.list_members.indexOf(from), 1);
  13693. this.onParticipantLeft(from);
  13694. }
  13695. // If the status code is 110 this means we're leaving and we would like
  13696. // to remove everyone else from our view, so we trigger the event.
  13697. else if (this.list_members.length > 1) {
  13698. for (var i = 0; i < this.list_members.length; i++) {
  13699. var member = this.list_members[i];
  13700. delete this.members[i];
  13701. this.list_members.splice(i, 1);
  13702. this.onParticipantLeft(member);
  13703. }
  13704. }
  13705. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  13706. $(document).trigger('kicked.muc', [from]);
  13707. if (this.myroomjid === from) {
  13708. XMPP.disposeConference(false);
  13709. eventEmitter.emit(XMPPEvents.KICKED);
  13710. }
  13711. }
  13712. return true;
  13713. },
  13714. onPresenceError: function (pres) {
  13715. var from = pres.getAttribute('from');
  13716. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13717. console.log('on password required', from);
  13718. var self = this;
  13719. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  13720. self.doJoin(from, value);
  13721. });
  13722. } else if ($(pres).find(
  13723. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13724. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  13725. if (toDomain === config.hosts.anonymousdomain) {
  13726. // enter the room by replying with 'not-authorized'. This would
  13727. // result in reconnection from authorized domain.
  13728. // We're either missing Jicofo/Prosody config for anonymous
  13729. // domains or something is wrong.
  13730. // XMPP.promptLogin();
  13731. APP.UI.messageHandler.openReportDialog(null, null,
  13732. "dialog.joinError",
  13733. 'Oops ! We couldn`t join the conference.' +
  13734. ' There might be some problem with security' +
  13735. ' configuration. Please contact service' +
  13736. ' administrator.', pres);
  13737. } else {
  13738. console.warn('onPresError ', pres);
  13739. APP.UI.messageHandler.openReportDialog(null, null,
  13740. "dialog.connectError",
  13741. 'Oops! Something went wrong and we couldn`t ' +
  13742. 'connect to the conference.',
  13743. pres);
  13744. }
  13745. } else {
  13746. console.warn('onPresError ', pres);
  13747. APP.UI.messageHandler.openReportDialog(null, null,
  13748. "dialog.connectError",
  13749. 'Oops! Something went wrong and we couldn`t ' +
  13750. 'connect to the conference.',
  13751. pres);
  13752. }
  13753. return true;
  13754. },
  13755. sendMessage: function (body, nickname) {
  13756. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13757. msg.c('body', body).up();
  13758. if (nickname) {
  13759. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  13760. }
  13761. this.connection.send(msg);
  13762. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  13763. },
  13764. setSubject: function (subject) {
  13765. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13766. msg.c('subject', subject);
  13767. this.connection.send(msg);
  13768. console.log("topic changed to " + subject);
  13769. },
  13770. onMessage: function (msg) {
  13771. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  13772. var from = msg.getAttribute('from');
  13773. var nick =
  13774. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  13775. .text() ||
  13776. Strophe.getResourceFromJid(from);
  13777. var txt = $(msg).find('>body').text();
  13778. var type = msg.getAttribute("type");
  13779. if (type == "error") {
  13780. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  13781. $(msg).find('>text').text(), txt);
  13782. return true;
  13783. }
  13784. var subject = $(msg).find('>subject');
  13785. if (subject.length) {
  13786. var subjectText = subject.text();
  13787. if (subjectText || subjectText == "") {
  13788. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  13789. console.log("Subject is changed to " + subjectText);
  13790. }
  13791. }
  13792. if (txt) {
  13793. console.log('chat', nick, txt);
  13794. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  13795. from, nick, txt, this.myroomjid);
  13796. }
  13797. return true;
  13798. },
  13799. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  13800. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  13801. var ob = this;
  13802. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  13803. function (res) {
  13804. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  13805. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13806. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13807. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13808. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  13809. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  13810. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  13811. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  13812. ob.connection.sendIQ(formsubmit,
  13813. onSuccess,
  13814. onError);
  13815. } else {
  13816. onNotSupported();
  13817. }
  13818. }, onError);
  13819. },
  13820. kick: function (jid) {
  13821. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  13822. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  13823. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  13824. .c('reason').t('You have been kicked.').up().up().up();
  13825. this.connection.sendIQ(
  13826. kickIQ,
  13827. function (result) {
  13828. console.log('Kick participant with jid: ', jid, result);
  13829. },
  13830. function (error) {
  13831. console.log('Kick participant error: ', error);
  13832. });
  13833. },
  13834. sendPresence: function () {
  13835. var pres = $pres({to: this.presMap['to'] });
  13836. pres.c('x', {xmlns: this.presMap['xns']});
  13837. if (this.presMap['password']) {
  13838. pres.c('password').t(this.presMap['password']).up();
  13839. }
  13840. pres.up();
  13841. // Send XEP-0115 'c' stanza that contains our capabilities info
  13842. if (this.connection.caps) {
  13843. this.connection.caps.node = config.clientNode;
  13844. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  13845. }
  13846. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  13847. .t(navigator.userAgent).up();
  13848. if (this.presMap['bridgeIsDown']) {
  13849. pres.c('bridgeIsDown').up();
  13850. }
  13851. if (this.presMap['email']) {
  13852. pres.c('email').t(this.presMap['email']).up();
  13853. }
  13854. if (this.presMap['userId']) {
  13855. pres.c('userId').t(this.presMap['userId']).up();
  13856. }
  13857. if (this.presMap['displayName']) {
  13858. // XEP-0172
  13859. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  13860. .t(this.presMap['displayName']).up();
  13861. }
  13862. if (this.presMap['audions']) {
  13863. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  13864. .t(this.presMap['audiomuted']).up();
  13865. }
  13866. if (this.presMap['videons']) {
  13867. pres.c('videomuted', {xmlns: this.presMap['videons']})
  13868. .t(this.presMap['videomuted']).up();
  13869. }
  13870. if (this.presMap['statsns']) {
  13871. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  13872. for (var stat in this.presMap["stats"])
  13873. if (this.presMap["stats"][stat] != null)
  13874. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  13875. pres.up();
  13876. }
  13877. if (this.presMap['prezins']) {
  13878. pres.c('prezi',
  13879. {xmlns: this.presMap['prezins'],
  13880. 'url': this.presMap['preziurl']})
  13881. .c('current').t(this.presMap['prezicurrent']).up().up();
  13882. }
  13883. if (this.presMap['etherpadns']) {
  13884. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  13885. .t(this.presMap['etherpadname']).up();
  13886. }
  13887. if (this.presMap['medians']) {
  13888. pres.c('media', {xmlns: this.presMap['medians']});
  13889. var sourceNumber = 0;
  13890. Object.keys(this.presMap).forEach(function (key) {
  13891. if (key.indexOf('source') >= 0) {
  13892. sourceNumber++;
  13893. }
  13894. });
  13895. if (sourceNumber > 0)
  13896. for (var i = 1; i <= sourceNumber / 3; i++) {
  13897. pres.c('source',
  13898. {type: this.presMap['source' + i + '_type'],
  13899. ssrc: this.presMap['source' + i + '_ssrc'],
  13900. direction: this.presMap['source' + i + '_direction']
  13901. || 'sendrecv' }
  13902. ).up();
  13903. }
  13904. }
  13905. pres.up();
  13906. this.connection.send(pres);
  13907. },
  13908. addDisplayNameToPresence: function (displayName) {
  13909. this.presMap['displayName'] = displayName;
  13910. },
  13911. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  13912. if (!this.presMap['medians'])
  13913. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  13914. this.presMap['source' + sourceNumber + '_type'] = mtype;
  13915. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  13916. this.presMap['source' + sourceNumber + '_direction'] = direction;
  13917. },
  13918. clearPresenceMedia: function () {
  13919. var self = this;
  13920. Object.keys(this.presMap).forEach(function (key) {
  13921. if (key.indexOf('source') != -1) {
  13922. delete self.presMap[key];
  13923. }
  13924. });
  13925. },
  13926. addPreziToPresence: function (url, currentSlide) {
  13927. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  13928. this.presMap['preziurl'] = url;
  13929. this.presMap['prezicurrent'] = currentSlide;
  13930. },
  13931. removePreziFromPresence: function () {
  13932. delete this.presMap['prezins'];
  13933. delete this.presMap['preziurl'];
  13934. delete this.presMap['prezicurrent'];
  13935. },
  13936. addCurrentSlideToPresence: function (currentSlide) {
  13937. this.presMap['prezicurrent'] = currentSlide;
  13938. },
  13939. getPrezi: function (roomjid) {
  13940. return this.preziMap[roomjid];
  13941. },
  13942. addEtherpadToPresence: function (etherpadName) {
  13943. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  13944. this.presMap['etherpadname'] = etherpadName;
  13945. },
  13946. addAudioInfoToPresence: function (isMuted) {
  13947. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  13948. this.presMap['audiomuted'] = isMuted.toString();
  13949. },
  13950. addVideoInfoToPresence: function (isMuted) {
  13951. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  13952. this.presMap['videomuted'] = isMuted.toString();
  13953. },
  13954. addConnectionInfoToPresence: function (stats) {
  13955. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  13956. this.presMap['stats'] = stats;
  13957. },
  13958. findJidFromResource: function (resourceJid) {
  13959. if (resourceJid &&
  13960. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  13961. return this.myroomjid;
  13962. }
  13963. var peerJid = null;
  13964. Object.keys(this.members).some(function (jid) {
  13965. peerJid = jid;
  13966. return Strophe.getResourceFromJid(jid) === resourceJid;
  13967. });
  13968. return peerJid;
  13969. },
  13970. addBridgeIsDownToPresence: function () {
  13971. this.presMap['bridgeIsDown'] = true;
  13972. },
  13973. addEmailToPresence: function (email) {
  13974. this.presMap['email'] = email;
  13975. },
  13976. addUserIdToPresence: function (userId) {
  13977. this.presMap['userId'] = userId;
  13978. },
  13979. isModerator: function () {
  13980. return this.role === 'moderator';
  13981. },
  13982. getMemberRole: function (peerJid) {
  13983. if (this.members[peerJid]) {
  13984. return this.members[peerJid].role;
  13985. }
  13986. return null;
  13987. },
  13988. onParticipantLeft: function (jid) {
  13989. eventEmitter.emit(XMPPEvents.MUC_LEFT, jid);
  13990. this.connection.jingle.terminateByJid(jid);
  13991. if (this.getPrezi(jid)) {
  13992. $(document).trigger('presentationremoved.muc',
  13993. [jid, this.getPrezi(jid)]);
  13994. }
  13995. Moderator.onMucLeft(jid);
  13996. },
  13997. parsePresence: function (from, memeber, pres) {
  13998. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  13999. bridgeIsDown = true;
  14000. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  14001. }
  14002. if(memeber.isFocus)
  14003. return;
  14004. var self = this;
  14005. // Remove old ssrcs coming from the jid
  14006. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  14007. if (self.ssrc2jid[ssrc] == from) {
  14008. delete self.ssrc2jid[ssrc];
  14009. }
  14010. });
  14011. var changedStreams = [];
  14012. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  14013. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  14014. var ssrcV = ssrc.getAttribute('ssrc');
  14015. self.ssrc2jid[ssrcV] = from;
  14016. JingleSession.notReceivedSSRCs.push(ssrcV);
  14017. var type = ssrc.getAttribute('type');
  14018. var direction = ssrc.getAttribute('direction');
  14019. changedStreams.push({type: type, direction: direction});
  14020. });
  14021. eventEmitter.emit(XMPPEvents.CHANGED_STREAMS, from, changedStreams);
  14022. var displayName = !config.displayJids
  14023. ? memeber.displayName : Strophe.getResourceFromJid(from);
  14024. if (displayName && displayName.length > 0)
  14025. {
  14026. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  14027. }
  14028. var id = $(pres).find('>userID').text();
  14029. var email = $(pres).find('>email');
  14030. if(email.length > 0) {
  14031. id = email.text();
  14032. }
  14033. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  14034. }
  14035. });
  14036. };
  14037. },{"../../service/xmpp/XMPPEvents":89,"./JingleSession":48,"./moderator":53}],56:[function(require,module,exports){
  14038. /* jshint -W117 */
  14039. var JingleSession = require("./JingleSession");
  14040. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14041. module.exports = function(XMPP, eventEmitter)
  14042. {
  14043. function CallIncomingJingle(sid, connection) {
  14044. var sess = connection.jingle.sessions[sid];
  14045. // TODO: do we check activecall == null?
  14046. connection.jingle.activecall = sess;
  14047. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  14048. // TODO: check affiliation and/or role
  14049. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  14050. sess.usedrip = true; // not-so-naive trickle ice
  14051. sess.sendAnswer();
  14052. sess.accept();
  14053. };
  14054. Strophe.addConnectionPlugin('jingle', {
  14055. connection: null,
  14056. sessions: {},
  14057. jid2session: {},
  14058. ice_config: {iceServers: []},
  14059. pc_constraints: {},
  14060. activecall: null,
  14061. media_constraints: {
  14062. mandatory: {
  14063. 'OfferToReceiveAudio': true,
  14064. 'OfferToReceiveVideo': true
  14065. }
  14066. // MozDontOfferDataChannel: true when this is firefox
  14067. },
  14068. init: function (conn) {
  14069. this.connection = conn;
  14070. if (this.connection.disco) {
  14071. // http://xmpp.org/extensions/xep-0167.html#support
  14072. // http://xmpp.org/extensions/xep-0176.html#support
  14073. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  14074. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  14075. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  14076. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  14077. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  14078. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  14079. // this is dealt with by SDP O/A so we don't need to annouce this
  14080. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  14081. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  14082. if (config.useRtcpMux) {
  14083. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  14084. }
  14085. if (config.useBundle) {
  14086. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  14087. }
  14088. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  14089. }
  14090. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  14091. },
  14092. onJingle: function (iq) {
  14093. var sid = $(iq).find('jingle').attr('sid');
  14094. var action = $(iq).find('jingle').attr('action');
  14095. var fromJid = iq.getAttribute('from');
  14096. // send ack first
  14097. var ack = $iq({type: 'result',
  14098. to: fromJid,
  14099. id: iq.getAttribute('id')
  14100. });
  14101. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  14102. var sess = this.sessions[sid];
  14103. if ('session-initiate' != action) {
  14104. if (sess === null) {
  14105. ack.type = 'error';
  14106. ack.c('error', {type: 'cancel'})
  14107. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14108. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14109. this.connection.send(ack);
  14110. return true;
  14111. }
  14112. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  14113. // local jid is not checked
  14114. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  14115. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  14116. ack.type = 'error';
  14117. ack.c('error', {type: 'cancel'})
  14118. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14119. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14120. this.connection.send(ack);
  14121. return true;
  14122. }
  14123. } else if (sess !== undefined) {
  14124. // existing session with same session id
  14125. // this might be out-of-order if the sess.peerjid is the same as from
  14126. ack.type = 'error';
  14127. ack.c('error', {type: 'cancel'})
  14128. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  14129. console.warn('duplicate session id', sid);
  14130. this.connection.send(ack);
  14131. return true;
  14132. }
  14133. // FIXME: check for a defined action
  14134. this.connection.send(ack);
  14135. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  14136. switch (action) {
  14137. case 'session-initiate':
  14138. sess = new JingleSession(
  14139. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  14140. this.connection, XMPP);
  14141. // configure session
  14142. sess.media_constraints = this.media_constraints;
  14143. sess.pc_constraints = this.pc_constraints;
  14144. sess.ice_config = this.ice_config;
  14145. sess.initiate(fromJid, false);
  14146. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  14147. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  14148. this.sessions[sess.sid] = sess;
  14149. this.jid2session[sess.peerjid] = sess;
  14150. // the callback should either
  14151. // .sendAnswer and .accept
  14152. // or .sendTerminate -- not necessarily synchronus
  14153. CallIncomingJingle(sess.sid, this.connection);
  14154. break;
  14155. case 'session-accept':
  14156. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  14157. sess.accept();
  14158. $(document).trigger('callaccepted.jingle', [sess.sid]);
  14159. break;
  14160. case 'session-terminate':
  14161. // If this is not the focus sending the terminate, we have
  14162. // nothing more to do here.
  14163. if (Object.keys(this.sessions).length < 1
  14164. || !(this.sessions[Object.keys(this.sessions)[0]]
  14165. instanceof JingleSession))
  14166. {
  14167. break;
  14168. }
  14169. console.log('terminating...', sess.sid);
  14170. sess.terminate();
  14171. this.terminate(sess.sid);
  14172. if ($(iq).find('>jingle>reason').length) {
  14173. $(document).trigger('callterminated.jingle', [
  14174. sess.sid,
  14175. sess.peerjid,
  14176. $(iq).find('>jingle>reason>:first')[0].tagName,
  14177. $(iq).find('>jingle>reason>text').text()
  14178. ]);
  14179. } else {
  14180. $(document).trigger('callterminated.jingle',
  14181. [sess.sid, sess.peerjid]);
  14182. }
  14183. break;
  14184. case 'transport-info':
  14185. sess.addIceCandidate($(iq).find('>jingle>content'));
  14186. break;
  14187. case 'session-info':
  14188. var affected;
  14189. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14190. $(document).trigger('ringing.jingle', [sess.sid]);
  14191. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14192. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14193. $(document).trigger('mute.jingle', [sess.sid, affected]);
  14194. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14195. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14196. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  14197. }
  14198. break;
  14199. case 'addsource': // FIXME: proprietary, un-jingleish
  14200. case 'source-add': // FIXME: proprietary
  14201. sess.addSource($(iq).find('>jingle>content'), fromJid);
  14202. break;
  14203. case 'removesource': // FIXME: proprietary, un-jingleish
  14204. case 'source-remove': // FIXME: proprietary
  14205. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  14206. break;
  14207. default:
  14208. console.warn('jingle action not implemented', action);
  14209. break;
  14210. }
  14211. return true;
  14212. },
  14213. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  14214. var sess = new JingleSession(myjid || this.connection.jid,
  14215. Math.random().toString(36).substr(2, 12), // random string
  14216. this.connection, XMPP);
  14217. // configure session
  14218. sess.media_constraints = this.media_constraints;
  14219. sess.pc_constraints = this.pc_constraints;
  14220. sess.ice_config = this.ice_config;
  14221. sess.initiate(peerjid, true);
  14222. this.sessions[sess.sid] = sess;
  14223. this.jid2session[sess.peerjid] = sess;
  14224. sess.sendOffer();
  14225. return sess;
  14226. },
  14227. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  14228. if (sid === null || sid === undefined) {
  14229. for (sid in this.sessions) {
  14230. if (this.sessions[sid].state != 'ended') {
  14231. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14232. this.sessions[sid].terminate();
  14233. }
  14234. delete this.jid2session[this.sessions[sid].peerjid];
  14235. delete this.sessions[sid];
  14236. }
  14237. } else if (this.sessions.hasOwnProperty(sid)) {
  14238. if (this.sessions[sid].state != 'ended') {
  14239. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14240. this.sessions[sid].terminate();
  14241. }
  14242. delete this.jid2session[this.sessions[sid].peerjid];
  14243. delete this.sessions[sid];
  14244. }
  14245. },
  14246. // Used to terminate a session when an unavailable presence is received.
  14247. terminateByJid: function (jid) {
  14248. if (this.jid2session.hasOwnProperty(jid)) {
  14249. var sess = this.jid2session[jid];
  14250. if (sess) {
  14251. sess.terminate();
  14252. console.log('peer went away silently', jid);
  14253. delete this.sessions[sess.sid];
  14254. delete this.jid2session[jid];
  14255. $(document).trigger('callterminated.jingle',
  14256. [sess.sid, jid], 'gone');
  14257. }
  14258. }
  14259. },
  14260. terminateRemoteByJid: function (jid, reason) {
  14261. if (this.jid2session.hasOwnProperty(jid)) {
  14262. var sess = this.jid2session[jid];
  14263. if (sess) {
  14264. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  14265. sess.terminate();
  14266. console.log('terminate peer with jid', sess.sid, jid);
  14267. delete this.sessions[sess.sid];
  14268. delete this.jid2session[jid];
  14269. $(document).trigger('callterminated.jingle',
  14270. [sess.sid, jid, 'kicked']);
  14271. }
  14272. }
  14273. },
  14274. getStunAndTurnCredentials: function () {
  14275. // get stun and turn configuration from server via xep-0215
  14276. // uses time-limited credentials as described in
  14277. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  14278. //
  14279. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  14280. // for a prosody module which implements this
  14281. //
  14282. // currently, this doesn't work with updateIce and therefore credentials with a long
  14283. // validity have to be fetched before creating the peerconnection
  14284. // TODO: implement refresh via updateIce as described in
  14285. // https://code.google.com/p/webrtc/issues/detail?id=1650
  14286. var self = this;
  14287. this.connection.sendIQ(
  14288. $iq({type: 'get', to: this.connection.domain})
  14289. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  14290. function (res) {
  14291. var iceservers = [];
  14292. $(res).find('>services>service').each(function (idx, el) {
  14293. el = $(el);
  14294. var dict = {};
  14295. var type = el.attr('type');
  14296. switch (type) {
  14297. case 'stun':
  14298. dict.url = 'stun:' + el.attr('host');
  14299. if (el.attr('port')) {
  14300. dict.url += ':' + el.attr('port');
  14301. }
  14302. iceservers.push(dict);
  14303. break;
  14304. case 'turn':
  14305. case 'turns':
  14306. dict.url = type + ':';
  14307. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  14308. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  14309. dict.url += el.attr('username') + '@';
  14310. } else {
  14311. dict.username = el.attr('username'); // only works in M28
  14312. }
  14313. }
  14314. dict.url += el.attr('host');
  14315. if (el.attr('port') && el.attr('port') != '3478') {
  14316. dict.url += ':' + el.attr('port');
  14317. }
  14318. if (el.attr('transport') && el.attr('transport') != 'udp') {
  14319. dict.url += '?transport=' + el.attr('transport');
  14320. }
  14321. if (el.attr('password')) {
  14322. dict.credential = el.attr('password');
  14323. }
  14324. iceservers.push(dict);
  14325. break;
  14326. }
  14327. });
  14328. self.ice_config.iceServers = iceservers;
  14329. },
  14330. function (err) {
  14331. console.warn('getting turn credentials failed', err);
  14332. console.warn('is mod_turncredentials or similar installed?');
  14333. }
  14334. );
  14335. // implement push?
  14336. },
  14337. /**
  14338. * Populates the log data
  14339. */
  14340. populateData: function () {
  14341. var data = {};
  14342. Object.keys(this.sessions).forEach(function (sid) {
  14343. var session = this.sessions[sid];
  14344. if (session.peerconnection && session.peerconnection.updateLog) {
  14345. // FIXME: should probably be a .dump call
  14346. data["jingle_" + session.sid] = {
  14347. updateLog: session.peerconnection.updateLog,
  14348. stats: session.peerconnection.stats,
  14349. url: window.location.href
  14350. };
  14351. }
  14352. });
  14353. return data;
  14354. }
  14355. });
  14356. };
  14357. },{"../../service/xmpp/XMPPEvents":89,"./JingleSession":48}],57:[function(require,module,exports){
  14358. /* global Strophe */
  14359. module.exports = function () {
  14360. Strophe.addConnectionPlugin('logger', {
  14361. // logs raw stanzas and makes them available for download as JSON
  14362. connection: null,
  14363. log: [],
  14364. init: function (conn) {
  14365. this.connection = conn;
  14366. this.connection.rawInput = this.log_incoming.bind(this);
  14367. this.connection.rawOutput = this.log_outgoing.bind(this);
  14368. },
  14369. log_incoming: function (stanza) {
  14370. this.log.push([new Date().getTime(), 'incoming', stanza]);
  14371. },
  14372. log_outgoing: function (stanza) {
  14373. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  14374. }
  14375. });
  14376. };
  14377. },{}],58:[function(require,module,exports){
  14378. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  14379. setAudioMuted, Strophe */
  14380. /**
  14381. * Moderate connection plugin.
  14382. */
  14383. module.exports = function (XMPP) {
  14384. Strophe.addConnectionPlugin('moderate', {
  14385. connection: null,
  14386. init: function (conn) {
  14387. this.connection = conn;
  14388. this.connection.addHandler(this.onMute.bind(this),
  14389. 'http://jitsi.org/jitmeet/audio',
  14390. 'iq',
  14391. 'set',
  14392. null,
  14393. null);
  14394. },
  14395. setMute: function (jid, mute) {
  14396. console.info("set mute", mute);
  14397. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  14398. .c('mute', {
  14399. xmlns: 'http://jitsi.org/jitmeet/audio',
  14400. jid: jid
  14401. })
  14402. .t(mute.toString())
  14403. .up();
  14404. this.connection.sendIQ(
  14405. iqToFocus,
  14406. function (result) {
  14407. console.log('set mute', result);
  14408. },
  14409. function (error) {
  14410. console.log('set mute error', error);
  14411. });
  14412. },
  14413. onMute: function (iq) {
  14414. var from = iq.getAttribute('from');
  14415. if (from !== this.connection.emuc.focusMucJid) {
  14416. console.warn("Ignored mute from non focus peer");
  14417. return false;
  14418. }
  14419. var mute = $(iq).find('mute');
  14420. if (mute.length) {
  14421. var doMuteAudio = mute.text() === "true";
  14422. APP.UI.setAudioMuted(doMuteAudio);
  14423. XMPP.forceMuted = doMuteAudio;
  14424. }
  14425. return true;
  14426. },
  14427. eject: function (jid) {
  14428. // We're not the focus, so can't terminate
  14429. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  14430. this.connection.emuc.kick(jid);
  14431. }
  14432. });
  14433. }
  14434. },{}],59:[function(require,module,exports){
  14435. /* jshint -W117 */
  14436. module.exports = function() {
  14437. Strophe.addConnectionPlugin('rayo',
  14438. {
  14439. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  14440. connection: null,
  14441. init: function (conn) {
  14442. this.connection = conn;
  14443. if (this.connection.disco) {
  14444. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  14445. }
  14446. this.connection.addHandler(
  14447. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  14448. },
  14449. onRayo: function (iq) {
  14450. console.info("Rayo IQ", iq);
  14451. },
  14452. dial: function (to, from, roomName, roomPass) {
  14453. var self = this;
  14454. var req = $iq(
  14455. {
  14456. type: 'set',
  14457. to: this.connection.emuc.focusMucJid
  14458. }
  14459. );
  14460. req.c('dial',
  14461. {
  14462. xmlns: this.RAYO_XMLNS,
  14463. to: to,
  14464. from: from
  14465. });
  14466. req.c('header',
  14467. {
  14468. name: 'JvbRoomName',
  14469. value: roomName
  14470. }).up();
  14471. if (roomPass !== null && roomPass.length) {
  14472. req.c('header',
  14473. {
  14474. name: 'JvbRoomPassword',
  14475. value: roomPass
  14476. }).up();
  14477. }
  14478. this.connection.sendIQ(
  14479. req,
  14480. function (result) {
  14481. console.info('Dial result ', result);
  14482. var resource = $(result).find('ref').attr('uri');
  14483. this.call_resource = resource.substr('xmpp:'.length);
  14484. console.info(
  14485. "Received call resource: " + this.call_resource);
  14486. },
  14487. function (error) {
  14488. console.info('Dial error ', error);
  14489. }
  14490. );
  14491. },
  14492. hang_up: function () {
  14493. if (!this.call_resource) {
  14494. console.warn("No call in progress");
  14495. return;
  14496. }
  14497. var self = this;
  14498. var req = $iq(
  14499. {
  14500. type: 'set',
  14501. to: this.call_resource
  14502. }
  14503. );
  14504. req.c('hangup',
  14505. {
  14506. xmlns: this.RAYO_XMLNS
  14507. });
  14508. this.connection.sendIQ(
  14509. req,
  14510. function (result) {
  14511. console.info('Hangup result ', result);
  14512. self.call_resource = null;
  14513. },
  14514. function (error) {
  14515. console.info('Hangup error ', error);
  14516. self.call_resource = null;
  14517. }
  14518. );
  14519. }
  14520. }
  14521. );
  14522. };
  14523. },{}],60:[function(require,module,exports){
  14524. /**
  14525. * Strophe logger implementation. Logs from level WARN and above.
  14526. */
  14527. module.exports = function () {
  14528. Strophe.log = function (level, msg) {
  14529. switch (level) {
  14530. case Strophe.LogLevel.WARN:
  14531. console.warn("Strophe: " + msg);
  14532. break;
  14533. case Strophe.LogLevel.ERROR:
  14534. case Strophe.LogLevel.FATAL:
  14535. console.error("Strophe: " + msg);
  14536. break;
  14537. }
  14538. };
  14539. Strophe.getStatusString = function (status) {
  14540. switch (status) {
  14541. case Strophe.Status.ERROR:
  14542. return "ERROR";
  14543. case Strophe.Status.CONNECTING:
  14544. return "CONNECTING";
  14545. case Strophe.Status.CONNFAIL:
  14546. return "CONNFAIL";
  14547. case Strophe.Status.AUTHENTICATING:
  14548. return "AUTHENTICATING";
  14549. case Strophe.Status.AUTHFAIL:
  14550. return "AUTHFAIL";
  14551. case Strophe.Status.CONNECTED:
  14552. return "CONNECTED";
  14553. case Strophe.Status.DISCONNECTED:
  14554. return "DISCONNECTED";
  14555. case Strophe.Status.DISCONNECTING:
  14556. return "DISCONNECTING";
  14557. case Strophe.Status.ATTACHED:
  14558. return "ATTACHED";
  14559. default:
  14560. return "unknown";
  14561. }
  14562. };
  14563. };
  14564. },{}],61:[function(require,module,exports){
  14565. var Moderator = require("./moderator");
  14566. var EventEmitter = require("events");
  14567. var Recording = require("./recording");
  14568. var SDP = require("./SDP");
  14569. var Pako = require("pako");
  14570. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  14571. var UIEvents = require("../../service/UI/UIEvents");
  14572. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14573. var eventEmitter = new EventEmitter();
  14574. var connection = null;
  14575. var authenticatedUser = false;
  14576. function connect(jid, password, uiCredentials) {
  14577. var bosh
  14578. = (uiCredentials && uiCredentials.bosh? uiCredentials.bosh : null)
  14579. || config.bosh || '/http-bind';
  14580. connection = new Strophe.Connection(bosh);
  14581. Moderator.setConnection(connection);
  14582. if(uiCredentials) {
  14583. var email = uiCredentials.email;
  14584. var displayName = uiCredentials.displayName;
  14585. if (email) {
  14586. connection.emuc.addEmailToPresence(email);
  14587. } else {
  14588. connection.emuc.addUserIdToPresence(uiCredentials.uid);
  14589. }
  14590. if (displayName) {
  14591. connection.emuc.addDisplayNameToPresence(displayName);
  14592. }
  14593. }
  14594. if (connection.disco) {
  14595. // for chrome, add multistream cap
  14596. }
  14597. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  14598. if (config.useIPv6) {
  14599. // https://code.google.com/p/webrtc/issues/detail?id=2828
  14600. if (!connection.jingle.pc_constraints.optional)
  14601. connection.jingle.pc_constraints.optional = [];
  14602. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  14603. }
  14604. if(!password)
  14605. password = uiCredentials.password;
  14606. var anonymousConnectionFailed = false;
  14607. connection.connect(jid, password, function (status, msg) {
  14608. console.log('Strophe status changed to',
  14609. Strophe.getStatusString(status));
  14610. if (status === Strophe.Status.CONNECTED) {
  14611. if (config.useStunTurn) {
  14612. connection.jingle.getStunAndTurnCredentials();
  14613. }
  14614. APP.UI.disableConnect();
  14615. console.info("My Jabber ID: " + connection.jid);
  14616. if(password)
  14617. authenticatedUser = true;
  14618. maybeDoJoin();
  14619. } else if (status === Strophe.Status.CONNFAIL) {
  14620. if(msg === 'x-strophe-bad-non-anon-jid') {
  14621. anonymousConnectionFailed = true;
  14622. }
  14623. } else if (status === Strophe.Status.DISCONNECTED) {
  14624. if(anonymousConnectionFailed) {
  14625. // prompt user for username and password
  14626. XMPP.promptLogin();
  14627. }
  14628. } else if (status === Strophe.Status.AUTHFAIL) {
  14629. // wrong password or username, prompt user
  14630. XMPP.promptLogin();
  14631. }
  14632. });
  14633. }
  14634. function maybeDoJoin() {
  14635. if (connection && connection.connected &&
  14636. Strophe.getResourceFromJid(connection.jid)
  14637. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  14638. // .connected is true while connecting?
  14639. doJoin();
  14640. }
  14641. }
  14642. function doJoin() {
  14643. var roomName = APP.UI.generateRoomName();
  14644. Moderator.allocateConferenceFocus(
  14645. roomName, APP.UI.checkForNicknameAndJoin);
  14646. }
  14647. function initStrophePlugins()
  14648. {
  14649. require("./strophe.emuc")(XMPP, eventEmitter);
  14650. require("./strophe.jingle")(XMPP, eventEmitter);
  14651. require("./strophe.moderate")(XMPP);
  14652. require("./strophe.util")();
  14653. require("./strophe.rayo")();
  14654. require("./strophe.logger")();
  14655. }
  14656. function registerListeners() {
  14657. APP.RTC.addStreamListener(maybeDoJoin,
  14658. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  14659. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  14660. XMPP.addToPresence("displayName", nickname);
  14661. });
  14662. }
  14663. function setupEvents() {
  14664. $(window).bind('beforeunload', function () {
  14665. if (connection && connection.connected) {
  14666. // ensure signout
  14667. $.ajax({
  14668. type: 'POST',
  14669. url: config.bosh,
  14670. async: false,
  14671. cache: false,
  14672. contentType: 'application/xml',
  14673. data: "<body rid='" + (connection.rid || connection._proto.rid)
  14674. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  14675. + (connection.sid || connection._proto.sid)
  14676. + "' type='terminate'>" +
  14677. "<presence xmlns='jabber:client' type='unavailable'/>" +
  14678. "</body>",
  14679. success: function (data) {
  14680. console.log('signed out');
  14681. console.log(data);
  14682. },
  14683. error: function (XMLHttpRequest, textStatus, errorThrown) {
  14684. console.log('signout error',
  14685. textStatus + ' (' + errorThrown + ')');
  14686. }
  14687. });
  14688. }
  14689. XMPP.disposeConference(true);
  14690. });
  14691. }
  14692. var XMPP = {
  14693. sessionTerminated: false,
  14694. /**
  14695. * Remembers if we were muted by the focus.
  14696. * @type {boolean}
  14697. */
  14698. forceMuted: false,
  14699. start: function (uiCredentials) {
  14700. setupEvents();
  14701. initStrophePlugins();
  14702. registerListeners();
  14703. Moderator.init(this, eventEmitter);
  14704. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  14705. // Force authenticated domain if room is appended with '?login=true'
  14706. if (config.hosts.anonymousdomain &&
  14707. window.location.search.indexOf("login=true") !== -1) {
  14708. configDomain = config.hosts.domain;
  14709. }
  14710. var jid = uiCredentials.jid || configDomain || window.location.hostname;
  14711. connect(jid, null, uiCredentials);
  14712. },
  14713. promptLogin: function () {
  14714. APP.UI.showLoginPopup(connect);
  14715. },
  14716. joinRoom: function(roomName, useNicks, nick)
  14717. {
  14718. var roomjid;
  14719. roomjid = roomName;
  14720. if (useNicks) {
  14721. if (nick) {
  14722. roomjid += '/' + nick;
  14723. } else {
  14724. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  14725. }
  14726. } else {
  14727. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  14728. if(!authenticatedUser)
  14729. tmpJid = tmpJid.substr(0, 8);
  14730. roomjid += '/' + tmpJid;
  14731. }
  14732. connection.emuc.doJoin(roomjid);
  14733. },
  14734. myJid: function () {
  14735. if(!connection)
  14736. return null;
  14737. return connection.emuc.myroomjid;
  14738. },
  14739. myResource: function () {
  14740. if(!connection || ! connection.emuc.myroomjid)
  14741. return null;
  14742. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  14743. },
  14744. disposeConference: function (onUnload) {
  14745. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  14746. var handler = connection.jingle.activecall;
  14747. if (handler && handler.peerconnection) {
  14748. // FIXME: probably removing streams is not required and close() should
  14749. // be enough
  14750. if (APP.RTC.localAudio) {
  14751. handler.peerconnection.removeStream(APP.RTC.localAudio.getOriginalStream(), onUnload);
  14752. }
  14753. if (APP.RTC.localVideo) {
  14754. handler.peerconnection.removeStream(APP.RTC.localVideo.getOriginalStream(), onUnload);
  14755. }
  14756. handler.peerconnection.close();
  14757. }
  14758. connection.jingle.activecall = null;
  14759. if(!onUnload)
  14760. {
  14761. this.sessionTerminated = true;
  14762. connection.emuc.doLeave();
  14763. }
  14764. },
  14765. addListener: function(type, listener)
  14766. {
  14767. eventEmitter.on(type, listener);
  14768. },
  14769. removeListener: function (type, listener) {
  14770. eventEmitter.removeListener(type, listener);
  14771. },
  14772. allocateConferenceFocus: function(roomName, callback) {
  14773. Moderator.allocateConferenceFocus(roomName, callback);
  14774. },
  14775. getLoginUrl: function (roomName, callback) {
  14776. Moderator.getLoginUrl(roomName, callback);
  14777. },
  14778. getPopupLoginUrl: function (roomName, callback) {
  14779. Moderator.getPopupLoginUrl(roomName, callback);
  14780. },
  14781. isModerator: function () {
  14782. return Moderator.isModerator();
  14783. },
  14784. isSipGatewayEnabled: function () {
  14785. return Moderator.isSipGatewayEnabled();
  14786. },
  14787. isExternalAuthEnabled: function () {
  14788. return Moderator.isExternalAuthEnabled();
  14789. },
  14790. switchStreams: function (stream, oldStream, callback) {
  14791. if (connection && connection.jingle.activecall) {
  14792. // FIXME: will block switchInProgress on true value in case of exception
  14793. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  14794. } else {
  14795. // We are done immediately
  14796. console.error("No conference handler");
  14797. APP.UI.messageHandler.showError("dialog.error", 'Error',
  14798. "dialog.unableToSwitch", 'Unable to switch video stream.');
  14799. callback();
  14800. }
  14801. },
  14802. setVideoMute: function (mute, callback, options) {
  14803. if(connection && APP.RTC.localVideo && connection.jingle.activecall)
  14804. {
  14805. connection.jingle.activecall.setVideoMute(mute, callback, options);
  14806. }
  14807. },
  14808. setAudioMute: function (mute, callback) {
  14809. if (!(connection && APP.RTC.localAudio)) {
  14810. return false;
  14811. }
  14812. if (this.forceMuted && !mute) {
  14813. console.info("Asking focus for unmute");
  14814. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  14815. // FIXME: wait for result before resetting muted status
  14816. this.forceMuted = false;
  14817. }
  14818. if (mute == APP.RTC.localAudio.isMuted()) {
  14819. // Nothing to do
  14820. return true;
  14821. }
  14822. // It is not clear what is the right way to handle multiple tracks.
  14823. // So at least make sure that they are all muted or all unmuted and
  14824. // that we send presence just once.
  14825. APP.RTC.localAudio.mute();
  14826. // isMuted is the opposite of audioEnabled
  14827. connection.emuc.addAudioInfoToPresence(mute);
  14828. connection.emuc.sendPresence();
  14829. callback();
  14830. return true;
  14831. },
  14832. // Really mute video, i.e. dont even send black frames
  14833. muteVideo: function (pc, unmute) {
  14834. // FIXME: this probably needs another of those lovely state safeguards...
  14835. // which checks for iceconn == connected and sigstate == stable
  14836. pc.setRemoteDescription(pc.remoteDescription,
  14837. function () {
  14838. pc.createAnswer(
  14839. function (answer) {
  14840. var sdp = new SDP(answer.sdp);
  14841. if (sdp.media.length > 1) {
  14842. if (unmute)
  14843. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  14844. else
  14845. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  14846. sdp.raw = sdp.session + sdp.media.join('');
  14847. answer.sdp = sdp.raw;
  14848. }
  14849. pc.setLocalDescription(answer,
  14850. function () {
  14851. console.log('mute SLD ok');
  14852. },
  14853. function (error) {
  14854. console.log('mute SLD error');
  14855. APP.UI.messageHandler.showError("dialog.error",
  14856. 'Error', "dialog.SLDFailure",
  14857. 'Oops! Something went wrong and we failed to ' +
  14858. 'mute! (SLD Failure)');
  14859. }
  14860. );
  14861. },
  14862. function (error) {
  14863. console.log(error);
  14864. APP.UI.messageHandler.showError();
  14865. }
  14866. );
  14867. },
  14868. function (error) {
  14869. console.log('muteVideo SRD error');
  14870. APP.UI.messageHandler.showError("dialog.error", 'Error',
  14871. "dialog.SRDFailure",
  14872. 'Oops! Something went wrong and we failed to stop video!' +
  14873. '(SRD Failure)');
  14874. }
  14875. );
  14876. },
  14877. toggleRecording: function (tokenEmptyCallback,
  14878. startingCallback, startedCallback) {
  14879. Recording.toggleRecording(tokenEmptyCallback,
  14880. startingCallback, startedCallback, connection);
  14881. },
  14882. addToPresence: function (name, value, dontSend) {
  14883. switch (name)
  14884. {
  14885. case "displayName":
  14886. connection.emuc.addDisplayNameToPresence(value);
  14887. break;
  14888. case "etherpad":
  14889. connection.emuc.addEtherpadToPresence(value);
  14890. break;
  14891. case "prezi":
  14892. connection.emuc.addPreziToPresence(value, 0);
  14893. break;
  14894. case "preziSlide":
  14895. connection.emuc.addCurrentSlideToPresence(value);
  14896. break;
  14897. case "connectionQuality":
  14898. connection.emuc.addConnectionInfoToPresence(value);
  14899. break;
  14900. case "email":
  14901. connection.emuc.addEmailToPresence(value);
  14902. default :
  14903. console.log("Unknown tag for presence.");
  14904. return;
  14905. }
  14906. if(!dontSend)
  14907. connection.emuc.sendPresence();
  14908. },
  14909. sendLogs: function (data) {
  14910. if(!connection.emuc.focusMucJid)
  14911. return;
  14912. var deflate = true;
  14913. var content = JSON.stringify(data);
  14914. if (deflate) {
  14915. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  14916. }
  14917. content = Base64.encode(content);
  14918. // XEP-0337-ish
  14919. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  14920. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  14921. id: 'PeerConnectionStats'});
  14922. message.c('message').t(content).up();
  14923. if (deflate) {
  14924. message.c('tag', {name: "deflated", value: "true"}).up();
  14925. }
  14926. message.up();
  14927. connection.send(message);
  14928. },
  14929. populateData: function () {
  14930. var data = {};
  14931. if (connection.jingle) {
  14932. data = connection.jingle.populateData();
  14933. }
  14934. return data;
  14935. },
  14936. getLogger: function () {
  14937. if(connection.logger)
  14938. return connection.logger.log;
  14939. return null;
  14940. },
  14941. getPrezi: function () {
  14942. return connection.emuc.getPrezi(this.myJid());
  14943. },
  14944. removePreziFromPresence: function () {
  14945. connection.emuc.removePreziFromPresence();
  14946. connection.emuc.sendPresence();
  14947. },
  14948. sendChatMessage: function (message, nickname) {
  14949. connection.emuc.sendMessage(message, nickname);
  14950. },
  14951. setSubject: function (topic) {
  14952. connection.emuc.setSubject(topic);
  14953. },
  14954. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14955. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  14956. },
  14957. dial: function (to, from, roomName,roomPass) {
  14958. connection.rayo.dial(to, from, roomName,roomPass);
  14959. },
  14960. setMute: function (jid, mute) {
  14961. connection.moderate.setMute(jid, mute);
  14962. },
  14963. eject: function (jid) {
  14964. connection.moderate.eject(jid);
  14965. },
  14966. logout: function (callback) {
  14967. Moderator.logout(callback);
  14968. },
  14969. findJidFromResource: function (resource) {
  14970. return connection.emuc.findJidFromResource(resource);
  14971. },
  14972. getMembers: function () {
  14973. return connection.emuc.members;
  14974. },
  14975. getJidFromSSRC: function (ssrc) {
  14976. if(!connection)
  14977. return null;
  14978. return connection.emuc.ssrc2jid[ssrc];
  14979. },
  14980. getMUCJoined: function () {
  14981. return connection.emuc.joined;
  14982. },
  14983. getSessions: function () {
  14984. return connection.jingle.sessions;
  14985. }
  14986. };
  14987. module.exports = XMPP;
  14988. },{"../../service/RTC/StreamEventTypes":83,"../../service/UI/UIEvents":84,"../../service/xmpp/XMPPEvents":89,"./SDP":49,"./moderator":53,"./recording":54,"./strophe.emuc":55,"./strophe.jingle":56,"./strophe.logger":57,"./strophe.moderate":58,"./strophe.rayo":59,"./strophe.util":60,"events":1,"pako":63}],62:[function(require,module,exports){
  14989. // i18next, v1.7.7
  14990. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  14991. // Distributed under MIT license
  14992. // http://i18next.com
  14993. (function() {
  14994. // add indexOf to non ECMA-262 standard compliant browsers
  14995. if (!Array.prototype.indexOf) {
  14996. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  14997. "use strict";
  14998. if (this == null) {
  14999. throw new TypeError();
  15000. }
  15001. var t = Object(this);
  15002. var len = t.length >>> 0;
  15003. if (len === 0) {
  15004. return -1;
  15005. }
  15006. var n = 0;
  15007. if (arguments.length > 0) {
  15008. n = Number(arguments[1]);
  15009. if (n != n) { // shortcut for verifying if it's NaN
  15010. n = 0;
  15011. } else if (n != 0 && n != Infinity && n != -Infinity) {
  15012. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  15013. }
  15014. }
  15015. if (n >= len) {
  15016. return -1;
  15017. }
  15018. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  15019. for (; k < len; k++) {
  15020. if (k in t && t[k] === searchElement) {
  15021. return k;
  15022. }
  15023. }
  15024. return -1;
  15025. }
  15026. }
  15027. // add lastIndexOf to non ECMA-262 standard compliant browsers
  15028. if (!Array.prototype.lastIndexOf) {
  15029. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  15030. "use strict";
  15031. if (this == null) {
  15032. throw new TypeError();
  15033. }
  15034. var t = Object(this);
  15035. var len = t.length >>> 0;
  15036. if (len === 0) {
  15037. return -1;
  15038. }
  15039. var n = len;
  15040. if (arguments.length > 1) {
  15041. n = Number(arguments[1]);
  15042. if (n != n) {
  15043. n = 0;
  15044. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  15045. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  15046. }
  15047. }
  15048. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  15049. for (; k >= 0; k--) {
  15050. if (k in t && t[k] === searchElement) {
  15051. return k;
  15052. }
  15053. }
  15054. return -1;
  15055. };
  15056. }
  15057. // Add string trim for IE8.
  15058. if (typeof String.prototype.trim !== 'function') {
  15059. String.prototype.trim = function() {
  15060. return this.replace(/^\s+|\s+$/g, '');
  15061. }
  15062. }
  15063. var root = this
  15064. , $ = root.jQuery || root.Zepto
  15065. , i18n = {}
  15066. , resStore = {}
  15067. , currentLng
  15068. , replacementCounter = 0
  15069. , languages = []
  15070. , initialized = false
  15071. , sync = {};
  15072. // Export the i18next object for **CommonJS**.
  15073. // If we're not in CommonJS, add `i18n` to the
  15074. // global object or to jquery.
  15075. if (typeof module !== 'undefined' && module.exports) {
  15076. if (!$) {
  15077. try {
  15078. $ = require('jquery');
  15079. } catch(e) {
  15080. // just ignore
  15081. }
  15082. }
  15083. if ($) {
  15084. $.i18n = $.i18n || i18n;
  15085. }
  15086. module.exports = i18n;
  15087. } else {
  15088. if ($) {
  15089. $.i18n = $.i18n || i18n;
  15090. }
  15091. root.i18n = root.i18n || i18n;
  15092. }
  15093. sync = {
  15094. load: function(lngs, options, cb) {
  15095. if (options.useLocalStorage) {
  15096. sync._loadLocal(lngs, options, function(err, store) {
  15097. var missingLngs = [];
  15098. for (var i = 0, len = lngs.length; i < len; i++) {
  15099. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  15100. }
  15101. if (missingLngs.length > 0) {
  15102. sync._fetch(missingLngs, options, function(err, fetched) {
  15103. f.extend(store, fetched);
  15104. sync._storeLocal(fetched);
  15105. cb(null, store);
  15106. });
  15107. } else {
  15108. cb(null, store);
  15109. }
  15110. });
  15111. } else {
  15112. sync._fetch(lngs, options, function(err, store){
  15113. cb(null, store);
  15114. });
  15115. }
  15116. },
  15117. _loadLocal: function(lngs, options, cb) {
  15118. var store = {}
  15119. , nowMS = new Date().getTime();
  15120. if(window.localStorage) {
  15121. var todo = lngs.length;
  15122. f.each(lngs, function(key, lng) {
  15123. var local = window.localStorage.getItem('res_' + lng);
  15124. if (local) {
  15125. local = JSON.parse(local);
  15126. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  15127. store[lng] = local;
  15128. }
  15129. }
  15130. todo--; // wait for all done befor callback
  15131. if (todo === 0) cb(null, store);
  15132. });
  15133. }
  15134. },
  15135. _storeLocal: function(store) {
  15136. if(window.localStorage) {
  15137. for (var m in store) {
  15138. store[m].i18nStamp = new Date().getTime();
  15139. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  15140. }
  15141. }
  15142. return;
  15143. },
  15144. _fetch: function(lngs, options, cb) {
  15145. var ns = options.ns
  15146. , store = {};
  15147. if (!options.dynamicLoad) {
  15148. var todo = ns.namespaces.length * lngs.length
  15149. , errors;
  15150. // load each file individual
  15151. f.each(ns.namespaces, function(nsIndex, nsValue) {
  15152. f.each(lngs, function(lngIndex, lngValue) {
  15153. // Call this once our translation has returned.
  15154. var loadComplete = function(err, data) {
  15155. if (err) {
  15156. errors = errors || [];
  15157. errors.push(err);
  15158. }
  15159. store[lngValue] = store[lngValue] || {};
  15160. store[lngValue][nsValue] = data;
  15161. todo--; // wait for all done befor callback
  15162. if (todo === 0) cb(errors, store);
  15163. };
  15164. if(typeof options.customLoad == 'function'){
  15165. // Use the specified custom callback.
  15166. options.customLoad(lngValue, nsValue, options, loadComplete);
  15167. } else {
  15168. //~ // Use our inbuilt sync.
  15169. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  15170. }
  15171. });
  15172. });
  15173. } else {
  15174. // Call this once our translation has returned.
  15175. var loadComplete = function(err, data) {
  15176. cb(null, data);
  15177. };
  15178. if(typeof options.customLoad == 'function'){
  15179. // Use the specified custom callback.
  15180. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  15181. } else {
  15182. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  15183. // load all needed stuff once
  15184. f.ajax({
  15185. url: url,
  15186. success: function(data, status, xhr) {
  15187. f.log('loaded: ' + url);
  15188. loadComplete(null, data);
  15189. },
  15190. error : function(xhr, status, error) {
  15191. f.log('failed loading: ' + url);
  15192. loadComplete('failed loading resource.json error: ' + error);
  15193. },
  15194. dataType: "json",
  15195. async : options.getAsync
  15196. });
  15197. }
  15198. }
  15199. },
  15200. _fetchOne: function(lng, ns, options, done) {
  15201. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  15202. f.ajax({
  15203. url: url,
  15204. success: function(data, status, xhr) {
  15205. f.log('loaded: ' + url);
  15206. done(null, data);
  15207. },
  15208. error : function(xhr, status, error) {
  15209. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  15210. // file loaded but invalid json, stop waste time !
  15211. f.error('There is a typo in: ' + url);
  15212. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  15213. f.log('Does not exist: ' + url);
  15214. } else {
  15215. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  15216. f.log(theStatus + ' when loading ' + url);
  15217. }
  15218. done(error, {});
  15219. },
  15220. dataType: "json",
  15221. async : options.getAsync
  15222. });
  15223. },
  15224. postMissing: function(lng, ns, key, defaultValue, lngs) {
  15225. var payload = {};
  15226. payload[key] = defaultValue;
  15227. var urls = [];
  15228. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  15229. for (var i = 0; i < o.fallbackLng.length; i++) {
  15230. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  15231. }
  15232. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  15233. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  15234. } else if (o.sendMissingTo === 'all') {
  15235. for (var i = 0, l = lngs.length; i < l; i++) {
  15236. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  15237. }
  15238. }
  15239. for (var y = 0, len = urls.length; y < len; y++) {
  15240. var item = urls[y];
  15241. f.ajax({
  15242. url: item.url,
  15243. type: o.sendType,
  15244. data: payload,
  15245. success: function(data, status, xhr) {
  15246. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  15247. // add key to resStore
  15248. var keys = key.split('.');
  15249. var x = 0;
  15250. var value = resStore[item.lng][ns];
  15251. while (keys[x]) {
  15252. if (x === keys.length - 1) {
  15253. value = value[keys[x]] = defaultValue;
  15254. } else {
  15255. value = value[keys[x]] = value[keys[x]] || {};
  15256. }
  15257. x++;
  15258. }
  15259. },
  15260. error : function(xhr, status, error) {
  15261. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  15262. },
  15263. dataType: "json",
  15264. async : o.postAsync
  15265. });
  15266. }
  15267. },
  15268. reload: reload
  15269. };
  15270. // defaults
  15271. var o = {
  15272. lng: undefined,
  15273. load: 'all',
  15274. preload: [],
  15275. lowerCaseLng: false,
  15276. returnObjectTrees: false,
  15277. fallbackLng: ['dev'],
  15278. fallbackNS: [],
  15279. detectLngQS: 'setLng',
  15280. detectLngFromLocalStorage: false,
  15281. ns: 'translation',
  15282. fallbackOnNull: true,
  15283. fallbackOnEmpty: false,
  15284. fallbackToDefaultNS: false,
  15285. nsseparator: ':',
  15286. keyseparator: '.',
  15287. selectorAttr: 'data-i18n',
  15288. debug: false,
  15289. resGetPath: 'locales/__lng__/__ns__.json',
  15290. resPostPath: 'locales/add/__lng__/__ns__',
  15291. getAsync: true,
  15292. postAsync: true,
  15293. resStore: undefined,
  15294. useLocalStorage: false,
  15295. localStorageExpirationTime: 7*24*60*60*1000,
  15296. dynamicLoad: false,
  15297. sendMissing: false,
  15298. sendMissingTo: 'fallback', // current | all
  15299. sendType: 'POST',
  15300. interpolationPrefix: '__',
  15301. interpolationSuffix: '__',
  15302. defaultVariables: false,
  15303. reusePrefix: '$t(',
  15304. reuseSuffix: ')',
  15305. pluralSuffix: '_plural',
  15306. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  15307. contextNotFound: ['context_not_found', Math.random()].join(''),
  15308. escapeInterpolation: false,
  15309. indefiniteSuffix: '_indefinite',
  15310. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  15311. setJqueryExt: true,
  15312. defaultValueFromContent: true,
  15313. useDataAttrOptions: false,
  15314. cookieExpirationTime: undefined,
  15315. useCookie: true,
  15316. cookieName: 'i18next',
  15317. cookieDomain: undefined,
  15318. objectTreeKeyHandler: undefined,
  15319. postProcess: undefined,
  15320. parseMissingKey: undefined,
  15321. missingKeyHandler: sync.postMissing,
  15322. shortcutFunction: 'sprintf' // or: defaultValue
  15323. };
  15324. function _extend(target, source) {
  15325. if (!source || typeof source === 'function') {
  15326. return target;
  15327. }
  15328. for (var attr in source) { target[attr] = source[attr]; }
  15329. return target;
  15330. }
  15331. function _deepExtend(target, source) {
  15332. for (var prop in source)
  15333. if (prop in target)
  15334. _deepExtend(target[prop], source[prop]);
  15335. else
  15336. target[prop] = source[prop];
  15337. return target;
  15338. }
  15339. function _each(object, callback, args) {
  15340. var name, i = 0,
  15341. length = object.length,
  15342. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  15343. if (args) {
  15344. if (isObj) {
  15345. for (name in object) {
  15346. if (callback.apply(object[name], args) === false) {
  15347. break;
  15348. }
  15349. }
  15350. } else {
  15351. for ( ; i < length; ) {
  15352. if (callback.apply(object[i++], args) === false) {
  15353. break;
  15354. }
  15355. }
  15356. }
  15357. // A special, fast, case for the most common use of each
  15358. } else {
  15359. if (isObj) {
  15360. for (name in object) {
  15361. if (callback.call(object[name], name, object[name]) === false) {
  15362. break;
  15363. }
  15364. }
  15365. } else {
  15366. for ( ; i < length; ) {
  15367. if (callback.call(object[i], i, object[i++]) === false) {
  15368. break;
  15369. }
  15370. }
  15371. }
  15372. }
  15373. return object;
  15374. }
  15375. var _entityMap = {
  15376. "&": "&amp;",
  15377. "<": "&lt;",
  15378. ">": "&gt;",
  15379. '"': '&quot;',
  15380. "'": '&#39;',
  15381. "/": '&#x2F;'
  15382. };
  15383. function _escape(data) {
  15384. if (typeof data === 'string') {
  15385. return data.replace(/[&<>"'\/]/g, function (s) {
  15386. return _entityMap[s];
  15387. });
  15388. }else{
  15389. return data;
  15390. }
  15391. }
  15392. function _ajax(options) {
  15393. // v0.5.0 of https://github.com/goloroden/http.js
  15394. var getXhr = function (callback) {
  15395. // Use the native XHR object if the browser supports it.
  15396. if (window.XMLHttpRequest) {
  15397. return callback(null, new XMLHttpRequest());
  15398. } else if (window.ActiveXObject) {
  15399. // In Internet Explorer check for ActiveX versions of the XHR object.
  15400. try {
  15401. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  15402. } catch (e) {
  15403. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  15404. }
  15405. }
  15406. // If no XHR support was found, throw an error.
  15407. return callback(new Error());
  15408. };
  15409. var encodeUsingUrlEncoding = function (data) {
  15410. if(typeof data === 'string') {
  15411. return data;
  15412. }
  15413. var result = [];
  15414. for(var dataItem in data) {
  15415. if(data.hasOwnProperty(dataItem)) {
  15416. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  15417. }
  15418. }
  15419. return result.join('&');
  15420. };
  15421. var utf8 = function (text) {
  15422. text = text.replace(/\r\n/g, '\n');
  15423. var result = '';
  15424. for(var i = 0; i < text.length; i++) {
  15425. var c = text.charCodeAt(i);
  15426. if(c < 128) {
  15427. result += String.fromCharCode(c);
  15428. } else if((c > 127) && (c < 2048)) {
  15429. result += String.fromCharCode((c >> 6) | 192);
  15430. result += String.fromCharCode((c & 63) | 128);
  15431. } else {
  15432. result += String.fromCharCode((c >> 12) | 224);
  15433. result += String.fromCharCode(((c >> 6) & 63) | 128);
  15434. result += String.fromCharCode((c & 63) | 128);
  15435. }
  15436. }
  15437. return result;
  15438. };
  15439. var base64 = function (text) {
  15440. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15441. text = utf8(text);
  15442. var result = '',
  15443. chr1, chr2, chr3,
  15444. enc1, enc2, enc3, enc4,
  15445. i = 0;
  15446. do {
  15447. chr1 = text.charCodeAt(i++);
  15448. chr2 = text.charCodeAt(i++);
  15449. chr3 = text.charCodeAt(i++);
  15450. enc1 = chr1 >> 2;
  15451. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  15452. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  15453. enc4 = chr3 & 63;
  15454. if(isNaN(chr2)) {
  15455. enc3 = enc4 = 64;
  15456. } else if(isNaN(chr3)) {
  15457. enc4 = 64;
  15458. }
  15459. result +=
  15460. keyStr.charAt(enc1) +
  15461. keyStr.charAt(enc2) +
  15462. keyStr.charAt(enc3) +
  15463. keyStr.charAt(enc4);
  15464. chr1 = chr2 = chr3 = '';
  15465. enc1 = enc2 = enc3 = enc4 = '';
  15466. } while(i < text.length);
  15467. return result;
  15468. };
  15469. var mergeHeaders = function () {
  15470. // Use the first header object as base.
  15471. var result = arguments[0];
  15472. // Iterate through the remaining header objects and add them.
  15473. for(var i = 1; i < arguments.length; i++) {
  15474. var currentHeaders = arguments[i];
  15475. for(var header in currentHeaders) {
  15476. if(currentHeaders.hasOwnProperty(header)) {
  15477. result[header] = currentHeaders[header];
  15478. }
  15479. }
  15480. }
  15481. // Return the merged headers.
  15482. return result;
  15483. };
  15484. var ajax = function (method, url, options, callback) {
  15485. // Adjust parameters.
  15486. if(typeof options === 'function') {
  15487. callback = options;
  15488. options = {};
  15489. }
  15490. // Set default parameter values.
  15491. options.cache = options.cache || false;
  15492. options.data = options.data || {};
  15493. options.headers = options.headers || {};
  15494. options.jsonp = options.jsonp || false;
  15495. options.async = options.async === undefined ? true : options.async;
  15496. // Merge the various header objects.
  15497. var headers = mergeHeaders({
  15498. 'accept': '*/*',
  15499. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  15500. }, ajax.headers, options.headers);
  15501. // Encode the data according to the content-type.
  15502. var payload;
  15503. if (headers['content-type'] === 'application/json') {
  15504. payload = JSON.stringify(options.data);
  15505. } else {
  15506. payload = encodeUsingUrlEncoding(options.data);
  15507. }
  15508. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  15509. // if neccessary.
  15510. if(method === 'GET') {
  15511. // Setup the query string.
  15512. var queryString = [];
  15513. if(payload) {
  15514. queryString.push(payload);
  15515. payload = null;
  15516. }
  15517. // Handle caching.
  15518. if(!options.cache) {
  15519. queryString.push('_=' + (new Date()).getTime());
  15520. }
  15521. // If neccessary prepare the query string for a JSONP call.
  15522. if(options.jsonp) {
  15523. queryString.push('callback=' + options.jsonp);
  15524. queryString.push('jsonp=' + options.jsonp);
  15525. }
  15526. // Merge the query string and attach it to the url.
  15527. queryString = queryString.join('&');
  15528. if (queryString.length > 1) {
  15529. if (url.indexOf('?') > -1) {
  15530. url += '&' + queryString;
  15531. } else {
  15532. url += '?' + queryString;
  15533. }
  15534. }
  15535. // Make a JSONP call if neccessary.
  15536. if(options.jsonp) {
  15537. var head = document.getElementsByTagName('head')[0];
  15538. var script = document.createElement('script');
  15539. script.type = 'text/javascript';
  15540. script.src = url;
  15541. head.appendChild(script);
  15542. return;
  15543. }
  15544. }
  15545. // Since we got here, it is no JSONP request, so make a normal XHR request.
  15546. getXhr(function (err, xhr) {
  15547. if(err) return callback(err);
  15548. // Open the request.
  15549. xhr.open(method, url, options.async);
  15550. // Set the request headers.
  15551. for(var header in headers) {
  15552. if(headers.hasOwnProperty(header)) {
  15553. xhr.setRequestHeader(header, headers[header]);
  15554. }
  15555. }
  15556. // Handle the request events.
  15557. xhr.onreadystatechange = function () {
  15558. if(xhr.readyState === 4) {
  15559. var data = xhr.responseText || '';
  15560. // If no callback is given, return.
  15561. if(!callback) {
  15562. return;
  15563. }
  15564. // Return an object that provides access to the data as text and JSON.
  15565. callback(xhr.status, {
  15566. text: function () {
  15567. return data;
  15568. },
  15569. json: function () {
  15570. try {
  15571. return JSON.parse(data)
  15572. } catch (e) {
  15573. f.error('Can not parse JSON. URL: ' + url);
  15574. return {};
  15575. }
  15576. }
  15577. });
  15578. }
  15579. };
  15580. // Actually send the XHR request.
  15581. xhr.send(payload);
  15582. });
  15583. };
  15584. // Define the external interface.
  15585. var http = {
  15586. authBasic: function (username, password) {
  15587. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  15588. },
  15589. connect: function (url, options, callback) {
  15590. return ajax('CONNECT', url, options, callback);
  15591. },
  15592. del: function (url, options, callback) {
  15593. return ajax('DELETE', url, options, callback);
  15594. },
  15595. get: function (url, options, callback) {
  15596. return ajax('GET', url, options, callback);
  15597. },
  15598. head: function (url, options, callback) {
  15599. return ajax('HEAD', url, options, callback);
  15600. },
  15601. headers: function (headers) {
  15602. ajax.headers = headers || {};
  15603. },
  15604. isAllowed: function (url, verb, callback) {
  15605. this.options(url, function (status, data) {
  15606. callback(data.text().indexOf(verb) !== -1);
  15607. });
  15608. },
  15609. options: function (url, options, callback) {
  15610. return ajax('OPTIONS', url, options, callback);
  15611. },
  15612. patch: function (url, options, callback) {
  15613. return ajax('PATCH', url, options, callback);
  15614. },
  15615. post: function (url, options, callback) {
  15616. return ajax('POST', url, options, callback);
  15617. },
  15618. put: function (url, options, callback) {
  15619. return ajax('PUT', url, options, callback);
  15620. },
  15621. trace: function (url, options, callback) {
  15622. return ajax('TRACE', url, options, callback);
  15623. }
  15624. };
  15625. var methode = options.type ? options.type.toLowerCase() : 'get';
  15626. http[methode](options.url, options, function (status, data) {
  15627. // file: protocol always gives status code 0, so check for data
  15628. if (status === 200 || (status === 0 && data.text())) {
  15629. options.success(data.json(), status, null);
  15630. } else {
  15631. options.error(data.text(), status, null);
  15632. }
  15633. });
  15634. }
  15635. var _cookie = {
  15636. create: function(name,value,minutes,domain) {
  15637. var expires;
  15638. if (minutes) {
  15639. var date = new Date();
  15640. date.setTime(date.getTime()+(minutes*60*1000));
  15641. expires = "; expires="+date.toGMTString();
  15642. }
  15643. else expires = "";
  15644. domain = (domain)? "domain="+domain+";" : "";
  15645. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  15646. },
  15647. read: function(name) {
  15648. var nameEQ = name + "=";
  15649. var ca = document.cookie.split(';');
  15650. for(var i=0;i < ca.length;i++) {
  15651. var c = ca[i];
  15652. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  15653. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  15654. }
  15655. return null;
  15656. },
  15657. remove: function(name) {
  15658. this.create(name,"",-1);
  15659. }
  15660. };
  15661. var cookie_noop = {
  15662. create: function(name,value,minutes,domain) {},
  15663. read: function(name) { return null; },
  15664. remove: function(name) {}
  15665. };
  15666. // move dependent functions to a container so that
  15667. // they can be overriden easier in no jquery environment (node.js)
  15668. var f = {
  15669. extend: $ ? $.extend : _extend,
  15670. deepExtend: _deepExtend,
  15671. each: $ ? $.each : _each,
  15672. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  15673. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  15674. detectLanguage: detectLanguage,
  15675. escape: _escape,
  15676. log: function(str) {
  15677. if (o.debug && typeof console !== "undefined") console.log(str);
  15678. },
  15679. error: function(str) {
  15680. if (typeof console !== "undefined") console.error(str);
  15681. },
  15682. getCountyIndexOfLng: function(lng) {
  15683. var lng_index = 0;
  15684. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  15685. return lng_index;
  15686. },
  15687. toLanguages: function(lng) {
  15688. var log = this.log;
  15689. function applyCase(l) {
  15690. var ret = l;
  15691. if (typeof l === 'string' && l.indexOf('-') > -1) {
  15692. var parts = l.split('-');
  15693. ret = o.lowerCaseLng ?
  15694. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  15695. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  15696. } else {
  15697. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  15698. }
  15699. return ret;
  15700. }
  15701. var languages = [];
  15702. var whitelist = o.lngWhitelist || false;
  15703. var addLanguage = function(language){
  15704. //reject langs not whitelisted
  15705. if(!whitelist || whitelist.indexOf(language) > -1){
  15706. languages.push(language);
  15707. }else{
  15708. log('rejecting non-whitelisted language: ' + language);
  15709. }
  15710. };
  15711. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  15712. var parts = lng.split('-');
  15713. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  15714. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  15715. } else {
  15716. addLanguage(applyCase(lng));
  15717. }
  15718. for (var i = 0; i < o.fallbackLng.length; i++) {
  15719. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  15720. }
  15721. return languages;
  15722. },
  15723. regexEscape: function(str) {
  15724. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  15725. },
  15726. regexReplacementEscape: function(strOrFn) {
  15727. if (typeof strOrFn === 'string') {
  15728. return strOrFn.replace(/\$/g, "$$$$");
  15729. } else {
  15730. return strOrFn;
  15731. }
  15732. },
  15733. localStorage: {
  15734. setItem: function(key, value) {
  15735. if (window.localStorage) {
  15736. try {
  15737. window.localStorage.setItem(key, value);
  15738. } catch (e) {
  15739. f.log('failed to set value for key "' + key + '" to localStorage.');
  15740. }
  15741. }
  15742. }
  15743. }
  15744. };
  15745. function init(options, cb) {
  15746. if (typeof options === 'function') {
  15747. cb = options;
  15748. options = {};
  15749. }
  15750. options = options || {};
  15751. // override defaults with passed in options
  15752. f.extend(o, options);
  15753. delete o.fixLng; /* passed in each time */
  15754. // override functions: .log(), .detectLanguage(), etc
  15755. if (o.functions) {
  15756. delete o.functions;
  15757. f.extend(f, options.functions);
  15758. }
  15759. // create namespace object if namespace is passed in as string
  15760. if (typeof o.ns == 'string') {
  15761. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  15762. }
  15763. // fallback namespaces
  15764. if (typeof o.fallbackNS == 'string') {
  15765. o.fallbackNS = [o.fallbackNS];
  15766. }
  15767. // fallback languages
  15768. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  15769. o.fallbackLng = [o.fallbackLng];
  15770. }
  15771. // escape prefix/suffix
  15772. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  15773. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  15774. if (!o.lng) o.lng = f.detectLanguage();
  15775. languages = f.toLanguages(o.lng);
  15776. currentLng = languages[0];
  15777. f.log('currentLng set to: ' + currentLng);
  15778. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  15779. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  15780. }
  15781. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  15782. f.localStorage.setItem('i18next_lng', currentLng);
  15783. }
  15784. var lngTranslate = translate;
  15785. if (options.fixLng) {
  15786. lngTranslate = function(key, options) {
  15787. options = options || {};
  15788. options.lng = options.lng || lngTranslate.lng;
  15789. return translate(key, options);
  15790. };
  15791. lngTranslate.lng = currentLng;
  15792. }
  15793. pluralExtensions.setCurrentLng(currentLng);
  15794. // add JQuery extensions
  15795. if ($ && o.setJqueryExt) addJqueryFunct();
  15796. // jQuery deferred
  15797. var deferred;
  15798. if ($ && $.Deferred) {
  15799. deferred = $.Deferred();
  15800. }
  15801. // return immidiatly if res are passed in
  15802. if (o.resStore) {
  15803. resStore = o.resStore;
  15804. initialized = true;
  15805. if (cb) cb(lngTranslate);
  15806. if (deferred) deferred.resolve(lngTranslate);
  15807. if (deferred) return deferred.promise();
  15808. return;
  15809. }
  15810. // languages to load
  15811. var lngsToLoad = f.toLanguages(o.lng);
  15812. if (typeof o.preload === 'string') o.preload = [o.preload];
  15813. for (var i = 0, l = o.preload.length; i < l; i++) {
  15814. var pres = f.toLanguages(o.preload[i]);
  15815. for (var y = 0, len = pres.length; y < len; y++) {
  15816. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15817. lngsToLoad.push(pres[y]);
  15818. }
  15819. }
  15820. }
  15821. // else load them
  15822. i18n.sync.load(lngsToLoad, o, function(err, store) {
  15823. resStore = store;
  15824. initialized = true;
  15825. if (cb) cb(lngTranslate);
  15826. if (deferred) deferred.resolve(lngTranslate);
  15827. });
  15828. if (deferred) return deferred.promise();
  15829. }
  15830. function preload(lngs, cb) {
  15831. if (typeof lngs === 'string') lngs = [lngs];
  15832. for (var i = 0, l = lngs.length; i < l; i++) {
  15833. if (o.preload.indexOf(lngs[i]) < 0) {
  15834. o.preload.push(lngs[i]);
  15835. }
  15836. }
  15837. return init(cb);
  15838. }
  15839. function addResourceBundle(lng, ns, resources, deep) {
  15840. if (typeof ns !== 'string') {
  15841. resources = ns;
  15842. ns = o.ns.defaultNs;
  15843. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15844. o.ns.namespaces.push(ns);
  15845. }
  15846. resStore[lng] = resStore[lng] || {};
  15847. resStore[lng][ns] = resStore[lng][ns] || {};
  15848. if (deep) {
  15849. f.deepExtend(resStore[lng][ns], resources);
  15850. } else {
  15851. f.extend(resStore[lng][ns], resources);
  15852. }
  15853. }
  15854. function hasResourceBundle(lng, ns) {
  15855. if (typeof ns !== 'string') {
  15856. ns = o.ns.defaultNs;
  15857. }
  15858. resStore[lng] = resStore[lng] || {};
  15859. var res = resStore[lng][ns] || {};
  15860. var hasValues = false;
  15861. for(var prop in res) {
  15862. if (res.hasOwnProperty(prop)) {
  15863. hasValues = true;
  15864. }
  15865. }
  15866. return hasValues;
  15867. }
  15868. function removeResourceBundle(lng, ns) {
  15869. if (typeof ns !== 'string') {
  15870. ns = o.ns.defaultNs;
  15871. }
  15872. resStore[lng] = resStore[lng] || {};
  15873. resStore[lng][ns] = {};
  15874. }
  15875. function addResource(lng, ns, key, value) {
  15876. if (typeof ns !== 'string') {
  15877. resource = ns;
  15878. ns = o.ns.defaultNs;
  15879. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15880. o.ns.namespaces.push(ns);
  15881. }
  15882. resStore[lng] = resStore[lng] || {};
  15883. resStore[lng][ns] = resStore[lng][ns] || {};
  15884. var keys = key.split(o.keyseparator);
  15885. var x = 0;
  15886. var node = resStore[lng][ns];
  15887. var origRef = node;
  15888. while (keys[x]) {
  15889. if (x == keys.length - 1)
  15890. node[keys[x]] = value;
  15891. else {
  15892. if (node[keys[x]] == null)
  15893. node[keys[x]] = {};
  15894. node = node[keys[x]];
  15895. }
  15896. x++;
  15897. }
  15898. }
  15899. function addResources(lng, ns, resources) {
  15900. if (typeof ns !== 'string') {
  15901. resource = ns;
  15902. ns = o.ns.defaultNs;
  15903. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15904. o.ns.namespaces.push(ns);
  15905. }
  15906. for (var m in resources) {
  15907. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  15908. }
  15909. }
  15910. function setDefaultNamespace(ns) {
  15911. o.ns.defaultNs = ns;
  15912. }
  15913. function loadNamespace(namespace, cb) {
  15914. loadNamespaces([namespace], cb);
  15915. }
  15916. function loadNamespaces(namespaces, cb) {
  15917. var opts = {
  15918. dynamicLoad: o.dynamicLoad,
  15919. resGetPath: o.resGetPath,
  15920. getAsync: o.getAsync,
  15921. customLoad: o.customLoad,
  15922. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  15923. };
  15924. // languages to load
  15925. var lngsToLoad = f.toLanguages(o.lng);
  15926. if (typeof o.preload === 'string') o.preload = [o.preload];
  15927. for (var i = 0, l = o.preload.length; i < l; i++) {
  15928. var pres = f.toLanguages(o.preload[i]);
  15929. for (var y = 0, len = pres.length; y < len; y++) {
  15930. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15931. lngsToLoad.push(pres[y]);
  15932. }
  15933. }
  15934. }
  15935. // check if we have to load
  15936. var lngNeedLoad = [];
  15937. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  15938. var needLoad = false;
  15939. var resSet = resStore[lngsToLoad[a]];
  15940. if (resSet) {
  15941. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  15942. if (!resSet[namespaces[b]]) needLoad = true;
  15943. }
  15944. } else {
  15945. needLoad = true;
  15946. }
  15947. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  15948. }
  15949. if (lngNeedLoad.length) {
  15950. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  15951. var todo = namespaces.length * lngNeedLoad.length;
  15952. // load each file individual
  15953. f.each(namespaces, function(nsIndex, nsValue) {
  15954. // append namespace to namespace array
  15955. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  15956. o.ns.namespaces.push(nsValue);
  15957. }
  15958. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  15959. resStore[lngValue] = resStore[lngValue] || {};
  15960. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  15961. todo--; // wait for all done befor callback
  15962. if (todo === 0 && cb) {
  15963. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  15964. cb();
  15965. }
  15966. });
  15967. });
  15968. });
  15969. } else {
  15970. if (cb) cb();
  15971. }
  15972. }
  15973. function setLng(lng, options, cb) {
  15974. if (typeof options === 'function') {
  15975. cb = options;
  15976. options = {};
  15977. } else if (!options) {
  15978. options = {};
  15979. }
  15980. options.lng = lng;
  15981. return init(options, cb);
  15982. }
  15983. function lng() {
  15984. return currentLng;
  15985. }
  15986. function reload(cb) {
  15987. resStore = {};
  15988. setLng(currentLng, cb);
  15989. }
  15990. function addJqueryFunct() {
  15991. // $.t shortcut
  15992. $.t = $.t || translate;
  15993. function parse(ele, key, options) {
  15994. if (key.length === 0) return;
  15995. var attr = 'text';
  15996. if (key.indexOf('[') === 0) {
  15997. var parts = key.split(']');
  15998. key = parts[1];
  15999. attr = parts[0].substr(1, parts[0].length-1);
  16000. }
  16001. if (key.indexOf(';') === key.length-1) {
  16002. key = key.substr(0, key.length-2);
  16003. }
  16004. var optionsToUse;
  16005. if (attr === 'html') {
  16006. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16007. ele.html($.t(key, optionsToUse));
  16008. } else if (attr === 'text') {
  16009. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  16010. ele.text($.t(key, optionsToUse));
  16011. } else if (attr === 'prepend') {
  16012. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16013. ele.prepend($.t(key, optionsToUse));
  16014. } else if (attr === 'append') {
  16015. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16016. ele.append($.t(key, optionsToUse));
  16017. } else if (attr.indexOf("data-") === 0) {
  16018. var dataAttr = attr.substr(("data-").length);
  16019. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  16020. var translated = $.t(key, optionsToUse);
  16021. //we change into the data cache
  16022. ele.data(dataAttr, translated);
  16023. //we change into the dom
  16024. ele.attr(attr, translated);
  16025. } else {
  16026. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  16027. ele.attr(attr, $.t(key, optionsToUse));
  16028. }
  16029. }
  16030. function localize(ele, options) {
  16031. var key = ele.attr(o.selectorAttr);
  16032. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  16033. if (!key) return;
  16034. var target = ele
  16035. , targetSelector = ele.data("i18n-target");
  16036. if (targetSelector) {
  16037. target = ele.find(targetSelector) || ele;
  16038. }
  16039. if (!options && o.useDataAttrOptions === true) {
  16040. options = ele.data("i18n-options");
  16041. }
  16042. options = options || {};
  16043. if (key.indexOf(';') >= 0) {
  16044. var keys = key.split(';');
  16045. $.each(keys, function(m, k) {
  16046. if (k !== '') parse(target, k, options);
  16047. });
  16048. } else {
  16049. parse(target, key, options);
  16050. }
  16051. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  16052. }
  16053. // fn
  16054. $.fn.i18n = function (options) {
  16055. return this.each(function() {
  16056. // localize element itself
  16057. localize($(this), options);
  16058. // localize childs
  16059. var elements = $(this).find('[' + o.selectorAttr + ']');
  16060. elements.each(function() {
  16061. localize($(this), options);
  16062. });
  16063. });
  16064. };
  16065. }
  16066. function applyReplacement(str, replacementHash, nestedKey, options) {
  16067. if (!str) return str;
  16068. options = options || replacementHash; // first call uses replacement hash combined with options
  16069. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  16070. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  16071. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  16072. , unEscapingSuffix = 'HTML'+suffix;
  16073. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  16074. f.each(hash, function(key, value) {
  16075. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  16076. if (typeof value === 'object' && value !== null) {
  16077. str = applyReplacement(str, value, nextKey, options);
  16078. } else {
  16079. if (options.escapeInterpolation || o.escapeInterpolation) {
  16080. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  16081. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  16082. } else {
  16083. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  16084. }
  16085. // str = options.escapeInterpolation;
  16086. }
  16087. });
  16088. return str;
  16089. }
  16090. // append it to functions
  16091. f.applyReplacement = applyReplacement;
  16092. function applyReuse(translated, options) {
  16093. var comma = ',';
  16094. var options_open = '{';
  16095. var options_close = '}';
  16096. var opts = f.extend({}, options);
  16097. delete opts.postProcess;
  16098. while (translated.indexOf(o.reusePrefix) != -1) {
  16099. replacementCounter++;
  16100. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  16101. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  16102. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  16103. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  16104. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  16105. if (index_of_end_of_closing <= index_of_opening) {
  16106. f.error('there is an missing closing in following translation value', translated);
  16107. return '';
  16108. }
  16109. if (token_without_symbols.indexOf(comma) != -1) {
  16110. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  16111. 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) {
  16112. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  16113. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  16114. try {
  16115. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  16116. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  16117. } catch (e) {
  16118. }
  16119. }
  16120. }
  16121. var translated_token = _translate(token_without_symbols, opts);
  16122. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  16123. }
  16124. return translated;
  16125. }
  16126. function hasContext(options) {
  16127. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  16128. }
  16129. function needsPlural(options, lng) {
  16130. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  16131. }
  16132. function needsIndefiniteArticle(options) {
  16133. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  16134. }
  16135. function exists(key, options) {
  16136. options = options || {};
  16137. var notFound = _getDefaultValue(key, options)
  16138. , found = _find(key, options);
  16139. return found !== undefined || found === notFound;
  16140. }
  16141. function translate(key, options) {
  16142. options = options || {};
  16143. if (!initialized) {
  16144. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  16145. return options.defaultValue || '';
  16146. };
  16147. replacementCounter = 0;
  16148. return _translate.apply(null, arguments);
  16149. }
  16150. function _getDefaultValue(key, options) {
  16151. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  16152. }
  16153. function _injectSprintfProcessor() {
  16154. var values = [];
  16155. // mh: build array from second argument onwards
  16156. for (var i = 1; i < arguments.length; i++) {
  16157. values.push(arguments[i]);
  16158. }
  16159. return {
  16160. postProcess: 'sprintf',
  16161. sprintf: values
  16162. };
  16163. }
  16164. function _translate(potentialKeys, options) {
  16165. if (options && typeof options !== 'object') {
  16166. if (o.shortcutFunction === 'sprintf') {
  16167. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  16168. options = _injectSprintfProcessor.apply(null, arguments);
  16169. } else if (o.shortcutFunction === 'defaultValue') {
  16170. options = {
  16171. defaultValue: options
  16172. }
  16173. }
  16174. } else {
  16175. options = options || {};
  16176. }
  16177. if (typeof o.defaultVariables === 'object') {
  16178. options = f.extend({}, o.defaultVariables, options);
  16179. }
  16180. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  16181. if (typeof potentialKeys === 'string') {
  16182. potentialKeys = [potentialKeys];
  16183. }
  16184. var key = potentialKeys[0];
  16185. if (potentialKeys.length > 1) {
  16186. for (var i = 0; i < potentialKeys.length; i++) {
  16187. key = potentialKeys[i];
  16188. if (exists(key, options)) {
  16189. break;
  16190. }
  16191. }
  16192. }
  16193. var notFound = _getDefaultValue(key, options)
  16194. , found = _find(key, options)
  16195. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  16196. , ns = options.ns || o.ns.defaultNs
  16197. , parts;
  16198. // split ns and key
  16199. if (key.indexOf(o.nsseparator) > -1) {
  16200. parts = key.split(o.nsseparator);
  16201. ns = parts[0];
  16202. key = parts[1];
  16203. }
  16204. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  16205. if (options.lng) {
  16206. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  16207. } else {
  16208. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  16209. }
  16210. }
  16211. var postProcessor = options.postProcess || o.postProcess;
  16212. if (found !== undefined && postProcessor) {
  16213. if (postProcessors[postProcessor]) {
  16214. found = postProcessors[postProcessor](found, key, options);
  16215. }
  16216. }
  16217. // process notFound if function exists
  16218. var splitNotFound = notFound;
  16219. if (notFound.indexOf(o.nsseparator) > -1) {
  16220. parts = notFound.split(o.nsseparator);
  16221. splitNotFound = parts[1];
  16222. }
  16223. if (splitNotFound === key && o.parseMissingKey) {
  16224. notFound = o.parseMissingKey(notFound);
  16225. }
  16226. if (found === undefined) {
  16227. notFound = applyReplacement(notFound, options);
  16228. notFound = applyReuse(notFound, options);
  16229. if (postProcessor && postProcessors[postProcessor]) {
  16230. var val = _getDefaultValue(key, options);
  16231. found = postProcessors[postProcessor](val, key, options);
  16232. }
  16233. }
  16234. return (found !== undefined) ? found : notFound;
  16235. }
  16236. function _find(key, options) {
  16237. options = options || {};
  16238. var optionWithoutCount, translated
  16239. , notFound = _getDefaultValue(key, options)
  16240. , lngs = languages;
  16241. if (!resStore) { return notFound; } // no resStore to translate from
  16242. // CI mode
  16243. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  16244. // passed in lng
  16245. if (options.lngs) lngs = options.lngs;
  16246. if (options.lng) {
  16247. lngs = f.toLanguages(options.lng, options.fallbackLng);
  16248. if (!resStore[lngs[0]]) {
  16249. var oldAsync = o.getAsync;
  16250. o.getAsync = false;
  16251. i18n.sync.load(lngs, o, function(err, store) {
  16252. f.extend(resStore, store);
  16253. o.getAsync = oldAsync;
  16254. });
  16255. }
  16256. }
  16257. var ns = options.ns || o.ns.defaultNs;
  16258. if (key.indexOf(o.nsseparator) > -1) {
  16259. var parts = key.split(o.nsseparator);
  16260. ns = parts[0];
  16261. key = parts[1];
  16262. }
  16263. if (hasContext(options)) {
  16264. optionWithoutCount = f.extend({}, options);
  16265. delete optionWithoutCount.context;
  16266. optionWithoutCount.defaultValue = o.contextNotFound;
  16267. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  16268. translated = translate(contextKey, optionWithoutCount);
  16269. if (translated != o.contextNotFound) {
  16270. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  16271. } // else continue translation with original/nonContext key
  16272. }
  16273. if (needsPlural(options, lngs[0])) {
  16274. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  16275. delete optionWithoutCount.count;
  16276. delete optionWithoutCount.lng;
  16277. optionWithoutCount.defaultValue = o.pluralNotFound;
  16278. var pluralKey;
  16279. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  16280. pluralKey = ns + o.nsseparator + key;
  16281. } else {
  16282. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  16283. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  16284. if (pluralExtension >= 0) {
  16285. pluralKey = pluralKey + '_' + pluralExtension;
  16286. } else if (pluralExtension === 1) {
  16287. pluralKey = ns + o.nsseparator + key; // singular
  16288. }
  16289. }
  16290. translated = translate(pluralKey, optionWithoutCount);
  16291. if (translated != o.pluralNotFound) {
  16292. return applyReplacement(translated, {
  16293. count: options.count,
  16294. interpolationPrefix: options.interpolationPrefix,
  16295. interpolationSuffix: options.interpolationSuffix
  16296. }); // apply replacement for count only
  16297. } else if (lngs.length > 1) {
  16298. // remove failed lng
  16299. var clone = lngs.slice();
  16300. clone.shift();
  16301. options = f.extend(options, { lngs: clone });
  16302. delete options.lng;
  16303. // retry with fallbacks
  16304. translated = translate(ns + o.nsseparator + key, options);
  16305. if (translated != o.pluralNotFound) return translated;
  16306. } else {
  16307. return translated;
  16308. }
  16309. }
  16310. if (needsIndefiniteArticle(options)) {
  16311. var optionsWithoutIndef = f.extend({}, options);
  16312. delete optionsWithoutIndef.indefinite_article;
  16313. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  16314. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  16315. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  16316. translated = translate(indefiniteKey, optionsWithoutIndef);
  16317. if (translated != o.indefiniteNotFound) {
  16318. return translated;
  16319. }
  16320. }
  16321. var found;
  16322. var keys = key.split(o.keyseparator);
  16323. for (var i = 0, len = lngs.length; i < len; i++ ) {
  16324. if (found !== undefined) break;
  16325. var l = lngs[i];
  16326. var x = 0;
  16327. var value = resStore[l] && resStore[l][ns];
  16328. while (keys[x]) {
  16329. value = value && value[keys[x]];
  16330. x++;
  16331. }
  16332. if (value !== undefined) {
  16333. var valueType = Object.prototype.toString.apply(value);
  16334. if (typeof value === 'string') {
  16335. value = applyReplacement(value, options);
  16336. value = applyReuse(value, options);
  16337. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  16338. value = value.join('\n');
  16339. value = applyReplacement(value, options);
  16340. value = applyReuse(value, options);
  16341. } else if (value === null && o.fallbackOnNull === true) {
  16342. value = undefined;
  16343. } else if (value !== null) {
  16344. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  16345. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  16346. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  16347. } else {
  16348. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  16349. 'returned an object instead of string.';
  16350. f.log(value);
  16351. }
  16352. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  16353. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  16354. f.each(value, function(m) {
  16355. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  16356. });
  16357. value = copy;
  16358. }
  16359. }
  16360. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  16361. value = undefined;
  16362. found = value;
  16363. }
  16364. }
  16365. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  16366. // set flag for fallback lookup - avoid recursion
  16367. options.isFallbackLookup = true;
  16368. if (o.fallbackNS.length) {
  16369. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  16370. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  16371. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  16372. /* compare value without namespace */
  16373. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  16374. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  16375. if (foundValue !== notFoundValue) break;
  16376. }
  16377. }
  16378. } else {
  16379. found = _find(key, options); // fallback to default NS
  16380. }
  16381. options.isFallbackLookup = false;
  16382. }
  16383. return found;
  16384. }
  16385. function detectLanguage() {
  16386. var detectedLng;
  16387. var whitelist = o.lngWhitelist || [];
  16388. var userLngChoices = [];
  16389. // get from qs
  16390. var qsParm = [];
  16391. if (typeof window !== 'undefined') {
  16392. (function() {
  16393. var query = window.location.search.substring(1);
  16394. var params = query.split('&');
  16395. for (var i=0; i<params.length; i++) {
  16396. var pos = params[i].indexOf('=');
  16397. if (pos > 0) {
  16398. var key = params[i].substring(0,pos);
  16399. if (key == o.detectLngQS) {
  16400. userLngChoices.push(params[i].substring(pos+1));
  16401. }
  16402. }
  16403. }
  16404. })();
  16405. }
  16406. // get from cookie
  16407. if (o.useCookie && typeof document !== 'undefined') {
  16408. var c = f.cookie.read(o.cookieName);
  16409. if (c) userLngChoices.push(c);
  16410. }
  16411. // get from localStorage
  16412. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  16413. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  16414. }
  16415. // get from navigator
  16416. if (typeof navigator !== 'undefined') {
  16417. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  16418. for (var i=0;i<navigator.languages.length;i++) {
  16419. userLngChoices.push(navigator.languages[i]);
  16420. }
  16421. }
  16422. if (navigator.userLanguage) {
  16423. userLngChoices.push(navigator.userLanguage);
  16424. }
  16425. if (navigator.language) {
  16426. userLngChoices.push(navigator.language);
  16427. }
  16428. }
  16429. (function() {
  16430. for (var i=0;i<userLngChoices.length;i++) {
  16431. var lng = userLngChoices[i];
  16432. if (lng.indexOf('-') > -1) {
  16433. var parts = lng.split('-');
  16434. lng = o.lowerCaseLng ?
  16435. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  16436. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  16437. }
  16438. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  16439. detectedLng = lng;
  16440. break;
  16441. }
  16442. }
  16443. })();
  16444. //fallback
  16445. if (!detectedLng){
  16446. detectedLng = o.fallbackLng[0];
  16447. }
  16448. return detectedLng;
  16449. }
  16450. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  16451. /* [code, name, numbers, pluralsType] */
  16452. var _rules = [
  16453. ["ach", "Acholi", [1,2], 1],
  16454. ["af", "Afrikaans",[1,2], 2],
  16455. ["ak", "Akan", [1,2], 1],
  16456. ["am", "Amharic", [1,2], 1],
  16457. ["an", "Aragonese",[1,2], 2],
  16458. ["ar", "Arabic", [0,1,2,3,11,100],5],
  16459. ["arn", "Mapudungun",[1,2], 1],
  16460. ["ast", "Asturian", [1,2], 2],
  16461. ["ay", "Aymará", [1], 3],
  16462. ["az", "Azerbaijani",[1,2],2],
  16463. ["be", "Belarusian",[1,2,5],4],
  16464. ["bg", "Bulgarian",[1,2], 2],
  16465. ["bn", "Bengali", [1,2], 2],
  16466. ["bo", "Tibetan", [1], 3],
  16467. ["br", "Breton", [1,2], 1],
  16468. ["bs", "Bosnian", [1,2,5],4],
  16469. ["ca", "Catalan", [1,2], 2],
  16470. ["cgg", "Chiga", [1], 3],
  16471. ["cs", "Czech", [1,2,5],6],
  16472. ["csb", "Kashubian",[1,2,5],7],
  16473. ["cy", "Welsh", [1,2,3,8],8],
  16474. ["da", "Danish", [1,2], 2],
  16475. ["de", "German", [1,2], 2],
  16476. ["dev", "Development Fallback", [1,2], 2],
  16477. ["dz", "Dzongkha", [1], 3],
  16478. ["el", "Greek", [1,2], 2],
  16479. ["en", "English", [1,2], 2],
  16480. ["eo", "Esperanto",[1,2], 2],
  16481. ["es", "Spanish", [1,2], 2],
  16482. ["es_ar","Argentinean Spanish", [1,2], 2],
  16483. ["et", "Estonian", [1,2], 2],
  16484. ["eu", "Basque", [1,2], 2],
  16485. ["fa", "Persian", [1], 3],
  16486. ["fi", "Finnish", [1,2], 2],
  16487. ["fil", "Filipino", [1,2], 1],
  16488. ["fo", "Faroese", [1,2], 2],
  16489. ["fr", "French", [1,2], 9],
  16490. ["fur", "Friulian", [1,2], 2],
  16491. ["fy", "Frisian", [1,2], 2],
  16492. ["ga", "Irish", [1,2,3,7,11],10],
  16493. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  16494. ["gl", "Galician", [1,2], 2],
  16495. ["gu", "Gujarati", [1,2], 2],
  16496. ["gun", "Gun", [1,2], 1],
  16497. ["ha", "Hausa", [1,2], 2],
  16498. ["he", "Hebrew", [1,2], 2],
  16499. ["hi", "Hindi", [1,2], 2],
  16500. ["hr", "Croatian", [1,2,5],4],
  16501. ["hu", "Hungarian",[1,2], 2],
  16502. ["hy", "Armenian", [1,2], 2],
  16503. ["ia", "Interlingua",[1,2],2],
  16504. ["id", "Indonesian",[1], 3],
  16505. ["is", "Icelandic",[1,2], 12],
  16506. ["it", "Italian", [1,2], 2],
  16507. ["ja", "Japanese", [1], 3],
  16508. ["jbo", "Lojban", [1], 3],
  16509. ["jv", "Javanese", [0,1], 13],
  16510. ["ka", "Georgian", [1], 3],
  16511. ["kk", "Kazakh", [1], 3],
  16512. ["km", "Khmer", [1], 3],
  16513. ["kn", "Kannada", [1,2], 2],
  16514. ["ko", "Korean", [1], 3],
  16515. ["ku", "Kurdish", [1,2], 2],
  16516. ["kw", "Cornish", [1,2,3,4],14],
  16517. ["ky", "Kyrgyz", [1], 3],
  16518. ["lb", "Letzeburgesch",[1,2],2],
  16519. ["ln", "Lingala", [1,2], 1],
  16520. ["lo", "Lao", [1], 3],
  16521. ["lt", "Lithuanian",[1,2,10],15],
  16522. ["lv", "Latvian", [1,2,0],16],
  16523. ["mai", "Maithili", [1,2], 2],
  16524. ["mfe", "Mauritian Creole",[1,2],1],
  16525. ["mg", "Malagasy", [1,2], 1],
  16526. ["mi", "Maori", [1,2], 1],
  16527. ["mk", "Macedonian",[1,2],17],
  16528. ["ml", "Malayalam",[1,2], 2],
  16529. ["mn", "Mongolian",[1,2], 2],
  16530. ["mnk", "Mandinka", [0,1,2],18],
  16531. ["mr", "Marathi", [1,2], 2],
  16532. ["ms", "Malay", [1], 3],
  16533. ["mt", "Maltese", [1,2,11,20],19],
  16534. ["nah", "Nahuatl", [1,2], 2],
  16535. ["nap", "Neapolitan",[1,2], 2],
  16536. ["nb", "Norwegian Bokmal",[1,2],2],
  16537. ["ne", "Nepali", [1,2], 2],
  16538. ["nl", "Dutch", [1,2], 2],
  16539. ["nn", "Norwegian Nynorsk",[1,2],2],
  16540. ["no", "Norwegian",[1,2], 2],
  16541. ["nso", "Northern Sotho",[1,2],2],
  16542. ["oc", "Occitan", [1,2], 1],
  16543. ["or", "Oriya", [2,1], 2],
  16544. ["pa", "Punjabi", [1,2], 2],
  16545. ["pap", "Papiamento",[1,2], 2],
  16546. ["pl", "Polish", [1,2,5],7],
  16547. ["pms", "Piemontese",[1,2], 2],
  16548. ["ps", "Pashto", [1,2], 2],
  16549. ["pt", "Portuguese",[1,2], 2],
  16550. ["pt_br","Brazilian Portuguese",[1,2], 2],
  16551. ["rm", "Romansh", [1,2], 2],
  16552. ["ro", "Romanian", [1,2,20],20],
  16553. ["ru", "Russian", [1,2,5],4],
  16554. ["sah", "Yakut", [1], 3],
  16555. ["sco", "Scots", [1,2], 2],
  16556. ["se", "Northern Sami",[1,2], 2],
  16557. ["si", "Sinhala", [1,2], 2],
  16558. ["sk", "Slovak", [1,2,5],6],
  16559. ["sl", "Slovenian",[5,1,2,3],21],
  16560. ["so", "Somali", [1,2], 2],
  16561. ["son", "Songhay", [1,2], 2],
  16562. ["sq", "Albanian", [1,2], 2],
  16563. ["sr", "Serbian", [1,2,5],4],
  16564. ["su", "Sundanese",[1], 3],
  16565. ["sv", "Swedish", [1,2], 2],
  16566. ["sw", "Swahili", [1,2], 2],
  16567. ["ta", "Tamil", [1,2], 2],
  16568. ["te", "Telugu", [1,2], 2],
  16569. ["tg", "Tajik", [1,2], 1],
  16570. ["th", "Thai", [1], 3],
  16571. ["ti", "Tigrinya", [1,2], 1],
  16572. ["tk", "Turkmen", [1,2], 2],
  16573. ["tr", "Turkish", [1,2], 1],
  16574. ["tt", "Tatar", [1], 3],
  16575. ["ug", "Uyghur", [1], 3],
  16576. ["uk", "Ukrainian",[1,2,5],4],
  16577. ["ur", "Urdu", [1,2], 2],
  16578. ["uz", "Uzbek", [1,2], 1],
  16579. ["vi", "Vietnamese",[1], 3],
  16580. ["wa", "Walloon", [1,2], 1],
  16581. ["wo", "Wolof", [1], 3],
  16582. ["yo", "Yoruba", [1,2], 2],
  16583. ["zh", "Chinese", [1], 3]
  16584. ];
  16585. var _rulesPluralsTypes = {
  16586. 1: function(n) {return Number(n > 1);},
  16587. 2: function(n) {return Number(n != 1);},
  16588. 3: function(n) {return 0;},
  16589. 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);},
  16590. 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);},
  16591. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  16592. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16593. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  16594. 9: function(n) {return Number(n >= 2);},
  16595. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  16596. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  16597. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  16598. 13: function(n) {return Number(n !== 0);},
  16599. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  16600. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16601. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  16602. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  16603. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  16604. 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);},
  16605. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  16606. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  16607. };
  16608. var pluralExtensions = {
  16609. rules: (function () {
  16610. var l, rules = {};
  16611. for (l=_rules.length; l-- ;) {
  16612. rules[_rules[l][0]] = {
  16613. name: _rules[l][1],
  16614. numbers: _rules[l][2],
  16615. plurals: _rulesPluralsTypes[_rules[l][3]]
  16616. }
  16617. }
  16618. return rules;
  16619. }()),
  16620. // you can add your own pluralExtensions
  16621. addRule: function(lng, obj) {
  16622. pluralExtensions.rules[lng] = obj;
  16623. },
  16624. setCurrentLng: function(lng) {
  16625. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  16626. var parts = lng.split('-');
  16627. pluralExtensions.currentRule = {
  16628. lng: lng,
  16629. rule: pluralExtensions.rules[parts[0]]
  16630. };
  16631. }
  16632. },
  16633. needsPlural: function(lng, count) {
  16634. var parts = lng.split('-');
  16635. var ext;
  16636. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16637. ext = pluralExtensions.currentRule.rule;
  16638. } else {
  16639. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  16640. }
  16641. if (ext && ext.numbers.length <= 1) {
  16642. return false;
  16643. } else {
  16644. return this.get(lng, count) !== 1;
  16645. }
  16646. },
  16647. get: function(lng, count) {
  16648. var parts = lng.split('-');
  16649. function getResult(l, c) {
  16650. var ext;
  16651. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16652. ext = pluralExtensions.currentRule.rule;
  16653. } else {
  16654. ext = pluralExtensions.rules[l];
  16655. }
  16656. if (ext) {
  16657. var i;
  16658. if (ext.noAbs) {
  16659. i = ext.plurals(c);
  16660. } else {
  16661. i = ext.plurals(Math.abs(c));
  16662. }
  16663. var number = ext.numbers[i];
  16664. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  16665. if (number === 2) {
  16666. number = -1; // regular plural
  16667. } else if (number === 1) {
  16668. number = 1; // singular
  16669. }
  16670. }//console.log(count + '-' + number);
  16671. return number;
  16672. } else {
  16673. return c === 1 ? '1' : '-1';
  16674. }
  16675. }
  16676. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  16677. }
  16678. };
  16679. var postProcessors = {};
  16680. var addPostProcessor = function(name, fc) {
  16681. postProcessors[name] = fc;
  16682. };
  16683. // sprintf support
  16684. var sprintf = (function() {
  16685. function get_type(variable) {
  16686. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  16687. }
  16688. function str_repeat(input, multiplier) {
  16689. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  16690. return output.join('');
  16691. }
  16692. var str_format = function() {
  16693. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  16694. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  16695. }
  16696. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  16697. };
  16698. str_format.format = function(parse_tree, argv) {
  16699. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  16700. for (i = 0; i < tree_length; i++) {
  16701. node_type = get_type(parse_tree[i]);
  16702. if (node_type === 'string') {
  16703. output.push(parse_tree[i]);
  16704. }
  16705. else if (node_type === 'array') {
  16706. match = parse_tree[i]; // convenience purposes only
  16707. if (match[2]) { // keyword argument
  16708. arg = argv[cursor];
  16709. for (k = 0; k < match[2].length; k++) {
  16710. if (!arg.hasOwnProperty(match[2][k])) {
  16711. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  16712. }
  16713. arg = arg[match[2][k]];
  16714. }
  16715. }
  16716. else if (match[1]) { // positional argument (explicit)
  16717. arg = argv[match[1]];
  16718. }
  16719. else { // positional argument (implicit)
  16720. arg = argv[cursor++];
  16721. }
  16722. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  16723. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  16724. }
  16725. switch (match[8]) {
  16726. case 'b': arg = arg.toString(2); break;
  16727. case 'c': arg = String.fromCharCode(arg); break;
  16728. case 'd': arg = parseInt(arg, 10); break;
  16729. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  16730. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  16731. case 'o': arg = arg.toString(8); break;
  16732. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  16733. case 'u': arg = Math.abs(arg); break;
  16734. case 'x': arg = arg.toString(16); break;
  16735. case 'X': arg = arg.toString(16).toUpperCase(); break;
  16736. }
  16737. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  16738. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  16739. pad_length = match[6] - String(arg).length;
  16740. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  16741. output.push(match[5] ? arg + pad : pad + arg);
  16742. }
  16743. }
  16744. return output.join('');
  16745. };
  16746. str_format.cache = {};
  16747. str_format.parse = function(fmt) {
  16748. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  16749. while (_fmt) {
  16750. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  16751. parse_tree.push(match[0]);
  16752. }
  16753. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  16754. parse_tree.push('%');
  16755. }
  16756. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  16757. if (match[2]) {
  16758. arg_names |= 1;
  16759. var field_list = [], replacement_field = match[2], field_match = [];
  16760. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16761. field_list.push(field_match[1]);
  16762. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  16763. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16764. field_list.push(field_match[1]);
  16765. }
  16766. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  16767. field_list.push(field_match[1]);
  16768. }
  16769. else {
  16770. throw('[sprintf] huh?');
  16771. }
  16772. }
  16773. }
  16774. else {
  16775. throw('[sprintf] huh?');
  16776. }
  16777. match[2] = field_list;
  16778. }
  16779. else {
  16780. arg_names |= 2;
  16781. }
  16782. if (arg_names === 3) {
  16783. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  16784. }
  16785. parse_tree.push(match);
  16786. }
  16787. else {
  16788. throw('[sprintf] huh?');
  16789. }
  16790. _fmt = _fmt.substring(match[0].length);
  16791. }
  16792. return parse_tree;
  16793. };
  16794. return str_format;
  16795. })();
  16796. var vsprintf = function(fmt, argv) {
  16797. argv.unshift(fmt);
  16798. return sprintf.apply(null, argv);
  16799. };
  16800. addPostProcessor("sprintf", function(val, key, opts) {
  16801. if (!opts.sprintf) return val;
  16802. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  16803. return vsprintf(val, opts.sprintf);
  16804. } else if (typeof opts.sprintf === 'object') {
  16805. return sprintf(val, opts.sprintf);
  16806. }
  16807. return val;
  16808. });
  16809. // public api interface
  16810. i18n.init = init;
  16811. i18n.setLng = setLng;
  16812. i18n.preload = preload;
  16813. i18n.addResourceBundle = addResourceBundle;
  16814. i18n.hasResourceBundle = hasResourceBundle;
  16815. i18n.addResource = addResource;
  16816. i18n.addResources = addResources;
  16817. i18n.removeResourceBundle = removeResourceBundle;
  16818. i18n.loadNamespace = loadNamespace;
  16819. i18n.loadNamespaces = loadNamespaces;
  16820. i18n.setDefaultNamespace = setDefaultNamespace;
  16821. i18n.t = translate;
  16822. i18n.translate = translate;
  16823. i18n.exists = exists;
  16824. i18n.detectLanguage = f.detectLanguage;
  16825. i18n.pluralExtensions = pluralExtensions;
  16826. i18n.sync = sync;
  16827. i18n.functions = f;
  16828. i18n.lng = lng;
  16829. i18n.addPostProcessor = addPostProcessor;
  16830. i18n.options = o;
  16831. })();
  16832. },{"jquery":"jquery"}],63:[function(require,module,exports){
  16833. // Top level file is just a mixin of submodules & constants
  16834. 'use strict';
  16835. var assign = require('./lib/utils/common').assign;
  16836. var deflate = require('./lib/deflate');
  16837. var inflate = require('./lib/inflate');
  16838. var constants = require('./lib/zlib/constants');
  16839. var pako = {};
  16840. assign(pako, deflate, inflate, constants);
  16841. module.exports = pako;
  16842. },{"./lib/deflate":64,"./lib/inflate":65,"./lib/utils/common":66,"./lib/zlib/constants":69}],64:[function(require,module,exports){
  16843. 'use strict';
  16844. var zlib_deflate = require('./zlib/deflate.js');
  16845. var utils = require('./utils/common');
  16846. var strings = require('./utils/strings');
  16847. var msg = require('./zlib/messages');
  16848. var zstream = require('./zlib/zstream');
  16849. /* Public constants ==========================================================*/
  16850. /* ===========================================================================*/
  16851. var Z_NO_FLUSH = 0;
  16852. var Z_FINISH = 4;
  16853. var Z_OK = 0;
  16854. var Z_STREAM_END = 1;
  16855. var Z_DEFAULT_COMPRESSION = -1;
  16856. var Z_DEFAULT_STRATEGY = 0;
  16857. var Z_DEFLATED = 8;
  16858. /* ===========================================================================*/
  16859. /**
  16860. * class Deflate
  16861. *
  16862. * Generic JS-style wrapper for zlib calls. If you don't need
  16863. * streaming behaviour - use more simple functions: [[deflate]],
  16864. * [[deflateRaw]] and [[gzip]].
  16865. **/
  16866. /* internal
  16867. * Deflate.chunks -> Array
  16868. *
  16869. * Chunks of output data, if [[Deflate#onData]] not overriden.
  16870. **/
  16871. /**
  16872. * Deflate.result -> Uint8Array|Array
  16873. *
  16874. * Compressed result, generated by default [[Deflate#onData]]
  16875. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  16876. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  16877. **/
  16878. /**
  16879. * Deflate.err -> Number
  16880. *
  16881. * Error code after deflate finished. 0 (Z_OK) on success.
  16882. * You will not need it in real life, because deflate errors
  16883. * are possible only on wrong options or bad `onData` / `onEnd`
  16884. * custom handlers.
  16885. **/
  16886. /**
  16887. * Deflate.msg -> String
  16888. *
  16889. * Error message, if [[Deflate.err]] != 0
  16890. **/
  16891. /**
  16892. * new Deflate(options)
  16893. * - options (Object): zlib deflate options.
  16894. *
  16895. * Creates new deflator instance with specified params. Throws exception
  16896. * on bad params. Supported options:
  16897. *
  16898. * - `level`
  16899. * - `windowBits`
  16900. * - `memLevel`
  16901. * - `strategy`
  16902. *
  16903. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  16904. * for more information on these.
  16905. *
  16906. * Additional options, for internal needs:
  16907. *
  16908. * - `chunkSize` - size of generated data chunks (16K by default)
  16909. * - `raw` (Boolean) - do raw deflate
  16910. * - `gzip` (Boolean) - create gzip wrapper
  16911. * - `to` (String) - if equal to 'string', then result will be "binary string"
  16912. * (each char code [0..255])
  16913. * - `header` (Object) - custom header for gzip
  16914. * - `text` (Boolean) - true if compressed data believed to be text
  16915. * - `time` (Number) - modification time, unix timestamp
  16916. * - `os` (Number) - operation system code
  16917. * - `extra` (Array) - array of bytes with extra data (max 65536)
  16918. * - `name` (String) - file name (binary string)
  16919. * - `comment` (String) - comment (binary string)
  16920. * - `hcrc` (Boolean) - true if header crc should be added
  16921. *
  16922. * ##### Example:
  16923. *
  16924. * ```javascript
  16925. * var pako = require('pako')
  16926. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  16927. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  16928. *
  16929. * var deflate = new pako.Deflate({ level: 3});
  16930. *
  16931. * deflate.push(chunk1, false);
  16932. * deflate.push(chunk2, true); // true -> last chunk
  16933. *
  16934. * if (deflate.err) { throw new Error(deflate.err); }
  16935. *
  16936. * console.log(deflate.result);
  16937. * ```
  16938. **/
  16939. var Deflate = function(options) {
  16940. this.options = utils.assign({
  16941. level: Z_DEFAULT_COMPRESSION,
  16942. method: Z_DEFLATED,
  16943. chunkSize: 16384,
  16944. windowBits: 15,
  16945. memLevel: 8,
  16946. strategy: Z_DEFAULT_STRATEGY,
  16947. to: ''
  16948. }, options || {});
  16949. var opt = this.options;
  16950. if (opt.raw && (opt.windowBits > 0)) {
  16951. opt.windowBits = -opt.windowBits;
  16952. }
  16953. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  16954. opt.windowBits += 16;
  16955. }
  16956. this.err = 0; // error code, if happens (0 = Z_OK)
  16957. this.msg = ''; // error message
  16958. this.ended = false; // used to avoid multiple onEnd() calls
  16959. this.chunks = []; // chunks of compressed data
  16960. this.strm = new zstream();
  16961. this.strm.avail_out = 0;
  16962. var status = zlib_deflate.deflateInit2(
  16963. this.strm,
  16964. opt.level,
  16965. opt.method,
  16966. opt.windowBits,
  16967. opt.memLevel,
  16968. opt.strategy
  16969. );
  16970. if (status !== Z_OK) {
  16971. throw new Error(msg[status]);
  16972. }
  16973. if (opt.header) {
  16974. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  16975. }
  16976. };
  16977. /**
  16978. * Deflate#push(data[, mode]) -> Boolean
  16979. * - data (Uint8Array|Array|String): input data. Strings will be converted to
  16980. * utf8 byte sequence.
  16981. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  16982. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  16983. *
  16984. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  16985. * new compressed chunks. Returns `true` on success. The last data block must have
  16986. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  16987. * [[Deflate#onEnd]].
  16988. *
  16989. * On fail call [[Deflate#onEnd]] with error code and return false.
  16990. *
  16991. * We strongly recommend to use `Uint8Array` on input for best speed (output
  16992. * array format is detected automatically). Also, don't skip last param and always
  16993. * use the same type in your code (boolean or number). That will improve JS speed.
  16994. *
  16995. * For regular `Array`-s make sure all elements are [0..255].
  16996. *
  16997. * ##### Example
  16998. *
  16999. * ```javascript
  17000. * push(chunk, false); // push one of data chunks
  17001. * ...
  17002. * push(chunk, true); // push last chunk
  17003. * ```
  17004. **/
  17005. Deflate.prototype.push = function(data, mode) {
  17006. var strm = this.strm;
  17007. var chunkSize = this.options.chunkSize;
  17008. var status, _mode;
  17009. if (this.ended) { return false; }
  17010. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  17011. // Convert data if needed
  17012. if (typeof data === 'string') {
  17013. // If we need to compress text, change encoding to utf8.
  17014. strm.input = strings.string2buf(data);
  17015. } else {
  17016. strm.input = data;
  17017. }
  17018. strm.next_in = 0;
  17019. strm.avail_in = strm.input.length;
  17020. do {
  17021. if (strm.avail_out === 0) {
  17022. strm.output = new utils.Buf8(chunkSize);
  17023. strm.next_out = 0;
  17024. strm.avail_out = chunkSize;
  17025. }
  17026. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  17027. if (status !== Z_STREAM_END && status !== Z_OK) {
  17028. this.onEnd(status);
  17029. this.ended = true;
  17030. return false;
  17031. }
  17032. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  17033. if (this.options.to === 'string') {
  17034. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  17035. } else {
  17036. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17037. }
  17038. }
  17039. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  17040. // Finalize on the last chunk.
  17041. if (_mode === Z_FINISH) {
  17042. status = zlib_deflate.deflateEnd(this.strm);
  17043. this.onEnd(status);
  17044. this.ended = true;
  17045. return status === Z_OK;
  17046. }
  17047. return true;
  17048. };
  17049. /**
  17050. * Deflate#onData(chunk) -> Void
  17051. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17052. * on js engine support. When string output requested, each chunk
  17053. * will be string.
  17054. *
  17055. * By default, stores data blocks in `chunks[]` property and glue
  17056. * those in `onEnd`. Override this handler, if you need another behaviour.
  17057. **/
  17058. Deflate.prototype.onData = function(chunk) {
  17059. this.chunks.push(chunk);
  17060. };
  17061. /**
  17062. * Deflate#onEnd(status) -> Void
  17063. * - status (Number): deflate status. 0 (Z_OK) on success,
  17064. * other if not.
  17065. *
  17066. * Called once after you tell deflate that input stream complete
  17067. * or error happenned. By default - join collected chunks,
  17068. * free memory and fill `results` / `err` properties.
  17069. **/
  17070. Deflate.prototype.onEnd = function(status) {
  17071. // On success - join
  17072. if (status === Z_OK) {
  17073. if (this.options.to === 'string') {
  17074. this.result = this.chunks.join('');
  17075. } else {
  17076. this.result = utils.flattenChunks(this.chunks);
  17077. }
  17078. }
  17079. this.chunks = [];
  17080. this.err = status;
  17081. this.msg = this.strm.msg;
  17082. };
  17083. /**
  17084. * deflate(data[, options]) -> Uint8Array|Array|String
  17085. * - data (Uint8Array|Array|String): input data to compress.
  17086. * - options (Object): zlib deflate options.
  17087. *
  17088. * Compress `data` with deflate alrorythm and `options`.
  17089. *
  17090. * Supported options are:
  17091. *
  17092. * - level
  17093. * - windowBits
  17094. * - memLevel
  17095. * - strategy
  17096. *
  17097. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17098. * for more information on these.
  17099. *
  17100. * Sugar (options):
  17101. *
  17102. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17103. * negative windowBits implicitly.
  17104. * - `to` (String) - if equal to 'string', then result will be "binary string"
  17105. * (each char code [0..255])
  17106. *
  17107. * ##### Example:
  17108. *
  17109. * ```javascript
  17110. * var pako = require('pako')
  17111. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  17112. *
  17113. * console.log(pako.deflate(data));
  17114. * ```
  17115. **/
  17116. function deflate(input, options) {
  17117. var deflator = new Deflate(options);
  17118. deflator.push(input, true);
  17119. // That will never happens, if you don't cheat with options :)
  17120. if (deflator.err) { throw deflator.msg; }
  17121. return deflator.result;
  17122. }
  17123. /**
  17124. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  17125. * - data (Uint8Array|Array|String): input data to compress.
  17126. * - options (Object): zlib deflate options.
  17127. *
  17128. * The same as [[deflate]], but creates raw data, without wrapper
  17129. * (header and adler32 crc).
  17130. **/
  17131. function deflateRaw(input, options) {
  17132. options = options || {};
  17133. options.raw = true;
  17134. return deflate(input, options);
  17135. }
  17136. /**
  17137. * gzip(data[, options]) -> Uint8Array|Array|String
  17138. * - data (Uint8Array|Array|String): input data to compress.
  17139. * - options (Object): zlib deflate options.
  17140. *
  17141. * The same as [[deflate]], but create gzip wrapper instead of
  17142. * deflate one.
  17143. **/
  17144. function gzip(input, options) {
  17145. options = options || {};
  17146. options.gzip = true;
  17147. return deflate(input, options);
  17148. }
  17149. exports.Deflate = Deflate;
  17150. exports.deflate = deflate;
  17151. exports.deflateRaw = deflateRaw;
  17152. exports.gzip = gzip;
  17153. },{"./utils/common":66,"./utils/strings":67,"./zlib/deflate.js":71,"./zlib/messages":76,"./zlib/zstream":78}],65:[function(require,module,exports){
  17154. 'use strict';
  17155. var zlib_inflate = require('./zlib/inflate.js');
  17156. var utils = require('./utils/common');
  17157. var strings = require('./utils/strings');
  17158. var c = require('./zlib/constants');
  17159. var msg = require('./zlib/messages');
  17160. var zstream = require('./zlib/zstream');
  17161. var gzheader = require('./zlib/gzheader');
  17162. /**
  17163. * class Inflate
  17164. *
  17165. * Generic JS-style wrapper for zlib calls. If you don't need
  17166. * streaming behaviour - use more simple functions: [[inflate]]
  17167. * and [[inflateRaw]].
  17168. **/
  17169. /* internal
  17170. * inflate.chunks -> Array
  17171. *
  17172. * Chunks of output data, if [[Inflate#onData]] not overriden.
  17173. **/
  17174. /**
  17175. * Inflate.result -> Uint8Array|Array|String
  17176. *
  17177. * Uncompressed result, generated by default [[Inflate#onData]]
  17178. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  17179. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  17180. **/
  17181. /**
  17182. * Inflate.err -> Number
  17183. *
  17184. * Error code after inflate finished. 0 (Z_OK) on success.
  17185. * Should be checked if broken data possible.
  17186. **/
  17187. /**
  17188. * Inflate.msg -> String
  17189. *
  17190. * Error message, if [[Inflate.err]] != 0
  17191. **/
  17192. /**
  17193. * new Inflate(options)
  17194. * - options (Object): zlib inflate options.
  17195. *
  17196. * Creates new inflator instance with specified params. Throws exception
  17197. * on bad params. Supported options:
  17198. *
  17199. * - `windowBits`
  17200. *
  17201. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17202. * for more information on these.
  17203. *
  17204. * Additional options, for internal needs:
  17205. *
  17206. * - `chunkSize` - size of generated data chunks (16K by default)
  17207. * - `raw` (Boolean) - do raw inflate
  17208. * - `to` (String) - if equal to 'string', then result will be converted
  17209. * from utf8 to utf16 (javascript) string. When string output requested,
  17210. * chunk length can differ from `chunkSize`, depending on content.
  17211. *
  17212. * By default, when no options set, autodetect deflate/gzip data format via
  17213. * wrapper header.
  17214. *
  17215. * ##### Example:
  17216. *
  17217. * ```javascript
  17218. * var pako = require('pako')
  17219. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17220. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17221. *
  17222. * var inflate = new pako.Inflate({ level: 3});
  17223. *
  17224. * inflate.push(chunk1, false);
  17225. * inflate.push(chunk2, true); // true -> last chunk
  17226. *
  17227. * if (inflate.err) { throw new Error(inflate.err); }
  17228. *
  17229. * console.log(inflate.result);
  17230. * ```
  17231. **/
  17232. var Inflate = function(options) {
  17233. this.options = utils.assign({
  17234. chunkSize: 16384,
  17235. windowBits: 0,
  17236. to: ''
  17237. }, options || {});
  17238. var opt = this.options;
  17239. // Force window size for `raw` data, if not set directly,
  17240. // because we have no header for autodetect.
  17241. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  17242. opt.windowBits = -opt.windowBits;
  17243. if (opt.windowBits === 0) { opt.windowBits = -15; }
  17244. }
  17245. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  17246. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  17247. !(options && options.windowBits)) {
  17248. opt.windowBits += 32;
  17249. }
  17250. // Gzip header has no info about windows size, we can do autodetect only
  17251. // for deflate. So, if window size not set, force it to max when gzip possible
  17252. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  17253. // bit 3 (16) -> gzipped data
  17254. // bit 4 (32) -> autodetect gzip/deflate
  17255. if ((opt.windowBits & 15) === 0) {
  17256. opt.windowBits |= 15;
  17257. }
  17258. }
  17259. this.err = 0; // error code, if happens (0 = Z_OK)
  17260. this.msg = ''; // error message
  17261. this.ended = false; // used to avoid multiple onEnd() calls
  17262. this.chunks = []; // chunks of compressed data
  17263. this.strm = new zstream();
  17264. this.strm.avail_out = 0;
  17265. var status = zlib_inflate.inflateInit2(
  17266. this.strm,
  17267. opt.windowBits
  17268. );
  17269. if (status !== c.Z_OK) {
  17270. throw new Error(msg[status]);
  17271. }
  17272. this.header = new gzheader();
  17273. zlib_inflate.inflateGetHeader(this.strm, this.header);
  17274. };
  17275. /**
  17276. * Inflate#push(data[, mode]) -> Boolean
  17277. * - data (Uint8Array|Array|String): input data
  17278. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17279. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17280. *
  17281. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  17282. * new output chunks. Returns `true` on success. The last data block must have
  17283. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17284. * [[Inflate#onEnd]].
  17285. *
  17286. * On fail call [[Inflate#onEnd]] with error code and return false.
  17287. *
  17288. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17289. * format is detected automatically). Also, don't skip last param and always
  17290. * use the same type in your code (boolean or number). That will improve JS speed.
  17291. *
  17292. * For regular `Array`-s make sure all elements are [0..255].
  17293. *
  17294. * ##### Example
  17295. *
  17296. * ```javascript
  17297. * push(chunk, false); // push one of data chunks
  17298. * ...
  17299. * push(chunk, true); // push last chunk
  17300. * ```
  17301. **/
  17302. Inflate.prototype.push = function(data, mode) {
  17303. var strm = this.strm;
  17304. var chunkSize = this.options.chunkSize;
  17305. var status, _mode;
  17306. var next_out_utf8, tail, utf8str;
  17307. if (this.ended) { return false; }
  17308. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  17309. // Convert data if needed
  17310. if (typeof data === 'string') {
  17311. // Only binary strings can be decompressed on practice
  17312. strm.input = strings.binstring2buf(data);
  17313. } else {
  17314. strm.input = data;
  17315. }
  17316. strm.next_in = 0;
  17317. strm.avail_in = strm.input.length;
  17318. do {
  17319. if (strm.avail_out === 0) {
  17320. strm.output = new utils.Buf8(chunkSize);
  17321. strm.next_out = 0;
  17322. strm.avail_out = chunkSize;
  17323. }
  17324. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  17325. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  17326. this.onEnd(status);
  17327. this.ended = true;
  17328. return false;
  17329. }
  17330. if (strm.next_out) {
  17331. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  17332. if (this.options.to === 'string') {
  17333. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  17334. tail = strm.next_out - next_out_utf8;
  17335. utf8str = strings.buf2string(strm.output, next_out_utf8);
  17336. // move tail
  17337. strm.next_out = tail;
  17338. strm.avail_out = chunkSize - tail;
  17339. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  17340. this.onData(utf8str);
  17341. } else {
  17342. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17343. }
  17344. }
  17345. }
  17346. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  17347. if (status === c.Z_STREAM_END) {
  17348. _mode = c.Z_FINISH;
  17349. }
  17350. // Finalize on the last chunk.
  17351. if (_mode === c.Z_FINISH) {
  17352. status = zlib_inflate.inflateEnd(this.strm);
  17353. this.onEnd(status);
  17354. this.ended = true;
  17355. return status === c.Z_OK;
  17356. }
  17357. return true;
  17358. };
  17359. /**
  17360. * Inflate#onData(chunk) -> Void
  17361. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17362. * on js engine support. When string output requested, each chunk
  17363. * will be string.
  17364. *
  17365. * By default, stores data blocks in `chunks[]` property and glue
  17366. * those in `onEnd`. Override this handler, if you need another behaviour.
  17367. **/
  17368. Inflate.prototype.onData = function(chunk) {
  17369. this.chunks.push(chunk);
  17370. };
  17371. /**
  17372. * Inflate#onEnd(status) -> Void
  17373. * - status (Number): inflate status. 0 (Z_OK) on success,
  17374. * other if not.
  17375. *
  17376. * Called once after you tell inflate that input stream complete
  17377. * or error happenned. By default - join collected chunks,
  17378. * free memory and fill `results` / `err` properties.
  17379. **/
  17380. Inflate.prototype.onEnd = function(status) {
  17381. // On success - join
  17382. if (status === c.Z_OK) {
  17383. if (this.options.to === 'string') {
  17384. // Glue & convert here, until we teach pako to send
  17385. // utf8 alligned strings to onData
  17386. this.result = this.chunks.join('');
  17387. } else {
  17388. this.result = utils.flattenChunks(this.chunks);
  17389. }
  17390. }
  17391. this.chunks = [];
  17392. this.err = status;
  17393. this.msg = this.strm.msg;
  17394. };
  17395. /**
  17396. * inflate(data[, options]) -> Uint8Array|Array|String
  17397. * - data (Uint8Array|Array|String): input data to decompress.
  17398. * - options (Object): zlib inflate options.
  17399. *
  17400. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  17401. * format via wrapper header by default. That's why we don't provide
  17402. * separate `ungzip` method.
  17403. *
  17404. * Supported options are:
  17405. *
  17406. * - windowBits
  17407. *
  17408. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17409. * for more information.
  17410. *
  17411. * Sugar (options):
  17412. *
  17413. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17414. * negative windowBits implicitly.
  17415. * - `to` (String) - if equal to 'string', then result will be converted
  17416. * from utf8 to utf16 (javascript) string. When string output requested,
  17417. * chunk length can differ from `chunkSize`, depending on content.
  17418. *
  17419. *
  17420. * ##### Example:
  17421. *
  17422. * ```javascript
  17423. * var pako = require('pako')
  17424. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  17425. * , output;
  17426. *
  17427. * try {
  17428. * output = pako.inflate(input);
  17429. * } catch (err)
  17430. * console.log(err);
  17431. * }
  17432. * ```
  17433. **/
  17434. function inflate(input, options) {
  17435. var inflator = new Inflate(options);
  17436. inflator.push(input, true);
  17437. // That will never happens, if you don't cheat with options :)
  17438. if (inflator.err) { throw inflator.msg; }
  17439. return inflator.result;
  17440. }
  17441. /**
  17442. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  17443. * - data (Uint8Array|Array|String): input data to decompress.
  17444. * - options (Object): zlib inflate options.
  17445. *
  17446. * The same as [[inflate]], but creates raw data, without wrapper
  17447. * (header and adler32 crc).
  17448. **/
  17449. function inflateRaw(input, options) {
  17450. options = options || {};
  17451. options.raw = true;
  17452. return inflate(input, options);
  17453. }
  17454. /**
  17455. * ungzip(data[, options]) -> Uint8Array|Array|String
  17456. * - data (Uint8Array|Array|String): input data to decompress.
  17457. * - options (Object): zlib inflate options.
  17458. *
  17459. * Just shortcut to [[inflate]], because it autodetects format
  17460. * by header.content. Done for convenience.
  17461. **/
  17462. exports.Inflate = Inflate;
  17463. exports.inflate = inflate;
  17464. exports.inflateRaw = inflateRaw;
  17465. exports.ungzip = inflate;
  17466. },{"./utils/common":66,"./utils/strings":67,"./zlib/constants":69,"./zlib/gzheader":72,"./zlib/inflate.js":74,"./zlib/messages":76,"./zlib/zstream":78}],66:[function(require,module,exports){
  17467. 'use strict';
  17468. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  17469. (typeof Uint16Array !== 'undefined') &&
  17470. (typeof Int32Array !== 'undefined');
  17471. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  17472. var sources = Array.prototype.slice.call(arguments, 1);
  17473. while (sources.length) {
  17474. var source = sources.shift();
  17475. if (!source) { continue; }
  17476. if (typeof(source) !== 'object') {
  17477. throw new TypeError(source + 'must be non-object');
  17478. }
  17479. for (var p in source) {
  17480. if (source.hasOwnProperty(p)) {
  17481. obj[p] = source[p];
  17482. }
  17483. }
  17484. }
  17485. return obj;
  17486. };
  17487. // reduce buffer size, avoiding mem copy
  17488. exports.shrinkBuf = function (buf, size) {
  17489. if (buf.length === size) { return buf; }
  17490. if (buf.subarray) { return buf.subarray(0, size); }
  17491. buf.length = size;
  17492. return buf;
  17493. };
  17494. var fnTyped = {
  17495. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17496. if (src.subarray && dest.subarray) {
  17497. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  17498. return;
  17499. }
  17500. // Fallback to ordinary array
  17501. for(var i=0; i<len; i++) {
  17502. dest[dest_offs + i] = src[src_offs + i];
  17503. }
  17504. },
  17505. // Join array of chunks to single array.
  17506. flattenChunks: function(chunks) {
  17507. var i, l, len, pos, chunk, result;
  17508. // calculate data length
  17509. len = 0;
  17510. for (i=0, l=chunks.length; i<l; i++) {
  17511. len += chunks[i].length;
  17512. }
  17513. // join chunks
  17514. result = new Uint8Array(len);
  17515. pos = 0;
  17516. for (i=0, l=chunks.length; i<l; i++) {
  17517. chunk = chunks[i];
  17518. result.set(chunk, pos);
  17519. pos += chunk.length;
  17520. }
  17521. return result;
  17522. }
  17523. };
  17524. var fnUntyped = {
  17525. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17526. for(var i=0; i<len; i++) {
  17527. dest[dest_offs + i] = src[src_offs + i];
  17528. }
  17529. },
  17530. // Join array of chunks to single array.
  17531. flattenChunks: function(chunks) {
  17532. return [].concat.apply([], chunks);
  17533. }
  17534. };
  17535. // Enable/Disable typed arrays use, for testing
  17536. //
  17537. exports.setTyped = function (on) {
  17538. if (on) {
  17539. exports.Buf8 = Uint8Array;
  17540. exports.Buf16 = Uint16Array;
  17541. exports.Buf32 = Int32Array;
  17542. exports.assign(exports, fnTyped);
  17543. } else {
  17544. exports.Buf8 = Array;
  17545. exports.Buf16 = Array;
  17546. exports.Buf32 = Array;
  17547. exports.assign(exports, fnUntyped);
  17548. }
  17549. };
  17550. exports.setTyped(TYPED_OK);
  17551. },{}],67:[function(require,module,exports){
  17552. // String encode/decode helpers
  17553. 'use strict';
  17554. var utils = require('./common');
  17555. // Quick check if we can use fast array to bin string conversion
  17556. //
  17557. // - apply(Array) can fail on Android 2.2
  17558. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  17559. //
  17560. var STR_APPLY_OK = true;
  17561. var STR_APPLY_UIA_OK = true;
  17562. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  17563. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  17564. // Table with utf8 lengths (calculated by first byte of sequence)
  17565. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  17566. // because max possible codepoint is 0x10ffff
  17567. var _utf8len = new utils.Buf8(256);
  17568. for (var i=0; i<256; i++) {
  17569. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  17570. }
  17571. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  17572. // convert string to array (typed, when possible)
  17573. exports.string2buf = function (str) {
  17574. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  17575. // count binary size
  17576. for (m_pos = 0; m_pos < str_len; m_pos++) {
  17577. c = str.charCodeAt(m_pos);
  17578. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17579. c2 = str.charCodeAt(m_pos+1);
  17580. if ((c2 & 0xfc00) === 0xdc00) {
  17581. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17582. m_pos++;
  17583. }
  17584. }
  17585. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  17586. }
  17587. // allocate buffer
  17588. buf = new utils.Buf8(buf_len);
  17589. // convert
  17590. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  17591. c = str.charCodeAt(m_pos);
  17592. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17593. c2 = str.charCodeAt(m_pos+1);
  17594. if ((c2 & 0xfc00) === 0xdc00) {
  17595. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17596. m_pos++;
  17597. }
  17598. }
  17599. if (c < 0x80) {
  17600. /* one byte */
  17601. buf[i++] = c;
  17602. } else if (c < 0x800) {
  17603. /* two bytes */
  17604. buf[i++] = 0xC0 | (c >>> 6);
  17605. buf[i++] = 0x80 | (c & 0x3f);
  17606. } else if (c < 0x10000) {
  17607. /* three bytes */
  17608. buf[i++] = 0xE0 | (c >>> 12);
  17609. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17610. buf[i++] = 0x80 | (c & 0x3f);
  17611. } else {
  17612. /* four bytes */
  17613. buf[i++] = 0xf0 | (c >>> 18);
  17614. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  17615. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17616. buf[i++] = 0x80 | (c & 0x3f);
  17617. }
  17618. }
  17619. return buf;
  17620. };
  17621. // Helper (used in 2 places)
  17622. function buf2binstring(buf, len) {
  17623. // use fallback for big arrays to avoid stack overflow
  17624. if (len < 65537) {
  17625. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  17626. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  17627. }
  17628. }
  17629. var result = '';
  17630. for(var i=0; i < len; i++) {
  17631. result += String.fromCharCode(buf[i]);
  17632. }
  17633. return result;
  17634. }
  17635. // Convert byte array to binary string
  17636. exports.buf2binstring = function(buf) {
  17637. return buf2binstring(buf, buf.length);
  17638. };
  17639. // Convert binary string (typed, when possible)
  17640. exports.binstring2buf = function(str) {
  17641. var buf = new utils.Buf8(str.length);
  17642. for(var i=0, len=buf.length; i < len; i++) {
  17643. buf[i] = str.charCodeAt(i);
  17644. }
  17645. return buf;
  17646. };
  17647. // convert array to string
  17648. exports.buf2string = function (buf, max) {
  17649. var i, out, c, c_len;
  17650. var len = max || buf.length;
  17651. // Reserve max possible length (2 words per char)
  17652. // NB: by unknown reasons, Array is significantly faster for
  17653. // String.fromCharCode.apply than Uint16Array.
  17654. var utf16buf = new Array(len*2);
  17655. for (out=0, i=0; i<len;) {
  17656. c = buf[i++];
  17657. // quick process ascii
  17658. if (c < 0x80) { utf16buf[out++] = c; continue; }
  17659. c_len = _utf8len[c];
  17660. // skip 5 & 6 byte codes
  17661. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  17662. // apply mask on first byte
  17663. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  17664. // join the rest
  17665. while (c_len > 1 && i < len) {
  17666. c = (c << 6) | (buf[i++] & 0x3f);
  17667. c_len--;
  17668. }
  17669. // terminated by end of string?
  17670. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  17671. if (c < 0x10000) {
  17672. utf16buf[out++] = c;
  17673. } else {
  17674. c -= 0x10000;
  17675. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  17676. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  17677. }
  17678. }
  17679. return buf2binstring(utf16buf, out);
  17680. };
  17681. // Calculate max possible position in utf8 buffer,
  17682. // that will not break sequence. If that's not possible
  17683. // - (very small limits) return max size as is.
  17684. //
  17685. // buf[] - utf8 bytes array
  17686. // max - length limit (mandatory);
  17687. exports.utf8border = function(buf, max) {
  17688. var pos;
  17689. max = max || buf.length;
  17690. if (max > buf.length) { max = buf.length; }
  17691. // go back from last position, until start of sequence found
  17692. pos = max-1;
  17693. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  17694. // Fuckup - very small and broken sequence,
  17695. // return max, because we should return something anyway.
  17696. if (pos < 0) { return max; }
  17697. // If we came to start of buffer - that means vuffer is too small,
  17698. // return max too.
  17699. if (pos === 0) { return max; }
  17700. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  17701. };
  17702. },{"./common":66}],68:[function(require,module,exports){
  17703. 'use strict';
  17704. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  17705. // It doesn't worth to make additional optimizationa as in original.
  17706. // Small size is preferable.
  17707. function adler32(adler, buf, len, pos) {
  17708. var s1 = (adler & 0xffff) |0
  17709. , s2 = ((adler >>> 16) & 0xffff) |0
  17710. , n = 0;
  17711. while (len !== 0) {
  17712. // Set limit ~ twice less than 5552, to keep
  17713. // s2 in 31-bits, because we force signed ints.
  17714. // in other case %= will fail.
  17715. n = len > 2000 ? 2000 : len;
  17716. len -= n;
  17717. do {
  17718. s1 = (s1 + buf[pos++]) |0;
  17719. s2 = (s2 + s1) |0;
  17720. } while (--n);
  17721. s1 %= 65521;
  17722. s2 %= 65521;
  17723. }
  17724. return (s1 | (s2 << 16)) |0;
  17725. }
  17726. module.exports = adler32;
  17727. },{}],69:[function(require,module,exports){
  17728. module.exports = {
  17729. /* Allowed flush values; see deflate() and inflate() below for details */
  17730. Z_NO_FLUSH: 0,
  17731. Z_PARTIAL_FLUSH: 1,
  17732. Z_SYNC_FLUSH: 2,
  17733. Z_FULL_FLUSH: 3,
  17734. Z_FINISH: 4,
  17735. Z_BLOCK: 5,
  17736. Z_TREES: 6,
  17737. /* Return codes for the compression/decompression functions. Negative values
  17738. * are errors, positive values are used for special but normal events.
  17739. */
  17740. Z_OK: 0,
  17741. Z_STREAM_END: 1,
  17742. Z_NEED_DICT: 2,
  17743. Z_ERRNO: -1,
  17744. Z_STREAM_ERROR: -2,
  17745. Z_DATA_ERROR: -3,
  17746. //Z_MEM_ERROR: -4,
  17747. Z_BUF_ERROR: -5,
  17748. //Z_VERSION_ERROR: -6,
  17749. /* compression levels */
  17750. Z_NO_COMPRESSION: 0,
  17751. Z_BEST_SPEED: 1,
  17752. Z_BEST_COMPRESSION: 9,
  17753. Z_DEFAULT_COMPRESSION: -1,
  17754. Z_FILTERED: 1,
  17755. Z_HUFFMAN_ONLY: 2,
  17756. Z_RLE: 3,
  17757. Z_FIXED: 4,
  17758. Z_DEFAULT_STRATEGY: 0,
  17759. /* Possible values of the data_type field (though see inflate()) */
  17760. Z_BINARY: 0,
  17761. Z_TEXT: 1,
  17762. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  17763. Z_UNKNOWN: 2,
  17764. /* The deflate compression method */
  17765. Z_DEFLATED: 8
  17766. //Z_NULL: null // Use -1 or null inline, depending on var type
  17767. };
  17768. },{}],70:[function(require,module,exports){
  17769. 'use strict';
  17770. // Note: we can't get significant speed boost here.
  17771. // So write code to minimize size - no pregenerated tables
  17772. // and array tools dependencies.
  17773. // Use ordinary array, since untyped makes no boost here
  17774. function makeTable() {
  17775. var c, table = [];
  17776. for(var n =0; n < 256; n++){
  17777. c = n;
  17778. for(var k =0; k < 8; k++){
  17779. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  17780. }
  17781. table[n] = c;
  17782. }
  17783. return table;
  17784. }
  17785. // Create table on load. Just 255 signed longs. Not a problem.
  17786. var crcTable = makeTable();
  17787. function crc32(crc, buf, len, pos) {
  17788. var t = crcTable
  17789. , end = pos + len;
  17790. crc = crc ^ (-1);
  17791. for (var i = pos; i < end; i++ ) {
  17792. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  17793. }
  17794. return (crc ^ (-1)); // >>> 0;
  17795. }
  17796. module.exports = crc32;
  17797. },{}],71:[function(require,module,exports){
  17798. 'use strict';
  17799. var utils = require('../utils/common');
  17800. var trees = require('./trees');
  17801. var adler32 = require('./adler32');
  17802. var crc32 = require('./crc32');
  17803. var msg = require('./messages');
  17804. /* Public constants ==========================================================*/
  17805. /* ===========================================================================*/
  17806. /* Allowed flush values; see deflate() and inflate() below for details */
  17807. var Z_NO_FLUSH = 0;
  17808. var Z_PARTIAL_FLUSH = 1;
  17809. //var Z_SYNC_FLUSH = 2;
  17810. var Z_FULL_FLUSH = 3;
  17811. var Z_FINISH = 4;
  17812. var Z_BLOCK = 5;
  17813. //var Z_TREES = 6;
  17814. /* Return codes for the compression/decompression functions. Negative values
  17815. * are errors, positive values are used for special but normal events.
  17816. */
  17817. var Z_OK = 0;
  17818. var Z_STREAM_END = 1;
  17819. //var Z_NEED_DICT = 2;
  17820. //var Z_ERRNO = -1;
  17821. var Z_STREAM_ERROR = -2;
  17822. var Z_DATA_ERROR = -3;
  17823. //var Z_MEM_ERROR = -4;
  17824. var Z_BUF_ERROR = -5;
  17825. //var Z_VERSION_ERROR = -6;
  17826. /* compression levels */
  17827. //var Z_NO_COMPRESSION = 0;
  17828. //var Z_BEST_SPEED = 1;
  17829. //var Z_BEST_COMPRESSION = 9;
  17830. var Z_DEFAULT_COMPRESSION = -1;
  17831. var Z_FILTERED = 1;
  17832. var Z_HUFFMAN_ONLY = 2;
  17833. var Z_RLE = 3;
  17834. var Z_FIXED = 4;
  17835. var Z_DEFAULT_STRATEGY = 0;
  17836. /* Possible values of the data_type field (though see inflate()) */
  17837. //var Z_BINARY = 0;
  17838. //var Z_TEXT = 1;
  17839. //var Z_ASCII = 1; // = Z_TEXT
  17840. var Z_UNKNOWN = 2;
  17841. /* The deflate compression method */
  17842. var Z_DEFLATED = 8;
  17843. /*============================================================================*/
  17844. var MAX_MEM_LEVEL = 9;
  17845. /* Maximum value for memLevel in deflateInit2 */
  17846. var MAX_WBITS = 15;
  17847. /* 32K LZ77 window */
  17848. var DEF_MEM_LEVEL = 8;
  17849. var LENGTH_CODES = 29;
  17850. /* number of length codes, not counting the special END_BLOCK code */
  17851. var LITERALS = 256;
  17852. /* number of literal bytes 0..255 */
  17853. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17854. /* number of Literal or Length codes, including the END_BLOCK code */
  17855. var D_CODES = 30;
  17856. /* number of distance codes */
  17857. var BL_CODES = 19;
  17858. /* number of codes used to transfer the bit lengths */
  17859. var HEAP_SIZE = 2*L_CODES + 1;
  17860. /* maximum heap size */
  17861. var MAX_BITS = 15;
  17862. /* All codes must not exceed MAX_BITS bits */
  17863. var MIN_MATCH = 3;
  17864. var MAX_MATCH = 258;
  17865. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  17866. var PRESET_DICT = 0x20;
  17867. var INIT_STATE = 42;
  17868. var EXTRA_STATE = 69;
  17869. var NAME_STATE = 73;
  17870. var COMMENT_STATE = 91;
  17871. var HCRC_STATE = 103;
  17872. var BUSY_STATE = 113;
  17873. var FINISH_STATE = 666;
  17874. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  17875. var BS_BLOCK_DONE = 2; /* block flush performed */
  17876. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  17877. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  17878. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  17879. function err(strm, errorCode) {
  17880. strm.msg = msg[errorCode];
  17881. return errorCode;
  17882. }
  17883. function rank(f) {
  17884. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  17885. }
  17886. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17887. /* =========================================================================
  17888. * Flush as much pending output as possible. All deflate() output goes
  17889. * through this function so some applications may wish to modify it
  17890. * to avoid allocating a large strm->output buffer and copying into it.
  17891. * (See also read_buf()).
  17892. */
  17893. function flush_pending(strm) {
  17894. var s = strm.state;
  17895. //_tr_flush_bits(s);
  17896. var len = s.pending;
  17897. if (len > strm.avail_out) {
  17898. len = strm.avail_out;
  17899. }
  17900. if (len === 0) { return; }
  17901. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  17902. strm.next_out += len;
  17903. s.pending_out += len;
  17904. strm.total_out += len;
  17905. strm.avail_out -= len;
  17906. s.pending -= len;
  17907. if (s.pending === 0) {
  17908. s.pending_out = 0;
  17909. }
  17910. }
  17911. function flush_block_only (s, last) {
  17912. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  17913. s.block_start = s.strstart;
  17914. flush_pending(s.strm);
  17915. }
  17916. function put_byte(s, b) {
  17917. s.pending_buf[s.pending++] = b;
  17918. }
  17919. /* =========================================================================
  17920. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  17921. * IN assertion: the stream state is correct and there is enough room in
  17922. * pending_buf.
  17923. */
  17924. function putShortMSB(s, b) {
  17925. // put_byte(s, (Byte)(b >> 8));
  17926. // put_byte(s, (Byte)(b & 0xff));
  17927. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  17928. s.pending_buf[s.pending++] = b & 0xff;
  17929. }
  17930. /* ===========================================================================
  17931. * Read a new buffer from the current input stream, update the adler32
  17932. * and total number of bytes read. All deflate() input goes through
  17933. * this function so some applications may wish to modify it to avoid
  17934. * allocating a large strm->input buffer and copying from it.
  17935. * (See also flush_pending()).
  17936. */
  17937. function read_buf(strm, buf, start, size) {
  17938. var len = strm.avail_in;
  17939. if (len > size) { len = size; }
  17940. if (len === 0) { return 0; }
  17941. strm.avail_in -= len;
  17942. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  17943. if (strm.state.wrap === 1) {
  17944. strm.adler = adler32(strm.adler, buf, len, start);
  17945. }
  17946. else if (strm.state.wrap === 2) {
  17947. strm.adler = crc32(strm.adler, buf, len, start);
  17948. }
  17949. strm.next_in += len;
  17950. strm.total_in += len;
  17951. return len;
  17952. }
  17953. /* ===========================================================================
  17954. * Set match_start to the longest match starting at the given string and
  17955. * return its length. Matches shorter or equal to prev_length are discarded,
  17956. * in which case the result is equal to prev_length and match_start is
  17957. * garbage.
  17958. * IN assertions: cur_match is the head of the hash chain for the current
  17959. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  17960. * OUT assertion: the match length is not greater than s->lookahead.
  17961. */
  17962. function longest_match(s, cur_match) {
  17963. var chain_length = s.max_chain_length; /* max hash chain length */
  17964. var scan = s.strstart; /* current string */
  17965. var match; /* matched string */
  17966. var len; /* length of current match */
  17967. var best_len = s.prev_length; /* best match length so far */
  17968. var nice_match = s.nice_match; /* stop if match long enough */
  17969. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  17970. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  17971. var _win = s.window; // shortcut
  17972. var wmask = s.w_mask;
  17973. var prev = s.prev;
  17974. /* Stop when cur_match becomes <= limit. To simplify the code,
  17975. * we prevent matches with the string of window index 0.
  17976. */
  17977. var strend = s.strstart + MAX_MATCH;
  17978. var scan_end1 = _win[scan + best_len - 1];
  17979. var scan_end = _win[scan + best_len];
  17980. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  17981. * It is easy to get rid of this optimization if necessary.
  17982. */
  17983. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  17984. /* Do not waste too much time if we already have a good match: */
  17985. if (s.prev_length >= s.good_match) {
  17986. chain_length >>= 2;
  17987. }
  17988. /* Do not look for matches beyond the end of the input. This is necessary
  17989. * to make deflate deterministic.
  17990. */
  17991. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  17992. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  17993. do {
  17994. // Assert(cur_match < s->strstart, "no future");
  17995. match = cur_match;
  17996. /* Skip to next match if the match length cannot increase
  17997. * or if the match length is less than 2. Note that the checks below
  17998. * for insufficient lookahead only occur occasionally for performance
  17999. * reasons. Therefore uninitialized memory will be accessed, and
  18000. * conditional jumps will be made that depend on those values.
  18001. * However the length of the match is limited to the lookahead, so
  18002. * the output of deflate is not affected by the uninitialized values.
  18003. */
  18004. if (_win[match + best_len] !== scan_end ||
  18005. _win[match + best_len - 1] !== scan_end1 ||
  18006. _win[match] !== _win[scan] ||
  18007. _win[++match] !== _win[scan + 1]) {
  18008. continue;
  18009. }
  18010. /* The check at best_len-1 can be removed because it will be made
  18011. * again later. (This heuristic is not always a win.)
  18012. * It is not necessary to compare scan[2] and match[2] since they
  18013. * are always equal when the other bytes match, given that
  18014. * the hash keys are equal and that HASH_BITS >= 8.
  18015. */
  18016. scan += 2;
  18017. match++;
  18018. // Assert(*scan == *match, "match[2]?");
  18019. /* We check for insufficient lookahead only every 8th comparison;
  18020. * the 256th check will be made at strstart+258.
  18021. */
  18022. do {
  18023. /*jshint noempty:false*/
  18024. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18025. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18026. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18027. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18028. scan < strend);
  18029. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  18030. len = MAX_MATCH - (strend - scan);
  18031. scan = strend - MAX_MATCH;
  18032. if (len > best_len) {
  18033. s.match_start = cur_match;
  18034. best_len = len;
  18035. if (len >= nice_match) {
  18036. break;
  18037. }
  18038. scan_end1 = _win[scan + best_len - 1];
  18039. scan_end = _win[scan + best_len];
  18040. }
  18041. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  18042. if (best_len <= s.lookahead) {
  18043. return best_len;
  18044. }
  18045. return s.lookahead;
  18046. }
  18047. /* ===========================================================================
  18048. * Fill the window when the lookahead becomes insufficient.
  18049. * Updates strstart and lookahead.
  18050. *
  18051. * IN assertion: lookahead < MIN_LOOKAHEAD
  18052. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  18053. * At least one byte has been read, or avail_in == 0; reads are
  18054. * performed for at least two bytes (required for the zip translate_eol
  18055. * option -- not supported here).
  18056. */
  18057. function fill_window(s) {
  18058. var _w_size = s.w_size;
  18059. var p, n, m, more, str;
  18060. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  18061. do {
  18062. more = s.window_size - s.lookahead - s.strstart;
  18063. // JS ints have 32 bit, block below not needed
  18064. /* Deal with !@#$% 64K limit: */
  18065. //if (sizeof(int) <= 2) {
  18066. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  18067. // more = wsize;
  18068. //
  18069. // } else if (more == (unsigned)(-1)) {
  18070. // /* Very unlikely, but possible on 16 bit machine if
  18071. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  18072. // */
  18073. // more--;
  18074. // }
  18075. //}
  18076. /* If the window is almost full and there is insufficient lookahead,
  18077. * move the upper half to the lower one to make room in the upper half.
  18078. */
  18079. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  18080. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  18081. s.match_start -= _w_size;
  18082. s.strstart -= _w_size;
  18083. /* we now have strstart >= MAX_DIST */
  18084. s.block_start -= _w_size;
  18085. /* Slide the hash table (could be avoided with 32 bit values
  18086. at the expense of memory usage). We slide even when level == 0
  18087. to keep the hash table consistent if we switch back to level > 0
  18088. later. (Using level 0 permanently is not an optimal usage of
  18089. zlib, so we don't care about this pathological case.)
  18090. */
  18091. n = s.hash_size;
  18092. p = n;
  18093. do {
  18094. m = s.head[--p];
  18095. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  18096. } while (--n);
  18097. n = _w_size;
  18098. p = n;
  18099. do {
  18100. m = s.prev[--p];
  18101. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  18102. /* If n is not on any hash chain, prev[n] is garbage but
  18103. * its value will never be used.
  18104. */
  18105. } while (--n);
  18106. more += _w_size;
  18107. }
  18108. if (s.strm.avail_in === 0) {
  18109. break;
  18110. }
  18111. /* If there was no sliding:
  18112. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  18113. * more == window_size - lookahead - strstart
  18114. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  18115. * => more >= window_size - 2*WSIZE + 2
  18116. * In the BIG_MEM or MMAP case (not yet supported),
  18117. * window_size == input_size + MIN_LOOKAHEAD &&
  18118. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  18119. * Otherwise, window_size == 2*WSIZE so more >= 2.
  18120. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  18121. */
  18122. //Assert(more >= 2, "more < 2");
  18123. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  18124. s.lookahead += n;
  18125. /* Initialize the hash value now that we have some input: */
  18126. if (s.lookahead + s.insert >= MIN_MATCH) {
  18127. str = s.strstart - s.insert;
  18128. s.ins_h = s.window[str];
  18129. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  18130. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  18131. //#if MIN_MATCH != 3
  18132. // Call update_hash() MIN_MATCH-3 more times
  18133. //#endif
  18134. while (s.insert) {
  18135. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  18136. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  18137. s.prev[str & s.w_mask] = s.head[s.ins_h];
  18138. s.head[s.ins_h] = str;
  18139. str++;
  18140. s.insert--;
  18141. if (s.lookahead + s.insert < MIN_MATCH) {
  18142. break;
  18143. }
  18144. }
  18145. }
  18146. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  18147. * but this is not important since only literal bytes will be emitted.
  18148. */
  18149. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  18150. /* If the WIN_INIT bytes after the end of the current data have never been
  18151. * written, then zero those bytes in order to avoid memory check reports of
  18152. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  18153. * the longest match routines. Update the high water mark for the next
  18154. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  18155. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  18156. */
  18157. // if (s.high_water < s.window_size) {
  18158. // var curr = s.strstart + s.lookahead;
  18159. // var init = 0;
  18160. //
  18161. // if (s.high_water < curr) {
  18162. // /* Previous high water mark below current data -- zero WIN_INIT
  18163. // * bytes or up to end of window, whichever is less.
  18164. // */
  18165. // init = s.window_size - curr;
  18166. // if (init > WIN_INIT)
  18167. // init = WIN_INIT;
  18168. // zmemzero(s->window + curr, (unsigned)init);
  18169. // s->high_water = curr + init;
  18170. // }
  18171. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  18172. // /* High water mark at or above current data, but below current data
  18173. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  18174. // * to end of window, whichever is less.
  18175. // */
  18176. // init = (ulg)curr + WIN_INIT - s->high_water;
  18177. // if (init > s->window_size - s->high_water)
  18178. // init = s->window_size - s->high_water;
  18179. // zmemzero(s->window + s->high_water, (unsigned)init);
  18180. // s->high_water += init;
  18181. // }
  18182. // }
  18183. //
  18184. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  18185. // "not enough room for search");
  18186. }
  18187. /* ===========================================================================
  18188. * Copy without compression as much as possible from the input stream, return
  18189. * the current block state.
  18190. * This function does not insert new strings in the dictionary since
  18191. * uncompressible data is probably not useful. This function is used
  18192. * only for the level=0 compression option.
  18193. * NOTE: this function should be optimized to avoid extra copying from
  18194. * window to pending_buf.
  18195. */
  18196. function deflate_stored(s, flush) {
  18197. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  18198. * to pending_buf_size, and each stored block has a 5 byte header:
  18199. */
  18200. var max_block_size = 0xffff;
  18201. if (max_block_size > s.pending_buf_size - 5) {
  18202. max_block_size = s.pending_buf_size - 5;
  18203. }
  18204. /* Copy as much as possible from input to output: */
  18205. for (;;) {
  18206. /* Fill the window as much as possible: */
  18207. if (s.lookahead <= 1) {
  18208. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  18209. // s->block_start >= (long)s->w_size, "slide too late");
  18210. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  18211. // s.block_start >= s.w_size)) {
  18212. // throw new Error("slide too late");
  18213. // }
  18214. fill_window(s);
  18215. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  18216. return BS_NEED_MORE;
  18217. }
  18218. if (s.lookahead === 0) {
  18219. break;
  18220. }
  18221. /* flush the current block */
  18222. }
  18223. //Assert(s->block_start >= 0L, "block gone");
  18224. // if (s.block_start < 0) throw new Error("block gone");
  18225. s.strstart += s.lookahead;
  18226. s.lookahead = 0;
  18227. /* Emit a stored block if pending_buf will be full: */
  18228. var max_start = s.block_start + max_block_size;
  18229. if (s.strstart === 0 || s.strstart >= max_start) {
  18230. /* strstart == 0 is possible when wraparound on 16-bit machine */
  18231. s.lookahead = s.strstart - max_start;
  18232. s.strstart = max_start;
  18233. /*** FLUSH_BLOCK(s, 0); ***/
  18234. flush_block_only(s, false);
  18235. if (s.strm.avail_out === 0) {
  18236. return BS_NEED_MORE;
  18237. }
  18238. /***/
  18239. }
  18240. /* Flush if we may have to slide, otherwise block_start may become
  18241. * negative and the data will be gone:
  18242. */
  18243. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  18244. /*** FLUSH_BLOCK(s, 0); ***/
  18245. flush_block_only(s, false);
  18246. if (s.strm.avail_out === 0) {
  18247. return BS_NEED_MORE;
  18248. }
  18249. /***/
  18250. }
  18251. }
  18252. s.insert = 0;
  18253. if (flush === Z_FINISH) {
  18254. /*** FLUSH_BLOCK(s, 1); ***/
  18255. flush_block_only(s, true);
  18256. if (s.strm.avail_out === 0) {
  18257. return BS_FINISH_STARTED;
  18258. }
  18259. /***/
  18260. return BS_FINISH_DONE;
  18261. }
  18262. if (s.strstart > s.block_start) {
  18263. /*** FLUSH_BLOCK(s, 0); ***/
  18264. flush_block_only(s, false);
  18265. if (s.strm.avail_out === 0) {
  18266. return BS_NEED_MORE;
  18267. }
  18268. /***/
  18269. }
  18270. return BS_NEED_MORE;
  18271. }
  18272. /* ===========================================================================
  18273. * Compress as much as possible from the input stream, return the current
  18274. * block state.
  18275. * This function does not perform lazy evaluation of matches and inserts
  18276. * new strings in the dictionary only for unmatched strings or for short
  18277. * matches. It is used only for the fast compression options.
  18278. */
  18279. function deflate_fast(s, flush) {
  18280. var hash_head; /* head of the hash chain */
  18281. var bflush; /* set if current block must be flushed */
  18282. for (;;) {
  18283. /* Make sure that we always have enough lookahead, except
  18284. * at the end of the input file. We need MAX_MATCH bytes
  18285. * for the next match, plus MIN_MATCH bytes to insert the
  18286. * string following the next match.
  18287. */
  18288. if (s.lookahead < MIN_LOOKAHEAD) {
  18289. fill_window(s);
  18290. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18291. return BS_NEED_MORE;
  18292. }
  18293. if (s.lookahead === 0) {
  18294. break; /* flush the current block */
  18295. }
  18296. }
  18297. /* Insert the string window[strstart .. strstart+2] in the
  18298. * dictionary, and set hash_head to the head of the hash chain:
  18299. */
  18300. hash_head = 0/*NIL*/;
  18301. if (s.lookahead >= MIN_MATCH) {
  18302. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18303. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18304. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18305. s.head[s.ins_h] = s.strstart;
  18306. /***/
  18307. }
  18308. /* Find the longest match, discarding those <= prev_length.
  18309. * At this point we have always match_length < MIN_MATCH
  18310. */
  18311. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  18312. /* To simplify the code, we prevent matches with the string
  18313. * of window index 0 (in particular we have to avoid a match
  18314. * of the string with itself at the start of the input file).
  18315. */
  18316. s.match_length = longest_match(s, hash_head);
  18317. /* longest_match() sets match_start */
  18318. }
  18319. if (s.match_length >= MIN_MATCH) {
  18320. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  18321. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  18322. s.match_length - MIN_MATCH, bflush); ***/
  18323. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  18324. s.lookahead -= s.match_length;
  18325. /* Insert new strings in the hash table only if the match length
  18326. * is not too large. This saves time but degrades compression.
  18327. */
  18328. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  18329. s.match_length--; /* string at strstart already in table */
  18330. do {
  18331. s.strstart++;
  18332. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18333. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18334. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18335. s.head[s.ins_h] = s.strstart;
  18336. /***/
  18337. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  18338. * always MIN_MATCH bytes ahead.
  18339. */
  18340. } while (--s.match_length !== 0);
  18341. s.strstart++;
  18342. } else
  18343. {
  18344. s.strstart += s.match_length;
  18345. s.match_length = 0;
  18346. s.ins_h = s.window[s.strstart];
  18347. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  18348. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  18349. //#if MIN_MATCH != 3
  18350. // Call UPDATE_HASH() MIN_MATCH-3 more times
  18351. //#endif
  18352. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  18353. * matter since it will be recomputed at next deflate call.
  18354. */
  18355. }
  18356. } else {
  18357. /* No match, output a literal byte */
  18358. //Tracevv((stderr,"%c", s.window[s.strstart]));
  18359. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18360. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18361. s.lookahead--;
  18362. s.strstart++;
  18363. }
  18364. if (bflush) {
  18365. /*** FLUSH_BLOCK(s, 0); ***/
  18366. flush_block_only(s, false);
  18367. if (s.strm.avail_out === 0) {
  18368. return BS_NEED_MORE;
  18369. }
  18370. /***/
  18371. }
  18372. }
  18373. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  18374. if (flush === Z_FINISH) {
  18375. /*** FLUSH_BLOCK(s, 1); ***/
  18376. flush_block_only(s, true);
  18377. if (s.strm.avail_out === 0) {
  18378. return BS_FINISH_STARTED;
  18379. }
  18380. /***/
  18381. return BS_FINISH_DONE;
  18382. }
  18383. if (s.last_lit) {
  18384. /*** FLUSH_BLOCK(s, 0); ***/
  18385. flush_block_only(s, false);
  18386. if (s.strm.avail_out === 0) {
  18387. return BS_NEED_MORE;
  18388. }
  18389. /***/
  18390. }
  18391. return BS_BLOCK_DONE;
  18392. }
  18393. /* ===========================================================================
  18394. * Same as above, but achieves better compression. We use a lazy
  18395. * evaluation for matches: a match is finally adopted only if there is
  18396. * no better match at the next window position.
  18397. */
  18398. function deflate_slow(s, flush) {
  18399. var hash_head; /* head of hash chain */
  18400. var bflush; /* set if current block must be flushed */
  18401. var max_insert;
  18402. /* Process the input block. */
  18403. for (;;) {
  18404. /* Make sure that we always have enough lookahead, except
  18405. * at the end of the input file. We need MAX_MATCH bytes
  18406. * for the next match, plus MIN_MATCH bytes to insert the
  18407. * string following the next match.
  18408. */
  18409. if (s.lookahead < MIN_LOOKAHEAD) {
  18410. fill_window(s);
  18411. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18412. return BS_NEED_MORE;
  18413. }
  18414. if (s.lookahead === 0) { break; } /* flush the current block */
  18415. }
  18416. /* Insert the string window[strstart .. strstart+2] in the
  18417. * dictionary, and set hash_head to the head of the hash chain:
  18418. */
  18419. hash_head = 0/*NIL*/;
  18420. if (s.lookahead >= MIN_MATCH) {
  18421. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18422. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18423. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18424. s.head[s.ins_h] = s.strstart;
  18425. /***/
  18426. }
  18427. /* Find the longest match, discarding those <= prev_length.
  18428. */
  18429. s.prev_length = s.match_length;
  18430. s.prev_match = s.match_start;
  18431. s.match_length = MIN_MATCH-1;
  18432. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  18433. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  18434. /* To simplify the code, we prevent matches with the string
  18435. * of window index 0 (in particular we have to avoid a match
  18436. * of the string with itself at the start of the input file).
  18437. */
  18438. s.match_length = longest_match(s, hash_head);
  18439. /* longest_match() sets match_start */
  18440. if (s.match_length <= 5 &&
  18441. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  18442. /* If prev_match is also MIN_MATCH, match_start is garbage
  18443. * but we will ignore the current match anyway.
  18444. */
  18445. s.match_length = MIN_MATCH-1;
  18446. }
  18447. }
  18448. /* If there was a match at the previous step and the current
  18449. * match is not better, output the previous match:
  18450. */
  18451. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  18452. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  18453. /* Do not insert strings in hash table beyond this. */
  18454. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  18455. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  18456. s.prev_length - MIN_MATCH, bflush);***/
  18457. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  18458. /* Insert in hash table all strings up to the end of the match.
  18459. * strstart-1 and strstart are already inserted. If there is not
  18460. * enough lookahead, the last two strings are not inserted in
  18461. * the hash table.
  18462. */
  18463. s.lookahead -= s.prev_length-1;
  18464. s.prev_length -= 2;
  18465. do {
  18466. if (++s.strstart <= max_insert) {
  18467. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18468. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18469. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18470. s.head[s.ins_h] = s.strstart;
  18471. /***/
  18472. }
  18473. } while (--s.prev_length !== 0);
  18474. s.match_available = 0;
  18475. s.match_length = MIN_MATCH-1;
  18476. s.strstart++;
  18477. if (bflush) {
  18478. /*** FLUSH_BLOCK(s, 0); ***/
  18479. flush_block_only(s, false);
  18480. if (s.strm.avail_out === 0) {
  18481. return BS_NEED_MORE;
  18482. }
  18483. /***/
  18484. }
  18485. } else if (s.match_available) {
  18486. /* If there was no match at the previous position, output a
  18487. * single literal. If there was a match but the current match
  18488. * is longer, truncate the previous match to a single literal.
  18489. */
  18490. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18491. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18492. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18493. if (bflush) {
  18494. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  18495. flush_block_only(s, false);
  18496. /***/
  18497. }
  18498. s.strstart++;
  18499. s.lookahead--;
  18500. if (s.strm.avail_out === 0) {
  18501. return BS_NEED_MORE;
  18502. }
  18503. } else {
  18504. /* There is no previous match to compare with, wait for
  18505. * the next step to decide.
  18506. */
  18507. s.match_available = 1;
  18508. s.strstart++;
  18509. s.lookahead--;
  18510. }
  18511. }
  18512. //Assert (flush != Z_NO_FLUSH, "no flush?");
  18513. if (s.match_available) {
  18514. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18515. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18516. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18517. s.match_available = 0;
  18518. }
  18519. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  18520. if (flush === Z_FINISH) {
  18521. /*** FLUSH_BLOCK(s, 1); ***/
  18522. flush_block_only(s, true);
  18523. if (s.strm.avail_out === 0) {
  18524. return BS_FINISH_STARTED;
  18525. }
  18526. /***/
  18527. return BS_FINISH_DONE;
  18528. }
  18529. if (s.last_lit) {
  18530. /*** FLUSH_BLOCK(s, 0); ***/
  18531. flush_block_only(s, false);
  18532. if (s.strm.avail_out === 0) {
  18533. return BS_NEED_MORE;
  18534. }
  18535. /***/
  18536. }
  18537. return BS_BLOCK_DONE;
  18538. }
  18539. /* ===========================================================================
  18540. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  18541. * one. Do not maintain a hash table. (It will be regenerated if this run of
  18542. * deflate switches away from Z_RLE.)
  18543. */
  18544. function deflate_rle(s, flush) {
  18545. var bflush; /* set if current block must be flushed */
  18546. var prev; /* byte at distance one to match */
  18547. var scan, strend; /* scan goes up to strend for length of run */
  18548. var _win = s.window;
  18549. for (;;) {
  18550. /* Make sure that we always have enough lookahead, except
  18551. * at the end of the input file. We need MAX_MATCH bytes
  18552. * for the longest run, plus one for the unrolled loop.
  18553. */
  18554. if (s.lookahead <= MAX_MATCH) {
  18555. fill_window(s);
  18556. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  18557. return BS_NEED_MORE;
  18558. }
  18559. if (s.lookahead === 0) { break; } /* flush the current block */
  18560. }
  18561. /* See how many times the previous byte repeats */
  18562. s.match_length = 0;
  18563. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  18564. scan = s.strstart - 1;
  18565. prev = _win[scan];
  18566. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  18567. strend = s.strstart + MAX_MATCH;
  18568. do {
  18569. /*jshint noempty:false*/
  18570. } while (prev === _win[++scan] && prev === _win[++scan] &&
  18571. prev === _win[++scan] && prev === _win[++scan] &&
  18572. prev === _win[++scan] && prev === _win[++scan] &&
  18573. prev === _win[++scan] && prev === _win[++scan] &&
  18574. scan < strend);
  18575. s.match_length = MAX_MATCH - (strend - scan);
  18576. if (s.match_length > s.lookahead) {
  18577. s.match_length = s.lookahead;
  18578. }
  18579. }
  18580. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  18581. }
  18582. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  18583. if (s.match_length >= MIN_MATCH) {
  18584. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  18585. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  18586. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  18587. s.lookahead -= s.match_length;
  18588. s.strstart += s.match_length;
  18589. s.match_length = 0;
  18590. } else {
  18591. /* No match, output a literal byte */
  18592. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18593. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18594. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18595. s.lookahead--;
  18596. s.strstart++;
  18597. }
  18598. if (bflush) {
  18599. /*** FLUSH_BLOCK(s, 0); ***/
  18600. flush_block_only(s, false);
  18601. if (s.strm.avail_out === 0) {
  18602. return BS_NEED_MORE;
  18603. }
  18604. /***/
  18605. }
  18606. }
  18607. s.insert = 0;
  18608. if (flush === Z_FINISH) {
  18609. /*** FLUSH_BLOCK(s, 1); ***/
  18610. flush_block_only(s, true);
  18611. if (s.strm.avail_out === 0) {
  18612. return BS_FINISH_STARTED;
  18613. }
  18614. /***/
  18615. return BS_FINISH_DONE;
  18616. }
  18617. if (s.last_lit) {
  18618. /*** FLUSH_BLOCK(s, 0); ***/
  18619. flush_block_only(s, false);
  18620. if (s.strm.avail_out === 0) {
  18621. return BS_NEED_MORE;
  18622. }
  18623. /***/
  18624. }
  18625. return BS_BLOCK_DONE;
  18626. }
  18627. /* ===========================================================================
  18628. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  18629. * (It will be regenerated if this run of deflate switches away from Huffman.)
  18630. */
  18631. function deflate_huff(s, flush) {
  18632. var bflush; /* set if current block must be flushed */
  18633. for (;;) {
  18634. /* Make sure that we have a literal to write. */
  18635. if (s.lookahead === 0) {
  18636. fill_window(s);
  18637. if (s.lookahead === 0) {
  18638. if (flush === Z_NO_FLUSH) {
  18639. return BS_NEED_MORE;
  18640. }
  18641. break; /* flush the current block */
  18642. }
  18643. }
  18644. /* Output a literal byte */
  18645. s.match_length = 0;
  18646. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18647. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18648. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18649. s.lookahead--;
  18650. s.strstart++;
  18651. if (bflush) {
  18652. /*** FLUSH_BLOCK(s, 0); ***/
  18653. flush_block_only(s, false);
  18654. if (s.strm.avail_out === 0) {
  18655. return BS_NEED_MORE;
  18656. }
  18657. /***/
  18658. }
  18659. }
  18660. s.insert = 0;
  18661. if (flush === Z_FINISH) {
  18662. /*** FLUSH_BLOCK(s, 1); ***/
  18663. flush_block_only(s, true);
  18664. if (s.strm.avail_out === 0) {
  18665. return BS_FINISH_STARTED;
  18666. }
  18667. /***/
  18668. return BS_FINISH_DONE;
  18669. }
  18670. if (s.last_lit) {
  18671. /*** FLUSH_BLOCK(s, 0); ***/
  18672. flush_block_only(s, false);
  18673. if (s.strm.avail_out === 0) {
  18674. return BS_NEED_MORE;
  18675. }
  18676. /***/
  18677. }
  18678. return BS_BLOCK_DONE;
  18679. }
  18680. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  18681. * the desired pack level (0..9). The values given below have been tuned to
  18682. * exclude worst case performance for pathological files. Better values may be
  18683. * found for specific files.
  18684. */
  18685. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  18686. this.good_length = good_length;
  18687. this.max_lazy = max_lazy;
  18688. this.nice_length = nice_length;
  18689. this.max_chain = max_chain;
  18690. this.func = func;
  18691. };
  18692. var configuration_table;
  18693. configuration_table = [
  18694. /* good lazy nice chain */
  18695. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  18696. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  18697. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  18698. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  18699. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  18700. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  18701. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  18702. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  18703. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  18704. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  18705. ];
  18706. /* ===========================================================================
  18707. * Initialize the "longest match" routines for a new zlib stream
  18708. */
  18709. function lm_init(s) {
  18710. s.window_size = 2 * s.w_size;
  18711. /*** CLEAR_HASH(s); ***/
  18712. zero(s.head); // Fill with NIL (= 0);
  18713. /* Set the default configuration parameters:
  18714. */
  18715. s.max_lazy_match = configuration_table[s.level].max_lazy;
  18716. s.good_match = configuration_table[s.level].good_length;
  18717. s.nice_match = configuration_table[s.level].nice_length;
  18718. s.max_chain_length = configuration_table[s.level].max_chain;
  18719. s.strstart = 0;
  18720. s.block_start = 0;
  18721. s.lookahead = 0;
  18722. s.insert = 0;
  18723. s.match_length = s.prev_length = MIN_MATCH - 1;
  18724. s.match_available = 0;
  18725. s.ins_h = 0;
  18726. }
  18727. function DeflateState() {
  18728. this.strm = null; /* pointer back to this zlib stream */
  18729. this.status = 0; /* as the name implies */
  18730. this.pending_buf = null; /* output still pending */
  18731. this.pending_buf_size = 0; /* size of pending_buf */
  18732. this.pending_out = 0; /* next pending byte to output to the stream */
  18733. this.pending = 0; /* nb of bytes in the pending buffer */
  18734. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  18735. this.gzhead = null; /* gzip header information to write */
  18736. this.gzindex = 0; /* where in extra, name, or comment */
  18737. this.method = Z_DEFLATED; /* can only be DEFLATED */
  18738. this.last_flush = -1; /* value of flush param for previous deflate call */
  18739. this.w_size = 0; /* LZ77 window size (32K by default) */
  18740. this.w_bits = 0; /* log2(w_size) (8..16) */
  18741. this.w_mask = 0; /* w_size - 1 */
  18742. this.window = null;
  18743. /* Sliding window. Input bytes are read into the second half of the window,
  18744. * and move to the first half later to keep a dictionary of at least wSize
  18745. * bytes. With this organization, matches are limited to a distance of
  18746. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  18747. * performed with a length multiple of the block size.
  18748. */
  18749. this.window_size = 0;
  18750. /* Actual size of window: 2*wSize, except when the user input buffer
  18751. * is directly used as sliding window.
  18752. */
  18753. this.prev = null;
  18754. /* Link to older string with same hash index. To limit the size of this
  18755. * array to 64K, this link is maintained only for the last 32K strings.
  18756. * An index in this array is thus a window index modulo 32K.
  18757. */
  18758. this.head = null; /* Heads of the hash chains or NIL. */
  18759. this.ins_h = 0; /* hash index of string to be inserted */
  18760. this.hash_size = 0; /* number of elements in hash table */
  18761. this.hash_bits = 0; /* log2(hash_size) */
  18762. this.hash_mask = 0; /* hash_size-1 */
  18763. this.hash_shift = 0;
  18764. /* Number of bits by which ins_h must be shifted at each input
  18765. * step. It must be such that after MIN_MATCH steps, the oldest
  18766. * byte no longer takes part in the hash key, that is:
  18767. * hash_shift * MIN_MATCH >= hash_bits
  18768. */
  18769. this.block_start = 0;
  18770. /* Window position at the beginning of the current output block. Gets
  18771. * negative when the window is moved backwards.
  18772. */
  18773. this.match_length = 0; /* length of best match */
  18774. this.prev_match = 0; /* previous match */
  18775. this.match_available = 0; /* set if previous match exists */
  18776. this.strstart = 0; /* start of string to insert */
  18777. this.match_start = 0; /* start of matching string */
  18778. this.lookahead = 0; /* number of valid bytes ahead in window */
  18779. this.prev_length = 0;
  18780. /* Length of the best match at previous step. Matches not greater than this
  18781. * are discarded. This is used in the lazy match evaluation.
  18782. */
  18783. this.max_chain_length = 0;
  18784. /* To speed up deflation, hash chains are never searched beyond this
  18785. * length. A higher limit improves compression ratio but degrades the
  18786. * speed.
  18787. */
  18788. this.max_lazy_match = 0;
  18789. /* Attempt to find a better match only when the current match is strictly
  18790. * smaller than this value. This mechanism is used only for compression
  18791. * levels >= 4.
  18792. */
  18793. // That's alias to max_lazy_match, don't use directly
  18794. //this.max_insert_length = 0;
  18795. /* Insert new strings in the hash table only if the match length is not
  18796. * greater than this length. This saves time but degrades compression.
  18797. * max_insert_length is used only for compression levels <= 3.
  18798. */
  18799. this.level = 0; /* compression level (1..9) */
  18800. this.strategy = 0; /* favor or force Huffman coding*/
  18801. this.good_match = 0;
  18802. /* Use a faster search when the previous match is longer than this */
  18803. this.nice_match = 0; /* Stop searching when current match exceeds this */
  18804. /* used by trees.c: */
  18805. /* Didn't use ct_data typedef below to suppress compiler warning */
  18806. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  18807. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  18808. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  18809. // Use flat array of DOUBLE size, with interleaved fata,
  18810. // because JS does not support effective
  18811. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  18812. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  18813. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  18814. zero(this.dyn_ltree);
  18815. zero(this.dyn_dtree);
  18816. zero(this.bl_tree);
  18817. this.l_desc = null; /* desc. for literal tree */
  18818. this.d_desc = null; /* desc. for distance tree */
  18819. this.bl_desc = null; /* desc. for bit length tree */
  18820. //ush bl_count[MAX_BITS+1];
  18821. this.bl_count = new utils.Buf16(MAX_BITS+1);
  18822. /* number of codes at each bit length for an optimal tree */
  18823. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  18824. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  18825. zero(this.heap);
  18826. this.heap_len = 0; /* number of elements in the heap */
  18827. this.heap_max = 0; /* element of largest frequency */
  18828. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  18829. * The same heap array is used to build all trees.
  18830. */
  18831. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  18832. zero(this.depth);
  18833. /* Depth of each subtree used as tie breaker for trees of equal frequency
  18834. */
  18835. this.l_buf = 0; /* buffer index for literals or lengths */
  18836. this.lit_bufsize = 0;
  18837. /* Size of match buffer for literals/lengths. There are 4 reasons for
  18838. * limiting lit_bufsize to 64K:
  18839. * - frequencies can be kept in 16 bit counters
  18840. * - if compression is not successful for the first block, all input
  18841. * data is still in the window so we can still emit a stored block even
  18842. * when input comes from standard input. (This can also be done for
  18843. * all blocks if lit_bufsize is not greater than 32K.)
  18844. * - if compression is not successful for a file smaller than 64K, we can
  18845. * even emit a stored file instead of a stored block (saving 5 bytes).
  18846. * This is applicable only for zip (not gzip or zlib).
  18847. * - creating new Huffman trees less frequently may not provide fast
  18848. * adaptation to changes in the input data statistics. (Take for
  18849. * example a binary file with poorly compressible code followed by
  18850. * a highly compressible string table.) Smaller buffer sizes give
  18851. * fast adaptation but have of course the overhead of transmitting
  18852. * trees more frequently.
  18853. * - I can't count above 4
  18854. */
  18855. this.last_lit = 0; /* running index in l_buf */
  18856. this.d_buf = 0;
  18857. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  18858. * the same number of elements. To use different lengths, an extra flag
  18859. * array would be necessary.
  18860. */
  18861. this.opt_len = 0; /* bit length of current block with optimal trees */
  18862. this.static_len = 0; /* bit length of current block with static trees */
  18863. this.matches = 0; /* number of string matches in current block */
  18864. this.insert = 0; /* bytes at end of window left to insert */
  18865. this.bi_buf = 0;
  18866. /* Output buffer. bits are inserted starting at the bottom (least
  18867. * significant bits).
  18868. */
  18869. this.bi_valid = 0;
  18870. /* Number of valid bits in bi_buf. All bits above the last valid bit
  18871. * are always zero.
  18872. */
  18873. // Used for window memory init. We safely ignore it for JS. That makes
  18874. // sense only for pointers and memory check tools.
  18875. //this.high_water = 0;
  18876. /* High water mark offset in window for initialized bytes -- bytes above
  18877. * this are set to zero in order to avoid memory check warnings when
  18878. * longest match routines access bytes past the input. This is then
  18879. * updated to the new high water mark.
  18880. */
  18881. }
  18882. function deflateResetKeep(strm) {
  18883. var s;
  18884. if (!strm || !strm.state) {
  18885. return err(strm, Z_STREAM_ERROR);
  18886. }
  18887. strm.total_in = strm.total_out = 0;
  18888. strm.data_type = Z_UNKNOWN;
  18889. s = strm.state;
  18890. s.pending = 0;
  18891. s.pending_out = 0;
  18892. if (s.wrap < 0) {
  18893. s.wrap = -s.wrap;
  18894. /* was made negative by deflate(..., Z_FINISH); */
  18895. }
  18896. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  18897. strm.adler = (s.wrap === 2) ?
  18898. 0 // crc32(0, Z_NULL, 0)
  18899. :
  18900. 1; // adler32(0, Z_NULL, 0)
  18901. s.last_flush = Z_NO_FLUSH;
  18902. trees._tr_init(s);
  18903. return Z_OK;
  18904. }
  18905. function deflateReset(strm) {
  18906. var ret = deflateResetKeep(strm);
  18907. if (ret === Z_OK) {
  18908. lm_init(strm.state);
  18909. }
  18910. return ret;
  18911. }
  18912. function deflateSetHeader(strm, head) {
  18913. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18914. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  18915. strm.state.gzhead = head;
  18916. return Z_OK;
  18917. }
  18918. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  18919. if (!strm) { // === Z_NULL
  18920. return Z_STREAM_ERROR;
  18921. }
  18922. var wrap = 1;
  18923. if (level === Z_DEFAULT_COMPRESSION) {
  18924. level = 6;
  18925. }
  18926. if (windowBits < 0) { /* suppress zlib wrapper */
  18927. wrap = 0;
  18928. windowBits = -windowBits;
  18929. }
  18930. else if (windowBits > 15) {
  18931. wrap = 2; /* write gzip wrapper instead */
  18932. windowBits -= 16;
  18933. }
  18934. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  18935. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  18936. strategy < 0 || strategy > Z_FIXED) {
  18937. return err(strm, Z_STREAM_ERROR);
  18938. }
  18939. if (windowBits === 8) {
  18940. windowBits = 9;
  18941. }
  18942. /* until 256-byte window bug fixed */
  18943. var s = new DeflateState();
  18944. strm.state = s;
  18945. s.strm = strm;
  18946. s.wrap = wrap;
  18947. s.gzhead = null;
  18948. s.w_bits = windowBits;
  18949. s.w_size = 1 << s.w_bits;
  18950. s.w_mask = s.w_size - 1;
  18951. s.hash_bits = memLevel + 7;
  18952. s.hash_size = 1 << s.hash_bits;
  18953. s.hash_mask = s.hash_size - 1;
  18954. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  18955. s.window = new utils.Buf8(s.w_size * 2);
  18956. s.head = new utils.Buf16(s.hash_size);
  18957. s.prev = new utils.Buf16(s.w_size);
  18958. // Don't need mem init magic for JS.
  18959. //s.high_water = 0; /* nothing written to s->window yet */
  18960. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  18961. s.pending_buf_size = s.lit_bufsize * 4;
  18962. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  18963. s.d_buf = s.lit_bufsize >> 1;
  18964. s.l_buf = (1 + 2) * s.lit_bufsize;
  18965. s.level = level;
  18966. s.strategy = strategy;
  18967. s.method = method;
  18968. return deflateReset(strm);
  18969. }
  18970. function deflateInit(strm, level) {
  18971. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  18972. }
  18973. function deflate(strm, flush) {
  18974. var old_flush, s;
  18975. var beg, val; // for gzip header write only
  18976. if (!strm || !strm.state ||
  18977. flush > Z_BLOCK || flush < 0) {
  18978. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  18979. }
  18980. s = strm.state;
  18981. if (!strm.output ||
  18982. (!strm.input && strm.avail_in !== 0) ||
  18983. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  18984. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  18985. }
  18986. s.strm = strm; /* just in case */
  18987. old_flush = s.last_flush;
  18988. s.last_flush = flush;
  18989. /* Write the header */
  18990. if (s.status === INIT_STATE) {
  18991. if (s.wrap === 2) { // GZIP header
  18992. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  18993. put_byte(s, 31);
  18994. put_byte(s, 139);
  18995. put_byte(s, 8);
  18996. if (!s.gzhead) { // s->gzhead == Z_NULL
  18997. put_byte(s, 0);
  18998. put_byte(s, 0);
  18999. put_byte(s, 0);
  19000. put_byte(s, 0);
  19001. put_byte(s, 0);
  19002. put_byte(s, s.level === 9 ? 2 :
  19003. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  19004. 4 : 0));
  19005. put_byte(s, OS_CODE);
  19006. s.status = BUSY_STATE;
  19007. }
  19008. else {
  19009. put_byte(s, (s.gzhead.text ? 1 : 0) +
  19010. (s.gzhead.hcrc ? 2 : 0) +
  19011. (!s.gzhead.extra ? 0 : 4) +
  19012. (!s.gzhead.name ? 0 : 8) +
  19013. (!s.gzhead.comment ? 0 : 16)
  19014. );
  19015. put_byte(s, s.gzhead.time & 0xff);
  19016. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  19017. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  19018. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  19019. put_byte(s, s.level === 9 ? 2 :
  19020. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  19021. 4 : 0));
  19022. put_byte(s, s.gzhead.os & 0xff);
  19023. if (s.gzhead.extra && s.gzhead.extra.length) {
  19024. put_byte(s, s.gzhead.extra.length & 0xff);
  19025. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  19026. }
  19027. if (s.gzhead.hcrc) {
  19028. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  19029. }
  19030. s.gzindex = 0;
  19031. s.status = EXTRA_STATE;
  19032. }
  19033. }
  19034. else // DEFLATE header
  19035. {
  19036. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  19037. var level_flags = -1;
  19038. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  19039. level_flags = 0;
  19040. } else if (s.level < 6) {
  19041. level_flags = 1;
  19042. } else if (s.level === 6) {
  19043. level_flags = 2;
  19044. } else {
  19045. level_flags = 3;
  19046. }
  19047. header |= (level_flags << 6);
  19048. if (s.strstart !== 0) { header |= PRESET_DICT; }
  19049. header += 31 - (header % 31);
  19050. s.status = BUSY_STATE;
  19051. putShortMSB(s, header);
  19052. /* Save the adler32 of the preset dictionary: */
  19053. if (s.strstart !== 0) {
  19054. putShortMSB(s, strm.adler >>> 16);
  19055. putShortMSB(s, strm.adler & 0xffff);
  19056. }
  19057. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  19058. }
  19059. }
  19060. //#ifdef GZIP
  19061. if (s.status === EXTRA_STATE) {
  19062. if (s.gzhead.extra/* != Z_NULL*/) {
  19063. beg = s.pending; /* start of bytes to update crc */
  19064. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  19065. if (s.pending === s.pending_buf_size) {
  19066. if (s.gzhead.hcrc && s.pending > beg) {
  19067. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19068. }
  19069. flush_pending(strm);
  19070. beg = s.pending;
  19071. if (s.pending === s.pending_buf_size) {
  19072. break;
  19073. }
  19074. }
  19075. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  19076. s.gzindex++;
  19077. }
  19078. if (s.gzhead.hcrc && s.pending > beg) {
  19079. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19080. }
  19081. if (s.gzindex === s.gzhead.extra.length) {
  19082. s.gzindex = 0;
  19083. s.status = NAME_STATE;
  19084. }
  19085. }
  19086. else {
  19087. s.status = NAME_STATE;
  19088. }
  19089. }
  19090. if (s.status === NAME_STATE) {
  19091. if (s.gzhead.name/* != Z_NULL*/) {
  19092. beg = s.pending; /* start of bytes to update crc */
  19093. //int val;
  19094. do {
  19095. if (s.pending === s.pending_buf_size) {
  19096. if (s.gzhead.hcrc && s.pending > beg) {
  19097. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19098. }
  19099. flush_pending(strm);
  19100. beg = s.pending;
  19101. if (s.pending === s.pending_buf_size) {
  19102. val = 1;
  19103. break;
  19104. }
  19105. }
  19106. // JS specific: little magic to add zero terminator to end of string
  19107. if (s.gzindex < s.gzhead.name.length) {
  19108. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  19109. } else {
  19110. val = 0;
  19111. }
  19112. put_byte(s, val);
  19113. } while (val !== 0);
  19114. if (s.gzhead.hcrc && s.pending > beg){
  19115. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19116. }
  19117. if (val === 0) {
  19118. s.gzindex = 0;
  19119. s.status = COMMENT_STATE;
  19120. }
  19121. }
  19122. else {
  19123. s.status = COMMENT_STATE;
  19124. }
  19125. }
  19126. if (s.status === COMMENT_STATE) {
  19127. if (s.gzhead.comment/* != Z_NULL*/) {
  19128. beg = s.pending; /* start of bytes to update crc */
  19129. //int val;
  19130. do {
  19131. if (s.pending === s.pending_buf_size) {
  19132. if (s.gzhead.hcrc && s.pending > beg) {
  19133. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19134. }
  19135. flush_pending(strm);
  19136. beg = s.pending;
  19137. if (s.pending === s.pending_buf_size) {
  19138. val = 1;
  19139. break;
  19140. }
  19141. }
  19142. // JS specific: little magic to add zero terminator to end of string
  19143. if (s.gzindex < s.gzhead.comment.length) {
  19144. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  19145. } else {
  19146. val = 0;
  19147. }
  19148. put_byte(s, val);
  19149. } while (val !== 0);
  19150. if (s.gzhead.hcrc && s.pending > beg) {
  19151. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19152. }
  19153. if (val === 0) {
  19154. s.status = HCRC_STATE;
  19155. }
  19156. }
  19157. else {
  19158. s.status = HCRC_STATE;
  19159. }
  19160. }
  19161. if (s.status === HCRC_STATE) {
  19162. if (s.gzhead.hcrc) {
  19163. if (s.pending + 2 > s.pending_buf_size) {
  19164. flush_pending(strm);
  19165. }
  19166. if (s.pending + 2 <= s.pending_buf_size) {
  19167. put_byte(s, strm.adler & 0xff);
  19168. put_byte(s, (strm.adler >> 8) & 0xff);
  19169. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19170. s.status = BUSY_STATE;
  19171. }
  19172. }
  19173. else {
  19174. s.status = BUSY_STATE;
  19175. }
  19176. }
  19177. //#endif
  19178. /* Flush as much pending output as possible */
  19179. if (s.pending !== 0) {
  19180. flush_pending(strm);
  19181. if (strm.avail_out === 0) {
  19182. /* Since avail_out is 0, deflate will be called again with
  19183. * more output space, but possibly with both pending and
  19184. * avail_in equal to zero. There won't be anything to do,
  19185. * but this is not an error situation so make sure we
  19186. * return OK instead of BUF_ERROR at next call of deflate:
  19187. */
  19188. s.last_flush = -1;
  19189. return Z_OK;
  19190. }
  19191. /* Make sure there is something to do and avoid duplicate consecutive
  19192. * flushes. For repeated and useless calls with Z_FINISH, we keep
  19193. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  19194. */
  19195. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  19196. flush !== Z_FINISH) {
  19197. return err(strm, Z_BUF_ERROR);
  19198. }
  19199. /* User must not provide more input after the first FINISH: */
  19200. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  19201. return err(strm, Z_BUF_ERROR);
  19202. }
  19203. /* Start a new block or continue the current one.
  19204. */
  19205. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  19206. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  19207. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  19208. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  19209. configuration_table[s.level].func(s, flush));
  19210. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  19211. s.status = FINISH_STATE;
  19212. }
  19213. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  19214. if (strm.avail_out === 0) {
  19215. s.last_flush = -1;
  19216. /* avoid BUF_ERROR next call, see above */
  19217. }
  19218. return Z_OK;
  19219. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  19220. * of deflate should use the same flush parameter to make sure
  19221. * that the flush is complete. So we don't have to output an
  19222. * empty block here, this will be done at next call. This also
  19223. * ensures that for a very small output buffer, we emit at most
  19224. * one empty block.
  19225. */
  19226. }
  19227. if (bstate === BS_BLOCK_DONE) {
  19228. if (flush === Z_PARTIAL_FLUSH) {
  19229. trees._tr_align(s);
  19230. }
  19231. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  19232. trees._tr_stored_block(s, 0, 0, false);
  19233. /* For a full flush, this empty block will be recognized
  19234. * as a special marker by inflate_sync().
  19235. */
  19236. if (flush === Z_FULL_FLUSH) {
  19237. /*** CLEAR_HASH(s); ***/ /* forget history */
  19238. zero(s.head); // Fill with NIL (= 0);
  19239. if (s.lookahead === 0) {
  19240. s.strstart = 0;
  19241. s.block_start = 0;
  19242. s.insert = 0;
  19243. }
  19244. }
  19245. }
  19246. flush_pending(strm);
  19247. if (strm.avail_out === 0) {
  19248. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  19249. return Z_OK;
  19250. }
  19251. }
  19252. }
  19253. //Assert(strm->avail_out > 0, "bug2");
  19254. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  19255. if (flush !== Z_FINISH) { return Z_OK; }
  19256. if (s.wrap <= 0) { return Z_STREAM_END; }
  19257. /* Write the trailer */
  19258. if (s.wrap === 2) {
  19259. put_byte(s, strm.adler & 0xff);
  19260. put_byte(s, (strm.adler >> 8) & 0xff);
  19261. put_byte(s, (strm.adler >> 16) & 0xff);
  19262. put_byte(s, (strm.adler >> 24) & 0xff);
  19263. put_byte(s, strm.total_in & 0xff);
  19264. put_byte(s, (strm.total_in >> 8) & 0xff);
  19265. put_byte(s, (strm.total_in >> 16) & 0xff);
  19266. put_byte(s, (strm.total_in >> 24) & 0xff);
  19267. }
  19268. else
  19269. {
  19270. putShortMSB(s, strm.adler >>> 16);
  19271. putShortMSB(s, strm.adler & 0xffff);
  19272. }
  19273. flush_pending(strm);
  19274. /* If avail_out is zero, the application will call deflate again
  19275. * to flush the rest.
  19276. */
  19277. if (s.wrap > 0) { s.wrap = -s.wrap; }
  19278. /* write the trailer only once! */
  19279. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  19280. }
  19281. function deflateEnd(strm) {
  19282. var status;
  19283. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  19284. return Z_STREAM_ERROR;
  19285. }
  19286. status = strm.state.status;
  19287. if (status !== INIT_STATE &&
  19288. status !== EXTRA_STATE &&
  19289. status !== NAME_STATE &&
  19290. status !== COMMENT_STATE &&
  19291. status !== HCRC_STATE &&
  19292. status !== BUSY_STATE &&
  19293. status !== FINISH_STATE
  19294. ) {
  19295. return err(strm, Z_STREAM_ERROR);
  19296. }
  19297. strm.state = null;
  19298. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  19299. }
  19300. /* =========================================================================
  19301. * Copy the source state to the destination state
  19302. */
  19303. //function deflateCopy(dest, source) {
  19304. //
  19305. //}
  19306. exports.deflateInit = deflateInit;
  19307. exports.deflateInit2 = deflateInit2;
  19308. exports.deflateReset = deflateReset;
  19309. exports.deflateResetKeep = deflateResetKeep;
  19310. exports.deflateSetHeader = deflateSetHeader;
  19311. exports.deflate = deflate;
  19312. exports.deflateEnd = deflateEnd;
  19313. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  19314. /* Not implemented
  19315. exports.deflateBound = deflateBound;
  19316. exports.deflateCopy = deflateCopy;
  19317. exports.deflateSetDictionary = deflateSetDictionary;
  19318. exports.deflateParams = deflateParams;
  19319. exports.deflatePending = deflatePending;
  19320. exports.deflatePrime = deflatePrime;
  19321. exports.deflateTune = deflateTune;
  19322. */
  19323. },{"../utils/common":66,"./adler32":68,"./crc32":70,"./messages":76,"./trees":77}],72:[function(require,module,exports){
  19324. 'use strict';
  19325. function GZheader() {
  19326. /* true if compressed data believed to be text */
  19327. this.text = 0;
  19328. /* modification time */
  19329. this.time = 0;
  19330. /* extra flags (not used when writing a gzip file) */
  19331. this.xflags = 0;
  19332. /* operating system */
  19333. this.os = 0;
  19334. /* pointer to extra field or Z_NULL if none */
  19335. this.extra = null;
  19336. /* extra field length (valid if extra != Z_NULL) */
  19337. this.extra_len = 0; // Actually, we don't need it in JS,
  19338. // but leave for few code modifications
  19339. //
  19340. // Setup limits is not necessary because in js we should not preallocate memory
  19341. // for inflate use constant limit in 65536 bytes
  19342. //
  19343. /* space at extra (only when reading header) */
  19344. // this.extra_max = 0;
  19345. /* pointer to zero-terminated file name or Z_NULL */
  19346. this.name = '';
  19347. /* space at name (only when reading header) */
  19348. // this.name_max = 0;
  19349. /* pointer to zero-terminated comment or Z_NULL */
  19350. this.comment = '';
  19351. /* space at comment (only when reading header) */
  19352. // this.comm_max = 0;
  19353. /* true if there was or will be a header crc */
  19354. this.hcrc = 0;
  19355. /* true when done reading gzip header (not used when writing a gzip file) */
  19356. this.done = false;
  19357. }
  19358. module.exports = GZheader;
  19359. },{}],73:[function(require,module,exports){
  19360. 'use strict';
  19361. // See state defs from inflate.js
  19362. var BAD = 30; /* got a data error -- remain here until reset */
  19363. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19364. /*
  19365. Decode literal, length, and distance codes and write out the resulting
  19366. literal and match bytes until either not enough input or output is
  19367. available, an end-of-block is encountered, or a data error is encountered.
  19368. When large enough input and output buffers are supplied to inflate(), for
  19369. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  19370. inflate execution time is spent in this routine.
  19371. Entry assumptions:
  19372. state.mode === LEN
  19373. strm.avail_in >= 6
  19374. strm.avail_out >= 258
  19375. start >= strm.avail_out
  19376. state.bits < 8
  19377. On return, state.mode is one of:
  19378. LEN -- ran out of enough output space or enough available input
  19379. TYPE -- reached end of block code, inflate() to interpret next block
  19380. BAD -- error in block data
  19381. Notes:
  19382. - The maximum input bits used by a length/distance pair is 15 bits for the
  19383. length code, 5 bits for the length extra, 15 bits for the distance code,
  19384. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  19385. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  19386. checking for available input while decoding.
  19387. - The maximum bytes that a single length/distance pair can output is 258
  19388. bytes, which is the maximum length that can be coded. inflate_fast()
  19389. requires strm.avail_out >= 258 for each loop to avoid checking for
  19390. output space.
  19391. */
  19392. module.exports = function inflate_fast(strm, start) {
  19393. var state;
  19394. var _in; /* local strm.input */
  19395. var last; /* have enough input while in < last */
  19396. var _out; /* local strm.output */
  19397. var beg; /* inflate()'s initial strm.output */
  19398. var end; /* while out < end, enough space available */
  19399. //#ifdef INFLATE_STRICT
  19400. var dmax; /* maximum distance from zlib header */
  19401. //#endif
  19402. var wsize; /* window size or zero if not using window */
  19403. var whave; /* valid bytes in the window */
  19404. var wnext; /* window write index */
  19405. var window; /* allocated sliding window, if wsize != 0 */
  19406. var hold; /* local strm.hold */
  19407. var bits; /* local strm.bits */
  19408. var lcode; /* local strm.lencode */
  19409. var dcode; /* local strm.distcode */
  19410. var lmask; /* mask for first level of length codes */
  19411. var dmask; /* mask for first level of distance codes */
  19412. var here; /* retrieved table entry */
  19413. var op; /* code bits, operation, extra bits, or */
  19414. /* window position, window bytes to copy */
  19415. var len; /* match length, unused bytes */
  19416. var dist; /* match distance */
  19417. var from; /* where to copy match from */
  19418. var from_source;
  19419. var input, output; // JS specific, because we have no pointers
  19420. /* copy state to local variables */
  19421. state = strm.state;
  19422. //here = state.here;
  19423. _in = strm.next_in;
  19424. input = strm.input;
  19425. last = _in + (strm.avail_in - 5);
  19426. _out = strm.next_out;
  19427. output = strm.output;
  19428. beg = _out - (start - strm.avail_out);
  19429. end = _out + (strm.avail_out - 257);
  19430. //#ifdef INFLATE_STRICT
  19431. dmax = state.dmax;
  19432. //#endif
  19433. wsize = state.wsize;
  19434. whave = state.whave;
  19435. wnext = state.wnext;
  19436. window = state.window;
  19437. hold = state.hold;
  19438. bits = state.bits;
  19439. lcode = state.lencode;
  19440. dcode = state.distcode;
  19441. lmask = (1 << state.lenbits) - 1;
  19442. dmask = (1 << state.distbits) - 1;
  19443. /* decode literals and length/distances until end-of-block or not enough
  19444. input data or output space */
  19445. top:
  19446. do {
  19447. if (bits < 15) {
  19448. hold += input[_in++] << bits;
  19449. bits += 8;
  19450. hold += input[_in++] << bits;
  19451. bits += 8;
  19452. }
  19453. here = lcode[hold & lmask];
  19454. dolen:
  19455. for (;;) { // Goto emulation
  19456. op = here >>> 24/*here.bits*/;
  19457. hold >>>= op;
  19458. bits -= op;
  19459. op = (here >>> 16) & 0xff/*here.op*/;
  19460. if (op === 0) { /* literal */
  19461. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  19462. // "inflate: literal '%c'\n" :
  19463. // "inflate: literal 0x%02x\n", here.val));
  19464. output[_out++] = here & 0xffff/*here.val*/;
  19465. }
  19466. else if (op & 16) { /* length base */
  19467. len = here & 0xffff/*here.val*/;
  19468. op &= 15; /* number of extra bits */
  19469. if (op) {
  19470. if (bits < op) {
  19471. hold += input[_in++] << bits;
  19472. bits += 8;
  19473. }
  19474. len += hold & ((1 << op) - 1);
  19475. hold >>>= op;
  19476. bits -= op;
  19477. }
  19478. //Tracevv((stderr, "inflate: length %u\n", len));
  19479. if (bits < 15) {
  19480. hold += input[_in++] << bits;
  19481. bits += 8;
  19482. hold += input[_in++] << bits;
  19483. bits += 8;
  19484. }
  19485. here = dcode[hold & dmask];
  19486. dodist:
  19487. for (;;) { // goto emulation
  19488. op = here >>> 24/*here.bits*/;
  19489. hold >>>= op;
  19490. bits -= op;
  19491. op = (here >>> 16) & 0xff/*here.op*/;
  19492. if (op & 16) { /* distance base */
  19493. dist = here & 0xffff/*here.val*/;
  19494. op &= 15; /* number of extra bits */
  19495. if (bits < op) {
  19496. hold += input[_in++] << bits;
  19497. bits += 8;
  19498. if (bits < op) {
  19499. hold += input[_in++] << bits;
  19500. bits += 8;
  19501. }
  19502. }
  19503. dist += hold & ((1 << op) - 1);
  19504. //#ifdef INFLATE_STRICT
  19505. if (dist > dmax) {
  19506. strm.msg = 'invalid distance too far back';
  19507. state.mode = BAD;
  19508. break top;
  19509. }
  19510. //#endif
  19511. hold >>>= op;
  19512. bits -= op;
  19513. //Tracevv((stderr, "inflate: distance %u\n", dist));
  19514. op = _out - beg; /* max distance in output */
  19515. if (dist > op) { /* see if copy from window */
  19516. op = dist - op; /* distance back in window */
  19517. if (op > whave) {
  19518. if (state.sane) {
  19519. strm.msg = 'invalid distance too far back';
  19520. state.mode = BAD;
  19521. break top;
  19522. }
  19523. // (!) This block is disabled in zlib defailts,
  19524. // don't enable it for binary compatibility
  19525. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  19526. // if (len <= op - whave) {
  19527. // do {
  19528. // output[_out++] = 0;
  19529. // } while (--len);
  19530. // continue top;
  19531. // }
  19532. // len -= op - whave;
  19533. // do {
  19534. // output[_out++] = 0;
  19535. // } while (--op > whave);
  19536. // if (op === 0) {
  19537. // from = _out - dist;
  19538. // do {
  19539. // output[_out++] = output[from++];
  19540. // } while (--len);
  19541. // continue top;
  19542. // }
  19543. //#endif
  19544. }
  19545. from = 0; // window index
  19546. from_source = window;
  19547. if (wnext === 0) { /* very common case */
  19548. from += wsize - op;
  19549. if (op < len) { /* some from window */
  19550. len -= op;
  19551. do {
  19552. output[_out++] = window[from++];
  19553. } while (--op);
  19554. from = _out - dist; /* rest from output */
  19555. from_source = output;
  19556. }
  19557. }
  19558. else if (wnext < op) { /* wrap around window */
  19559. from += wsize + wnext - op;
  19560. op -= wnext;
  19561. if (op < len) { /* some from end of window */
  19562. len -= op;
  19563. do {
  19564. output[_out++] = window[from++];
  19565. } while (--op);
  19566. from = 0;
  19567. if (wnext < len) { /* some from start of window */
  19568. op = wnext;
  19569. len -= op;
  19570. do {
  19571. output[_out++] = window[from++];
  19572. } while (--op);
  19573. from = _out - dist; /* rest from output */
  19574. from_source = output;
  19575. }
  19576. }
  19577. }
  19578. else { /* contiguous in window */
  19579. from += wnext - op;
  19580. if (op < len) { /* some from window */
  19581. len -= op;
  19582. do {
  19583. output[_out++] = window[from++];
  19584. } while (--op);
  19585. from = _out - dist; /* rest from output */
  19586. from_source = output;
  19587. }
  19588. }
  19589. while (len > 2) {
  19590. output[_out++] = from_source[from++];
  19591. output[_out++] = from_source[from++];
  19592. output[_out++] = from_source[from++];
  19593. len -= 3;
  19594. }
  19595. if (len) {
  19596. output[_out++] = from_source[from++];
  19597. if (len > 1) {
  19598. output[_out++] = from_source[from++];
  19599. }
  19600. }
  19601. }
  19602. else {
  19603. from = _out - dist; /* copy direct from output */
  19604. do { /* minimum length is three */
  19605. output[_out++] = output[from++];
  19606. output[_out++] = output[from++];
  19607. output[_out++] = output[from++];
  19608. len -= 3;
  19609. } while (len > 2);
  19610. if (len) {
  19611. output[_out++] = output[from++];
  19612. if (len > 1) {
  19613. output[_out++] = output[from++];
  19614. }
  19615. }
  19616. }
  19617. }
  19618. else if ((op & 64) === 0) { /* 2nd level distance code */
  19619. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19620. continue dodist;
  19621. }
  19622. else {
  19623. strm.msg = 'invalid distance code';
  19624. state.mode = BAD;
  19625. break top;
  19626. }
  19627. break; // need to emulate goto via "continue"
  19628. }
  19629. }
  19630. else if ((op & 64) === 0) { /* 2nd level length code */
  19631. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19632. continue dolen;
  19633. }
  19634. else if (op & 32) { /* end-of-block */
  19635. //Tracevv((stderr, "inflate: end of block\n"));
  19636. state.mode = TYPE;
  19637. break top;
  19638. }
  19639. else {
  19640. strm.msg = 'invalid literal/length code';
  19641. state.mode = BAD;
  19642. break top;
  19643. }
  19644. break; // need to emulate goto via "continue"
  19645. }
  19646. } while (_in < last && _out < end);
  19647. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  19648. len = bits >> 3;
  19649. _in -= len;
  19650. bits -= len << 3;
  19651. hold &= (1 << bits) - 1;
  19652. /* update state and return */
  19653. strm.next_in = _in;
  19654. strm.next_out = _out;
  19655. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  19656. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  19657. state.hold = hold;
  19658. state.bits = bits;
  19659. return;
  19660. };
  19661. },{}],74:[function(require,module,exports){
  19662. 'use strict';
  19663. var utils = require('../utils/common');
  19664. var adler32 = require('./adler32');
  19665. var crc32 = require('./crc32');
  19666. var inflate_fast = require('./inffast');
  19667. var inflate_table = require('./inftrees');
  19668. var CODES = 0;
  19669. var LENS = 1;
  19670. var DISTS = 2;
  19671. /* Public constants ==========================================================*/
  19672. /* ===========================================================================*/
  19673. /* Allowed flush values; see deflate() and inflate() below for details */
  19674. //var Z_NO_FLUSH = 0;
  19675. //var Z_PARTIAL_FLUSH = 1;
  19676. //var Z_SYNC_FLUSH = 2;
  19677. //var Z_FULL_FLUSH = 3;
  19678. var Z_FINISH = 4;
  19679. var Z_BLOCK = 5;
  19680. var Z_TREES = 6;
  19681. /* Return codes for the compression/decompression functions. Negative values
  19682. * are errors, positive values are used for special but normal events.
  19683. */
  19684. var Z_OK = 0;
  19685. var Z_STREAM_END = 1;
  19686. var Z_NEED_DICT = 2;
  19687. //var Z_ERRNO = -1;
  19688. var Z_STREAM_ERROR = -2;
  19689. var Z_DATA_ERROR = -3;
  19690. var Z_MEM_ERROR = -4;
  19691. var Z_BUF_ERROR = -5;
  19692. //var Z_VERSION_ERROR = -6;
  19693. /* The deflate compression method */
  19694. var Z_DEFLATED = 8;
  19695. /* STATES ====================================================================*/
  19696. /* ===========================================================================*/
  19697. var HEAD = 1; /* i: waiting for magic header */
  19698. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  19699. var TIME = 3; /* i: waiting for modification time (gzip) */
  19700. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  19701. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  19702. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  19703. var NAME = 7; /* i: waiting for end of file name (gzip) */
  19704. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  19705. var HCRC = 9; /* i: waiting for header crc (gzip) */
  19706. var DICTID = 10; /* i: waiting for dictionary check value */
  19707. var DICT = 11; /* waiting for inflateSetDictionary() call */
  19708. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19709. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  19710. var STORED = 14; /* i: waiting for stored size (length and complement) */
  19711. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  19712. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  19713. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  19714. var LENLENS = 18; /* i: waiting for code length code lengths */
  19715. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  19716. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  19717. var LEN = 21; /* i: waiting for length/lit/eob code */
  19718. var LENEXT = 22; /* i: waiting for length extra bits */
  19719. var DIST = 23; /* i: waiting for distance code */
  19720. var DISTEXT = 24; /* i: waiting for distance extra bits */
  19721. var MATCH = 25; /* o: waiting for output space to copy string */
  19722. var LIT = 26; /* o: waiting for output space to write literal */
  19723. var CHECK = 27; /* i: waiting for 32-bit check value */
  19724. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  19725. var DONE = 29; /* finished check, done -- remain here until reset */
  19726. var BAD = 30; /* got a data error -- remain here until reset */
  19727. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  19728. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  19729. /* ===========================================================================*/
  19730. var ENOUGH_LENS = 852;
  19731. var ENOUGH_DISTS = 592;
  19732. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  19733. var MAX_WBITS = 15;
  19734. /* 32K LZ77 window */
  19735. var DEF_WBITS = MAX_WBITS;
  19736. function ZSWAP32(q) {
  19737. return (((q >>> 24) & 0xff) +
  19738. ((q >>> 8) & 0xff00) +
  19739. ((q & 0xff00) << 8) +
  19740. ((q & 0xff) << 24));
  19741. }
  19742. function InflateState() {
  19743. this.mode = 0; /* current inflate mode */
  19744. this.last = false; /* true if processing last block */
  19745. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  19746. this.havedict = false; /* true if dictionary provided */
  19747. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  19748. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  19749. this.check = 0; /* protected copy of check value */
  19750. this.total = 0; /* protected copy of output count */
  19751. // TODO: may be {}
  19752. this.head = null; /* where to save gzip header information */
  19753. /* sliding window */
  19754. this.wbits = 0; /* log base 2 of requested window size */
  19755. this.wsize = 0; /* window size or zero if not using window */
  19756. this.whave = 0; /* valid bytes in the window */
  19757. this.wnext = 0; /* window write index */
  19758. this.window = null; /* allocated sliding window, if needed */
  19759. /* bit accumulator */
  19760. this.hold = 0; /* input bit accumulator */
  19761. this.bits = 0; /* number of bits in "in" */
  19762. /* for string and stored block copying */
  19763. this.length = 0; /* literal or length of data to copy */
  19764. this.offset = 0; /* distance back to copy string from */
  19765. /* for table and code decoding */
  19766. this.extra = 0; /* extra bits needed */
  19767. /* fixed and dynamic code tables */
  19768. this.lencode = null; /* starting table for length/literal codes */
  19769. this.distcode = null; /* starting table for distance codes */
  19770. this.lenbits = 0; /* index bits for lencode */
  19771. this.distbits = 0; /* index bits for distcode */
  19772. /* dynamic table building */
  19773. this.ncode = 0; /* number of code length code lengths */
  19774. this.nlen = 0; /* number of length code lengths */
  19775. this.ndist = 0; /* number of distance code lengths */
  19776. this.have = 0; /* number of code lengths in lens[] */
  19777. this.next = null; /* next available space in codes[] */
  19778. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  19779. this.work = new utils.Buf16(288); /* work area for code table building */
  19780. /*
  19781. because we don't have pointers in js, we use lencode and distcode directly
  19782. as buffers so we don't need codes
  19783. */
  19784. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  19785. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  19786. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  19787. this.sane = 0; /* if false, allow invalid distance too far */
  19788. this.back = 0; /* bits back of last unprocessed length/lit */
  19789. this.was = 0; /* initial length of match */
  19790. }
  19791. function inflateResetKeep(strm) {
  19792. var state;
  19793. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19794. state = strm.state;
  19795. strm.total_in = strm.total_out = state.total = 0;
  19796. strm.msg = ''; /*Z_NULL*/
  19797. if (state.wrap) { /* to support ill-conceived Java test suite */
  19798. strm.adler = state.wrap & 1;
  19799. }
  19800. state.mode = HEAD;
  19801. state.last = 0;
  19802. state.havedict = 0;
  19803. state.dmax = 32768;
  19804. state.head = null/*Z_NULL*/;
  19805. state.hold = 0;
  19806. state.bits = 0;
  19807. //state.lencode = state.distcode = state.next = state.codes;
  19808. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  19809. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  19810. state.sane = 1;
  19811. state.back = -1;
  19812. //Tracev((stderr, "inflate: reset\n"));
  19813. return Z_OK;
  19814. }
  19815. function inflateReset(strm) {
  19816. var state;
  19817. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19818. state = strm.state;
  19819. state.wsize = 0;
  19820. state.whave = 0;
  19821. state.wnext = 0;
  19822. return inflateResetKeep(strm);
  19823. }
  19824. function inflateReset2(strm, windowBits) {
  19825. var wrap;
  19826. var state;
  19827. /* get the state */
  19828. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19829. state = strm.state;
  19830. /* extract wrap request from windowBits parameter */
  19831. if (windowBits < 0) {
  19832. wrap = 0;
  19833. windowBits = -windowBits;
  19834. }
  19835. else {
  19836. wrap = (windowBits >> 4) + 1;
  19837. if (windowBits < 48) {
  19838. windowBits &= 15;
  19839. }
  19840. }
  19841. /* set number of window bits, free window if different */
  19842. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  19843. return Z_STREAM_ERROR;
  19844. }
  19845. if (state.window !== null && state.wbits !== windowBits) {
  19846. state.window = null;
  19847. }
  19848. /* update state and reset the rest of it */
  19849. state.wrap = wrap;
  19850. state.wbits = windowBits;
  19851. return inflateReset(strm);
  19852. }
  19853. function inflateInit2(strm, windowBits) {
  19854. var ret;
  19855. var state;
  19856. if (!strm) { return Z_STREAM_ERROR; }
  19857. //strm.msg = Z_NULL; /* in case we return an error */
  19858. state = new InflateState();
  19859. //if (state === Z_NULL) return Z_MEM_ERROR;
  19860. //Tracev((stderr, "inflate: allocated\n"));
  19861. strm.state = state;
  19862. state.window = null/*Z_NULL*/;
  19863. ret = inflateReset2(strm, windowBits);
  19864. if (ret !== Z_OK) {
  19865. strm.state = null/*Z_NULL*/;
  19866. }
  19867. return ret;
  19868. }
  19869. function inflateInit(strm) {
  19870. return inflateInit2(strm, DEF_WBITS);
  19871. }
  19872. /*
  19873. Return state with length and distance decoding tables and index sizes set to
  19874. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  19875. If BUILDFIXED is defined, then instead this routine builds the tables the
  19876. first time it's called, and returns those tables the first time and
  19877. thereafter. This reduces the size of the code by about 2K bytes, in
  19878. exchange for a little execution time. However, BUILDFIXED should not be
  19879. used for threaded applications, since the rewriting of the tables and virgin
  19880. may not be thread-safe.
  19881. */
  19882. var virgin = true;
  19883. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  19884. function fixedtables(state) {
  19885. /* build fixed huffman tables if first call (may not be thread safe) */
  19886. if (virgin) {
  19887. var sym;
  19888. lenfix = new utils.Buf32(512);
  19889. distfix = new utils.Buf32(32);
  19890. /* literal/length table */
  19891. sym = 0;
  19892. while (sym < 144) { state.lens[sym++] = 8; }
  19893. while (sym < 256) { state.lens[sym++] = 9; }
  19894. while (sym < 280) { state.lens[sym++] = 7; }
  19895. while (sym < 288) { state.lens[sym++] = 8; }
  19896. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  19897. /* distance table */
  19898. sym = 0;
  19899. while (sym < 32) { state.lens[sym++] = 5; }
  19900. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  19901. /* do this just once */
  19902. virgin = false;
  19903. }
  19904. state.lencode = lenfix;
  19905. state.lenbits = 9;
  19906. state.distcode = distfix;
  19907. state.distbits = 5;
  19908. }
  19909. /*
  19910. Update the window with the last wsize (normally 32K) bytes written before
  19911. returning. If window does not exist yet, create it. This is only called
  19912. when a window is already in use, or when output has been written during this
  19913. inflate call, but the end of the deflate stream has not been reached yet.
  19914. It is also called to create a window for dictionary data when a dictionary
  19915. is loaded.
  19916. Providing output buffers larger than 32K to inflate() should provide a speed
  19917. advantage, since only the last 32K of output is copied to the sliding window
  19918. upon return from inflate(), and since all distances after the first 32K of
  19919. output will fall in the output data, making match copies simpler and faster.
  19920. The advantage may be dependent on the size of the processor's data caches.
  19921. */
  19922. function updatewindow(strm, src, end, copy) {
  19923. var dist;
  19924. var state = strm.state;
  19925. /* if it hasn't been done already, allocate space for the window */
  19926. if (state.window === null) {
  19927. state.wsize = 1 << state.wbits;
  19928. state.wnext = 0;
  19929. state.whave = 0;
  19930. state.window = new utils.Buf8(state.wsize);
  19931. }
  19932. /* copy state->wsize or less output bytes into the circular window */
  19933. if (copy >= state.wsize) {
  19934. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  19935. state.wnext = 0;
  19936. state.whave = state.wsize;
  19937. }
  19938. else {
  19939. dist = state.wsize - state.wnext;
  19940. if (dist > copy) {
  19941. dist = copy;
  19942. }
  19943. //zmemcpy(state->window + state->wnext, end - copy, dist);
  19944. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  19945. copy -= dist;
  19946. if (copy) {
  19947. //zmemcpy(state->window, end - copy, copy);
  19948. utils.arraySet(state.window,src, end - copy, copy, 0);
  19949. state.wnext = copy;
  19950. state.whave = state.wsize;
  19951. }
  19952. else {
  19953. state.wnext += dist;
  19954. if (state.wnext === state.wsize) { state.wnext = 0; }
  19955. if (state.whave < state.wsize) { state.whave += dist; }
  19956. }
  19957. }
  19958. return 0;
  19959. }
  19960. function inflate(strm, flush) {
  19961. var state;
  19962. var input, output; // input/output buffers
  19963. var next; /* next input INDEX */
  19964. var put; /* next output INDEX */
  19965. var have, left; /* available input and output */
  19966. var hold; /* bit buffer */
  19967. var bits; /* bits in bit buffer */
  19968. var _in, _out; /* save starting available input and output */
  19969. var copy; /* number of stored or match bytes to copy */
  19970. var from; /* where to copy match bytes from */
  19971. var from_source;
  19972. var here = 0; /* current decoding table entry */
  19973. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  19974. //var last; /* parent table entry */
  19975. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  19976. var len; /* length to copy for repeats, bits to drop */
  19977. var ret; /* return code */
  19978. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  19979. var opts;
  19980. var n; // temporary var for NEED_BITS
  19981. var order = /* permutation of code lengths */
  19982. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  19983. if (!strm || !strm.state || !strm.output ||
  19984. (!strm.input && strm.avail_in !== 0)) {
  19985. return Z_STREAM_ERROR;
  19986. }
  19987. state = strm.state;
  19988. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  19989. //--- LOAD() ---
  19990. put = strm.next_out;
  19991. output = strm.output;
  19992. left = strm.avail_out;
  19993. next = strm.next_in;
  19994. input = strm.input;
  19995. have = strm.avail_in;
  19996. hold = state.hold;
  19997. bits = state.bits;
  19998. //---
  19999. _in = have;
  20000. _out = left;
  20001. ret = Z_OK;
  20002. inf_leave: // goto emulation
  20003. for (;;) {
  20004. switch (state.mode) {
  20005. case HEAD:
  20006. if (state.wrap === 0) {
  20007. state.mode = TYPEDO;
  20008. break;
  20009. }
  20010. //=== NEEDBITS(16);
  20011. while (bits < 16) {
  20012. if (have === 0) { break inf_leave; }
  20013. have--;
  20014. hold += input[next++] << bits;
  20015. bits += 8;
  20016. }
  20017. //===//
  20018. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  20019. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  20020. //=== CRC2(state.check, hold);
  20021. hbuf[0] = hold & 0xff;
  20022. hbuf[1] = (hold >>> 8) & 0xff;
  20023. state.check = crc32(state.check, hbuf, 2, 0);
  20024. //===//
  20025. //=== INITBITS();
  20026. hold = 0;
  20027. bits = 0;
  20028. //===//
  20029. state.mode = FLAGS;
  20030. break;
  20031. }
  20032. state.flags = 0; /* expect zlib header */
  20033. if (state.head) {
  20034. state.head.done = false;
  20035. }
  20036. if (!(state.wrap & 1) || /* check if zlib header allowed */
  20037. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  20038. strm.msg = 'incorrect header check';
  20039. state.mode = BAD;
  20040. break;
  20041. }
  20042. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  20043. strm.msg = 'unknown compression method';
  20044. state.mode = BAD;
  20045. break;
  20046. }
  20047. //--- DROPBITS(4) ---//
  20048. hold >>>= 4;
  20049. bits -= 4;
  20050. //---//
  20051. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  20052. if (state.wbits === 0) {
  20053. state.wbits = len;
  20054. }
  20055. else if (len > state.wbits) {
  20056. strm.msg = 'invalid window size';
  20057. state.mode = BAD;
  20058. break;
  20059. }
  20060. state.dmax = 1 << len;
  20061. //Tracev((stderr, "inflate: zlib header ok\n"));
  20062. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20063. state.mode = hold & 0x200 ? DICTID : TYPE;
  20064. //=== INITBITS();
  20065. hold = 0;
  20066. bits = 0;
  20067. //===//
  20068. break;
  20069. case FLAGS:
  20070. //=== NEEDBITS(16); */
  20071. while (bits < 16) {
  20072. if (have === 0) { break inf_leave; }
  20073. have--;
  20074. hold += input[next++] << bits;
  20075. bits += 8;
  20076. }
  20077. //===//
  20078. state.flags = hold;
  20079. if ((state.flags & 0xff) !== Z_DEFLATED) {
  20080. strm.msg = 'unknown compression method';
  20081. state.mode = BAD;
  20082. break;
  20083. }
  20084. if (state.flags & 0xe000) {
  20085. strm.msg = 'unknown header flags set';
  20086. state.mode = BAD;
  20087. break;
  20088. }
  20089. if (state.head) {
  20090. state.head.text = ((hold >> 8) & 1);
  20091. }
  20092. if (state.flags & 0x0200) {
  20093. //=== CRC2(state.check, hold);
  20094. hbuf[0] = hold & 0xff;
  20095. hbuf[1] = (hold >>> 8) & 0xff;
  20096. state.check = crc32(state.check, hbuf, 2, 0);
  20097. //===//
  20098. }
  20099. //=== INITBITS();
  20100. hold = 0;
  20101. bits = 0;
  20102. //===//
  20103. state.mode = TIME;
  20104. /* falls through */
  20105. case TIME:
  20106. //=== NEEDBITS(32); */
  20107. while (bits < 32) {
  20108. if (have === 0) { break inf_leave; }
  20109. have--;
  20110. hold += input[next++] << bits;
  20111. bits += 8;
  20112. }
  20113. //===//
  20114. if (state.head) {
  20115. state.head.time = hold;
  20116. }
  20117. if (state.flags & 0x0200) {
  20118. //=== CRC4(state.check, hold)
  20119. hbuf[0] = hold & 0xff;
  20120. hbuf[1] = (hold >>> 8) & 0xff;
  20121. hbuf[2] = (hold >>> 16) & 0xff;
  20122. hbuf[3] = (hold >>> 24) & 0xff;
  20123. state.check = crc32(state.check, hbuf, 4, 0);
  20124. //===
  20125. }
  20126. //=== INITBITS();
  20127. hold = 0;
  20128. bits = 0;
  20129. //===//
  20130. state.mode = OS;
  20131. /* falls through */
  20132. case OS:
  20133. //=== NEEDBITS(16); */
  20134. while (bits < 16) {
  20135. if (have === 0) { break inf_leave; }
  20136. have--;
  20137. hold += input[next++] << bits;
  20138. bits += 8;
  20139. }
  20140. //===//
  20141. if (state.head) {
  20142. state.head.xflags = (hold & 0xff);
  20143. state.head.os = (hold >> 8);
  20144. }
  20145. if (state.flags & 0x0200) {
  20146. //=== CRC2(state.check, hold);
  20147. hbuf[0] = hold & 0xff;
  20148. hbuf[1] = (hold >>> 8) & 0xff;
  20149. state.check = crc32(state.check, hbuf, 2, 0);
  20150. //===//
  20151. }
  20152. //=== INITBITS();
  20153. hold = 0;
  20154. bits = 0;
  20155. //===//
  20156. state.mode = EXLEN;
  20157. /* falls through */
  20158. case EXLEN:
  20159. if (state.flags & 0x0400) {
  20160. //=== NEEDBITS(16); */
  20161. while (bits < 16) {
  20162. if (have === 0) { break inf_leave; }
  20163. have--;
  20164. hold += input[next++] << bits;
  20165. bits += 8;
  20166. }
  20167. //===//
  20168. state.length = hold;
  20169. if (state.head) {
  20170. state.head.extra_len = hold;
  20171. }
  20172. if (state.flags & 0x0200) {
  20173. //=== CRC2(state.check, hold);
  20174. hbuf[0] = hold & 0xff;
  20175. hbuf[1] = (hold >>> 8) & 0xff;
  20176. state.check = crc32(state.check, hbuf, 2, 0);
  20177. //===//
  20178. }
  20179. //=== INITBITS();
  20180. hold = 0;
  20181. bits = 0;
  20182. //===//
  20183. }
  20184. else if (state.head) {
  20185. state.head.extra = null/*Z_NULL*/;
  20186. }
  20187. state.mode = EXTRA;
  20188. /* falls through */
  20189. case EXTRA:
  20190. if (state.flags & 0x0400) {
  20191. copy = state.length;
  20192. if (copy > have) { copy = have; }
  20193. if (copy) {
  20194. if (state.head) {
  20195. len = state.head.extra_len - state.length;
  20196. if (!state.head.extra) {
  20197. // Use untyped array for more conveniend processing later
  20198. state.head.extra = new Array(state.head.extra_len);
  20199. }
  20200. utils.arraySet(
  20201. state.head.extra,
  20202. input,
  20203. next,
  20204. // extra field is limited to 65536 bytes
  20205. // - no need for additional size check
  20206. copy,
  20207. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  20208. len
  20209. );
  20210. //zmemcpy(state.head.extra + len, next,
  20211. // len + copy > state.head.extra_max ?
  20212. // state.head.extra_max - len : copy);
  20213. }
  20214. if (state.flags & 0x0200) {
  20215. state.check = crc32(state.check, input, copy, next);
  20216. }
  20217. have -= copy;
  20218. next += copy;
  20219. state.length -= copy;
  20220. }
  20221. if (state.length) { break inf_leave; }
  20222. }
  20223. state.length = 0;
  20224. state.mode = NAME;
  20225. /* falls through */
  20226. case NAME:
  20227. if (state.flags & 0x0800) {
  20228. if (have === 0) { break inf_leave; }
  20229. copy = 0;
  20230. do {
  20231. // TODO: 2 or 1 bytes?
  20232. len = input[next + copy++];
  20233. /* use constant limit because in js we should not preallocate memory */
  20234. if (state.head && len &&
  20235. (state.length < 65536 /*state.head.name_max*/)) {
  20236. state.head.name += String.fromCharCode(len);
  20237. }
  20238. } while (len && copy < have);
  20239. if (state.flags & 0x0200) {
  20240. state.check = crc32(state.check, input, copy, next);
  20241. }
  20242. have -= copy;
  20243. next += copy;
  20244. if (len) { break inf_leave; }
  20245. }
  20246. else if (state.head) {
  20247. state.head.name = null;
  20248. }
  20249. state.length = 0;
  20250. state.mode = COMMENT;
  20251. /* falls through */
  20252. case COMMENT:
  20253. if (state.flags & 0x1000) {
  20254. if (have === 0) { break inf_leave; }
  20255. copy = 0;
  20256. do {
  20257. len = input[next + copy++];
  20258. /* use constant limit because in js we should not preallocate memory */
  20259. if (state.head && len &&
  20260. (state.length < 65536 /*state.head.comm_max*/)) {
  20261. state.head.comment += String.fromCharCode(len);
  20262. }
  20263. } while (len && copy < have);
  20264. if (state.flags & 0x0200) {
  20265. state.check = crc32(state.check, input, copy, next);
  20266. }
  20267. have -= copy;
  20268. next += copy;
  20269. if (len) { break inf_leave; }
  20270. }
  20271. else if (state.head) {
  20272. state.head.comment = null;
  20273. }
  20274. state.mode = HCRC;
  20275. /* falls through */
  20276. case HCRC:
  20277. if (state.flags & 0x0200) {
  20278. //=== NEEDBITS(16); */
  20279. while (bits < 16) {
  20280. if (have === 0) { break inf_leave; }
  20281. have--;
  20282. hold += input[next++] << bits;
  20283. bits += 8;
  20284. }
  20285. //===//
  20286. if (hold !== (state.check & 0xffff)) {
  20287. strm.msg = 'header crc mismatch';
  20288. state.mode = BAD;
  20289. break;
  20290. }
  20291. //=== INITBITS();
  20292. hold = 0;
  20293. bits = 0;
  20294. //===//
  20295. }
  20296. if (state.head) {
  20297. state.head.hcrc = ((state.flags >> 9) & 1);
  20298. state.head.done = true;
  20299. }
  20300. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  20301. state.mode = TYPE;
  20302. break;
  20303. case DICTID:
  20304. //=== NEEDBITS(32); */
  20305. while (bits < 32) {
  20306. if (have === 0) { break inf_leave; }
  20307. have--;
  20308. hold += input[next++] << bits;
  20309. bits += 8;
  20310. }
  20311. //===//
  20312. strm.adler = state.check = ZSWAP32(hold);
  20313. //=== INITBITS();
  20314. hold = 0;
  20315. bits = 0;
  20316. //===//
  20317. state.mode = DICT;
  20318. /* falls through */
  20319. case DICT:
  20320. if (state.havedict === 0) {
  20321. //--- RESTORE() ---
  20322. strm.next_out = put;
  20323. strm.avail_out = left;
  20324. strm.next_in = next;
  20325. strm.avail_in = have;
  20326. state.hold = hold;
  20327. state.bits = bits;
  20328. //---
  20329. return Z_NEED_DICT;
  20330. }
  20331. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20332. state.mode = TYPE;
  20333. /* falls through */
  20334. case TYPE:
  20335. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  20336. /* falls through */
  20337. case TYPEDO:
  20338. if (state.last) {
  20339. //--- BYTEBITS() ---//
  20340. hold >>>= bits & 7;
  20341. bits -= bits & 7;
  20342. //---//
  20343. state.mode = CHECK;
  20344. break;
  20345. }
  20346. //=== NEEDBITS(3); */
  20347. while (bits < 3) {
  20348. if (have === 0) { break inf_leave; }
  20349. have--;
  20350. hold += input[next++] << bits;
  20351. bits += 8;
  20352. }
  20353. //===//
  20354. state.last = (hold & 0x01)/*BITS(1)*/;
  20355. //--- DROPBITS(1) ---//
  20356. hold >>>= 1;
  20357. bits -= 1;
  20358. //---//
  20359. switch ((hold & 0x03)/*BITS(2)*/) {
  20360. case 0: /* stored block */
  20361. //Tracev((stderr, "inflate: stored block%s\n",
  20362. // state.last ? " (last)" : ""));
  20363. state.mode = STORED;
  20364. break;
  20365. case 1: /* fixed block */
  20366. fixedtables(state);
  20367. //Tracev((stderr, "inflate: fixed codes block%s\n",
  20368. // state.last ? " (last)" : ""));
  20369. state.mode = LEN_; /* decode codes */
  20370. if (flush === Z_TREES) {
  20371. //--- DROPBITS(2) ---//
  20372. hold >>>= 2;
  20373. bits -= 2;
  20374. //---//
  20375. break inf_leave;
  20376. }
  20377. break;
  20378. case 2: /* dynamic block */
  20379. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  20380. // state.last ? " (last)" : ""));
  20381. state.mode = TABLE;
  20382. break;
  20383. case 3:
  20384. strm.msg = 'invalid block type';
  20385. state.mode = BAD;
  20386. }
  20387. //--- DROPBITS(2) ---//
  20388. hold >>>= 2;
  20389. bits -= 2;
  20390. //---//
  20391. break;
  20392. case STORED:
  20393. //--- BYTEBITS() ---// /* go to byte boundary */
  20394. hold >>>= bits & 7;
  20395. bits -= bits & 7;
  20396. //---//
  20397. //=== NEEDBITS(32); */
  20398. while (bits < 32) {
  20399. if (have === 0) { break inf_leave; }
  20400. have--;
  20401. hold += input[next++] << bits;
  20402. bits += 8;
  20403. }
  20404. //===//
  20405. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  20406. strm.msg = 'invalid stored block lengths';
  20407. state.mode = BAD;
  20408. break;
  20409. }
  20410. state.length = hold & 0xffff;
  20411. //Tracev((stderr, "inflate: stored length %u\n",
  20412. // state.length));
  20413. //=== INITBITS();
  20414. hold = 0;
  20415. bits = 0;
  20416. //===//
  20417. state.mode = COPY_;
  20418. if (flush === Z_TREES) { break inf_leave; }
  20419. /* falls through */
  20420. case COPY_:
  20421. state.mode = COPY;
  20422. /* falls through */
  20423. case COPY:
  20424. copy = state.length;
  20425. if (copy) {
  20426. if (copy > have) { copy = have; }
  20427. if (copy > left) { copy = left; }
  20428. if (copy === 0) { break inf_leave; }
  20429. //--- zmemcpy(put, next, copy); ---
  20430. utils.arraySet(output, input, next, copy, put);
  20431. //---//
  20432. have -= copy;
  20433. next += copy;
  20434. left -= copy;
  20435. put += copy;
  20436. state.length -= copy;
  20437. break;
  20438. }
  20439. //Tracev((stderr, "inflate: stored end\n"));
  20440. state.mode = TYPE;
  20441. break;
  20442. case TABLE:
  20443. //=== NEEDBITS(14); */
  20444. while (bits < 14) {
  20445. if (have === 0) { break inf_leave; }
  20446. have--;
  20447. hold += input[next++] << bits;
  20448. bits += 8;
  20449. }
  20450. //===//
  20451. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  20452. //--- DROPBITS(5) ---//
  20453. hold >>>= 5;
  20454. bits -= 5;
  20455. //---//
  20456. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  20457. //--- DROPBITS(5) ---//
  20458. hold >>>= 5;
  20459. bits -= 5;
  20460. //---//
  20461. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  20462. //--- DROPBITS(4) ---//
  20463. hold >>>= 4;
  20464. bits -= 4;
  20465. //---//
  20466. //#ifndef PKZIP_BUG_WORKAROUND
  20467. if (state.nlen > 286 || state.ndist > 30) {
  20468. strm.msg = 'too many length or distance symbols';
  20469. state.mode = BAD;
  20470. break;
  20471. }
  20472. //#endif
  20473. //Tracev((stderr, "inflate: table sizes ok\n"));
  20474. state.have = 0;
  20475. state.mode = LENLENS;
  20476. /* falls through */
  20477. case LENLENS:
  20478. while (state.have < state.ncode) {
  20479. //=== NEEDBITS(3);
  20480. while (bits < 3) {
  20481. if (have === 0) { break inf_leave; }
  20482. have--;
  20483. hold += input[next++] << bits;
  20484. bits += 8;
  20485. }
  20486. //===//
  20487. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  20488. //--- DROPBITS(3) ---//
  20489. hold >>>= 3;
  20490. bits -= 3;
  20491. //---//
  20492. }
  20493. while (state.have < 19) {
  20494. state.lens[order[state.have++]] = 0;
  20495. }
  20496. // We have separate tables & no pointers. 2 commented lines below not needed.
  20497. //state.next = state.codes;
  20498. //state.lencode = state.next;
  20499. // Switch to use dynamic table
  20500. state.lencode = state.lendyn;
  20501. state.lenbits = 7;
  20502. opts = {bits: state.lenbits};
  20503. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  20504. state.lenbits = opts.bits;
  20505. if (ret) {
  20506. strm.msg = 'invalid code lengths set';
  20507. state.mode = BAD;
  20508. break;
  20509. }
  20510. //Tracev((stderr, "inflate: code lengths ok\n"));
  20511. state.have = 0;
  20512. state.mode = CODELENS;
  20513. /* falls through */
  20514. case CODELENS:
  20515. while (state.have < state.nlen + state.ndist) {
  20516. for (;;) {
  20517. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  20518. here_bits = here >>> 24;
  20519. here_op = (here >>> 16) & 0xff;
  20520. here_val = here & 0xffff;
  20521. if ((here_bits) <= bits) { break; }
  20522. //--- PULLBYTE() ---//
  20523. if (have === 0) { break inf_leave; }
  20524. have--;
  20525. hold += input[next++] << bits;
  20526. bits += 8;
  20527. //---//
  20528. }
  20529. if (here_val < 16) {
  20530. //--- DROPBITS(here.bits) ---//
  20531. hold >>>= here_bits;
  20532. bits -= here_bits;
  20533. //---//
  20534. state.lens[state.have++] = here_val;
  20535. }
  20536. else {
  20537. if (here_val === 16) {
  20538. //=== NEEDBITS(here.bits + 2);
  20539. n = here_bits + 2;
  20540. while (bits < n) {
  20541. if (have === 0) { break inf_leave; }
  20542. have--;
  20543. hold += input[next++] << bits;
  20544. bits += 8;
  20545. }
  20546. //===//
  20547. //--- DROPBITS(here.bits) ---//
  20548. hold >>>= here_bits;
  20549. bits -= here_bits;
  20550. //---//
  20551. if (state.have === 0) {
  20552. strm.msg = 'invalid bit length repeat';
  20553. state.mode = BAD;
  20554. break;
  20555. }
  20556. len = state.lens[state.have - 1];
  20557. copy = 3 + (hold & 0x03);//BITS(2);
  20558. //--- DROPBITS(2) ---//
  20559. hold >>>= 2;
  20560. bits -= 2;
  20561. //---//
  20562. }
  20563. else if (here_val === 17) {
  20564. //=== NEEDBITS(here.bits + 3);
  20565. n = here_bits + 3;
  20566. while (bits < n) {
  20567. if (have === 0) { break inf_leave; }
  20568. have--;
  20569. hold += input[next++] << bits;
  20570. bits += 8;
  20571. }
  20572. //===//
  20573. //--- DROPBITS(here.bits) ---//
  20574. hold >>>= here_bits;
  20575. bits -= here_bits;
  20576. //---//
  20577. len = 0;
  20578. copy = 3 + (hold & 0x07);//BITS(3);
  20579. //--- DROPBITS(3) ---//
  20580. hold >>>= 3;
  20581. bits -= 3;
  20582. //---//
  20583. }
  20584. else {
  20585. //=== NEEDBITS(here.bits + 7);
  20586. n = here_bits + 7;
  20587. while (bits < n) {
  20588. if (have === 0) { break inf_leave; }
  20589. have--;
  20590. hold += input[next++] << bits;
  20591. bits += 8;
  20592. }
  20593. //===//
  20594. //--- DROPBITS(here.bits) ---//
  20595. hold >>>= here_bits;
  20596. bits -= here_bits;
  20597. //---//
  20598. len = 0;
  20599. copy = 11 + (hold & 0x7f);//BITS(7);
  20600. //--- DROPBITS(7) ---//
  20601. hold >>>= 7;
  20602. bits -= 7;
  20603. //---//
  20604. }
  20605. if (state.have + copy > state.nlen + state.ndist) {
  20606. strm.msg = 'invalid bit length repeat';
  20607. state.mode = BAD;
  20608. break;
  20609. }
  20610. while (copy--) {
  20611. state.lens[state.have++] = len;
  20612. }
  20613. }
  20614. }
  20615. /* handle error breaks in while */
  20616. if (state.mode === BAD) { break; }
  20617. /* check for end-of-block code (better have one) */
  20618. if (state.lens[256] === 0) {
  20619. strm.msg = 'invalid code -- missing end-of-block';
  20620. state.mode = BAD;
  20621. break;
  20622. }
  20623. /* build code tables -- note: do not change the lenbits or distbits
  20624. values here (9 and 6) without reading the comments in inftrees.h
  20625. concerning the ENOUGH constants, which depend on those values */
  20626. state.lenbits = 9;
  20627. opts = {bits: state.lenbits};
  20628. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  20629. // We have separate tables & no pointers. 2 commented lines below not needed.
  20630. // state.next_index = opts.table_index;
  20631. state.lenbits = opts.bits;
  20632. // state.lencode = state.next;
  20633. if (ret) {
  20634. strm.msg = 'invalid literal/lengths set';
  20635. state.mode = BAD;
  20636. break;
  20637. }
  20638. state.distbits = 6;
  20639. //state.distcode.copy(state.codes);
  20640. // Switch to use dynamic table
  20641. state.distcode = state.distdyn;
  20642. opts = {bits: state.distbits};
  20643. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  20644. // We have separate tables & no pointers. 2 commented lines below not needed.
  20645. // state.next_index = opts.table_index;
  20646. state.distbits = opts.bits;
  20647. // state.distcode = state.next;
  20648. if (ret) {
  20649. strm.msg = 'invalid distances set';
  20650. state.mode = BAD;
  20651. break;
  20652. }
  20653. //Tracev((stderr, 'inflate: codes ok\n'));
  20654. state.mode = LEN_;
  20655. if (flush === Z_TREES) { break inf_leave; }
  20656. /* falls through */
  20657. case LEN_:
  20658. state.mode = LEN;
  20659. /* falls through */
  20660. case LEN:
  20661. if (have >= 6 && left >= 258) {
  20662. //--- RESTORE() ---
  20663. strm.next_out = put;
  20664. strm.avail_out = left;
  20665. strm.next_in = next;
  20666. strm.avail_in = have;
  20667. state.hold = hold;
  20668. state.bits = bits;
  20669. //---
  20670. inflate_fast(strm, _out);
  20671. //--- LOAD() ---
  20672. put = strm.next_out;
  20673. output = strm.output;
  20674. left = strm.avail_out;
  20675. next = strm.next_in;
  20676. input = strm.input;
  20677. have = strm.avail_in;
  20678. hold = state.hold;
  20679. bits = state.bits;
  20680. //---
  20681. if (state.mode === TYPE) {
  20682. state.back = -1;
  20683. }
  20684. break;
  20685. }
  20686. state.back = 0;
  20687. for (;;) {
  20688. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  20689. here_bits = here >>> 24;
  20690. here_op = (here >>> 16) & 0xff;
  20691. here_val = here & 0xffff;
  20692. if (here_bits <= bits) { break; }
  20693. //--- PULLBYTE() ---//
  20694. if (have === 0) { break inf_leave; }
  20695. have--;
  20696. hold += input[next++] << bits;
  20697. bits += 8;
  20698. //---//
  20699. }
  20700. if (here_op && (here_op & 0xf0) === 0) {
  20701. last_bits = here_bits;
  20702. last_op = here_op;
  20703. last_val = here_val;
  20704. for (;;) {
  20705. here = state.lencode[last_val +
  20706. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20707. here_bits = here >>> 24;
  20708. here_op = (here >>> 16) & 0xff;
  20709. here_val = here & 0xffff;
  20710. if ((last_bits + here_bits) <= bits) { break; }
  20711. //--- PULLBYTE() ---//
  20712. if (have === 0) { break inf_leave; }
  20713. have--;
  20714. hold += input[next++] << bits;
  20715. bits += 8;
  20716. //---//
  20717. }
  20718. //--- DROPBITS(last.bits) ---//
  20719. hold >>>= last_bits;
  20720. bits -= last_bits;
  20721. //---//
  20722. state.back += last_bits;
  20723. }
  20724. //--- DROPBITS(here.bits) ---//
  20725. hold >>>= here_bits;
  20726. bits -= here_bits;
  20727. //---//
  20728. state.back += here_bits;
  20729. state.length = here_val;
  20730. if (here_op === 0) {
  20731. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  20732. // "inflate: literal '%c'\n" :
  20733. // "inflate: literal 0x%02x\n", here.val));
  20734. state.mode = LIT;
  20735. break;
  20736. }
  20737. if (here_op & 32) {
  20738. //Tracevv((stderr, "inflate: end of block\n"));
  20739. state.back = -1;
  20740. state.mode = TYPE;
  20741. break;
  20742. }
  20743. if (here_op & 64) {
  20744. strm.msg = 'invalid literal/length code';
  20745. state.mode = BAD;
  20746. break;
  20747. }
  20748. state.extra = here_op & 15;
  20749. state.mode = LENEXT;
  20750. /* falls through */
  20751. case LENEXT:
  20752. if (state.extra) {
  20753. //=== NEEDBITS(state.extra);
  20754. n = state.extra;
  20755. while (bits < n) {
  20756. if (have === 0) { break inf_leave; }
  20757. have--;
  20758. hold += input[next++] << bits;
  20759. bits += 8;
  20760. }
  20761. //===//
  20762. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20763. //--- DROPBITS(state.extra) ---//
  20764. hold >>>= state.extra;
  20765. bits -= state.extra;
  20766. //---//
  20767. state.back += state.extra;
  20768. }
  20769. //Tracevv((stderr, "inflate: length %u\n", state.length));
  20770. state.was = state.length;
  20771. state.mode = DIST;
  20772. /* falls through */
  20773. case DIST:
  20774. for (;;) {
  20775. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  20776. here_bits = here >>> 24;
  20777. here_op = (here >>> 16) & 0xff;
  20778. here_val = here & 0xffff;
  20779. if ((here_bits) <= bits) { break; }
  20780. //--- PULLBYTE() ---//
  20781. if (have === 0) { break inf_leave; }
  20782. have--;
  20783. hold += input[next++] << bits;
  20784. bits += 8;
  20785. //---//
  20786. }
  20787. if ((here_op & 0xf0) === 0) {
  20788. last_bits = here_bits;
  20789. last_op = here_op;
  20790. last_val = here_val;
  20791. for (;;) {
  20792. here = state.distcode[last_val +
  20793. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20794. here_bits = here >>> 24;
  20795. here_op = (here >>> 16) & 0xff;
  20796. here_val = here & 0xffff;
  20797. if ((last_bits + here_bits) <= bits) { break; }
  20798. //--- PULLBYTE() ---//
  20799. if (have === 0) { break inf_leave; }
  20800. have--;
  20801. hold += input[next++] << bits;
  20802. bits += 8;
  20803. //---//
  20804. }
  20805. //--- DROPBITS(last.bits) ---//
  20806. hold >>>= last_bits;
  20807. bits -= last_bits;
  20808. //---//
  20809. state.back += last_bits;
  20810. }
  20811. //--- DROPBITS(here.bits) ---//
  20812. hold >>>= here_bits;
  20813. bits -= here_bits;
  20814. //---//
  20815. state.back += here_bits;
  20816. if (here_op & 64) {
  20817. strm.msg = 'invalid distance code';
  20818. state.mode = BAD;
  20819. break;
  20820. }
  20821. state.offset = here_val;
  20822. state.extra = (here_op) & 15;
  20823. state.mode = DISTEXT;
  20824. /* falls through */
  20825. case DISTEXT:
  20826. if (state.extra) {
  20827. //=== NEEDBITS(state.extra);
  20828. n = state.extra;
  20829. while (bits < n) {
  20830. if (have === 0) { break inf_leave; }
  20831. have--;
  20832. hold += input[next++] << bits;
  20833. bits += 8;
  20834. }
  20835. //===//
  20836. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20837. //--- DROPBITS(state.extra) ---//
  20838. hold >>>= state.extra;
  20839. bits -= state.extra;
  20840. //---//
  20841. state.back += state.extra;
  20842. }
  20843. //#ifdef INFLATE_STRICT
  20844. if (state.offset > state.dmax) {
  20845. strm.msg = 'invalid distance too far back';
  20846. state.mode = BAD;
  20847. break;
  20848. }
  20849. //#endif
  20850. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  20851. state.mode = MATCH;
  20852. /* falls through */
  20853. case MATCH:
  20854. if (left === 0) { break inf_leave; }
  20855. copy = _out - left;
  20856. if (state.offset > copy) { /* copy from window */
  20857. copy = state.offset - copy;
  20858. if (copy > state.whave) {
  20859. if (state.sane) {
  20860. strm.msg = 'invalid distance too far back';
  20861. state.mode = BAD;
  20862. break;
  20863. }
  20864. // (!) This block is disabled in zlib defailts,
  20865. // don't enable it for binary compatibility
  20866. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  20867. // Trace((stderr, "inflate.c too far\n"));
  20868. // copy -= state.whave;
  20869. // if (copy > state.length) { copy = state.length; }
  20870. // if (copy > left) { copy = left; }
  20871. // left -= copy;
  20872. // state.length -= copy;
  20873. // do {
  20874. // output[put++] = 0;
  20875. // } while (--copy);
  20876. // if (state.length === 0) { state.mode = LEN; }
  20877. // break;
  20878. //#endif
  20879. }
  20880. if (copy > state.wnext) {
  20881. copy -= state.wnext;
  20882. from = state.wsize - copy;
  20883. }
  20884. else {
  20885. from = state.wnext - copy;
  20886. }
  20887. if (copy > state.length) { copy = state.length; }
  20888. from_source = state.window;
  20889. }
  20890. else { /* copy from output */
  20891. from_source = output;
  20892. from = put - state.offset;
  20893. copy = state.length;
  20894. }
  20895. if (copy > left) { copy = left; }
  20896. left -= copy;
  20897. state.length -= copy;
  20898. do {
  20899. output[put++] = from_source[from++];
  20900. } while (--copy);
  20901. if (state.length === 0) { state.mode = LEN; }
  20902. break;
  20903. case LIT:
  20904. if (left === 0) { break inf_leave; }
  20905. output[put++] = state.length;
  20906. left--;
  20907. state.mode = LEN;
  20908. break;
  20909. case CHECK:
  20910. if (state.wrap) {
  20911. //=== NEEDBITS(32);
  20912. while (bits < 32) {
  20913. if (have === 0) { break inf_leave; }
  20914. have--;
  20915. // Use '|' insdead of '+' to make sure that result is signed
  20916. hold |= input[next++] << bits;
  20917. bits += 8;
  20918. }
  20919. //===//
  20920. _out -= left;
  20921. strm.total_out += _out;
  20922. state.total += _out;
  20923. if (_out) {
  20924. strm.adler = state.check =
  20925. /*UPDATE(state.check, put - _out, _out);*/
  20926. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  20927. }
  20928. _out = left;
  20929. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  20930. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  20931. strm.msg = 'incorrect data check';
  20932. state.mode = BAD;
  20933. break;
  20934. }
  20935. //=== INITBITS();
  20936. hold = 0;
  20937. bits = 0;
  20938. //===//
  20939. //Tracev((stderr, "inflate: check matches trailer\n"));
  20940. }
  20941. state.mode = LENGTH;
  20942. /* falls through */
  20943. case LENGTH:
  20944. if (state.wrap && state.flags) {
  20945. //=== NEEDBITS(32);
  20946. while (bits < 32) {
  20947. if (have === 0) { break inf_leave; }
  20948. have--;
  20949. hold += input[next++] << bits;
  20950. bits += 8;
  20951. }
  20952. //===//
  20953. if (hold !== (state.total & 0xffffffff)) {
  20954. strm.msg = 'incorrect length check';
  20955. state.mode = BAD;
  20956. break;
  20957. }
  20958. //=== INITBITS();
  20959. hold = 0;
  20960. bits = 0;
  20961. //===//
  20962. //Tracev((stderr, "inflate: length matches trailer\n"));
  20963. }
  20964. state.mode = DONE;
  20965. /* falls through */
  20966. case DONE:
  20967. ret = Z_STREAM_END;
  20968. break inf_leave;
  20969. case BAD:
  20970. ret = Z_DATA_ERROR;
  20971. break inf_leave;
  20972. case MEM:
  20973. return Z_MEM_ERROR;
  20974. case SYNC:
  20975. /* falls through */
  20976. default:
  20977. return Z_STREAM_ERROR;
  20978. }
  20979. }
  20980. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  20981. /*
  20982. Return from inflate(), updating the total counts and the check value.
  20983. If there was no progress during the inflate() call, return a buffer
  20984. error. Call updatewindow() to create and/or update the window state.
  20985. Note: a memory error from inflate() is non-recoverable.
  20986. */
  20987. //--- RESTORE() ---
  20988. strm.next_out = put;
  20989. strm.avail_out = left;
  20990. strm.next_in = next;
  20991. strm.avail_in = have;
  20992. state.hold = hold;
  20993. state.bits = bits;
  20994. //---
  20995. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  20996. (state.mode < CHECK || flush !== Z_FINISH))) {
  20997. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  20998. state.mode = MEM;
  20999. return Z_MEM_ERROR;
  21000. }
  21001. }
  21002. _in -= strm.avail_in;
  21003. _out -= strm.avail_out;
  21004. strm.total_in += _in;
  21005. strm.total_out += _out;
  21006. state.total += _out;
  21007. if (state.wrap && _out) {
  21008. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  21009. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  21010. }
  21011. strm.data_type = state.bits + (state.last ? 64 : 0) +
  21012. (state.mode === TYPE ? 128 : 0) +
  21013. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  21014. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  21015. ret = Z_BUF_ERROR;
  21016. }
  21017. return ret;
  21018. }
  21019. function inflateEnd(strm) {
  21020. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  21021. return Z_STREAM_ERROR;
  21022. }
  21023. var state = strm.state;
  21024. if (state.window) {
  21025. state.window = null;
  21026. }
  21027. strm.state = null;
  21028. return Z_OK;
  21029. }
  21030. function inflateGetHeader(strm, head) {
  21031. var state;
  21032. /* check state */
  21033. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21034. state = strm.state;
  21035. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  21036. /* save header structure */
  21037. state.head = head;
  21038. head.done = false;
  21039. return Z_OK;
  21040. }
  21041. exports.inflateReset = inflateReset;
  21042. exports.inflateReset2 = inflateReset2;
  21043. exports.inflateResetKeep = inflateResetKeep;
  21044. exports.inflateInit = inflateInit;
  21045. exports.inflateInit2 = inflateInit2;
  21046. exports.inflate = inflate;
  21047. exports.inflateEnd = inflateEnd;
  21048. exports.inflateGetHeader = inflateGetHeader;
  21049. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  21050. /* Not implemented
  21051. exports.inflateCopy = inflateCopy;
  21052. exports.inflateGetDictionary = inflateGetDictionary;
  21053. exports.inflateMark = inflateMark;
  21054. exports.inflatePrime = inflatePrime;
  21055. exports.inflateSetDictionary = inflateSetDictionary;
  21056. exports.inflateSync = inflateSync;
  21057. exports.inflateSyncPoint = inflateSyncPoint;
  21058. exports.inflateUndermine = inflateUndermine;
  21059. */
  21060. },{"../utils/common":66,"./adler32":68,"./crc32":70,"./inffast":73,"./inftrees":75}],75:[function(require,module,exports){
  21061. 'use strict';
  21062. var utils = require('../utils/common');
  21063. var MAXBITS = 15;
  21064. var ENOUGH_LENS = 852;
  21065. var ENOUGH_DISTS = 592;
  21066. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  21067. var CODES = 0;
  21068. var LENS = 1;
  21069. var DISTS = 2;
  21070. var lbase = [ /* Length codes 257..285 base */
  21071. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  21072. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  21073. ];
  21074. var lext = [ /* Length codes 257..285 extra */
  21075. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  21076. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  21077. ];
  21078. var dbase = [ /* Distance codes 0..29 base */
  21079. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  21080. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  21081. 8193, 12289, 16385, 24577, 0, 0
  21082. ];
  21083. var dext = [ /* Distance codes 0..29 extra */
  21084. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  21085. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  21086. 28, 28, 29, 29, 64, 64
  21087. ];
  21088. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  21089. {
  21090. var bits = opts.bits;
  21091. //here = opts.here; /* table entry for duplication */
  21092. var len = 0; /* a code's length in bits */
  21093. var sym = 0; /* index of code symbols */
  21094. var min = 0, max = 0; /* minimum and maximum code lengths */
  21095. var root = 0; /* number of index bits for root table */
  21096. var curr = 0; /* number of index bits for current table */
  21097. var drop = 0; /* code bits to drop for sub-table */
  21098. var left = 0; /* number of prefix codes available */
  21099. var used = 0; /* code entries in table used */
  21100. var huff = 0; /* Huffman code */
  21101. var incr; /* for incrementing code, index */
  21102. var fill; /* index for replicating entries */
  21103. var low; /* low bits for current root entry */
  21104. var mask; /* mask for low root bits */
  21105. var next; /* next available space in table */
  21106. var base = null; /* base value table to use */
  21107. var base_index = 0;
  21108. // var shoextra; /* extra bits table to use */
  21109. var end; /* use base and extra for symbol > end */
  21110. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  21111. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  21112. var extra = null;
  21113. var extra_index = 0;
  21114. var here_bits, here_op, here_val;
  21115. /*
  21116. Process a set of code lengths to create a canonical Huffman code. The
  21117. code lengths are lens[0..codes-1]. Each length corresponds to the
  21118. symbols 0..codes-1. The Huffman code is generated by first sorting the
  21119. symbols by length from short to long, and retaining the symbol order
  21120. for codes with equal lengths. Then the code starts with all zero bits
  21121. for the first code of the shortest length, and the codes are integer
  21122. increments for the same length, and zeros are appended as the length
  21123. increases. For the deflate format, these bits are stored backwards
  21124. from their more natural integer increment ordering, and so when the
  21125. decoding tables are built in the large loop below, the integer codes
  21126. are incremented backwards.
  21127. This routine assumes, but does not check, that all of the entries in
  21128. lens[] are in the range 0..MAXBITS. The caller must assure this.
  21129. 1..MAXBITS is interpreted as that code length. zero means that that
  21130. symbol does not occur in this code.
  21131. The codes are sorted by computing a count of codes for each length,
  21132. creating from that a table of starting indices for each length in the
  21133. sorted table, and then entering the symbols in order in the sorted
  21134. table. The sorted table is work[], with that space being provided by
  21135. the caller.
  21136. The length counts are used for other purposes as well, i.e. finding
  21137. the minimum and maximum length codes, determining if there are any
  21138. codes at all, checking for a valid set of lengths, and looking ahead
  21139. at length counts to determine sub-table sizes when building the
  21140. decoding tables.
  21141. */
  21142. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  21143. for (len = 0; len <= MAXBITS; len++) {
  21144. count[len] = 0;
  21145. }
  21146. for (sym = 0; sym < codes; sym++) {
  21147. count[lens[lens_index + sym]]++;
  21148. }
  21149. /* bound code lengths, force root to be within code lengths */
  21150. root = bits;
  21151. for (max = MAXBITS; max >= 1; max--) {
  21152. if (count[max] !== 0) { break; }
  21153. }
  21154. if (root > max) {
  21155. root = max;
  21156. }
  21157. if (max === 0) { /* no symbols to code at all */
  21158. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  21159. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  21160. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  21161. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21162. //table.op[opts.table_index] = 64;
  21163. //table.bits[opts.table_index] = 1;
  21164. //table.val[opts.table_index++] = 0;
  21165. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21166. opts.bits = 1;
  21167. return 0; /* no symbols, but wait for decoding to report error */
  21168. }
  21169. for (min = 1; min < max; min++) {
  21170. if (count[min] !== 0) { break; }
  21171. }
  21172. if (root < min) {
  21173. root = min;
  21174. }
  21175. /* check for an over-subscribed or incomplete set of lengths */
  21176. left = 1;
  21177. for (len = 1; len <= MAXBITS; len++) {
  21178. left <<= 1;
  21179. left -= count[len];
  21180. if (left < 0) {
  21181. return -1;
  21182. } /* over-subscribed */
  21183. }
  21184. if (left > 0 && (type === CODES || max !== 1)) {
  21185. return -1; /* incomplete set */
  21186. }
  21187. /* generate offsets into symbol table for each length for sorting */
  21188. offs[1] = 0;
  21189. for (len = 1; len < MAXBITS; len++) {
  21190. offs[len + 1] = offs[len] + count[len];
  21191. }
  21192. /* sort symbols by length, by symbol order within each length */
  21193. for (sym = 0; sym < codes; sym++) {
  21194. if (lens[lens_index + sym] !== 0) {
  21195. work[offs[lens[lens_index + sym]]++] = sym;
  21196. }
  21197. }
  21198. /*
  21199. Create and fill in decoding tables. In this loop, the table being
  21200. filled is at next and has curr index bits. The code being used is huff
  21201. with length len. That code is converted to an index by dropping drop
  21202. bits off of the bottom. For codes where len is less than drop + curr,
  21203. those top drop + curr - len bits are incremented through all values to
  21204. fill the table with replicated entries.
  21205. root is the number of index bits for the root table. When len exceeds
  21206. root, sub-tables are created pointed to by the root entry with an index
  21207. of the low root bits of huff. This is saved in low to check for when a
  21208. new sub-table should be started. drop is zero when the root table is
  21209. being filled, and drop is root when sub-tables are being filled.
  21210. When a new sub-table is needed, it is necessary to look ahead in the
  21211. code lengths to determine what size sub-table is needed. The length
  21212. counts are used for this, and so count[] is decremented as codes are
  21213. entered in the tables.
  21214. used keeps track of how many table entries have been allocated from the
  21215. provided *table space. It is checked for LENS and DIST tables against
  21216. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  21217. the initial root table size constants. See the comments in inftrees.h
  21218. for more information.
  21219. sym increments through all symbols, and the loop terminates when
  21220. all codes of length max, i.e. all codes, have been processed. This
  21221. routine permits incomplete codes, so another loop after this one fills
  21222. in the rest of the decoding tables with invalid code markers.
  21223. */
  21224. /* set up for code type */
  21225. // poor man optimization - use if-else instead of switch,
  21226. // to avoid deopts in old v8
  21227. if (type === CODES) {
  21228. base = extra = work; /* dummy value--not used */
  21229. end = 19;
  21230. } else if (type === LENS) {
  21231. base = lbase;
  21232. base_index -= 257;
  21233. extra = lext;
  21234. extra_index -= 257;
  21235. end = 256;
  21236. } else { /* DISTS */
  21237. base = dbase;
  21238. extra = dext;
  21239. end = -1;
  21240. }
  21241. /* initialize opts for loop */
  21242. huff = 0; /* starting code */
  21243. sym = 0; /* starting code symbol */
  21244. len = min; /* starting code length */
  21245. next = table_index; /* current table to fill in */
  21246. curr = root; /* current table index bits */
  21247. drop = 0; /* current bits to drop from code for index */
  21248. low = -1; /* trigger new sub-table when len > root */
  21249. used = 1 << root; /* use root table entries */
  21250. mask = used - 1; /* mask for comparing low */
  21251. /* check available table space */
  21252. if ((type === LENS && used > ENOUGH_LENS) ||
  21253. (type === DISTS && used > ENOUGH_DISTS)) {
  21254. return 1;
  21255. }
  21256. var i=0;
  21257. /* process all codes and make table entries */
  21258. for (;;) {
  21259. i++;
  21260. /* create table entry */
  21261. here_bits = len - drop;
  21262. if (work[sym] < end) {
  21263. here_op = 0;
  21264. here_val = work[sym];
  21265. }
  21266. else if (work[sym] > end) {
  21267. here_op = extra[extra_index + work[sym]];
  21268. here_val = base[base_index + work[sym]];
  21269. }
  21270. else {
  21271. here_op = 32 + 64; /* end of block */
  21272. here_val = 0;
  21273. }
  21274. /* replicate for those indices with low len bits equal to huff */
  21275. incr = 1 << (len - drop);
  21276. fill = 1 << curr;
  21277. min = fill; /* save offset to next table */
  21278. do {
  21279. fill -= incr;
  21280. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  21281. } while (fill !== 0);
  21282. /* backwards increment the len-bit code huff */
  21283. incr = 1 << (len - 1);
  21284. while (huff & incr) {
  21285. incr >>= 1;
  21286. }
  21287. if (incr !== 0) {
  21288. huff &= incr - 1;
  21289. huff += incr;
  21290. } else {
  21291. huff = 0;
  21292. }
  21293. /* go to next symbol, update count, len */
  21294. sym++;
  21295. if (--count[len] === 0) {
  21296. if (len === max) { break; }
  21297. len = lens[lens_index + work[sym]];
  21298. }
  21299. /* create new sub-table if needed */
  21300. if (len > root && (huff & mask) !== low) {
  21301. /* if first time, transition to sub-tables */
  21302. if (drop === 0) {
  21303. drop = root;
  21304. }
  21305. /* increment past last table */
  21306. next += min; /* here min is 1 << curr */
  21307. /* determine length of next table */
  21308. curr = len - drop;
  21309. left = 1 << curr;
  21310. while (curr + drop < max) {
  21311. left -= count[curr + drop];
  21312. if (left <= 0) { break; }
  21313. curr++;
  21314. left <<= 1;
  21315. }
  21316. /* check for enough space */
  21317. used += 1 << curr;
  21318. if ((type === LENS && used > ENOUGH_LENS) ||
  21319. (type === DISTS && used > ENOUGH_DISTS)) {
  21320. return 1;
  21321. }
  21322. /* point entry in root table to sub-table */
  21323. low = huff & mask;
  21324. /*table.op[low] = curr;
  21325. table.bits[low] = root;
  21326. table.val[low] = next - opts.table_index;*/
  21327. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  21328. }
  21329. }
  21330. /* fill in remaining table entry if code is incomplete (guaranteed to have
  21331. at most one remaining entry, since if the code is incomplete, the
  21332. maximum code length that was allowed to get this far is one bit) */
  21333. if (huff !== 0) {
  21334. //table.op[next + huff] = 64; /* invalid code marker */
  21335. //table.bits[next + huff] = len - drop;
  21336. //table.val[next + huff] = 0;
  21337. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  21338. }
  21339. /* set return parameters */
  21340. //opts.table_index += used;
  21341. opts.bits = root;
  21342. return 0;
  21343. };
  21344. },{"../utils/common":66}],76:[function(require,module,exports){
  21345. 'use strict';
  21346. module.exports = {
  21347. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  21348. '1': 'stream end', /* Z_STREAM_END 1 */
  21349. '0': '', /* Z_OK 0 */
  21350. '-1': 'file error', /* Z_ERRNO (-1) */
  21351. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  21352. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  21353. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  21354. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  21355. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  21356. };
  21357. },{}],77:[function(require,module,exports){
  21358. 'use strict';
  21359. var utils = require('../utils/common');
  21360. /* Public constants ==========================================================*/
  21361. /* ===========================================================================*/
  21362. //var Z_FILTERED = 1;
  21363. //var Z_HUFFMAN_ONLY = 2;
  21364. //var Z_RLE = 3;
  21365. var Z_FIXED = 4;
  21366. //var Z_DEFAULT_STRATEGY = 0;
  21367. /* Possible values of the data_type field (though see inflate()) */
  21368. var Z_BINARY = 0;
  21369. var Z_TEXT = 1;
  21370. //var Z_ASCII = 1; // = Z_TEXT
  21371. var Z_UNKNOWN = 2;
  21372. /*============================================================================*/
  21373. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  21374. // From zutil.h
  21375. var STORED_BLOCK = 0;
  21376. var STATIC_TREES = 1;
  21377. var DYN_TREES = 2;
  21378. /* The three kinds of block type */
  21379. var MIN_MATCH = 3;
  21380. var MAX_MATCH = 258;
  21381. /* The minimum and maximum match lengths */
  21382. // From deflate.h
  21383. /* ===========================================================================
  21384. * Internal compression state.
  21385. */
  21386. var LENGTH_CODES = 29;
  21387. /* number of length codes, not counting the special END_BLOCK code */
  21388. var LITERALS = 256;
  21389. /* number of literal bytes 0..255 */
  21390. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  21391. /* number of Literal or Length codes, including the END_BLOCK code */
  21392. var D_CODES = 30;
  21393. /* number of distance codes */
  21394. var BL_CODES = 19;
  21395. /* number of codes used to transfer the bit lengths */
  21396. var HEAP_SIZE = 2*L_CODES + 1;
  21397. /* maximum heap size */
  21398. var MAX_BITS = 15;
  21399. /* All codes must not exceed MAX_BITS bits */
  21400. var Buf_size = 16;
  21401. /* size of bit buffer in bi_buf */
  21402. /* ===========================================================================
  21403. * Constants
  21404. */
  21405. var MAX_BL_BITS = 7;
  21406. /* Bit length codes must not exceed MAX_BL_BITS bits */
  21407. var END_BLOCK = 256;
  21408. /* end of block literal code */
  21409. var REP_3_6 = 16;
  21410. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  21411. var REPZ_3_10 = 17;
  21412. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  21413. var REPZ_11_138 = 18;
  21414. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  21415. var extra_lbits = /* extra bits for each length code */
  21416. [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];
  21417. var extra_dbits = /* extra bits for each distance code */
  21418. [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];
  21419. var extra_blbits = /* extra bits for each bit length code */
  21420. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  21421. var bl_order =
  21422. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  21423. /* The lengths of the bit length codes are sent in order of decreasing
  21424. * probability, to avoid transmitting the lengths for unused bit length codes.
  21425. */
  21426. /* ===========================================================================
  21427. * Local data. These are initialized only once.
  21428. */
  21429. // We pre-fill arrays with 0 to avoid uninitialized gaps
  21430. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  21431. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  21432. var static_ltree = new Array((L_CODES+2) * 2);
  21433. zero(static_ltree);
  21434. /* The static literal tree. Since the bit lengths are imposed, there is no
  21435. * need for the L_CODES extra codes used during heap construction. However
  21436. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  21437. * below).
  21438. */
  21439. var static_dtree = new Array(D_CODES * 2);
  21440. zero(static_dtree);
  21441. /* The static distance tree. (Actually a trivial tree since all codes use
  21442. * 5 bits.)
  21443. */
  21444. var _dist_code = new Array(DIST_CODE_LEN);
  21445. zero(_dist_code);
  21446. /* Distance codes. The first 256 values correspond to the distances
  21447. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  21448. * the 15 bit distances.
  21449. */
  21450. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  21451. zero(_length_code);
  21452. /* length code for each normalized match length (0 == MIN_MATCH) */
  21453. var base_length = new Array(LENGTH_CODES);
  21454. zero(base_length);
  21455. /* First normalized length for each code (0 = MIN_MATCH) */
  21456. var base_dist = new Array(D_CODES);
  21457. zero(base_dist);
  21458. /* First normalized distance for each code (0 = distance of 1) */
  21459. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  21460. this.static_tree = static_tree; /* static tree or NULL */
  21461. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  21462. this.extra_base = extra_base; /* base index for extra_bits */
  21463. this.elems = elems; /* max number of elements in the tree */
  21464. this.max_length = max_length; /* max bit length for the codes */
  21465. // show if `static_tree` has data or dummy - needed for monomorphic objects
  21466. this.has_stree = static_tree && static_tree.length;
  21467. };
  21468. var static_l_desc;
  21469. var static_d_desc;
  21470. var static_bl_desc;
  21471. var TreeDesc = function(dyn_tree, stat_desc) {
  21472. this.dyn_tree = dyn_tree; /* the dynamic tree */
  21473. this.max_code = 0; /* largest code with non zero frequency */
  21474. this.stat_desc = stat_desc; /* the corresponding static tree */
  21475. };
  21476. function d_code(dist) {
  21477. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  21478. }
  21479. /* ===========================================================================
  21480. * Output a short LSB first on the stream.
  21481. * IN assertion: there is enough room in pendingBuf.
  21482. */
  21483. function put_short (s, w) {
  21484. // put_byte(s, (uch)((w) & 0xff));
  21485. // put_byte(s, (uch)((ush)(w) >> 8));
  21486. s.pending_buf[s.pending++] = (w) & 0xff;
  21487. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  21488. }
  21489. /* ===========================================================================
  21490. * Send a value on a given number of bits.
  21491. * IN assertion: length <= 16 and value fits in length bits.
  21492. */
  21493. function send_bits(s, value, length) {
  21494. if (s.bi_valid > (Buf_size - length)) {
  21495. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21496. put_short(s, s.bi_buf);
  21497. s.bi_buf = value >> (Buf_size - s.bi_valid);
  21498. s.bi_valid += length - Buf_size;
  21499. } else {
  21500. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21501. s.bi_valid += length;
  21502. }
  21503. }
  21504. function send_code(s, c, tree) {
  21505. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  21506. }
  21507. /* ===========================================================================
  21508. * Reverse the first len bits of a code, using straightforward code (a faster
  21509. * method would use a table)
  21510. * IN assertion: 1 <= len <= 15
  21511. */
  21512. function bi_reverse(code, len) {
  21513. var res = 0;
  21514. do {
  21515. res |= code & 1;
  21516. code >>>= 1;
  21517. res <<= 1;
  21518. } while (--len > 0);
  21519. return res >>> 1;
  21520. }
  21521. /* ===========================================================================
  21522. * Flush the bit buffer, keeping at most 7 bits in it.
  21523. */
  21524. function bi_flush(s) {
  21525. if (s.bi_valid === 16) {
  21526. put_short(s, s.bi_buf);
  21527. s.bi_buf = 0;
  21528. s.bi_valid = 0;
  21529. } else if (s.bi_valid >= 8) {
  21530. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  21531. s.bi_buf >>= 8;
  21532. s.bi_valid -= 8;
  21533. }
  21534. }
  21535. /* ===========================================================================
  21536. * Compute the optimal bit lengths for a tree and update the total bit length
  21537. * for the current block.
  21538. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  21539. * above are the tree nodes sorted by increasing frequency.
  21540. * OUT assertions: the field len is set to the optimal bit length, the
  21541. * array bl_count contains the frequencies for each bit length.
  21542. * The length opt_len is updated; static_len is also updated if stree is
  21543. * not null.
  21544. */
  21545. function gen_bitlen(s, desc)
  21546. // deflate_state *s;
  21547. // tree_desc *desc; /* the tree descriptor */
  21548. {
  21549. var tree = desc.dyn_tree;
  21550. var max_code = desc.max_code;
  21551. var stree = desc.stat_desc.static_tree;
  21552. var has_stree = desc.stat_desc.has_stree;
  21553. var extra = desc.stat_desc.extra_bits;
  21554. var base = desc.stat_desc.extra_base;
  21555. var max_length = desc.stat_desc.max_length;
  21556. var h; /* heap index */
  21557. var n, m; /* iterate over the tree elements */
  21558. var bits; /* bit length */
  21559. var xbits; /* extra bits */
  21560. var f; /* frequency */
  21561. var overflow = 0; /* number of elements with bit length too large */
  21562. for (bits = 0; bits <= MAX_BITS; bits++) {
  21563. s.bl_count[bits] = 0;
  21564. }
  21565. /* In a first pass, compute the optimal bit lengths (which may
  21566. * overflow in the case of the bit length tree).
  21567. */
  21568. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  21569. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  21570. n = s.heap[h];
  21571. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  21572. if (bits > max_length) {
  21573. bits = max_length;
  21574. overflow++;
  21575. }
  21576. tree[n*2 + 1]/*.Len*/ = bits;
  21577. /* We overwrite tree[n].Dad which is no longer needed */
  21578. if (n > max_code) { continue; } /* not a leaf node */
  21579. s.bl_count[bits]++;
  21580. xbits = 0;
  21581. if (n >= base) {
  21582. xbits = extra[n-base];
  21583. }
  21584. f = tree[n * 2]/*.Freq*/;
  21585. s.opt_len += f * (bits + xbits);
  21586. if (has_stree) {
  21587. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  21588. }
  21589. }
  21590. if (overflow === 0) { return; }
  21591. // Trace((stderr,"\nbit length overflow\n"));
  21592. /* This happens for example on obj2 and pic of the Calgary corpus */
  21593. /* Find the first bit length which could increase: */
  21594. do {
  21595. bits = max_length-1;
  21596. while (s.bl_count[bits] === 0) { bits--; }
  21597. s.bl_count[bits]--; /* move one leaf down the tree */
  21598. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  21599. s.bl_count[max_length]--;
  21600. /* The brother of the overflow item also moves one step up,
  21601. * but this does not affect bl_count[max_length]
  21602. */
  21603. overflow -= 2;
  21604. } while (overflow > 0);
  21605. /* Now recompute all bit lengths, scanning in increasing frequency.
  21606. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  21607. * lengths instead of fixing only the wrong ones. This idea is taken
  21608. * from 'ar' written by Haruhiko Okumura.)
  21609. */
  21610. for (bits = max_length; bits !== 0; bits--) {
  21611. n = s.bl_count[bits];
  21612. while (n !== 0) {
  21613. m = s.heap[--h];
  21614. if (m > max_code) { continue; }
  21615. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  21616. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  21617. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  21618. tree[m*2 + 1]/*.Len*/ = bits;
  21619. }
  21620. n--;
  21621. }
  21622. }
  21623. }
  21624. /* ===========================================================================
  21625. * Generate the codes for a given tree and bit counts (which need not be
  21626. * optimal).
  21627. * IN assertion: the array bl_count contains the bit length statistics for
  21628. * the given tree and the field len is set for all tree elements.
  21629. * OUT assertion: the field code is set for all tree elements of non
  21630. * zero code length.
  21631. */
  21632. function gen_codes(tree, max_code, bl_count)
  21633. // ct_data *tree; /* the tree to decorate */
  21634. // int max_code; /* largest code with non zero frequency */
  21635. // ushf *bl_count; /* number of codes at each bit length */
  21636. {
  21637. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  21638. var code = 0; /* running code value */
  21639. var bits; /* bit index */
  21640. var n; /* code index */
  21641. /* The distribution counts are first used to generate the code values
  21642. * without bit reversal.
  21643. */
  21644. for (bits = 1; bits <= MAX_BITS; bits++) {
  21645. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  21646. }
  21647. /* Check that the bit counts in bl_count are consistent. The last code
  21648. * must be all ones.
  21649. */
  21650. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  21651. // "inconsistent bit counts");
  21652. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  21653. for (n = 0; n <= max_code; n++) {
  21654. var len = tree[n*2 + 1]/*.Len*/;
  21655. if (len === 0) { continue; }
  21656. /* Now reverse the bits */
  21657. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  21658. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  21659. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  21660. }
  21661. }
  21662. /* ===========================================================================
  21663. * Initialize the various 'constant' tables.
  21664. */
  21665. function tr_static_init() {
  21666. var n; /* iterates over tree elements */
  21667. var bits; /* bit counter */
  21668. var length; /* length value */
  21669. var code; /* code value */
  21670. var dist; /* distance index */
  21671. var bl_count = new Array(MAX_BITS+1);
  21672. /* number of codes at each bit length for an optimal tree */
  21673. // do check in _tr_init()
  21674. //if (static_init_done) return;
  21675. /* For some embedded targets, global variables are not initialized: */
  21676. /*#ifdef NO_INIT_GLOBAL_POINTERS
  21677. static_l_desc.static_tree = static_ltree;
  21678. static_l_desc.extra_bits = extra_lbits;
  21679. static_d_desc.static_tree = static_dtree;
  21680. static_d_desc.extra_bits = extra_dbits;
  21681. static_bl_desc.extra_bits = extra_blbits;
  21682. #endif*/
  21683. /* Initialize the mapping length (0..255) -> length code (0..28) */
  21684. length = 0;
  21685. for (code = 0; code < LENGTH_CODES-1; code++) {
  21686. base_length[code] = length;
  21687. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  21688. _length_code[length++] = code;
  21689. }
  21690. }
  21691. //Assert (length == 256, "tr_static_init: length != 256");
  21692. /* Note that the length 255 (match length 258) can be represented
  21693. * in two different ways: code 284 + 5 bits or code 285, so we
  21694. * overwrite length_code[255] to use the best encoding:
  21695. */
  21696. _length_code[length-1] = code;
  21697. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  21698. dist = 0;
  21699. for (code = 0 ; code < 16; code++) {
  21700. base_dist[code] = dist;
  21701. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  21702. _dist_code[dist++] = code;
  21703. }
  21704. }
  21705. //Assert (dist == 256, "tr_static_init: dist != 256");
  21706. dist >>= 7; /* from now on, all distances are divided by 128 */
  21707. for ( ; code < D_CODES; code++) {
  21708. base_dist[code] = dist << 7;
  21709. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  21710. _dist_code[256 + dist++] = code;
  21711. }
  21712. }
  21713. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  21714. /* Construct the codes of the static literal tree */
  21715. for (bits = 0; bits <= MAX_BITS; bits++) {
  21716. bl_count[bits] = 0;
  21717. }
  21718. n = 0;
  21719. while (n <= 143) {
  21720. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21721. n++;
  21722. bl_count[8]++;
  21723. }
  21724. while (n <= 255) {
  21725. static_ltree[n*2 + 1]/*.Len*/ = 9;
  21726. n++;
  21727. bl_count[9]++;
  21728. }
  21729. while (n <= 279) {
  21730. static_ltree[n*2 + 1]/*.Len*/ = 7;
  21731. n++;
  21732. bl_count[7]++;
  21733. }
  21734. while (n <= 287) {
  21735. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21736. n++;
  21737. bl_count[8]++;
  21738. }
  21739. /* Codes 286 and 287 do not exist, but we must include them in the
  21740. * tree construction to get a canonical Huffman tree (longest code
  21741. * all ones)
  21742. */
  21743. gen_codes(static_ltree, L_CODES+1, bl_count);
  21744. /* The static distance tree is trivial: */
  21745. for (n = 0; n < D_CODES; n++) {
  21746. static_dtree[n*2 + 1]/*.Len*/ = 5;
  21747. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  21748. }
  21749. // Now data ready and we can init static trees
  21750. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  21751. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  21752. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  21753. //static_init_done = true;
  21754. }
  21755. /* ===========================================================================
  21756. * Initialize a new block.
  21757. */
  21758. function init_block(s) {
  21759. var n; /* iterates over tree elements */
  21760. /* Initialize the trees. */
  21761. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  21762. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  21763. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  21764. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  21765. s.opt_len = s.static_len = 0;
  21766. s.last_lit = s.matches = 0;
  21767. }
  21768. /* ===========================================================================
  21769. * Flush the bit buffer and align the output on a byte boundary
  21770. */
  21771. function bi_windup(s)
  21772. {
  21773. if (s.bi_valid > 8) {
  21774. put_short(s, s.bi_buf);
  21775. } else if (s.bi_valid > 0) {
  21776. //put_byte(s, (Byte)s->bi_buf);
  21777. s.pending_buf[s.pending++] = s.bi_buf;
  21778. }
  21779. s.bi_buf = 0;
  21780. s.bi_valid = 0;
  21781. }
  21782. /* ===========================================================================
  21783. * Copy a stored block, storing first the length and its
  21784. * one's complement if requested.
  21785. */
  21786. function copy_block(s, buf, len, header)
  21787. //DeflateState *s;
  21788. //charf *buf; /* the input data */
  21789. //unsigned len; /* its length */
  21790. //int header; /* true if block header must be written */
  21791. {
  21792. bi_windup(s); /* align on byte boundary */
  21793. if (header) {
  21794. put_short(s, len);
  21795. put_short(s, ~len);
  21796. }
  21797. // while (len--) {
  21798. // put_byte(s, *buf++);
  21799. // }
  21800. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  21801. s.pending += len;
  21802. }
  21803. /* ===========================================================================
  21804. * Compares to subtrees, using the tree depth as tie breaker when
  21805. * the subtrees have equal frequency. This minimizes the worst case length.
  21806. */
  21807. function smaller(tree, n, m, depth) {
  21808. var _n2 = n*2;
  21809. var _m2 = m*2;
  21810. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  21811. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  21812. }
  21813. /* ===========================================================================
  21814. * Restore the heap property by moving down the tree starting at node k,
  21815. * exchanging a node with the smallest of its two sons if necessary, stopping
  21816. * when the heap property is re-established (each father smaller than its
  21817. * two sons).
  21818. */
  21819. function pqdownheap(s, tree, k)
  21820. // deflate_state *s;
  21821. // ct_data *tree; /* the tree to restore */
  21822. // int k; /* node to move down */
  21823. {
  21824. var v = s.heap[k];
  21825. var j = k << 1; /* left son of k */
  21826. while (j <= s.heap_len) {
  21827. /* Set j to the smallest of the two sons: */
  21828. if (j < s.heap_len &&
  21829. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  21830. j++;
  21831. }
  21832. /* Exit if v is smaller than both sons */
  21833. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  21834. /* Exchange v with the smallest son */
  21835. s.heap[k] = s.heap[j];
  21836. k = j;
  21837. /* And continue down the tree, setting j to the left son of k */
  21838. j <<= 1;
  21839. }
  21840. s.heap[k] = v;
  21841. }
  21842. // inlined manually
  21843. // var SMALLEST = 1;
  21844. /* ===========================================================================
  21845. * Send the block data compressed using the given Huffman trees
  21846. */
  21847. function compress_block(s, ltree, dtree)
  21848. // deflate_state *s;
  21849. // const ct_data *ltree; /* literal tree */
  21850. // const ct_data *dtree; /* distance tree */
  21851. {
  21852. var dist; /* distance of matched string */
  21853. var lc; /* match length or unmatched char (if dist == 0) */
  21854. var lx = 0; /* running index in l_buf */
  21855. var code; /* the code to send */
  21856. var extra; /* number of extra bits to send */
  21857. if (s.last_lit !== 0) {
  21858. do {
  21859. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  21860. lc = s.pending_buf[s.l_buf + lx];
  21861. lx++;
  21862. if (dist === 0) {
  21863. send_code(s, lc, ltree); /* send a literal byte */
  21864. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  21865. } else {
  21866. /* Here, lc is the match length - MIN_MATCH */
  21867. code = _length_code[lc];
  21868. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  21869. extra = extra_lbits[code];
  21870. if (extra !== 0) {
  21871. lc -= base_length[code];
  21872. send_bits(s, lc, extra); /* send the extra length bits */
  21873. }
  21874. dist--; /* dist is now the match distance - 1 */
  21875. code = d_code(dist);
  21876. //Assert (code < D_CODES, "bad d_code");
  21877. send_code(s, code, dtree); /* send the distance code */
  21878. extra = extra_dbits[code];
  21879. if (extra !== 0) {
  21880. dist -= base_dist[code];
  21881. send_bits(s, dist, extra); /* send the extra distance bits */
  21882. }
  21883. } /* literal or match pair ? */
  21884. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  21885. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  21886. // "pendingBuf overflow");
  21887. } while (lx < s.last_lit);
  21888. }
  21889. send_code(s, END_BLOCK, ltree);
  21890. }
  21891. /* ===========================================================================
  21892. * Construct one Huffman tree and assigns the code bit strings and lengths.
  21893. * Update the total bit length for the current block.
  21894. * IN assertion: the field freq is set for all tree elements.
  21895. * OUT assertions: the fields len and code are set to the optimal bit length
  21896. * and corresponding code. The length opt_len is updated; static_len is
  21897. * also updated if stree is not null. The field max_code is set.
  21898. */
  21899. function build_tree(s, desc)
  21900. // deflate_state *s;
  21901. // tree_desc *desc; /* the tree descriptor */
  21902. {
  21903. var tree = desc.dyn_tree;
  21904. var stree = desc.stat_desc.static_tree;
  21905. var has_stree = desc.stat_desc.has_stree;
  21906. var elems = desc.stat_desc.elems;
  21907. var n, m; /* iterate over heap elements */
  21908. var max_code = -1; /* largest code with non zero frequency */
  21909. var node; /* new node being created */
  21910. /* Construct the initial heap, with least frequent element in
  21911. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  21912. * heap[0] is not used.
  21913. */
  21914. s.heap_len = 0;
  21915. s.heap_max = HEAP_SIZE;
  21916. for (n = 0; n < elems; n++) {
  21917. if (tree[n * 2]/*.Freq*/ !== 0) {
  21918. s.heap[++s.heap_len] = max_code = n;
  21919. s.depth[n] = 0;
  21920. } else {
  21921. tree[n*2 + 1]/*.Len*/ = 0;
  21922. }
  21923. }
  21924. /* The pkzip format requires that at least one distance code exists,
  21925. * and that at least one bit should be sent even if there is only one
  21926. * possible code. So to avoid special checks later on we force at least
  21927. * two codes of non zero frequency.
  21928. */
  21929. while (s.heap_len < 2) {
  21930. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  21931. tree[node * 2]/*.Freq*/ = 1;
  21932. s.depth[node] = 0;
  21933. s.opt_len--;
  21934. if (has_stree) {
  21935. s.static_len -= stree[node*2 + 1]/*.Len*/;
  21936. }
  21937. /* node is 0 or 1 so it does not have extra bits */
  21938. }
  21939. desc.max_code = max_code;
  21940. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  21941. * establish sub-heaps of increasing lengths:
  21942. */
  21943. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  21944. /* Construct the Huffman tree by repeatedly combining the least two
  21945. * frequent nodes.
  21946. */
  21947. node = elems; /* next internal node of the tree */
  21948. do {
  21949. //pqremove(s, tree, n); /* n = node of least frequency */
  21950. /*** pqremove ***/
  21951. n = s.heap[1/*SMALLEST*/];
  21952. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  21953. pqdownheap(s, tree, 1/*SMALLEST*/);
  21954. /***/
  21955. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  21956. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  21957. s.heap[--s.heap_max] = m;
  21958. /* Create a new node father of n and m */
  21959. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  21960. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  21961. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  21962. /* and insert the new node in the heap */
  21963. s.heap[1/*SMALLEST*/] = node++;
  21964. pqdownheap(s, tree, 1/*SMALLEST*/);
  21965. } while (s.heap_len >= 2);
  21966. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  21967. /* At this point, the fields freq and dad are set. We can now
  21968. * generate the bit lengths.
  21969. */
  21970. gen_bitlen(s, desc);
  21971. /* The field len is now set, we can generate the bit codes */
  21972. gen_codes(tree, max_code, s.bl_count);
  21973. }
  21974. /* ===========================================================================
  21975. * Scan a literal or distance tree to determine the frequencies of the codes
  21976. * in the bit length tree.
  21977. */
  21978. function scan_tree(s, tree, max_code)
  21979. // deflate_state *s;
  21980. // ct_data *tree; /* the tree to be scanned */
  21981. // int max_code; /* and its largest code of non zero frequency */
  21982. {
  21983. var n; /* iterates over all tree elements */
  21984. var prevlen = -1; /* last emitted length */
  21985. var curlen; /* length of current code */
  21986. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  21987. var count = 0; /* repeat count of the current code */
  21988. var max_count = 7; /* max repeat count */
  21989. var min_count = 4; /* min repeat count */
  21990. if (nextlen === 0) {
  21991. max_count = 138;
  21992. min_count = 3;
  21993. }
  21994. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  21995. for (n = 0; n <= max_code; n++) {
  21996. curlen = nextlen;
  21997. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  21998. if (++count < max_count && curlen === nextlen) {
  21999. continue;
  22000. } else if (count < min_count) {
  22001. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  22002. } else if (curlen !== 0) {
  22003. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  22004. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  22005. } else if (count <= 10) {
  22006. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  22007. } else {
  22008. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  22009. }
  22010. count = 0;
  22011. prevlen = curlen;
  22012. if (nextlen === 0) {
  22013. max_count = 138;
  22014. min_count = 3;
  22015. } else if (curlen === nextlen) {
  22016. max_count = 6;
  22017. min_count = 3;
  22018. } else {
  22019. max_count = 7;
  22020. min_count = 4;
  22021. }
  22022. }
  22023. }
  22024. /* ===========================================================================
  22025. * Send a literal or distance tree in compressed form, using the codes in
  22026. * bl_tree.
  22027. */
  22028. function send_tree(s, tree, max_code)
  22029. // deflate_state *s;
  22030. // ct_data *tree; /* the tree to be scanned */
  22031. // int max_code; /* and its largest code of non zero frequency */
  22032. {
  22033. var n; /* iterates over all tree elements */
  22034. var prevlen = -1; /* last emitted length */
  22035. var curlen; /* length of current code */
  22036. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  22037. var count = 0; /* repeat count of the current code */
  22038. var max_count = 7; /* max repeat count */
  22039. var min_count = 4; /* min repeat count */
  22040. /* tree[max_code+1].Len = -1; */ /* guard already set */
  22041. if (nextlen === 0) {
  22042. max_count = 138;
  22043. min_count = 3;
  22044. }
  22045. for (n = 0; n <= max_code; n++) {
  22046. curlen = nextlen;
  22047. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  22048. if (++count < max_count && curlen === nextlen) {
  22049. continue;
  22050. } else if (count < min_count) {
  22051. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  22052. } else if (curlen !== 0) {
  22053. if (curlen !== prevlen) {
  22054. send_code(s, curlen, s.bl_tree);
  22055. count--;
  22056. }
  22057. //Assert(count >= 3 && count <= 6, " 3_6?");
  22058. send_code(s, REP_3_6, s.bl_tree);
  22059. send_bits(s, count-3, 2);
  22060. } else if (count <= 10) {
  22061. send_code(s, REPZ_3_10, s.bl_tree);
  22062. send_bits(s, count-3, 3);
  22063. } else {
  22064. send_code(s, REPZ_11_138, s.bl_tree);
  22065. send_bits(s, count-11, 7);
  22066. }
  22067. count = 0;
  22068. prevlen = curlen;
  22069. if (nextlen === 0) {
  22070. max_count = 138;
  22071. min_count = 3;
  22072. } else if (curlen === nextlen) {
  22073. max_count = 6;
  22074. min_count = 3;
  22075. } else {
  22076. max_count = 7;
  22077. min_count = 4;
  22078. }
  22079. }
  22080. }
  22081. /* ===========================================================================
  22082. * Construct the Huffman tree for the bit lengths and return the index in
  22083. * bl_order of the last bit length code to send.
  22084. */
  22085. function build_bl_tree(s) {
  22086. var max_blindex; /* index of last bit length code of non zero freq */
  22087. /* Determine the bit length frequencies for literal and distance trees */
  22088. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  22089. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  22090. /* Build the bit length tree: */
  22091. build_tree(s, s.bl_desc);
  22092. /* opt_len now includes the length of the tree representations, except
  22093. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  22094. */
  22095. /* Determine the number of bit length codes to send. The pkzip format
  22096. * requires that at least 4 bit length codes be sent. (appnote.txt says
  22097. * 3 but the actual value used is 4.)
  22098. */
  22099. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  22100. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  22101. break;
  22102. }
  22103. }
  22104. /* Update opt_len to include the bit length tree and counts */
  22105. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  22106. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  22107. // s->opt_len, s->static_len));
  22108. return max_blindex;
  22109. }
  22110. /* ===========================================================================
  22111. * Send the header for a block using dynamic Huffman trees: the counts, the
  22112. * lengths of the bit length codes, the literal tree and the distance tree.
  22113. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  22114. */
  22115. function send_all_trees(s, lcodes, dcodes, blcodes)
  22116. // deflate_state *s;
  22117. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  22118. {
  22119. var rank; /* index in bl_order */
  22120. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  22121. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  22122. // "too many codes");
  22123. //Tracev((stderr, "\nbl counts: "));
  22124. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  22125. send_bits(s, dcodes-1, 5);
  22126. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  22127. for (rank = 0; rank < blcodes; rank++) {
  22128. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  22129. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  22130. }
  22131. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  22132. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  22133. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  22134. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  22135. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  22136. }
  22137. /* ===========================================================================
  22138. * Check if the data type is TEXT or BINARY, using the following algorithm:
  22139. * - TEXT if the two conditions below are satisfied:
  22140. * a) There are no non-portable control characters belonging to the
  22141. * "black list" (0..6, 14..25, 28..31).
  22142. * b) There is at least one printable character belonging to the
  22143. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  22144. * - BINARY otherwise.
  22145. * - The following partially-portable control characters form a
  22146. * "gray list" that is ignored in this detection algorithm:
  22147. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  22148. * IN assertion: the fields Freq of dyn_ltree are set.
  22149. */
  22150. function detect_data_type(s) {
  22151. /* black_mask is the bit mask of black-listed bytes
  22152. * set bits 0..6, 14..25, and 28..31
  22153. * 0xf3ffc07f = binary 11110011111111111100000001111111
  22154. */
  22155. var black_mask = 0xf3ffc07f;
  22156. var n;
  22157. /* Check for non-textual ("black-listed") bytes. */
  22158. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  22159. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  22160. return Z_BINARY;
  22161. }
  22162. }
  22163. /* Check for textual ("white-listed") bytes. */
  22164. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  22165. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  22166. return Z_TEXT;
  22167. }
  22168. for (n = 32; n < LITERALS; n++) {
  22169. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  22170. return Z_TEXT;
  22171. }
  22172. }
  22173. /* There are no "black-listed" or "white-listed" bytes:
  22174. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  22175. */
  22176. return Z_BINARY;
  22177. }
  22178. var static_init_done = false;
  22179. /* ===========================================================================
  22180. * Initialize the tree data structures for a new zlib stream.
  22181. */
  22182. function _tr_init(s)
  22183. {
  22184. if (!static_init_done) {
  22185. tr_static_init();
  22186. static_init_done = true;
  22187. }
  22188. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  22189. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  22190. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  22191. s.bi_buf = 0;
  22192. s.bi_valid = 0;
  22193. /* Initialize the first block of the first file: */
  22194. init_block(s);
  22195. }
  22196. /* ===========================================================================
  22197. * Send a stored block
  22198. */
  22199. function _tr_stored_block(s, buf, stored_len, last)
  22200. //DeflateState *s;
  22201. //charf *buf; /* input block */
  22202. //ulg stored_len; /* length of input block */
  22203. //int last; /* one if this is the last block for a file */
  22204. {
  22205. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  22206. copy_block(s, buf, stored_len, true); /* with header */
  22207. }
  22208. /* ===========================================================================
  22209. * Send one empty static block to give enough lookahead for inflate.
  22210. * This takes 10 bits, of which 7 may remain in the bit buffer.
  22211. */
  22212. function _tr_align(s) {
  22213. send_bits(s, STATIC_TREES<<1, 3);
  22214. send_code(s, END_BLOCK, static_ltree);
  22215. bi_flush(s);
  22216. }
  22217. /* ===========================================================================
  22218. * Determine the best encoding for the current block: dynamic trees, static
  22219. * trees or store, and output the encoded block to the zip file.
  22220. */
  22221. function _tr_flush_block(s, buf, stored_len, last)
  22222. //DeflateState *s;
  22223. //charf *buf; /* input block, or NULL if too old */
  22224. //ulg stored_len; /* length of input block */
  22225. //int last; /* one if this is the last block for a file */
  22226. {
  22227. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  22228. var max_blindex = 0; /* index of last bit length code of non zero freq */
  22229. /* Build the Huffman trees unless a stored block is forced */
  22230. if (s.level > 0) {
  22231. /* Check if the file is binary or text */
  22232. if (s.strm.data_type === Z_UNKNOWN) {
  22233. s.strm.data_type = detect_data_type(s);
  22234. }
  22235. /* Construct the literal and distance trees */
  22236. build_tree(s, s.l_desc);
  22237. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  22238. // s->static_len));
  22239. build_tree(s, s.d_desc);
  22240. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  22241. // s->static_len));
  22242. /* At this point, opt_len and static_len are the total bit lengths of
  22243. * the compressed block data, excluding the tree representations.
  22244. */
  22245. /* Build the bit length tree for the above two trees, and get the index
  22246. * in bl_order of the last bit length code to send.
  22247. */
  22248. max_blindex = build_bl_tree(s);
  22249. /* Determine the best encoding. Compute the block lengths in bytes. */
  22250. opt_lenb = (s.opt_len+3+7) >>> 3;
  22251. static_lenb = (s.static_len+3+7) >>> 3;
  22252. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  22253. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  22254. // s->last_lit));
  22255. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  22256. } else {
  22257. // Assert(buf != (char*)0, "lost buf");
  22258. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  22259. }
  22260. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  22261. /* 4: two words for the lengths */
  22262. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  22263. * Otherwise we can't have processed more than WSIZE input bytes since
  22264. * the last block flush, because compression would have been
  22265. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  22266. * transform a block into a stored block.
  22267. */
  22268. _tr_stored_block(s, buf, stored_len, last);
  22269. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  22270. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  22271. compress_block(s, static_ltree, static_dtree);
  22272. } else {
  22273. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  22274. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  22275. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  22276. }
  22277. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  22278. /* The above check is made mod 2^32, for files larger than 512 MB
  22279. * and uLong implemented on 32 bits.
  22280. */
  22281. init_block(s);
  22282. if (last) {
  22283. bi_windup(s);
  22284. }
  22285. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  22286. // s->compressed_len-7*last));
  22287. }
  22288. /* ===========================================================================
  22289. * Save the match info and tally the frequency counts. Return true if
  22290. * the current block must be flushed.
  22291. */
  22292. function _tr_tally(s, dist, lc)
  22293. // deflate_state *s;
  22294. // unsigned dist; /* distance of matched string */
  22295. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  22296. {
  22297. //var out_length, in_length, dcode;
  22298. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  22299. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  22300. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  22301. s.last_lit++;
  22302. if (dist === 0) {
  22303. /* lc is the unmatched char */
  22304. s.dyn_ltree[lc*2]/*.Freq*/++;
  22305. } else {
  22306. s.matches++;
  22307. /* Here, lc is the match length - MIN_MATCH */
  22308. dist--; /* dist = match distance - 1 */
  22309. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  22310. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  22311. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  22312. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  22313. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  22314. }
  22315. // (!) This block is disabled in zlib defailts,
  22316. // don't enable it for binary compatibility
  22317. //#ifdef TRUNCATE_BLOCK
  22318. // /* Try to guess if it is profitable to stop the current block here */
  22319. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  22320. // /* Compute an upper bound for the compressed length */
  22321. // out_length = s.last_lit*8;
  22322. // in_length = s.strstart - s.block_start;
  22323. //
  22324. // for (dcode = 0; dcode < D_CODES; dcode++) {
  22325. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  22326. // }
  22327. // out_length >>>= 3;
  22328. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  22329. // // s->last_lit, in_length, out_length,
  22330. // // 100L - out_length*100L/in_length));
  22331. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  22332. // return true;
  22333. // }
  22334. // }
  22335. //#endif
  22336. return (s.last_lit === s.lit_bufsize-1);
  22337. /* We avoid equality with lit_bufsize because of wraparound at 64K
  22338. * on 16 bit machines and because stored blocks are restricted to
  22339. * 64K-1 bytes.
  22340. */
  22341. }
  22342. exports._tr_init = _tr_init;
  22343. exports._tr_stored_block = _tr_stored_block;
  22344. exports._tr_flush_block = _tr_flush_block;
  22345. exports._tr_tally = _tr_tally;
  22346. exports._tr_align = _tr_align;
  22347. },{"../utils/common":66}],78:[function(require,module,exports){
  22348. 'use strict';
  22349. function ZStream() {
  22350. /* next input byte */
  22351. this.input = null; // JS specific, because we have no pointers
  22352. this.next_in = 0;
  22353. /* number of bytes available at input */
  22354. this.avail_in = 0;
  22355. /* total number of input bytes read so far */
  22356. this.total_in = 0;
  22357. /* next output byte should be put there */
  22358. this.output = null; // JS specific, because we have no pointers
  22359. this.next_out = 0;
  22360. /* remaining free space at output */
  22361. this.avail_out = 0;
  22362. /* total number of bytes output so far */
  22363. this.total_out = 0;
  22364. /* last error message, NULL if no error */
  22365. this.msg = ''/*Z_NULL*/;
  22366. /* not visible by applications */
  22367. this.state = null;
  22368. /* best guess about the data type: binary or text */
  22369. this.data_type = 2/*Z_UNKNOWN*/;
  22370. /* adler32 value of the uncompressed data */
  22371. this.adler = 0;
  22372. }
  22373. module.exports = ZStream;
  22374. },{}],79:[function(require,module,exports){
  22375. var MediaStreamType = {
  22376. VIDEO_TYPE: "Video",
  22377. AUDIO_TYPE: "Audio"
  22378. };
  22379. module.exports = MediaStreamType;
  22380. },{}],80:[function(require,module,exports){
  22381. var RTCBrowserType = {
  22382. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  22383. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  22384. };
  22385. module.exports = RTCBrowserType;
  22386. },{}],81:[function(require,module,exports){
  22387. var RTCEvents = {
  22388. LASTN_CHANGED: "rtc.lastn_changed",
  22389. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  22390. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  22391. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  22392. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  22393. SIMULCAST_START: "rtc.simlcast_start",
  22394. SIMULCAST_STOP: "rtc.simlcast_stop"
  22395. };
  22396. module.exports = RTCEvents;
  22397. },{}],82:[function(require,module,exports){
  22398. var Resolutions = {
  22399. "1080": {
  22400. width: 1920,
  22401. height: 1080,
  22402. order: 7
  22403. },
  22404. "fullhd": {
  22405. width: 1920,
  22406. height: 1080,
  22407. order: 7
  22408. },
  22409. "720": {
  22410. width: 1280,
  22411. height: 720,
  22412. order: 6
  22413. },
  22414. "hd": {
  22415. width: 1280,
  22416. height: 720,
  22417. order: 6
  22418. },
  22419. "960": {
  22420. width: 960,
  22421. height: 720,
  22422. order: 5
  22423. },
  22424. "640": {
  22425. width: 640,
  22426. height: 480,
  22427. order: 4
  22428. },
  22429. "vga": {
  22430. width: 640,
  22431. height: 480,
  22432. order: 4
  22433. },
  22434. "360": {
  22435. width: 640,
  22436. height: 360,
  22437. order: 3
  22438. },
  22439. "320": {
  22440. width: 320,
  22441. height: 240,
  22442. order: 2
  22443. },
  22444. "180": {
  22445. width: 320,
  22446. height: 180,
  22447. order: 1
  22448. }
  22449. };
  22450. module.exports = Resolutions;
  22451. },{}],83:[function(require,module,exports){
  22452. var StreamEventTypes = {
  22453. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  22454. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  22455. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  22456. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  22457. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  22458. };
  22459. module.exports = StreamEventTypes;
  22460. },{}],84:[function(require,module,exports){
  22461. var UIEvents = {
  22462. NICKNAME_CHANGED: "UI.nickname_changed",
  22463. SELECTED_ENDPOINT: "UI.selected_endpoint",
  22464. PINNED_ENDPOINT: "UI.pinned_endpoint"
  22465. };
  22466. module.exports = UIEvents;
  22467. },{}],85:[function(require,module,exports){
  22468. var AuthenticationEvents = {
  22469. /**
  22470. * Event callback arguments:
  22471. * function(authenticationEnabled, userIdentity)
  22472. * authenticationEnabled - indicates whether authentication has been enabled
  22473. * in this session
  22474. * userIdentity - if user has been logged in then it contains user name. If
  22475. * contains 'null' or 'undefined' then user is not logged in.
  22476. */
  22477. IDENTITY_UPDATED: "authentication.identity_updated"
  22478. };
  22479. module.exports = AuthenticationEvents;
  22480. },{}],86:[function(require,module,exports){
  22481. var CQEvents = {
  22482. LOCALSTATS_UPDATED: "cq.localstats_updated",
  22483. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  22484. STOP: "cq.stop"
  22485. };
  22486. module.exports = CQEvents;
  22487. },{}],87:[function(require,module,exports){
  22488. var DesktopSharingEventTypes = {
  22489. INIT: "ds.init",
  22490. SWITCHING_DONE: "ds.switching_done",
  22491. NEW_STREAM_CREATED: "ds.new_stream_created"
  22492. };
  22493. module.exports = DesktopSharingEventTypes;
  22494. },{}],88:[function(require,module,exports){
  22495. module.exports = {
  22496. getLanguages : function () {
  22497. var languages = [];
  22498. for(var lang in this)
  22499. {
  22500. if(typeof this[lang] === "string")
  22501. languages.push(this[lang]);
  22502. }
  22503. return languages;
  22504. },
  22505. EN: "en"
  22506. }
  22507. },{}],89:[function(require,module,exports){
  22508. var XMPPEvents = {
  22509. CONFERENCE_CERATED: "xmpp.conferenceCreated.jingle",
  22510. CALL_TERMINATED: "xmpp.callterminated.jingle",
  22511. CALL_INCOMING: "xmpp.callincoming.jingle",
  22512. DISPOSE_CONFERENCE: "xmpp.dispoce_confernce",
  22513. KICKED: "xmpp.kicked",
  22514. BRIDGE_DOWN: "xmpp.bridge_down",
  22515. USER_ID_CHANGED: "xmpp.user_id_changed",
  22516. CHANGED_STREAMS: "xmpp.changed_streams",
  22517. MUC_JOINED: "xmpp.muc_joined",
  22518. MUC_ENTER: "xmpp.muc_enter",
  22519. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  22520. MUC_LEFT: "xmpp.muc_left",
  22521. MUC_DESTROYED: "xmpp.muc_destroyed",
  22522. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  22523. REMOTE_STATS: "xmpp.remote_stats",
  22524. LOCALROLE_CHANGED: "xmpp.localrole_changed",
  22525. PRESENCE_STATUS: "xmpp.presence_status",
  22526. SUBJECT_CHANGED: "xmpp.subject_changed",
  22527. MESSAGE_RECEIVED: "xmpp.message_received",
  22528. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  22529. PASSWORD_REQUIRED: "xmpp.password_required",
  22530. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  22531. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  22532. ETHERPAD: "xmpp.etherpad"
  22533. };
  22534. module.exports = XMPPEvents;
  22535. },{}]},{},[2])(2)
  22536. });