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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754
  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. /* jshint -W117 */
  3. /* application specific logic */
  4. var APP =
  5. {
  6. init: function () {
  7. this.UI = require("./modules/UI/UI");
  8. this.API = require("./modules/API/API");
  9. this.connectionquality = require("./modules/connectionquality/connectionquality");
  10. this.statistics = require("./modules/statistics/statistics");
  11. this.RTC = require("./modules/RTC/RTC");
  12. this.simulcast = require("./modules/simulcast/simulcast");
  13. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  14. this.xmpp = require("./modules/xmpp/xmpp");
  15. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  16. this.translation = require("./modules/translation/translation");
  17. }
  18. };
  19. function init() {
  20. APP.RTC.start();
  21. APP.xmpp.start(APP.UI.getCredentials());
  22. APP.statistics.start();
  23. APP.connectionquality.init();
  24. // Set default desktop sharing method
  25. APP.desktopsharing.init();
  26. APP.keyboardshortcut.init();
  27. }
  28. $(document).ready(function () {
  29. APP.init();
  30. APP.translation.init();
  31. if(APP.API.isEnabled())
  32. APP.API.init();
  33. APP.UI.start(init);
  34. });
  35. $(window).bind('beforeunload', function () {
  36. if(APP.API.isEnabled())
  37. APP.API.dispose();
  38. });
  39. module.exports = APP;
  40. },{"./modules/API/API":2,"./modules/RTC/RTC":6,"./modules/UI/UI":8,"./modules/connectionquality/connectionquality":34,"./modules/desktopsharing/desktopsharing":35,"./modules/keyboardshortcut/keyboardshortcut":36,"./modules/simulcast/simulcast":42,"./modules/statistics/statistics":45,"./modules/translation/translation":46,"./modules/xmpp/xmpp":60}],2:[function(require,module,exports){
  41. /**
  42. * Implements API class that communicates with external api class
  43. * and provides interface to access Jitsi Meet features by external
  44. * applications that embed Jitsi Meet
  45. */
  46. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  47. /**
  48. * List of the available commands.
  49. * @type {{
  50. * displayName: inputDisplayNameHandler,
  51. * muteAudio: toggleAudio,
  52. * muteVideo: toggleVideo,
  53. * filmStrip: toggleFilmStrip
  54. * }}
  55. */
  56. var commands =
  57. {
  58. displayName: APP.UI.inputDisplayNameHandler,
  59. muteAudio: APP.UI.toggleAudio,
  60. muteVideo: APP.UI.toggleVideo,
  61. toggleFilmStrip: APP.UI.toggleFilmStrip,
  62. toggleChat: APP.UI.toggleChat,
  63. toggleContactList: APP.UI.toggleContactList
  64. };
  65. /**
  66. * Maps the supported events and their status
  67. * (true it the event is enabled and false if it is disabled)
  68. * @type {{
  69. * incomingMessage: boolean,
  70. * outgoingMessage: boolean,
  71. * displayNameChange: boolean,
  72. * participantJoined: boolean,
  73. * participantLeft: boolean
  74. * }}
  75. */
  76. var events =
  77. {
  78. incomingMessage: false,
  79. outgoingMessage:false,
  80. displayNameChange: false,
  81. participantJoined: false,
  82. participantLeft: false
  83. };
  84. var displayName = {};
  85. /**
  86. * Processes commands from external applicaiton.
  87. * @param message the object with the command
  88. */
  89. function processCommand(message)
  90. {
  91. if(message.action != "execute")
  92. {
  93. console.error("Unknown action of the message");
  94. return;
  95. }
  96. for(var key in message)
  97. {
  98. if(commands[key])
  99. commands[key].apply(null, message[key]);
  100. }
  101. }
  102. /**
  103. * Processes events objects from external applications
  104. * @param event the event
  105. */
  106. function processEvent(event) {
  107. if(!event.action)
  108. {
  109. console.error("Event with no action is received.");
  110. return;
  111. }
  112. var i = 0;
  113. switch(event.action)
  114. {
  115. case "add":
  116. for(; i < event.events.length; i++)
  117. {
  118. events[event.events[i]] = true;
  119. }
  120. break;
  121. case "remove":
  122. for(; i < event.events.length; i++)
  123. {
  124. events[event.events[i]] = false;
  125. }
  126. break;
  127. default:
  128. console.error("Unknown action for event.");
  129. }
  130. }
  131. /**
  132. * Sends message to the external application.
  133. * @param object
  134. */
  135. function sendMessage(object) {
  136. window.parent.postMessage(JSON.stringify(object), "*");
  137. }
  138. /**
  139. * Processes a message event from the external application
  140. * @param event the message event
  141. */
  142. function processMessage(event)
  143. {
  144. var message;
  145. try {
  146. message = JSON.parse(event.data);
  147. } catch (e) {}
  148. if(!message.type)
  149. return;
  150. switch (message.type)
  151. {
  152. case "command":
  153. processCommand(message);
  154. break;
  155. case "event":
  156. processEvent(message);
  157. break;
  158. default:
  159. console.error("Unknown type of the message");
  160. return;
  161. }
  162. }
  163. function setupListeners() {
  164. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, function (from) {
  165. API.triggerEvent("participantJoined", {jid: from});
  166. });
  167. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid) {
  168. if (from != myjid)
  169. API.triggerEvent("incomingMessage",
  170. {"from": from, "nick": nick, "message": txt});
  171. });
  172. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, function (jid) {
  173. API.triggerEvent("participantLeft", {jid: jid});
  174. });
  175. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  176. name = displayName[jid];
  177. if(!name || name != newDisplayName) {
  178. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  179. displayName[jid] = newDisplayName;
  180. }
  181. });
  182. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  183. APP.API.triggerEvent("outgoingMessage", {"message": body});
  184. });
  185. }
  186. var API = {
  187. /**
  188. * Check whether the API should be enabled or not.
  189. * @returns {boolean}
  190. */
  191. isEnabled: function () {
  192. var hash = location.hash;
  193. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  194. return true;
  195. return false;
  196. },
  197. /**
  198. * Initializes the APIConnector. Setups message event listeners that will
  199. * receive information from external applications that embed Jitsi Meet.
  200. * It also sends a message to the external application that APIConnector
  201. * is initialized.
  202. */
  203. init: function () {
  204. if (window.addEventListener)
  205. {
  206. window.addEventListener('message',
  207. processMessage, false);
  208. }
  209. else
  210. {
  211. window.attachEvent('onmessage', processMessage);
  212. }
  213. sendMessage({type: "system", loaded: true});
  214. setupListeners();
  215. },
  216. /**
  217. * Checks whether the event is enabled ot not.
  218. * @param name the name of the event.
  219. * @returns {*}
  220. */
  221. isEventEnabled: function (name) {
  222. return events[name];
  223. },
  224. /**
  225. * Sends event object to the external application that has been subscribed
  226. * for that event.
  227. * @param name the name event
  228. * @param object data associated with the event
  229. */
  230. triggerEvent: function (name, object) {
  231. if(this.isEnabled() && this.isEventEnabled(name))
  232. sendMessage({
  233. type: "event", action: "result", event: name, result: object});
  234. },
  235. /**
  236. * Removes the listeners.
  237. */
  238. dispose: function () {
  239. if(window.removeEventListener)
  240. {
  241. window.removeEventListener("message",
  242. processMessage, false);
  243. }
  244. else
  245. {
  246. window.detachEvent('onmessage', processMessage);
  247. }
  248. }
  249. };
  250. module.exports = API;
  251. },{"../../service/xmpp/XMPPEvents":88}],3:[function(require,module,exports){
  252. /* global Strophe, updateLargeVideo, focusedVideoSrc*/
  253. // cache datachannels to avoid garbage collection
  254. // https://code.google.com/p/chromium/issues/detail?id=405545
  255. var RTCEvents = require("../../service/RTC/RTCEvents");
  256. var _dataChannels = [];
  257. var eventEmitter = null;
  258. var DataChannels =
  259. {
  260. /**
  261. * Callback triggered by PeerConnection when new data channel is opened
  262. * on the bridge.
  263. * @param event the event info object.
  264. */
  265. onDataChannel: function (event)
  266. {
  267. var dataChannel = event.channel;
  268. dataChannel.onopen = function () {
  269. console.info("Data channel opened by the Videobridge!", dataChannel);
  270. // Code sample for sending string and/or binary data
  271. // Sends String message to the bridge
  272. //dataChannel.send("Hello bridge!");
  273. // Sends 12 bytes binary message to the bridge
  274. //dataChannel.send(new ArrayBuffer(12));
  275. // when the data channel becomes available, tell the bridge about video
  276. // selections so that it can do adaptive simulcast,
  277. // we want the notification to trigger even if userJid is undefined,
  278. // or null.
  279. var userJid = APP.UI.getLargeVideoState().userResourceJid;
  280. // we want the notification to trigger even if userJid is undefined,
  281. // or null.
  282. onSelectedEndpointChanged(userJid);
  283. };
  284. dataChannel.onerror = function (error) {
  285. console.error("Data Channel Error:", error, dataChannel);
  286. };
  287. dataChannel.onmessage = function (event) {
  288. var data = event.data;
  289. // JSON
  290. var obj;
  291. try {
  292. obj = JSON.parse(data);
  293. }
  294. catch (e) {
  295. console.error(
  296. "Failed to parse data channel message as JSON: ",
  297. data,
  298. dataChannel);
  299. }
  300. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  301. var colibriClass = obj.colibriClass;
  302. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  303. // Endpoint ID from the Videobridge.
  304. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  305. console.info(
  306. "Data channel new dominant speaker event: ",
  307. dominantSpeakerEndpoint);
  308. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  309. }
  310. else if ("InLastNChangeEvent" === colibriClass)
  311. {
  312. var oldValue = obj.oldValue;
  313. var newValue = obj.newValue;
  314. // Make sure that oldValue and newValue are of type boolean.
  315. var type;
  316. if ((type = typeof oldValue) !== 'boolean') {
  317. if (type === 'string') {
  318. oldValue = (oldValue == "true");
  319. } else {
  320. oldValue = new Boolean(oldValue).valueOf();
  321. }
  322. }
  323. if ((type = typeof newValue) !== 'boolean') {
  324. if (type === 'string') {
  325. newValue = (newValue == "true");
  326. } else {
  327. newValue = new Boolean(newValue).valueOf();
  328. }
  329. }
  330. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  331. }
  332. else if ("LastNEndpointsChangeEvent" === colibriClass)
  333. {
  334. // The new/latest list of last-n endpoint IDs.
  335. var lastNEndpoints = obj.lastNEndpoints;
  336. // The list of endpoint IDs which are entering the list of
  337. // last-n at this time i.e. were not in the old list of last-n
  338. // endpoint IDs.
  339. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  340. var stream = obj.stream;
  341. console.log(
  342. "Data channel new last-n event: ",
  343. lastNEndpoints, endpointsEnteringLastN, obj);
  344. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  345. lastNEndpoints, endpointsEnteringLastN, obj);
  346. }
  347. else if ("SimulcastLayersChangedEvent" === colibriClass)
  348. {
  349. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGED,
  350. obj.endpointSimulcastLayers);
  351. }
  352. else if ("SimulcastLayersChangingEvent" === colibriClass)
  353. {
  354. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGING,
  355. obj.endpointSimulcastLayers);
  356. }
  357. else if ("StartSimulcastLayerEvent" === colibriClass)
  358. {
  359. eventEmitter.emit(RTCEvents.SIMULCAST_START, obj.simulcastLayer);
  360. }
  361. else if ("StopSimulcastLayerEvent" === colibriClass)
  362. {
  363. eventEmitter.emit(RTCEvents.SIMULCAST_STOP, obj.simulcastLayer);
  364. }
  365. else
  366. {
  367. console.debug("Data channel JSON-formatted message: ", obj);
  368. }
  369. }
  370. };
  371. dataChannel.onclose = function ()
  372. {
  373. console.info("The Data Channel closed", dataChannel);
  374. var idx = _dataChannels.indexOf(dataChannel);
  375. if (idx > -1)
  376. _dataChannels = _dataChannels.splice(idx, 1);
  377. };
  378. _dataChannels.push(dataChannel);
  379. },
  380. /**
  381. * Binds "ondatachannel" event listener to given PeerConnection instance.
  382. * @param peerConnection WebRTC peer connection instance.
  383. */
  384. init: function (peerConnection, emitter) {
  385. if(!config.openSctp)
  386. return;
  387. peerConnection.ondatachannel = this.onDataChannel;
  388. eventEmitter = emitter;
  389. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  390. // Although it's not a requirement to open separate channels from both bridge
  391. // and peer as single channel can be used for sending and receiving data.
  392. // So either channel opened by the bridge or the one opened here is enough
  393. // for communication with the bridge.
  394. /*var dataChannelOptions =
  395. {
  396. reliable: true
  397. };
  398. var dataChannel
  399. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  400. // Can be used only when is in open state
  401. dataChannel.onopen = function ()
  402. {
  403. dataChannel.send("My channel !!!");
  404. };
  405. dataChannel.onmessage = function (event)
  406. {
  407. var msgData = event.data;
  408. console.info("Got My Data Channel Message:", msgData, dataChannel);
  409. };*/
  410. },
  411. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  412. handlePinnedEndpointEvent: onPinnedEndpointChanged
  413. };
  414. function onSelectedEndpointChanged(userResource)
  415. {
  416. console.log('selected endpoint changed: ', userResource);
  417. if (_dataChannels && _dataChannels.length != 0)
  418. {
  419. _dataChannels.some(function (dataChannel) {
  420. if (dataChannel.readyState == 'open')
  421. {
  422. console.log('sending selected endpoint changed '
  423. + 'notification to the bridge: ', userResource);
  424. dataChannel.send(JSON.stringify({
  425. 'colibriClass': 'SelectedEndpointChangedEvent',
  426. 'selectedEndpoint':
  427. (!userResource || userResource === null)?
  428. null : userResource
  429. }));
  430. return true;
  431. }
  432. });
  433. }
  434. }
  435. function onPinnedEndpointChanged(userResource)
  436. {
  437. console.log('pinned endpoint changed: ', userResource);
  438. if (_dataChannels && _dataChannels.length != 0)
  439. {
  440. _dataChannels.some(function (dataChannel) {
  441. if (dataChannel.readyState == 'open')
  442. {
  443. dataChannel.send(JSON.stringify({
  444. 'colibriClass': 'PinnedEndpointChangedEvent',
  445. 'pinnedEndpoint':
  446. (!userResource || userResource == null)?
  447. null : userResource
  448. }));
  449. return true;
  450. }
  451. });
  452. }
  453. }
  454. module.exports = DataChannels;
  455. },{"../../service/RTC/RTCEvents":80}],4:[function(require,module,exports){
  456. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  457. function LocalStream(stream, type, eventEmitter, videoType)
  458. {
  459. this.stream = stream;
  460. this.eventEmitter = eventEmitter;
  461. this.type = type;
  462. this.videoType = videoType;
  463. var self = this;
  464. if(type == "audio")
  465. {
  466. this.getTracks = function () {
  467. return self.stream.getAudioTracks();
  468. };
  469. }
  470. else
  471. {
  472. this.getTracks = function () {
  473. return self.stream.getVideoTracks();
  474. };
  475. }
  476. this.stream.onended = function()
  477. {
  478. self.streamEnded();
  479. };
  480. }
  481. LocalStream.prototype.streamEnded = function () {
  482. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  483. }
  484. LocalStream.prototype.getOriginalStream = function()
  485. {
  486. return this.stream;
  487. }
  488. LocalStream.prototype.isAudioStream = function () {
  489. return (this.stream.getAudioTracks() && this.stream.getAudioTracks().length > 0);
  490. };
  491. LocalStream.prototype.mute = function()
  492. {
  493. var ismuted = false;
  494. var tracks = this.getTracks();
  495. for (var idx = 0; idx < tracks.length; idx++) {
  496. ismuted = !tracks[idx].enabled;
  497. tracks[idx].enabled = ismuted;
  498. }
  499. return ismuted;
  500. };
  501. LocalStream.prototype.setMute = function(mute)
  502. {
  503. var tracks = this.getTracks();
  504. for (var idx = 0; idx < tracks.length; idx++) {
  505. tracks[idx].enabled = mute;
  506. }
  507. };
  508. LocalStream.prototype.isMuted = function () {
  509. var tracks = [];
  510. if(this.type == "audio")
  511. {
  512. tracks = this.stream.getAudioTracks();
  513. }
  514. else
  515. {
  516. tracks = this.stream.getVideoTracks();
  517. }
  518. for (var idx = 0; idx < tracks.length; idx++) {
  519. if(tracks[idx].enabled)
  520. return false;
  521. }
  522. return true;
  523. }
  524. LocalStream.prototype.getId = function () {
  525. return this.stream.getTracks()[0].id;
  526. }
  527. module.exports = LocalStream;
  528. },{"../../service/RTC/StreamEventTypes.js":82}],5:[function(require,module,exports){
  529. ////These lines should be uncommented when require works in app.js
  530. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  531. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  532. /**
  533. * Creates a MediaStream object for the given data, session id and ssrc.
  534. * It is a wrapper class for the MediaStream.
  535. *
  536. * @param data the data object from which we obtain the stream,
  537. * the peerjid, etc.
  538. * @param sid the session id
  539. * @param ssrc the ssrc corresponding to this MediaStream
  540. *
  541. * @constructor
  542. */
  543. function MediaStream(data, sid, ssrc, browser) {
  544. // XXX(gp) to minimize headaches in the future, we should build our
  545. // abstractions around tracks and not streams. ORTC is track based API.
  546. // Mozilla expects m-lines to represent media tracks.
  547. //
  548. // Practically, what I'm saying is that we should have a MediaTrack class
  549. // and not a MediaStream class.
  550. //
  551. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  552. // a track might have an associated RTX and FEC sources.
  553. this.sid = sid;
  554. this.stream = data.stream;
  555. this.peerjid = data.peerjid;
  556. this.ssrc = ssrc;
  557. this.type = (this.stream.getVideoTracks().length > 0)?
  558. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  559. this.videoType = null;
  560. this.muted = false;
  561. if(browser == RTCBrowserType.RTC_BROWSER_FIREFOX)
  562. {
  563. if (!this.getVideoTracks)
  564. this.getVideoTracks = function () { return []; };
  565. if (!this.getAudioTracks)
  566. this.getAudioTracks = function () { return []; };
  567. }
  568. }
  569. MediaStream.prototype.getOriginalStream = function()
  570. {
  571. return this.stream;
  572. }
  573. MediaStream.prototype.setMute = function (value)
  574. {
  575. this.stream.muted = value;
  576. this.muted = value;
  577. }
  578. module.exports = MediaStream;
  579. },{"../../service/RTC/MediaStreamTypes":78,"../../service/RTC/RTCBrowserType.js":79}],6:[function(require,module,exports){
  580. var EventEmitter = require("events");
  581. var RTCUtils = require("./RTCUtils.js");
  582. var LocalStream = require("./LocalStream.js");
  583. var DataChannels = require("./DataChannels");
  584. var MediaStream = require("./MediaStream.js");
  585. var DesktopSharingEventTypes
  586. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  587. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  588. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  589. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  590. var UIEvents = require("../../service/UI/UIEvents");
  591. var eventEmitter = new EventEmitter();
  592. var RTC = {
  593. rtcUtils: null,
  594. localStreams: [],
  595. remoteStreams: {},
  596. localAudio: null,
  597. localVideo: null,
  598. addStreamListener: function (listener, eventType) {
  599. eventEmitter.on(eventType, listener);
  600. },
  601. addListener: function (type, listener) {
  602. eventEmitter.on(type, listener);
  603. },
  604. removeStreamListener: function (listener, eventType) {
  605. if(!(eventType instanceof StreamEventTypes))
  606. throw "Illegal argument";
  607. eventEmitter.removeListener(eventType, listener);
  608. },
  609. createLocalStream: function (stream, type, change) {
  610. var localStream = new LocalStream(stream, type, eventEmitter);
  611. //in firefox we have only one stream object
  612. if(this.localStreams.length == 0 ||
  613. this.localStreams[0].getOriginalStream() != stream)
  614. this.localStreams.push(localStream);
  615. if(type == "audio")
  616. {
  617. this.localAudio = localStream;
  618. }
  619. else
  620. {
  621. this.localVideo = localStream;
  622. }
  623. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  624. if(change)
  625. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  626. eventEmitter.emit(eventType, localStream);
  627. return localStream;
  628. },
  629. removeLocalStream: function (stream) {
  630. for(var i = 0; i < this.localStreams.length; i++)
  631. {
  632. if(this.localStreams[i].getOriginalStream() === stream) {
  633. delete this.localStreams[i];
  634. return;
  635. }
  636. }
  637. },
  638. createRemoteStream: function (data, sid, thessrc) {
  639. var remoteStream = new MediaStream(data, sid, thessrc,
  640. this.getBrowserType());
  641. var jid = data.peerjid || APP.xmpp.myJid();
  642. if(!this.remoteStreams[jid]) {
  643. this.remoteStreams[jid] = {};
  644. }
  645. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  646. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  647. console.debug("ADD remote stream ", remoteStream.type, " ", jid, " ", thessrc);
  648. return remoteStream;
  649. },
  650. getBrowserType: function () {
  651. return this.rtcUtils.browser;
  652. },
  653. getPCConstraints: function () {
  654. return this.rtcUtils.pc_constraints;
  655. },
  656. getUserMediaWithConstraints:function(um, success_callback,
  657. failure_callback, resolution,
  658. bandwidth, fps, desktopStream)
  659. {
  660. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  661. failure_callback, resolution, bandwidth, fps, desktopStream);
  662. },
  663. attachMediaStream: function (element, stream) {
  664. this.rtcUtils.attachMediaStream(element, stream);
  665. },
  666. getStreamID: function (stream) {
  667. return this.rtcUtils.getStreamID(stream);
  668. },
  669. getVideoSrc: function (element) {
  670. return this.rtcUtils.getVideoSrc(element);
  671. },
  672. setVideoSrc: function (element, src) {
  673. this.rtcUtils.setVideoSrc(element, src);
  674. },
  675. dispose: function() {
  676. if (this.rtcUtils) {
  677. this.rtcUtils = null;
  678. }
  679. },
  680. stop: function () {
  681. this.dispose();
  682. },
  683. start: function () {
  684. var self = this;
  685. APP.desktopsharing.addListener(
  686. function (stream, isUsingScreenStream, callback) {
  687. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  688. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  689. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  690. for(var i = 0; i < changedStreams.length; i++) {
  691. var type = changedStreams[i].type;
  692. if (type != "audio") {
  693. var peerStreams = self.remoteStreams[jid];
  694. if(!peerStreams)
  695. continue;
  696. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  697. if(!videoStream)
  698. continue;
  699. videoStream.videoType = changedStreams[i].type;
  700. }
  701. }
  702. });
  703. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  704. DataChannels.init(event.peerconnection, eventEmitter);
  705. });
  706. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  707. DataChannels.handleSelectedEndpointEvent);
  708. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  709. DataChannels.handlePinnedEndpointEvent);
  710. this.rtcUtils = new RTCUtils(this);
  711. this.rtcUtils.obtainAudioAndVideoPermissions();
  712. },
  713. muteRemoteVideoStream: function (jid, value) {
  714. var stream;
  715. if(this.remoteStreams[jid] &&
  716. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  717. {
  718. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  719. }
  720. if(!stream)
  721. return false;
  722. if (value != stream.muted) {
  723. stream.setMute(value);
  724. return true;
  725. }
  726. return false;
  727. },
  728. switchVideoStreams: function (new_stream) {
  729. this.localVideo.stream = new_stream;
  730. this.localStreams = [];
  731. //in firefox we have only one stream object
  732. if (this.localAudio.getOriginalStream() != new_stream)
  733. this.localStreams.push(this.localAudio);
  734. this.localStreams.push(this.localVideo);
  735. },
  736. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  737. var oldStream = this.localVideo.getOriginalStream();
  738. var type = (isUsingScreenStream? "screen" : "video");
  739. this.localVideo = this.createLocalStream(stream, "video", true, type);
  740. // Stop the stream to trigger onended event for old stream
  741. oldStream.stop();
  742. APP.xmpp.switchStreams(stream, oldStream,callback);
  743. },
  744. /**
  745. * Checks if video identified by given src is desktop stream.
  746. * @param videoSrc eg.
  747. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  748. * @returns {boolean}
  749. */
  750. isVideoSrcDesktop: function (jid) {
  751. if(!jid)
  752. return false;
  753. var isDesktop = false;
  754. var stream = null;
  755. if (APP.xmpp.myJid() &&
  756. APP.xmpp.myResource() === jid) {
  757. // local video
  758. stream = this.localVideo;
  759. } else {
  760. var peerStreams = this.remoteStreams[jid];
  761. if(!peerStreams)
  762. return false;
  763. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  764. }
  765. if(stream)
  766. isDesktop = (stream.videoType === "screen");
  767. return isDesktop;
  768. }
  769. };
  770. module.exports = RTC;
  771. },{"../../service/RTC/MediaStreamTypes":78,"../../service/RTC/StreamEventTypes.js":82,"../../service/UI/UIEvents":83,"../../service/desktopsharing/DesktopSharingEventTypes":86,"../../service/xmpp/XMPPEvents":88,"./DataChannels":3,"./LocalStream.js":4,"./MediaStream.js":5,"./RTCUtils.js":7,"events":89}],7:[function(require,module,exports){
  772. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  773. var Resolutions = require("../../service/RTC/Resolutions");
  774. var currentResolution = null;
  775. function getPreviousResolution(resolution) {
  776. if(!Resolutions[resolution])
  777. return null;
  778. var order = Resolutions[resolution].order;
  779. var res = null;
  780. var resName = null;
  781. for(var i in Resolutions)
  782. {
  783. var tmp = Resolutions[i];
  784. if(res == null || (res.order < tmp.order && tmp.order < order))
  785. {
  786. resName = i;
  787. res = tmp;
  788. }
  789. }
  790. return resName;
  791. }
  792. function setResolutionConstraints(constraints, resolution, isAndroid)
  793. {
  794. if (resolution && !constraints.video || isAndroid) {
  795. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  796. }
  797. if(Resolutions[resolution])
  798. {
  799. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  800. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  801. }
  802. else
  803. {
  804. if (isAndroid) {
  805. constraints.video.mandatory.minWidth = 320;
  806. constraints.video.mandatory.minHeight = 240;
  807. constraints.video.mandatory.maxFrameRate = 15;
  808. }
  809. }
  810. if (constraints.video.mandatory.minWidth)
  811. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  812. if (constraints.video.mandatory.minHeight)
  813. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  814. }
  815. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  816. {
  817. var constraints = {audio: false, video: false};
  818. if (um.indexOf('video') >= 0) {
  819. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  820. }
  821. if (um.indexOf('audio') >= 0) {
  822. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  823. }
  824. if (um.indexOf('screen') >= 0) {
  825. constraints.video = {
  826. mandatory: {
  827. chromeMediaSource: "screen",
  828. googLeakyBucket: true,
  829. maxWidth: window.screen.width,
  830. maxHeight: window.screen.height,
  831. maxFrameRate: 3
  832. },
  833. optional: []
  834. };
  835. }
  836. if (um.indexOf('desktop') >= 0) {
  837. constraints.video = {
  838. mandatory: {
  839. chromeMediaSource: "desktop",
  840. chromeMediaSourceId: desktopStream,
  841. googLeakyBucket: true,
  842. maxWidth: window.screen.width,
  843. maxHeight: window.screen.height,
  844. maxFrameRate: 3
  845. },
  846. optional: []
  847. };
  848. }
  849. if (constraints.audio) {
  850. // if it is good enough for hangouts...
  851. constraints.audio.optional.push(
  852. {googEchoCancellation: true},
  853. {googAutoGainControl: true},
  854. {googNoiseSupression: true},
  855. {googHighpassFilter: true},
  856. {googNoisesuppression2: true},
  857. {googEchoCancellation2: true},
  858. {googAutoGainControl2: true}
  859. );
  860. }
  861. if (constraints.video) {
  862. constraints.video.optional.push(
  863. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  864. );
  865. if (um.indexOf('video') >= 0) {
  866. constraints.video.optional.push(
  867. {googLeakyBucket: true}
  868. );
  869. }
  870. }
  871. if (um.indexOf('video') >= 0) {
  872. setResolutionConstraints(constraints, resolution, isAndroid);
  873. }
  874. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  875. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  876. constraints.video.optional.push({bandwidth: bandwidth});
  877. }
  878. if (fps) { // for some cameras it might be necessary to request 30fps
  879. // so they choose 30fps mjpg over 10fps yuy2
  880. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  881. constraints.video.mandatory.minFrameRate = fps;
  882. }
  883. return constraints;
  884. }
  885. function RTCUtils(RTCService)
  886. {
  887. this.service = RTCService;
  888. if (navigator.mozGetUserMedia) {
  889. console.log('This appears to be Firefox');
  890. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  891. if (version >= 22) {
  892. this.peerconnection = mozRTCPeerConnection;
  893. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  894. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  895. this.pc_constraints = {};
  896. this.attachMediaStream = function (element, stream) {
  897. element[0].mozSrcObject = stream;
  898. element[0].play();
  899. };
  900. this.getStreamID = function (stream) {
  901. var tracks = stream.getVideoTracks();
  902. if(!tracks || tracks.length == 0)
  903. {
  904. tracks = stream.getAudioTracks();
  905. }
  906. return tracks[0].id.replace(/[\{,\}]/g,"");
  907. };
  908. this.getVideoSrc = function (element) {
  909. return element.mozSrcObject;
  910. };
  911. this.setVideoSrc = function (element, src) {
  912. element.mozSrcObject = src;
  913. };
  914. RTCSessionDescription = mozRTCSessionDescription;
  915. RTCIceCandidate = mozRTCIceCandidate;
  916. }
  917. } else if (navigator.webkitGetUserMedia) {
  918. console.log('This appears to be Chrome');
  919. this.peerconnection = webkitRTCPeerConnection;
  920. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  921. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  922. this.attachMediaStream = function (element, stream) {
  923. element.attr('src', webkitURL.createObjectURL(stream));
  924. };
  925. this.getStreamID = function (stream) {
  926. // streams from FF endpoints have the characters '{' and '}'
  927. // that make jQuery choke.
  928. return stream.id.replace(/[\{,\}]/g,"");
  929. };
  930. this.getVideoSrc = function (element) {
  931. return element.getAttribute("src");
  932. };
  933. this.setVideoSrc = function (element, src) {
  934. element.setAttribute("src", src);
  935. };
  936. // DTLS should now be enabled by default but..
  937. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  938. if (navigator.userAgent.indexOf('Android') != -1) {
  939. this.pc_constraints = {}; // disable DTLS on Android
  940. }
  941. if (!webkitMediaStream.prototype.getVideoTracks) {
  942. webkitMediaStream.prototype.getVideoTracks = function () {
  943. return this.videoTracks;
  944. };
  945. }
  946. if (!webkitMediaStream.prototype.getAudioTracks) {
  947. webkitMediaStream.prototype.getAudioTracks = function () {
  948. return this.audioTracks;
  949. };
  950. }
  951. }
  952. else
  953. {
  954. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  955. window.location.href = 'webrtcrequired.html';
  956. return;
  957. }
  958. if (this.browser !== RTCBrowserType.RTC_BROWSER_CHROME &&
  959. config.enableFirefoxSupport !== true) {
  960. window.location.href = 'chromeonly.html';
  961. return;
  962. }
  963. }
  964. RTCUtils.prototype.getUserMediaWithConstraints = function(
  965. um, success_callback, failure_callback, resolution,bandwidth, fps,
  966. desktopStream)
  967. {
  968. currentResolution = resolution;
  969. // Check if we are running on Android device
  970. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  971. var constraints = getConstraints(
  972. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  973. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  974. try {
  975. if (config.enableSimulcast
  976. && constraints.video
  977. && constraints.video.chromeMediaSource !== 'screen'
  978. && constraints.video.chromeMediaSource !== 'desktop'
  979. && !isAndroid
  980. // We currently do not support FF, as it doesn't have multistream support.
  981. && !isFF) {
  982. APP.simulcast.getUserMedia(constraints, function (stream) {
  983. console.log('onUserMediaSuccess');
  984. success_callback(stream);
  985. },
  986. function (error) {
  987. console.warn('Failed to get access to local media. Error ', error);
  988. if (failure_callback) {
  989. failure_callback(error);
  990. }
  991. });
  992. } else {
  993. this.getUserMedia(constraints,
  994. function (stream) {
  995. console.log('onUserMediaSuccess');
  996. success_callback(stream);
  997. },
  998. function (error) {
  999. console.warn('Failed to get access to local media. Error ',
  1000. error, constraints);
  1001. if (failure_callback) {
  1002. failure_callback(error);
  1003. }
  1004. });
  1005. }
  1006. } catch (e) {
  1007. console.error('GUM failed: ', e);
  1008. if(failure_callback) {
  1009. failure_callback(e);
  1010. }
  1011. }
  1012. };
  1013. /**
  1014. * We ask for audio and video combined stream in order to get permissions and
  1015. * not to ask twice.
  1016. */
  1017. RTCUtils.prototype.obtainAudioAndVideoPermissions = function() {
  1018. var self = this;
  1019. // Get AV
  1020. this.getUserMediaWithConstraints(
  1021. ['audio', 'video'],
  1022. function (stream) {
  1023. self.successCallback(stream);
  1024. },
  1025. function (error) {
  1026. self.errorCallback(error);
  1027. },
  1028. config.resolution || '360');
  1029. }
  1030. RTCUtils.prototype.successCallback = function (stream) {
  1031. console.log('got', stream, stream.getAudioTracks().length,
  1032. stream.getVideoTracks().length);
  1033. this.handleLocalStream(stream);
  1034. };
  1035. RTCUtils.prototype.errorCallback = function (error) {
  1036. var self = this;
  1037. console.error('failed to obtain audio/video stream - trying audio only', error);
  1038. var resolution = getPreviousResolution(currentResolution);
  1039. if(typeof error == "object" && error.constraintName && error.name
  1040. && (error.name == "ConstraintNotSatisfiedError" ||
  1041. error.name == "OverconstrainedError") &&
  1042. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1043. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1044. && resolution != null)
  1045. {
  1046. self.getUserMediaWithConstraints(['audio', 'video'],
  1047. function (stream) {
  1048. return self.successCallback(stream);
  1049. }, function (error) {
  1050. return self.errorCallback(error);
  1051. }, resolution);
  1052. }
  1053. else
  1054. {
  1055. self.getUserMediaWithConstraints(
  1056. ['audio'],
  1057. function (stream) {
  1058. return self.successCallback(stream);
  1059. },
  1060. function (error) {
  1061. console.error('failed to obtain audio/video stream - stop',
  1062. error);
  1063. APP.UI.messageHandler.showError("dialog.error", "Error",
  1064. "dialog.failedpermissions",
  1065. "Failed to obtain permissions to use the local microphone " +
  1066. "and/or camera.");
  1067. }
  1068. );
  1069. }
  1070. }
  1071. RTCUtils.prototype.handleLocalStream = function(stream)
  1072. {
  1073. if(window.webkitMediaStream)
  1074. {
  1075. var audioStream = new webkitMediaStream();
  1076. var videoStream = new webkitMediaStream();
  1077. var audioTracks = stream.getAudioTracks();
  1078. var videoTracks = stream.getVideoTracks();
  1079. for (var i = 0; i < audioTracks.length; i++) {
  1080. audioStream.addTrack(audioTracks[i]);
  1081. }
  1082. this.service.createLocalStream(audioStream, "audio");
  1083. for (i = 0; i < videoTracks.length; i++) {
  1084. videoStream.addTrack(videoTracks[i]);
  1085. }
  1086. this.service.createLocalStream(videoStream, "video");
  1087. }
  1088. else
  1089. {//firefox
  1090. this.service.createLocalStream(stream, "stream");
  1091. }
  1092. };
  1093. module.exports = RTCUtils;
  1094. },{"../../service/RTC/RTCBrowserType.js":79,"../../service/RTC/Resolutions":81}],8:[function(require,module,exports){
  1095. var UI = {};
  1096. var VideoLayout = require("./videolayout/VideoLayout.js");
  1097. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1098. var Prezi = require("./prezi/Prezi.js");
  1099. var Etherpad = require("./etherpad/Etherpad.js");
  1100. var Chat = require("./side_pannels/chat/Chat.js");
  1101. var Toolbar = require("./toolbars/Toolbar");
  1102. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1103. var BottomToolbar = require("./toolbars/BottomToolbar");
  1104. var ContactList = require("./side_pannels/contactlist/ContactList");
  1105. var Avatar = require("./avatar/Avatar");
  1106. var EventEmitter = require("events");
  1107. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1108. var Settings = require("./../settings/Settings");
  1109. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1110. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1111. UI.messageHandler = require("./util/MessageHandler");
  1112. var messageHandler = UI.messageHandler;
  1113. var Authentication = require("./authentication/Authentication");
  1114. var UIUtil = require("./util/UIUtil");
  1115. var NicknameHandler = require("./util/NicknameHandler");
  1116. var CQEvents = require("../../service/connectionquality/CQEvents");
  1117. var DesktopSharingEventTypes
  1118. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1119. var RTCEvents = require("../../service/RTC/RTCEvents");
  1120. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1121. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1122. var eventEmitter = new EventEmitter();
  1123. var roomName = null;
  1124. function setupPrezi()
  1125. {
  1126. $("#reloadPresentationLink").click(function()
  1127. {
  1128. Prezi.reloadPresentation();
  1129. });
  1130. }
  1131. function setupChat()
  1132. {
  1133. Chat.init();
  1134. $("#toggle_smileys").click(function() {
  1135. Chat.toggleSmileys();
  1136. });
  1137. }
  1138. function setupToolbars() {
  1139. Toolbar.init(UI);
  1140. Toolbar.setupButtonsFromConfig();
  1141. BottomToolbar.init();
  1142. }
  1143. function streamHandler(stream) {
  1144. switch (stream.type)
  1145. {
  1146. case "audio":
  1147. VideoLayout.changeLocalAudio(stream);
  1148. break;
  1149. case "video":
  1150. VideoLayout.changeLocalVideo(stream);
  1151. break;
  1152. case "stream":
  1153. VideoLayout.changeLocalStream(stream);
  1154. break;
  1155. }
  1156. }
  1157. function onDisposeConference(unload) {
  1158. Toolbar.showAuthenticateButton(false);
  1159. };
  1160. function onDisplayNameChanged(jid, displayName) {
  1161. ContactList.onDisplayNameChange(jid, displayName);
  1162. SettingsMenu.onDisplayNameChange(jid, displayName);
  1163. VideoLayout.onDisplayNameChanged(jid, displayName);
  1164. }
  1165. function registerListeners() {
  1166. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1167. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1168. APP.RTC.addStreamListener(function (stream) {
  1169. VideoLayout.onRemoteStreamAdded(stream);
  1170. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1171. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1172. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1173. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1174. });
  1175. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1176. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1177. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1178. endpointsEnteringLastN, stream);
  1179. });
  1180. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  1181. function (endpointSimulcastLayers) {
  1182. VideoLayout.onSimulcastLayersChanged(endpointSimulcastLayers);
  1183. });
  1184. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGING,
  1185. function (endpointSimulcastLayers) {
  1186. VideoLayout.onSimulcastLayersChanging(endpointSimulcastLayers);
  1187. });
  1188. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1189. {
  1190. var resourceJid;
  1191. if(jid === APP.statistics.LOCAL_JID)
  1192. {
  1193. resourceJid = AudioLevels.LOCAL_LEVEL;
  1194. if(APP.RTC.localAudio.isMuted())
  1195. {
  1196. audioLevel = 0;
  1197. }
  1198. }
  1199. else
  1200. {
  1201. resourceJid = Strophe.getResourceFromJid(jid);
  1202. }
  1203. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1204. UI.getLargeVideoState().userResourceJid);
  1205. });
  1206. APP.desktopsharing.addListener(function () {
  1207. ToolbarToggler.showDesktopSharingButton();
  1208. }, DesktopSharingEventTypes.INIT);
  1209. APP.desktopsharing.addListener(
  1210. Toolbar.changeDesktopSharingButtonState,
  1211. DesktopSharingEventTypes.SWITCHING_DONE);
  1212. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1213. VideoLayout.updateLocalConnectionStats);
  1214. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1215. VideoLayout.updateConnectionStats);
  1216. APP.connectionquality.addListener(CQEvents.STOP,
  1217. VideoLayout.onStatsStop);
  1218. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1219. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1220. messageHandler.openMessageDialog("dialog.sessTerminated", "Session Terminated",
  1221. "dialog.kickMessage", "Ouch! You have been kicked out of the meet!");
  1222. });
  1223. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1224. //FIXME: use Session Terminated from translation, but
  1225. // 'reason' text comes from XMPP packet and is not translated
  1226. messageHandler.openDialog(
  1227. "Session Terminated", reason, true, {},
  1228. function (event, value, message, formVals)
  1229. {
  1230. return false;
  1231. }
  1232. );
  1233. });
  1234. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1235. messageHandler.showError("dialog.error","Error",
  1236. "dialog.bridgeUnavailable",
  1237. "Jitsi Videobridge is currently unavailable. Please try again later!");
  1238. });
  1239. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1240. Avatar.setUserAvatar(from, id);
  1241. });
  1242. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  1243. for(stream in changedStreams)
  1244. {
  1245. // might need to update the direction if participant just went from sendrecv to recvonly
  1246. if (stream.type === 'video' || stream.type === 'screen') {
  1247. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1248. switch (stream.direction) {
  1249. case 'sendrecv':
  1250. el.show();
  1251. break;
  1252. case 'recvonly':
  1253. el.hide();
  1254. // FIXME: Check if we have to change large video
  1255. //VideoLayout.updateLargeVideo(el);
  1256. break;
  1257. }
  1258. }
  1259. }
  1260. });
  1261. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1262. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1263. APP.xmpp.addListener(XMPPEvents.LOCALROLE_CHANGED, onLocalRoleChange);
  1264. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, onMucEntered);
  1265. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1266. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1267. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1268. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1269. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1270. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordReqiured);
  1271. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1272. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1273. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, onAuthenticationRequired);
  1274. }
  1275. /**
  1276. * Mutes/unmutes the local video.
  1277. *
  1278. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1279. * @param options an object which specifies optional arguments such as the
  1280. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1281. * specifies whether the method was initiated in response to a user command (in
  1282. * contrast to an automatic decision taken by the application logic)
  1283. */
  1284. function setVideoMute(mute, options) {
  1285. APP.xmpp.setVideoMute(
  1286. mute,
  1287. function (mute) {
  1288. var video = $('#video');
  1289. var communicativeClass = "icon-camera";
  1290. var muteClass = "icon-camera icon-camera-disabled";
  1291. if (mute) {
  1292. video.removeClass(communicativeClass);
  1293. video.addClass(muteClass);
  1294. } else {
  1295. video.removeClass(muteClass);
  1296. video.addClass(communicativeClass);
  1297. }
  1298. },
  1299. options);
  1300. }
  1301. function bindEvents()
  1302. {
  1303. /**
  1304. * Resizes and repositions videos in full screen mode.
  1305. */
  1306. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1307. function () {
  1308. VideoLayout.resizeLargeVideoContainer();
  1309. VideoLayout.positionLarge();
  1310. }
  1311. );
  1312. $(window).resize(function () {
  1313. VideoLayout.resizeLargeVideoContainer();
  1314. VideoLayout.positionLarge();
  1315. });
  1316. }
  1317. UI.start = function (init) {
  1318. document.title = interfaceConfig.APP_NAME;
  1319. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1320. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1321. {
  1322. $("#videoconference_page").hide();
  1323. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1324. setupWelcomePage();
  1325. return;
  1326. }
  1327. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1328. var leftWatermarkDiv
  1329. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1330. leftWatermarkDiv.css({display: 'block'});
  1331. leftWatermarkDiv.parent().get(0).href
  1332. = interfaceConfig.JITSI_WATERMARK_LINK;
  1333. }
  1334. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1335. var rightWatermarkDiv
  1336. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1337. rightWatermarkDiv.css({display: 'block'});
  1338. rightWatermarkDiv.parent().get(0).href
  1339. = interfaceConfig.BRAND_WATERMARK_LINK;
  1340. rightWatermarkDiv.get(0).style.backgroundImage
  1341. = "url(images/rightwatermark.png)";
  1342. }
  1343. if (interfaceConfig.SHOW_POWERED_BY) {
  1344. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1345. }
  1346. $("#welcome_page").hide();
  1347. VideoLayout.resizeLargeVideoContainer();
  1348. $("#videospace").mousemove(function () {
  1349. return ToolbarToggler.showToolbar();
  1350. });
  1351. // Set the defaults for prompt dialogs.
  1352. jQuery.prompt.setDefaults({persistent: false});
  1353. VideoLayout.init(eventEmitter);
  1354. AudioLevels.init();
  1355. NicknameHandler.init(eventEmitter);
  1356. registerListeners();
  1357. bindEvents();
  1358. setupPrezi();
  1359. setupToolbars();
  1360. setupChat();
  1361. document.title = interfaceConfig.APP_NAME;
  1362. $("#downloadlog").click(function (event) {
  1363. dump(event.target);
  1364. });
  1365. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1366. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1367. {
  1368. $("#videoconference_page").hide();
  1369. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1370. setupWelcomePage();
  1371. return;
  1372. }
  1373. $("#welcome_page").hide();
  1374. document.getElementById('largeVideo').volume = 0;
  1375. if (!$('#settings').is(':visible')) {
  1376. console.log('init');
  1377. init();
  1378. } else {
  1379. loginInfo.onsubmit = function (e) {
  1380. if (e.preventDefault) e.preventDefault();
  1381. $('#settings').hide();
  1382. init();
  1383. };
  1384. }
  1385. toastr.options = {
  1386. "closeButton": true,
  1387. "debug": false,
  1388. "positionClass": "notification-bottom-right",
  1389. "onclick": null,
  1390. "showDuration": "300",
  1391. "hideDuration": "1000",
  1392. "timeOut": "2000",
  1393. "extendedTimeOut": "1000",
  1394. "showEasing": "swing",
  1395. "hideEasing": "linear",
  1396. "showMethod": "fadeIn",
  1397. "hideMethod": "fadeOut",
  1398. "reposition": function() {
  1399. if(PanelToggler.isVisible()) {
  1400. $("#toast-container").addClass("notification-bottom-right-center");
  1401. } else {
  1402. $("#toast-container").removeClass("notification-bottom-right-center");
  1403. }
  1404. },
  1405. "newestOnTop": false
  1406. };
  1407. SettingsMenu.init();
  1408. };
  1409. function chatAddError(errorMessage, originalText)
  1410. {
  1411. return Chat.chatAddError(errorMessage, originalText);
  1412. };
  1413. function chatSetSubject(text)
  1414. {
  1415. return Chat.chatSetSubject(text);
  1416. };
  1417. function updateChatConversation(from, displayName, message) {
  1418. return Chat.updateChatConversation(from, displayName, message);
  1419. };
  1420. function onMucJoined(jid, info) {
  1421. Toolbar.updateRoomUrl(window.location.href);
  1422. document.getElementById('localNick').appendChild(
  1423. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  1424. );
  1425. var settings = Settings.getSettings();
  1426. // Add myself to the contact list.
  1427. ContactList.addContact(jid, settings.email || settings.uid);
  1428. // Once we've joined the muc show the toolbar
  1429. ToolbarToggler.showToolbar();
  1430. var displayName = !config.displayJids
  1431. ? info.displayName : Strophe.getResourceFromJid(jid);
  1432. if (displayName)
  1433. onDisplayNameChanged('localVideoContainer', displayName + ' (me)');
  1434. }
  1435. function initEtherpad(name) {
  1436. Etherpad.init(name);
  1437. };
  1438. function onMucLeft(jid) {
  1439. console.log('left.muc', jid);
  1440. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1441. '>.displayname').html();
  1442. messageHandler.notify(displayName,'notify.somebody', "Somebody",
  1443. 'disconnected',
  1444. 'notify.disconnected', "disconnected");
  1445. // Need to call this with a slight delay, otherwise the element couldn't be
  1446. // found for some reason.
  1447. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1448. window.setTimeout(function () {
  1449. var container = document.getElementById(
  1450. 'participant_' + Strophe.getResourceFromJid(jid));
  1451. if (container) {
  1452. ContactList.removeContact(jid);
  1453. VideoLayout.removeConnectionIndicator(jid);
  1454. // hide here, wait for video to close before removing
  1455. $(container).hide();
  1456. VideoLayout.resizeThumbnails();
  1457. }
  1458. }, 10);
  1459. VideoLayout.participantLeft(jid);
  1460. };
  1461. function onLocalRoleChange(jid, info, pres, isModerator)
  1462. {
  1463. console.info("My role changed, new role: " + info.role);
  1464. onModeratorStatusChanged(isModerator);
  1465. VideoLayout.showModeratorIndicator();
  1466. if (isModerator) {
  1467. Authentication.closeAuthenticationWindow();
  1468. messageHandler.notify(null, "notify.me",
  1469. 'Me', 'connected', "notify.moderator",
  1470. 'Moderator rights granted !');
  1471. }
  1472. }
  1473. function onModeratorStatusChanged(isModerator) {
  1474. Toolbar.showSipCallButton(isModerator);
  1475. Toolbar.showRecordingButton(
  1476. isModerator); //&&
  1477. // FIXME:
  1478. // Recording visible if
  1479. // there are at least 2(+ 1 focus) participants
  1480. //Object.keys(connection.emuc.members).length >= 3);
  1481. if (isModerator && config.etherpad_base) {
  1482. Etherpad.init();
  1483. }
  1484. };
  1485. function onPasswordReqiured(callback) {
  1486. // password is required
  1487. Toolbar.lockLockButton();
  1488. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1489. message += APP.translation.translateString(
  1490. "dialog.passwordRequired", null, "Password required");
  1491. message += '</h2>' +
  1492. '<input id="lockKey" type="text" placeholder="password" autofocus>';
  1493. messageHandler.openTwoButtonDialog(null, null, null, message,
  1494. true,
  1495. "dialog.Ok",
  1496. function (e, v, m, f) {},
  1497. function (event) {
  1498. document.getElementById('lockKey').focus();
  1499. },
  1500. function (e, v, m, f) {
  1501. if (v) {
  1502. var lockKey = document.getElementById('lockKey');
  1503. if (lockKey.value !== null) {
  1504. Toolbar.setSharedKey(lockKey.value);
  1505. callback(lockKey.value);
  1506. }
  1507. }
  1508. }
  1509. );
  1510. }
  1511. function onMucEntered(jid, id, displayName) {
  1512. messageHandler.notify(displayName,'notify.somebody', "Somebody",
  1513. 'connected',
  1514. 'notify.connected', "connected");
  1515. // Add Peer's container
  1516. VideoLayout.ensurePeerContainerExists(jid,id);
  1517. }
  1518. function onMucPresenceStatus( jid, info) {
  1519. VideoLayout.setPresenceStatus(
  1520. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1521. }
  1522. function onMucRoleChanged(role, displayName) {
  1523. VideoLayout.showModeratorIndicator();
  1524. if (role === 'moderator') {
  1525. var messageKey, messageOptions = {};
  1526. var lDisplayName = displayName;
  1527. if (!lDisplayName) {
  1528. lDisplayName = 'Somebody';
  1529. messageKey = "notify.grantedToUnknown";
  1530. }
  1531. else
  1532. {
  1533. messageKey = "notify.grantedTo";
  1534. messageOptions = {to: displayName};
  1535. }
  1536. messageHandler.notify(
  1537. displayName,'notify.somebody', "Somebody",
  1538. 'connected', messageKey,
  1539. 'Moderator rights granted to ' + lDisplayName + '!',
  1540. messageOptions);
  1541. }
  1542. }
  1543. function onAuthenticationRequired(intervalCallback) {
  1544. Authentication.openAuthenticationDialog(
  1545. roomName, intervalCallback, function () {
  1546. Toolbar.authenticateClicked();
  1547. });
  1548. };
  1549. function onLastNChanged(oldValue, newValue) {
  1550. if (config.muteLocalVideoIfNotInLastN) {
  1551. setVideoMute(!newValue, { 'byUser': false });
  1552. }
  1553. }
  1554. UI.toggleSmileys = function () {
  1555. Chat.toggleSmileys();
  1556. };
  1557. UI.getSettings = function () {
  1558. return Settings.getSettings();
  1559. };
  1560. UI.toggleFilmStrip = function () {
  1561. return BottomToolbar.toggleFilmStrip();
  1562. };
  1563. UI.toggleChat = function () {
  1564. return BottomToolbar.toggleChat();
  1565. };
  1566. UI.toggleContactList = function () {
  1567. return BottomToolbar.toggleContactList();
  1568. };
  1569. UI.inputDisplayNameHandler = function (value) {
  1570. VideoLayout.inputDisplayNameHandler(value);
  1571. };
  1572. UI.getLargeVideoState = function()
  1573. {
  1574. return VideoLayout.getLargeVideoState();
  1575. };
  1576. UI.generateRoomName = function() {
  1577. if(roomName)
  1578. return roomName;
  1579. var roomnode = null;
  1580. var path = window.location.pathname;
  1581. // determinde the room node from the url
  1582. // TODO: just the roomnode or the whole bare jid?
  1583. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1584. // custom function might be responsible for doing the pushstate
  1585. roomnode = config.getroomnode(path);
  1586. } else {
  1587. /* fall back to default strategy
  1588. * this is making assumptions about how the URL->room mapping happens.
  1589. * It currently assumes deployment at root, with a rewrite like the
  1590. * following one (for nginx):
  1591. location ~ ^/([a-zA-Z0-9]+)$ {
  1592. rewrite ^/(.*)$ / break;
  1593. }
  1594. */
  1595. if (path.length > 1) {
  1596. roomnode = path.substr(1).toLowerCase();
  1597. } else {
  1598. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1599. roomnode = word.toLowerCase();
  1600. window.history.pushState('VideoChat',
  1601. 'Room: ' + word, window.location.pathname + word);
  1602. }
  1603. }
  1604. roomName = roomnode + '@' + config.hosts.muc;
  1605. return roomName;
  1606. };
  1607. UI.connectionIndicatorShowMore = function(id)
  1608. {
  1609. return VideoLayout.connectionIndicators[id].showMore();
  1610. };
  1611. UI.getCredentials = function () {
  1612. var settings = this.getSettings();
  1613. return {
  1614. bosh: document.getElementById('boshURL').value,
  1615. password: document.getElementById('password').value,
  1616. jid: document.getElementById('jid').value,
  1617. email: settings.email,
  1618. displayName: settings.displayName,
  1619. uid: settings.uid
  1620. };
  1621. };
  1622. UI.disableConnect = function () {
  1623. document.getElementById('connect').disabled = true;
  1624. };
  1625. UI.showLoginPopup = function(callback)
  1626. {
  1627. console.log('password is required');
  1628. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1629. message += APP.translation.translateString(
  1630. "dialog.passwordRequired", null, "Password required");
  1631. message += '</h2>' +
  1632. '<input id="passwordrequired.username" type="text" ' +
  1633. 'placeholder="user@domain.net" autofocus>' +
  1634. '<input id="passwordrequired.password" ' +
  1635. 'type="password" placeholder="user password">';
  1636. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  1637. true,
  1638. "dialog.Ok",
  1639. function (e, v, m, f) {
  1640. if (v) {
  1641. var username = document.getElementById('passwordrequired.username');
  1642. var password = document.getElementById('passwordrequired.password');
  1643. if (username.value !== null && password.value != null) {
  1644. callback(username.value, password.value);
  1645. }
  1646. }
  1647. },
  1648. function (event) {
  1649. document.getElementById('passwordrequired.username').focus();
  1650. }
  1651. );
  1652. }
  1653. UI.checkForNicknameAndJoin = function () {
  1654. Authentication.closeAuthenticationDialog();
  1655. Authentication.stopInterval();
  1656. var nick = null;
  1657. if (config.useNicks) {
  1658. nick = window.prompt('Your nickname (optional)');
  1659. }
  1660. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1661. };
  1662. function dump(elem, filename) {
  1663. elem = elem.parentNode;
  1664. elem.download = filename || 'meetlog.json';
  1665. elem.href = 'data:application/json;charset=utf-8,\n';
  1666. var data = APP.xmpp.populateData();
  1667. var metadata = {};
  1668. metadata.time = new Date();
  1669. metadata.url = window.location.href;
  1670. metadata.ua = navigator.userAgent;
  1671. var log = APP.xmpp.getLogger();
  1672. if (log) {
  1673. metadata.xmpp = log;
  1674. }
  1675. data.metadata = metadata;
  1676. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1677. return false;
  1678. }
  1679. UI.getRoomName = function () {
  1680. return roomName;
  1681. };
  1682. /**
  1683. * Mutes/unmutes the local video.
  1684. */
  1685. UI.toggleVideo = function () {
  1686. UIUtil.buttonClick("#video", "icon-camera icon-camera-disabled");
  1687. setVideoMute(!APP.RTC.localVideo.isMuted());
  1688. };
  1689. /**
  1690. * Mutes / unmutes audio for the local participant.
  1691. */
  1692. UI.toggleAudio = function() {
  1693. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  1694. };
  1695. /**
  1696. * Sets muted audio state for the local participant.
  1697. */
  1698. UI.setAudioMuted = function (mute) {
  1699. if(!APP.xmpp.setAudioMute(mute, function () {
  1700. VideoLayout.showLocalAudioIndicator(mute);
  1701. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1702. }))
  1703. {
  1704. // We still click the button.
  1705. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1706. return;
  1707. }
  1708. }
  1709. UI.addListener = function (type, listener) {
  1710. eventEmitter.on(type, listener);
  1711. }
  1712. UI.clickOnVideo = function (videoNumber) {
  1713. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  1714. if (remoteVideos.length > videoNumber) {
  1715. remoteVideos[videoNumber].click();
  1716. }
  1717. }
  1718. //Used by torture
  1719. UI.showToolbar = function () {
  1720. return ToolbarToggler.showToolbar();
  1721. }
  1722. //Used by torture
  1723. UI.dockToolbar = function (isDock) {
  1724. return ToolbarToggler.dockToolbar(isDock);
  1725. }
  1726. module.exports = UI;
  1727. },{"../../service/RTC/RTCEvents":80,"../../service/RTC/StreamEventTypes":82,"../../service/connectionquality/CQEvents":85,"../../service/desktopsharing/DesktopSharingEventTypes":86,"../../service/xmpp/XMPPEvents":88,"./../settings/Settings":37,"./audio_levels/AudioLevels.js":9,"./authentication/Authentication":11,"./avatar/Avatar":12,"./etherpad/Etherpad.js":13,"./prezi/Prezi.js":14,"./side_pannels/SidePanelToggler":16,"./side_pannels/chat/Chat.js":17,"./side_pannels/contactlist/ContactList":21,"./side_pannels/settings/SettingsMenu":22,"./toolbars/BottomToolbar":23,"./toolbars/Toolbar":24,"./toolbars/ToolbarToggler":25,"./util/MessageHandler":27,"./util/NicknameHandler":28,"./util/UIUtil":29,"./videolayout/VideoLayout.js":31,"./welcome_page/RoomnameGenerator":32,"./welcome_page/WelcomePage":33,"events":89}],9:[function(require,module,exports){
  1728. var CanvasUtil = require("./CanvasUtils");
  1729. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  1730. function initActiveSpeakerAudioLevels() {
  1731. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  1732. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  1733. // Draw a circle.
  1734. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  1735. // Add a shadow around the circle
  1736. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  1737. ASDrawContext.shadowOffsetX = 0;
  1738. ASDrawContext.shadowOffsetY = 0;
  1739. }
  1740. /**
  1741. * The audio Levels plugin.
  1742. */
  1743. var AudioLevels = (function(my) {
  1744. var audioLevelCanvasCache = {};
  1745. my.LOCAL_LEVEL = 'local';
  1746. my.init = function () {
  1747. initActiveSpeakerAudioLevels();
  1748. }
  1749. /**
  1750. * Updates the audio level canvas for the given peerJid. If the canvas
  1751. * didn't exist we create it.
  1752. */
  1753. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  1754. var resourceJid = null;
  1755. var videoSpanId = null;
  1756. if (!peerJid)
  1757. videoSpanId = 'localVideoContainer';
  1758. else {
  1759. resourceJid = Strophe.getResourceFromJid(peerJid);
  1760. videoSpanId = 'participant_' + resourceJid;
  1761. }
  1762. var videoSpan = document.getElementById(videoSpanId);
  1763. if (!videoSpan) {
  1764. if (resourceJid)
  1765. console.error("No video element for jid", resourceJid);
  1766. else
  1767. console.error("No video element for local video.");
  1768. return;
  1769. }
  1770. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  1771. var videoSpaceWidth = $('#remoteVideos').width();
  1772. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  1773. var thumbnailWidth = thumbnailSize[0];
  1774. var thumbnailHeight = thumbnailSize[1];
  1775. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  1776. audioLevelCanvas = document.createElement('canvas');
  1777. audioLevelCanvas.className = "audiolevel";
  1778. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1779. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1780. resizeAudioLevelCanvas( audioLevelCanvas,
  1781. thumbnailWidth,
  1782. thumbnailHeight);
  1783. videoSpan.appendChild(audioLevelCanvas);
  1784. } else {
  1785. audioLevelCanvas = audioLevelCanvas.get(0);
  1786. resizeAudioLevelCanvas( audioLevelCanvas,
  1787. thumbnailWidth,
  1788. thumbnailHeight);
  1789. }
  1790. };
  1791. /**
  1792. * Updates the audio level UI for the given resourceJid.
  1793. *
  1794. * @param resourceJid the resource jid indicating the video element for
  1795. * which we draw the audio level
  1796. * @param audioLevel the newAudio level to render
  1797. */
  1798. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  1799. drawAudioLevelCanvas(resourceJid, audioLevel);
  1800. var videoSpanId = getVideoSpanId(resourceJid);
  1801. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  1802. if (!audioLevelCanvas)
  1803. return;
  1804. var drawContext = audioLevelCanvas.getContext('2d');
  1805. var canvasCache = audioLevelCanvasCache[resourceJid];
  1806. drawContext.clearRect (0, 0,
  1807. audioLevelCanvas.width, audioLevelCanvas.height);
  1808. drawContext.drawImage(canvasCache, 0, 0);
  1809. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  1810. if(!APP.xmpp.myJid()) {
  1811. return;
  1812. }
  1813. resourceJid = APP.xmpp.myResource();
  1814. }
  1815. if(resourceJid === largeVideoResourceJid) {
  1816. window.requestAnimationFrame(function () {
  1817. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  1818. });
  1819. }
  1820. };
  1821. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  1822. if($("#activeSpeaker").css("visibility") == "hidden")
  1823. return;
  1824. ASDrawContext.clearRect(0, 0, 300, 300);
  1825. if(audioLevel == 0)
  1826. return;
  1827. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  1828. // Fill the shape.
  1829. ASDrawContext.fill();
  1830. };
  1831. /**
  1832. * Resizes the given audio level canvas to match the given thumbnail size.
  1833. */
  1834. function resizeAudioLevelCanvas(audioLevelCanvas,
  1835. thumbnailWidth,
  1836. thumbnailHeight) {
  1837. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  1838. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  1839. }
  1840. /**
  1841. * Draws the audio level canvas into the cached canvas object.
  1842. *
  1843. * @param resourceJid the resource jid indicating the video element for
  1844. * which we draw the audio level
  1845. * @param audioLevel the newAudio level to render
  1846. */
  1847. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  1848. if (!audioLevelCanvasCache[resourceJid]) {
  1849. var videoSpanId = getVideoSpanId(resourceJid);
  1850. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  1851. /*
  1852. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  1853. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  1854. * error. Since audio levels are frequently updated, the errors have
  1855. * been observed to pile into the console, strain the CPU.
  1856. */
  1857. if (audioLevelCanvasOrig)
  1858. {
  1859. audioLevelCanvasCache[resourceJid]
  1860. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  1861. }
  1862. }
  1863. var canvas = audioLevelCanvasCache[resourceJid];
  1864. if (!canvas)
  1865. return;
  1866. var drawContext = canvas.getContext('2d');
  1867. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  1868. var shadowLevel = getShadowLevel(audioLevel);
  1869. if (shadowLevel > 0)
  1870. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  1871. CanvasUtil.drawRoundRectGlow( drawContext,
  1872. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  1873. canvas.width - interfaceConfig.CANVAS_EXTRA,
  1874. canvas.height - interfaceConfig.CANVAS_EXTRA,
  1875. interfaceConfig.CANVAS_RADIUS,
  1876. interfaceConfig.SHADOW_COLOR,
  1877. shadowLevel);
  1878. }
  1879. /**
  1880. * Returns the shadow/glow level for the given audio level.
  1881. *
  1882. * @param audioLevel the audio level from which we determine the shadow
  1883. * level
  1884. */
  1885. function getShadowLevel (audioLevel) {
  1886. var shadowLevel = 0;
  1887. if (audioLevel <= 0.3) {
  1888. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  1889. }
  1890. else if (audioLevel <= 0.6) {
  1891. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  1892. }
  1893. else {
  1894. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  1895. }
  1896. return shadowLevel;
  1897. }
  1898. /**
  1899. * Returns the video span id corresponding to the given resourceJid or local
  1900. * user.
  1901. */
  1902. function getVideoSpanId(resourceJid) {
  1903. var videoSpanId = null;
  1904. if (resourceJid === AudioLevels.LOCAL_LEVEL
  1905. || (APP.xmpp.myResource() && resourceJid
  1906. === APP.xmpp.myResource()))
  1907. videoSpanId = 'localVideoContainer';
  1908. else
  1909. videoSpanId = 'participant_' + resourceJid;
  1910. return videoSpanId;
  1911. }
  1912. /**
  1913. * Indicates that the remote video has been resized.
  1914. */
  1915. $(document).bind('remotevideo.resized', function (event, width, height) {
  1916. var resized = false;
  1917. $('#remoteVideos>span>canvas').each(function() {
  1918. var canvas = $(this).get(0);
  1919. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  1920. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  1921. resized = true;
  1922. }
  1923. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  1924. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  1925. resized = true;
  1926. }
  1927. });
  1928. if (resized)
  1929. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  1930. audioLevelCanvasCache[resourceJid].width
  1931. = width + interfaceConfig.CANVAS_EXTRA;
  1932. audioLevelCanvasCache[resourceJid].height
  1933. = height + interfaceConfig.CANVAS_EXTRA;
  1934. });
  1935. });
  1936. return my;
  1937. })(AudioLevels || {});
  1938. module.exports = AudioLevels;
  1939. },{"./CanvasUtils":10}],10:[function(require,module,exports){
  1940. /**
  1941. * Utility class for drawing canvas shapes.
  1942. */
  1943. var CanvasUtil = (function(my) {
  1944. /**
  1945. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  1946. * of the glow.
  1947. *
  1948. * @param drawContext the context of the canvas to draw to
  1949. * @param x the x coordinate of the round rectangle
  1950. * @param y the y coordinate of the round rectangle
  1951. * @param w the width of the round rectangle
  1952. * @param h the height of the round rectangle
  1953. * @param glowColor the color of the glow
  1954. * @param glowWidth the width of the glow
  1955. */
  1956. my.drawRoundRectGlow
  1957. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  1958. // Save the previous state of the context.
  1959. drawContext.save();
  1960. if (w < 2 * r) r = w / 2;
  1961. if (h < 2 * r) r = h / 2;
  1962. // Draw a round rectangle.
  1963. drawContext.beginPath();
  1964. drawContext.moveTo(x+r, y);
  1965. drawContext.arcTo(x+w, y, x+w, y+h, r);
  1966. drawContext.arcTo(x+w, y+h, x, y+h, r);
  1967. drawContext.arcTo(x, y+h, x, y, r);
  1968. drawContext.arcTo(x, y, x+w, y, r);
  1969. drawContext.closePath();
  1970. // Add a shadow around the rectangle
  1971. drawContext.shadowColor = glowColor;
  1972. drawContext.shadowBlur = glowWidth;
  1973. drawContext.shadowOffsetX = 0;
  1974. drawContext.shadowOffsetY = 0;
  1975. // Fill the shape.
  1976. drawContext.fill();
  1977. drawContext.save();
  1978. drawContext.restore();
  1979. // 1) Uncomment this line to use Composite Operation, which is doing the
  1980. // same as the clip function below and is also antialiasing the round
  1981. // border, but is said to be less fast performance wise.
  1982. // drawContext.globalCompositeOperation='destination-out';
  1983. drawContext.beginPath();
  1984. drawContext.moveTo(x+r, y);
  1985. drawContext.arcTo(x+w, y, x+w, y+h, r);
  1986. drawContext.arcTo(x+w, y+h, x, y+h, r);
  1987. drawContext.arcTo(x, y+h, x, y, r);
  1988. drawContext.arcTo(x, y, x+w, y, r);
  1989. drawContext.closePath();
  1990. // 2) Uncomment this line to use Composite Operation, which is doing the
  1991. // same as the clip function below and is also antialiasing the round
  1992. // border, but is said to be less fast performance wise.
  1993. // drawContext.fill();
  1994. // Comment these two lines if choosing to do the same with composite
  1995. // operation above 1 and 2.
  1996. drawContext.clip();
  1997. drawContext.clearRect(0, 0, 277, 200);
  1998. // Restore the previous context state.
  1999. drawContext.restore();
  2000. };
  2001. /**
  2002. * Clones the given canvas.
  2003. *
  2004. * @return the new cloned canvas.
  2005. */
  2006. my.cloneCanvas = function (oldCanvas) {
  2007. /*
  2008. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2009. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2010. * levels are frequently updated, the errors have been observed to pile
  2011. * into the console, strain the CPU.
  2012. */
  2013. if (!oldCanvas)
  2014. return oldCanvas;
  2015. //create a new canvas
  2016. var newCanvas = document.createElement('canvas');
  2017. var context = newCanvas.getContext('2d');
  2018. //set dimensions
  2019. newCanvas.width = oldCanvas.width;
  2020. newCanvas.height = oldCanvas.height;
  2021. //apply the old canvas to the new one
  2022. context.drawImage(oldCanvas, 0, 0);
  2023. //return the new canvas
  2024. return newCanvas;
  2025. };
  2026. return my;
  2027. })(CanvasUtil || {});
  2028. module.exports = CanvasUtil;
  2029. },{}],11:[function(require,module,exports){
  2030. /* Initial "authentication required" dialog */
  2031. var authDialog = null;
  2032. /* Loop retry ID that wits for other user to create the room */
  2033. var authRetryId = null;
  2034. var authenticationWindow = null;
  2035. var Authentication = {
  2036. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2037. // This is the loop that will wait for the room to be created by
  2038. // someone else. 'auth_required.moderator' will bring us back here.
  2039. authRetryId = window.setTimeout(intervalCallback , 5000);
  2040. // Show prompt only if it's not open
  2041. if (authDialog !== null) {
  2042. return;
  2043. }
  2044. // extract room name from 'room@muc.server.net'
  2045. var room = roomName.substr(0, roomName.indexOf('@'));
  2046. var title = APP.translation.generateTranslatonHTML("dialog.Stop",
  2047. "Stop");
  2048. var defMsg = 'Authentication is required to create room:<br/><b>' +
  2049. room +
  2050. '</b></br> You can either authenticate to create the room or ' +
  2051. 'just wait for someone else to do so.';
  2052. var msg = APP.translation.generateTranslatonHTML("dialog.AuthMsg",
  2053. defMsg, {room: room});
  2054. var button = APP.translation.generateTranslatonHTML(
  2055. "dialog.Authenticate", "Authenticate");
  2056. var buttons = {};
  2057. buttons.authenticate = {title: button, value: "authNow"};
  2058. authDialog = APP.UI.messageHandler.openDialog(
  2059. title,
  2060. msg,
  2061. true,
  2062. buttons,
  2063. function (onSubmitEvent, submitValue) {
  2064. // Do not close the dialog yet
  2065. onSubmitEvent.preventDefault();
  2066. // Open login popup
  2067. if (submitValue === 'authNow') {
  2068. callback();
  2069. }
  2070. }
  2071. );
  2072. },
  2073. closeAuthenticationWindow:function () {
  2074. if (authenticationWindow) {
  2075. authenticationWindow.close();
  2076. authenticationWindow = null;
  2077. }
  2078. },
  2079. focusAuthenticationWindow: function () {
  2080. // If auth window exists just bring it to the front
  2081. if (authenticationWindow) {
  2082. authenticationWindow.focus();
  2083. return;
  2084. }
  2085. },
  2086. closeAuthenticationDialog: function () {
  2087. // Close authentication dialog if opened
  2088. if (authDialog) {
  2089. APP.UI.messageHandler.closeDialog();
  2090. authDialog = null;
  2091. }
  2092. },
  2093. createAuthenticationWindow: function (callback, url) {
  2094. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2095. url, 910, 660,
  2096. // On closed
  2097. function () {
  2098. // Close authentication dialog if opened
  2099. if (authDialog) {
  2100. messageHandler.closeDialog();
  2101. authDialog = null;
  2102. }
  2103. callback();
  2104. authenticationWindow = null;
  2105. });
  2106. return authenticationWindow;
  2107. },
  2108. stopInterval: function () {
  2109. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2110. if (authRetryId) {
  2111. window.clearTimeout(authRetryId);
  2112. authRetryId = null;
  2113. }
  2114. }
  2115. };
  2116. module.exports = Authentication;
  2117. },{}],12:[function(require,module,exports){
  2118. var Settings = require("../../settings/Settings");
  2119. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2120. var users = {};
  2121. var activeSpeakerJid;
  2122. function setVisibility(selector, show) {
  2123. if (selector && selector.length > 0) {
  2124. selector.css("visibility", show ? "visible" : "hidden");
  2125. }
  2126. }
  2127. function isUserMuted(jid) {
  2128. // XXX(gp) we may want to rename this method to something like
  2129. // isUserStreaming, for example.
  2130. if (jid && jid != APP.xmpp.myJid()) {
  2131. var resource = Strophe.getResourceFromJid(jid);
  2132. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2133. return true;
  2134. }
  2135. }
  2136. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2137. return null;
  2138. }
  2139. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2140. }
  2141. function getGravatarUrl(id, size) {
  2142. if(id === APP.xmpp.myJid() || !id) {
  2143. id = Settings.getSettings().uid;
  2144. }
  2145. return 'https://www.gravatar.com/avatar/' +
  2146. MD5.hexdigest(id.trim().toLowerCase()) +
  2147. "?d=wavatar&size=" + (size || "30");
  2148. }
  2149. var Avatar = {
  2150. /**
  2151. * Sets the user's avatar in the settings menu(if local user), contact list
  2152. * and thumbnail
  2153. * @param jid jid of the user
  2154. * @param id email or userID to be used as a hash
  2155. */
  2156. setUserAvatar: function (jid, id) {
  2157. if (id) {
  2158. if (users[jid] === id) {
  2159. return;
  2160. }
  2161. users[jid] = id;
  2162. }
  2163. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2164. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2165. var resourceJid = Strophe.getResourceFromJid(jid);
  2166. var thumbnail = $('#participant_' + resourceJid);
  2167. var avatar = $('#avatar_' + resourceJid);
  2168. // set the avatar in the settings menu if it is local user and get the
  2169. // local video container
  2170. if (jid === APP.xmpp.myJid()) {
  2171. $('#avatar').get(0).src = thumbUrl;
  2172. thumbnail = $('#localVideoContainer');
  2173. }
  2174. // set the avatar in the contact list
  2175. var contact = $('#' + resourceJid + '>img');
  2176. if (contact && contact.length > 0) {
  2177. contact.get(0).src = contactListUrl;
  2178. }
  2179. // set the avatar in the thumbnail
  2180. if (avatar && avatar.length > 0) {
  2181. avatar[0].src = thumbUrl;
  2182. } else {
  2183. if (thumbnail && thumbnail.length > 0) {
  2184. avatar = document.createElement('img');
  2185. avatar.id = 'avatar_' + resourceJid;
  2186. avatar.className = 'userAvatar';
  2187. avatar.src = thumbUrl;
  2188. thumbnail.append(avatar);
  2189. }
  2190. }
  2191. //if the user is the current active speaker - update the active speaker
  2192. // avatar
  2193. if (jid === activeSpeakerJid) {
  2194. this.updateActiveSpeakerAvatarSrc(jid);
  2195. }
  2196. },
  2197. /**
  2198. * Hides or shows the user's avatar
  2199. * @param jid jid of the user
  2200. * @param show whether we should show the avatar or not
  2201. * video because there is no dominant speaker and no focused speaker
  2202. */
  2203. showUserAvatar: function (jid, show) {
  2204. if (users[jid]) {
  2205. var resourceJid = Strophe.getResourceFromJid(jid);
  2206. var video = $('#participant_' + resourceJid + '>video');
  2207. var avatar = $('#avatar_' + resourceJid);
  2208. if (jid === APP.xmpp.myJid()) {
  2209. video = $('#localVideoWrapper>video');
  2210. }
  2211. if (show === undefined || show === null) {
  2212. show = isUserMuted(jid);
  2213. }
  2214. //if the user is the currently focused, the dominant speaker or if
  2215. //there is no focused and no dominant speaker and the large video is
  2216. //currently shown
  2217. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2218. setVisibility($("#largeVideo"), !show);
  2219. setVisibility($('#activeSpeaker'), show);
  2220. setVisibility(avatar, false);
  2221. setVisibility(video, false);
  2222. } else {
  2223. if (video && video.length > 0) {
  2224. setVisibility(video, !show);
  2225. setVisibility(avatar, show);
  2226. }
  2227. }
  2228. }
  2229. },
  2230. /**
  2231. * Updates the src of the active speaker avatar
  2232. * @param jid of the current active speaker
  2233. */
  2234. updateActiveSpeakerAvatarSrc: function (jid) {
  2235. if (!jid) {
  2236. jid = APP.xmpp.findJidFromResource(
  2237. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2238. }
  2239. var avatar = $("#activeSpeakerAvatar")[0];
  2240. var url = getGravatarUrl(users[jid],
  2241. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2242. if (jid === activeSpeakerJid && avatar.src === url) {
  2243. return;
  2244. }
  2245. activeSpeakerJid = jid;
  2246. var isMuted = isUserMuted(jid);
  2247. if (jid && isMuted !== null) {
  2248. avatar.src = url;
  2249. setVisibility($("#largeVideo"), !isMuted);
  2250. Avatar.showUserAvatar(jid, isMuted);
  2251. }
  2252. }
  2253. };
  2254. module.exports = Avatar;
  2255. },{"../../../service/RTC/MediaStreamTypes":78,"../../settings/Settings":37,"../videolayout/VideoLayout":31}],13:[function(require,module,exports){
  2256. /* global $, config,
  2257. setLargeVideoVisible, Util */
  2258. var VideoLayout = require("../videolayout/VideoLayout");
  2259. var Prezi = require("../prezi/Prezi");
  2260. var UIUtil = require("../util/UIUtil");
  2261. var etherpadName = null;
  2262. var etherpadIFrame = null;
  2263. var domain = null;
  2264. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2265. /**
  2266. * Resizes the etherpad.
  2267. */
  2268. function resize() {
  2269. if ($('#etherpad>iframe').length) {
  2270. var remoteVideos = $('#remoteVideos');
  2271. var availableHeight
  2272. = window.innerHeight - remoteVideos.outerHeight();
  2273. var availableWidth = UIUtil.getAvailableVideoWidth();
  2274. $('#etherpad>iframe').width(availableWidth);
  2275. $('#etherpad>iframe').height(availableHeight);
  2276. }
  2277. }
  2278. /**
  2279. * Shares the Etherpad name with other participants.
  2280. */
  2281. function shareEtherpad() {
  2282. APP.xmpp.addToPresence("etherpad", etherpadName);
  2283. }
  2284. /**
  2285. * Creates the Etherpad button and adds it to the toolbar.
  2286. */
  2287. function enableEtherpadButton() {
  2288. if (!$('#etherpadButton').is(":visible"))
  2289. $('#etherpadButton').css({display: 'inline-block'});
  2290. }
  2291. /**
  2292. * Creates the IFrame for the etherpad.
  2293. */
  2294. function createIFrame() {
  2295. etherpadIFrame = document.createElement('iframe');
  2296. etherpadIFrame.src = domain + etherpadName + options;
  2297. etherpadIFrame.frameBorder = 0;
  2298. etherpadIFrame.scrolling = "no";
  2299. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2300. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2301. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2302. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2303. etherpadIFrame.onload = function() {
  2304. document.domain = document.domain;
  2305. bubbleIframeMouseMove(etherpadIFrame);
  2306. setTimeout(function() {
  2307. // the iframes inside of the etherpad are
  2308. // not yet loaded when the etherpad iframe is loaded
  2309. var outer = etherpadIFrame.
  2310. contentDocument.getElementsByName("ace_outer")[0];
  2311. bubbleIframeMouseMove(outer);
  2312. var inner = outer.
  2313. contentDocument.getElementsByName("ace_inner")[0];
  2314. bubbleIframeMouseMove(inner);
  2315. }, 2000);
  2316. };
  2317. }
  2318. function bubbleIframeMouseMove(iframe){
  2319. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2320. iframe.contentWindow.onmousemove = function(e){
  2321. if(existingOnMouseMove) existingOnMouseMove(e);
  2322. var evt = document.createEvent("MouseEvents");
  2323. var boundingClientRect = iframe.getBoundingClientRect();
  2324. evt.initMouseEvent(
  2325. "mousemove",
  2326. true, // bubbles
  2327. false, // not cancelable
  2328. window,
  2329. e.detail,
  2330. e.screenX,
  2331. e.screenY,
  2332. e.clientX + boundingClientRect.left,
  2333. e.clientY + boundingClientRect.top,
  2334. e.ctrlKey,
  2335. e.altKey,
  2336. e.shiftKey,
  2337. e.metaKey,
  2338. e.button,
  2339. null // no related element
  2340. );
  2341. iframe.dispatchEvent(evt);
  2342. };
  2343. }
  2344. /**
  2345. * On video selected event.
  2346. */
  2347. $(document).bind('video.selected', function (event, isPresentation) {
  2348. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2349. Etherpad.toggleEtherpad(isPresentation);
  2350. });
  2351. var Etherpad = {
  2352. /**
  2353. * Initializes the etherpad.
  2354. */
  2355. init: function (name) {
  2356. if (config.etherpad_base && !etherpadName) {
  2357. domain = config.etherpad_base;
  2358. if (!name) {
  2359. // In case we're the focus we generate the name.
  2360. etherpadName = Math.random().toString(36).substring(7) +
  2361. '_' + (new Date().getTime()).toString();
  2362. shareEtherpad();
  2363. }
  2364. else
  2365. etherpadName = name;
  2366. enableEtherpadButton();
  2367. /**
  2368. * Resizes the etherpad, when the window is resized.
  2369. */
  2370. $(window).resize(function () {
  2371. resize();
  2372. });
  2373. }
  2374. },
  2375. /**
  2376. * Opens/hides the Etherpad.
  2377. */
  2378. toggleEtherpad: function (isPresentation) {
  2379. if (!etherpadIFrame)
  2380. createIFrame();
  2381. var largeVideo = null;
  2382. if (Prezi.isPresentationVisible())
  2383. largeVideo = $('#presentation>iframe');
  2384. else
  2385. largeVideo = $('#largeVideo');
  2386. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2387. $('#activeSpeaker').css('visibility', 'hidden');
  2388. largeVideo.fadeOut(300, function () {
  2389. if (Prezi.isPresentationVisible()) {
  2390. largeVideo.css({opacity: '0'});
  2391. } else {
  2392. VideoLayout.setLargeVideoVisible(false);
  2393. }
  2394. });
  2395. $('#etherpad>iframe').fadeIn(300, function () {
  2396. document.body.style.background = '#eeeeee';
  2397. $('#etherpad>iframe').css({visibility: 'visible'});
  2398. $('#etherpad').css({zIndex: 2});
  2399. });
  2400. }
  2401. else if ($('#etherpad>iframe')) {
  2402. $('#etherpad>iframe').fadeOut(300, function () {
  2403. $('#etherpad>iframe').css({visibility: 'hidden'});
  2404. $('#etherpad').css({zIndex: 0});
  2405. document.body.style.background = 'black';
  2406. });
  2407. if (!isPresentation) {
  2408. $('#largeVideo').fadeIn(300, function () {
  2409. VideoLayout.setLargeVideoVisible(true);
  2410. });
  2411. }
  2412. }
  2413. resize();
  2414. },
  2415. isVisible: function() {
  2416. var etherpadIframe = $('#etherpad>iframe');
  2417. return etherpadIframe && etherpadIframe.is(':visible');
  2418. }
  2419. };
  2420. module.exports = Etherpad;
  2421. },{"../prezi/Prezi":14,"../util/UIUtil":29,"../videolayout/VideoLayout":31}],14:[function(require,module,exports){
  2422. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2423. var UIUtil = require("../util/UIUtil");
  2424. var VideoLayout = require("../videolayout/VideoLayout");
  2425. var messageHandler = require("../util/MessageHandler");
  2426. var PreziPlayer = require("./PreziPlayer");
  2427. var preziPlayer = null;
  2428. var Prezi = {
  2429. /**
  2430. * Reloads the current presentation.
  2431. */
  2432. reloadPresentation: function() {
  2433. var iframe = document.getElementById(preziPlayer.options.preziId);
  2434. iframe.src = iframe.src;
  2435. },
  2436. /**
  2437. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2438. * otherwise.
  2439. */
  2440. isPresentationVisible: function () {
  2441. return ($('#presentation>iframe') != null
  2442. && $('#presentation>iframe').css('opacity') == 1);
  2443. },
  2444. /**
  2445. * Opens the Prezi dialog, from which the user could choose a presentation
  2446. * to load.
  2447. */
  2448. openPreziDialog: function() {
  2449. var myprezi = APP.xmpp.getPrezi();
  2450. if (myprezi) {
  2451. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  2452. "Remove Prezi", "dialog.removePreziMsg",
  2453. "Are you sure you would like to remove your Prezi?",
  2454. false,
  2455. "dialog.Remove",
  2456. function(e,v,m,f) {
  2457. if(v) {
  2458. APP.xmpp.removePreziFromPresence();
  2459. }
  2460. }
  2461. );
  2462. }
  2463. else if (preziPlayer != null) {
  2464. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  2465. "Share a Prezi", "dialog.sharePreziMsg",
  2466. "Another participant is already sharing a Prezi." +
  2467. "This conference allows only one Prezi at a time.",
  2468. false,
  2469. "dialog.Ok",
  2470. function(e,v,m,f) {
  2471. $.prompt.close();
  2472. }
  2473. );
  2474. }
  2475. else {
  2476. var html = APP.translation.generateTranslatonHTML(
  2477. "dialog.sharePreziTitle", "Share a Prezi");
  2478. var cancelButton = APP.translation.generateTranslatonHTML(
  2479. "dialog.Cancel", "Cancel");
  2480. var shareButton = APP.translation.generateTranslatonHTML(
  2481. "dialog.Share", "Share");
  2482. var backButton = APP.translation.generateTranslatonHTML(
  2483. "dialog.Back", "Back");
  2484. var buttons = {};
  2485. var buttons1 = {};
  2486. buttons1.button1 = buttons.button1 = {title: cancelButton, value: false};
  2487. buttons.button2 = {title: shareButton, value: true};
  2488. buttons1.button2 = {title: backButton, value: true};
  2489. var linkError = APP.translation.generateTranslatonHTML(
  2490. "dialog.preziLinkError", "Please provide a correct prezi link.")
  2491. var openPreziState = {
  2492. state0: {
  2493. html: '<h2>' + html + '</h2>' +
  2494. '<input id="preziUrl" type="text" ' +
  2495. 'placeholder="e.g. ' +
  2496. 'http://prezi.com/wz7vhjycl7e6/my-prezi" autofocus>',
  2497. persistent: false,
  2498. buttons: buttons,
  2499. defaultButton: 1,
  2500. submit: function(e,v,m,f){
  2501. e.preventDefault();
  2502. if(v)
  2503. {
  2504. var preziUrl = document.getElementById('preziUrl');
  2505. if (preziUrl.value)
  2506. {
  2507. var urlValue
  2508. = encodeURI(UIUtil.escapeHtml(preziUrl.value));
  2509. if (urlValue.indexOf('http://prezi.com/') != 0
  2510. && urlValue.indexOf('https://prezi.com/') != 0)
  2511. {
  2512. $.prompt.goToState('state1');
  2513. return false;
  2514. }
  2515. else {
  2516. var presIdTmp = urlValue.substring(
  2517. urlValue.indexOf("prezi.com/") + 10);
  2518. if (!isAlphanumeric(presIdTmp)
  2519. || presIdTmp.indexOf('/') < 2) {
  2520. $.prompt.goToState('state1');
  2521. return false;
  2522. }
  2523. else {
  2524. APP.xmpp.addToPresence("prezi", urlValue);
  2525. $.prompt.close();
  2526. }
  2527. }
  2528. }
  2529. }
  2530. else
  2531. $.prompt.close();
  2532. }
  2533. },
  2534. state1: {
  2535. html: '<h2>' + html + '</h2>' +
  2536. linkError,
  2537. persistent: false,
  2538. buttons: buttons1,
  2539. defaultButton: 1,
  2540. submit:function(e,v,m,f) {
  2541. e.preventDefault();
  2542. if(v==0)
  2543. $.prompt.close();
  2544. else
  2545. $.prompt.goToState('state0');
  2546. }
  2547. }
  2548. };
  2549. var focusPreziUrl = function(e) {
  2550. document.getElementById('preziUrl').focus();
  2551. };
  2552. messageHandler.openDialogWithStates(openPreziState, focusPreziUrl, focusPreziUrl);
  2553. }
  2554. }
  2555. };
  2556. /**
  2557. * A new presentation has been added.
  2558. *
  2559. * @param event the event indicating the add of a presentation
  2560. * @param jid the jid from which the presentation was added
  2561. * @param presUrl url of the presentation
  2562. * @param currentSlide the current slide to which we should move
  2563. */
  2564. function presentationAdded(event, jid, presUrl, currentSlide) {
  2565. console.log("presentation added", presUrl);
  2566. var presId = getPresentationId(presUrl);
  2567. var elementId = 'participant_'
  2568. + Strophe.getResourceFromJid(jid)
  2569. + '_' + presId;
  2570. // We explicitly don't specify the peer jid here, because we don't want
  2571. // this video to be dealt with as a peer related one (for example we
  2572. // don't want to show a mute/kick menu for this one, etc.).
  2573. VideoLayout.addRemoteVideoContainer(null, elementId);
  2574. VideoLayout.resizeThumbnails();
  2575. var controlsEnabled = false;
  2576. if (jid === APP.xmpp.myJid())
  2577. controlsEnabled = true;
  2578. setPresentationVisible(true);
  2579. $('#largeVideoContainer').hover(
  2580. function (event) {
  2581. if (Prezi.isPresentationVisible()) {
  2582. var reloadButtonRight = window.innerWidth
  2583. - $('#presentation>iframe').offset().left
  2584. - $('#presentation>iframe').width();
  2585. $('#reloadPresentation').css({ right: reloadButtonRight,
  2586. display:'inline-block'});
  2587. }
  2588. },
  2589. function (event) {
  2590. if (!Prezi.isPresentationVisible())
  2591. $('#reloadPresentation').css({display:'none'});
  2592. else {
  2593. var e = event.toElement || event.relatedTarget;
  2594. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  2595. $('#reloadPresentation').css({display:'none'});
  2596. }
  2597. });
  2598. preziPlayer = new PreziPlayer(
  2599. 'presentation',
  2600. {preziId: presId,
  2601. width: getPresentationWidth(),
  2602. height: getPresentationHeihgt(),
  2603. controls: controlsEnabled,
  2604. debug: true
  2605. });
  2606. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  2607. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  2608. console.log("prezi status", event.value);
  2609. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  2610. if (jid != APP.xmpp.myJid())
  2611. preziPlayer.flyToStep(currentSlide);
  2612. }
  2613. });
  2614. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  2615. console.log("event value", event.value);
  2616. APP.xmpp.addToPresence("preziSlide", event.value);
  2617. });
  2618. $("#" + elementId).css( 'background-image',
  2619. 'url(../images/avatarprezi.png)');
  2620. $("#" + elementId).click(
  2621. function () {
  2622. setPresentationVisible(true);
  2623. }
  2624. );
  2625. };
  2626. /**
  2627. * A presentation has been removed.
  2628. *
  2629. * @param event the event indicating the remove of a presentation
  2630. * @param jid the jid for which the presentation was removed
  2631. * @param the url of the presentation
  2632. */
  2633. function presentationRemoved(event, jid, presUrl) {
  2634. console.log('presentation removed', presUrl);
  2635. var presId = getPresentationId(presUrl);
  2636. setPresentationVisible(false);
  2637. $('#participant_'
  2638. + Strophe.getResourceFromJid(jid)
  2639. + '_' + presId).remove();
  2640. $('#presentation>iframe').remove();
  2641. if (preziPlayer != null) {
  2642. preziPlayer.destroy();
  2643. preziPlayer = null;
  2644. }
  2645. };
  2646. /**
  2647. * Indicates if the given string is an alphanumeric string.
  2648. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  2649. * purpose of checking URIs.
  2650. */
  2651. function isAlphanumeric(unsafeText) {
  2652. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  2653. return regex.test(unsafeText);
  2654. }
  2655. /**
  2656. * Returns the presentation id from the given url.
  2657. */
  2658. function getPresentationId (presUrl) {
  2659. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  2660. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  2661. }
  2662. /**
  2663. * Returns the presentation width.
  2664. */
  2665. function getPresentationWidth() {
  2666. var availableWidth = UIUtil.getAvailableVideoWidth();
  2667. var availableHeight = getPresentationHeihgt();
  2668. var aspectRatio = 16.0 / 9.0;
  2669. if (availableHeight < availableWidth / aspectRatio) {
  2670. availableWidth = Math.floor(availableHeight * aspectRatio);
  2671. }
  2672. return availableWidth;
  2673. }
  2674. /**
  2675. * Returns the presentation height.
  2676. */
  2677. function getPresentationHeihgt() {
  2678. var remoteVideos = $('#remoteVideos');
  2679. return window.innerHeight - remoteVideos.outerHeight();
  2680. }
  2681. /**
  2682. * Resizes the presentation iframe.
  2683. */
  2684. function resize() {
  2685. if ($('#presentation>iframe')) {
  2686. $('#presentation>iframe').width(getPresentationWidth());
  2687. $('#presentation>iframe').height(getPresentationHeihgt());
  2688. }
  2689. }
  2690. /**
  2691. * Shows/hides a presentation.
  2692. */
  2693. function setPresentationVisible(visible) {
  2694. var prezi = $('#presentation>iframe');
  2695. if (visible) {
  2696. // Trigger the video.selected event to indicate a change in the
  2697. // large video.
  2698. $(document).trigger("video.selected", [true]);
  2699. $('#largeVideo').fadeOut(300);
  2700. prezi.fadeIn(300, function() {
  2701. prezi.css({opacity:'1'});
  2702. ToolbarToggler.dockToolbar(true);
  2703. VideoLayout.setLargeVideoVisible(false);
  2704. });
  2705. $('#activeSpeaker').css('visibility', 'hidden');
  2706. }
  2707. else {
  2708. if (prezi.css('opacity') == '1') {
  2709. prezi.fadeOut(300, function () {
  2710. prezi.css({opacity:'0'});
  2711. $('#reloadPresentation').css({display:'none'});
  2712. $('#largeVideo').fadeIn(300, function() {
  2713. VideoLayout.setLargeVideoVisible(true);
  2714. ToolbarToggler.dockToolbar(false);
  2715. });
  2716. });
  2717. }
  2718. }
  2719. }
  2720. /**
  2721. * Presentation has been removed.
  2722. */
  2723. $(document).bind('presentationremoved.muc', presentationRemoved);
  2724. /**
  2725. * Presentation has been added.
  2726. */
  2727. $(document).bind('presentationadded.muc', presentationAdded);
  2728. /*
  2729. * Indicates presentation slide change.
  2730. */
  2731. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  2732. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  2733. preziPlayer.flyToStep(current);
  2734. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  2735. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  2736. preziPlayer.flyToStep(current, i);
  2737. }
  2738. }
  2739. });
  2740. /**
  2741. * On video selected event.
  2742. */
  2743. $(document).bind('video.selected', function (event, isPresentation) {
  2744. if (!isPresentation && $('#presentation>iframe')) {
  2745. setPresentationVisible(false);
  2746. }
  2747. });
  2748. $(window).resize(function () {
  2749. resize();
  2750. });
  2751. module.exports = Prezi;
  2752. },{"../toolbars/ToolbarToggler":25,"../util/MessageHandler":27,"../util/UIUtil":29,"../videolayout/VideoLayout":31,"./PreziPlayer":15}],15:[function(require,module,exports){
  2753. (function() {
  2754. "use strict";
  2755. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  2756. window.PreziPlayer = (function() {
  2757. PreziPlayer.API_VERSION = 1;
  2758. PreziPlayer.CURRENT_STEP = 'currentStep';
  2759. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  2760. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  2761. PreziPlayer.STATUS_LOADING = 'loading';
  2762. PreziPlayer.STATUS_READY = 'ready';
  2763. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  2764. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  2765. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  2766. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  2767. PreziPlayer.EVENT_STATUS = "statusChange";
  2768. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  2769. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  2770. PreziPlayer.domain = "https://prezi.com";
  2771. PreziPlayer.path = "/player/";
  2772. PreziPlayer.players = {};
  2773. PreziPlayer.binded_methods = ['changesHandler'];
  2774. PreziPlayer.createMultiplePlayers = function(optionArray){
  2775. for(var i=0; i<optionArray.length; i++) {
  2776. var optionSet = optionArray[i];
  2777. new PreziPlayer(optionSet.id, optionSet);
  2778. };
  2779. };
  2780. PreziPlayer.messageReceived = function(event){
  2781. var message, item, player;
  2782. try {
  2783. message = JSON.parse(event.data);
  2784. if (message.id && (player = PreziPlayer.players[message.id])) {
  2785. if (player.options.debug === true) {
  2786. if (console && console.log)
  2787. console.log('received', message);
  2788. }
  2789. if (message.type === "changes") {
  2790. player.changesHandler(message);
  2791. }
  2792. for (var i = 0; i < player.callbacks.length; i++) {
  2793. item = player.callbacks[i];
  2794. if (item && message.type === item.event) {
  2795. item.callback(message);
  2796. }
  2797. }
  2798. }
  2799. } catch (e) { }
  2800. };
  2801. function PreziPlayer(id, options) {
  2802. var params, paramString = "", _this = this;
  2803. if (PreziPlayer.players[id]){
  2804. PreziPlayer.players[id].destroy();
  2805. }
  2806. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  2807. var method_name = PreziPlayer.binded_methods[i];
  2808. _this[method_name] = __bind(_this[method_name], _this);
  2809. };
  2810. options = options || {};
  2811. this.options = options;
  2812. this.values = {'status': PreziPlayer.STATUS_LOADING};
  2813. this.values[PreziPlayer.CURRENT_STEP] = 0;
  2814. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  2815. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  2816. this.callbacks = [];
  2817. this.id = id;
  2818. this.embedTo = document.getElementById(id);
  2819. if (!this.embedTo) {
  2820. throw "The element id is not available.";
  2821. }
  2822. this.iframe = document.createElement('iframe');
  2823. params = [
  2824. { name: 'oid', value: options.preziId },
  2825. { name: 'explorable', value: options.explorable ? 1 : 0 },
  2826. { name: 'controls', value: options.controls ? 1 : 0 }
  2827. ];
  2828. for(var i=0; i<params.length; i++) {
  2829. var param = params[i];
  2830. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  2831. };
  2832. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  2833. this.iframe.frameBorder = 0;
  2834. this.iframe.scrolling = "no";
  2835. this.iframe.width = options.width || 640;
  2836. this.iframe.height = options.height || 480;
  2837. this.embedTo.innerHTML = '';
  2838. // JITSI: IN CASE SOMETHING GOES WRONG.
  2839. try {
  2840. this.embedTo.appendChild(this.iframe);
  2841. }
  2842. catch (err) {
  2843. console.log("CATCH ERROR");
  2844. }
  2845. // JITSI: Increase interval from 200 to 500, which fixes prezi
  2846. // crashes for us.
  2847. this.initPollInterval = setInterval(function(){
  2848. _this.sendMessage({'action': 'init'});
  2849. }, 500);
  2850. PreziPlayer.players[id] = this;
  2851. }
  2852. PreziPlayer.prototype.changesHandler = function(message) {
  2853. var key, value, j, item;
  2854. if (this.initPollInterval) {
  2855. clearInterval(this.initPollInterval);
  2856. this.initPollInterval = false;
  2857. }
  2858. for (key in message.data) {
  2859. if (message.data.hasOwnProperty(key)){
  2860. value = message.data[key];
  2861. this.values[key] = value;
  2862. for (j=0; j<this.callbacks.length; j++) {
  2863. item = this.callbacks[j];
  2864. if (item && item.event === key + "Change"){
  2865. item.callback({type: item.event, value: value});
  2866. }
  2867. }
  2868. }
  2869. }
  2870. };
  2871. PreziPlayer.prototype.destroy = function() {
  2872. if (this.initPollInterval) {
  2873. clearInterval(this.initPollInterval);
  2874. this.initPollInterval = false;
  2875. }
  2876. this.embedTo.innerHTML = '';
  2877. };
  2878. PreziPlayer.prototype.sendMessage = function(message) {
  2879. if (this.options.debug === true) {
  2880. if (console && console.log) console.log('sent', message);
  2881. }
  2882. message.version = PreziPlayer.API_VERSION;
  2883. message.id = this.id;
  2884. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  2885. };
  2886. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  2887. PreziPlayer.prototype.flyToNextStep = function() {
  2888. return this.sendMessage({
  2889. 'action': 'present',
  2890. 'data': ['moveToNextStep']
  2891. });
  2892. };
  2893. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  2894. PreziPlayer.prototype.flyToPreviousStep = function() {
  2895. return this.sendMessage({
  2896. 'action': 'present',
  2897. 'data': ['moveToPrevStep']
  2898. });
  2899. };
  2900. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  2901. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  2902. var obj = this;
  2903. // check animation_step
  2904. if (animation_step > 0 &&
  2905. obj.values.animationCountOnSteps &&
  2906. obj.values.animationCountOnSteps[step] <= animation_step) {
  2907. animation_step = obj.values.animationCountOnSteps[step];
  2908. }
  2909. // jump to animation steps by calling flyToNextStep()
  2910. function doAnimationSteps() {
  2911. if (obj.values.isMoving == true) {
  2912. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  2913. return;
  2914. }
  2915. while (animation_step-- > 0) {
  2916. obj.flyToNextStep(); // do the animation steps
  2917. }
  2918. }
  2919. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  2920. // jump to the step
  2921. return this.sendMessage({
  2922. 'action': 'present',
  2923. 'data': ['moveToStep', step]
  2924. });
  2925. };
  2926. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  2927. PreziPlayer.prototype.flyToObject = function(objectId) {
  2928. return this.sendMessage({
  2929. 'action': 'present',
  2930. 'data': ['moveToObject', objectId]
  2931. });
  2932. };
  2933. PreziPlayer.prototype.play = function(defaultDelay) {
  2934. return this.sendMessage({
  2935. 'action': 'present',
  2936. 'data': ['startAutoPlay', defaultDelay]
  2937. });
  2938. };
  2939. PreziPlayer.prototype.stop = function() {
  2940. return this.sendMessage({
  2941. 'action': 'present',
  2942. 'data': ['stopAutoPlay']
  2943. });
  2944. };
  2945. PreziPlayer.prototype.pause = function(defaultDelay) {
  2946. return this.sendMessage({
  2947. 'action': 'present',
  2948. 'data': ['pauseAutoPlay', defaultDelay]
  2949. });
  2950. };
  2951. PreziPlayer.prototype.getCurrentStep = function() {
  2952. return this.values.currentStep;
  2953. };
  2954. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  2955. return this.values.currentAnimationStep;
  2956. };
  2957. PreziPlayer.prototype.getCurrentObject = function() {
  2958. return this.values.currentObject;
  2959. };
  2960. PreziPlayer.prototype.getStatus = function() {
  2961. return this.values.status;
  2962. };
  2963. PreziPlayer.prototype.isPlaying = function() {
  2964. return this.values.isAutoPlaying;
  2965. };
  2966. PreziPlayer.prototype.getStepCount = function() {
  2967. return this.values.stepCount;
  2968. };
  2969. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  2970. return this.values.animationCountOnSteps;
  2971. };
  2972. PreziPlayer.prototype.getTitle = function() {
  2973. return this.values.title;
  2974. };
  2975. PreziPlayer.prototype.setDimensions = function(dims) {
  2976. for (var parameter in dims) {
  2977. this.iframe[parameter] = dims[parameter];
  2978. }
  2979. }
  2980. PreziPlayer.prototype.getDimensions = function() {
  2981. return {
  2982. width: parseInt(this.iframe.width, 10),
  2983. height: parseInt(this.iframe.height, 10)
  2984. }
  2985. }
  2986. PreziPlayer.prototype.on = function(event, callback) {
  2987. this.callbacks.push({
  2988. event: event,
  2989. callback: callback
  2990. });
  2991. };
  2992. PreziPlayer.prototype.off = function(event, callback) {
  2993. var j, item;
  2994. if (event === undefined) {
  2995. this.callbacks = [];
  2996. }
  2997. j = this.callbacks.length;
  2998. while (j--) {
  2999. item = this.callbacks[j];
  3000. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3001. this.callbacks.splice(j, 1);
  3002. }
  3003. }
  3004. };
  3005. if (window.addEventListener) {
  3006. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3007. } else {
  3008. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3009. }
  3010. return PreziPlayer;
  3011. })();
  3012. })();
  3013. module.exports = PreziPlayer;
  3014. },{}],16:[function(require,module,exports){
  3015. var Chat = require("./chat/Chat");
  3016. var ContactList = require("./contactlist/ContactList");
  3017. var Settings = require("./../../settings/Settings");
  3018. var SettingsMenu = require("./settings/SettingsMenu");
  3019. var VideoLayout = require("../videolayout/VideoLayout");
  3020. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3021. var UIUtil = require("../util/UIUtil");
  3022. /**
  3023. * Toggler for the chat, contact list, settings menu, etc..
  3024. */
  3025. var PanelToggler = (function(my) {
  3026. var currentlyOpen = null;
  3027. var buttons = {
  3028. '#chatspace': '#chatBottomButton',
  3029. '#contactlist': '#contactListButton',
  3030. '#settingsmenu': '#settingsButton'
  3031. };
  3032. /**
  3033. * Resizes the video area
  3034. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3035. * @param completeFunction a function to be called when the video space is resized
  3036. */
  3037. var resizeVideoArea = function(isClosing, completeFunction) {
  3038. var videospace = $('#videospace');
  3039. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3040. var videospaceWidth = window.innerWidth - panelSize[0];
  3041. var videospaceHeight = window.innerHeight;
  3042. var videoSize
  3043. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3044. var videoWidth = videoSize[0];
  3045. var videoHeight = videoSize[1];
  3046. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3047. videoHeight,
  3048. videospaceWidth,
  3049. videospaceHeight);
  3050. var horizontalIndent = videoPosition[0];
  3051. var verticalIndent = videoPosition[1];
  3052. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3053. var thumbnailsWidth = thumbnailSize[0];
  3054. var thumbnailsHeight = thumbnailSize[1];
  3055. //for chat
  3056. videospace.animate({
  3057. right: panelSize[0],
  3058. width: videospaceWidth,
  3059. height: videospaceHeight
  3060. },
  3061. {
  3062. queue: false,
  3063. duration: 500,
  3064. complete: completeFunction
  3065. });
  3066. $('#remoteVideos').animate({
  3067. height: thumbnailsHeight
  3068. },
  3069. {
  3070. queue: false,
  3071. duration: 500
  3072. });
  3073. $('#remoteVideos>span').animate({
  3074. height: thumbnailsHeight,
  3075. width: thumbnailsWidth
  3076. },
  3077. {
  3078. queue: false,
  3079. duration: 500,
  3080. complete: function () {
  3081. $(document).trigger(
  3082. "remotevideo.resized",
  3083. [thumbnailsWidth,
  3084. thumbnailsHeight]);
  3085. }
  3086. });
  3087. $('#largeVideoContainer').animate({
  3088. width: videospaceWidth,
  3089. height: videospaceHeight
  3090. },
  3091. {
  3092. queue: false,
  3093. duration: 500
  3094. });
  3095. $('#largeVideo').animate({
  3096. width: videoWidth,
  3097. height: videoHeight,
  3098. top: verticalIndent,
  3099. bottom: verticalIndent,
  3100. left: horizontalIndent,
  3101. right: horizontalIndent
  3102. },
  3103. {
  3104. queue: false,
  3105. duration: 500
  3106. });
  3107. };
  3108. /**
  3109. * Toggles the windows in the side panel
  3110. * @param object the window that should be shown
  3111. * @param selector the selector for the element containing the panel
  3112. * @param onOpenComplete function to be called when the panel is opened
  3113. * @param onOpen function to be called if the window is going to be opened
  3114. * @param onClose function to be called if the window is going to be closed
  3115. */
  3116. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3117. UIUtil.buttonClick(buttons[selector], "active");
  3118. if (object.isVisible()) {
  3119. $("#toast-container").animate({
  3120. right: '5px'
  3121. },
  3122. {
  3123. queue: false,
  3124. duration: 500
  3125. });
  3126. $(selector).hide("slide", {
  3127. direction: "right",
  3128. queue: false,
  3129. duration: 500
  3130. });
  3131. if(typeof onClose === "function") {
  3132. onClose();
  3133. }
  3134. currentlyOpen = null;
  3135. }
  3136. else {
  3137. // Undock the toolbar when the chat is shown and if we're in a
  3138. // video mode.
  3139. if (VideoLayout.isLargeVideoVisible()) {
  3140. ToolbarToggler.dockToolbar(false);
  3141. }
  3142. if(currentlyOpen) {
  3143. var current = $(currentlyOpen);
  3144. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3145. current.css('z-index', 4);
  3146. setTimeout(function () {
  3147. current.css('display', 'none');
  3148. current.css('z-index', 5);
  3149. }, 500);
  3150. }
  3151. $("#toast-container").animate({
  3152. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3153. },
  3154. {
  3155. queue: false,
  3156. duration: 500
  3157. });
  3158. $(selector).show("slide", {
  3159. direction: "right",
  3160. queue: false,
  3161. duration: 500,
  3162. complete: onOpenComplete
  3163. });
  3164. if(typeof onOpen === "function") {
  3165. onOpen();
  3166. }
  3167. currentlyOpen = selector;
  3168. }
  3169. };
  3170. /**
  3171. * Opens / closes the chat area.
  3172. */
  3173. my.toggleChat = function() {
  3174. var chatCompleteFunction = Chat.isVisible() ?
  3175. function() {} : function () {
  3176. Chat.scrollChatToBottom();
  3177. $('#chatspace').trigger('shown');
  3178. };
  3179. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3180. toggle(Chat,
  3181. '#chatspace',
  3182. function () {
  3183. // Request the focus in the nickname field or the chat input field.
  3184. if ($('#nickname').css('visibility') === 'visible') {
  3185. $('#nickinput').focus();
  3186. } else {
  3187. $('#usermsg').focus();
  3188. }
  3189. },
  3190. null,
  3191. Chat.resizeChat,
  3192. null);
  3193. };
  3194. /**
  3195. * Opens / closes the contact list area.
  3196. */
  3197. my.toggleContactList = function () {
  3198. var completeFunction = ContactList.isVisible() ?
  3199. function() {} : function () { $('#contactlist').trigger('shown');};
  3200. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3201. toggle(ContactList,
  3202. '#contactlist',
  3203. null,
  3204. function() {
  3205. ContactList.setVisualNotification(false);
  3206. },
  3207. null);
  3208. };
  3209. /**
  3210. * Opens / closes the settings menu
  3211. */
  3212. my.toggleSettingsMenu = function() {
  3213. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3214. toggle(SettingsMenu,
  3215. '#settingsmenu',
  3216. null,
  3217. function() {
  3218. var settings = Settings.getSettings();
  3219. $('#setDisplayName').get(0).value = settings.displayName;
  3220. $('#setEmail').get(0).value = settings.email;
  3221. },
  3222. null);
  3223. };
  3224. /**
  3225. * Returns the size of the side panel.
  3226. */
  3227. my.getPanelSize = function () {
  3228. var availableHeight = window.innerHeight;
  3229. var availableWidth = window.innerWidth;
  3230. var panelWidth = 200;
  3231. if (availableWidth * 0.2 < 200) {
  3232. panelWidth = availableWidth * 0.2;
  3233. }
  3234. return [panelWidth, availableHeight];
  3235. };
  3236. my.isVisible = function() {
  3237. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3238. };
  3239. return my;
  3240. }(PanelToggler || {}));
  3241. module.exports = PanelToggler;
  3242. },{"../toolbars/ToolbarToggler":25,"../util/UIUtil":29,"../videolayout/VideoLayout":31,"./../../settings/Settings":37,"./chat/Chat":17,"./contactlist/ContactList":21,"./settings/SettingsMenu":22}],17:[function(require,module,exports){
  3243. /* global $, Util, nickname:true */
  3244. var Replacement = require("./Replacement");
  3245. var CommandsProcessor = require("./Commands");
  3246. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3247. var smileys = require("./smileys.json").smileys;
  3248. var NicknameHandler = require("../../util/NicknameHandler");
  3249. var UIUtil = require("../../util/UIUtil");
  3250. var UIEvents = require("../../../../service/UI/UIEvents");
  3251. var notificationInterval = false;
  3252. var unreadMessages = 0;
  3253. /**
  3254. * Shows/hides a visual notification, indicating that a message has arrived.
  3255. */
  3256. function setVisualNotification(show) {
  3257. var unreadMsgElement = document.getElementById('unreadMessages');
  3258. var unreadMsgBottomElement
  3259. = document.getElementById('bottomUnreadMessages');
  3260. var glower = $('#chatButton');
  3261. var bottomGlower = $('#chatBottomButton');
  3262. if (unreadMessages) {
  3263. unreadMsgElement.innerHTML = unreadMessages.toString();
  3264. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3265. ToolbarToggler.dockToolbar(true);
  3266. var chatButtonElement
  3267. = document.getElementById('chatButton').parentNode;
  3268. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3269. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3270. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3271. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3272. unreadMsgElement.setAttribute(
  3273. 'style',
  3274. 'top:' + topIndent +
  3275. '; left:' + leftIndent + ';');
  3276. var chatBottomButtonElement
  3277. = document.getElementById('chatBottomButton').parentNode;
  3278. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3279. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3280. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3281. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3282. unreadMsgBottomElement.setAttribute(
  3283. 'style',
  3284. 'top:' + bottomTopIndent +
  3285. '; left:' + bottomLeftIndent + ';');
  3286. if (!glower.hasClass('icon-chat-simple')) {
  3287. glower.removeClass('icon-chat');
  3288. glower.addClass('icon-chat-simple');
  3289. }
  3290. }
  3291. else {
  3292. unreadMsgElement.innerHTML = '';
  3293. unreadMsgBottomElement.innerHTML = '';
  3294. glower.removeClass('icon-chat-simple');
  3295. glower.addClass('icon-chat');
  3296. }
  3297. if (show && !notificationInterval) {
  3298. notificationInterval = window.setInterval(function () {
  3299. glower.toggleClass('active');
  3300. bottomGlower.toggleClass('active glowing');
  3301. }, 800);
  3302. }
  3303. else if (!show && notificationInterval) {
  3304. window.clearInterval(notificationInterval);
  3305. notificationInterval = false;
  3306. glower.removeClass('active');
  3307. bottomGlower.removeClass('glowing');
  3308. bottomGlower.addClass('active');
  3309. }
  3310. }
  3311. /**
  3312. * Returns the current time in the format it is shown to the user
  3313. * @returns {string}
  3314. */
  3315. function getCurrentTime() {
  3316. var now = new Date();
  3317. var hour = now.getHours();
  3318. var minute = now.getMinutes();
  3319. var second = now.getSeconds();
  3320. if(hour.toString().length === 1) {
  3321. hour = '0'+hour;
  3322. }
  3323. if(minute.toString().length === 1) {
  3324. minute = '0'+minute;
  3325. }
  3326. if(second.toString().length === 1) {
  3327. second = '0'+second;
  3328. }
  3329. return hour+':'+minute+':'+second;
  3330. }
  3331. function toggleSmileys()
  3332. {
  3333. var smileys = $('#smileysContainer');
  3334. if(!smileys.is(':visible')) {
  3335. smileys.show("slide", { direction: "down", duration: 300});
  3336. } else {
  3337. smileys.hide("slide", { direction: "down", duration: 300});
  3338. }
  3339. $('#usermsg').focus();
  3340. }
  3341. function addClickFunction(smiley, number) {
  3342. smiley.onclick = function addSmileyToMessage() {
  3343. var usermsg = $('#usermsg');
  3344. var message = usermsg.val();
  3345. message += smileys['smiley' + number];
  3346. usermsg.val(message);
  3347. usermsg.get(0).setSelectionRange(message.length, message.length);
  3348. toggleSmileys();
  3349. usermsg.focus();
  3350. };
  3351. }
  3352. /**
  3353. * Adds the smileys container to the chat
  3354. */
  3355. function addSmileys() {
  3356. var smileysContainer = document.createElement('div');
  3357. smileysContainer.id = 'smileysContainer';
  3358. for(var i = 1; i <= 21; i++) {
  3359. var smileyContainer = document.createElement('div');
  3360. smileyContainer.id = 'smiley' + i;
  3361. smileyContainer.className = 'smileyContainer';
  3362. var smiley = document.createElement('img');
  3363. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3364. smiley.className = 'smiley';
  3365. addClickFunction(smiley, i);
  3366. smileyContainer.appendChild(smiley);
  3367. smileysContainer.appendChild(smileyContainer);
  3368. }
  3369. $("#chatspace").append(smileysContainer);
  3370. }
  3371. /**
  3372. * Resizes the chat conversation.
  3373. */
  3374. function resizeChatConversation() {
  3375. var msgareaHeight = $('#usermsg').outerHeight();
  3376. var chatspace = $('#chatspace');
  3377. var width = chatspace.width();
  3378. var chat = $('#chatconversation');
  3379. var smileys = $('#smileysarea');
  3380. smileys.height(msgareaHeight);
  3381. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3382. $('#smileysContainer').css('bottom', msgareaHeight);
  3383. chat.width(width - 10);
  3384. chat.height(window.innerHeight - 15 - msgareaHeight);
  3385. }
  3386. /**
  3387. * Chat related user interface.
  3388. */
  3389. var Chat = (function (my) {
  3390. /**
  3391. * Initializes chat related interface.
  3392. */
  3393. my.init = function () {
  3394. if(NicknameHandler.getNickname())
  3395. Chat.setChatConversationMode(true);
  3396. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3397. function (nickname) {
  3398. Chat.setChatConversationMode(true);
  3399. });
  3400. $('#nickinput').keydown(function (event) {
  3401. if (event.keyCode === 13) {
  3402. event.preventDefault();
  3403. var val = UIUtil.escapeHtml(this.value);
  3404. this.value = '';
  3405. if (!NicknameHandler.getNickname()) {
  3406. NicknameHandler.setNickname(val);
  3407. return;
  3408. }
  3409. }
  3410. });
  3411. $('#usermsg').keydown(function (event) {
  3412. if (event.keyCode === 13) {
  3413. event.preventDefault();
  3414. var value = this.value;
  3415. $('#usermsg').val('').trigger('autosize.resize');
  3416. this.focus();
  3417. var command = new CommandsProcessor(value);
  3418. if(command.isCommand())
  3419. {
  3420. command.processCommand();
  3421. }
  3422. else
  3423. {
  3424. var message = UIUtil.escapeHtml(value);
  3425. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3426. }
  3427. }
  3428. });
  3429. var onTextAreaResize = function () {
  3430. resizeChatConversation();
  3431. Chat.scrollChatToBottom();
  3432. };
  3433. $('#usermsg').autosize({callback: onTextAreaResize});
  3434. $("#chatspace").bind("shown",
  3435. function () {
  3436. unreadMessages = 0;
  3437. setVisualNotification(false);
  3438. });
  3439. addSmileys();
  3440. };
  3441. /**
  3442. * Appends the given message to the chat conversation.
  3443. */
  3444. my.updateChatConversation = function (from, displayName, message) {
  3445. var divClassName = '';
  3446. if (APP.xmpp.myJid() === from) {
  3447. divClassName = "localuser";
  3448. }
  3449. else {
  3450. divClassName = "remoteuser";
  3451. if (!Chat.isVisible()) {
  3452. unreadMessages++;
  3453. UIUtil.playSoundNotification('chatNotification');
  3454. setVisualNotification(true);
  3455. }
  3456. }
  3457. // replace links and smileys
  3458. // Strophe already escapes special symbols on sending,
  3459. // so we escape here only tags to avoid double &amp;
  3460. var escMessage = message.replace(/</g, '&lt;').
  3461. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  3462. var escDisplayName = UIUtil.escapeHtml(displayName);
  3463. message = Replacement.processReplacements(escMessage);
  3464. var messageContainer =
  3465. '<div class="chatmessage">'+
  3466. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  3467. '<div class="username ' + divClassName +'">' + escDisplayName +
  3468. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  3469. '</div>' + '<div class="usermessage">' + message + '</div>' +
  3470. '</div>';
  3471. $('#chatconversation').append(messageContainer);
  3472. $('#chatconversation').animate(
  3473. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3474. };
  3475. /**
  3476. * Appends error message to the conversation
  3477. * @param errorMessage the received error message.
  3478. * @param originalText the original message.
  3479. */
  3480. my.chatAddError = function(errorMessage, originalText)
  3481. {
  3482. errorMessage = UIUtil.escapeHtml(errorMessage);
  3483. originalText = UIUtil.escapeHtml(originalText);
  3484. $('#chatconversation').append(
  3485. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  3486. (originalText? (' \"'+ originalText + '\"') : "") +
  3487. ' was not sent.' +
  3488. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  3489. $('#chatconversation').animate(
  3490. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3491. };
  3492. /**
  3493. * Sets the subject to the UI
  3494. * @param subject the subject
  3495. */
  3496. my.chatSetSubject = function(subject)
  3497. {
  3498. if(subject)
  3499. subject = subject.trim();
  3500. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  3501. if(subject === "")
  3502. {
  3503. $("#subject").css({display: "none"});
  3504. }
  3505. else
  3506. {
  3507. $("#subject").css({display: "block"});
  3508. }
  3509. };
  3510. /**
  3511. * Sets the chat conversation mode.
  3512. */
  3513. my.setChatConversationMode = function (isConversationMode) {
  3514. if (isConversationMode) {
  3515. $('#nickname').css({visibility: 'hidden'});
  3516. $('#chatconversation').css({visibility: 'visible'});
  3517. $('#usermsg').css({visibility: 'visible'});
  3518. $('#smileysarea').css({visibility: 'visible'});
  3519. $('#usermsg').focus();
  3520. }
  3521. };
  3522. /**
  3523. * Resizes the chat area.
  3524. */
  3525. my.resizeChat = function () {
  3526. var chatSize = require("../SidePanelToggler").getPanelSize();
  3527. $('#chatspace').width(chatSize[0]);
  3528. $('#chatspace').height(chatSize[1]);
  3529. resizeChatConversation();
  3530. };
  3531. /**
  3532. * Indicates if the chat is currently visible.
  3533. */
  3534. my.isVisible = function () {
  3535. return $('#chatspace').is(":visible");
  3536. };
  3537. /**
  3538. * Shows and hides the window with the smileys
  3539. */
  3540. my.toggleSmileys = toggleSmileys;
  3541. /**
  3542. * Scrolls chat to the bottom.
  3543. */
  3544. my.scrollChatToBottom = function() {
  3545. setTimeout(function () {
  3546. $('#chatconversation').scrollTop(
  3547. $('#chatconversation')[0].scrollHeight);
  3548. }, 5);
  3549. };
  3550. return my;
  3551. }(Chat || {}));
  3552. module.exports = Chat;
  3553. },{"../../../../service/UI/UIEvents":83,"../../toolbars/ToolbarToggler":25,"../../util/NicknameHandler":28,"../../util/UIUtil":29,"../SidePanelToggler":16,"./Commands":18,"./Replacement":19,"./smileys.json":20}],18:[function(require,module,exports){
  3554. var UIUtil = require("../../util/UIUtil");
  3555. /**
  3556. * List with supported commands. The keys are the names of the commands and
  3557. * the value is the function that processes the message.
  3558. * @type {{String: function}}
  3559. */
  3560. var commands = {
  3561. "topic" : processTopic
  3562. };
  3563. /**
  3564. * Extracts the command from the message.
  3565. * @param message the received message
  3566. * @returns {string} the command
  3567. */
  3568. function getCommand(message)
  3569. {
  3570. if(message)
  3571. {
  3572. for(var command in commands)
  3573. {
  3574. if(message.indexOf("/" + command) == 0)
  3575. return command;
  3576. }
  3577. }
  3578. return "";
  3579. };
  3580. /**
  3581. * Processes the data for topic command.
  3582. * @param commandArguments the arguments of the topic command.
  3583. */
  3584. function processTopic(commandArguments)
  3585. {
  3586. var topic = UIUtil.escapeHtml(commandArguments);
  3587. APP.xmpp.setSubject(topic);
  3588. }
  3589. /**
  3590. * Constructs new CommandProccessor instance from a message that
  3591. * handles commands received via chat messages.
  3592. * @param message the message
  3593. * @constructor
  3594. */
  3595. function CommandsProcessor(message)
  3596. {
  3597. var command = getCommand(message);
  3598. /**
  3599. * Returns the name of the command.
  3600. * @returns {String} the command
  3601. */
  3602. this.getCommand = function()
  3603. {
  3604. return command;
  3605. };
  3606. var messageArgument = message.substr(command.length + 2);
  3607. /**
  3608. * Returns the arguments of the command.
  3609. * @returns {string}
  3610. */
  3611. this.getArgument = function()
  3612. {
  3613. return messageArgument;
  3614. };
  3615. }
  3616. /**
  3617. * Checks whether this instance is valid command or not.
  3618. * @returns {boolean}
  3619. */
  3620. CommandsProcessor.prototype.isCommand = function()
  3621. {
  3622. if(this.getCommand())
  3623. return true;
  3624. return false;
  3625. };
  3626. /**
  3627. * Processes the command.
  3628. */
  3629. CommandsProcessor.prototype.processCommand = function()
  3630. {
  3631. if(!this.isCommand())
  3632. return;
  3633. commands[this.getCommand()](this.getArgument());
  3634. };
  3635. module.exports = CommandsProcessor;
  3636. },{"../../util/UIUtil":29}],19:[function(require,module,exports){
  3637. var Smileys = require("./smileys.json");
  3638. /**
  3639. * Processes links and smileys in "body"
  3640. */
  3641. function processReplacements(body)
  3642. {
  3643. //make links clickable
  3644. body = linkify(body);
  3645. //add smileys
  3646. body = smilify(body);
  3647. return body;
  3648. }
  3649. /**
  3650. * Finds and replaces all links in the links in "body"
  3651. * with their <a href=""></a>
  3652. */
  3653. function linkify(inputText)
  3654. {
  3655. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  3656. //URLs starting with http://, https://, or ftp://
  3657. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  3658. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  3659. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  3660. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  3661. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  3662. //Change email addresses to mailto:: links.
  3663. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  3664. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  3665. return replacedText;
  3666. }
  3667. /**
  3668. * Replaces common smiley strings with images
  3669. */
  3670. function smilify(body)
  3671. {
  3672. if(!body) {
  3673. return body;
  3674. }
  3675. var regexs = Smileys["regexs"];
  3676. for(var smiley in regexs) {
  3677. if(regexs.hasOwnProperty(smiley)) {
  3678. body = body.replace(regexs[smiley],
  3679. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  3680. }
  3681. }
  3682. return body;
  3683. }
  3684. module.exports = {
  3685. processReplacements: processReplacements,
  3686. linkify: linkify
  3687. };
  3688. },{"./smileys.json":20}],20:[function(require,module,exports){
  3689. module.exports={
  3690. "smileys": {
  3691. "smiley1": ":)",
  3692. "smiley2": ":(",
  3693. "smiley3": ":D",
  3694. "smiley4": "(y)",
  3695. "smiley5": " :P",
  3696. "smiley6": "(wave)",
  3697. "smiley7": "(blush)",
  3698. "smiley8": "(chuckle)",
  3699. "smiley9": "(shocked)",
  3700. "smiley10": ":*",
  3701. "smiley11": "(n)",
  3702. "smiley12": "(search)",
  3703. "smiley13": " <3",
  3704. "smiley14": "(oops)",
  3705. "smiley15": "(angry)",
  3706. "smiley16": "(angel)",
  3707. "smiley17": "(sick)",
  3708. "smiley18": ";(",
  3709. "smiley19": "(bomb)",
  3710. "smiley20": "(clap)",
  3711. "smiley21": " ;)"
  3712. },
  3713. "regexs": {
  3714. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  3715. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  3716. "smiley1": /(:-\)|:\))/gi,
  3717. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  3718. "smiley5": /(:-P|:P|:-p|:p)/gi,
  3719. "smiley6": /(\(wave\))/gi,
  3720. "smiley7": /(\(blush\))/gi,
  3721. "smiley8": /(\(chuckle\))/gi,
  3722. "smiley9": /(:-0|\(shocked\))/gi,
  3723. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  3724. "smiley11": /(\(n\))/gi,
  3725. "smiley12": /(\(search\))/g,
  3726. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  3727. "smiley14": /(\(oops\))/gi,
  3728. "smiley15": /(\(angry\))/gi,
  3729. "smiley16": /(\(angel\))/gi,
  3730. "smiley17": /(\(sick\))/gi,
  3731. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  3732. "smiley19": /(\(bomb\))/gi,
  3733. "smiley20": /(\(clap\))/gi,
  3734. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  3735. }
  3736. }
  3737. },{}],21:[function(require,module,exports){
  3738. var numberOfContacts = 0;
  3739. var notificationInterval;
  3740. /**
  3741. * Updates the number of participants in the contact list button and sets
  3742. * the glow
  3743. * @param delta indicates whether a new user has joined (1) or someone has
  3744. * left(-1)
  3745. */
  3746. function updateNumberOfParticipants(delta) {
  3747. //when the user is alone we don't show the number of participants
  3748. if(numberOfContacts === 0) {
  3749. $("#numberOfParticipants").text('');
  3750. numberOfContacts += delta;
  3751. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  3752. ContactList.setVisualNotification(true);
  3753. numberOfContacts += delta;
  3754. $("#numberOfParticipants").text(numberOfContacts);
  3755. }
  3756. }
  3757. /**
  3758. * Creates the avatar element.
  3759. *
  3760. * @return the newly created avatar element
  3761. */
  3762. function createAvatar(id) {
  3763. var avatar = document.createElement('img');
  3764. avatar.className = "icon-avatar avatar";
  3765. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  3766. return avatar;
  3767. }
  3768. /**
  3769. * Creates the display name paragraph.
  3770. *
  3771. * @param displayName the display name to set
  3772. */
  3773. function createDisplayNameParagraph(displayName) {
  3774. var p = document.createElement('p');
  3775. p.innerText = displayName;
  3776. return p;
  3777. }
  3778. function stopGlowing(glower) {
  3779. window.clearInterval(notificationInterval);
  3780. notificationInterval = false;
  3781. glower.removeClass('glowing');
  3782. if (!ContactList.isVisible()) {
  3783. glower.removeClass('active');
  3784. }
  3785. }
  3786. /**
  3787. * Contact list.
  3788. */
  3789. var ContactList = {
  3790. /**
  3791. * Indicates if the chat is currently visible.
  3792. *
  3793. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  3794. * otherwise
  3795. */
  3796. isVisible: function () {
  3797. return $('#contactlist').is(":visible");
  3798. },
  3799. /**
  3800. * Adds a contact for the given peerJid if such doesn't yet exist.
  3801. *
  3802. * @param peerJid the peerJid corresponding to the contact
  3803. * @param id the user's email or userId used to get the user's avatar
  3804. */
  3805. ensureAddContact: function (peerJid, id) {
  3806. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3807. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  3808. if (!contact || contact.length <= 0)
  3809. ContactList.addContact(peerJid, id);
  3810. },
  3811. /**
  3812. * Adds a contact for the given peer jid.
  3813. *
  3814. * @param peerJid the jid of the contact to add
  3815. * @param id the email or userId of the user
  3816. */
  3817. addContact: function (peerJid, id) {
  3818. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3819. var contactlist = $('#contactlist>ul');
  3820. var newContact = document.createElement('li');
  3821. newContact.id = resourceJid;
  3822. newContact.className = "clickable";
  3823. newContact.onclick = function (event) {
  3824. if (event.currentTarget.className === "clickable") {
  3825. $(ContactList).trigger('contactclicked', [peerJid]);
  3826. }
  3827. };
  3828. newContact.appendChild(createAvatar(id));
  3829. newContact.appendChild(createDisplayNameParagraph("Participant"));
  3830. var clElement = contactlist.get(0);
  3831. if (resourceJid === APP.xmpp.myResource()
  3832. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  3833. clElement.insertBefore(newContact,
  3834. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  3835. }
  3836. else {
  3837. clElement.appendChild(newContact);
  3838. }
  3839. updateNumberOfParticipants(1);
  3840. },
  3841. /**
  3842. * Removes a contact for the given peer jid.
  3843. *
  3844. * @param peerJid the peerJid corresponding to the contact to remove
  3845. */
  3846. removeContact: function (peerJid) {
  3847. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3848. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  3849. if (contact && contact.length > 0) {
  3850. var contactlist = $('#contactlist>ul');
  3851. contactlist.get(0).removeChild(contact.get(0));
  3852. updateNumberOfParticipants(-1);
  3853. }
  3854. },
  3855. setVisualNotification: function (show, stopGlowingIn) {
  3856. var glower = $('#contactListButton');
  3857. if (show && !notificationInterval) {
  3858. notificationInterval = window.setInterval(function () {
  3859. glower.toggleClass('active glowing');
  3860. }, 800);
  3861. }
  3862. else if (!show && notificationInterval) {
  3863. stopGlowing(glower);
  3864. }
  3865. if (stopGlowingIn) {
  3866. setTimeout(function () {
  3867. stopGlowing(glower);
  3868. }, stopGlowingIn);
  3869. }
  3870. },
  3871. setClickable: function (resourceJid, isClickable) {
  3872. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  3873. if (isClickable) {
  3874. contact.addClass('clickable');
  3875. } else {
  3876. contact.removeClass('clickable');
  3877. }
  3878. },
  3879. onDisplayNameChange: function (peerJid, displayName) {
  3880. if (peerJid === 'localVideoContainer')
  3881. peerJid = APP.xmpp.myJid();
  3882. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3883. var contactName = $('#contactlist #' + resourceJid + '>p');
  3884. if (contactName && displayName && displayName.length > 0)
  3885. contactName.html(displayName);
  3886. }
  3887. };
  3888. module.exports = ContactList;
  3889. },{}],22:[function(require,module,exports){
  3890. var Avatar = require("../../avatar/Avatar");
  3891. var Settings = require("./../../../settings/Settings");
  3892. var UIUtil = require("../../util/UIUtil");
  3893. var languages = require("../../../../service/translation/languages");
  3894. function generateLanguagesSelectBox()
  3895. {
  3896. var currentLang = APP.translation.getCurrentLanguage();
  3897. var html = "<select id=\"languages_selectbox\">";
  3898. var langArray = languages.getLanguages();
  3899. for(var i = 0; i < langArray.length; i++)
  3900. {
  3901. var lang = langArray[i];
  3902. html += "<option ";
  3903. if(lang === currentLang)
  3904. html += "selected ";
  3905. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  3906. html += "</option>";
  3907. }
  3908. return html + "</select>";
  3909. }
  3910. var SettingsMenu = {
  3911. init: function () {
  3912. $("#updateSettings").before(generateLanguagesSelectBox());
  3913. $('#settingsmenu>input').keyup(function(event){
  3914. if(event.keyCode === 13) {//enter
  3915. SettingsMenu.update();
  3916. }
  3917. });
  3918. $("#updateSettings").click(function () {
  3919. SettingsMenu.update();
  3920. });
  3921. },
  3922. update: function() {
  3923. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  3924. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  3925. if(newDisplayName) {
  3926. var displayName = Settings.setDisplayName(newDisplayName);
  3927. APP.xmpp.addToPresence("displayName", displayName, true);
  3928. }
  3929. var language = $("#languages_selectbox").val();
  3930. APP.translation.setLanguage(language);
  3931. Settings.setLanguage(language);
  3932. APP.xmpp.addToPresence("email", newEmail);
  3933. var email = Settings.setEmail(newEmail);
  3934. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  3935. },
  3936. isVisible: function() {
  3937. return $('#settingsmenu').is(':visible');
  3938. },
  3939. setDisplayName: function(newDisplayName) {
  3940. var displayName = Settings.setDisplayName(newDisplayName);
  3941. $('#setDisplayName').get(0).value = displayName;
  3942. },
  3943. onDisplayNameChange: function(peerJid, newDisplayName) {
  3944. if(peerJid === 'localVideoContainer' ||
  3945. peerJid === APP.xmpp.myJid()) {
  3946. this.setDisplayName(newDisplayName);
  3947. }
  3948. }
  3949. };
  3950. module.exports = SettingsMenu;
  3951. },{"../../../../service/translation/languages":87,"../../avatar/Avatar":12,"../../util/UIUtil":29,"./../../../settings/Settings":37}],23:[function(require,module,exports){
  3952. var PanelToggler = require("../side_pannels/SidePanelToggler");
  3953. var buttonHandlers = {
  3954. "bottom_toolbar_contact_list": function () {
  3955. BottomToolbar.toggleContactList();
  3956. },
  3957. "bottom_toolbar_film_strip": function () {
  3958. BottomToolbar.toggleFilmStrip();
  3959. },
  3960. "bottom_toolbar_chat": function () {
  3961. BottomToolbar.toggleChat();
  3962. }
  3963. };
  3964. var BottomToolbar = (function (my) {
  3965. my.init = function () {
  3966. for(var k in buttonHandlers)
  3967. $("#" + k).click(buttonHandlers[k]);
  3968. };
  3969. my.toggleChat = function() {
  3970. PanelToggler.toggleChat();
  3971. };
  3972. my.toggleContactList = function() {
  3973. PanelToggler.toggleContactList();
  3974. };
  3975. my.toggleFilmStrip = function() {
  3976. var filmstrip = $("#remoteVideos");
  3977. filmstrip.toggleClass("hidden");
  3978. };
  3979. $(document).bind("remotevideo.resized", function (event, width, height) {
  3980. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  3981. $('#bottomToolbar').css({bottom: bottom + 'px'});
  3982. });
  3983. return my;
  3984. }(BottomToolbar || {}));
  3985. module.exports = BottomToolbar;
  3986. },{"../side_pannels/SidePanelToggler":16}],24:[function(require,module,exports){
  3987. /* global APP,$, buttonClick, config, lockRoom,
  3988. setSharedKey, Util */
  3989. var messageHandler = require("../util/MessageHandler");
  3990. var BottomToolbar = require("./BottomToolbar");
  3991. var Prezi = require("../prezi/Prezi");
  3992. var Etherpad = require("../etherpad/Etherpad");
  3993. var PanelToggler = require("../side_pannels/SidePanelToggler");
  3994. var Authentication = require("../authentication/Authentication");
  3995. var UIUtil = require("../util/UIUtil");
  3996. var AuthenticationEvents
  3997. = require("../../../service/authentication/AuthenticationEvents");
  3998. var roomUrl = null;
  3999. var sharedKey = '';
  4000. var UI = null;
  4001. var buttonHandlers =
  4002. {
  4003. "toolbar_button_mute": function () {
  4004. return APP.UI.toggleAudio();
  4005. },
  4006. "toolbar_button_camera": function () {
  4007. return APP.UI.toggleVideo();
  4008. },
  4009. /*"toolbar_button_authentication": function () {
  4010. return Toolbar.authenticateClicked();
  4011. },*/
  4012. "toolbar_button_record": function () {
  4013. return toggleRecording();
  4014. },
  4015. "toolbar_button_security": function () {
  4016. return Toolbar.openLockDialog();
  4017. },
  4018. "toolbar_button_link": function () {
  4019. return Toolbar.openLinkDialog();
  4020. },
  4021. "toolbar_button_chat": function () {
  4022. return BottomToolbar.toggleChat();
  4023. },
  4024. "toolbar_button_prezi": function () {
  4025. return Prezi.openPreziDialog();
  4026. },
  4027. "toolbar_button_etherpad": function () {
  4028. return Etherpad.toggleEtherpad(0);
  4029. },
  4030. "toolbar_button_desktopsharing": function () {
  4031. return APP.desktopsharing.toggleScreenSharing();
  4032. },
  4033. "toolbar_button_fullScreen": function()
  4034. {
  4035. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4036. return Toolbar.toggleFullScreen();
  4037. },
  4038. "toolbar_button_sip": function () {
  4039. return callSipButtonClicked();
  4040. },
  4041. "toolbar_button_settings": function () {
  4042. PanelToggler.toggleSettingsMenu();
  4043. },
  4044. "toolbar_button_hangup": function () {
  4045. return hangup();
  4046. },
  4047. "toolbar_button_login": function () {
  4048. Toolbar.authenticateClicked();
  4049. },
  4050. "toolbar_button_logout": function () {
  4051. // Ask for confirmation
  4052. messageHandler.openTwoButtonDialog(
  4053. "dialog.logoutTitle", "Logout",
  4054. "dialog.logoutQuestion",
  4055. "Are you sure you want to logout and stop the conference ?",
  4056. false, "Yes",
  4057. function (evt, yes) {
  4058. if (yes) {
  4059. APP.xmpp.logout(function (url) {
  4060. if (url) {
  4061. window.location.href = url;
  4062. } else {
  4063. hangup();
  4064. }
  4065. });
  4066. }
  4067. });
  4068. }
  4069. };
  4070. function hangup() {
  4071. APP.xmpp.disposeConference();
  4072. if(config.enableWelcomePage)
  4073. {
  4074. setTimeout(function()
  4075. {
  4076. window.localStorage.welcomePageDisabled = false;
  4077. window.location.pathname = "/";
  4078. }, 10000);
  4079. }
  4080. var title = APP.translation.generateTranslatonHTML(
  4081. "dialog.sessTerminated", "Session Terminated");
  4082. var msg = APP.translation.generateTranslatonHTML(
  4083. "dialog.hungUp","You hung up the call");
  4084. var button = APP.translation.generateTranslatonHTML(
  4085. "dialog.joinAgain", "Join again");
  4086. var buttons = {};
  4087. buttons.joinAgain = {title: button, value: true};
  4088. UI.messageHandler.openDialog(
  4089. title,
  4090. msg,
  4091. true,
  4092. buttons,
  4093. function(event, value, message, formVals)
  4094. {
  4095. window.location.reload();
  4096. return false;
  4097. }
  4098. );
  4099. }
  4100. /**
  4101. * Starts or stops the recording for the conference.
  4102. */
  4103. function toggleRecording() {
  4104. APP.xmpp.toggleRecording(function (callback) {
  4105. var msg = APP.translation.generateTranslatonHTML(
  4106. "dialog.recordingToken", "Enter recording token");
  4107. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  4108. '<h2>' + msg + '</h2>' +
  4109. '<input id="recordingToken" type="text" ' +
  4110. 'placeholder="token" autofocus>',
  4111. false,
  4112. "dialog.Save",
  4113. function (e, v, m, f) {
  4114. if (v) {
  4115. var token = document.getElementById('recordingToken');
  4116. if (token.value) {
  4117. callback(UIUtil.escapeHtml(token.value));
  4118. }
  4119. }
  4120. },
  4121. function (event) {
  4122. document.getElementById('recordingToken').focus();
  4123. },
  4124. function () {
  4125. }
  4126. );
  4127. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4128. }
  4129. /**
  4130. * Locks / unlocks the room.
  4131. */
  4132. function lockRoom(lock) {
  4133. var currentSharedKey = '';
  4134. if (lock)
  4135. currentSharedKey = sharedKey;
  4136. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4137. // password is required
  4138. if (sharedKey)
  4139. {
  4140. console.log('set room password');
  4141. Toolbar.lockLockButton();
  4142. }
  4143. else
  4144. {
  4145. console.log('removed room password');
  4146. Toolbar.unlockLockButton();
  4147. }
  4148. }, function (err) {
  4149. console.warn('setting password failed', err);
  4150. messageHandler.showError("dialog.lockTitle", 'Lock failed',
  4151. "dialog.lockMessage",
  4152. 'Failed to lock conference.',
  4153. err);
  4154. Toolbar.setSharedKey('');
  4155. }, function () {
  4156. console.warn('room passwords not supported');
  4157. messageHandler.showError("dialog.warning", 'Warning',
  4158. "dialog.passwordNotSupported",
  4159. 'Room passwords are currently not supported.');
  4160. Toolbar.setSharedKey('');
  4161. });
  4162. };
  4163. /**
  4164. * Invite participants to conference.
  4165. */
  4166. function inviteParticipants() {
  4167. if (roomUrl === null)
  4168. return;
  4169. var sharedKeyText = "";
  4170. if (sharedKey && sharedKey.length > 0) {
  4171. sharedKeyText =
  4172. "This conference is password protected. Please use the " +
  4173. "following pin when joining:%0D%0A%0D%0A" +
  4174. sharedKey + "%0D%0A%0D%0A";
  4175. }
  4176. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4177. var subject = "Invitation to a " + interfaceConfig.APP_NAME + " (" + conferenceName + ")";
  4178. var body = "Hey there, I%27d like to invite you to a " + interfaceConfig.APP_NAME +
  4179. " conference I%27ve just set up.%0D%0A%0D%0A" +
  4180. "Please click on the following link in order" +
  4181. " to join the conference.%0D%0A%0D%0A" +
  4182. roomUrl +
  4183. "%0D%0A%0D%0A" +
  4184. sharedKeyText +
  4185. "Note that " + interfaceConfig.APP_NAME + " is currently" +
  4186. " only supported by Chromium," +
  4187. " Google Chrome and Opera, so you need" +
  4188. " to be using one of these browsers.%0D%0A%0D%0A" +
  4189. "Talk to you in a sec!";
  4190. if (window.localStorage.displayname) {
  4191. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4192. }
  4193. if (interfaceConfig.INVITATION_POWERED_BY) {
  4194. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4195. }
  4196. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4197. }
  4198. function callSipButtonClicked()
  4199. {
  4200. var defaultNumber
  4201. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4202. var sipMsg = APP.translation.generateTranslatonHTML(
  4203. "dialog.sipMsg", "Enter SIP number");
  4204. messageHandler.openTwoButtonDialog(null, null, null,
  4205. '<h2>' + sipMsg + '</h2>' +
  4206. '<input id="sipNumber" type="text"' +
  4207. ' value="' + defaultNumber + '" autofocus>',
  4208. false,
  4209. "dialog.Dial",
  4210. function (e, v, m, f) {
  4211. if (v) {
  4212. var numberInput = document.getElementById('sipNumber');
  4213. if (numberInput.value) {
  4214. APP.xmpp.dial(numberInput.value, 'fromnumber',
  4215. UI.getRoomName(), sharedKey);
  4216. }
  4217. }
  4218. },
  4219. function (event) {
  4220. document.getElementById('sipNumber').focus();
  4221. }
  4222. );
  4223. }
  4224. var Toolbar = (function (my) {
  4225. my.init = function (ui) {
  4226. for(var k in buttonHandlers)
  4227. $("#" + k).click(buttonHandlers[k]);
  4228. UI = ui;
  4229. // Update login info
  4230. APP.xmpp.addListener(
  4231. AuthenticationEvents.IDENTITY_UPDATED,
  4232. function (authenticationEnabled, userIdentity) {
  4233. var loggedIn = false;
  4234. if (userIdentity) {
  4235. loggedIn = true;
  4236. }
  4237. //FIXME: XMPP authentication need improvements for "live" login
  4238. if (!APP.xmpp.isExternalAuthEnabled() && !loggedIn)
  4239. {
  4240. authenticationEnabled = false;
  4241. }
  4242. Toolbar.showAuthenticateButton(authenticationEnabled);
  4243. if (authenticationEnabled) {
  4244. Toolbar.setAuthenticatedIdentity(userIdentity);
  4245. Toolbar.showLoginButton(!loggedIn);
  4246. Toolbar.showLogoutButton(loggedIn);
  4247. }
  4248. }
  4249. );
  4250. },
  4251. /**
  4252. * Sets shared key
  4253. * @param sKey the shared key
  4254. */
  4255. my.setSharedKey = function (sKey) {
  4256. sharedKey = sKey;
  4257. };
  4258. my.authenticateClicked = function () {
  4259. Authentication.focusAuthenticationWindow();
  4260. // Get authentication URL
  4261. if (!APP.xmpp.getMUCJoined()) {
  4262. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4263. // If conference has not been started yet - redirect to login page
  4264. window.location.href = url;
  4265. });
  4266. } else {
  4267. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4268. // Otherwise - open popup with authentication URL
  4269. var authenticationWindow = Authentication.createAuthenticationWindow(
  4270. function () {
  4271. // On popup closed - retry room allocation
  4272. APP.xmpp.allocateConferenceFocus(
  4273. APP.UI.getRoomName(),
  4274. function () { console.info("AUTH DONE"); }
  4275. );
  4276. }, url);
  4277. if (!authenticationWindow) {
  4278. messageHandler.openMessageDialog(
  4279. null, null, "dialog.popupError",
  4280. "Your browser is blocking popup windows from this site." +
  4281. " Please enable popups in your browser security settings" +
  4282. " and try again.");
  4283. }
  4284. });
  4285. }
  4286. };
  4287. /**
  4288. * Updates the room invite url.
  4289. */
  4290. my.updateRoomUrl = function (newRoomUrl) {
  4291. roomUrl = newRoomUrl;
  4292. // If the invite dialog has been already opened we update the information.
  4293. var inviteLink = document.getElementById('inviteLinkRef');
  4294. if (inviteLink) {
  4295. inviteLink.value = roomUrl;
  4296. inviteLink.select();
  4297. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  4298. }
  4299. };
  4300. /**
  4301. * Disables and enables some of the buttons.
  4302. */
  4303. my.setupButtonsFromConfig = function () {
  4304. if (config.disablePrezi)
  4305. {
  4306. $("#prezi_button").css({display: "none"});
  4307. }
  4308. };
  4309. /**
  4310. * Opens the lock room dialog.
  4311. */
  4312. my.openLockDialog = function () {
  4313. // Only the focus is able to set a shared key.
  4314. if (!APP.xmpp.isModerator()) {
  4315. if (sharedKey) {
  4316. messageHandler.openMessageDialog(null, null,
  4317. "dialog.passwordError",
  4318. "This conversation is currently protected by" +
  4319. " a password. Only the owner of the conference" +
  4320. " could set a password.",
  4321. false,
  4322. "Password");
  4323. } else {
  4324. messageHandler.openMessageDialog(null, null, "dialog.passwordError2",
  4325. "This conversation isn't currently protected by" +
  4326. " a password. Only the owner of the conference" +
  4327. " could set a password.",
  4328. false,
  4329. "Password");
  4330. }
  4331. } else {
  4332. if (sharedKey) {
  4333. messageHandler.openTwoButtonDialog(null, null,
  4334. "dialog.passwordCheck",
  4335. "Are you sure you would like to remove your password?",
  4336. false,
  4337. "dialog.Remove",
  4338. function (e, v) {
  4339. if (v) {
  4340. Toolbar.setSharedKey('');
  4341. lockRoom(false);
  4342. }
  4343. });
  4344. } else {
  4345. var msg = APP.translation.generateTranslatonHTML(
  4346. "dialog.passwordMsg", "Set a password to lock your room");
  4347. var yourPassword = APP.translation.translateString(
  4348. "dialog.yourPassword", null, "your password");
  4349. messageHandler.openTwoButtonDialog(null, null, null,
  4350. '<h2>' + msg + '</h2>' +
  4351. '<input id="lockKey" type="text"' +
  4352. 'placeholder="' + yourPassword + '" autofocus>',
  4353. false,
  4354. "dialog.Save",
  4355. function (e, v) {
  4356. if (v) {
  4357. var lockKey = document.getElementById('lockKey');
  4358. if (lockKey.value) {
  4359. Toolbar.setSharedKey(UIUtil.escapeHtml(lockKey.value));
  4360. lockRoom(true);
  4361. }
  4362. }
  4363. },
  4364. function () {
  4365. document.getElementById('lockKey').focus();
  4366. }
  4367. );
  4368. }
  4369. }
  4370. };
  4371. /**
  4372. * Opens the invite link dialog.
  4373. */
  4374. my.openLinkDialog = function () {
  4375. var inviteLink;
  4376. if (roomUrl === null) {
  4377. inviteLink = "Your conference is currently being created...";
  4378. } else {
  4379. inviteLink = encodeURI(roomUrl);
  4380. }
  4381. messageHandler.openTwoButtonDialog("dialog.shareLink",
  4382. "Share this link with everyone you want to invite", null,
  4383. '<input id="inviteLinkRef" type="text" value="' +
  4384. inviteLink + '" onclick="this.select();" readonly>',
  4385. false,
  4386. "dialog.Invite",
  4387. function (e, v) {
  4388. if (v) {
  4389. if (roomUrl) {
  4390. inviteParticipants();
  4391. }
  4392. }
  4393. },
  4394. function () {
  4395. if (roomUrl) {
  4396. document.getElementById('inviteLinkRef').select();
  4397. } else {
  4398. document.getElementById('jqi_state0_buttonInvite')
  4399. .disabled = true;
  4400. }
  4401. }
  4402. );
  4403. };
  4404. /**
  4405. * Opens the settings dialog.
  4406. */
  4407. my.openSettingsDialog = function () {
  4408. var settings1 = APP.translation.generateTranslatonHTML(
  4409. "dialog.settings1", "Configure your conference");
  4410. var settings2 = APP.translation.generateTranslatonHTML(
  4411. "dialog.settings2", "Participants join muted");
  4412. var settings3 = APP.translation.generateTranslatonHTML(
  4413. "dialog.settings3", "Require nicknames<br/><br/>" +
  4414. "Set a password to lock your room:");
  4415. var yourPassword = APP.translation.translateString(
  4416. "dialog.yourPassword", null, "your password");
  4417. messageHandler.openTwoButtonDialog(null,
  4418. '<h2>' + settings1 + '</h2>' +
  4419. '<input type="checkbox" id="initMuted">' +
  4420. settings2 + '<br/>' +
  4421. '<input type="checkbox" id="requireNicknames">' +
  4422. settings3 +
  4423. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  4424. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  4425. null,
  4426. null,
  4427. false,
  4428. "dialog.Save",
  4429. function () {
  4430. document.getElementById('lockKey').focus();
  4431. },
  4432. function (e, v) {
  4433. if (v) {
  4434. if ($('#initMuted').is(":checked")) {
  4435. // it is checked
  4436. }
  4437. if ($('#requireNicknames').is(":checked")) {
  4438. // it is checked
  4439. }
  4440. /*
  4441. var lockKey = document.getElementById('lockKey');
  4442. if (lockKey.value) {
  4443. setSharedKey(lockKey.value);
  4444. lockRoom(true);
  4445. }
  4446. */
  4447. }
  4448. }
  4449. );
  4450. };
  4451. /**
  4452. * Toggles the application in and out of full screen mode
  4453. * (a.k.a. presentation mode in Chrome).
  4454. */
  4455. my.toggleFullScreen = function () {
  4456. var fsElement = document.documentElement;
  4457. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  4458. //Enter Full Screen
  4459. if (fsElement.mozRequestFullScreen) {
  4460. fsElement.mozRequestFullScreen();
  4461. }
  4462. else {
  4463. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  4464. }
  4465. } else {
  4466. //Exit Full Screen
  4467. if (document.mozCancelFullScreen) {
  4468. document.mozCancelFullScreen();
  4469. } else {
  4470. document.webkitCancelFullScreen();
  4471. }
  4472. }
  4473. };
  4474. /**
  4475. * Unlocks the lock button state.
  4476. */
  4477. my.unlockLockButton = function () {
  4478. if ($("#lockIcon").hasClass("icon-security-locked"))
  4479. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4480. };
  4481. /**
  4482. * Updates the lock button state to locked.
  4483. */
  4484. my.lockLockButton = function () {
  4485. if ($("#lockIcon").hasClass("icon-security"))
  4486. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4487. };
  4488. /**
  4489. * Shows or hides authentication button
  4490. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  4491. */
  4492. my.showAuthenticateButton = function (show) {
  4493. if (show) {
  4494. $('#authentication').css({display: "inline"});
  4495. }
  4496. else {
  4497. $('#authentication').css({display: "none"});
  4498. }
  4499. };
  4500. // Shows or hides the 'recording' button.
  4501. my.showRecordingButton = function (show) {
  4502. if (!config.enableRecording) {
  4503. return;
  4504. }
  4505. if (show) {
  4506. $('#recording').css({display: "inline"});
  4507. }
  4508. else {
  4509. $('#recording').css({display: "none"});
  4510. }
  4511. };
  4512. // Sets the state of the recording button
  4513. my.setRecordingButtonState = function (isRecording) {
  4514. if (isRecording) {
  4515. $('#recordButton').removeClass("icon-recEnable");
  4516. $('#recordButton').addClass("icon-recEnable active");
  4517. } else {
  4518. $('#recordButton').removeClass("icon-recEnable active");
  4519. $('#recordButton').addClass("icon-recEnable");
  4520. }
  4521. };
  4522. // Shows or hides SIP calls button
  4523. my.showSipCallButton = function (show) {
  4524. if (APP.xmpp.isSipGatewayEnabled() && show) {
  4525. $('#sipCallButton').css({display: "inline-block"});
  4526. } else {
  4527. $('#sipCallButton').css({display: "none"});
  4528. }
  4529. };
  4530. /**
  4531. * Displays user authenticated identity name(login).
  4532. * @param authIdentity identity name to be displayed.
  4533. */
  4534. my.setAuthenticatedIdentity = function (authIdentity) {
  4535. if (authIdentity) {
  4536. $('#toolbar_auth_identity').css({display: "list-item"});
  4537. $('#toolbar_auth_identity').text(authIdentity);
  4538. } else {
  4539. $('#toolbar_auth_identity').css({display: "none"});
  4540. }
  4541. };
  4542. /**
  4543. * Shows/hides login button.
  4544. * @param show <tt>true</tt> to show
  4545. */
  4546. my.showLoginButton = function (show) {
  4547. if (show) {
  4548. $('#toolbar_button_login').css({display: "list-item"});
  4549. } else {
  4550. $('#toolbar_button_login').css({display: "none"});
  4551. }
  4552. };
  4553. /**
  4554. * Shows/hides logout button.
  4555. * @param show <tt>true</tt> to show
  4556. */
  4557. my.showLogoutButton = function (show) {
  4558. if (show) {
  4559. $('#toolbar_button_logout').css({display: "list-item"});
  4560. } else {
  4561. $('#toolbar_button_logout').css({display: "none"});
  4562. }
  4563. };
  4564. /**
  4565. * Sets the state of the button. The button has blue glow if desktop
  4566. * streaming is active.
  4567. * @param active the state of the desktop streaming.
  4568. */
  4569. my.changeDesktopSharingButtonState = function (active) {
  4570. var button = $("#desktopsharing > a");
  4571. if (active)
  4572. {
  4573. button.addClass("glow");
  4574. }
  4575. else
  4576. {
  4577. button.removeClass("glow");
  4578. }
  4579. };
  4580. return my;
  4581. }(Toolbar || {}));
  4582. module.exports = Toolbar;
  4583. },{"../../../service/authentication/AuthenticationEvents":84,"../authentication/Authentication":11,"../etherpad/Etherpad":13,"../prezi/Prezi":14,"../side_pannels/SidePanelToggler":16,"../util/MessageHandler":27,"../util/UIUtil":29,"./BottomToolbar":23}],25:[function(require,module,exports){
  4584. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  4585. var toolbarTimeoutObject,
  4586. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  4587. function showDesktopSharingButton() {
  4588. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  4589. $('#desktopsharing').css({display: "inline"});
  4590. } else {
  4591. $('#desktopsharing').css({display: "none"});
  4592. }
  4593. }
  4594. /**
  4595. * Hides the toolbar.
  4596. */
  4597. function hideToolbar() {
  4598. var header = $("#header"),
  4599. bottomToolbar = $("#bottomToolbar");
  4600. var isToolbarHover = false;
  4601. header.find('*').each(function () {
  4602. var id = $(this).attr('id');
  4603. if ($("#" + id + ":hover").length > 0) {
  4604. isToolbarHover = true;
  4605. }
  4606. });
  4607. if ($("#bottomToolbar:hover").length > 0) {
  4608. isToolbarHover = true;
  4609. }
  4610. clearTimeout(toolbarTimeoutObject);
  4611. toolbarTimeoutObject = null;
  4612. if (!isToolbarHover) {
  4613. header.hide("slide", { direction: "up", duration: 300});
  4614. $('#subject').animate({top: "-=40"}, 300);
  4615. if ($("#remoteVideos").hasClass("hidden")) {
  4616. bottomToolbar.hide(
  4617. "slide", {direction: "right", duration: 300});
  4618. }
  4619. }
  4620. else {
  4621. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4622. }
  4623. }
  4624. var ToolbarToggler = {
  4625. /**
  4626. * Shows the main toolbar.
  4627. */
  4628. showToolbar: function () {
  4629. var header = $("#header"),
  4630. bottomToolbar = $("#bottomToolbar");
  4631. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  4632. header.show("slide", { direction: "up", duration: 300});
  4633. $('#subject').animate({top: "+=40"}, 300);
  4634. if (!bottomToolbar.is(":visible")) {
  4635. bottomToolbar.show(
  4636. "slide", {direction: "right", duration: 300});
  4637. }
  4638. if (toolbarTimeoutObject) {
  4639. clearTimeout(toolbarTimeoutObject);
  4640. toolbarTimeoutObject = null;
  4641. }
  4642. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4643. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  4644. }
  4645. if (APP.xmpp.isModerator())
  4646. {
  4647. // TODO: Enable settings functionality.
  4648. // Need to uncomment the settings button in index.html.
  4649. // $('#settingsButton').css({visibility:"visible"});
  4650. }
  4651. // Show/hide desktop sharing button
  4652. showDesktopSharingButton();
  4653. },
  4654. /**
  4655. * Docks/undocks the toolbar.
  4656. *
  4657. * @param isDock indicates what operation to perform
  4658. */
  4659. dockToolbar: function (isDock) {
  4660. if (isDock) {
  4661. // First make sure the toolbar is shown.
  4662. if (!$('#header').is(':visible')) {
  4663. this.showToolbar();
  4664. }
  4665. // Then clear the time out, to dock the toolbar.
  4666. if (toolbarTimeoutObject) {
  4667. clearTimeout(toolbarTimeoutObject);
  4668. toolbarTimeoutObject = null;
  4669. }
  4670. }
  4671. else {
  4672. if (!$('#header').is(':visible')) {
  4673. this.showToolbar();
  4674. }
  4675. else {
  4676. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4677. }
  4678. }
  4679. },
  4680. showDesktopSharingButton: showDesktopSharingButton
  4681. };
  4682. module.exports = ToolbarToggler;
  4683. },{}],26:[function(require,module,exports){
  4684. var JitsiPopover = (function () {
  4685. /**
  4686. * Constructs new JitsiPopover and attaches it to the element
  4687. * @param element jquery selector
  4688. * @param options the options for the popover.
  4689. * @constructor
  4690. */
  4691. function JitsiPopover(element, options)
  4692. {
  4693. this.options = {
  4694. skin: "white",
  4695. content: ""
  4696. };
  4697. if(options)
  4698. {
  4699. if(options.skin)
  4700. this.options.skin = options.skin;
  4701. if(options.content)
  4702. this.options.content = options.content;
  4703. }
  4704. this.elementIsHovered = false;
  4705. this.popoverIsHovered = false;
  4706. this.popoverShown = false;
  4707. element.data("jitsi_popover", this);
  4708. this.element = element;
  4709. this.template = ' <div class="jitsipopover ' + this.options.skin +
  4710. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  4711. '<div class="jitsiPopupmenuPadding"></div></div>';
  4712. var self = this;
  4713. this.element.on("mouseenter", function () {
  4714. self.elementIsHovered = true;
  4715. self.show();
  4716. }).on("mouseleave", function () {
  4717. self.elementIsHovered = false;
  4718. setTimeout(function () {
  4719. self.hide();
  4720. }, 10);
  4721. });
  4722. }
  4723. /**
  4724. * Shows the popover
  4725. */
  4726. JitsiPopover.prototype.show = function () {
  4727. this.createPopover();
  4728. this.popoverShown = true;
  4729. };
  4730. /**
  4731. * Hides the popover
  4732. */
  4733. JitsiPopover.prototype.hide = function () {
  4734. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  4735. {
  4736. this.forceHide();
  4737. }
  4738. };
  4739. /**
  4740. * Hides the popover
  4741. */
  4742. JitsiPopover.prototype.forceHide = function () {
  4743. $(".jitsipopover").remove();
  4744. this.popoverShown = false;
  4745. };
  4746. /**
  4747. * Creates the popover html
  4748. */
  4749. JitsiPopover.prototype.createPopover = function () {
  4750. $("body").append(this.template);
  4751. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  4752. var self = this;
  4753. $(".jitsipopover").on("mouseenter", function () {
  4754. self.popoverIsHovered = true;
  4755. }).on("mouseleave", function () {
  4756. self.popoverIsHovered = false;
  4757. self.hide();
  4758. });
  4759. this.refreshPosition();
  4760. };
  4761. /**
  4762. * Refreshes the position of the popover
  4763. */
  4764. JitsiPopover.prototype.refreshPosition = function () {
  4765. $(".jitsipopover").position({
  4766. my: "bottom",
  4767. at: "top",
  4768. collision: "fit",
  4769. of: this.element,
  4770. using: function (position, elements) {
  4771. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  4772. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  4773. $(".jitsipopover > .arrow").css({left: calcLeft});
  4774. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  4775. }
  4776. });
  4777. };
  4778. /**
  4779. * Updates the content of popover.
  4780. * @param content new content
  4781. */
  4782. JitsiPopover.prototype.updateContent = function (content) {
  4783. this.options.content = content;
  4784. if(!this.popoverShown)
  4785. return;
  4786. $(".jitsipopover").remove();
  4787. this.createPopover();
  4788. };
  4789. return JitsiPopover;
  4790. })();
  4791. module.exports = JitsiPopover;
  4792. },{}],27:[function(require,module,exports){
  4793. /* global $, jQuery */
  4794. var messageHandler = (function(my) {
  4795. /**
  4796. * Shows a message to the user.
  4797. *
  4798. * @param titleString the title of the message
  4799. * @param messageString the text of the message
  4800. */
  4801. my.openMessageDialog = function(titleKey, titleString,
  4802. messageKey, messageString) {
  4803. var title = null;
  4804. if(titleKey)
  4805. {
  4806. title = APP.translation.generateTranslatonHTML(titleKey,
  4807. titleString);
  4808. }
  4809. var message = APP.translation.generateTranslatonHTML(messageKey,
  4810. messageString);
  4811. $.prompt(message,
  4812. {
  4813. title: title,
  4814. persistent: false
  4815. }
  4816. );
  4817. };
  4818. /**
  4819. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  4820. *
  4821. * @param titleString the title of the message
  4822. * @param msgString the text of the message
  4823. * @param persistent boolean value which determines whether the message is persistent or not
  4824. * @param leftButton the fist button's text
  4825. * @param submitFunction function to be called on submit
  4826. * @param loadedFunction function to be called after the prompt is fully loaded
  4827. * @param closeFunction function to be called after the prompt is closed
  4828. */
  4829. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  4830. persistent, leftButtonKey, submitFunction, loadedFunction,
  4831. closeFunction)
  4832. {
  4833. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  4834. var buttons = {};
  4835. buttons.button1 = {title: leftButton, value: true};
  4836. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel",
  4837. "Cancel");
  4838. buttons.button2 = {title: cancelButton, value: false};
  4839. var message = msgString, title = titleString;
  4840. if(titleKey)
  4841. {
  4842. title = APP.translation.generateTranslatonHTML(titleKey, titleString);
  4843. }
  4844. if(msgKey) {
  4845. message = APP.translation.generateTranslatonHTML(msgKey, msgString);
  4846. }
  4847. $.prompt(message, {
  4848. title: title,
  4849. persistent: false,
  4850. buttons: buttons,
  4851. defaultButton: 1,
  4852. loaded: loadedFunction,
  4853. submit: submitFunction,
  4854. close: closeFunction
  4855. });
  4856. };
  4857. /**
  4858. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  4859. *
  4860. * @param titleString the title of the message
  4861. * @param msgString the text of the message
  4862. * @param persistent boolean value which determines whether the message is persistent or not
  4863. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  4864. * that will be passed to submitFunction
  4865. * @param submitFunction function to be called on submit
  4866. * @param loadedFunction function to be called after the prompt is fully loaded
  4867. */
  4868. my.openDialog = function (titleString, msgString, persistent, buttons,
  4869. submitFunction, loadedFunction) {
  4870. var args = {
  4871. title: titleString,
  4872. persistent: persistent,
  4873. buttons: buttons,
  4874. defaultButton: 1,
  4875. loaded: loadedFunction,
  4876. submit: submitFunction
  4877. };
  4878. if (persistent) {
  4879. args.closeText = '';
  4880. }
  4881. return $.prompt(msgString, args);
  4882. };
  4883. /**
  4884. * Closes currently opened dialog.
  4885. */
  4886. my.closeDialog = function () {
  4887. $.prompt.close();
  4888. };
  4889. /**
  4890. * Shows a dialog with different states to the user.
  4891. *
  4892. * @param statesObject object containing all the states of the dialog
  4893. * @param loadedFunction function to be called after the prompt is fully loaded
  4894. * @param stateChangedFunction function to be called when the state of the dialog is changed
  4895. */
  4896. my.openDialogWithStates = function(statesObject, loadedFunction, stateChangedFunction) {
  4897. var myPrompt = $.prompt(statesObject);
  4898. myPrompt.on('impromptu:loaded', loadedFunction);
  4899. myPrompt.on('impromptu:statechanged', stateChangedFunction);
  4900. };
  4901. /**
  4902. * Opens new popup window for given <tt>url</tt> centered over current
  4903. * window.
  4904. *
  4905. * @param url the URL to be displayed in the popup window
  4906. * @param w the width of the popup window
  4907. * @param h the height of the popup window
  4908. * @param onPopupClosed optional callback function called when popup window
  4909. * has been closed.
  4910. *
  4911. * @returns popup window object if opened successfully or undefined
  4912. * in case we failed to open it(popup blocked)
  4913. */
  4914. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  4915. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  4916. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  4917. var popup = window.open(
  4918. url, '_blank',
  4919. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  4920. if (popup && onPopupClosed) {
  4921. var pollTimer = window.setInterval(function () {
  4922. if (popup.closed !== false) {
  4923. window.clearInterval(pollTimer);
  4924. onPopupClosed();
  4925. }
  4926. }, 200);
  4927. }
  4928. return popup;
  4929. };
  4930. /**
  4931. * Shows a dialog prompting the user to send an error report.
  4932. *
  4933. * @param titleString the title of the message
  4934. * @param msgString the text of the message
  4935. * @param error the error that is being reported
  4936. */
  4937. my.openReportDialog = function(titleKey, titleString, msgKey,
  4938. msgString, error) {
  4939. my.openMessageDialog(titleKey, titleString, msgKey, msgString);
  4940. console.log(error);
  4941. //FIXME send the error to the server
  4942. };
  4943. /**
  4944. * Shows an error dialog to the user.
  4945. * @param title the title of the message
  4946. * @param message the text of the messafe
  4947. */
  4948. my.showError = function(titleKey, title, msgKey, message) {
  4949. if(!titleKey) {
  4950. title = "Oops!";
  4951. titleKey = "dialog.oops";
  4952. }
  4953. if(!msgKey)
  4954. {
  4955. message = "There was some kind of error";
  4956. msgKey = "dialog.defaultError";
  4957. }
  4958. messageHandler.openMessageDialog(titleKey, title, msgKey, message);
  4959. };
  4960. my.notify = function(displayName, displayNameKey, displayNameDefault,
  4961. cls, messageKey, messageDefault, messageArguments) {
  4962. var displayNameSpan = '<span class="nickname" ';
  4963. if(displayName)
  4964. {
  4965. displayNameSpan += ">" + displayName;
  4966. }
  4967. else
  4968. {
  4969. displayNameSpan += "data-i18n='" + displayNameKey +
  4970. "'>" + APP.translation.translateString(displayNameKey, null,
  4971. {defaultValue: displayNameDefault});
  4972. }
  4973. displayNameSpan += "</span>";
  4974. var lMessageArguments = messageArguments;
  4975. if(!messageArguments)
  4976. lMessageArguments = {};
  4977. lMessageArguments.defaultValue = messageDefault;
  4978. toastr.info(
  4979. displayNameSpan + '<br>' +
  4980. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  4981. (messageArguments?
  4982. " i18n-options='" + JSON.stringify(messageArguments) + "'"
  4983. : "") + ">" +
  4984. APP.translation.translateString(messageKey, null,
  4985. lMessageArguments) +
  4986. '</span>');
  4987. };
  4988. return my;
  4989. }(messageHandler || {}));
  4990. module.exports = messageHandler;
  4991. },{}],28:[function(require,module,exports){
  4992. var UIEvents = require("../../../service/UI/UIEvents");
  4993. var nickname = null;
  4994. var eventEmitter = null;
  4995. var NickanameHandler = {
  4996. init: function (emitter) {
  4997. eventEmitter = emitter;
  4998. var storedDisplayName = window.localStorage.displayname;
  4999. if (storedDisplayName) {
  5000. nickname = storedDisplayName;
  5001. }
  5002. },
  5003. setNickname: function (newNickname) {
  5004. if (!newNickname || nickname === newNickname)
  5005. return;
  5006. nickname = newNickname;
  5007. window.localStorage.displayname = nickname;
  5008. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  5009. },
  5010. getNickname: function () {
  5011. return nickname;
  5012. },
  5013. addListener: function (type, listener) {
  5014. eventEmitter.on(type, listener);
  5015. }
  5016. };
  5017. module.exports = NickanameHandler;
  5018. },{"../../../service/UI/UIEvents":83}],29:[function(require,module,exports){
  5019. /**
  5020. * Created by hristo on 12/22/14.
  5021. */
  5022. module.exports = {
  5023. /**
  5024. * Returns the available video width.
  5025. */
  5026. getAvailableVideoWidth: function () {
  5027. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5028. var rightPanelWidth
  5029. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5030. return window.innerWidth - rightPanelWidth;
  5031. },
  5032. /**
  5033. * Changes the style class of the element given by id.
  5034. */
  5035. buttonClick: function(id, classname) {
  5036. $(id).toggleClass(classname); // add the class to the clicked element
  5037. },
  5038. /**
  5039. * Returns the text width for the given element.
  5040. *
  5041. * @param el the element
  5042. */
  5043. getTextWidth: function (el) {
  5044. return (el.clientWidth + 1);
  5045. },
  5046. /**
  5047. * Returns the text height for the given element.
  5048. *
  5049. * @param el the element
  5050. */
  5051. getTextHeight: function (el) {
  5052. return (el.clientHeight + 1);
  5053. },
  5054. /**
  5055. * Plays the sound given by id.
  5056. *
  5057. * @param id the identifier of the audio element.
  5058. */
  5059. playSoundNotification: function (id) {
  5060. document.getElementById(id).play();
  5061. },
  5062. /**
  5063. * Escapes the given text.
  5064. */
  5065. escapeHtml: function (unsafeText) {
  5066. return $('<div/>').text(unsafeText).html();
  5067. },
  5068. imageToGrayScale: function (canvas) {
  5069. var context = canvas.getContext('2d');
  5070. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5071. var pixels = imgData.data;
  5072. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5073. var grayscale
  5074. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5075. pixels[i ] = grayscale; // red
  5076. pixels[i+1] = grayscale; // green
  5077. pixels[i+2] = grayscale; // blue
  5078. // pixels[i+3] is alpha
  5079. }
  5080. // redraw the image in black & white
  5081. context.putImageData(imgData, 0, 0);
  5082. },
  5083. setTooltip: function (element, key, position) {
  5084. element.setAttribute("data-i18n", "[data-content]" + key);
  5085. element.setAttribute("data-toggle", "popover");
  5086. element.setAttribute("data-placement", position);
  5087. element.setAttribute("data-html", true);
  5088. element.setAttribute("data-container", "body");
  5089. }
  5090. };
  5091. },{"../side_pannels/SidePanelToggler":16}],30:[function(require,module,exports){
  5092. var JitsiPopover = require("../util/JitsiPopover");
  5093. /**
  5094. * Constructs new connection indicator.
  5095. * @param videoContainer the video container associated with the indicator.
  5096. * @constructor
  5097. */
  5098. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5099. {
  5100. this.videoContainer = videoContainer;
  5101. this.bandwidth = null;
  5102. this.packetLoss = null;
  5103. this.bitrate = null;
  5104. this.showMoreValue = false;
  5105. this.resolution = null;
  5106. this.transport = [];
  5107. this.popover = null;
  5108. this.jid = jid;
  5109. this.create();
  5110. this.videoLayout = VideoLayout;
  5111. }
  5112. /**
  5113. * Values for the connection quality
  5114. * @type {{98: string,
  5115. * 81: string,
  5116. * 64: string,
  5117. * 47: string,
  5118. * 30: string,
  5119. * 0: string}}
  5120. */
  5121. ConnectionIndicator.connectionQualityValues = {
  5122. 98: "18px", //full
  5123. 81: "15px",//4 bars
  5124. 64: "11px",//3 bars
  5125. 47: "7px",//2 bars
  5126. 30: "3px",//1 bar
  5127. 0: "0px"//empty
  5128. };
  5129. ConnectionIndicator.getIP = function(value)
  5130. {
  5131. return value.substring(0, value.lastIndexOf(":"));
  5132. };
  5133. ConnectionIndicator.getPort = function(value)
  5134. {
  5135. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5136. };
  5137. ConnectionIndicator.getStringFromArray = function (array) {
  5138. var res = "";
  5139. for(var i = 0; i < array.length; i++)
  5140. {
  5141. res += (i === 0? "" : ", ") + array[i];
  5142. }
  5143. return res;
  5144. };
  5145. /**
  5146. * Generates the html content.
  5147. * @returns {string} the html content.
  5148. */
  5149. ConnectionIndicator.prototype.generateText = function () {
  5150. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5151. var translate = APP.translation.translateString;
  5152. if(this.bitrate === null)
  5153. {
  5154. downloadBitrate = "N/A";
  5155. uploadBitrate = "N/A";
  5156. }
  5157. else
  5158. {
  5159. downloadBitrate =
  5160. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5161. uploadBitrate =
  5162. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5163. }
  5164. if(this.packetLoss === null)
  5165. {
  5166. packetLoss = "N/A";
  5167. }
  5168. else
  5169. {
  5170. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5171. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5172. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5173. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5174. }
  5175. var resolutionValue = null;
  5176. if(this.resolution && this.jid != null)
  5177. {
  5178. var keys = Object.keys(this.resolution);
  5179. if(keys.length == 1)
  5180. {
  5181. for(var ssrc in this.resolution)
  5182. {
  5183. resolutionValue = this.resolution[ssrc];
  5184. }
  5185. }
  5186. else if(keys.length > 1)
  5187. {
  5188. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  5189. resolutionValue = this.resolution[displayedSsrc];
  5190. }
  5191. }
  5192. if(this.jid === null)
  5193. {
  5194. resolution = "";
  5195. if(this.resolution === null || !Object.keys(this.resolution) ||
  5196. Object.keys(this.resolution).length === 0)
  5197. {
  5198. resolution = "N/A";
  5199. }
  5200. else
  5201. for(i in this.resolution)
  5202. {
  5203. resolutionValue = this.resolution[i];
  5204. if(resolutionValue)
  5205. {
  5206. if(resolutionValue.height &&
  5207. resolutionValue.width)
  5208. {
  5209. resolution += (resolution === ""? "" : ", ") +
  5210. resolutionValue.width + "x" +
  5211. resolutionValue.height;
  5212. }
  5213. }
  5214. }
  5215. }
  5216. else if(!resolutionValue ||
  5217. !resolutionValue.height ||
  5218. !resolutionValue.width)
  5219. {
  5220. resolution = "N/A";
  5221. }
  5222. else
  5223. {
  5224. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5225. }
  5226. var result = "<table style='width:100%'>" +
  5227. "<tr>" +
  5228. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5229. translate("connectionindicator.bitrate") + "</span></td>" +
  5230. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5231. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5232. uploadBitrate + "</td>" +
  5233. "</tr><tr>" +
  5234. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5235. translate("connectionindicator.packetloss") + "</span></td>" +
  5236. "<td>" + packetLoss + "</td>" +
  5237. "</tr><tr>" +
  5238. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5239. translate("connectionindicator.resolution") + "</span></td>" +
  5240. "<td>" + resolution + "</td></tr></table>";
  5241. if(this.videoContainer.id == "localVideoContainer") {
  5242. result += "<div class=\"jitsipopover_showmore\" " +
  5243. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5244. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5245. (this.showMoreValue ? "less" : "more") + "'>" +
  5246. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5247. "</div><br />";
  5248. }
  5249. if(this.showMoreValue)
  5250. {
  5251. var downloadBandwidth, uploadBandwidth, transport;
  5252. if(this.bandwidth === null)
  5253. {
  5254. downloadBandwidth = "N/A";
  5255. uploadBandwidth = "N/A";
  5256. }
  5257. else
  5258. {
  5259. downloadBandwidth = this.bandwidth.download?
  5260. this.bandwidth.download + " Kbps" :
  5261. "N/A";
  5262. uploadBandwidth = this.bandwidth.upload?
  5263. this.bandwidth.upload + " Kbps" :
  5264. "N/A";
  5265. }
  5266. if(!this.transport || this.transport.length === 0)
  5267. {
  5268. transport = "<tr>" +
  5269. "<td><span class='jitsipopover_blue' " +
  5270. "data-i18n='connectionindicator.address'>" +
  5271. translate("connectionindicator.address") + "</span></td>" +
  5272. "<td> N/A</td></tr>";
  5273. }
  5274. else
  5275. {
  5276. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5277. for(i = 0; i < this.transport.length; i++)
  5278. {
  5279. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5280. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5281. var localIP =
  5282. ConnectionIndicator.getIP(this.transport[i].localip);
  5283. var localPort =
  5284. ConnectionIndicator.getPort(this.transport[i].localip);
  5285. if(data.remoteIP.indexOf(ip) == -1)
  5286. {
  5287. data.remoteIP.push(ip);
  5288. }
  5289. if(data.remotePort.indexOf(port) == -1)
  5290. {
  5291. data.remotePort.push(port);
  5292. }
  5293. if(data.localIP.indexOf(localIP) == -1)
  5294. {
  5295. data.localIP.push(localIP);
  5296. }
  5297. if(data.localPort.indexOf(localPort) == -1)
  5298. {
  5299. data.localPort.push(localPort);
  5300. }
  5301. }
  5302. var local_address_key = "connectionindicator." +
  5303. (data.localIP.length > 1? "localaddresses" : "localaddress");
  5304. var remote_address_key = "connectionindicator." +
  5305. (data.remoteIP.length > 1? "remoteaddresses" : "remoteaddress");
  5306. var localTransport =
  5307. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5308. local_address_key +"'>" +
  5309. translate(local_address_key) + "</span></td><td> " +
  5310. ConnectionIndicator.getStringFromArray(data.localIP) +
  5311. "</td></tr>";
  5312. transport =
  5313. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5314. remote_address_key + "'>" +
  5315. translate(remote_address_key) + "</span></td><td> " +
  5316. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5317. "</td></tr>";
  5318. var key_remote = "connectionindicator.",
  5319. key_local = "connectionindicator.";
  5320. if(this.transport.length > 1)
  5321. {
  5322. key_remote += "remoteports";
  5323. key_local += "localports";
  5324. }
  5325. else
  5326. {
  5327. key_remote += "remoteport";
  5328. key_local += "localport";
  5329. }
  5330. transport += "<tr>" +
  5331. "<td>" +
  5332. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5333. "'>" +
  5334. translate(key_remote) + "</span></td><td>";
  5335. localTransport += "<tr>" +
  5336. "<td>" +
  5337. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5338. "'>" +
  5339. translate(key_local) + "</span></td><td>";
  5340. transport +=
  5341. ConnectionIndicator.getStringFromArray(data.remotePort);
  5342. localTransport +=
  5343. ConnectionIndicator.getStringFromArray(data.localPort);
  5344. transport += "</td></tr>";
  5345. transport += localTransport + "</td></tr>";
  5346. transport +="<tr>" +
  5347. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5348. translate("connectionindicator.transport") + "</span></td>" +
  5349. "<td>" + this.transport[0].type + "</td></tr>";
  5350. }
  5351. result += "<table style='width:100%'>" +
  5352. "<tr>" +
  5353. "<td>" +
  5354. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5355. translate("connectionindicator.bandwidth") + "</span>" +
  5356. "</td><td>" +
  5357. "<span class='jitsipopover_green'>&darr;</span>" +
  5358. downloadBandwidth +
  5359. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5360. uploadBandwidth + "</td></tr>";
  5361. result += transport + "</table>";
  5362. }
  5363. return result;
  5364. };
  5365. /**
  5366. * Shows or hide the additional information.
  5367. */
  5368. ConnectionIndicator.prototype.showMore = function () {
  5369. this.showMoreValue = !this.showMoreValue;
  5370. this.updatePopoverData();
  5371. };
  5372. function createIcon(classes)
  5373. {
  5374. var icon = document.createElement("span");
  5375. for(var i in classes)
  5376. {
  5377. icon.classList.add(classes[i]);
  5378. }
  5379. icon.appendChild(
  5380. document.createElement("i")).classList.add("icon-connection");
  5381. return icon;
  5382. }
  5383. /**
  5384. * Creates the indicator
  5385. */
  5386. ConnectionIndicator.prototype.create = function () {
  5387. this.connectionIndicatorContainer = document.createElement("div");
  5388. this.connectionIndicatorContainer.className = "connectionindicator";
  5389. this.connectionIndicatorContainer.style.display = "none";
  5390. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5391. this.popover = new JitsiPopover(
  5392. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5393. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5394. APP.translation.translateString("connectionindicator.na") + "</div>",
  5395. skin: "black"});
  5396. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5397. createIcon(["connection", "connection_empty"]));
  5398. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5399. createIcon(["connection", "connection_full"]));
  5400. };
  5401. /**
  5402. * Removes the indicator
  5403. */
  5404. ConnectionIndicator.prototype.remove = function()
  5405. {
  5406. this.connectionIndicatorContainer.remove();
  5407. this.popover.forceHide();
  5408. };
  5409. /**
  5410. * Updates the data of the indicator
  5411. * @param percent the percent of connection quality
  5412. * @param object the statistics data.
  5413. */
  5414. ConnectionIndicator.prototype.updateConnectionQuality =
  5415. function (percent, object) {
  5416. if(percent === null)
  5417. {
  5418. this.connectionIndicatorContainer.style.display = "none";
  5419. this.popover.forceHide();
  5420. return;
  5421. }
  5422. else
  5423. {
  5424. if(this.connectionIndicatorContainer.style.display == "none") {
  5425. this.connectionIndicatorContainer.style.display = "block";
  5426. this.videoLayout.updateMutePosition(this.videoContainer.id);
  5427. }
  5428. }
  5429. this.bandwidth = object.bandwidth;
  5430. this.bitrate = object.bitrate;
  5431. this.packetLoss = object.packetLoss;
  5432. this.transport = object.transport;
  5433. if(object.resolution)
  5434. {
  5435. this.resolution = object.resolution;
  5436. }
  5437. for(var quality in ConnectionIndicator.connectionQualityValues)
  5438. {
  5439. if(percent >= quality)
  5440. {
  5441. this.fullIcon.style.width =
  5442. ConnectionIndicator.connectionQualityValues[quality];
  5443. }
  5444. }
  5445. this.updatePopoverData();
  5446. };
  5447. /**
  5448. * Updates the resolution
  5449. * @param resolution the new resolution
  5450. */
  5451. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  5452. this.resolution = resolution;
  5453. this.updatePopoverData();
  5454. };
  5455. /**
  5456. * Updates the content of the popover
  5457. */
  5458. ConnectionIndicator.prototype.updatePopoverData = function () {
  5459. this.popover.updateContent(
  5460. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  5461. APP.translation.translateElement($(".connection_info"));
  5462. };
  5463. /**
  5464. * Hides the popover
  5465. */
  5466. ConnectionIndicator.prototype.hide = function () {
  5467. this.popover.forceHide();
  5468. };
  5469. /**
  5470. * Hides the indicator
  5471. */
  5472. ConnectionIndicator.prototype.hideIndicator = function () {
  5473. this.connectionIndicatorContainer.style.display = "none";
  5474. if(this.popover)
  5475. this.popover.forceHide();
  5476. };
  5477. module.exports = ConnectionIndicator;
  5478. },{"../util/JitsiPopover":26}],31:[function(require,module,exports){
  5479. var AudioLevels = require("../audio_levels/AudioLevels");
  5480. var Avatar = require("../avatar/Avatar");
  5481. var Chat = require("../side_pannels/chat/Chat");
  5482. var ContactList = require("../side_pannels/contactlist/ContactList");
  5483. var UIUtil = require("../util/UIUtil");
  5484. var ConnectionIndicator = require("./ConnectionIndicator");
  5485. var NicknameHandler = require("../util/NicknameHandler");
  5486. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  5487. var UIEvents = require("../../../service/UI/UIEvents");
  5488. var currentDominantSpeaker = null;
  5489. var lastNCount = config.channelLastN;
  5490. var localLastNCount = config.channelLastN;
  5491. var localLastNSet = [];
  5492. var lastNEndpointsCache = [];
  5493. var lastNPickupJid = null;
  5494. var largeVideoState = {
  5495. updateInProgress: false,
  5496. newSrc: ''
  5497. };
  5498. var eventEmitter = null;
  5499. /**
  5500. * Currently focused video "src"(displayed in large video).
  5501. * @type {String}
  5502. */
  5503. var focusedVideoInfo = null;
  5504. /**
  5505. * Indicates if we have muted our audio before the conference has started.
  5506. * @type {boolean}
  5507. */
  5508. var preMuted = false;
  5509. var mutedAudios = {};
  5510. var flipXLocalVideo = true;
  5511. var currentVideoWidth = null;
  5512. var currentVideoHeight = null;
  5513. var localVideoSrc = null;
  5514. function videoactive( videoelem) {
  5515. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  5516. // ignore mixedmslabela0 and v0
  5517. videoelem.show();
  5518. VideoLayout.resizeThumbnails();
  5519. var videoParent = videoelem.parent();
  5520. var parentResourceJid = null;
  5521. if (videoParent)
  5522. parentResourceJid
  5523. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  5524. // Update the large video to the last added video only if there's no
  5525. // current dominant, focused speaker or prezi playing or update it to
  5526. // the current dominant speaker.
  5527. if ((!focusedVideoInfo &&
  5528. !VideoLayout.getDominantSpeakerResourceJid() &&
  5529. !require("../prezi/Prezi").isPresentationVisible()) ||
  5530. (parentResourceJid &&
  5531. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  5532. VideoLayout.updateLargeVideo(
  5533. APP.RTC.getVideoSrc(videoelem[0]),
  5534. 1,
  5535. parentResourceJid);
  5536. }
  5537. VideoLayout.showModeratorIndicator();
  5538. }
  5539. }
  5540. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  5541. // XXX(gp) so, every call to this function is *always* preceded by a call
  5542. // to the RTC.attachMediaStream() function but that call is *not* followed
  5543. // by an update to the videoSrcToSsrc map!
  5544. //
  5545. // The above way of doing things results in video SRCs that don't correspond
  5546. // to any SSRC for a short period of time (to be more precise, for as long
  5547. // the waitForRemoteVideo takes to complete). This causes problems (see
  5548. // bellow).
  5549. //
  5550. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  5551. // a second time in here and only then update the videoSrcToSsrc map? Why
  5552. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  5553. // is called the first time? I actually do that in the lastN changed event
  5554. // handler because the "orphan" video SRC is causing troubles there. The
  5555. // purpose of this method would then be to fire the "videoactive.jingle".
  5556. //
  5557. // Food for though I guess :-)
  5558. if (selector.removed || !selector.parent().is(":visible")) {
  5559. console.warn("Media removed before had started", selector);
  5560. return;
  5561. }
  5562. if (stream.id === 'mixedmslabel') return;
  5563. if (selector[0].currentTime > 0) {
  5564. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  5565. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  5566. videoactive(selector);
  5567. } else {
  5568. setTimeout(function () {
  5569. waitForRemoteVideo(selector, ssrc, stream, jid);
  5570. }, 250);
  5571. }
  5572. }
  5573. /**
  5574. * Returns an array of the video horizontal and vertical indents,
  5575. * so that if fits its parent.
  5576. *
  5577. * @return an array with 2 elements, the horizontal indent and the vertical
  5578. * indent
  5579. */
  5580. function getCameraVideoPosition(videoWidth,
  5581. videoHeight,
  5582. videoSpaceWidth,
  5583. videoSpaceHeight) {
  5584. // Parent height isn't completely calculated when we position the video in
  5585. // full screen mode and this is why we use the screen height in this case.
  5586. // Need to think it further at some point and implement it properly.
  5587. var isFullScreen = document.fullScreen ||
  5588. document.mozFullScreen ||
  5589. document.webkitIsFullScreen;
  5590. if (isFullScreen)
  5591. videoSpaceHeight = window.innerHeight;
  5592. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5593. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  5594. return [horizontalIndent, verticalIndent];
  5595. }
  5596. /**
  5597. * Returns an array of the video horizontal and vertical indents.
  5598. * Centers horizontally and top aligns vertically.
  5599. *
  5600. * @return an array with 2 elements, the horizontal indent and the vertical
  5601. * indent
  5602. */
  5603. function getDesktopVideoPosition(videoWidth,
  5604. videoHeight,
  5605. videoSpaceWidth,
  5606. videoSpaceHeight) {
  5607. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5608. var verticalIndent = 0;// Top aligned
  5609. return [horizontalIndent, verticalIndent];
  5610. }
  5611. /**
  5612. * Returns an array of the video dimensions, so that it covers the screen.
  5613. * It leaves no empty areas, but some parts of the video might not be visible.
  5614. *
  5615. * @return an array with 2 elements, the video width and the video height
  5616. */
  5617. function getCameraVideoSize(videoWidth,
  5618. videoHeight,
  5619. videoSpaceWidth,
  5620. videoSpaceHeight) {
  5621. if (!videoWidth)
  5622. videoWidth = currentVideoWidth;
  5623. if (!videoHeight)
  5624. videoHeight = currentVideoHeight;
  5625. var aspectRatio = videoWidth / videoHeight;
  5626. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5627. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5628. if (availableWidth / aspectRatio < videoSpaceHeight) {
  5629. availableHeight = videoSpaceHeight;
  5630. availableWidth = availableHeight * aspectRatio;
  5631. }
  5632. if (availableHeight * aspectRatio < videoSpaceWidth) {
  5633. availableWidth = videoSpaceWidth;
  5634. availableHeight = availableWidth / aspectRatio;
  5635. }
  5636. return [availableWidth, availableHeight];
  5637. }
  5638. /**
  5639. * Sets the display name for the given video span id.
  5640. */
  5641. function setDisplayName(videoSpanId, displayName) {
  5642. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  5643. var defaultLocalDisplayName = interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME;
  5644. // If we already have a display name for this video.
  5645. if (nameSpan.length > 0) {
  5646. var nameSpanElement = nameSpan.get(0);
  5647. if (nameSpanElement.id === 'localDisplayName' &&
  5648. $('#localDisplayName').text() !== displayName) {
  5649. if (displayName && displayName.length > 0)
  5650. $('#localDisplayName').html(displayName + ' (me)');
  5651. else
  5652. $('#localDisplayName').text(defaultLocalDisplayName);
  5653. } else {
  5654. if (displayName && displayName.length > 0)
  5655. $('#' + videoSpanId + '_name').html(displayName);
  5656. else
  5657. $('#' + videoSpanId + '_name').text(interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  5658. }
  5659. } else {
  5660. var editButton = null;
  5661. nameSpan = document.createElement('span');
  5662. nameSpan.className = 'displayname';
  5663. $('#' + videoSpanId)[0].appendChild(nameSpan);
  5664. if (videoSpanId === 'localVideoContainer') {
  5665. editButton = createEditDisplayNameButton();
  5666. nameSpan.innerText = defaultLocalDisplayName;
  5667. }
  5668. else {
  5669. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  5670. }
  5671. if (displayName && displayName.length > 0) {
  5672. nameSpan.innerText = displayName;
  5673. }
  5674. if (!editButton) {
  5675. nameSpan.id = videoSpanId + '_name';
  5676. } else {
  5677. nameSpan.id = 'localDisplayName';
  5678. $('#' + videoSpanId)[0].appendChild(editButton);
  5679. //translates popover of edit button
  5680. APP.translation.translateElement($("a.displayname"));
  5681. var editableText = document.createElement('input');
  5682. editableText.className = 'displayname';
  5683. editableText.type = 'text';
  5684. editableText.id = 'editDisplayName';
  5685. if (displayName && displayName.length) {
  5686. editableText.value
  5687. = displayName.substring(0, displayName.indexOf(' (me)'));
  5688. }
  5689. editableText.setAttribute('style', 'display:none;');
  5690. editableText.setAttribute('placeholder', 'ex. Jane Pink');
  5691. $('#' + videoSpanId)[0].appendChild(editableText);
  5692. $('#localVideoContainer .displayname')
  5693. .bind("click", function (e) {
  5694. e.preventDefault();
  5695. e.stopPropagation();
  5696. $('#localDisplayName').hide();
  5697. $('#editDisplayName').show();
  5698. $('#editDisplayName').focus();
  5699. $('#editDisplayName').select();
  5700. $('#editDisplayName').one("focusout", function (e) {
  5701. VideoLayout.inputDisplayNameHandler(this.value);
  5702. });
  5703. $('#editDisplayName').on('keydown', function (e) {
  5704. if (e.keyCode === 13) {
  5705. e.preventDefault();
  5706. VideoLayout.inputDisplayNameHandler(this.value);
  5707. }
  5708. });
  5709. });
  5710. }
  5711. }
  5712. }
  5713. /**
  5714. * Gets the selector of video thumbnail container for the user identified by
  5715. * given <tt>userJid</tt>
  5716. * @param resourceJid user's Jid for whom we want to get the video container.
  5717. */
  5718. function getParticipantContainer(resourceJid)
  5719. {
  5720. if (!resourceJid)
  5721. return null;
  5722. if (resourceJid === APP.xmpp.myResource())
  5723. return $("#localVideoContainer");
  5724. else
  5725. return $("#participant_" + resourceJid);
  5726. }
  5727. /**
  5728. * Sets the size and position of the given video element.
  5729. *
  5730. * @param video the video element to position
  5731. * @param width the desired video width
  5732. * @param height the desired video height
  5733. * @param horizontalIndent the left and right indent
  5734. * @param verticalIndent the top and bottom indent
  5735. */
  5736. function positionVideo(video,
  5737. width,
  5738. height,
  5739. horizontalIndent,
  5740. verticalIndent) {
  5741. video.width(width);
  5742. video.height(height);
  5743. video.css({ top: verticalIndent + 'px',
  5744. bottom: verticalIndent + 'px',
  5745. left: horizontalIndent + 'px',
  5746. right: horizontalIndent + 'px'});
  5747. }
  5748. /**
  5749. * Adds the remote video menu element for the given <tt>jid</tt> in the
  5750. * given <tt>parentElement</tt>.
  5751. *
  5752. * @param jid the jid indicating the video for which we're adding a menu.
  5753. * @param parentElement the parent element where this menu will be added
  5754. */
  5755. function addRemoteVideoMenu(jid, parentElement) {
  5756. var spanElement = document.createElement('span');
  5757. spanElement.className = 'remotevideomenu';
  5758. parentElement.appendChild(spanElement);
  5759. var menuElement = document.createElement('i');
  5760. menuElement.className = 'fa fa-angle-down';
  5761. menuElement.title = 'Remote user controls';
  5762. spanElement.appendChild(menuElement);
  5763. // <ul class="popupmenu">
  5764. // <li><a href="#">Mute</a></li>
  5765. // <li><a href="#">Eject</a></li>
  5766. // </ul>
  5767. var popupmenuElement = document.createElement('ul');
  5768. popupmenuElement.className = 'popupmenu';
  5769. popupmenuElement.id
  5770. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  5771. spanElement.appendChild(popupmenuElement);
  5772. var muteMenuItem = document.createElement('li');
  5773. var muteLinkItem = document.createElement('a');
  5774. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  5775. if (!mutedAudios[jid]) {
  5776. muteLinkItem.innerHTML = mutedIndicator +
  5777. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  5778. muteLinkItem.className = 'mutelink';
  5779. }
  5780. else {
  5781. muteLinkItem.innerHTML = mutedIndicator +
  5782. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  5783. muteLinkItem.className = 'mutelink disabled';
  5784. }
  5785. muteLinkItem.onclick = function(){
  5786. if ($(this).attr('disabled') != undefined) {
  5787. event.preventDefault();
  5788. }
  5789. var isMute = mutedAudios[jid] == true;
  5790. APP.xmpp.setMute(jid, !isMute);
  5791. popupmenuElement.setAttribute('style', 'display:none;');
  5792. if (isMute) {
  5793. this.innerHTML = mutedIndicator +
  5794. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  5795. this.className = 'mutelink disabled';
  5796. }
  5797. else {
  5798. this.innerHTML = mutedIndicator +
  5799. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  5800. this.className = 'mutelink';
  5801. }
  5802. };
  5803. muteMenuItem.appendChild(muteLinkItem);
  5804. popupmenuElement.appendChild(muteMenuItem);
  5805. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  5806. var ejectMenuItem = document.createElement('li');
  5807. var ejectLinkItem = document.createElement('a');
  5808. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  5809. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  5810. ejectLinkItem.onclick = function(){
  5811. APP.xmpp.eject(jid);
  5812. popupmenuElement.setAttribute('style', 'display:none;');
  5813. };
  5814. ejectMenuItem.appendChild(ejectLinkItem);
  5815. popupmenuElement.appendChild(ejectMenuItem);
  5816. var paddingSpan = document.createElement('span');
  5817. paddingSpan.className = 'popupmenuPadding';
  5818. popupmenuElement.appendChild(paddingSpan);
  5819. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  5820. }
  5821. /**
  5822. * Removes remote video menu element from video element identified by
  5823. * given <tt>videoElementId</tt>.
  5824. *
  5825. * @param videoElementId the id of local or remote video element.
  5826. */
  5827. function removeRemoteVideoMenu(videoElementId) {
  5828. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  5829. if (menuSpan.length) {
  5830. menuSpan.remove();
  5831. }
  5832. }
  5833. /**
  5834. * Updates the data for the indicator
  5835. * @param id the id of the indicator
  5836. * @param percent the percent for connection quality
  5837. * @param object the data
  5838. */
  5839. function updateStatsIndicator(id, percent, object) {
  5840. if(VideoLayout.connectionIndicators[id])
  5841. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  5842. }
  5843. /**
  5844. * Returns an array of the video dimensions, so that it keeps it's aspect
  5845. * ratio and fits available area with it's larger dimension. This method
  5846. * ensures that whole video will be visible and can leave empty areas.
  5847. *
  5848. * @return an array with 2 elements, the video width and the video height
  5849. */
  5850. function getDesktopVideoSize(videoWidth,
  5851. videoHeight,
  5852. videoSpaceWidth,
  5853. videoSpaceHeight) {
  5854. if (!videoWidth)
  5855. videoWidth = currentVideoWidth;
  5856. if (!videoHeight)
  5857. videoHeight = currentVideoHeight;
  5858. var aspectRatio = videoWidth / videoHeight;
  5859. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5860. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5861. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  5862. if (availableWidth / aspectRatio >= videoSpaceHeight)
  5863. {
  5864. availableHeight = videoSpaceHeight;
  5865. availableWidth = availableHeight * aspectRatio;
  5866. }
  5867. if (availableHeight * aspectRatio >= videoSpaceWidth)
  5868. {
  5869. availableWidth = videoSpaceWidth;
  5870. availableHeight = availableWidth / aspectRatio;
  5871. }
  5872. return [availableWidth, availableHeight];
  5873. }
  5874. /**
  5875. * Creates the edit display name button.
  5876. *
  5877. * @returns the edit button
  5878. */
  5879. function createEditDisplayNameButton() {
  5880. var editButton = document.createElement('a');
  5881. editButton.className = 'displayname';
  5882. UIUtil.setTooltip(editButton,
  5883. "videothumbnail.editnickname",
  5884. "top");
  5885. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  5886. return editButton;
  5887. }
  5888. /**
  5889. * Creates the element indicating the moderator(owner) of the conference.
  5890. *
  5891. * @param parentElement the parent element where the owner indicator will
  5892. * be added
  5893. */
  5894. function createModeratorIndicatorElement(parentElement) {
  5895. var moderatorIndicator = document.createElement('i');
  5896. moderatorIndicator.className = 'fa fa-star';
  5897. parentElement.appendChild(moderatorIndicator);
  5898. UIUtil.setTooltip(parentElement,
  5899. "videothumbnail.moderator",
  5900. "top");
  5901. }
  5902. var VideoLayout = (function (my) {
  5903. my.connectionIndicators = {};
  5904. // By default we use camera
  5905. my.getVideoSize = getCameraVideoSize;
  5906. my.getVideoPosition = getCameraVideoPosition;
  5907. my.init = function (emitter) {
  5908. // Listen for large video size updates
  5909. document.getElementById('largeVideo')
  5910. .addEventListener('loadedmetadata', function (e) {
  5911. currentVideoWidth = this.videoWidth;
  5912. currentVideoHeight = this.videoHeight;
  5913. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  5914. });
  5915. eventEmitter = emitter;
  5916. };
  5917. my.isInLastN = function(resource) {
  5918. return lastNCount < 0 // lastN is disabled, return true
  5919. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  5920. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  5921. };
  5922. my.changeLocalStream = function (stream) {
  5923. VideoLayout.changeLocalVideo(stream);
  5924. };
  5925. my.changeLocalAudio = function(stream) {
  5926. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  5927. document.getElementById('localAudio').autoplay = true;
  5928. document.getElementById('localAudio').volume = 0;
  5929. if (preMuted) {
  5930. if(!APP.UI.setAudioMuted(true))
  5931. {
  5932. preMuted = mute;
  5933. }
  5934. preMuted = false;
  5935. }
  5936. };
  5937. my.changeLocalVideo = function(stream) {
  5938. var flipX = true;
  5939. if(stream.videoType == "screen")
  5940. flipX = false;
  5941. var localVideo = document.createElement('video');
  5942. localVideo.id = 'localVideo_' +
  5943. APP.RTC.getStreamID(stream.getOriginalStream());
  5944. localVideo.autoplay = true;
  5945. localVideo.volume = 0; // is it required if audio is separated ?
  5946. localVideo.oncontextmenu = function () { return false; };
  5947. var localVideoContainer = document.getElementById('localVideoWrapper');
  5948. localVideoContainer.appendChild(localVideo);
  5949. // Set default display name.
  5950. setDisplayName('localVideoContainer');
  5951. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  5952. VideoLayout.connectionIndicators["localVideoContainer"]
  5953. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  5954. }
  5955. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  5956. var localVideoSelector = $('#' + localVideo.id);
  5957. function localVideoClick(event) {
  5958. event.stopPropagation();
  5959. VideoLayout.handleVideoThumbClicked(
  5960. APP.RTC.getVideoSrc(localVideo),
  5961. false,
  5962. APP.xmpp.myResource());
  5963. }
  5964. // Add click handler to both video and video wrapper elements in case
  5965. // there's no video.
  5966. localVideoSelector.click(localVideoClick);
  5967. $('#localVideoContainer').click(localVideoClick);
  5968. // Add hover handler
  5969. $('#localVideoContainer').hover(
  5970. function() {
  5971. VideoLayout.showDisplayName('localVideoContainer', true);
  5972. },
  5973. function() {
  5974. if (!VideoLayout.isLargeVideoVisible()
  5975. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  5976. VideoLayout.showDisplayName('localVideoContainer', false);
  5977. }
  5978. );
  5979. // Add stream ended handler
  5980. stream.getOriginalStream().onended = function () {
  5981. localVideoContainer.removeChild(localVideo);
  5982. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  5983. };
  5984. // Flip video x axis if needed
  5985. flipXLocalVideo = flipX;
  5986. if (flipX) {
  5987. localVideoSelector.addClass("flipVideoX");
  5988. }
  5989. // Attach WebRTC stream
  5990. var videoStream = APP.simulcast.getLocalVideoStream();
  5991. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  5992. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  5993. var myResourceJid = APP.xmpp.myResource();
  5994. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  5995. myResourceJid);
  5996. };
  5997. /**
  5998. * Checks if removed video is currently displayed and tries to display
  5999. * another one instead.
  6000. * @param removedVideoSrc src stream identifier of the video.
  6001. */
  6002. my.updateRemovedVideo = function(removedVideoSrc) {
  6003. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  6004. // this is currently displayed as large
  6005. // pick the last visible video in the row
  6006. // if nobody else is left, this picks the local video
  6007. var pick
  6008. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  6009. .get(0);
  6010. if (!pick) {
  6011. console.info("Last visible video no longer exists");
  6012. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  6013. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  6014. // Try local video
  6015. console.info("Fallback to local video...");
  6016. pick = $('#remoteVideos>span>span>video').get(0);
  6017. }
  6018. }
  6019. // mute if localvideo
  6020. if (pick) {
  6021. var container = pick.parentNode;
  6022. var jid = null;
  6023. if(container)
  6024. {
  6025. if(container.id == "localVideoWrapper")
  6026. {
  6027. jid = APP.xmpp.myResource();
  6028. }
  6029. else
  6030. {
  6031. jid = VideoLayout.getPeerContainerResourceJid(container);
  6032. }
  6033. }
  6034. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(pick), pick.volume, jid);
  6035. } else {
  6036. console.warn("Failed to elect large video");
  6037. }
  6038. }
  6039. };
  6040. my.onRemoteStreamAdded = function (stream) {
  6041. var container;
  6042. var remotes = document.getElementById('remoteVideos');
  6043. if (stream.peerjid) {
  6044. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6045. container = document.getElementById(
  6046. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6047. } else {
  6048. var id = stream.getOriginalStream().id;
  6049. if (id !== 'mixedmslabel'
  6050. // FIXME: default stream is added always with new focus
  6051. // (to be investigated)
  6052. && id !== 'default') {
  6053. console.error('can not associate stream',
  6054. id,
  6055. 'with a participant');
  6056. // We don't want to add it here since it will cause troubles
  6057. return;
  6058. }
  6059. // FIXME: for the mixed ms we dont need a video -- currently
  6060. container = document.createElement('span');
  6061. container.id = 'mixedstream';
  6062. container.className = 'videocontainer';
  6063. remotes.appendChild(container);
  6064. UIUtil.playSoundNotification('userJoined');
  6065. }
  6066. if (container) {
  6067. VideoLayout.addRemoteStreamElement( container,
  6068. stream.sid,
  6069. stream.getOriginalStream(),
  6070. stream.peerjid,
  6071. stream.ssrc);
  6072. }
  6073. }
  6074. my.getLargeVideoState = function () {
  6075. return largeVideoState;
  6076. };
  6077. /**
  6078. * Updates the large video with the given new video source.
  6079. */
  6080. my.updateLargeVideo = function(newSrc, vol, resourceJid) {
  6081. console.log('hover in', newSrc);
  6082. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc) {
  6083. $('#activeSpeaker').css('visibility', 'hidden');
  6084. // Due to the simulcast the localVideoSrc may have changed when the
  6085. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6086. // isVideoSrcDesktop methods will not function correctly.
  6087. //
  6088. // Also, again due to the simulcast, the updateLargeVideo method can
  6089. // be called multiple times almost simultaneously. Therefore, we
  6090. // store the state here and update only once.
  6091. largeVideoState.newSrc = newSrc;
  6092. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6093. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(resourceJid);
  6094. if(largeVideoState.userResourceJid) {
  6095. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6096. } else {
  6097. largeVideoState.oldResourceJid = null;
  6098. }
  6099. largeVideoState.userResourceJid = resourceJid;
  6100. // Screen stream is already rotated
  6101. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6102. var userChanged = false;
  6103. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6104. userChanged = true;
  6105. // we want the notification to trigger even if userJid is undefined,
  6106. // or null.
  6107. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6108. largeVideoState.userResourceJid);
  6109. }
  6110. if (!largeVideoState.updateInProgress) {
  6111. largeVideoState.updateInProgress = true;
  6112. var doUpdate = function () {
  6113. Avatar.updateActiveSpeakerAvatarSrc(
  6114. APP.xmpp.findJidFromResource(
  6115. largeVideoState.userResourceJid));
  6116. if (!userChanged && largeVideoState.preload &&
  6117. largeVideoState.preload !== null &&
  6118. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  6119. {
  6120. console.info('Switching to preloaded video');
  6121. var attributes = $('#largeVideo').prop("attributes");
  6122. // loop through largeVideo attributes and apply them on
  6123. // preload.
  6124. $.each(attributes, function () {
  6125. if (this.name !== 'id' && this.name !== 'src') {
  6126. largeVideoState.preload.attr(this.name, this.value);
  6127. }
  6128. });
  6129. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  6130. $('#largeVideo').attr('id', 'previousLargeVideo');
  6131. largeVideoState.preload.attr('id', 'largeVideo');
  6132. $('#previousLargeVideo').remove();
  6133. largeVideoState.preload.on('loadedmetadata', function (e) {
  6134. currentVideoWidth = this.videoWidth;
  6135. currentVideoHeight = this.videoHeight;
  6136. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6137. });
  6138. largeVideoState.preload = null;
  6139. largeVideoState.preload_ssrc = 0;
  6140. } else {
  6141. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6142. }
  6143. var videoTransform = document.getElementById('largeVideo')
  6144. .style.webkitTransform;
  6145. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6146. document.getElementById('largeVideo').style.webkitTransform
  6147. = "scaleX(-1)";
  6148. }
  6149. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6150. document.getElementById('largeVideo').style.webkitTransform
  6151. = "none";
  6152. }
  6153. // Change the way we'll be measuring and positioning large video
  6154. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6155. ? getDesktopVideoSize
  6156. : getCameraVideoSize;
  6157. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6158. ? getDesktopVideoPosition
  6159. : getCameraVideoPosition;
  6160. // Only if the large video is currently visible.
  6161. // Disable previous dominant speaker video.
  6162. if (largeVideoState.oldResourceJid) {
  6163. VideoLayout.enableDominantSpeaker(
  6164. largeVideoState.oldResourceJid,
  6165. false);
  6166. }
  6167. // Enable new dominant speaker in the remote videos section.
  6168. if (largeVideoState.userResourceJid) {
  6169. VideoLayout.enableDominantSpeaker(
  6170. largeVideoState.userResourceJid,
  6171. true);
  6172. }
  6173. if (userChanged && largeVideoState.isVisible) {
  6174. // using "this" should be ok because we're called
  6175. // from within the fadeOut event.
  6176. $(this).fadeIn(300);
  6177. }
  6178. if(userChanged) {
  6179. Avatar.showUserAvatar(
  6180. APP.xmpp.findJidFromResource(
  6181. largeVideoState.oldResourceJid));
  6182. }
  6183. largeVideoState.updateInProgress = false;
  6184. };
  6185. if (userChanged) {
  6186. $('#largeVideo').fadeOut(300, doUpdate);
  6187. } else {
  6188. doUpdate();
  6189. }
  6190. }
  6191. } else {
  6192. Avatar.showUserAvatar(
  6193. APP.xmpp.findJidFromResource(
  6194. largeVideoState.userResourceJid));
  6195. }
  6196. };
  6197. my.handleVideoThumbClicked = function(videoSrc,
  6198. noPinnedEndpointChangedEvent,
  6199. resourceJid) {
  6200. // Restore style for previously focused video
  6201. var oldContainer = null;
  6202. if(focusedVideoInfo) {
  6203. var focusResourceJid = focusedVideoInfo.resourceJid;
  6204. oldContainer = getParticipantContainer(focusResourceJid);
  6205. }
  6206. if (oldContainer) {
  6207. oldContainer.removeClass("videoContainerFocused");
  6208. }
  6209. // Unlock current focused.
  6210. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6211. {
  6212. focusedVideoInfo = null;
  6213. var dominantSpeakerVideo = null;
  6214. // Enable the currently set dominant speaker.
  6215. if (currentDominantSpeaker) {
  6216. dominantSpeakerVideo
  6217. = $('#participant_' + currentDominantSpeaker + '>video')
  6218. .get(0);
  6219. if (dominantSpeakerVideo) {
  6220. VideoLayout.updateLargeVideo(
  6221. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6222. 1,
  6223. currentDominantSpeaker);
  6224. }
  6225. }
  6226. if (!noPinnedEndpointChangedEvent) {
  6227. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6228. }
  6229. return;
  6230. }
  6231. // Lock new video
  6232. focusedVideoInfo = {
  6233. src: videoSrc,
  6234. resourceJid: resourceJid
  6235. };
  6236. // Update focused/pinned interface.
  6237. if (resourceJid)
  6238. {
  6239. var container = getParticipantContainer(resourceJid);
  6240. container.addClass("videoContainerFocused");
  6241. if (!noPinnedEndpointChangedEvent) {
  6242. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6243. }
  6244. }
  6245. if ($('#largeVideo').attr('src') === videoSrc &&
  6246. VideoLayout.isLargeVideoOnTop()) {
  6247. return;
  6248. }
  6249. // Triggers a "video.selected" event. The "false" parameter indicates
  6250. // this isn't a prezi.
  6251. $(document).trigger("video.selected", [false]);
  6252. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6253. $('audio').each(function (idx, el) {
  6254. if (el.id.indexOf('mixedmslabel') !== -1) {
  6255. el.volume = 0;
  6256. el.volume = 1;
  6257. }
  6258. });
  6259. };
  6260. /**
  6261. * Positions the large video.
  6262. *
  6263. * @param videoWidth the stream video width
  6264. * @param videoHeight the stream video height
  6265. */
  6266. my.positionLarge = function (videoWidth, videoHeight) {
  6267. var videoSpaceWidth = $('#videospace').width();
  6268. var videoSpaceHeight = window.innerHeight;
  6269. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6270. videoHeight,
  6271. videoSpaceWidth,
  6272. videoSpaceHeight);
  6273. var largeVideoWidth = videoSize[0];
  6274. var largeVideoHeight = videoSize[1];
  6275. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6276. largeVideoHeight,
  6277. videoSpaceWidth,
  6278. videoSpaceHeight);
  6279. var horizontalIndent = videoPosition[0];
  6280. var verticalIndent = videoPosition[1];
  6281. positionVideo($('#largeVideo'),
  6282. largeVideoWidth,
  6283. largeVideoHeight,
  6284. horizontalIndent, verticalIndent);
  6285. };
  6286. /**
  6287. * Shows/hides the large video.
  6288. */
  6289. my.setLargeVideoVisible = function(isVisible) {
  6290. var resourceJid = largeVideoState.userResourceJid;
  6291. if (isVisible) {
  6292. $('#largeVideo').css({visibility: 'visible'});
  6293. $('.watermark').css({visibility: 'visible'});
  6294. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6295. }
  6296. else {
  6297. $('#largeVideo').css({visibility: 'hidden'});
  6298. $('#activeSpeaker').css('visibility', 'hidden');
  6299. $('.watermark').css({visibility: 'hidden'});
  6300. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6301. if(focusedVideoInfo) {
  6302. var focusResourceJid = focusedVideoInfo.resourceJid;
  6303. var oldContainer = getParticipantContainer(focusResourceJid);
  6304. if (oldContainer && oldContainer.length > 0) {
  6305. oldContainer.removeClass("videoContainerFocused");
  6306. }
  6307. focusedVideoInfo = null;
  6308. if(focusResourceJid) {
  6309. Avatar.showUserAvatar(
  6310. APP.xmpp.findJidFromResource(focusResourceJid));
  6311. }
  6312. }
  6313. }
  6314. };
  6315. /**
  6316. * Indicates if the large video is currently visible.
  6317. *
  6318. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6319. */
  6320. my.isLargeVideoVisible = function() {
  6321. return $('#largeVideo').is(':visible');
  6322. };
  6323. my.isLargeVideoOnTop = function () {
  6324. var Etherpad = require("../etherpad/Etherpad");
  6325. var Prezi = require("../prezi/Prezi");
  6326. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6327. };
  6328. /**
  6329. * Checks if container for participant identified by given peerJid exists
  6330. * in the document and creates it eventually.
  6331. *
  6332. * @param peerJid peer Jid to check.
  6333. * @param userId user email or id for setting the avatar
  6334. *
  6335. * @return Returns <tt>true</tt> if the peer container exists,
  6336. * <tt>false</tt> - otherwise
  6337. */
  6338. my.ensurePeerContainerExists = function(peerJid, userId) {
  6339. ContactList.ensureAddContact(peerJid, userId);
  6340. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6341. var videoSpanId = 'participant_' + resourceJid;
  6342. if (!$('#' + videoSpanId).length) {
  6343. var container =
  6344. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6345. Avatar.setUserAvatar(peerJid, userId);
  6346. // Set default display name.
  6347. setDisplayName(videoSpanId);
  6348. VideoLayout.connectionIndicators[videoSpanId] =
  6349. new ConnectionIndicator(container, peerJid, VideoLayout);
  6350. var nickfield = document.createElement('span');
  6351. nickfield.className = "nick";
  6352. nickfield.appendChild(document.createTextNode(resourceJid));
  6353. container.appendChild(nickfield);
  6354. // In case this is not currently in the last n we don't show it.
  6355. if (localLastNCount
  6356. && localLastNCount > 0
  6357. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  6358. showPeerContainer(resourceJid, 'hide');
  6359. }
  6360. else
  6361. VideoLayout.resizeThumbnails();
  6362. }
  6363. };
  6364. my.addRemoteVideoContainer = function(peerJid, spanId) {
  6365. var container = document.createElement('span');
  6366. container.id = spanId;
  6367. container.className = 'videocontainer';
  6368. var remotes = document.getElementById('remoteVideos');
  6369. remotes.appendChild(container);
  6370. // If the peerJid is null then this video span couldn't be directly
  6371. // associated with a participant (this could happen in the case of prezi).
  6372. if (APP.xmpp.isModerator() && peerJid !== null)
  6373. addRemoteVideoMenu(peerJid, container);
  6374. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  6375. return container;
  6376. };
  6377. /**
  6378. * Creates an audio or video stream element.
  6379. */
  6380. my.createStreamElement = function (sid, stream) {
  6381. var isVideo = stream.getVideoTracks().length > 0;
  6382. var element = isVideo
  6383. ? document.createElement('video')
  6384. : document.createElement('audio');
  6385. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  6386. + sid + '_' + APP.RTC.getStreamID(stream);
  6387. element.id = id;
  6388. element.autoplay = true;
  6389. element.oncontextmenu = function () { return false; };
  6390. return element;
  6391. };
  6392. my.addRemoteStreamElement
  6393. = function (container, sid, stream, peerJid, thessrc) {
  6394. var newElementId = null;
  6395. var isVideo = stream.getVideoTracks().length > 0;
  6396. if (container) {
  6397. var streamElement = VideoLayout.createStreamElement(sid, stream);
  6398. newElementId = streamElement.id;
  6399. container.appendChild(streamElement);
  6400. var sel = $('#' + newElementId);
  6401. sel.hide();
  6402. // If the container is currently visible we attach the stream.
  6403. if (!isVideo
  6404. || (container.offsetParent !== null && isVideo)) {
  6405. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6406. APP.RTC.attachMediaStream(sel, videoStream);
  6407. if (isVideo)
  6408. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  6409. }
  6410. stream.onended = function () {
  6411. console.log('stream ended', this);
  6412. VideoLayout.removeRemoteStreamElement(
  6413. stream, isVideo, container);
  6414. // NOTE(gp) it seems that under certain circumstances, the
  6415. // onended event is not fired and thus the contact list is not
  6416. // updated.
  6417. //
  6418. // The onended event of a stream should be fired when the SSRCs
  6419. // corresponding to that stream are removed from the SDP; but
  6420. // this doesn't seem to always be the case, resulting in ghost
  6421. // contacts.
  6422. //
  6423. // In an attempt to fix the ghost contacts problem, I'm moving
  6424. // the removeContact() method call in app.js, inside the
  6425. // 'muc.left' event handler.
  6426. //if (peerJid)
  6427. // ContactList.removeContact(peerJid);
  6428. };
  6429. // Add click handler.
  6430. container.onclick = function (event) {
  6431. /*
  6432. * FIXME It turns out that videoThumb may not exist (if there is
  6433. * no actual video).
  6434. */
  6435. var videoThumb = $('#' + container.id + '>video').get(0);
  6436. if (videoThumb) {
  6437. VideoLayout.handleVideoThumbClicked(
  6438. APP.RTC.getVideoSrc(videoThumb),
  6439. false,
  6440. Strophe.getResourceFromJid(peerJid));
  6441. }
  6442. event.stopPropagation();
  6443. event.preventDefault();
  6444. return false;
  6445. };
  6446. // Add hover handler
  6447. $(container).hover(
  6448. function() {
  6449. VideoLayout.showDisplayName(container.id, true);
  6450. },
  6451. function() {
  6452. var videoSrc = null;
  6453. if ($('#' + container.id + '>video')
  6454. && $('#' + container.id + '>video').length > 0) {
  6455. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  6456. }
  6457. // If the video has been "pinned" by the user we want to
  6458. // keep the display name on place.
  6459. if (!VideoLayout.isLargeVideoVisible()
  6460. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6461. VideoLayout.showDisplayName(container.id, false);
  6462. }
  6463. );
  6464. }
  6465. return newElementId;
  6466. };
  6467. /**
  6468. * Removes the remote stream element corresponding to the given stream and
  6469. * parent container.
  6470. *
  6471. * @param stream the stream
  6472. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  6473. * @param container
  6474. */
  6475. my.removeRemoteStreamElement = function (stream, isVideo, container) {
  6476. if (!container)
  6477. return;
  6478. var select = null;
  6479. var removedVideoSrc = null;
  6480. if (isVideo) {
  6481. select = $('#' + container.id + '>video');
  6482. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  6483. }
  6484. else
  6485. select = $('#' + container.id + '>audio');
  6486. // Mark video as removed to cancel waiting loop(if video is removed
  6487. // before has started)
  6488. select.removed = true;
  6489. select.remove();
  6490. var audioCount = $('#' + container.id + '>audio').length;
  6491. var videoCount = $('#' + container.id + '>video').length;
  6492. if (!audioCount && !videoCount) {
  6493. console.log("Remove whole user", container.id);
  6494. if(VideoLayout.connectionIndicators[container.id])
  6495. VideoLayout.connectionIndicators[container.id].remove();
  6496. // Remove whole container
  6497. container.remove();
  6498. UIUtil.playSoundNotification('userLeft');
  6499. VideoLayout.resizeThumbnails();
  6500. }
  6501. if (removedVideoSrc)
  6502. VideoLayout.updateRemovedVideo(removedVideoSrc);
  6503. };
  6504. /**
  6505. * Show/hide peer container for the given resourceJid.
  6506. */
  6507. function showPeerContainer(resourceJid, state) {
  6508. var peerContainer = $('#participant_' + resourceJid);
  6509. if (!peerContainer)
  6510. return;
  6511. var isHide = state === 'hide';
  6512. var resizeThumbnails = false;
  6513. if (!isHide) {
  6514. if (!peerContainer.is(':visible')) {
  6515. resizeThumbnails = true;
  6516. peerContainer.show();
  6517. }
  6518. var jid = APP.xmpp.findJidFromResource(resourceJid);
  6519. if (state == 'show')
  6520. {
  6521. // peerContainer.css('-webkit-filter', '');
  6522. Avatar.showUserAvatar(jid, false);
  6523. }
  6524. else // if (state == 'avatar')
  6525. {
  6526. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  6527. Avatar.showUserAvatar(jid, true);
  6528. }
  6529. }
  6530. else if (peerContainer.is(':visible') && isHide)
  6531. {
  6532. resizeThumbnails = true;
  6533. peerContainer.hide();
  6534. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  6535. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  6536. }
  6537. if (resizeThumbnails) {
  6538. VideoLayout.resizeThumbnails();
  6539. }
  6540. // We want to be able to pin a participant from the contact list, even
  6541. // if he's not in the lastN set!
  6542. // ContactList.setClickable(resourceJid, !isHide);
  6543. };
  6544. my.inputDisplayNameHandler = function (name) {
  6545. NicknameHandler.setNickname(name);
  6546. if (!$('#localDisplayName').is(":visible")) {
  6547. if (NicknameHandler.getNickname())
  6548. $('#localDisplayName').text(NicknameHandler.getNickname() + " (me)");
  6549. else
  6550. $('#localDisplayName')
  6551. .text(interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6552. $('#localDisplayName').show();
  6553. }
  6554. $('#editDisplayName').hide();
  6555. };
  6556. /**
  6557. * Shows/hides the display name on the remote video.
  6558. * @param videoSpanId the identifier of the video span element
  6559. * @param isShow indicates if the display name should be shown or hidden
  6560. */
  6561. my.showDisplayName = function(videoSpanId, isShow) {
  6562. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  6563. if (isShow) {
  6564. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  6565. nameSpan.setAttribute("style", "display:inline-block;");
  6566. }
  6567. else {
  6568. if (nameSpan)
  6569. nameSpan.setAttribute("style", "display:none;");
  6570. }
  6571. };
  6572. /**
  6573. * Shows the presence status message for the given video.
  6574. */
  6575. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  6576. if (!$('#' + videoSpanId).length) {
  6577. // No container
  6578. return;
  6579. }
  6580. var statusSpan = $('#' + videoSpanId + '>span.status');
  6581. if (!statusSpan.length) {
  6582. //Add status span
  6583. statusSpan = document.createElement('span');
  6584. statusSpan.className = 'status';
  6585. statusSpan.id = videoSpanId + '_status';
  6586. $('#' + videoSpanId)[0].appendChild(statusSpan);
  6587. statusSpan = $('#' + videoSpanId + '>span.status');
  6588. }
  6589. // Display status
  6590. if (statusMsg && statusMsg.length) {
  6591. $('#' + videoSpanId + '_status').text(statusMsg);
  6592. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  6593. }
  6594. else {
  6595. // Hide
  6596. statusSpan.get(0).setAttribute("style", "display:none;");
  6597. }
  6598. };
  6599. /**
  6600. * Shows a visual indicator for the moderator of the conference.
  6601. */
  6602. my.showModeratorIndicator = function () {
  6603. var isModerator = APP.xmpp.isModerator();
  6604. if (isModerator) {
  6605. var indicatorSpan = $('#localVideoContainer .focusindicator');
  6606. if (indicatorSpan.children().length === 0)
  6607. {
  6608. createModeratorIndicatorElement(indicatorSpan[0]);
  6609. //translates text in focus indicator
  6610. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  6611. }
  6612. }
  6613. var members = APP.xmpp.getMembers();
  6614. Object.keys(members).forEach(function (jid) {
  6615. if (Strophe.getResourceFromJid(jid) === 'focus') {
  6616. // Skip server side focus
  6617. return;
  6618. }
  6619. var resourceJid = Strophe.getResourceFromJid(jid);
  6620. var videoSpanId = 'participant_' + resourceJid;
  6621. var videoContainer = document.getElementById(videoSpanId);
  6622. if (!videoContainer) {
  6623. console.error("No video container for " + jid);
  6624. return;
  6625. }
  6626. var member = members[jid];
  6627. if (member.role === 'moderator') {
  6628. // Remove menu if peer is moderator
  6629. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  6630. if (menuSpan.length) {
  6631. removeRemoteVideoMenu(videoSpanId);
  6632. }
  6633. // Show moderator indicator
  6634. var indicatorSpan
  6635. = $('#' + videoSpanId + ' .focusindicator');
  6636. if (!indicatorSpan || indicatorSpan.length === 0) {
  6637. indicatorSpan = document.createElement('span');
  6638. indicatorSpan.className = 'focusindicator';
  6639. videoContainer.appendChild(indicatorSpan);
  6640. createModeratorIndicatorElement(indicatorSpan);
  6641. //translates text in focus indicators
  6642. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  6643. }
  6644. } else if (isModerator) {
  6645. // We are moderator, but user is not - add menu
  6646. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  6647. addRemoteVideoMenu(
  6648. jid,
  6649. document.getElementById('participant_' + resourceJid));
  6650. }
  6651. }
  6652. });
  6653. };
  6654. /**
  6655. * Shows video muted indicator over small videos.
  6656. */
  6657. my.showVideoIndicator = function(videoSpanId, isMuted) {
  6658. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6659. if (isMuted === 'false') {
  6660. if (videoMutedSpan.length > 0) {
  6661. videoMutedSpan.remove();
  6662. }
  6663. }
  6664. else {
  6665. if(videoMutedSpan.length == 0) {
  6666. videoMutedSpan = document.createElement('span');
  6667. videoMutedSpan.className = 'videoMuted';
  6668. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  6669. var mutedIndicator = document.createElement('i');
  6670. mutedIndicator.className = 'icon-camera-disabled';
  6671. UIUtil.setTooltip(mutedIndicator,
  6672. "videothumbnail.videomute",
  6673. "top");
  6674. videoMutedSpan.appendChild(mutedIndicator);
  6675. //translate texts for muted indicator
  6676. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  6677. }
  6678. VideoLayout.updateMutePosition(videoSpanId);
  6679. }
  6680. };
  6681. my.updateMutePosition = function (videoSpanId) {
  6682. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6683. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  6684. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6685. if(connectionIndicator.length > 0
  6686. && connectionIndicator[0].style.display != "none") {
  6687. audioMutedSpan.css({right: "23px"});
  6688. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  6689. }
  6690. else
  6691. {
  6692. audioMutedSpan.css({right: "0px"});
  6693. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  6694. }
  6695. }
  6696. /**
  6697. * Shows audio muted indicator over small videos.
  6698. * @param {string} isMuted
  6699. */
  6700. my.showAudioIndicator = function(videoSpanId, isMuted) {
  6701. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6702. if (isMuted === 'false') {
  6703. if (audioMutedSpan.length > 0) {
  6704. audioMutedSpan.popover('hide');
  6705. audioMutedSpan.remove();
  6706. }
  6707. }
  6708. else {
  6709. if(audioMutedSpan.length == 0 ) {
  6710. audioMutedSpan = document.createElement('span');
  6711. audioMutedSpan.className = 'audioMuted';
  6712. UIUtil.setTooltip(audioMutedSpan,
  6713. "videothumbnail.mute",
  6714. "top");
  6715. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  6716. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  6717. var mutedIndicator = document.createElement('i');
  6718. mutedIndicator.className = 'icon-mic-disabled';
  6719. audioMutedSpan.appendChild(mutedIndicator);
  6720. }
  6721. VideoLayout.updateMutePosition(videoSpanId);
  6722. }
  6723. };
  6724. /*
  6725. * Shows or hides the audio muted indicator over the local thumbnail video.
  6726. * @param {boolean} isMuted
  6727. */
  6728. my.showLocalAudioIndicator = function(isMuted) {
  6729. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  6730. };
  6731. /**
  6732. * Resizes the large video container.
  6733. */
  6734. my.resizeLargeVideoContainer = function () {
  6735. Chat.resizeChat();
  6736. var availableHeight = window.innerHeight;
  6737. var availableWidth = UIUtil.getAvailableVideoWidth();
  6738. if (availableWidth < 0 || availableHeight < 0) return;
  6739. $('#videospace').width(availableWidth);
  6740. $('#videospace').height(availableHeight);
  6741. $('#largeVideoContainer').width(availableWidth);
  6742. $('#largeVideoContainer').height(availableHeight);
  6743. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  6744. var top = availableHeight / 2 - avatarSize / 4 * 3;
  6745. $('#activeSpeaker').css('top', top);
  6746. VideoLayout.resizeThumbnails();
  6747. };
  6748. /**
  6749. * Resizes thumbnails.
  6750. */
  6751. my.resizeThumbnails = function() {
  6752. var videoSpaceWidth = $('#remoteVideos').width();
  6753. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  6754. var width = thumbnailSize[0];
  6755. var height = thumbnailSize[1];
  6756. // size videos so that while keeping AR and max height, we have a
  6757. // nice fit
  6758. $('#remoteVideos').height(height);
  6759. $('#remoteVideos>span').width(width);
  6760. $('#remoteVideos>span').height(height);
  6761. $('.userAvatar').css('left', (width - height) / 2);
  6762. $(document).trigger("remotevideo.resized", [width, height]);
  6763. };
  6764. /**
  6765. * Enables the dominant speaker UI.
  6766. *
  6767. * @param resourceJid the jid indicating the video element to
  6768. * activate/deactivate
  6769. * @param isEnable indicates if the dominant speaker should be enabled or
  6770. * disabled
  6771. */
  6772. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  6773. var videoSpanId = null;
  6774. var videoContainerId = null;
  6775. if (resourceJid
  6776. === APP.xmpp.myResource()) {
  6777. videoSpanId = 'localVideoWrapper';
  6778. videoContainerId = 'localVideoContainer';
  6779. }
  6780. else {
  6781. videoSpanId = 'participant_' + resourceJid;
  6782. videoContainerId = videoSpanId;
  6783. }
  6784. var displayName = resourceJid;
  6785. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  6786. if (nameSpan.length > 0)
  6787. displayName = nameSpan.html();
  6788. console.log("UI enable dominant speaker",
  6789. displayName,
  6790. resourceJid,
  6791. isEnable);
  6792. videoSpan = document.getElementById(videoContainerId);
  6793. if (!videoSpan) {
  6794. return;
  6795. }
  6796. var video = $('#' + videoSpanId + '>video');
  6797. if (video && video.length > 0) {
  6798. if (isEnable) {
  6799. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  6800. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  6801. if (!videoSpan.classList.contains("dominantspeaker"))
  6802. videoSpan.classList.add("dominantspeaker");
  6803. }
  6804. else {
  6805. VideoLayout.showDisplayName(videoContainerId, false);
  6806. if (videoSpan.classList.contains("dominantspeaker"))
  6807. videoSpan.classList.remove("dominantspeaker");
  6808. }
  6809. Avatar.showUserAvatar(
  6810. APP.xmpp.findJidFromResource(resourceJid));
  6811. }
  6812. };
  6813. /**
  6814. * Calculates the thumbnail size.
  6815. *
  6816. * @param videoSpaceWidth the width of the video space
  6817. */
  6818. my.calculateThumbnailSize = function (videoSpaceWidth) {
  6819. // Calculate the available height, which is the inner window height minus
  6820. // 39px for the header minus 2px for the delimiter lines on the top and
  6821. // bottom of the large video, minus the 36px space inside the remoteVideos
  6822. // container used for highlighting shadow.
  6823. var availableHeight = 100;
  6824. var numvids = $('#remoteVideos>span:visible').length;
  6825. if (localLastNCount && localLastNCount > 0) {
  6826. numvids = Math.min(localLastNCount + 1, numvids);
  6827. }
  6828. // Remove the 3px borders arround videos and border around the remote
  6829. // videos area and the 4 pixels between the local video and the others
  6830. //TODO: Find out where the 4 pixels come from and remove them
  6831. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  6832. var availableWidth = availableWinWidth / numvids;
  6833. var aspectRatio = 16.0 / 9.0;
  6834. var maxHeight = Math.min(160, availableHeight);
  6835. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  6836. if (availableHeight < availableWidth / aspectRatio) {
  6837. availableWidth = Math.floor(availableHeight * aspectRatio);
  6838. }
  6839. return [availableWidth, availableHeight];
  6840. };
  6841. /**
  6842. * Updates the remote video menu.
  6843. *
  6844. * @param jid the jid indicating the video for which we're adding a menu.
  6845. * @param isMuted indicates the current mute state
  6846. */
  6847. my.updateRemoteVideoMenu = function(jid, isMuted) {
  6848. var muteMenuItem
  6849. = $('#remote_popupmenu_'
  6850. + Strophe.getResourceFromJid(jid)
  6851. + '>li>a.mutelink');
  6852. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  6853. if (muteMenuItem.length) {
  6854. var muteLink = muteMenuItem.get(0);
  6855. if (isMuted === 'true') {
  6856. muteLink.innerHTML = mutedIndicator + ' Muted';
  6857. muteLink.className = 'mutelink disabled';
  6858. }
  6859. else {
  6860. muteLink.innerHTML = mutedIndicator + ' Mute';
  6861. muteLink.className = 'mutelink';
  6862. }
  6863. }
  6864. };
  6865. /**
  6866. * Returns the current dominant speaker resource jid.
  6867. */
  6868. my.getDominantSpeakerResourceJid = function () {
  6869. return currentDominantSpeaker;
  6870. };
  6871. /**
  6872. * Returns the corresponding resource jid to the given peer container
  6873. * DOM element.
  6874. *
  6875. * @return the corresponding resource jid to the given peer container
  6876. * DOM element
  6877. */
  6878. my.getPeerContainerResourceJid = function (containerElement) {
  6879. var i = containerElement.id.indexOf('participant_');
  6880. if (i >= 0)
  6881. return containerElement.id.substring(i + 12);
  6882. };
  6883. /**
  6884. * On contact list item clicked.
  6885. */
  6886. $(ContactList).bind('contactclicked', function(event, jid) {
  6887. if (!jid) {
  6888. return;
  6889. }
  6890. var resource = Strophe.getResourceFromJid(jid);
  6891. var videoContainer = $("#participant_" + resource);
  6892. if (videoContainer.length > 0) {
  6893. var videoThumb = $('video', videoContainer).get(0);
  6894. // It is not always the case that a videoThumb exists (if there is
  6895. // no actual video).
  6896. if (videoThumb) {
  6897. if (videoThumb.src && videoThumb.src != '') {
  6898. // We have a video src, great! Let's update the large video
  6899. // now.
  6900. VideoLayout.handleVideoThumbClicked(
  6901. videoThumb.src,
  6902. false,
  6903. Strophe.getResourceFromJid(jid));
  6904. } else {
  6905. // If we don't have a video src for jid, there's absolutely
  6906. // no point in calling handleVideoThumbClicked; Quite
  6907. // simply, it won't work because it needs an src to attach
  6908. // to the large video.
  6909. //
  6910. // Instead, we trigger the pinned endpoint changed event to
  6911. // let the bridge adjust its lastN set for myjid and store
  6912. // the pinned user in the lastNPickupJid variable to be
  6913. // picked up later by the lastN changed event handler.
  6914. lastNPickupJid = jid;
  6915. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  6916. Strophe.getResourceFromJid(jid));
  6917. }
  6918. } else if (jid == APP.xmpp.myJid()) {
  6919. $("#localVideoContainer").click();
  6920. }
  6921. }
  6922. });
  6923. /**
  6924. * On audio muted event.
  6925. */
  6926. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  6927. /*
  6928. // FIXME: but focus can not mute in this case ? - check
  6929. if (jid === xmpp.myJid()) {
  6930. // The local mute indicator is controlled locally
  6931. return;
  6932. }*/
  6933. var videoSpanId = null;
  6934. if (jid === APP.xmpp.myJid()) {
  6935. videoSpanId = 'localVideoContainer';
  6936. } else {
  6937. VideoLayout.ensurePeerContainerExists(jid);
  6938. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  6939. }
  6940. mutedAudios[jid] = isMuted;
  6941. if (APP.xmpp.isModerator()) {
  6942. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  6943. }
  6944. if (videoSpanId)
  6945. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  6946. });
  6947. /**
  6948. * On video muted event.
  6949. */
  6950. $(document).bind('videomuted.muc', function (event, jid, value) {
  6951. var isMuted = (value === "true");
  6952. if(!APP.RTC.muteRemoteVideoStream(jid, isMuted))
  6953. return;
  6954. Avatar.showUserAvatar(jid, isMuted);
  6955. var videoSpanId = null;
  6956. if (jid === APP.xmpp.myJid()) {
  6957. videoSpanId = 'localVideoContainer';
  6958. } else {
  6959. VideoLayout.ensurePeerContainerExists(jid);
  6960. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  6961. }
  6962. if (videoSpanId)
  6963. VideoLayout.showVideoIndicator(videoSpanId, value);
  6964. });
  6965. /**
  6966. * Display name changed.
  6967. */
  6968. my.onDisplayNameChanged =
  6969. function (jid, displayName, status) {
  6970. if (jid === 'localVideoContainer'
  6971. || jid === APP.xmpp.myJid()) {
  6972. setDisplayName('localVideoContainer',
  6973. displayName);
  6974. } else {
  6975. VideoLayout.ensurePeerContainerExists(jid);
  6976. setDisplayName(
  6977. 'participant_' + Strophe.getResourceFromJid(jid),
  6978. displayName,
  6979. status);
  6980. }
  6981. };
  6982. /**
  6983. * On dominant speaker changed event.
  6984. */
  6985. my.onDominantSpeakerChanged = function (resourceJid) {
  6986. // We ignore local user events.
  6987. if (resourceJid
  6988. === APP.xmpp.myResource())
  6989. return;
  6990. // Update the current dominant speaker.
  6991. if (resourceJid !== currentDominantSpeaker) {
  6992. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  6993. newSpeakerVideoSpanId = "participant_" + resourceJid;
  6994. if($("#" + oldSpeakerVideoSpanId + ">span.displayname").text() ===
  6995. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME) {
  6996. setDisplayName(oldSpeakerVideoSpanId, null);
  6997. }
  6998. if($("#" + newSpeakerVideoSpanId + ">span.displayname").text() ===
  6999. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME) {
  7000. setDisplayName(newSpeakerVideoSpanId,
  7001. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  7002. }
  7003. currentDominantSpeaker = resourceJid;
  7004. } else {
  7005. return;
  7006. }
  7007. // Obtain container for new dominant speaker.
  7008. var container = document.getElementById(
  7009. 'participant_' + resourceJid);
  7010. // Local video will not have container found, but that's ok
  7011. // since we don't want to switch to local video.
  7012. if (container && !focusedVideoInfo)
  7013. {
  7014. var video = container.getElementsByTagName("video");
  7015. // Update the large video if the video source is already available,
  7016. // otherwise wait for the "videoactive.jingle" event.
  7017. if (video.length && video[0].currentTime > 0)
  7018. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  7019. }
  7020. };
  7021. /**
  7022. * On last N change event.
  7023. *
  7024. * @param lastNEndpoints the list of last N endpoints
  7025. * @param endpointsEnteringLastN the list currently entering last N
  7026. * endpoints
  7027. */
  7028. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7029. endpointsEnteringLastN,
  7030. stream) {
  7031. if (lastNCount !== lastNEndpoints.length)
  7032. lastNCount = lastNEndpoints.length;
  7033. lastNEndpointsCache = lastNEndpoints;
  7034. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7035. //
  7036. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7037. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7038. // so E sees them. C is only in E's local LastN set.
  7039. //
  7040. // If F starts talking and LastN = 3, then E should see thumbnails for
  7041. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7042. // enters E's local LastN ejecting C.
  7043. // Increase the local LastN set size, if necessary.
  7044. if (lastNCount > localLastNCount) {
  7045. localLastNCount = lastNCount;
  7046. }
  7047. // Update the local LastN set preserving the order in which the
  7048. // endpoints appeared in the LastN/local LastN set.
  7049. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7050. for (var i = 0; i < localLastNSet.length; i++) {
  7051. if (nextLocalLastNSet.length >= localLastNCount) {
  7052. break;
  7053. }
  7054. var resourceJid = localLastNSet[i];
  7055. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7056. nextLocalLastNSet.push(resourceJid);
  7057. }
  7058. }
  7059. localLastNSet = nextLocalLastNSet;
  7060. var updateLargeVideo = false;
  7061. // Handle LastN/local LastN changes.
  7062. $('#remoteVideos>span').each(function( index, element ) {
  7063. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7064. var isReceived = true;
  7065. if (resourceJid
  7066. && lastNEndpoints.indexOf(resourceJid) < 0
  7067. && localLastNSet.indexOf(resourceJid) < 0) {
  7068. console.log("Remove from last N", resourceJid);
  7069. showPeerContainer(resourceJid, 'hide');
  7070. isReceived = false;
  7071. } else if (resourceJid
  7072. && $('#participant_' + resourceJid).is(':visible')
  7073. && lastNEndpoints.indexOf(resourceJid) < 0
  7074. && localLastNSet.indexOf(resourceJid) >= 0) {
  7075. showPeerContainer(resourceJid, 'avatar');
  7076. isReceived = false;
  7077. }
  7078. if (!isReceived) {
  7079. // resourceJid has dropped out of the server side lastN set, so
  7080. // it is no longer being received. If resourceJid was being
  7081. // displayed in the large video we have to switch to another
  7082. // user.
  7083. var largeVideoResource = largeVideoState.userResourceJid;
  7084. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7085. updateLargeVideo = true;
  7086. }
  7087. }
  7088. });
  7089. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7090. endpointsEnteringLastN = lastNEndpoints;
  7091. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7092. endpointsEnteringLastN.forEach(function (resourceJid) {
  7093. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7094. showPeerContainer(resourceJid, 'show');
  7095. if (!isVisible) {
  7096. console.log("Add to last N", resourceJid);
  7097. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7098. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7099. var sel = $('#participant_' + resourceJid + '>video');
  7100. var videoStream = APP.simulcast.getReceivingVideoStream(
  7101. mediaStream.stream);
  7102. APP.RTC.attachMediaStream(sel, videoStream);
  7103. if (lastNPickupJid == mediaStream.peerjid) {
  7104. // Clean up the lastN pickup jid.
  7105. lastNPickupJid = null;
  7106. // Don't fire the events again, they've already
  7107. // been fired in the contact list click handler.
  7108. VideoLayout.handleVideoThumbClicked(
  7109. $(sel).attr('src'),
  7110. false,
  7111. Strophe.getResourceFromJid(mediaStream.peerjid));
  7112. updateLargeVideo = false;
  7113. }
  7114. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7115. }
  7116. })
  7117. }
  7118. // The endpoint that was being shown in the large video has dropped out
  7119. // of the lastN set and there was no lastN pickup jid. We need to update
  7120. // the large video now.
  7121. if (updateLargeVideo) {
  7122. var resource, container, src;
  7123. var myResource
  7124. = APP.xmpp.myResource();
  7125. // Find out which endpoint to show in the large video.
  7126. for (var i = 0; i < lastNEndpoints.length; i++) {
  7127. resource = lastNEndpoints[i];
  7128. if (!resource || resource === myResource)
  7129. continue;
  7130. container = $("#participant_" + resource);
  7131. if (container.length == 0)
  7132. continue;
  7133. src = $('video', container).attr('src');
  7134. if (!src)
  7135. continue;
  7136. // videoSrcToSsrc needs to be update for this call to succeed.
  7137. VideoLayout.updateLargeVideo(src);
  7138. break;
  7139. }
  7140. }
  7141. };
  7142. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  7143. endpointSimulcastLayers.forEach(function (esl) {
  7144. var resource = esl.endpoint;
  7145. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7146. // then ignore the event (= do not preload anything).
  7147. //
  7148. // The bridge could probably stop sending this message if it's for
  7149. // an endpoint that's not in lastN.
  7150. if (lastNCount != -1
  7151. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7152. return;
  7153. }
  7154. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7155. // Get session and stream from primary ssrc.
  7156. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7157. var sid = res.sid;
  7158. var electedStream = res.stream;
  7159. if (sid && electedStream) {
  7160. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7161. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7162. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  7163. if (preload) {
  7164. if (largeVideoState.preload)
  7165. {
  7166. $(largeVideoState.preload).remove();
  7167. }
  7168. console.info('Preloading remote video');
  7169. largeVideoState.preload = $('<video autoplay></video>');
  7170. // ssrcs are unique in an rtp session
  7171. largeVideoState.preload_ssrc = primarySSRC;
  7172. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  7173. }
  7174. } else {
  7175. console.error('Could not find a stream or a session.', sid, electedStream);
  7176. }
  7177. });
  7178. };
  7179. /**
  7180. * On simulcast layers changed event.
  7181. */
  7182. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  7183. endpointSimulcastLayers.forEach(function (esl) {
  7184. var resource = esl.endpoint;
  7185. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7186. // then ignore the event (= do not change large video/thumbnail
  7187. // SRCs).
  7188. //
  7189. // Note that even if we ignore the "changed" event in this event
  7190. // handler, the bridge must continue sending these events because
  7191. // the simulcast code in simulcast.js uses it to know what's going
  7192. // to be streamed by the bridge when/if the endpoint gets back into
  7193. // the lastN set.
  7194. if (lastNCount != -1
  7195. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7196. return;
  7197. }
  7198. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7199. // Get session and stream from primary ssrc.
  7200. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7201. var sid = res.sid;
  7202. var electedStream = res.stream;
  7203. if (sid && electedStream) {
  7204. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7205. console.info('Switching simulcast substream.');
  7206. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7207. var msidParts = msid.split(' ');
  7208. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  7209. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  7210. == largeVideoState.userResourceJid);
  7211. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  7212. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  7213. var electedStreamUrl;
  7214. if (largeVideoState.preload_ssrc == primarySSRC)
  7215. {
  7216. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  7217. }
  7218. else
  7219. {
  7220. if (largeVideoState.preload
  7221. && largeVideoState.preload != null) {
  7222. $(largeVideoState.preload).remove();
  7223. }
  7224. largeVideoState.preload_ssrc = 0;
  7225. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  7226. }
  7227. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  7228. if (updateLargeVideo) {
  7229. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  7230. Strophe.getResourceFromJid(jid));
  7231. }
  7232. if (updateFocusedVideoSrc) {
  7233. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  7234. }
  7235. var videoId;
  7236. if(resource == APP.xmpp.myResource())
  7237. {
  7238. videoId = "localVideoContainer";
  7239. }
  7240. else
  7241. {
  7242. videoId = "participant_" + resource;
  7243. }
  7244. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  7245. if(connectionIndicator)
  7246. connectionIndicator.updatePopoverData();
  7247. } else {
  7248. console.error('Could not find a stream or a sid.', sid, electedStream);
  7249. }
  7250. });
  7251. };
  7252. /**
  7253. * Updates local stats
  7254. * @param percent
  7255. * @param object
  7256. */
  7257. my.updateLocalConnectionStats = function (percent, object) {
  7258. var resolution = null;
  7259. if(object.resolution !== null)
  7260. {
  7261. resolution = object.resolution;
  7262. object.resolution = resolution[APP.xmpp.myJid()];
  7263. delete resolution[APP.xmpp.myJid()];
  7264. }
  7265. updateStatsIndicator("localVideoContainer", percent, object);
  7266. for(var jid in resolution)
  7267. {
  7268. if(resolution[jid] === null)
  7269. continue;
  7270. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7271. if(VideoLayout.connectionIndicators[id])
  7272. {
  7273. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7274. }
  7275. }
  7276. };
  7277. /**
  7278. * Updates remote stats.
  7279. * @param jid the jid associated with the stats
  7280. * @param percent the connection quality percent
  7281. * @param object the stats data
  7282. */
  7283. my.updateConnectionStats = function (jid, percent, object) {
  7284. var resourceJid = Strophe.getResourceFromJid(jid);
  7285. var videoSpanId = 'participant_' + resourceJid;
  7286. updateStatsIndicator(videoSpanId, percent, object);
  7287. };
  7288. /**
  7289. * Removes the connection
  7290. * @param jid
  7291. */
  7292. my.removeConnectionIndicator = function (jid) {
  7293. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7294. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7295. };
  7296. /**
  7297. * Hides the connection indicator
  7298. * @param jid
  7299. */
  7300. my.hideConnectionIndicator = function (jid) {
  7301. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7302. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7303. };
  7304. /**
  7305. * Hides all the indicators
  7306. */
  7307. my.onStatsStop = function () {
  7308. for(var indicator in VideoLayout.connectionIndicators)
  7309. {
  7310. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7311. }
  7312. };
  7313. my.participantLeft = function (jid) {
  7314. // Unlock large video
  7315. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7316. {
  7317. console.info("Focused video owner has left the conference");
  7318. focusedVideoInfo = null;
  7319. }
  7320. }
  7321. return my;
  7322. }(VideoLayout || {}));
  7323. module.exports = VideoLayout;
  7324. },{"../../../service/RTC/MediaStreamTypes":78,"../../../service/UI/UIEvents":83,"../audio_levels/AudioLevels":9,"../avatar/Avatar":12,"../etherpad/Etherpad":13,"../prezi/Prezi":14,"../side_pannels/chat/Chat":17,"../side_pannels/contactlist/ContactList":21,"../util/NicknameHandler":28,"../util/UIUtil":29,"./ConnectionIndicator":30}],32:[function(require,module,exports){
  7325. //var nouns = [
  7326. //];
  7327. var pluralNouns = [
  7328. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7329. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  7330. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  7331. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  7332. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  7333. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  7334. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  7335. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  7336. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  7337. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  7338. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  7339. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  7340. ];
  7341. //var places = [
  7342. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  7343. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  7344. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  7345. // "Bridge"
  7346. //];
  7347. var verbs = [
  7348. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  7349. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  7350. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  7351. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  7352. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  7353. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  7354. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  7355. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  7356. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  7357. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  7358. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  7359. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  7360. ];
  7361. var adverbs = [
  7362. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  7363. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  7364. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  7365. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  7366. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  7367. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  7368. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  7369. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  7370. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  7371. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  7372. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  7373. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  7374. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  7375. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  7376. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  7377. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  7378. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  7379. ];
  7380. var adjectives = [
  7381. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  7382. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  7383. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  7384. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  7385. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  7386. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  7387. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  7388. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  7389. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  7390. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  7391. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  7392. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  7393. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  7394. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  7395. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  7396. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  7397. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  7398. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  7399. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  7400. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  7401. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  7402. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  7403. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  7404. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  7405. "Zealous"
  7406. ];
  7407. //var pronouns = [
  7408. //];
  7409. //var conjunctions = [
  7410. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  7411. //];
  7412. /*
  7413. * Maps a string (category name) to the array of words from that category.
  7414. */
  7415. var CATEGORIES =
  7416. {
  7417. //"_NOUN_": nouns,
  7418. "_PLURALNOUN_": pluralNouns,
  7419. //"_PLACE_": places,
  7420. "_VERB_": verbs,
  7421. "_ADVERB_": adverbs,
  7422. "_ADJECTIVE_": adjectives
  7423. //"_PRONOUN_": pronouns,
  7424. //"_CONJUNCTION_": conjunctions,
  7425. };
  7426. var PATTERNS = [
  7427. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  7428. // BeautifulFungiOrSpaghetti
  7429. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  7430. // AmazinglyScaryToy
  7431. //"_ADVERB__ADJECTIVE__NOUN_",
  7432. // NeitherTrashNorRifle
  7433. //"Neither_NOUN_Nor_NOUN_",
  7434. //"Either_NOUN_Or_NOUN_",
  7435. // EitherCopulateOrInvestigate
  7436. //"Either_VERB_Or_VERB_",
  7437. //"Neither_VERB_Nor_VERB_",
  7438. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  7439. //"The_ADVERB__ADJECTIVE__NOUN_",
  7440. //"The_ADVERB__ADJECTIVE__NOUN_s",
  7441. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  7442. // WolvesComputeBadly
  7443. //"_PLURALNOUN__VERB__ADVERB_",
  7444. // UniteFacilitateAndMerge
  7445. //"_VERB__VERB_And_VERB_",
  7446. //NastyWitchesAtThePub
  7447. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  7448. ];
  7449. /*
  7450. * Returns a random element from the array 'arr'
  7451. */
  7452. function randomElement(arr)
  7453. {
  7454. return arr[Math.floor(Math.random() * arr.length)];
  7455. }
  7456. /*
  7457. * Returns true if the string 's' contains one of the
  7458. * template strings.
  7459. */
  7460. function hasTemplate(s)
  7461. {
  7462. for (var template in CATEGORIES){
  7463. if (s.indexOf(template) >= 0){
  7464. return true;
  7465. }
  7466. }
  7467. }
  7468. /**
  7469. * Generates new room name.
  7470. */
  7471. var RoomNameGenerator = {
  7472. generateRoomWithoutSeparator: function()
  7473. {
  7474. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  7475. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  7476. var name = randomElement(PATTERNS);
  7477. var word;
  7478. while (hasTemplate(name)){
  7479. for (var template in CATEGORIES){
  7480. word = randomElement(CATEGORIES[template]);
  7481. name = name.replace(template, word);
  7482. }
  7483. }
  7484. return name;
  7485. }
  7486. }
  7487. module.exports = RoomNameGenerator;
  7488. },{}],33:[function(require,module,exports){
  7489. var animateTimeout, updateTimeout;
  7490. var RoomNameGenerator = require("./RoomnameGenerator");
  7491. function enter_room()
  7492. {
  7493. var val = $("#enter_room_field").val();
  7494. if(!val) {
  7495. val = $("#enter_room_field").attr("room_name");
  7496. }
  7497. if (val) {
  7498. window.location.pathname = "/" + val;
  7499. }
  7500. }
  7501. function animate(word) {
  7502. var currentVal = $("#enter_room_field").attr("placeholder");
  7503. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  7504. animateTimeout = setTimeout(function() {
  7505. animate(word.substring(1, word.length))
  7506. }, 70);
  7507. }
  7508. function update_roomname()
  7509. {
  7510. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  7511. $("#enter_room_field").attr("room_name", word);
  7512. $("#enter_room_field").attr("placeholder", "");
  7513. clearTimeout(animateTimeout);
  7514. animate(word);
  7515. updateTimeout = setTimeout(update_roomname, 10000);
  7516. }
  7517. function setupWelcomePage()
  7518. {
  7519. $("#videoconference_page").hide();
  7520. $("#domain_name").text(
  7521. window.location.protocol + "//" + window.location.host + "/");
  7522. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7523. var leftWatermarkDiv
  7524. = $("#welcome_page_header div[class='watermark leftwatermark']");
  7525. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  7526. {
  7527. leftWatermarkDiv.css({display: 'block'});
  7528. leftWatermarkDiv.parent().get(0).href
  7529. = interfaceConfig.JITSI_WATERMARK_LINK;
  7530. }
  7531. }
  7532. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7533. var rightWatermarkDiv
  7534. = $("#welcome_page_header div[class='watermark rightwatermark']");
  7535. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  7536. rightWatermarkDiv.css({display: 'block'});
  7537. rightWatermarkDiv.parent().get(0).href
  7538. = interfaceConfig.BRAND_WATERMARK_LINK;
  7539. rightWatermarkDiv.get(0).style.backgroundImage
  7540. = "url(images/rightwatermark.png)";
  7541. }
  7542. }
  7543. if (interfaceConfig.SHOW_POWERED_BY) {
  7544. $("#welcome_page_header>a[class='poweredby']")
  7545. .css({display: 'block'});
  7546. }
  7547. $("#enter_room_button").click(function()
  7548. {
  7549. enter_room();
  7550. });
  7551. $("#enter_room_field").keydown(function (event) {
  7552. if (event.keyCode === 13 /* enter */) {
  7553. enter_room();
  7554. }
  7555. });
  7556. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  7557. var updateTimeout;
  7558. var animateTimeout;
  7559. $("#reload_roomname").click(function () {
  7560. clearTimeout(updateTimeout);
  7561. clearTimeout(animateTimeout);
  7562. update_roomname();
  7563. });
  7564. $("#reload_roomname").show();
  7565. update_roomname();
  7566. }
  7567. $("#disable_welcome").click(function () {
  7568. window.localStorage.welcomePageDisabled
  7569. = $("#disable_welcome").is(":checked");
  7570. });
  7571. }
  7572. module.exports = setupWelcomePage;
  7573. },{"./RoomnameGenerator":32}],34:[function(require,module,exports){
  7574. var EventEmitter = require("events");
  7575. var eventEmitter = new EventEmitter();
  7576. var CQEvents = require("../../service/connectionquality/CQEvents");
  7577. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7578. /**
  7579. * local stats
  7580. * @type {{}}
  7581. */
  7582. var stats = {};
  7583. /**
  7584. * remote stats
  7585. * @type {{}}
  7586. */
  7587. var remoteStats = {};
  7588. /**
  7589. * Interval for sending statistics to other participants
  7590. * @type {null}
  7591. */
  7592. var sendIntervalId = null;
  7593. /**
  7594. * Start statistics sending.
  7595. */
  7596. function startSendingStats() {
  7597. sendStats();
  7598. sendIntervalId = setInterval(sendStats, 10000);
  7599. }
  7600. /**
  7601. * Sends statistics to other participants
  7602. */
  7603. function sendStats() {
  7604. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  7605. }
  7606. /**
  7607. * Converts statistics to format for sending through XMPP
  7608. * @param stats the statistics
  7609. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  7610. */
  7611. function convertToMUCStats(stats) {
  7612. return {
  7613. "bitrate_download": stats.bitrate.download,
  7614. "bitrate_upload": stats.bitrate.upload,
  7615. "packetLoss_total": stats.packetLoss.total,
  7616. "packetLoss_download": stats.packetLoss.download,
  7617. "packetLoss_upload": stats.packetLoss.upload
  7618. };
  7619. }
  7620. /**
  7621. * Converts statitistics to format used by VideoLayout
  7622. * @param stats
  7623. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  7624. */
  7625. function parseMUCStats(stats) {
  7626. return {
  7627. bitrate: {
  7628. download: stats.bitrate_download,
  7629. upload: stats.bitrate_upload
  7630. },
  7631. packetLoss: {
  7632. total: stats.packetLoss_total,
  7633. download: stats.packetLoss_download,
  7634. upload: stats.packetLoss_upload
  7635. }
  7636. };
  7637. }
  7638. var ConnectionQuality = {
  7639. init: function () {
  7640. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  7641. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  7642. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  7643. },
  7644. /**
  7645. * Updates the local statistics
  7646. * @param data new statistics
  7647. */
  7648. updateLocalStats: function (data) {
  7649. stats = data;
  7650. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  7651. if (sendIntervalId == null) {
  7652. startSendingStats();
  7653. }
  7654. },
  7655. /**
  7656. * Updates remote statistics
  7657. * @param jid the jid associated with the statistics
  7658. * @param data the statistics
  7659. */
  7660. updateRemoteStats: function (jid, data) {
  7661. if (data == null || data.packetLoss_total == null) {
  7662. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  7663. return;
  7664. }
  7665. remoteStats[jid] = parseMUCStats(data);
  7666. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  7667. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  7668. },
  7669. /**
  7670. * Stops statistics sending.
  7671. */
  7672. stopSendingStats: function () {
  7673. clearInterval(sendIntervalId);
  7674. sendIntervalId = null;
  7675. //notify UI about stopping statistics gathering
  7676. eventEmitter.emit(CQEvents.STOP);
  7677. },
  7678. /**
  7679. * Returns the local statistics.
  7680. */
  7681. getStats: function () {
  7682. return stats;
  7683. },
  7684. addListener: function (type, listener) {
  7685. eventEmitter.on(type, listener);
  7686. }
  7687. };
  7688. module.exports = ConnectionQuality;
  7689. },{"../../service/connectionquality/CQEvents":85,"../../service/xmpp/XMPPEvents":88,"events":89}],35:[function(require,module,exports){
  7690. /* global $, alert, changeLocalVideo, chrome, config, getConferenceHandler, getUserMediaWithConstraints */
  7691. /**
  7692. * Indicates that desktop stream is currently in use(for toggle purpose).
  7693. * @type {boolean}
  7694. */
  7695. var isUsingScreenStream = false;
  7696. /**
  7697. * Indicates that switch stream operation is in progress and prevent from triggering new events.
  7698. * @type {boolean}
  7699. */
  7700. var switchInProgress = false;
  7701. /**
  7702. * Method used to get screen sharing stream.
  7703. *
  7704. * @type {function (stream_callback, failure_callback}
  7705. */
  7706. var obtainDesktopStream = null;
  7707. /**
  7708. * Flag used to cache desktop sharing enabled state. Do not use directly as it can be <tt>null</tt>.
  7709. * @type {null|boolean}
  7710. */
  7711. var _desktopSharingEnabled = null;
  7712. var EventEmitter = require("events");
  7713. var eventEmitter = new EventEmitter();
  7714. var DesktopSharingEventTypes = require("../../service/desktopsharing/DesktopSharingEventTypes");
  7715. /**
  7716. * Method obtains desktop stream from WebRTC 'screen' source.
  7717. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  7718. */
  7719. function obtainWebRTCScreen(streamCallback, failCallback) {
  7720. APP.RTC.getUserMediaWithConstraints(
  7721. ['screen'],
  7722. streamCallback,
  7723. failCallback
  7724. );
  7725. }
  7726. /**
  7727. * Constructs inline install URL for Chrome desktop streaming extension.
  7728. * The 'chromeExtensionId' must be defined in config.js.
  7729. * @returns {string}
  7730. */
  7731. function getWebStoreInstallUrl()
  7732. {
  7733. return "https://chrome.google.com/webstore/detail/" + config.chromeExtensionId;
  7734. }
  7735. /**
  7736. * Checks whether extension update is required.
  7737. * @param minVersion minimal required version
  7738. * @param extVersion current extension version
  7739. * @returns {boolean}
  7740. */
  7741. function isUpdateRequired(minVersion, extVersion)
  7742. {
  7743. try
  7744. {
  7745. var s1 = minVersion.split('.');
  7746. var s2 = extVersion.split('.');
  7747. var len = Math.max(s1.length, s2.length);
  7748. for (var i = 0; i < len; i++)
  7749. {
  7750. var n1 = 0,
  7751. n2 = 0;
  7752. if (i < s1.length)
  7753. n1 = parseInt(s1[i]);
  7754. if (i < s2.length)
  7755. n2 = parseInt(s2[i]);
  7756. if (isNaN(n1) || isNaN(n2))
  7757. {
  7758. return true;
  7759. }
  7760. else if (n1 !== n2)
  7761. {
  7762. return n1 > n2;
  7763. }
  7764. }
  7765. // will happen if boths version has identical numbers in
  7766. // their components (even if one of them is longer, has more components)
  7767. return false;
  7768. }
  7769. catch (e)
  7770. {
  7771. console.error("Failed to parse extension version", e);
  7772. APP.UI.messageHandler.showError("dialog.error", 'Error',
  7773. "dialod.detectext",
  7774. 'Error when trying to detect desktopsharing extension.');
  7775. return true;
  7776. }
  7777. }
  7778. function checkExtInstalled(isInstalledCallback) {
  7779. if (!chrome.runtime) {
  7780. // No API, so no extension for sure
  7781. isInstalledCallback(false);
  7782. return;
  7783. }
  7784. chrome.runtime.sendMessage(
  7785. config.chromeExtensionId,
  7786. { getVersion: true },
  7787. function (response) {
  7788. if (!response || !response.version) {
  7789. // Communication failure - assume that no endpoint exists
  7790. console.warn("Extension not installed?: " + chrome.runtime.lastError);
  7791. isInstalledCallback(false);
  7792. } else {
  7793. // Check installed extension version
  7794. var extVersion = response.version;
  7795. console.log('Extension version is: ' + extVersion);
  7796. var updateRequired = isUpdateRequired(config.minChromeExtVersion, extVersion);
  7797. if (updateRequired) {
  7798. alert(
  7799. 'Jitsi Desktop Streamer requires update. ' +
  7800. 'Changes will take effect after next Chrome restart.');
  7801. }
  7802. isInstalledCallback(!updateRequired);
  7803. }
  7804. }
  7805. );
  7806. }
  7807. function doGetStreamFromExtension(streamCallback, failCallback) {
  7808. // Sends 'getStream' msg to the extension. Extension id must be defined in the config.
  7809. chrome.runtime.sendMessage(
  7810. config.chromeExtensionId,
  7811. { getStream: true, sources: config.desktopSharingSources },
  7812. function (response) {
  7813. if (!response) {
  7814. failCallback(chrome.runtime.lastError);
  7815. return;
  7816. }
  7817. console.log("Response from extension: " + response);
  7818. if (response.streamId) {
  7819. APP.RTC.getUserMediaWithConstraints(
  7820. ['desktop'],
  7821. function (stream) {
  7822. streamCallback(stream);
  7823. },
  7824. failCallback,
  7825. null, null, null,
  7826. response.streamId);
  7827. } else {
  7828. failCallback("Extension failed to get the stream");
  7829. }
  7830. }
  7831. );
  7832. }
  7833. /**
  7834. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop' stream for returned stream token.
  7835. */
  7836. function obtainScreenFromExtension(streamCallback, failCallback) {
  7837. checkExtInstalled(
  7838. function (isInstalled) {
  7839. if (isInstalled) {
  7840. doGetStreamFromExtension(streamCallback, failCallback);
  7841. } else {
  7842. chrome.webstore.install(
  7843. getWebStoreInstallUrl(),
  7844. function (arg) {
  7845. console.log("Extension installed successfully", arg);
  7846. // We need to reload the page in order to get the access to chrome.runtime
  7847. window.location.reload(false);
  7848. },
  7849. function (arg) {
  7850. console.log("Failed to install the extension", arg);
  7851. failCallback(arg);
  7852. APP.UI.messageHandler.showError("dialog.error", 'Error',
  7853. "dialog.failtoinstall",
  7854. 'Failed to install desktop sharing extension');
  7855. }
  7856. );
  7857. }
  7858. }
  7859. );
  7860. }
  7861. /**
  7862. * Call this method to toggle desktop sharing feature.
  7863. * @param method pass "ext" to use chrome extension for desktop capture(chrome extension required),
  7864. * pass "webrtc" to use WebRTC "screen" desktop source('chrome://flags/#enable-usermedia-screen-capture'
  7865. * must be enabled), pass any other string or nothing in order to disable this feature completely.
  7866. */
  7867. function setDesktopSharing(method) {
  7868. // Check if we are running chrome
  7869. if (!navigator.webkitGetUserMedia) {
  7870. obtainDesktopStream = null;
  7871. console.info("Desktop sharing disabled");
  7872. } else if (method == "ext") {
  7873. obtainDesktopStream = obtainScreenFromExtension;
  7874. console.info("Using Chrome extension for desktop sharing");
  7875. } else if (method == "webrtc") {
  7876. obtainDesktopStream = obtainWebRTCScreen;
  7877. console.info("Using Chrome WebRTC for desktop sharing");
  7878. }
  7879. // Reset enabled cache
  7880. _desktopSharingEnabled = null;
  7881. }
  7882. /**
  7883. * Initializes <link rel=chrome-webstore-item /> with extension id set in config.js to support inline installs.
  7884. * Host site must be selected as main website of published extension.
  7885. */
  7886. function initInlineInstalls()
  7887. {
  7888. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  7889. }
  7890. function getSwitchStreamFailed(error) {
  7891. console.error("Failed to obtain the stream to switch to", error);
  7892. switchInProgress = false;
  7893. }
  7894. function streamSwitchDone() {
  7895. switchInProgress = false;
  7896. eventEmitter.emit(
  7897. DesktopSharingEventTypes.SWITCHING_DONE,
  7898. isUsingScreenStream);
  7899. }
  7900. function newStreamCreated(stream)
  7901. {
  7902. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  7903. stream, isUsingScreenStream, streamSwitchDone);
  7904. }
  7905. module.exports = {
  7906. isUsingScreenStream: function () {
  7907. return isUsingScreenStream;
  7908. },
  7909. /**
  7910. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available and enabled.
  7911. */
  7912. isDesktopSharingEnabled: function () {
  7913. if (_desktopSharingEnabled === null) {
  7914. if (obtainDesktopStream === obtainScreenFromExtension) {
  7915. // Parse chrome version
  7916. var userAgent = navigator.userAgent.toLowerCase();
  7917. // We can assume that user agent is chrome, because it's enforced when 'ext' streaming method is set
  7918. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  7919. console.log("Chrome version" + userAgent, ver);
  7920. _desktopSharingEnabled = ver >= 34;
  7921. } else {
  7922. _desktopSharingEnabled = obtainDesktopStream === obtainWebRTCScreen;
  7923. }
  7924. }
  7925. return _desktopSharingEnabled;
  7926. },
  7927. init: function () {
  7928. setDesktopSharing(config.desktopSharing);
  7929. // Initialize Chrome extension inline installs
  7930. if (config.chromeExtensionId) {
  7931. initInlineInstalls();
  7932. }
  7933. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  7934. },
  7935. addListener: function(listener, type)
  7936. {
  7937. eventEmitter.on(type, listener);
  7938. },
  7939. removeListener: function (listener,type) {
  7940. eventEmitter.removeListener(type, listener);
  7941. },
  7942. /*
  7943. * Toggles screen sharing.
  7944. */
  7945. toggleScreenSharing: function () {
  7946. if (switchInProgress || !obtainDesktopStream) {
  7947. console.warn("Switch in progress or no method defined");
  7948. return;
  7949. }
  7950. switchInProgress = true;
  7951. if (!isUsingScreenStream)
  7952. {
  7953. // Switch to desktop stream
  7954. obtainDesktopStream(
  7955. function (stream) {
  7956. // We now use screen stream
  7957. isUsingScreenStream = true;
  7958. // Hook 'ended' event to restore camera when screen stream stops
  7959. stream.addEventListener('ended',
  7960. function (e) {
  7961. if (!switchInProgress && isUsingScreenStream) {
  7962. toggleScreenSharing();
  7963. }
  7964. }
  7965. );
  7966. newStreamCreated(stream);
  7967. },
  7968. getSwitchStreamFailed);
  7969. } else {
  7970. // Disable screen stream
  7971. APP.RTC.getUserMediaWithConstraints(
  7972. ['video'],
  7973. function (stream) {
  7974. // We are now using camera stream
  7975. isUsingScreenStream = false;
  7976. newStreamCreated(stream);
  7977. },
  7978. getSwitchStreamFailed, config.resolution || '360'
  7979. );
  7980. }
  7981. }
  7982. };
  7983. },{"../../service/desktopsharing/DesktopSharingEventTypes":86,"events":89}],36:[function(require,module,exports){
  7984. //maps keycode to character, id of popover for given function and function
  7985. var shortcuts = {
  7986. 67: {
  7987. character: "C",
  7988. id: "toggleChatPopover",
  7989. function: APP.UI.toggleChat
  7990. },
  7991. 70: {
  7992. character: "F",
  7993. id: "filmstripPopover",
  7994. function: APP.UI.toggleFilmStrip
  7995. },
  7996. 77: {
  7997. character: "M",
  7998. id: "mutePopover",
  7999. function: APP.UI.toggleAudio
  8000. },
  8001. 84: {
  8002. character: "T",
  8003. function: function() {
  8004. if(!APP.RTC.localAudio.isMuted()) {
  8005. APP.UI.toggleAudio();
  8006. }
  8007. }
  8008. },
  8009. 86: {
  8010. character: "V",
  8011. id: "toggleVideoPopover",
  8012. function: APP.UI.toggleVideo
  8013. }
  8014. };
  8015. var KeyboardShortcut = {
  8016. init: function () {
  8017. window.onkeyup = function(e) {
  8018. var keycode = e.which;
  8019. if(!($(":focus").is("input[type=text]") ||
  8020. $(":focus").is("input[type=password]") ||
  8021. $(":focus").is("textarea"))) {
  8022. if (typeof shortcuts[keycode] === "object") {
  8023. shortcuts[keycode].function();
  8024. }
  8025. else if (keycode >= "0".charCodeAt(0) &&
  8026. keycode <= "9".charCodeAt(0)) {
  8027. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8028. }
  8029. //esc while the smileys are visible hides them
  8030. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8031. APP.UI.toggleSmileys();
  8032. }
  8033. };
  8034. window.onkeydown = function(e) {
  8035. if(!($(":focus").is("input[type=text]") ||
  8036. $(":focus").is("input[type=password]") ||
  8037. $(":focus").is("textarea"))) {
  8038. if(e.which === "T".charCodeAt(0)) {
  8039. if(APP.RTC.localAudio.isMuted()) {
  8040. APP.UI.toggleAudio();
  8041. }
  8042. }
  8043. }
  8044. };
  8045. var self = this;
  8046. $('body').popover({ selector: '[data-toggle=popover]',
  8047. trigger: 'click hover',
  8048. content: function() {
  8049. return this.getAttribute("content") +
  8050. self.getShortcut(this.getAttribute("shortcut"));
  8051. }
  8052. });
  8053. },
  8054. /**
  8055. *
  8056. * @param id indicates the popover associated with the shortcut
  8057. * @returns {string} the keyboard shortcut used for the id given
  8058. */
  8059. getShortcut: function (id) {
  8060. for (var keycode in shortcuts) {
  8061. if (shortcuts.hasOwnProperty(keycode)) {
  8062. if (shortcuts[keycode].id === id) {
  8063. return " (" + shortcuts[keycode].character + ")";
  8064. }
  8065. }
  8066. }
  8067. return "";
  8068. }
  8069. };
  8070. module.exports = KeyboardShortcut;
  8071. },{}],37:[function(require,module,exports){
  8072. var email = '';
  8073. var displayName = '';
  8074. var userId;
  8075. var language = null;
  8076. function supportsLocalStorage() {
  8077. try {
  8078. return 'localStorage' in window && window.localStorage !== null;
  8079. } catch (e) {
  8080. console.log("localstorage is not supported");
  8081. return false;
  8082. }
  8083. }
  8084. function generateUniqueId() {
  8085. function _p8() {
  8086. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8087. }
  8088. return _p8() + _p8() + _p8() + _p8();
  8089. }
  8090. if (supportsLocalStorage()) {
  8091. if (!window.localStorage.jitsiMeetId) {
  8092. window.localStorage.jitsiMeetId = generateUniqueId();
  8093. console.log("generated id", window.localStorage.jitsiMeetId);
  8094. }
  8095. userId = window.localStorage.jitsiMeetId || '';
  8096. email = window.localStorage.email || '';
  8097. displayName = window.localStorage.displayname || '';
  8098. language = window.localStorage.language;
  8099. } else {
  8100. console.log("local storage is not supported");
  8101. userId = generateUniqueId();
  8102. }
  8103. var Settings =
  8104. {
  8105. setDisplayName: function (newDisplayName) {
  8106. displayName = newDisplayName;
  8107. window.localStorage.displayname = displayName;
  8108. return displayName;
  8109. },
  8110. setEmail: function (newEmail)
  8111. {
  8112. email = newEmail;
  8113. window.localStorage.email = newEmail;
  8114. return email;
  8115. },
  8116. getSettings: function () {
  8117. return {
  8118. email: email,
  8119. displayName: displayName,
  8120. uid: userId,
  8121. language: language
  8122. };
  8123. },
  8124. setLanguage: function (lang) {
  8125. language = lang;
  8126. window.localStorage.language = lang;
  8127. }
  8128. };
  8129. module.exports = Settings;
  8130. },{}],38:[function(require,module,exports){
  8131. /**
  8132. *
  8133. * @constructor
  8134. */
  8135. function SimulcastLogger(name, lvl) {
  8136. this.name = name;
  8137. this.lvl = lvl;
  8138. }
  8139. SimulcastLogger.prototype.log = function (text) {
  8140. if (this.lvl) {
  8141. console.log(text);
  8142. }
  8143. };
  8144. SimulcastLogger.prototype.info = function (text) {
  8145. if (this.lvl > 1) {
  8146. console.info(text);
  8147. }
  8148. };
  8149. SimulcastLogger.prototype.fine = function (text) {
  8150. if (this.lvl > 2) {
  8151. console.log(text);
  8152. }
  8153. };
  8154. SimulcastLogger.prototype.error = function (text) {
  8155. console.error(text);
  8156. };
  8157. module.exports = SimulcastLogger;
  8158. },{}],39:[function(require,module,exports){
  8159. var SimulcastLogger = require("./SimulcastLogger");
  8160. var SimulcastUtils = require("./SimulcastUtils");
  8161. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  8162. function SimulcastReceiver() {
  8163. this.simulcastUtils = new SimulcastUtils();
  8164. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  8165. }
  8166. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  8167. SimulcastReceiver.prototype._remoteMaps = {
  8168. msid2Quality: {},
  8169. ssrc2Msid: {},
  8170. msid2ssrc: {},
  8171. receivingVideoStreams: {}
  8172. };
  8173. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  8174. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8175. };
  8176. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  8177. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  8178. };
  8179. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  8180. var sb;
  8181. this.logger.info('Ensuring x-google-conference flag...')
  8182. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8183. // TODO(gp) do that for the audio as well as suggested by fippo.
  8184. // Add the google conference flag
  8185. sb = this.simulcastUtils._getVideoSources(lines);
  8186. sb = ['a=x-google-flag:conference'].concat(sb);
  8187. this.simulcastUtils._replaceVideoSources(lines, sb);
  8188. }
  8189. };
  8190. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  8191. this._restoreRemoteVideoSources(sb);
  8192. };
  8193. /**
  8194. * Restores the simulcast groups of the remote description. In
  8195. * transformRemoteDescription we remove those in order for the set remote
  8196. * description to succeed. The focus needs the signal the groups to new
  8197. * participants.
  8198. *
  8199. * @param desc
  8200. * @returns {*}
  8201. */
  8202. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  8203. var sb;
  8204. if (!this.simulcastUtils.isValidDescription(desc)) {
  8205. return desc;
  8206. }
  8207. if (config.enableSimulcast) {
  8208. sb = desc.sdp.split('\r\n');
  8209. this._restoreSimulcastGroups(sb);
  8210. desc = new RTCSessionDescription({
  8211. type: desc.type,
  8212. sdp: sb.join('\r\n')
  8213. });
  8214. }
  8215. return desc;
  8216. };
  8217. SimulcastUtils.prototype._ensureOrder = function (lines) {
  8218. var videoSources, sb;
  8219. videoSources = this.parseMedia(lines, ['video'])[0];
  8220. sb = this._compileVideoSources(videoSources);
  8221. this._replaceVideoSources(lines, sb);
  8222. };
  8223. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  8224. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  8225. videoSource, quality;
  8226. // (re) initialize the remote maps.
  8227. this._remoteMaps.msid2Quality = {};
  8228. this._remoteMaps.ssrc2Msid = {};
  8229. this._remoteMaps.msid2ssrc = {};
  8230. var self = this;
  8231. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  8232. remoteVideoSources.groups.forEach(function (group) {
  8233. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  8234. quality = 0;
  8235. group.ssrcs.forEach(function (ssrc) {
  8236. videoSource = remoteVideoSources.sources[ssrc];
  8237. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  8238. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  8239. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  8240. });
  8241. }
  8242. });
  8243. }
  8244. };
  8245. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  8246. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  8247. };
  8248. /**
  8249. * Returns a stream with single video track, the one currently being
  8250. * received by this endpoint.
  8251. *
  8252. * @param stream the remote simulcast stream.
  8253. * @returns {webkitMediaStream}
  8254. */
  8255. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  8256. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  8257. var self = this;
  8258. if (config.enableSimulcast) {
  8259. stream.getVideoTracks().some(function (track) {
  8260. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  8261. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  8262. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  8263. if (msid == [stream.id, track.id].join(' ')) {
  8264. electedTrack = track;
  8265. return true;
  8266. }
  8267. });
  8268. });
  8269. if (!electedTrack) {
  8270. // we don't have an elected track, choose by initial quality.
  8271. tracks = stream.getVideoTracks();
  8272. for (i = 0; i < tracks.length; i++) {
  8273. msid = [stream.id, tracks[i].id].join(' ');
  8274. if (this._remoteMaps.msid2Quality[msid] === quality) {
  8275. electedTrack = tracks[i];
  8276. break;
  8277. }
  8278. }
  8279. // TODO(gp) if the initialQuality could not be satisfied, lower
  8280. // the requirement and try again.
  8281. }
  8282. }
  8283. return (electedTrack)
  8284. ? new webkitMediaStream([electedTrack])
  8285. : stream;
  8286. };
  8287. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  8288. var resource = Strophe.getResourceFromJid(jid);
  8289. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  8290. // If we haven't receiving a "changed" event yet, then we must be receiving
  8291. // low quality (that the sender always streams).
  8292. if(!ssrc)
  8293. {
  8294. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8295. var remoteStream = remoteStreamObject.getOriginalStream();
  8296. var tracks = remoteStream.getVideoTracks();
  8297. if (tracks) {
  8298. for (var k = 0; k < tracks.length; k++) {
  8299. var track = tracks[k];
  8300. var msid = [remoteStream.id, track.id].join(' ');
  8301. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  8302. var quality = this._remoteMaps.msid2Quality[msid];
  8303. if (quality == 0) {
  8304. ssrc = _ssrc;
  8305. }
  8306. }
  8307. }
  8308. }
  8309. return ssrc;
  8310. };
  8311. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  8312. {
  8313. var sid, electedStream;
  8314. var i, j, k;
  8315. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  8316. if(jid && APP.RTC.remoteStreams[jid])
  8317. {
  8318. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8319. var remoteStream = remoteStreamObject.getOriginalStream();
  8320. var tracks = remoteStream.getVideoTracks();
  8321. if (tracks) {
  8322. for (k = 0; k < tracks.length; k++) {
  8323. var track = tracks[k];
  8324. var msid = [remoteStream.id, track.id].join(' ');
  8325. var tmp = this._remoteMaps.msid2ssrc[msid];
  8326. if (tmp == ssrc) {
  8327. electedStream = new webkitMediaStream([track]);
  8328. sid = remoteStreamObject.sid;
  8329. // stream found, stop.
  8330. break;
  8331. }
  8332. }
  8333. }
  8334. }
  8335. else
  8336. {
  8337. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  8338. }
  8339. return {
  8340. sid: sid,
  8341. stream: electedStream
  8342. };
  8343. };
  8344. /**
  8345. * Gets the fully qualified msid (stream.id + track.id) associated to the
  8346. * SSRC.
  8347. *
  8348. * @param ssrc
  8349. * @returns {*}
  8350. */
  8351. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  8352. return this._remoteMaps.ssrc2Msid[ssrc];
  8353. };
  8354. /**
  8355. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  8356. * either gets confused and thinks this is an FID group or, if an FID group
  8357. * is already present, it fails to set the remote description.
  8358. *
  8359. * @param desc
  8360. * @returns {*}
  8361. */
  8362. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  8363. if (desc && desc.sdp) {
  8364. var sb = desc.sdp.split('\r\n');
  8365. this._updateRemoteMaps(sb);
  8366. this._cacheRemoteVideoSources(sb);
  8367. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  8368. // need the simulcast group in the _updateRemoteMaps() method.
  8369. this.simulcastUtils._removeSimulcastGroup(sb);
  8370. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  8371. // We don't need the goog conference flag if we're not doing
  8372. // simulcast.
  8373. this._ensureGoogConference(sb);
  8374. }
  8375. desc = new RTCSessionDescription({
  8376. type: desc.type,
  8377. sdp: sb.join('\r\n')
  8378. });
  8379. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  8380. }
  8381. return desc;
  8382. };
  8383. module.exports = SimulcastReceiver;
  8384. },{"../../service/RTC/MediaStreamTypes":78,"./SimulcastLogger":38,"./SimulcastUtils":41}],40:[function(require,module,exports){
  8385. var SimulcastLogger = require("./SimulcastLogger");
  8386. var SimulcastUtils = require("./SimulcastUtils");
  8387. function SimulcastSender() {
  8388. this.simulcastUtils = new SimulcastUtils();
  8389. this.logger = new SimulcastLogger('SimulcastSender', 1);
  8390. }
  8391. SimulcastSender.prototype.displayedLocalVideoStream = null;
  8392. SimulcastSender.prototype._generateGuid = (function () {
  8393. function s4() {
  8394. return Math.floor((1 + Math.random()) * 0x10000)
  8395. .toString(16)
  8396. .substring(1);
  8397. }
  8398. return function () {
  8399. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  8400. s4() + '-' + s4() + s4() + s4();
  8401. };
  8402. }());
  8403. // Returns a random integer between min (included) and max (excluded)
  8404. // Using Math.round() gives a non-uniform distribution!
  8405. SimulcastSender.prototype._generateRandomSSRC = function () {
  8406. var min = 0, max = 0xffffffff;
  8407. return Math.floor(Math.random() * (max - min)) + min;
  8408. };
  8409. SimulcastSender.prototype.getLocalVideoStream = function () {
  8410. return (this.displayedLocalVideoStream != null)
  8411. ? this.displayedLocalVideoStream
  8412. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  8413. : APP.RTC.localVideo.getOriginalStream();
  8414. };
  8415. function NativeSimulcastSender() {
  8416. SimulcastSender.call(this); // call the super constructor.
  8417. }
  8418. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8419. NativeSimulcastSender.prototype._localExplosionMap = {};
  8420. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  8421. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  8422. NativeSimulcastSender.prototype.reset = function () {
  8423. this._localExplosionMap = {};
  8424. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  8425. };
  8426. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  8427. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8428. };
  8429. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  8430. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  8431. };
  8432. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  8433. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  8434. this.logger.info('Appending simulcast group...');
  8435. // Get the primary SSRC information.
  8436. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8437. // Start building the SIM SSRC group.
  8438. ssrcGroup = ['a=ssrc-group:SIM'];
  8439. // The video source buffer.
  8440. sb = [];
  8441. // Create the simulcast sub-streams.
  8442. for (i = 0; i < numOfSubs; i++) {
  8443. // TODO(gp) prevent SSRC collision.
  8444. simSSRC = this._generateRandomSSRC();
  8445. ssrcGroup.push(simSSRC);
  8446. if (videoSources.base) {
  8447. sb.splice.apply(sb, [sb.length, 0].concat(
  8448. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  8449. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  8450. ));
  8451. }
  8452. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  8453. }
  8454. // Add the group sim layers.
  8455. sb.splice(0, 0, ssrcGroup.join(' '))
  8456. this.simulcastUtils._replaceVideoSources(lines, sb);
  8457. };
  8458. // Does the actual patching.
  8459. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  8460. this.logger.info('Ensuring simulcast group...');
  8461. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8462. this._appendSimulcastGroup(lines);
  8463. this._cacheLocalVideoSources(lines);
  8464. } else {
  8465. // verify that the ssrcs participating in the SIM group are present
  8466. // in the SDP (needed for presence).
  8467. this._restoreLocalVideoSources(lines);
  8468. }
  8469. };
  8470. /**
  8471. * Produces a single stream with multiple tracks for local video sources.
  8472. *
  8473. * @param lines
  8474. * @private
  8475. */
  8476. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  8477. var sb, msid, sid, tid, videoSources, self;
  8478. this.logger.info('Exploding local video sources...');
  8479. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8480. self = this;
  8481. if (videoSources.groups && videoSources.groups.length !== 0) {
  8482. videoSources.groups.forEach(function (group) {
  8483. if (group.semantics === 'SIM') {
  8484. group.ssrcs.forEach(function (ssrc) {
  8485. // Get the msid for this ssrc..
  8486. if (self._localExplosionMap[ssrc]) {
  8487. // .. either from the explosion map..
  8488. msid = self._localExplosionMap[ssrc];
  8489. } else {
  8490. // .. or generate a new one (msid).
  8491. sid = videoSources.sources[ssrc].msid
  8492. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  8493. tid = self._generateGuid();
  8494. msid = [sid, tid].join(' ');
  8495. self._localExplosionMap[ssrc] = msid;
  8496. }
  8497. // Assign it to the source object.
  8498. videoSources.sources[ssrc].msid = msid;
  8499. // TODO(gp) Change the msid of associated sources.
  8500. });
  8501. }
  8502. });
  8503. }
  8504. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8505. this.simulcastUtils._replaceVideoSources(lines, sb);
  8506. };
  8507. /**
  8508. * GUM for simulcast.
  8509. *
  8510. * @param constraints
  8511. * @param success
  8512. * @param err
  8513. */
  8514. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8515. // There's nothing special to do for native simulcast, so just do a normal GUM.
  8516. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8517. success(hqStream);
  8518. }, err);
  8519. };
  8520. /**
  8521. * Prepares the local description for public usage (i.e. to be signaled
  8522. * through Jingle to the focus).
  8523. *
  8524. * @param desc
  8525. * @returns {RTCSessionDescription}
  8526. */
  8527. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8528. var sb;
  8529. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8530. return desc;
  8531. }
  8532. sb = desc.sdp.split('\r\n');
  8533. this._explodeSimulcastSenderSources(sb);
  8534. desc = new RTCSessionDescription({
  8535. type: desc.type,
  8536. sdp: sb.join('\r\n')
  8537. });
  8538. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  8539. return desc;
  8540. };
  8541. /**
  8542. * Ensures that the simulcast group is present in the answer, _if_ native
  8543. * simulcast is enabled,
  8544. *
  8545. * @param desc
  8546. * @returns {*}
  8547. */
  8548. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  8549. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8550. return desc;
  8551. }
  8552. var sb = desc.sdp.split('\r\n');
  8553. // Even if we have enabled native simulcasting previously
  8554. // (with a call to SLD with an appropriate SDP, for example),
  8555. // createAnswer seems to consistently generate incomplete SDP
  8556. // with missing SSRCS.
  8557. //
  8558. // So, subsequent calls to SLD will have missing SSRCS and presence
  8559. // won't have the complete list of SRCs.
  8560. this._ensureSimulcastGroup(sb);
  8561. desc = new RTCSessionDescription({
  8562. type: desc.type,
  8563. sdp: sb.join('\r\n')
  8564. });
  8565. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  8566. return desc;
  8567. };
  8568. /**
  8569. *
  8570. *
  8571. * @param desc
  8572. * @returns {*}
  8573. */
  8574. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8575. return desc;
  8576. };
  8577. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8578. // Nothing to do here, native simulcast does that auto-magically.
  8579. };
  8580. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  8581. function SimpleSimulcastSender() {
  8582. SimulcastSender.call(this);
  8583. }
  8584. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8585. SimpleSimulcastSender.prototype.localStream = null;
  8586. SimpleSimulcastSender.prototype._localMaps = {
  8587. msids: [],
  8588. msid2ssrc: {}
  8589. };
  8590. /**
  8591. * Groups local video sources together in the ssrc-group:SIM group.
  8592. *
  8593. * @param lines
  8594. * @private
  8595. */
  8596. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  8597. var sb, videoSources, ssrcs = [], ssrc;
  8598. this.logger.info('Grouping local video sources...');
  8599. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8600. for (ssrc in videoSources.sources) {
  8601. // jitsi-meet destroys/creates streams at various places causing
  8602. // the original local stream ids to change. The only thing that
  8603. // remains unchanged is the trackid.
  8604. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  8605. }
  8606. var self = this;
  8607. // TODO(gp) add only "free" sources.
  8608. this._localMaps.msids.forEach(function (msid) {
  8609. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  8610. });
  8611. if (!videoSources.groups) {
  8612. videoSources.groups = [];
  8613. }
  8614. videoSources.groups.push({
  8615. 'semantics': 'SIM',
  8616. 'ssrcs': ssrcs
  8617. });
  8618. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8619. this.simulcastUtils._replaceVideoSources(lines, sb);
  8620. };
  8621. /**
  8622. * GUM for simulcast.
  8623. *
  8624. * @param constraints
  8625. * @param success
  8626. * @param err
  8627. */
  8628. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8629. // TODO(gp) what if we request a resolution not supported by the hardware?
  8630. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  8631. var lqConstraints = {
  8632. audio: false,
  8633. video: {
  8634. mandatory: {
  8635. maxWidth: 320,
  8636. maxHeight: 180,
  8637. maxFrameRate: 15
  8638. }
  8639. }
  8640. };
  8641. this.logger.info('HQ constraints: ', constraints);
  8642. this.logger.info('LQ constraints: ', lqConstraints);
  8643. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  8644. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  8645. // reason appears to be that Chrome only acquires the cam once and
  8646. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  8647. var self = this;
  8648. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8649. self.localStream = hqStream;
  8650. // reset local maps.
  8651. self._localMaps.msids = [];
  8652. self._localMaps.msid2ssrc = {};
  8653. // add hq trackid to local map
  8654. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  8655. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  8656. self.displayedLocalVideoStream = lqStream;
  8657. // NOTE(gp) The specification says Array.forEach() will visit
  8658. // the array elements in numeric order, and that it doesn't
  8659. // visit elements that don't exist.
  8660. // add lq trackid to local map
  8661. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  8662. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  8663. success(self.localStream);
  8664. }, err);
  8665. }, err);
  8666. };
  8667. /**
  8668. * Prepares the local description for public usage (i.e. to be signaled
  8669. * through Jingle to the focus).
  8670. *
  8671. * @param desc
  8672. * @returns {RTCSessionDescription}
  8673. */
  8674. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8675. var sb;
  8676. if (!this.simulcastUtils.isValidDescription(desc)) {
  8677. return desc;
  8678. }
  8679. sb = desc.sdp.split('\r\n');
  8680. this._groupLocalVideoSources(sb);
  8681. desc = new RTCSessionDescription({
  8682. type: desc.type,
  8683. sdp: sb.join('\r\n')
  8684. });
  8685. this.logger.fine('Grouped local video sources');
  8686. this.logger.fine(desc.sdp);
  8687. return desc;
  8688. };
  8689. /**
  8690. * Ensures that the simulcast group is present in the answer, _if_ native
  8691. * simulcast is enabled,
  8692. *
  8693. * @param desc
  8694. * @returns {*}
  8695. */
  8696. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  8697. return desc;
  8698. };
  8699. /**
  8700. *
  8701. *
  8702. * @param desc
  8703. * @returns {*}
  8704. */
  8705. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8706. var sb = desc.sdp.split('\r\n');
  8707. this.simulcastUtils._removeSimulcastGroup(sb);
  8708. desc = new RTCSessionDescription({
  8709. type: desc.type,
  8710. sdp: sb.join('\r\n')
  8711. });
  8712. this.logger.fine('Transformed local description');
  8713. this.logger.fine(desc.sdp);
  8714. return desc;
  8715. };
  8716. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8717. var trackid;
  8718. var self = this;
  8719. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  8720. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  8721. // Search for the track id that corresponds to the ssrc
  8722. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  8723. trackid = tid;
  8724. return true;
  8725. }
  8726. }) && self.localStream.getVideoTracks().some(function (track) {
  8727. // Start/stop the track that corresponds to the track id
  8728. if (track.id === trackid) {
  8729. track.enabled = enabled;
  8730. return true;
  8731. }
  8732. })) {
  8733. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  8734. $(document).trigger(enabled
  8735. ? 'simulcastlayerstarted'
  8736. : 'simulcastlayerstopped');
  8737. } else {
  8738. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  8739. }
  8740. };
  8741. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  8742. function NoSimulcastSender() {
  8743. SimulcastSender.call(this);
  8744. }
  8745. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8746. /**
  8747. * GUM for simulcast.
  8748. *
  8749. * @param constraints
  8750. * @param success
  8751. * @param err
  8752. */
  8753. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8754. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8755. success(hqStream);
  8756. }, err);
  8757. };
  8758. /**
  8759. * Prepares the local description for public usage (i.e. to be signaled
  8760. * through Jingle to the focus).
  8761. *
  8762. * @param desc
  8763. * @returns {RTCSessionDescription}
  8764. */
  8765. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8766. return desc;
  8767. };
  8768. /**
  8769. * Ensures that the simulcast group is present in the answer, _if_ native
  8770. * simulcast is enabled,
  8771. *
  8772. * @param desc
  8773. * @returns {*}
  8774. */
  8775. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  8776. return desc;
  8777. };
  8778. /**
  8779. *
  8780. *
  8781. * @param desc
  8782. * @returns {*}
  8783. */
  8784. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8785. return desc;
  8786. };
  8787. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8788. };
  8789. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  8790. module.exports = {
  8791. "native": NativeSimulcastSender,
  8792. "no": NoSimulcastSender
  8793. }
  8794. },{"./SimulcastLogger":38,"./SimulcastUtils":41}],41:[function(require,module,exports){
  8795. var SimulcastLogger = require("./SimulcastLogger");
  8796. /**
  8797. *
  8798. * @constructor
  8799. */
  8800. function SimulcastUtils() {
  8801. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  8802. }
  8803. /**
  8804. *
  8805. * @type {{}}
  8806. * @private
  8807. */
  8808. SimulcastUtils.prototype._emptyCompoundIndex = {};
  8809. /**
  8810. *
  8811. * @param lines
  8812. * @param videoSources
  8813. * @private
  8814. */
  8815. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  8816. var i, inVideo = false, index = -1, howMany = 0;
  8817. this.logger.info('Replacing video sources...');
  8818. for (i = 0; i < lines.length; i++) {
  8819. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  8820. // Out of video.
  8821. break;
  8822. }
  8823. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  8824. // In video.
  8825. inVideo = true;
  8826. }
  8827. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  8828. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  8829. if (index === -1) {
  8830. index = i;
  8831. }
  8832. howMany++;
  8833. }
  8834. }
  8835. // efficiency baby ;)
  8836. lines.splice.apply(lines,
  8837. [index, howMany].concat(videoSources));
  8838. };
  8839. SimulcastUtils.prototype.isValidDescription = function (desc)
  8840. {
  8841. return desc && desc != null
  8842. && desc.type && desc.type != ''
  8843. && desc.sdp && desc.sdp != '';
  8844. };
  8845. SimulcastUtils.prototype._getVideoSources = function (lines) {
  8846. var i, inVideo = false, sb = [];
  8847. this.logger.info('Getting video sources...');
  8848. for (i = 0; i < lines.length; i++) {
  8849. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  8850. // Out of video.
  8851. break;
  8852. }
  8853. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  8854. // In video.
  8855. inVideo = true;
  8856. }
  8857. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  8858. // In SSRC.
  8859. sb.push(lines[i]);
  8860. }
  8861. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  8862. sb.push(lines[i]);
  8863. }
  8864. }
  8865. return sb;
  8866. };
  8867. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  8868. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  8869. ssrc_attribute, group, semantics, skip = true;
  8870. this.logger.info('Parsing media sources...');
  8871. for (i = 0; i < lines.length; i++) {
  8872. if (lines[i].substring(0, 'm='.length) === 'm=') {
  8873. type = lines[i]
  8874. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  8875. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  8876. if (!skip) {
  8877. cur_media = {
  8878. 'type': type,
  8879. 'sources': {},
  8880. 'groups': []
  8881. };
  8882. res.push(cur_media);
  8883. }
  8884. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  8885. idx = lines[i].indexOf(' ');
  8886. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  8887. if (cur_media.sources[ssrc] === undefined) {
  8888. cur_ssrc = {'ssrc': ssrc};
  8889. cur_media.sources[ssrc] = cur_ssrc;
  8890. }
  8891. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  8892. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  8893. if (cur_media.base === undefined) {
  8894. cur_media.base = cur_ssrc;
  8895. }
  8896. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  8897. idx = lines[i].indexOf(' ');
  8898. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  8899. ssrcs = lines[i].substr(idx).trim().split(' ');
  8900. group = {
  8901. 'semantics': semantics,
  8902. 'ssrcs': ssrcs
  8903. };
  8904. cur_media.groups.push(group);
  8905. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  8906. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  8907. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  8908. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  8909. cur_media.direction = lines[i].substring('a='.length);
  8910. }
  8911. }
  8912. return res;
  8913. };
  8914. /**
  8915. * The _indexOfArray() method returns the first a CompoundIndex at which a
  8916. * given element can be found in the array, or _emptyCompoundIndex if it is
  8917. * not present.
  8918. *
  8919. * Example:
  8920. *
  8921. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  8922. *
  8923. * returns {row: 2, column: 14}
  8924. *
  8925. * @param needle
  8926. * @param haystack
  8927. * @param start
  8928. * @returns {}
  8929. * @private
  8930. */
  8931. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  8932. var length = haystack.length, idx, i;
  8933. if (!start) {
  8934. start = 0;
  8935. }
  8936. for (i = start; i < length; i++) {
  8937. idx = haystack[i].indexOf(needle);
  8938. if (idx !== -1) {
  8939. return {row: i, column: idx};
  8940. }
  8941. }
  8942. return this._emptyCompoundIndex;
  8943. };
  8944. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  8945. var i;
  8946. for (i = lines.length - 1; i >= 0; i--) {
  8947. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  8948. lines.splice(i, 1);
  8949. }
  8950. }
  8951. };
  8952. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  8953. var sb = [], ssrc, addedSSRCs = [];
  8954. this.logger.info('Compiling video sources...');
  8955. // Add the groups
  8956. if (videoSources.groups && videoSources.groups.length !== 0) {
  8957. videoSources.groups.forEach(function (group) {
  8958. if (group.ssrcs && group.ssrcs.length !== 0) {
  8959. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  8960. // if (group.semantics !== 'SIM') {
  8961. group.ssrcs.forEach(function (ssrc) {
  8962. addedSSRCs.push(ssrc);
  8963. sb.splice.apply(sb, [sb.length, 0].concat([
  8964. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  8965. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  8966. });
  8967. //}
  8968. }
  8969. });
  8970. }
  8971. // Then add any free sources.
  8972. if (videoSources.sources) {
  8973. for (ssrc in videoSources.sources) {
  8974. if (addedSSRCs.indexOf(ssrc) === -1) {
  8975. sb.splice.apply(sb, [sb.length, 0].concat([
  8976. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  8977. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  8978. }
  8979. }
  8980. }
  8981. return sb;
  8982. };
  8983. module.exports = SimulcastUtils;
  8984. },{"./SimulcastLogger":38}],42:[function(require,module,exports){
  8985. /*jslint plusplus: true */
  8986. /*jslint nomen: true*/
  8987. var SimulcastSender = require("./SimulcastSender");
  8988. var NoSimulcastSender = SimulcastSender["no"];
  8989. var NativeSimulcastSender = SimulcastSender["native"];
  8990. var SimulcastReceiver = require("./SimulcastReceiver");
  8991. var SimulcastUtils = require("./SimulcastUtils");
  8992. var RTCEvents = require("../../service/RTC/RTCEvents");
  8993. /**
  8994. *
  8995. * @constructor
  8996. */
  8997. function SimulcastManager() {
  8998. // Create the simulcast utilities.
  8999. this.simulcastUtils = new SimulcastUtils();
  9000. // Create remote simulcast.
  9001. this.simulcastReceiver = new SimulcastReceiver();
  9002. // Initialize local simulcast.
  9003. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  9004. // account constraints.
  9005. if (!config.enableSimulcast) {
  9006. this.simulcastSender = new NoSimulcastSender();
  9007. } else {
  9008. var isChromium = window.chrome,
  9009. vendorName = window.navigator.vendor;
  9010. if(isChromium !== null && isChromium !== undefined
  9011. /* skip opera */
  9012. && vendorName === "Google Inc."
  9013. /* skip Chromium as suggested by fippo */
  9014. && !window.navigator.appVersion.match(/Chromium\//) ) {
  9015. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  9016. if (ver > 37) {
  9017. this.simulcastSender = new NativeSimulcastSender();
  9018. } else {
  9019. this.simulcastSender = new NoSimulcastSender();
  9020. }
  9021. } else {
  9022. this.simulcastSender = new NoSimulcastSender();
  9023. }
  9024. }
  9025. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  9026. function (endpointSimulcastLayers) {
  9027. endpointSimulcastLayers.forEach(function (esl) {
  9028. var ssrc = esl.simulcastLayer.primarySSRC;
  9029. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  9030. });
  9031. });
  9032. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  9033. var ssrc = simulcastLayer.primarySSRC;
  9034. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  9035. });
  9036. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  9037. var ssrc = simulcastLayer.primarySSRC;
  9038. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  9039. });
  9040. }
  9041. /**
  9042. * Restores the simulcast groups of the remote description. In
  9043. * transformRemoteDescription we remove those in order for the set remote
  9044. * description to succeed. The focus needs the signal the groups to new
  9045. * participants.
  9046. *
  9047. * @param desc
  9048. * @returns {*}
  9049. */
  9050. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  9051. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  9052. };
  9053. /**
  9054. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9055. * either gets confused and thinks this is an FID group or, if an FID group
  9056. * is already present, it fails to set the remote description.
  9057. *
  9058. * @param desc
  9059. * @returns {*}
  9060. */
  9061. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  9062. return this.simulcastReceiver.transformRemoteDescription(desc);
  9063. };
  9064. /**
  9065. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9066. * SSRC.
  9067. *
  9068. * @param ssrc
  9069. * @returns {*}
  9070. */
  9071. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9072. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  9073. };
  9074. /**
  9075. * Returns a stream with single video track, the one currently being
  9076. * received by this endpoint.
  9077. *
  9078. * @param stream the remote simulcast stream.
  9079. * @returns {webkitMediaStream}
  9080. */
  9081. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  9082. return this.simulcastReceiver.getReceivingVideoStream(stream);
  9083. };
  9084. /**
  9085. *
  9086. *
  9087. * @param desc
  9088. * @returns {*}
  9089. */
  9090. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  9091. return this.simulcastSender.transformLocalDescription(desc);
  9092. };
  9093. /**
  9094. *
  9095. * @returns {*}
  9096. */
  9097. SimulcastManager.prototype.getLocalVideoStream = function() {
  9098. return this.simulcastSender.getLocalVideoStream();
  9099. };
  9100. /**
  9101. * GUM for simulcast.
  9102. *
  9103. * @param constraints
  9104. * @param success
  9105. * @param err
  9106. */
  9107. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  9108. this.simulcastSender.getUserMedia(constraints, success, err);
  9109. };
  9110. /**
  9111. * Prepares the local description for public usage (i.e. to be signaled
  9112. * through Jingle to the focus).
  9113. *
  9114. * @param desc
  9115. * @returns {RTCSessionDescription}
  9116. */
  9117. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  9118. return this.simulcastSender.reverseTransformLocalDescription(desc);
  9119. };
  9120. /**
  9121. * Ensures that the simulcast group is present in the answer, _if_ native
  9122. * simulcast is enabled,
  9123. *
  9124. * @param desc
  9125. * @returns {*}
  9126. */
  9127. SimulcastManager.prototype.transformAnswer = function (desc) {
  9128. return this.simulcastSender.transformAnswer(desc);
  9129. };
  9130. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  9131. return this.simulcastReceiver.getReceivingSSRC(jid);
  9132. };
  9133. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  9134. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  9135. };
  9136. /**
  9137. *
  9138. * @param lines
  9139. * @param mediatypes
  9140. * @returns {*}
  9141. */
  9142. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  9143. var sb = lines.sdp.split('\r\n');
  9144. return this.simulcastUtils.parseMedia(sb, mediatypes);
  9145. };
  9146. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  9147. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  9148. };
  9149. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  9150. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  9151. };
  9152. SimulcastManager.prototype.resetSender = function() {
  9153. if (typeof this.simulcastSender.reset === 'function'){
  9154. this.simulcastSender.reset();
  9155. }
  9156. };
  9157. var simulcast = new SimulcastManager();
  9158. module.exports = simulcast;
  9159. },{"../../service/RTC/RTCEvents":80,"./SimulcastReceiver":39,"./SimulcastSender":40,"./SimulcastUtils":41}],43:[function(require,module,exports){
  9160. /**
  9161. * Provides statistics for the local stream.
  9162. */
  9163. /**
  9164. * Size of the webaudio analizer buffer.
  9165. * @type {number}
  9166. */
  9167. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  9168. /**
  9169. * Value of the webaudio analizer smoothing time parameter.
  9170. * @type {number}
  9171. */
  9172. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  9173. /**
  9174. * Converts time domain data array to audio level.
  9175. * @param array the time domain data array.
  9176. * @returns {number} the audio level
  9177. */
  9178. function timeDomainDataToAudioLevel(samples) {
  9179. var maxVolume = 0;
  9180. var length = samples.length;
  9181. for (var i = 0; i < length; i++) {
  9182. if (maxVolume < samples[i])
  9183. maxVolume = samples[i];
  9184. }
  9185. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  9186. };
  9187. /**
  9188. * Animates audio level change
  9189. * @param newLevel the new audio level
  9190. * @param lastLevel the last audio level
  9191. * @returns {Number} the audio level to be set
  9192. */
  9193. function animateLevel(newLevel, lastLevel)
  9194. {
  9195. var value = 0;
  9196. var diff = lastLevel - newLevel;
  9197. if(diff > 0.2)
  9198. {
  9199. value = lastLevel - 0.2;
  9200. }
  9201. else if(diff < -0.4)
  9202. {
  9203. value = lastLevel + 0.4;
  9204. }
  9205. else
  9206. {
  9207. value = newLevel;
  9208. }
  9209. return parseFloat(value.toFixed(3));
  9210. }
  9211. /**
  9212. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  9213. *
  9214. * @param stream the local stream
  9215. * @param interval stats refresh interval given in ms.
  9216. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  9217. * update.
  9218. * @constructor
  9219. */
  9220. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  9221. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  9222. this.stream = stream;
  9223. this.intervalId = null;
  9224. this.intervalMilis = interval;
  9225. this.eventEmitter = eventEmitter;
  9226. this.audioLevel = 0;
  9227. this.statisticsService = statisticsService;
  9228. }
  9229. /**
  9230. * Starts the collecting the statistics.
  9231. */
  9232. LocalStatsCollector.prototype.start = function () {
  9233. if (config.disableAudioLevels || !window.AudioContext)
  9234. return;
  9235. var context = new AudioContext();
  9236. var analyser = context.createAnalyser();
  9237. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  9238. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  9239. var source = context.createMediaStreamSource(this.stream);
  9240. source.connect(analyser);
  9241. var self = this;
  9242. this.intervalId = setInterval(
  9243. function () {
  9244. var array = new Uint8Array(analyser.frequencyBinCount);
  9245. analyser.getByteTimeDomainData(array);
  9246. var audioLevel = timeDomainDataToAudioLevel(array);
  9247. if(audioLevel != self.audioLevel) {
  9248. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  9249. self.eventEmitter.emit(
  9250. "statistics.audioLevel",
  9251. self.statisticsService.LOCAL_JID,
  9252. self.audioLevel);
  9253. }
  9254. },
  9255. this.intervalMilis
  9256. );
  9257. };
  9258. /**
  9259. * Stops collecting the statistics.
  9260. */
  9261. LocalStatsCollector.prototype.stop = function () {
  9262. if (this.intervalId) {
  9263. clearInterval(this.intervalId);
  9264. this.intervalId = null;
  9265. }
  9266. };
  9267. module.exports = LocalStatsCollector;
  9268. },{}],44:[function(require,module,exports){
  9269. /* global ssrc2jid */
  9270. /* jshint -W117 */
  9271. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9272. /**
  9273. * Calculates packet lost percent using the number of lost packets and the
  9274. * number of all packet.
  9275. * @param lostPackets the number of lost packets
  9276. * @param totalPackets the number of all packets.
  9277. * @returns {number} packet loss percent
  9278. */
  9279. function calculatePacketLoss(lostPackets, totalPackets) {
  9280. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  9281. return 0;
  9282. return Math.round((lostPackets/totalPackets)*100);
  9283. }
  9284. function getStatValue(item, name) {
  9285. if(!keyMap[APP.RTC.getBrowserType()][name])
  9286. throw "The property isn't supported!";
  9287. var key = keyMap[APP.RTC.getBrowserType()][name];
  9288. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  9289. }
  9290. /**
  9291. * Peer statistics data holder.
  9292. * @constructor
  9293. */
  9294. function PeerStats()
  9295. {
  9296. this.ssrc2Loss = {};
  9297. this.ssrc2AudioLevel = {};
  9298. this.ssrc2bitrate = {};
  9299. this.ssrc2resolution = {};
  9300. }
  9301. /**
  9302. * The bandwidth
  9303. * @type {{}}
  9304. */
  9305. PeerStats.bandwidth = {};
  9306. /**
  9307. * The bit rate
  9308. * @type {{}}
  9309. */
  9310. PeerStats.bitrate = {};
  9311. /**
  9312. * The packet loss rate
  9313. * @type {{}}
  9314. */
  9315. PeerStats.packetLoss = null;
  9316. /**
  9317. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  9318. * represented by this instance.
  9319. * @param ssrc audio or video RTP stream SSRC.
  9320. * @param lossRate new packet loss rate value to be set.
  9321. */
  9322. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  9323. {
  9324. this.ssrc2Loss[ssrc] = lossRate;
  9325. };
  9326. /**
  9327. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  9328. * represented by this instance.
  9329. * @param ssrc audio or video RTP stream SSRC.
  9330. * @param resolution new resolution value to be set.
  9331. */
  9332. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  9333. {
  9334. if(resolution === null && this.ssrc2resolution[ssrc])
  9335. {
  9336. delete this.ssrc2resolution[ssrc];
  9337. }
  9338. else if(resolution !== null)
  9339. this.ssrc2resolution[ssrc] = resolution;
  9340. };
  9341. /**
  9342. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  9343. * represented by this instance.
  9344. * @param ssrc audio or video RTP stream SSRC.
  9345. * @param bitrate new bitrate value to be set.
  9346. */
  9347. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  9348. {
  9349. if(this.ssrc2bitrate[ssrc])
  9350. {
  9351. this.ssrc2bitrate[ssrc].download += bitrate.download;
  9352. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  9353. }
  9354. else {
  9355. this.ssrc2bitrate[ssrc] = bitrate;
  9356. }
  9357. };
  9358. /**
  9359. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  9360. * the stream which belongs to the peer represented by this instance.
  9361. * @param ssrc RTP stream SSRC for which current audio level value will be
  9362. * updated.
  9363. * @param audioLevel the new audio level value to be set. Value is truncated to
  9364. * fit the range from 0 to 1.
  9365. */
  9366. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  9367. {
  9368. // Range limit 0 - 1
  9369. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  9370. };
  9371. function formatAudioLevel(audioLevel) {
  9372. return Math.min(Math.max(audioLevel, 0), 1);
  9373. }
  9374. /**
  9375. * Array with the transport information.
  9376. * @type {Array}
  9377. */
  9378. PeerStats.transport = [];
  9379. /**
  9380. * <tt>StatsCollector</tt> registers for stats updates of given
  9381. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  9382. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  9383. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9384. * instance as an event source.
  9385. *
  9386. * @param peerconnection webRTC peer connection object.
  9387. * @param interval stats refresh interval given in ms.
  9388. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  9389. * called on stats update.
  9390. * @constructor
  9391. */
  9392. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  9393. {
  9394. this.peerconnection = peerconnection;
  9395. this.baselineAudioLevelsReport = null;
  9396. this.currentAudioLevelsReport = null;
  9397. this.currentStatsReport = null;
  9398. this.baselineStatsReport = null;
  9399. this.audioLevelsIntervalId = null;
  9400. this.eventEmitter = eventEmitter;
  9401. /**
  9402. * Gather PeerConnection stats once every this many milliseconds.
  9403. */
  9404. this.GATHER_INTERVAL = 10000;
  9405. /**
  9406. * Log stats via the focus once every this many milliseconds.
  9407. */
  9408. this.LOG_INTERVAL = 60000;
  9409. /**
  9410. * Gather stats and store them in this.statsToBeLogged.
  9411. */
  9412. this.gatherStatsIntervalId = null;
  9413. /**
  9414. * Send the stats already saved in this.statsToBeLogged to be logged via
  9415. * the focus.
  9416. */
  9417. this.logStatsIntervalId = null;
  9418. /**
  9419. * Stores the statistics which will be send to the focus to be logged.
  9420. */
  9421. this.statsToBeLogged =
  9422. {
  9423. timestamps: [],
  9424. stats: {}
  9425. };
  9426. // Updates stats interval
  9427. this.audioLevelsIntervalMilis = audioLevelsInterval;
  9428. this.statsIntervalId = null;
  9429. this.statsIntervalMilis = statsInterval;
  9430. // Map of jids to PeerStats
  9431. this.jid2stats = {};
  9432. }
  9433. module.exports = StatsCollector;
  9434. /**
  9435. * Stops stats updates.
  9436. */
  9437. StatsCollector.prototype.stop = function () {
  9438. if (this.audioLevelsIntervalId) {
  9439. clearInterval(this.audioLevelsIntervalId);
  9440. this.audioLevelsIntervalId = null;
  9441. }
  9442. if (this.statsIntervalId)
  9443. {
  9444. clearInterval(this.statsIntervalId);
  9445. this.statsIntervalId = null;
  9446. }
  9447. if(this.logStatsIntervalId)
  9448. {
  9449. clearInterval(this.logStatsIntervalId);
  9450. this.logStatsIntervalId = null;
  9451. }
  9452. if(this.gatherStatsIntervalId)
  9453. {
  9454. clearInterval(this.gatherStatsIntervalId);
  9455. this.gatherStatsIntervalId = null;
  9456. }
  9457. };
  9458. /**
  9459. * Callback passed to <tt>getStats</tt> method.
  9460. * @param error an error that occurred on <tt>getStats</tt> call.
  9461. */
  9462. StatsCollector.prototype.errorCallback = function (error)
  9463. {
  9464. console.error("Get stats error", error);
  9465. this.stop();
  9466. };
  9467. /**
  9468. * Starts stats updates.
  9469. */
  9470. StatsCollector.prototype.start = function ()
  9471. {
  9472. var self = this;
  9473. if(!config.disableAudioLevels) {
  9474. console.debug("set audio levels interval");
  9475. this.audioLevelsIntervalId = setInterval(
  9476. function () {
  9477. // Interval updates
  9478. self.peerconnection.getStats(
  9479. function (report) {
  9480. var results = null;
  9481. if (!report || !report.result ||
  9482. typeof report.result != 'function') {
  9483. results = report;
  9484. }
  9485. else {
  9486. results = report.result();
  9487. }
  9488. //console.error("Got interval report", results);
  9489. self.currentAudioLevelsReport = results;
  9490. self.processAudioLevelReport();
  9491. self.baselineAudioLevelsReport =
  9492. self.currentAudioLevelsReport;
  9493. },
  9494. self.errorCallback
  9495. );
  9496. },
  9497. self.audioLevelsIntervalMilis
  9498. );
  9499. }
  9500. if(!config.disableStats) {
  9501. console.debug("set stats interval");
  9502. this.statsIntervalId = setInterval(
  9503. function () {
  9504. // Interval updates
  9505. self.peerconnection.getStats(
  9506. function (report) {
  9507. var results = null;
  9508. if (!report || !report.result ||
  9509. typeof report.result != 'function') {
  9510. //firefox
  9511. results = report;
  9512. }
  9513. else {
  9514. //chrome
  9515. results = report.result();
  9516. }
  9517. //console.error("Got interval report", results);
  9518. self.currentStatsReport = results;
  9519. try {
  9520. self.processStatsReport();
  9521. }
  9522. catch (e) {
  9523. console.error("Unsupported key:" + e, e);
  9524. }
  9525. self.baselineStatsReport = self.currentStatsReport;
  9526. },
  9527. self.errorCallback
  9528. );
  9529. },
  9530. self.statsIntervalMilis
  9531. );
  9532. }
  9533. if (config.logStats) {
  9534. this.gatherStatsIntervalId = setInterval(
  9535. function () {
  9536. self.peerconnection.getStats(
  9537. function (report) {
  9538. self.addStatsToBeLogged(report.result());
  9539. },
  9540. function () {
  9541. }
  9542. );
  9543. },
  9544. this.GATHER_INTERVAL
  9545. );
  9546. this.logStatsIntervalId = setInterval(
  9547. function() { self.logStats(); },
  9548. this.LOG_INTERVAL);
  9549. }
  9550. };
  9551. /**
  9552. * Converts the stats to the format used for logging, and saves the data in
  9553. * this.statsToBeLogged.
  9554. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  9555. */
  9556. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  9557. var self = this;
  9558. var num_records = this.statsToBeLogged.timestamps.length;
  9559. this.statsToBeLogged.timestamps.push(new Date().getTime());
  9560. reports.map(function (report) {
  9561. var stat = self.statsToBeLogged.stats[report.id];
  9562. if (!stat) {
  9563. stat = self.statsToBeLogged.stats[report.id] = {};
  9564. }
  9565. stat.type = report.type;
  9566. report.names().map(function (name) {
  9567. var values = stat[name];
  9568. if (!values) {
  9569. values = stat[name] = [];
  9570. }
  9571. while (values.length < num_records) {
  9572. values.push(null);
  9573. }
  9574. values.push(report.stat(name));
  9575. });
  9576. });
  9577. };
  9578. StatsCollector.prototype.logStats = function () {
  9579. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  9580. return;
  9581. // Reset the stats
  9582. this.statsToBeLogged.stats = {};
  9583. this.statsToBeLogged.timestamps = [];
  9584. };
  9585. var keyMap = {};
  9586. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  9587. "ssrc": "ssrc",
  9588. "packetsReceived": "packetsReceived",
  9589. "packetsLost": "packetsLost",
  9590. "packetsSent": "packetsSent",
  9591. "bytesReceived": "bytesReceived",
  9592. "bytesSent": "bytesSent"
  9593. };
  9594. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  9595. "receiveBandwidth": "googAvailableReceiveBandwidth",
  9596. "sendBandwidth": "googAvailableSendBandwidth",
  9597. "remoteAddress": "googRemoteAddress",
  9598. "transportType": "googTransportType",
  9599. "localAddress": "googLocalAddress",
  9600. "activeConnection": "googActiveConnection",
  9601. "ssrc": "ssrc",
  9602. "packetsReceived": "packetsReceived",
  9603. "packetsSent": "packetsSent",
  9604. "packetsLost": "packetsLost",
  9605. "bytesReceived": "bytesReceived",
  9606. "bytesSent": "bytesSent",
  9607. "googFrameHeightReceived": "googFrameHeightReceived",
  9608. "googFrameWidthReceived": "googFrameWidthReceived",
  9609. "googFrameHeightSent": "googFrameHeightSent",
  9610. "googFrameWidthSent": "googFrameWidthSent",
  9611. "audioInputLevel": "audioInputLevel",
  9612. "audioOutputLevel": "audioOutputLevel"
  9613. };
  9614. /**
  9615. * Stats processing logic.
  9616. */
  9617. StatsCollector.prototype.processStatsReport = function () {
  9618. if (!this.baselineStatsReport) {
  9619. return;
  9620. }
  9621. for (var idx in this.currentStatsReport) {
  9622. var now = this.currentStatsReport[idx];
  9623. try {
  9624. if (getStatValue(now, 'receiveBandwidth') ||
  9625. getStatValue(now, 'sendBandwidth')) {
  9626. PeerStats.bandwidth = {
  9627. "download": Math.round(
  9628. (getStatValue(now, 'receiveBandwidth')) / 1000),
  9629. "upload": Math.round(
  9630. (getStatValue(now, 'sendBandwidth')) / 1000)
  9631. };
  9632. }
  9633. }
  9634. catch(e){/*not supported*/}
  9635. if(now.type == 'googCandidatePair')
  9636. {
  9637. var ip, type, localIP, active;
  9638. try {
  9639. ip = getStatValue(now, 'remoteAddress');
  9640. type = getStatValue(now, "transportType");
  9641. localIP = getStatValue(now, "localAddress");
  9642. active = getStatValue(now, "activeConnection");
  9643. }
  9644. catch(e){/*not supported*/}
  9645. if(!ip || !type || !localIP || active != "true")
  9646. continue;
  9647. var addressSaved = false;
  9648. for(var i = 0; i < PeerStats.transport.length; i++)
  9649. {
  9650. if(PeerStats.transport[i].ip == ip &&
  9651. PeerStats.transport[i].type == type &&
  9652. PeerStats.transport[i].localip == localIP)
  9653. {
  9654. addressSaved = true;
  9655. }
  9656. }
  9657. if(addressSaved)
  9658. continue;
  9659. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  9660. continue;
  9661. }
  9662. if(now.type == "candidatepair")
  9663. {
  9664. if(now.state == "succeeded")
  9665. continue;
  9666. var local = this.currentStatsReport[now.localCandidateId];
  9667. var remote = this.currentStatsReport[now.remoteCandidateId];
  9668. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  9669. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  9670. }
  9671. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  9672. now.type != "inboundrtp") {
  9673. continue;
  9674. }
  9675. var before = this.baselineStatsReport[idx];
  9676. if (!before) {
  9677. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9678. continue;
  9679. }
  9680. var ssrc = getStatValue(now, 'ssrc');
  9681. if(!ssrc)
  9682. continue;
  9683. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9684. if (!jid && (Date.now() - now.timestamp) < 3000) {
  9685. console.warn("No jid for ssrc: " + ssrc);
  9686. continue;
  9687. }
  9688. var jidStats = this.jid2stats[jid];
  9689. if (!jidStats) {
  9690. jidStats = new PeerStats();
  9691. this.jid2stats[jid] = jidStats;
  9692. }
  9693. var isDownloadStream = true;
  9694. var key = 'packetsReceived';
  9695. if (!getStatValue(now, key))
  9696. {
  9697. isDownloadStream = false;
  9698. key = 'packetsSent';
  9699. if (!getStatValue(now, key))
  9700. {
  9701. console.warn("No packetsReceived nor packetSent stat found");
  9702. continue;
  9703. }
  9704. }
  9705. var packetsNow = getStatValue(now, key);
  9706. if(!packetsNow || packetsNow < 0)
  9707. packetsNow = 0;
  9708. var packetsBefore = getStatValue(before, key);
  9709. if(!packetsBefore || packetsBefore < 0)
  9710. packetsBefore = 0;
  9711. var packetRate = packetsNow - packetsBefore;
  9712. if(!packetRate || packetRate < 0)
  9713. packetRate = 0;
  9714. var currentLoss = getStatValue(now, 'packetsLost');
  9715. if(!currentLoss || currentLoss < 0)
  9716. currentLoss = 0;
  9717. var previousLoss = getStatValue(before, 'packetsLost');
  9718. if(!previousLoss || previousLoss < 0)
  9719. previousLoss = 0;
  9720. var lossRate = currentLoss - previousLoss;
  9721. if(!lossRate || lossRate < 0)
  9722. lossRate = 0;
  9723. var packetsTotal = (packetRate + lossRate);
  9724. jidStats.setSsrcLoss(ssrc,
  9725. {"packetsTotal": packetsTotal,
  9726. "packetsLost": lossRate,
  9727. "isDownloadStream": isDownloadStream});
  9728. var bytesReceived = 0, bytesSent = 0;
  9729. if(getStatValue(now, "bytesReceived"))
  9730. {
  9731. bytesReceived = getStatValue(now, "bytesReceived") -
  9732. getStatValue(before, "bytesReceived");
  9733. }
  9734. if(getStatValue(now, "bytesSent"))
  9735. {
  9736. bytesSent = getStatValue(now, "bytesSent") -
  9737. getStatValue(before, "bytesSent");
  9738. }
  9739. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  9740. if(bytesReceived <= 0 || time <= 0)
  9741. {
  9742. bytesReceived = 0;
  9743. }
  9744. else
  9745. {
  9746. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  9747. }
  9748. if(bytesSent <= 0 || time <= 0)
  9749. {
  9750. bytesSent = 0;
  9751. }
  9752. else
  9753. {
  9754. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  9755. }
  9756. jidStats.setSsrcBitrate(ssrc, {
  9757. "download": bytesReceived,
  9758. "upload": bytesSent});
  9759. var resolution = {height: null, width: null};
  9760. try {
  9761. if (getStatValue(now, "googFrameHeightReceived") &&
  9762. getStatValue(now, "googFrameWidthReceived")) {
  9763. resolution.height = getStatValue(now, "googFrameHeightReceived");
  9764. resolution.width = getStatValue(now, "googFrameWidthReceived");
  9765. }
  9766. else if (getStatValue(now, "googFrameHeightSent") &&
  9767. getStatValue(now, "googFrameWidthSent")) {
  9768. resolution.height = getStatValue(now, "googFrameHeightSent");
  9769. resolution.width = getStatValue(now, "googFrameWidthSent");
  9770. }
  9771. }
  9772. catch(e){/*not supported*/}
  9773. if(resolution.height && resolution.width)
  9774. {
  9775. jidStats.setSsrcResolution(ssrc, resolution);
  9776. }
  9777. else
  9778. {
  9779. jidStats.setSsrcResolution(ssrc, null);
  9780. }
  9781. }
  9782. var self = this;
  9783. // Jid stats
  9784. var totalPackets = {download: 0, upload: 0};
  9785. var lostPackets = {download: 0, upload: 0};
  9786. var bitrateDownload = 0;
  9787. var bitrateUpload = 0;
  9788. var resolutions = {};
  9789. Object.keys(this.jid2stats).forEach(
  9790. function (jid)
  9791. {
  9792. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  9793. function (ssrc)
  9794. {
  9795. var type = "upload";
  9796. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  9797. type = "download";
  9798. totalPackets[type] +=
  9799. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  9800. lostPackets[type] +=
  9801. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  9802. }
  9803. );
  9804. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  9805. function (ssrc) {
  9806. bitrateDownload +=
  9807. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  9808. bitrateUpload +=
  9809. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  9810. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  9811. }
  9812. );
  9813. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  9814. }
  9815. );
  9816. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  9817. PeerStats.packetLoss = {
  9818. total:
  9819. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  9820. totalPackets.download + totalPackets.upload),
  9821. download:
  9822. calculatePacketLoss(lostPackets.download, totalPackets.download),
  9823. upload:
  9824. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  9825. };
  9826. this.eventEmitter.emit("statistics.connectionstats",
  9827. {
  9828. "bitrate": PeerStats.bitrate,
  9829. "packetLoss": PeerStats.packetLoss,
  9830. "bandwidth": PeerStats.bandwidth,
  9831. "resolution": resolutions,
  9832. "transport": PeerStats.transport
  9833. });
  9834. PeerStats.transport = [];
  9835. };
  9836. /**
  9837. * Stats processing logic.
  9838. */
  9839. StatsCollector.prototype.processAudioLevelReport = function ()
  9840. {
  9841. if (!this.baselineAudioLevelsReport)
  9842. {
  9843. return;
  9844. }
  9845. for (var idx in this.currentAudioLevelsReport)
  9846. {
  9847. var now = this.currentAudioLevelsReport[idx];
  9848. if (now.type != 'ssrc')
  9849. {
  9850. continue;
  9851. }
  9852. var before = this.baselineAudioLevelsReport[idx];
  9853. if (!before)
  9854. {
  9855. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9856. continue;
  9857. }
  9858. var ssrc = getStatValue(now, 'ssrc');
  9859. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9860. if (!jid && (Date.now() - now.timestamp) < 3000)
  9861. {
  9862. console.warn("No jid for ssrc: " + ssrc);
  9863. continue;
  9864. }
  9865. var jidStats = this.jid2stats[jid];
  9866. if (!jidStats)
  9867. {
  9868. jidStats = new PeerStats();
  9869. this.jid2stats[jid] = jidStats;
  9870. }
  9871. // Audio level
  9872. var audioLevel = null;
  9873. try {
  9874. audioLevel = getStatValue(now, 'audioInputLevel');
  9875. if (!audioLevel)
  9876. audioLevel = getStatValue(now, 'audioOutputLevel');
  9877. }
  9878. catch(e) {/*not supported*/
  9879. console.warn("Audio Levels are not available in the statistics.");
  9880. clearInterval(this.audioLevelsIntervalId);
  9881. return;
  9882. }
  9883. if (audioLevel)
  9884. {
  9885. // TODO: can't find specs about what this value really is,
  9886. // but it seems to vary between 0 and around 32k.
  9887. audioLevel = formatAudioLevel(audioLevel / 32767);
  9888. var oldLevel = jidStats.ssrc2AudioLevel[ssrc];
  9889. if(jid != APP.xmpp.myJid() && (!oldLevel || oldLevel != audioLevel))
  9890. {
  9891. jidStats.ssrc2AudioLevel[ssrc] = audioLevel;
  9892. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  9893. }
  9894. }
  9895. }
  9896. };
  9897. },{"../../service/RTC/RTCBrowserType":79}],45:[function(require,module,exports){
  9898. /**
  9899. * Created by hristo on 8/4/14.
  9900. */
  9901. var LocalStats = require("./LocalStatsCollector.js");
  9902. var RTPStats = require("./RTPStatsCollector.js");
  9903. var EventEmitter = require("events");
  9904. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  9905. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9906. var eventEmitter = new EventEmitter();
  9907. var localStats = null;
  9908. var rtpStats = null;
  9909. function stopLocal()
  9910. {
  9911. if(localStats)
  9912. {
  9913. localStats.stop();
  9914. localStats = null;
  9915. }
  9916. }
  9917. function stopRemote()
  9918. {
  9919. if(rtpStats)
  9920. {
  9921. rtpStats.stop();
  9922. eventEmitter.emit("statistics.stop");
  9923. rtpStats = null;
  9924. }
  9925. }
  9926. function startRemoteStats (peerconnection) {
  9927. if(rtpStats)
  9928. {
  9929. rtpStats.stop();
  9930. rtpStats = null;
  9931. }
  9932. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  9933. rtpStats.start();
  9934. }
  9935. function onStreamCreated(stream)
  9936. {
  9937. if(stream.getOriginalStream().getAudioTracks().length === 0)
  9938. return;
  9939. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  9940. eventEmitter);
  9941. localStats.start();
  9942. }
  9943. function onDisposeConference(onUnload) {
  9944. stopRemote();
  9945. if(onUnload) {
  9946. stopLocal();
  9947. eventEmitter.removeAllListeners();
  9948. }
  9949. }
  9950. var statistics =
  9951. {
  9952. /**
  9953. * Indicates that this audio level is for local jid.
  9954. * @type {string}
  9955. */
  9956. LOCAL_JID: 'local',
  9957. addAudioLevelListener: function(listener)
  9958. {
  9959. eventEmitter.on("statistics.audioLevel", listener);
  9960. },
  9961. removeAudioLevelListener: function(listener)
  9962. {
  9963. eventEmitter.removeListener("statistics.audioLevel", listener);
  9964. },
  9965. addConnectionStatsListener: function(listener)
  9966. {
  9967. eventEmitter.on("statistics.connectionstats", listener);
  9968. },
  9969. removeConnectionStatsListener: function(listener)
  9970. {
  9971. eventEmitter.removeListener("statistics.connectionstats", listener);
  9972. },
  9973. addRemoteStatsStopListener: function(listener)
  9974. {
  9975. eventEmitter.on("statistics.stop", listener);
  9976. },
  9977. removeRemoteStatsStopListener: function(listener)
  9978. {
  9979. eventEmitter.removeListener("statistics.stop", listener);
  9980. },
  9981. stop: function () {
  9982. stopLocal();
  9983. stopRemote();
  9984. if(eventEmitter)
  9985. {
  9986. eventEmitter.removeAllListeners();
  9987. }
  9988. },
  9989. stopRemoteStatistics: function()
  9990. {
  9991. stopRemote();
  9992. },
  9993. start: function () {
  9994. APP.RTC.addStreamListener(onStreamCreated,
  9995. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  9996. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  9997. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  9998. startRemoteStats(event.peerconnection);
  9999. });
  10000. }
  10001. };
  10002. module.exports = statistics;
  10003. },{"../../service/RTC/StreamEventTypes.js":82,"../../service/xmpp/XMPPEvents":88,"./LocalStatsCollector.js":43,"./RTPStatsCollector.js":44,"events":89}],46:[function(require,module,exports){
  10004. var i18n = require("i18next-client");
  10005. var languages = require("../../service/translation/languages");
  10006. var Settings = require("../settings/Settings");
  10007. var DEFAULT_LANG = languages.EN;
  10008. var initialized = false;
  10009. var waitingForInit = [];
  10010. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10011. return value.replace("__app__", interfaceConfig.APP_NAME);
  10012. });
  10013. var defaultOptions = {
  10014. detectLngQS: "lang",
  10015. useCookie: false,
  10016. fallbackLng: DEFAULT_LANG,
  10017. shortcutFunction: 'defaultValue',
  10018. load: "unspecific",
  10019. resGetPath: 'lang/__ns__-__lng__.json',
  10020. ns: {
  10021. namespaces: ['main', 'languages'],
  10022. defaultNs: 'main'
  10023. },
  10024. lngWhitelist : languages.getLanguages(),
  10025. fallbackOnNull: true,
  10026. fallbackOnEmpty: true,
  10027. useDataAttrOptions: true,
  10028. app: interfaceConfig.APP_NAME,
  10029. getAsync: true,
  10030. customLoad: function(lng, ns, options, done) {
  10031. var resPath = "lang/__ns__-__lng__.json";
  10032. if(lng === languages.EN)
  10033. resPath = "lang/__ns__.json";
  10034. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10035. initialized = false;
  10036. i18n.functions.ajax({
  10037. url: url,
  10038. success: function(data, status, xhr) {
  10039. i18n.functions.log('loaded: ' + url);
  10040. done(null, data);
  10041. },
  10042. error : function(xhr, status, error) {
  10043. if ((status && status == 200) ||
  10044. (xhr && xhr.status && xhr.status == 200)) {
  10045. // file loaded but invalid json, stop waste time !
  10046. i18n.functions.error('There is a typo in: ' + url);
  10047. } else if ((status && status == 404) ||
  10048. (xhr && xhr.status && xhr.status == 404)) {
  10049. i18n.functions.log('Does not exist: ' + url);
  10050. } else {
  10051. var theStatus = status ? status :
  10052. ((xhr && xhr.status) ? xhr.status : null);
  10053. i18n.functions.log(theStatus + ' when loading ' + url);
  10054. }
  10055. done(error, {});
  10056. },
  10057. dataType: "json",
  10058. async : options.getAsync
  10059. });
  10060. }
  10061. // options for caching
  10062. // useLocalStorage: true,
  10063. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10064. };
  10065. function initCompleted(t)
  10066. {
  10067. initialized = true;
  10068. $("[data-i18n]").i18n();
  10069. for(var i = 0; i < waitingForInit.length; i++)
  10070. {
  10071. var obj = waitingForInit[i];
  10072. obj.callback(i18n.t(obj.key));
  10073. }
  10074. waitingForInit = [];
  10075. }
  10076. function checkForParameter() {
  10077. var query = window.location.search.substring(1);
  10078. var vars = query.split("&");
  10079. for (var i=0;i<vars.length;i++) {
  10080. var pair = vars[i].split("=");
  10081. if(pair[0] == "lang")
  10082. {
  10083. return pair[1];
  10084. }
  10085. }
  10086. return null;
  10087. }
  10088. module.exports = {
  10089. init: function (lang) {
  10090. initialized = false;
  10091. var options = defaultOptions;
  10092. if(!lang)
  10093. {
  10094. lang = checkForParameter();
  10095. if(!lang)
  10096. {
  10097. var settings = Settings.getSettings();
  10098. if(settings)
  10099. lang = settings.language;
  10100. }
  10101. }
  10102. if(lang) {
  10103. options.lng = lang;
  10104. }
  10105. i18n.init(options, initCompleted);
  10106. },
  10107. translateString: function (key, cb, options) {
  10108. if(!cb)
  10109. return i18n.t(key, options);
  10110. if(initialized)
  10111. {
  10112. cb(i18n.t(key, options));
  10113. }
  10114. else
  10115. {
  10116. waitingForInit.push({"callback": cb, "key": key});
  10117. }
  10118. },
  10119. setLanguage: function (lang) {
  10120. initialized = false;
  10121. if(!lang)
  10122. lang = DEFAULT_LANG;
  10123. i18n.setLng(lang, defaultOptions, initCompleted);
  10124. },
  10125. getCurrentLanguage: function () {
  10126. return i18n.lng();
  10127. },
  10128. translateElement: function (selector) {
  10129. selector.i18n();
  10130. },
  10131. generateTranslatonHTML: function (key, defaultString, options) {
  10132. var str = "<span data-i18n=\"" + key + "\"";
  10133. if(options)
  10134. {
  10135. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10136. }
  10137. str += ">";
  10138. if(!options)
  10139. options = {};
  10140. if(defaultString)
  10141. {
  10142. options.defaultValue = defaultString;
  10143. }
  10144. str += this.translateString(key, null, options);
  10145. str += "</span>";
  10146. return str;
  10147. }
  10148. };
  10149. },{"../../service/translation/languages":87,"../settings/Settings":37,"i18next-client":61}],47:[function(require,module,exports){
  10150. /* jshint -W117 */
  10151. var TraceablePeerConnection = require("./TraceablePeerConnection");
  10152. var SDPDiffer = require("./SDPDiffer");
  10153. var SDPUtil = require("./SDPUtil");
  10154. var SDP = require("./SDP");
  10155. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10156. // Jingle stuff
  10157. function JingleSession(me, sid, connection, service) {
  10158. this.me = me;
  10159. this.sid = sid;
  10160. this.connection = connection;
  10161. this.initiator = null;
  10162. this.responder = null;
  10163. this.isInitiator = null;
  10164. this.peerjid = null;
  10165. this.state = null;
  10166. this.localSDP = null;
  10167. this.remoteSDP = null;
  10168. this.relayedStreams = [];
  10169. this.startTime = null;
  10170. this.stopTime = null;
  10171. this.media_constraints = null;
  10172. this.pc_constraints = null;
  10173. this.ice_config = {};
  10174. this.drip_container = [];
  10175. this.service = service;
  10176. this.usetrickle = true;
  10177. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  10178. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  10179. this.hadstuncandidate = false;
  10180. this.hadturncandidate = false;
  10181. this.lasticecandidate = false;
  10182. this.statsinterval = null;
  10183. this.reason = null;
  10184. this.addssrc = [];
  10185. this.removessrc = [];
  10186. this.pendingop = null;
  10187. this.switchstreams = false;
  10188. this.wait = true;
  10189. this.localStreamsSSRC = null;
  10190. /**
  10191. * The indicator which determines whether the (local) video has been muted
  10192. * in response to a user command in contrast to an automatic decision made
  10193. * by the application logic.
  10194. */
  10195. this.videoMuteByUser = false;
  10196. }
  10197. //TODO: this array must be removed when firefox implement multistream support
  10198. JingleSession.notReceivedSSRCs = [];
  10199. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  10200. var self = this;
  10201. if (this.state !== null) {
  10202. console.error('attempt to initiate on session ' + this.sid +
  10203. 'in state ' + this.state);
  10204. return;
  10205. }
  10206. this.isInitiator = isInitiator;
  10207. this.state = 'pending';
  10208. this.initiator = isInitiator ? this.me : peerjid;
  10209. this.responder = !isInitiator ? this.me : peerjid;
  10210. this.peerjid = peerjid;
  10211. this.hadstuncandidate = false;
  10212. this.hadturncandidate = false;
  10213. this.lasticecandidate = false;
  10214. this.peerconnection
  10215. = new TraceablePeerConnection(
  10216. this.connection.jingle.ice_config,
  10217. this.connection.jingle.pc_constraints );
  10218. this.peerconnection.onicecandidate = function (event) {
  10219. self.sendIceCandidate(event.candidate);
  10220. };
  10221. this.peerconnection.onaddstream = function (event) {
  10222. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  10223. self.remoteStreamAdded(event);
  10224. };
  10225. this.peerconnection.onremovestream = function (event) {
  10226. // Remove the stream from remoteStreams
  10227. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  10228. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  10229. };
  10230. this.peerconnection.onsignalingstatechange = function (event) {
  10231. if (!(self && self.peerconnection)) return;
  10232. };
  10233. this.peerconnection.oniceconnectionstatechange = function (event) {
  10234. if (!(self && self.peerconnection)) return;
  10235. switch (self.peerconnection.iceConnectionState) {
  10236. case 'connected':
  10237. this.startTime = new Date();
  10238. break;
  10239. case 'disconnected':
  10240. this.stopTime = new Date();
  10241. break;
  10242. }
  10243. onIceConnectionStateChange(self.sid, self);
  10244. };
  10245. // add any local and relayed stream
  10246. APP.RTC.localStreams.forEach(function(stream) {
  10247. self.peerconnection.addStream(stream.getOriginalStream());
  10248. });
  10249. this.relayedStreams.forEach(function(stream) {
  10250. self.peerconnection.addStream(stream);
  10251. });
  10252. };
  10253. function onIceConnectionStateChange(sid, session) {
  10254. switch (session.peerconnection.iceConnectionState) {
  10255. case 'checking':
  10256. session.timeChecking = (new Date()).getTime();
  10257. session.firstconnect = true;
  10258. break;
  10259. case 'completed': // on caller side
  10260. case 'connected':
  10261. if (session.firstconnect) {
  10262. session.firstconnect = false;
  10263. var metadata = {};
  10264. metadata.setupTime
  10265. = (new Date()).getTime() - session.timeChecking;
  10266. session.peerconnection.getStats(function (res) {
  10267. if(res && res.result) {
  10268. res.result().forEach(function (report) {
  10269. if (report.type == 'googCandidatePair' &&
  10270. report.stat('googActiveConnection') == 'true') {
  10271. metadata.localCandidateType
  10272. = report.stat('googLocalCandidateType');
  10273. metadata.remoteCandidateType
  10274. = report.stat('googRemoteCandidateType');
  10275. // log pair as well so we can get nice pie
  10276. // charts
  10277. metadata.candidatePair
  10278. = report.stat('googLocalCandidateType') +
  10279. ';' +
  10280. report.stat('googRemoteCandidateType');
  10281. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  10282. {
  10283. metadata.ipv6 = true;
  10284. }
  10285. }
  10286. });
  10287. }
  10288. });
  10289. }
  10290. break;
  10291. }
  10292. }
  10293. JingleSession.prototype.accept = function () {
  10294. var self = this;
  10295. this.state = 'active';
  10296. var pranswer = this.peerconnection.localDescription;
  10297. if (!pranswer || pranswer.type != 'pranswer') {
  10298. return;
  10299. }
  10300. console.log('going from pranswer to answer');
  10301. if (this.usetrickle) {
  10302. // remove candidates already sent from session-accept
  10303. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  10304. for (var i = 0; i < lines.length; i++) {
  10305. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  10306. }
  10307. }
  10308. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  10309. // FIXME: change any inactive to sendrecv or whatever they were originally
  10310. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  10311. }
  10312. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  10313. var prsdp = new SDP(pranswer.sdp);
  10314. var accept = $iq({to: this.peerjid,
  10315. type: 'set'})
  10316. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10317. action: 'session-accept',
  10318. initiator: this.initiator,
  10319. responder: this.responder,
  10320. sid: this.sid });
  10321. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10322. var sdp = this.peerconnection.localDescription.sdp;
  10323. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  10324. // FIXME: change any inactive to sendrecv or whatever they were originally
  10325. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  10326. }
  10327. var self = this;
  10328. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  10329. function () {
  10330. //console.log('setLocalDescription success');
  10331. self.setLocalDescription();
  10332. self.connection.sendIQ(accept,
  10333. function () {
  10334. var ack = {};
  10335. ack.source = 'answer';
  10336. $(document).trigger('ack.jingle', [self.sid, ack]);
  10337. },
  10338. function (stanza) {
  10339. var error = ($(stanza).find('error').length) ? {
  10340. code: $(stanza).find('error').attr('code'),
  10341. reason: $(stanza).find('error :first')[0].tagName
  10342. }:{};
  10343. error.source = 'answer';
  10344. JingleSession.onJingleError(self.sid, error);
  10345. },
  10346. 10000);
  10347. },
  10348. function (e) {
  10349. console.error('setLocalDescription failed', e);
  10350. }
  10351. );
  10352. };
  10353. JingleSession.prototype.terminate = function (reason) {
  10354. this.state = 'ended';
  10355. this.reason = reason;
  10356. this.peerconnection.close();
  10357. if (this.statsinterval !== null) {
  10358. window.clearInterval(this.statsinterval);
  10359. this.statsinterval = null;
  10360. }
  10361. };
  10362. JingleSession.prototype.active = function () {
  10363. return this.state == 'active';
  10364. };
  10365. JingleSession.prototype.sendIceCandidate = function (candidate) {
  10366. var self = this;
  10367. if (candidate && !this.lasticecandidate) {
  10368. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  10369. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  10370. if (!(ice && jcand)) {
  10371. console.error('failed to get ice && jcand');
  10372. return;
  10373. }
  10374. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10375. if (jcand.type === 'srflx') {
  10376. this.hadstuncandidate = true;
  10377. } else if (jcand.type === 'relay') {
  10378. this.hadturncandidate = true;
  10379. }
  10380. if (this.usetrickle) {
  10381. if (this.usedrip) {
  10382. if (this.drip_container.length === 0) {
  10383. // start 20ms callout
  10384. window.setTimeout(function () {
  10385. if (self.drip_container.length === 0) return;
  10386. self.sendIceCandidates(self.drip_container);
  10387. self.drip_container = [];
  10388. }, 20);
  10389. }
  10390. this.drip_container.push(candidate);
  10391. return;
  10392. } else {
  10393. self.sendIceCandidate([candidate]);
  10394. }
  10395. }
  10396. } else {
  10397. //console.log('sendIceCandidate: last candidate.');
  10398. if (!this.usetrickle) {
  10399. //console.log('should send full offer now...');
  10400. var init = $iq({to: this.peerjid,
  10401. type: 'set'})
  10402. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10403. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  10404. initiator: this.initiator,
  10405. sid: this.sid});
  10406. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  10407. var self = this;
  10408. var sendJingle = function (ssrc) {
  10409. if(!ssrc)
  10410. ssrc = {};
  10411. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  10412. self.connection.sendIQ(init,
  10413. function () {
  10414. //console.log('session initiate ack');
  10415. var ack = {};
  10416. ack.source = 'offer';
  10417. $(document).trigger('ack.jingle', [self.sid, ack]);
  10418. },
  10419. function (stanza) {
  10420. self.state = 'error';
  10421. self.peerconnection.close();
  10422. var error = ($(stanza).find('error').length) ? {
  10423. code: $(stanza).find('error').attr('code'),
  10424. reason: $(stanza).find('error :first')[0].tagName,
  10425. }:{};
  10426. error.source = 'offer';
  10427. JingleSession.onJingleError(self.sid, error);
  10428. },
  10429. 10000);
  10430. }
  10431. sendJingle();
  10432. }
  10433. this.lasticecandidate = true;
  10434. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  10435. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  10436. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  10437. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  10438. }
  10439. }
  10440. };
  10441. JingleSession.prototype.sendIceCandidates = function (candidates) {
  10442. console.log('sendIceCandidates', candidates);
  10443. var cand = $iq({to: this.peerjid, type: 'set'})
  10444. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10445. action: 'transport-info',
  10446. initiator: this.initiator,
  10447. sid: this.sid});
  10448. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  10449. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  10450. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  10451. if (cands.length > 0) {
  10452. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  10453. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10454. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  10455. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  10456. }).c('transport', ice);
  10457. for (var i = 0; i < cands.length; i++) {
  10458. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  10459. }
  10460. // add fingerprint
  10461. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  10462. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  10463. tmp.required = true;
  10464. cand.c(
  10465. 'fingerprint',
  10466. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  10467. .t(tmp.fingerprint);
  10468. delete tmp.fingerprint;
  10469. cand.attrs(tmp);
  10470. cand.up();
  10471. }
  10472. cand.up(); // transport
  10473. cand.up(); // content
  10474. }
  10475. }
  10476. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  10477. //console.log('was this the last candidate', this.lasticecandidate);
  10478. this.connection.sendIQ(cand,
  10479. function () {
  10480. var ack = {};
  10481. ack.source = 'transportinfo';
  10482. $(document).trigger('ack.jingle', [this.sid, ack]);
  10483. },
  10484. function (stanza) {
  10485. var error = ($(stanza).find('error').length) ? {
  10486. code: $(stanza).find('error').attr('code'),
  10487. reason: $(stanza).find('error :first')[0].tagName,
  10488. }:{};
  10489. error.source = 'transportinfo';
  10490. JingleSession.onJingleError(this.sid, error);
  10491. },
  10492. 10000);
  10493. };
  10494. JingleSession.prototype.sendOffer = function () {
  10495. //console.log('sendOffer...');
  10496. var self = this;
  10497. this.peerconnection.createOffer(function (sdp) {
  10498. self.createdOffer(sdp);
  10499. },
  10500. function (e) {
  10501. console.error('createOffer failed', e);
  10502. },
  10503. this.media_constraints
  10504. );
  10505. };
  10506. JingleSession.prototype.createdOffer = function (sdp) {
  10507. //console.log('createdOffer', sdp);
  10508. var self = this;
  10509. this.localSDP = new SDP(sdp.sdp);
  10510. //this.localSDP.mangle();
  10511. var sendJingle = function () {
  10512. var init = $iq({to: this.peerjid,
  10513. type: 'set'})
  10514. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10515. action: 'session-initiate',
  10516. initiator: this.initiator,
  10517. sid: this.sid});
  10518. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10519. self.connection.sendIQ(init,
  10520. function () {
  10521. var ack = {};
  10522. ack.source = 'offer';
  10523. $(document).trigger('ack.jingle', [self.sid, ack]);
  10524. },
  10525. function (stanza) {
  10526. self.state = 'error';
  10527. self.peerconnection.close();
  10528. var error = ($(stanza).find('error').length) ? {
  10529. code: $(stanza).find('error').attr('code'),
  10530. reason: $(stanza).find('error :first')[0].tagName,
  10531. }:{};
  10532. error.source = 'offer';
  10533. JingleSession.onJingleError(self.sid, error);
  10534. },
  10535. 10000);
  10536. }
  10537. sdp.sdp = this.localSDP.raw;
  10538. this.peerconnection.setLocalDescription(sdp,
  10539. function () {
  10540. if(self.usetrickle)
  10541. {
  10542. sendJingle();
  10543. }
  10544. self.setLocalDescription();
  10545. //console.log('setLocalDescription success');
  10546. },
  10547. function (e) {
  10548. console.error('setLocalDescription failed', e);
  10549. }
  10550. );
  10551. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10552. for (var i = 0; i < cands.length; i++) {
  10553. var cand = SDPUtil.parse_icecandidate(cands[i]);
  10554. if (cand.type == 'srflx') {
  10555. this.hadstuncandidate = true;
  10556. } else if (cand.type == 'relay') {
  10557. this.hadturncandidate = true;
  10558. }
  10559. }
  10560. };
  10561. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  10562. //console.log('setting remote description... ', desctype);
  10563. this.remoteSDP = new SDP('');
  10564. this.remoteSDP.fromJingle(elem);
  10565. if (this.peerconnection.remoteDescription !== null) {
  10566. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  10567. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  10568. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  10569. for (var i = 0; i < pranswer.media.length; i++) {
  10570. // make sure we have ice ufrag and pwd
  10571. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  10572. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  10573. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  10574. } else {
  10575. console.warn('no ice ufrag?');
  10576. }
  10577. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  10578. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  10579. } else {
  10580. console.warn('no ice pwd?');
  10581. }
  10582. }
  10583. // copy over candidates
  10584. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  10585. for (var j = 0; j < lines.length; j++) {
  10586. this.remoteSDP.media[i] += lines[j] + '\r\n';
  10587. }
  10588. }
  10589. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10590. }
  10591. }
  10592. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  10593. this.peerconnection.setRemoteDescription(remotedesc,
  10594. function () {
  10595. //console.log('setRemoteDescription success');
  10596. },
  10597. function (e) {
  10598. console.error('setRemoteDescription error', e);
  10599. JingleSession.onJingleFatalError(self, e);
  10600. }
  10601. );
  10602. };
  10603. JingleSession.prototype.addIceCandidate = function (elem) {
  10604. var self = this;
  10605. if (this.peerconnection.signalingState == 'closed') {
  10606. return;
  10607. }
  10608. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  10609. console.log('trickle ice candidate arriving before session accept...');
  10610. // create a PRANSWER for setRemoteDescription
  10611. if (!this.remoteSDP) {
  10612. var cobbled = 'v=0\r\n' +
  10613. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  10614. 's=-\r\n' +
  10615. 't=0 0\r\n';
  10616. // first, take some things from the local description
  10617. for (var i = 0; i < this.localSDP.media.length; i++) {
  10618. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  10619. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  10620. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  10621. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  10622. }
  10623. cobbled += 'a=inactive\r\n';
  10624. }
  10625. this.remoteSDP = new SDP(cobbled);
  10626. }
  10627. // then add things like ice and dtls from remote candidate
  10628. elem.each(function () {
  10629. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  10630. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10631. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10632. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  10633. var tmp = $(this).find('transport');
  10634. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  10635. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  10636. tmp = $(this).find('transport>fingerprint');
  10637. if (tmp.length) {
  10638. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  10639. } else {
  10640. console.log('no dtls fingerprint (webrtc issue #1718?)');
  10641. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  10642. }
  10643. break;
  10644. }
  10645. }
  10646. }
  10647. });
  10648. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10649. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  10650. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  10651. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  10652. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  10653. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  10654. }).length == this.remoteSDP.media.length;
  10655. if (iscomplete) {
  10656. console.log('setting pranswer');
  10657. try {
  10658. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  10659. function() {
  10660. },
  10661. function(e) {
  10662. console.log('setRemoteDescription pranswer failed', e.toString());
  10663. });
  10664. } catch (e) {
  10665. console.error('setting pranswer failed', e);
  10666. }
  10667. } else {
  10668. //console.log('not yet setting pranswer');
  10669. }
  10670. }
  10671. // operate on each content element
  10672. elem.each(function () {
  10673. // would love to deactivate this, but firefox still requires it
  10674. var idx = -1;
  10675. var i;
  10676. for (i = 0; i < self.remoteSDP.media.length; i++) {
  10677. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10678. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10679. idx = i;
  10680. break;
  10681. }
  10682. }
  10683. if (idx == -1) { // fall back to localdescription
  10684. for (i = 0; i < self.localSDP.media.length; i++) {
  10685. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10686. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10687. idx = i;
  10688. break;
  10689. }
  10690. }
  10691. }
  10692. var name = $(this).attr('name');
  10693. // TODO: check ice-pwd and ice-ufrag?
  10694. $(this).find('transport>candidate').each(function () {
  10695. var line, candidate;
  10696. line = SDPUtil.candidateFromJingle(this);
  10697. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  10698. sdpMid: name,
  10699. candidate: line});
  10700. try {
  10701. self.peerconnection.addIceCandidate(candidate);
  10702. } catch (e) {
  10703. console.error('addIceCandidate failed', e.toString(), line);
  10704. }
  10705. });
  10706. });
  10707. };
  10708. JingleSession.prototype.sendAnswer = function (provisional) {
  10709. //console.log('createAnswer', provisional);
  10710. var self = this;
  10711. this.peerconnection.createAnswer(
  10712. function (sdp) {
  10713. self.createdAnswer(sdp, provisional);
  10714. },
  10715. function (e) {
  10716. console.error('createAnswer failed', e);
  10717. },
  10718. this.media_constraints
  10719. );
  10720. };
  10721. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  10722. //console.log('createAnswer callback');
  10723. var self = this;
  10724. this.localSDP = new SDP(sdp.sdp);
  10725. //this.localSDP.mangle();
  10726. this.usepranswer = provisional === true;
  10727. if (this.usetrickle) {
  10728. if (this.usepranswer) {
  10729. sdp.type = 'pranswer';
  10730. for (var i = 0; i < this.localSDP.media.length; i++) {
  10731. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  10732. }
  10733. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  10734. }
  10735. }
  10736. var self = this;
  10737. var sendJingle = function (ssrcs) {
  10738. var accept = $iq({to: self.peerjid,
  10739. type: 'set'})
  10740. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10741. action: 'session-accept',
  10742. initiator: self.initiator,
  10743. responder: self.responder,
  10744. sid: self.sid });
  10745. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  10746. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  10747. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  10748. self.connection.sendIQ(accept,
  10749. function () {
  10750. var ack = {};
  10751. ack.source = 'answer';
  10752. $(document).trigger('ack.jingle', [self.sid, ack]);
  10753. },
  10754. function (stanza) {
  10755. var error = ($(stanza).find('error').length) ? {
  10756. code: $(stanza).find('error').attr('code'),
  10757. reason: $(stanza).find('error :first')[0].tagName,
  10758. }:{};
  10759. error.source = 'answer';
  10760. JingleSession.onJingleError(self.sid, error);
  10761. },
  10762. 10000);
  10763. }
  10764. sdp.sdp = this.localSDP.raw;
  10765. this.peerconnection.setLocalDescription(sdp,
  10766. function () {
  10767. //console.log('setLocalDescription success');
  10768. if (self.usetrickle && !self.usepranswer) {
  10769. sendJingle();
  10770. }
  10771. self.setLocalDescription();
  10772. },
  10773. function (e) {
  10774. console.error('setLocalDescription failed', e);
  10775. }
  10776. );
  10777. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10778. for (var j = 0; j < cands.length; j++) {
  10779. var cand = SDPUtil.parse_icecandidate(cands[j]);
  10780. if (cand.type == 'srflx') {
  10781. this.hadstuncandidate = true;
  10782. } else if (cand.type == 'relay') {
  10783. this.hadturncandidate = true;
  10784. }
  10785. }
  10786. };
  10787. JingleSession.prototype.sendTerminate = function (reason, text) {
  10788. var self = this,
  10789. term = $iq({to: this.peerjid,
  10790. type: 'set'})
  10791. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10792. action: 'session-terminate',
  10793. initiator: this.initiator,
  10794. sid: this.sid})
  10795. .c('reason')
  10796. .c(reason || 'success');
  10797. if (text) {
  10798. term.up().c('text').t(text);
  10799. }
  10800. this.connection.sendIQ(term,
  10801. function () {
  10802. self.peerconnection.close();
  10803. self.peerconnection = null;
  10804. self.terminate();
  10805. var ack = {};
  10806. ack.source = 'terminate';
  10807. $(document).trigger('ack.jingle', [self.sid, ack]);
  10808. },
  10809. function (stanza) {
  10810. var error = ($(stanza).find('error').length) ? {
  10811. code: $(stanza).find('error').attr('code'),
  10812. reason: $(stanza).find('error :first')[0].tagName,
  10813. }:{};
  10814. $(document).trigger('ack.jingle', [self.sid, error]);
  10815. },
  10816. 10000);
  10817. if (this.statsinterval !== null) {
  10818. window.clearInterval(this.statsinterval);
  10819. this.statsinterval = null;
  10820. }
  10821. };
  10822. JingleSession.prototype.addSource = function (elem, fromJid) {
  10823. var self = this;
  10824. // FIXME: dirty waiting
  10825. if (!this.peerconnection.localDescription)
  10826. {
  10827. console.warn("addSource - localDescription not ready yet")
  10828. setTimeout(function()
  10829. {
  10830. self.addSource(elem, fromJid);
  10831. },
  10832. 200
  10833. );
  10834. return;
  10835. }
  10836. console.log('addssrc', new Date().getTime());
  10837. console.log('ice', this.peerconnection.iceConnectionState);
  10838. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10839. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10840. $(elem).each(function (idx, content) {
  10841. var name = $(content).attr('name');
  10842. var lines = '';
  10843. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10844. var semantics = this.getAttribute('semantics');
  10845. var ssrcs = $(this).find('>source').map(function () {
  10846. return this.getAttribute('ssrc');
  10847. }).get();
  10848. if (ssrcs.length != 0) {
  10849. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10850. }
  10851. });
  10852. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  10853. tmp.each(function () {
  10854. var ssrc = $(this).attr('ssrc');
  10855. if(mySdp.containsSSRC(ssrc)){
  10856. /**
  10857. * This happens when multiple participants change their streams at the same time and
  10858. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  10859. * addssrc are scheduled for update IQ. See
  10860. */
  10861. console.warn("Got add stream request for my own ssrc: "+ssrc);
  10862. return;
  10863. }
  10864. $(this).find('>parameter').each(function () {
  10865. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  10866. if ($(this).attr('value') && $(this).attr('value').length)
  10867. lines += ':' + $(this).attr('value');
  10868. lines += '\r\n';
  10869. });
  10870. });
  10871. sdp.media.forEach(function(media, idx) {
  10872. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  10873. return;
  10874. sdp.media[idx] += lines;
  10875. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  10876. self.addssrc[idx] += lines;
  10877. });
  10878. sdp.raw = sdp.session + sdp.media.join('');
  10879. });
  10880. this.modifySources();
  10881. };
  10882. JingleSession.prototype.removeSource = function (elem, fromJid) {
  10883. var self = this;
  10884. // FIXME: dirty waiting
  10885. if (!this.peerconnection.localDescription)
  10886. {
  10887. console.warn("removeSource - localDescription not ready yet")
  10888. setTimeout(function()
  10889. {
  10890. self.removeSource(elem, fromJid);
  10891. },
  10892. 200
  10893. );
  10894. return;
  10895. }
  10896. console.log('removessrc', new Date().getTime());
  10897. console.log('ice', this.peerconnection.iceConnectionState);
  10898. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10899. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10900. $(elem).each(function (idx, content) {
  10901. var name = $(content).attr('name');
  10902. var lines = '';
  10903. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10904. var semantics = this.getAttribute('semantics');
  10905. var ssrcs = $(this).find('>source').map(function () {
  10906. return this.getAttribute('ssrc');
  10907. }).get();
  10908. if (ssrcs.length != 0) {
  10909. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10910. }
  10911. });
  10912. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  10913. tmp.each(function () {
  10914. var ssrc = $(this).attr('ssrc');
  10915. // This should never happen, but can be useful for bug detection
  10916. if(mySdp.containsSSRC(ssrc)){
  10917. console.error("Got remove stream request for my own ssrc: "+ssrc);
  10918. return;
  10919. }
  10920. $(this).find('>parameter').each(function () {
  10921. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  10922. if ($(this).attr('value') && $(this).attr('value').length)
  10923. lines += ':' + $(this).attr('value');
  10924. lines += '\r\n';
  10925. });
  10926. });
  10927. sdp.media.forEach(function(media, idx) {
  10928. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  10929. return;
  10930. sdp.media[idx] += lines;
  10931. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  10932. self.removessrc[idx] += lines;
  10933. });
  10934. sdp.raw = sdp.session + sdp.media.join('');
  10935. });
  10936. this.modifySources();
  10937. };
  10938. JingleSession.prototype.modifySources = function (successCallback) {
  10939. var self = this;
  10940. if (this.peerconnection.signalingState == 'closed') return;
  10941. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  10942. // There is nothing to do since scheduled job might have been executed by another succeeding call
  10943. this.setLocalDescription();
  10944. if(successCallback){
  10945. successCallback();
  10946. }
  10947. return;
  10948. }
  10949. // FIXME: this is a big hack
  10950. // https://code.google.com/p/webrtc/issues/detail?id=2688
  10951. // ^ has been fixed.
  10952. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
  10953. console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
  10954. this.wait = true;
  10955. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  10956. return;
  10957. }
  10958. if (this.wait) {
  10959. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  10960. this.wait = false;
  10961. return;
  10962. }
  10963. // Reset switch streams flag
  10964. this.switchstreams = false;
  10965. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10966. // add sources
  10967. this.addssrc.forEach(function(lines, idx) {
  10968. sdp.media[idx] += lines;
  10969. });
  10970. this.addssrc = [];
  10971. // remove sources
  10972. this.removessrc.forEach(function(lines, idx) {
  10973. lines = lines.split('\r\n');
  10974. lines.pop(); // remove empty last element;
  10975. lines.forEach(function(line) {
  10976. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  10977. });
  10978. });
  10979. this.removessrc = [];
  10980. // FIXME:
  10981. // this was a hack for the situation when only one peer exists
  10982. // in the conference.
  10983. // check if still required and remove
  10984. if (sdp.media[0])
  10985. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  10986. if (sdp.media[1])
  10987. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  10988. sdp.raw = sdp.session + sdp.media.join('');
  10989. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  10990. function() {
  10991. if(self.signalingState == 'closed') {
  10992. console.error("createAnswer attempt on closed state");
  10993. return;
  10994. }
  10995. self.peerconnection.createAnswer(
  10996. function(modifiedAnswer) {
  10997. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  10998. if (self.pendingop !== null) {
  10999. var sdp = new SDP(modifiedAnswer.sdp);
  11000. if (sdp.media.length > 1) {
  11001. switch(self.pendingop) {
  11002. case 'mute':
  11003. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  11004. break;
  11005. case 'unmute':
  11006. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11007. break;
  11008. }
  11009. sdp.raw = sdp.session + sdp.media.join('');
  11010. modifiedAnswer.sdp = sdp.raw;
  11011. }
  11012. self.pendingop = null;
  11013. }
  11014. // FIXME: pushing down an answer while ice connection state
  11015. // is still checking is bad...
  11016. //console.log(self.peerconnection.iceConnectionState);
  11017. // trying to work around another chrome bug
  11018. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11019. self.peerconnection.setLocalDescription(modifiedAnswer,
  11020. function() {
  11021. //console.log('modified setLocalDescription ok');
  11022. self.setLocalDescription();
  11023. if(successCallback){
  11024. successCallback();
  11025. }
  11026. },
  11027. function(error) {
  11028. console.error('modified setLocalDescription failed', error);
  11029. }
  11030. );
  11031. },
  11032. function(error) {
  11033. console.error('modified answer failed', error);
  11034. }
  11035. );
  11036. },
  11037. function(error) {
  11038. console.error('modify failed', error);
  11039. }
  11040. );
  11041. };
  11042. /**
  11043. * Switches video streams.
  11044. * @param new_stream new stream that will be used as video of this session.
  11045. * @param oldStream old video stream of this session.
  11046. * @param success_callback callback executed after successful stream switch.
  11047. */
  11048. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback) {
  11049. var self = this;
  11050. // Remember SDP to figure out added/removed SSRCs
  11051. var oldSdp = null;
  11052. if(self.peerconnection) {
  11053. if(self.peerconnection.localDescription) {
  11054. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11055. }
  11056. self.peerconnection.removeStream(oldStream, true);
  11057. self.peerconnection.addStream(new_stream);
  11058. }
  11059. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11060. // Conference is not active
  11061. if(!oldSdp || !self.peerconnection) {
  11062. success_callback();
  11063. return;
  11064. }
  11065. self.switchstreams = true;
  11066. self.modifySources(function() {
  11067. console.log('modify sources done');
  11068. success_callback();
  11069. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11070. console.log("SDPs", oldSdp, newSdp);
  11071. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11072. });
  11073. };
  11074. /**
  11075. * Figures out added/removed ssrcs and send update IQs.
  11076. * @param old_sdp SDP object for old description.
  11077. * @param new_sdp SDP object for new description.
  11078. */
  11079. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11080. if (!(this.peerconnection.signalingState == 'stable' &&
  11081. this.peerconnection.iceConnectionState == 'connected')){
  11082. console.log("Too early to send updates");
  11083. return;
  11084. }
  11085. // send source-remove IQ.
  11086. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11087. var remove = $iq({to: this.peerjid, type: 'set'})
  11088. .c('jingle', {
  11089. xmlns: 'urn:xmpp:jingle:1',
  11090. action: 'source-remove',
  11091. initiator: this.initiator,
  11092. sid: this.sid
  11093. }
  11094. );
  11095. var removed = sdpDiffer.toJingle(remove);
  11096. if (removed) {
  11097. this.connection.sendIQ(remove,
  11098. function (res) {
  11099. console.info('got remove result', res);
  11100. },
  11101. function (err) {
  11102. console.error('got remove error', err);
  11103. }
  11104. );
  11105. } else {
  11106. console.log('removal not necessary');
  11107. }
  11108. // send source-add IQ.
  11109. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11110. var add = $iq({to: this.peerjid, type: 'set'})
  11111. .c('jingle', {
  11112. xmlns: 'urn:xmpp:jingle:1',
  11113. action: 'source-add',
  11114. initiator: this.initiator,
  11115. sid: this.sid
  11116. }
  11117. );
  11118. var added = sdpDiffer.toJingle(add);
  11119. if (added) {
  11120. this.connection.sendIQ(add,
  11121. function (res) {
  11122. console.info('got add result', res);
  11123. },
  11124. function (err) {
  11125. console.error('got add error', err);
  11126. }
  11127. );
  11128. } else {
  11129. console.log('addition not necessary');
  11130. }
  11131. };
  11132. /**
  11133. * Determines whether the (local) video is mute i.e. all video tracks are
  11134. * disabled.
  11135. *
  11136. * @return <tt>true</tt> if the (local) video is mute i.e. all video tracks are
  11137. * disabled; otherwise, <tt>false</tt>
  11138. */
  11139. JingleSession.prototype.isVideoMute = function () {
  11140. var tracks = APP.RTC.localVideo.getVideoTracks();
  11141. var mute = true;
  11142. for (var i = 0; i < tracks.length; ++i) {
  11143. if (tracks[i].enabled) {
  11144. mute = false;
  11145. break;
  11146. }
  11147. }
  11148. return mute;
  11149. };
  11150. /**
  11151. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  11152. *
  11153. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  11154. * tracks; otherwise, <tt>false</tt>
  11155. * @param callback a function to be invoked with <tt>mute</tt> after all video
  11156. * tracks have been enabled/disabled. The function may, optionally, return
  11157. * another function which is to be invoked after the whole mute/unmute operation
  11158. * has completed successfully.
  11159. * @param options an object which specifies optional arguments such as the
  11160. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  11161. * specifies whether the method was initiated in response to a user command (in
  11162. * contrast to an automatic decision made by the application logic)
  11163. */
  11164. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  11165. var byUser;
  11166. if (options) {
  11167. byUser = options.byUser;
  11168. if (typeof byUser === 'undefined') {
  11169. byUser = true;
  11170. }
  11171. } else {
  11172. byUser = true;
  11173. }
  11174. // The user's command to mute the (local) video takes precedence over any
  11175. // automatic decision made by the application logic.
  11176. if (byUser) {
  11177. this.videoMuteByUser = mute;
  11178. } else if (this.videoMuteByUser) {
  11179. return;
  11180. }
  11181. var self = this;
  11182. var localCallback = function (mute) {
  11183. self.connection.emuc.addVideoInfoToPresence(mute);
  11184. self.connection.emuc.sendPresence();
  11185. return callback(mute)
  11186. };
  11187. if (mute == APP.RTC.localVideo.isMuted())
  11188. {
  11189. // Even if no change occurs, the specified callback is to be executed.
  11190. // The specified callback may, optionally, return a successCallback
  11191. // which is to be executed as well.
  11192. var successCallback = localCallback(mute);
  11193. if (successCallback) {
  11194. successCallback();
  11195. }
  11196. } else {
  11197. APP.RTC.localVideo.setMute(!mute);
  11198. this.hardMuteVideo(mute);
  11199. this.modifySources(localCallback(mute));
  11200. }
  11201. };
  11202. // SDP-based mute by going recvonly/sendrecv
  11203. // FIXME: should probably black out the screen as well
  11204. JingleSession.prototype.toggleVideoMute = function (callback) {
  11205. this.service.setVideoMute(APP.RTC.localVideo.isMuted(), callback);
  11206. };
  11207. JingleSession.prototype.hardMuteVideo = function (muted) {
  11208. this.pendingop = muted ? 'mute' : 'unmute';
  11209. };
  11210. JingleSession.prototype.sendMute = function (muted, content) {
  11211. var info = $iq({to: this.peerjid,
  11212. type: 'set'})
  11213. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11214. action: 'session-info',
  11215. initiator: this.initiator,
  11216. sid: this.sid });
  11217. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11218. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  11219. if (content) {
  11220. info.attrs({'name': content});
  11221. }
  11222. this.connection.send(info);
  11223. };
  11224. JingleSession.prototype.sendRinging = function () {
  11225. var info = $iq({to: this.peerjid,
  11226. type: 'set'})
  11227. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11228. action: 'session-info',
  11229. initiator: this.initiator,
  11230. sid: this.sid });
  11231. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11232. this.connection.send(info);
  11233. };
  11234. JingleSession.prototype.getStats = function (interval) {
  11235. var self = this;
  11236. var recv = {audio: 0, video: 0};
  11237. var lost = {audio: 0, video: 0};
  11238. var lastrecv = {audio: 0, video: 0};
  11239. var lastlost = {audio: 0, video: 0};
  11240. var loss = {audio: 0, video: 0};
  11241. var delta = {audio: 0, video: 0};
  11242. this.statsinterval = window.setInterval(function () {
  11243. if (self && self.peerconnection && self.peerconnection.getStats) {
  11244. self.peerconnection.getStats(function (stats) {
  11245. var results = stats.result();
  11246. // TODO: there are so much statistics you can get from this..
  11247. for (var i = 0; i < results.length; ++i) {
  11248. if (results[i].type == 'ssrc') {
  11249. var packetsrecv = results[i].stat('packetsReceived');
  11250. var packetslost = results[i].stat('packetsLost');
  11251. if (packetsrecv && packetslost) {
  11252. packetsrecv = parseInt(packetsrecv, 10);
  11253. packetslost = parseInt(packetslost, 10);
  11254. if (results[i].stat('googFrameRateReceived')) {
  11255. lastlost.video = lost.video;
  11256. lastrecv.video = recv.video;
  11257. recv.video = packetsrecv;
  11258. lost.video = packetslost;
  11259. } else {
  11260. lastlost.audio = lost.audio;
  11261. lastrecv.audio = recv.audio;
  11262. recv.audio = packetsrecv;
  11263. lost.audio = packetslost;
  11264. }
  11265. }
  11266. }
  11267. }
  11268. delta.audio = recv.audio - lastrecv.audio;
  11269. delta.video = recv.video - lastrecv.video;
  11270. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  11271. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  11272. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  11273. });
  11274. }
  11275. }, interval || 3000);
  11276. return this.statsinterval;
  11277. };
  11278. JingleSession.onJingleError = function (session, error)
  11279. {
  11280. console.error("Jingle error", error);
  11281. }
  11282. JingleSession.onJingleFatalError = function (session, error)
  11283. {
  11284. this.service.sessionTerminated = true;
  11285. this.connection.emuc.doLeave();
  11286. APP.UI.messageHandler.showError("dialog.sorry", "Sorry",
  11287. "dialog.internalError",
  11288. "Internal application error[setRemoteDescription]");
  11289. }
  11290. JingleSession.prototype.setLocalDescription = function () {
  11291. // put our ssrcs into presence so other clients can identify our stream
  11292. var newssrcs = [];
  11293. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  11294. media.forEach(function (media) {
  11295. if(Object.keys(media.sources).length > 0) {
  11296. // TODO(gp) maybe exclude FID streams?
  11297. Object.keys(media.sources).forEach(function (ssrc) {
  11298. newssrcs.push({
  11299. 'ssrc': ssrc,
  11300. 'type': media.type,
  11301. 'direction': media.direction
  11302. });
  11303. });
  11304. }
  11305. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  11306. {
  11307. newssrcs.push({
  11308. 'ssrc': this.localStreamsSSRC[media.type],
  11309. 'type': media.type,
  11310. 'direction': media.direction
  11311. });
  11312. }
  11313. });
  11314. console.log('new ssrcs', newssrcs);
  11315. // Have to clear presence map to get rid of removed streams
  11316. this.connection.emuc.clearPresenceMedia();
  11317. if (newssrcs.length > 0) {
  11318. for (var i = 1; i <= newssrcs.length; i ++) {
  11319. // Change video type to screen
  11320. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  11321. newssrcs[i-1].type = 'screen';
  11322. }
  11323. this.connection.emuc.addMediaToPresence(i,
  11324. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  11325. }
  11326. this.connection.emuc.sendPresence();
  11327. }
  11328. }
  11329. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11330. function sendKeyframe(pc) {
  11331. console.log('sendkeyframe', pc.iceConnectionState);
  11332. if (pc.iceConnectionState !== 'connected') return; // safe...
  11333. pc.setRemoteDescription(
  11334. pc.remoteDescription,
  11335. function () {
  11336. pc.createAnswer(
  11337. function (modifiedAnswer) {
  11338. pc.setLocalDescription(
  11339. modifiedAnswer,
  11340. function () {
  11341. // noop
  11342. },
  11343. function (error) {
  11344. console.log('triggerKeyframe setLocalDescription failed', error);
  11345. APP.UI.messageHandler.showError();
  11346. }
  11347. );
  11348. },
  11349. function (error) {
  11350. console.log('triggerKeyframe createAnswer failed', error);
  11351. APP.UI.messageHandler.showError();
  11352. }
  11353. );
  11354. },
  11355. function (error) {
  11356. console.log('triggerKeyframe setRemoteDescription failed', error);
  11357. APP.UI.messageHandler.showError();
  11358. }
  11359. );
  11360. }
  11361. JingleSession.prototype.remoteStreamAdded = function (data) {
  11362. var self = this;
  11363. var thessrc;
  11364. var ssrc2jid = this.connection.emuc.ssrc2jid;
  11365. // look up an associated JID for a stream id
  11366. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  11367. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  11368. var ssrclines
  11369. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  11370. ssrclines = ssrclines.filter(function (line) {
  11371. // NOTE(gp) previously we filtered on the mslabel, but that property
  11372. // is not always present.
  11373. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  11374. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  11375. });
  11376. if (ssrclines.length) {
  11377. thessrc = ssrclines[0].substring(7).split(' ')[0];
  11378. // We signal our streams (through Jingle to the focus) before we set
  11379. // our presence (through which peers associate remote streams to
  11380. // jids). So, it might arrive that a remote stream is added but
  11381. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  11382. // successfully set. Here we wait for up to a second for the
  11383. // presence to arrive.
  11384. if (!ssrc2jid[thessrc]) {
  11385. // TODO(gp) limit wait duration to 1 sec.
  11386. setTimeout(function(d) {
  11387. return function() {
  11388. self.remoteStreamAdded(d);
  11389. }
  11390. }(data), 250);
  11391. return;
  11392. }
  11393. // ok to overwrite the one from focus? might save work in colibri.js
  11394. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  11395. if (ssrc2jid[thessrc]) {
  11396. data.peerjid = ssrc2jid[thessrc];
  11397. }
  11398. }
  11399. }
  11400. //TODO: this code should be removed when firefox implement multistream support
  11401. if(APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_FIREFOX)
  11402. {
  11403. if((JingleSession.notReceivedSSRCs.length == 0) ||
  11404. !ssrc2jid[JingleSession.notReceivedSSRCs[JingleSession.notReceivedSSRCs.length - 1]])
  11405. {
  11406. // TODO(gp) limit wait duration to 1 sec.
  11407. setTimeout(function(d) {
  11408. return function() {
  11409. self.remoteStreamAdded(d);
  11410. }
  11411. }(data), 250);
  11412. return;
  11413. }
  11414. thessrc = JingleSession.notReceivedSSRCs.pop();
  11415. if (ssrc2jid[thessrc]) {
  11416. data.peerjid = ssrc2jid[thessrc];
  11417. }
  11418. }
  11419. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  11420. var isVideo = data.stream.getVideoTracks().length > 0;
  11421. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11422. if (isVideo &&
  11423. data.peerjid && this.peerjid === data.peerjid &&
  11424. data.stream.getVideoTracks().length === 0 &&
  11425. APP.RTC.localVideo.getTracks().length > 0) {
  11426. window.setTimeout(function () {
  11427. sendKeyframe(self.peerconnection);
  11428. }, 3000);
  11429. }
  11430. }
  11431. module.exports = JingleSession;
  11432. },{"../../service/RTC/RTCBrowserType":79,"./SDP":48,"./SDPDiffer":49,"./SDPUtil":50,"./TraceablePeerConnection":51}],48:[function(require,module,exports){
  11433. /* jshint -W117 */
  11434. var SDPUtil = require("./SDPUtil");
  11435. // SDP STUFF
  11436. function SDP(sdp) {
  11437. this.media = sdp.split('\r\nm=');
  11438. for (var i = 1; i < this.media.length; i++) {
  11439. this.media[i] = 'm=' + this.media[i];
  11440. if (i != this.media.length - 1) {
  11441. this.media[i] += '\r\n';
  11442. }
  11443. }
  11444. this.session = this.media.shift() + '\r\n';
  11445. this.raw = this.session + this.media.join('');
  11446. }
  11447. /**
  11448. * Returns map of MediaChannel mapped per channel idx.
  11449. */
  11450. SDP.prototype.getMediaSsrcMap = function() {
  11451. var self = this;
  11452. var media_ssrcs = {};
  11453. var tmp;
  11454. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  11455. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  11456. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  11457. var media = {
  11458. mediaindex: mediaindex,
  11459. mid: mid,
  11460. ssrcs: {},
  11461. ssrcGroups: []
  11462. };
  11463. media_ssrcs[mediaindex] = media;
  11464. tmp.forEach(function (line) {
  11465. var linessrc = line.substring(7).split(' ')[0];
  11466. // allocate new ChannelSsrc
  11467. if(!media.ssrcs[linessrc]) {
  11468. media.ssrcs[linessrc] = {
  11469. ssrc: linessrc,
  11470. lines: []
  11471. };
  11472. }
  11473. media.ssrcs[linessrc].lines.push(line);
  11474. });
  11475. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  11476. tmp.forEach(function(line){
  11477. var semantics = line.substr(0, idx).substr(13);
  11478. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11479. if (ssrcs.length != 0) {
  11480. media.ssrcGroups.push({
  11481. semantics: semantics,
  11482. ssrcs: ssrcs
  11483. });
  11484. }
  11485. });
  11486. }
  11487. return media_ssrcs;
  11488. };
  11489. /**
  11490. * Returns <tt>true</tt> if this SDP contains given SSRC.
  11491. * @param ssrc the ssrc to check.
  11492. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  11493. */
  11494. SDP.prototype.containsSSRC = function(ssrc) {
  11495. var medias = this.getMediaSsrcMap();
  11496. var contains = false;
  11497. Object.keys(medias).forEach(function(mediaindex){
  11498. var media = medias[mediaindex];
  11499. //console.log("Check", channel, ssrc);
  11500. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  11501. contains = true;
  11502. }
  11503. });
  11504. return contains;
  11505. };
  11506. // remove iSAC and CN from SDP
  11507. SDP.prototype.mangle = function () {
  11508. var i, j, mline, lines, rtpmap, newdesc;
  11509. for (i = 0; i < this.media.length; i++) {
  11510. lines = this.media[i].split('\r\n');
  11511. lines.pop(); // remove empty last element
  11512. mline = SDPUtil.parse_mline(lines.shift());
  11513. if (mline.media != 'audio')
  11514. continue;
  11515. newdesc = '';
  11516. mline.fmt.length = 0;
  11517. for (j = 0; j < lines.length; j++) {
  11518. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  11519. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  11520. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  11521. continue;
  11522. mline.fmt.push(rtpmap.id);
  11523. newdesc += lines[j] + '\r\n';
  11524. } else {
  11525. newdesc += lines[j] + '\r\n';
  11526. }
  11527. }
  11528. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  11529. this.media[i] += newdesc;
  11530. }
  11531. this.raw = this.session + this.media.join('');
  11532. };
  11533. // remove lines matching prefix from session section
  11534. SDP.prototype.removeSessionLines = function(prefix) {
  11535. var self = this;
  11536. var lines = SDPUtil.find_lines(this.session, prefix);
  11537. lines.forEach(function(line) {
  11538. self.session = self.session.replace(line + '\r\n', '');
  11539. });
  11540. this.raw = this.session + this.media.join('');
  11541. return lines;
  11542. }
  11543. // remove lines matching prefix from a media section specified by mediaindex
  11544. // TODO: non-numeric mediaindex could match mid
  11545. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  11546. var self = this;
  11547. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  11548. lines.forEach(function(line) {
  11549. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  11550. });
  11551. this.raw = this.session + this.media.join('');
  11552. return lines;
  11553. }
  11554. // add content's to a jingle element
  11555. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  11556. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  11557. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  11558. var self = this;
  11559. // new bundle plan
  11560. if (SDPUtil.find_line(this.session, 'a=group:')) {
  11561. lines = SDPUtil.find_lines(this.session, 'a=group:');
  11562. for (i = 0; i < lines.length; i++) {
  11563. tmp = lines[i].split(' ');
  11564. var semantics = tmp.shift().substr(8);
  11565. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  11566. for (j = 0; j < tmp.length; j++) {
  11567. elem.c('content', {name: tmp[j]}).up();
  11568. }
  11569. elem.up();
  11570. }
  11571. }
  11572. for (i = 0; i < this.media.length; i++) {
  11573. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  11574. if (!(mline.media === 'audio' ||
  11575. mline.media === 'video' ||
  11576. mline.media === 'application'))
  11577. {
  11578. continue;
  11579. }
  11580. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  11581. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  11582. } else {
  11583. if(ssrcs && ssrcs[mline.media])
  11584. {
  11585. ssrc = ssrcs[mline.media];
  11586. }
  11587. else
  11588. ssrc = false;
  11589. }
  11590. elem.c('content', {creator: thecreator, name: mline.media});
  11591. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  11592. // prefer identifier from a=mid if present
  11593. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  11594. elem.attrs({ name: mid });
  11595. }
  11596. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  11597. {
  11598. elem.c('description',
  11599. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  11600. media: mline.media });
  11601. if (ssrc) {
  11602. elem.attrs({ssrc: ssrc});
  11603. }
  11604. for (j = 0; j < mline.fmt.length; j++) {
  11605. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  11606. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  11607. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  11608. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  11609. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  11610. for (k = 0; k < tmp.length; k++) {
  11611. elem.c('parameter', tmp[k]).up();
  11612. }
  11613. }
  11614. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  11615. elem.up();
  11616. }
  11617. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  11618. elem.c('encryption', {required: 1});
  11619. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  11620. crypto.forEach(function(line) {
  11621. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  11622. });
  11623. elem.up(); // end of encryption
  11624. }
  11625. if (ssrc) {
  11626. // new style mapping
  11627. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11628. // FIXME: group by ssrc and support multiple different ssrcs
  11629. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  11630. if(ssrclines.length > 0) {
  11631. ssrclines.forEach(function (line) {
  11632. idx = line.indexOf(' ');
  11633. var linessrc = line.substr(0, idx).substr(7);
  11634. if (linessrc != ssrc) {
  11635. elem.up();
  11636. ssrc = linessrc;
  11637. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11638. }
  11639. var kv = line.substr(idx + 1);
  11640. elem.c('parameter');
  11641. if (kv.indexOf(':') == -1) {
  11642. elem.attrs({ name: kv });
  11643. } else {
  11644. elem.attrs({ name: kv.split(':', 2)[0] });
  11645. elem.attrs({ value: kv.split(':', 2)[1] });
  11646. }
  11647. elem.up();
  11648. });
  11649. elem.up();
  11650. }
  11651. else
  11652. {
  11653. elem.up();
  11654. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11655. elem.c('parameter');
  11656. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  11657. elem.up();
  11658. var msid = null;
  11659. if(mline.media == "audio")
  11660. {
  11661. msid = APP.RTC.localAudio.getId();
  11662. }
  11663. else
  11664. {
  11665. msid = APP.RTC.localVideo.getId();
  11666. }
  11667. if(msid != null)
  11668. {
  11669. msid = msid.replace(/[\{,\}]/g,"");
  11670. elem.c('parameter');
  11671. elem.attrs({name: "msid", value:msid});
  11672. elem.up();
  11673. elem.c('parameter');
  11674. elem.attrs({name: "mslabel", value:msid});
  11675. elem.up();
  11676. elem.c('parameter');
  11677. elem.attrs({name: "label", value:msid});
  11678. elem.up();
  11679. elem.up();
  11680. }
  11681. }
  11682. // XEP-0339 handle ssrc-group attributes
  11683. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  11684. ssrc_group_lines.forEach(function(line) {
  11685. idx = line.indexOf(' ');
  11686. var semantics = line.substr(0, idx).substr(13);
  11687. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11688. if (ssrcs.length != 0) {
  11689. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11690. ssrcs.forEach(function(ssrc) {
  11691. elem.c('source', { ssrc: ssrc })
  11692. .up();
  11693. });
  11694. elem.up();
  11695. }
  11696. });
  11697. }
  11698. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  11699. elem.c('rtcp-mux').up();
  11700. }
  11701. // XEP-0293 -- map a=rtcp-fb:*
  11702. this.RtcpFbToJingle(i, elem, '*');
  11703. // XEP-0294
  11704. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  11705. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  11706. for (j = 0; j < lines.length; j++) {
  11707. tmp = SDPUtil.parse_extmap(lines[j]);
  11708. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  11709. uri: tmp.uri,
  11710. id: tmp.value });
  11711. if (tmp.hasOwnProperty('direction')) {
  11712. switch (tmp.direction) {
  11713. case 'sendonly':
  11714. elem.attrs({senders: 'responder'});
  11715. break;
  11716. case 'recvonly':
  11717. elem.attrs({senders: 'initiator'});
  11718. break;
  11719. case 'sendrecv':
  11720. elem.attrs({senders: 'both'});
  11721. break;
  11722. case 'inactive':
  11723. elem.attrs({senders: 'none'});
  11724. break;
  11725. }
  11726. }
  11727. // TODO: handle params
  11728. elem.up();
  11729. }
  11730. }
  11731. elem.up(); // end of description
  11732. }
  11733. // map ice-ufrag/pwd, dtls fingerprint, candidates
  11734. this.TransportToJingle(i, elem);
  11735. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  11736. elem.attrs({senders: 'both'});
  11737. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  11738. elem.attrs({senders: 'initiator'});
  11739. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  11740. elem.attrs({senders: 'responder'});
  11741. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  11742. elem.attrs({senders: 'none'});
  11743. }
  11744. if (mline.port == '0') {
  11745. // estos hack to reject an m-line
  11746. elem.attrs({senders: 'rejected'});
  11747. }
  11748. elem.up(); // end of content
  11749. }
  11750. elem.up();
  11751. return elem;
  11752. };
  11753. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  11754. var i = mediaindex;
  11755. var tmp;
  11756. var self = this;
  11757. elem.c('transport');
  11758. // XEP-0343 DTLS/SCTP
  11759. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  11760. {
  11761. var sctpmap = SDPUtil.find_line(
  11762. this.media[i], 'a=sctpmap:', self.session);
  11763. if (sctpmap)
  11764. {
  11765. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  11766. elem.c('sctpmap',
  11767. {
  11768. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  11769. number: sctpAttrs[0], /* SCTP port */
  11770. protocol: sctpAttrs[1], /* protocol */
  11771. });
  11772. // Optional stream count attribute
  11773. if (sctpAttrs.length > 2)
  11774. elem.attrs({ streams: sctpAttrs[2]});
  11775. elem.up();
  11776. }
  11777. }
  11778. // XEP-0320
  11779. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  11780. fingerprints.forEach(function(line) {
  11781. tmp = SDPUtil.parse_fingerprint(line);
  11782. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  11783. elem.c('fingerprint').t(tmp.fingerprint);
  11784. delete tmp.fingerprint;
  11785. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  11786. if (line) {
  11787. tmp.setup = line.substr(8);
  11788. }
  11789. elem.attrs(tmp);
  11790. elem.up(); // end of fingerprint
  11791. });
  11792. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  11793. if (tmp) {
  11794. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11795. elem.attrs(tmp);
  11796. // XEP-0176
  11797. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  11798. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  11799. lines.forEach(function (line) {
  11800. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  11801. });
  11802. }
  11803. }
  11804. elem.up(); // end of transport
  11805. }
  11806. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  11807. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  11808. lines.forEach(function (line) {
  11809. var tmp = SDPUtil.parse_rtcpfb(line);
  11810. if (tmp.type == 'trr-int') {
  11811. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  11812. elem.up();
  11813. } else {
  11814. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  11815. if (tmp.params.length > 0) {
  11816. elem.attrs({'subtype': tmp.params[0]});
  11817. }
  11818. elem.up();
  11819. }
  11820. });
  11821. };
  11822. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  11823. var media = '';
  11824. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11825. if (tmp.length) {
  11826. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  11827. if (tmp.attr('value')) {
  11828. media += tmp.attr('value');
  11829. } else {
  11830. media += '0';
  11831. }
  11832. media += '\r\n';
  11833. }
  11834. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11835. tmp.each(function () {
  11836. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  11837. if ($(this).attr('subtype')) {
  11838. media += ' ' + $(this).attr('subtype');
  11839. }
  11840. media += '\r\n';
  11841. });
  11842. return media;
  11843. };
  11844. // construct an SDP from a jingle stanza
  11845. SDP.prototype.fromJingle = function (jingle) {
  11846. var self = this;
  11847. this.raw = 'v=0\r\n' +
  11848. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11849. 's=-\r\n' +
  11850. 't=0 0\r\n';
  11851. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  11852. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  11853. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  11854. var contents = $(group).find('>content').map(function (idx, content) {
  11855. return content.getAttribute('name');
  11856. }).get();
  11857. if (contents.length > 0) {
  11858. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  11859. }
  11860. });
  11861. }
  11862. this.session = this.raw;
  11863. jingle.find('>content').each(function () {
  11864. var m = self.jingle2media($(this));
  11865. self.media.push(m);
  11866. });
  11867. // reconstruct msid-semantic -- apparently not necessary
  11868. /*
  11869. var msid = SDPUtil.parse_ssrc(this.raw);
  11870. if (msid.hasOwnProperty('mslabel')) {
  11871. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  11872. }
  11873. */
  11874. this.raw = this.session + this.media.join('');
  11875. };
  11876. // translate a jingle content element into an an SDP media part
  11877. SDP.prototype.jingle2media = function (content) {
  11878. var media = '',
  11879. desc = content.find('description'),
  11880. ssrc = desc.attr('ssrc'),
  11881. self = this,
  11882. tmp;
  11883. var sctp = content.find(
  11884. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  11885. tmp = { media: desc.attr('media') };
  11886. tmp.port = '1';
  11887. if (content.attr('senders') == 'rejected') {
  11888. // estos hack to reject an m-line.
  11889. tmp.port = '0';
  11890. }
  11891. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  11892. if (sctp.length)
  11893. tmp.proto = 'DTLS/SCTP';
  11894. else
  11895. tmp.proto = 'RTP/SAVPF';
  11896. } else {
  11897. tmp.proto = 'RTP/AVPF';
  11898. }
  11899. if (!sctp.length)
  11900. {
  11901. tmp.fmt = desc.find('payload-type').map(
  11902. function () { return this.getAttribute('id'); }).get();
  11903. media += SDPUtil.build_mline(tmp) + '\r\n';
  11904. }
  11905. else
  11906. {
  11907. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  11908. media += 'a=sctpmap:' + sctp.attr('number') +
  11909. ' ' + sctp.attr('protocol');
  11910. var streamCount = sctp.attr('streams');
  11911. if (streamCount)
  11912. media += ' ' + streamCount + '\r\n';
  11913. else
  11914. media += '\r\n';
  11915. }
  11916. media += 'c=IN IP4 0.0.0.0\r\n';
  11917. if (!sctp.length)
  11918. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  11919. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  11920. if (tmp.length) {
  11921. if (tmp.attr('ufrag')) {
  11922. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  11923. }
  11924. if (tmp.attr('pwd')) {
  11925. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  11926. }
  11927. tmp.find('>fingerprint').each(function () {
  11928. // FIXME: check namespace at some point
  11929. media += 'a=fingerprint:' + this.getAttribute('hash');
  11930. media += ' ' + $(this).text();
  11931. media += '\r\n';
  11932. if (this.getAttribute('setup')) {
  11933. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  11934. }
  11935. });
  11936. }
  11937. switch (content.attr('senders')) {
  11938. case 'initiator':
  11939. media += 'a=sendonly\r\n';
  11940. break;
  11941. case 'responder':
  11942. media += 'a=recvonly\r\n';
  11943. break;
  11944. case 'none':
  11945. media += 'a=inactive\r\n';
  11946. break;
  11947. case 'both':
  11948. media += 'a=sendrecv\r\n';
  11949. break;
  11950. }
  11951. media += 'a=mid:' + content.attr('name') + '\r\n';
  11952. // <description><rtcp-mux/></description>
  11953. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  11954. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  11955. if (desc.find('rtcp-mux').length) {
  11956. media += 'a=rtcp-mux\r\n';
  11957. }
  11958. if (desc.find('encryption').length) {
  11959. desc.find('encryption>crypto').each(function () {
  11960. media += 'a=crypto:' + this.getAttribute('tag');
  11961. media += ' ' + this.getAttribute('crypto-suite');
  11962. media += ' ' + this.getAttribute('key-params');
  11963. if (this.getAttribute('session-params')) {
  11964. media += ' ' + this.getAttribute('session-params');
  11965. }
  11966. media += '\r\n';
  11967. });
  11968. }
  11969. desc.find('payload-type').each(function () {
  11970. media += SDPUtil.build_rtpmap(this) + '\r\n';
  11971. if ($(this).find('>parameter').length) {
  11972. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  11973. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  11974. media += '\r\n';
  11975. }
  11976. // xep-0293
  11977. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  11978. });
  11979. // xep-0293
  11980. media += self.RtcpFbFromJingle(desc, '*');
  11981. // xep-0294
  11982. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  11983. tmp.each(function () {
  11984. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  11985. });
  11986. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  11987. media += SDPUtil.candidateFromJingle(this);
  11988. });
  11989. // XEP-0339 handle ssrc-group attributes
  11990. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11991. var semantics = this.getAttribute('semantics');
  11992. var ssrcs = $(this).find('>source').map(function() {
  11993. return this.getAttribute('ssrc');
  11994. }).get();
  11995. if (ssrcs.length != 0) {
  11996. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11997. }
  11998. });
  11999. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12000. tmp.each(function () {
  12001. var ssrc = this.getAttribute('ssrc');
  12002. $(this).find('>parameter').each(function () {
  12003. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  12004. if (this.getAttribute('value') && this.getAttribute('value').length)
  12005. media += ':' + this.getAttribute('value');
  12006. media += '\r\n';
  12007. });
  12008. });
  12009. return media;
  12010. };
  12011. module.exports = SDP;
  12012. },{"./SDPUtil":50}],49:[function(require,module,exports){
  12013. function SDPDiffer(mySDP, otherSDP) {
  12014. this.mySDP = mySDP;
  12015. this.otherSDP = otherSDP;
  12016. }
  12017. /**
  12018. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  12019. * @param otherSdp the other SDP to check ssrc with.
  12020. */
  12021. SDPDiffer.prototype.getNewMedia = function() {
  12022. // this could be useful in Array.prototype.
  12023. function arrayEquals(array) {
  12024. // if the other array is a falsy value, return
  12025. if (!array)
  12026. return false;
  12027. // compare lengths - can save a lot of time
  12028. if (this.length != array.length)
  12029. return false;
  12030. for (var i = 0, l=this.length; i < l; i++) {
  12031. // Check if we have nested arrays
  12032. if (this[i] instanceof Array && array[i] instanceof Array) {
  12033. // recurse into the nested arrays
  12034. if (!this[i].equals(array[i]))
  12035. return false;
  12036. }
  12037. else if (this[i] != array[i]) {
  12038. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12039. return false;
  12040. }
  12041. }
  12042. return true;
  12043. }
  12044. var myMedias = this.mySDP.getMediaSsrcMap();
  12045. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12046. var newMedia = {};
  12047. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12048. var myMedia = myMedias[othersMediaIdx];
  12049. var othersMedia = othersMedias[othersMediaIdx];
  12050. if(!myMedia && othersMedia) {
  12051. // Add whole channel
  12052. newMedia[othersMediaIdx] = othersMedia;
  12053. return;
  12054. }
  12055. // Look for new ssrcs accross the channel
  12056. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12057. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12058. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12059. if(!newMedia[othersMediaIdx]){
  12060. newMedia[othersMediaIdx] = {
  12061. mediaindex: othersMedia.mediaindex,
  12062. mid: othersMedia.mid,
  12063. ssrcs: {},
  12064. ssrcGroups: []
  12065. };
  12066. }
  12067. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12068. }
  12069. });
  12070. // Look for new ssrc groups across the channels
  12071. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12072. // try to match the other ssrc-group with an ssrc-group of ours
  12073. var matched = false;
  12074. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12075. var mySsrcGroup = myMedia.ssrcGroups[i];
  12076. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12077. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12078. matched = true;
  12079. break;
  12080. }
  12081. }
  12082. if (!matched) {
  12083. // Allocate channel if we've found an ssrc-group that doesn't
  12084. // exist in our channel
  12085. if(!newMedia[othersMediaIdx]){
  12086. newMedia[othersMediaIdx] = {
  12087. mediaindex: othersMedia.mediaindex,
  12088. mid: othersMedia.mid,
  12089. ssrcs: {},
  12090. ssrcGroups: []
  12091. };
  12092. }
  12093. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12094. }
  12095. });
  12096. });
  12097. return newMedia;
  12098. };
  12099. /**
  12100. * Sends SSRC update IQ.
  12101. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12102. * @param sid session identifier that will be put into the IQ.
  12103. * @param initiator initiator identifier.
  12104. * @param toJid destination Jid
  12105. * @param isAdd indicates if this is remove or add operation.
  12106. */
  12107. SDPDiffer.prototype.toJingle = function(modify) {
  12108. var sdpMediaSsrcs = this.getNewMedia();
  12109. var self = this;
  12110. // FIXME: only announce video ssrcs since we mix audio and dont need
  12111. // the audio ssrcs therefore
  12112. var modified = false;
  12113. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12114. modified = true;
  12115. var media = sdpMediaSsrcs[mediaindex];
  12116. modify.c('content', {name: media.mid});
  12117. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12118. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12119. // generate sources from lines
  12120. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12121. var mediaSsrc = media.ssrcs[ssrcNum];
  12122. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12123. modify.attrs({ssrc: mediaSsrc.ssrc});
  12124. // iterate over ssrc lines
  12125. mediaSsrc.lines.forEach(function (line) {
  12126. var idx = line.indexOf(' ');
  12127. var kv = line.substr(idx + 1);
  12128. modify.c('parameter');
  12129. if (kv.indexOf(':') == -1) {
  12130. modify.attrs({ name: kv });
  12131. } else {
  12132. modify.attrs({ name: kv.split(':', 2)[0] });
  12133. modify.attrs({ value: kv.split(':', 2)[1] });
  12134. }
  12135. modify.up(); // end of parameter
  12136. });
  12137. modify.up(); // end of source
  12138. });
  12139. // generate source groups from lines
  12140. media.ssrcGroups.forEach(function(ssrcGroup) {
  12141. if (ssrcGroup.ssrcs.length != 0) {
  12142. modify.c('ssrc-group', {
  12143. semantics: ssrcGroup.semantics,
  12144. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12145. });
  12146. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12147. modify.c('source', { ssrc: ssrc })
  12148. .up(); // end of source
  12149. });
  12150. modify.up(); // end of ssrc-group
  12151. }
  12152. });
  12153. modify.up(); // end of description
  12154. modify.up(); // end of content
  12155. });
  12156. return modified;
  12157. };
  12158. module.exports = SDPDiffer;
  12159. },{}],50:[function(require,module,exports){
  12160. SDPUtil = {
  12161. iceparams: function (mediadesc, sessiondesc) {
  12162. var data = null;
  12163. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  12164. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  12165. data = {
  12166. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  12167. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  12168. };
  12169. }
  12170. return data;
  12171. },
  12172. parse_iceufrag: function (line) {
  12173. return line.substring(12);
  12174. },
  12175. build_iceufrag: function (frag) {
  12176. return 'a=ice-ufrag:' + frag;
  12177. },
  12178. parse_icepwd: function (line) {
  12179. return line.substring(10);
  12180. },
  12181. build_icepwd: function (pwd) {
  12182. return 'a=ice-pwd:' + pwd;
  12183. },
  12184. parse_mid: function (line) {
  12185. return line.substring(6);
  12186. },
  12187. parse_mline: function (line) {
  12188. var parts = line.substring(2).split(' '),
  12189. data = {};
  12190. data.media = parts.shift();
  12191. data.port = parts.shift();
  12192. data.proto = parts.shift();
  12193. if (parts[parts.length - 1] === '') { // trailing whitespace
  12194. parts.pop();
  12195. }
  12196. data.fmt = parts;
  12197. return data;
  12198. },
  12199. build_mline: function (mline) {
  12200. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  12201. },
  12202. parse_rtpmap: function (line) {
  12203. var parts = line.substring(9).split(' '),
  12204. data = {};
  12205. data.id = parts.shift();
  12206. parts = parts[0].split('/');
  12207. data.name = parts.shift();
  12208. data.clockrate = parts.shift();
  12209. data.channels = parts.length ? parts.shift() : '1';
  12210. return data;
  12211. },
  12212. /**
  12213. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  12214. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  12215. * @returns [SCTP port number, protocol, streams]
  12216. */
  12217. parse_sctpmap: function (line)
  12218. {
  12219. var parts = line.substring(10).split(' ');
  12220. var sctpPort = parts[0];
  12221. var protocol = parts[1];
  12222. // Stream count is optional
  12223. var streamCount = parts.length > 2 ? parts[2] : null;
  12224. return [sctpPort, protocol, streamCount];// SCTP port
  12225. },
  12226. build_rtpmap: function (el) {
  12227. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  12228. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  12229. line += '/' + el.getAttribute('channels');
  12230. }
  12231. return line;
  12232. },
  12233. parse_crypto: function (line) {
  12234. var parts = line.substring(9).split(' '),
  12235. data = {};
  12236. data.tag = parts.shift();
  12237. data['crypto-suite'] = parts.shift();
  12238. data['key-params'] = parts.shift();
  12239. if (parts.length) {
  12240. data['session-params'] = parts.join(' ');
  12241. }
  12242. return data;
  12243. },
  12244. parse_fingerprint: function (line) { // RFC 4572
  12245. var parts = line.substring(14).split(' '),
  12246. data = {};
  12247. data.hash = parts.shift();
  12248. data.fingerprint = parts.shift();
  12249. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  12250. return data;
  12251. },
  12252. parse_fmtp: function (line) {
  12253. var parts = line.split(' '),
  12254. i, key, value,
  12255. data = [];
  12256. parts.shift();
  12257. parts = parts.join(' ').split(';');
  12258. for (i = 0; i < parts.length; i++) {
  12259. key = parts[i].split('=')[0];
  12260. while (key.length && key[0] == ' ') {
  12261. key = key.substring(1);
  12262. }
  12263. value = parts[i].split('=')[1];
  12264. if (key && value) {
  12265. data.push({name: key, value: value});
  12266. } else if (key) {
  12267. // rfc 4733 (DTMF) style stuff
  12268. data.push({name: '', value: key});
  12269. }
  12270. }
  12271. return data;
  12272. },
  12273. parse_icecandidate: function (line) {
  12274. var candidate = {},
  12275. elems = line.split(' ');
  12276. candidate.foundation = elems[0].substring(12);
  12277. candidate.component = elems[1];
  12278. candidate.protocol = elems[2].toLowerCase();
  12279. candidate.priority = elems[3];
  12280. candidate.ip = elems[4];
  12281. candidate.port = elems[5];
  12282. // elems[6] => "typ"
  12283. candidate.type = elems[7];
  12284. candidate.generation = 0; // default value, may be overwritten below
  12285. for (var i = 8; i < elems.length; i += 2) {
  12286. switch (elems[i]) {
  12287. case 'raddr':
  12288. candidate['rel-addr'] = elems[i + 1];
  12289. break;
  12290. case 'rport':
  12291. candidate['rel-port'] = elems[i + 1];
  12292. break;
  12293. case 'generation':
  12294. candidate.generation = elems[i + 1];
  12295. break;
  12296. case 'tcptype':
  12297. candidate.tcptype = elems[i + 1];
  12298. break;
  12299. default: // TODO
  12300. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12301. }
  12302. }
  12303. candidate.network = '1';
  12304. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12305. return candidate;
  12306. },
  12307. build_icecandidate: function (cand) {
  12308. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  12309. line += ' ';
  12310. switch (cand.type) {
  12311. case 'srflx':
  12312. case 'prflx':
  12313. case 'relay':
  12314. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  12315. line += 'raddr';
  12316. line += ' ';
  12317. line += cand['rel-addr'];
  12318. line += ' ';
  12319. line += 'rport';
  12320. line += ' ';
  12321. line += cand['rel-port'];
  12322. line += ' ';
  12323. }
  12324. break;
  12325. }
  12326. if (cand.hasOwnAttribute('tcptype')) {
  12327. line += 'tcptype';
  12328. line += ' ';
  12329. line += cand.tcptype;
  12330. line += ' ';
  12331. }
  12332. line += 'generation';
  12333. line += ' ';
  12334. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  12335. return line;
  12336. },
  12337. parse_ssrc: function (desc) {
  12338. // proprietary mapping of a=ssrc lines
  12339. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  12340. // and parse according to that
  12341. var lines = desc.split('\r\n'),
  12342. data = {};
  12343. for (var i = 0; i < lines.length; i++) {
  12344. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  12345. var idx = lines[i].indexOf(' ');
  12346. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  12347. }
  12348. }
  12349. return data;
  12350. },
  12351. parse_rtcpfb: function (line) {
  12352. var parts = line.substr(10).split(' ');
  12353. var data = {};
  12354. data.pt = parts.shift();
  12355. data.type = parts.shift();
  12356. data.params = parts;
  12357. return data;
  12358. },
  12359. parse_extmap: function (line) {
  12360. var parts = line.substr(9).split(' ');
  12361. var data = {};
  12362. data.value = parts.shift();
  12363. if (data.value.indexOf('/') != -1) {
  12364. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  12365. data.value = data.value.substr(0, data.value.indexOf('/'));
  12366. } else {
  12367. data.direction = 'both';
  12368. }
  12369. data.uri = parts.shift();
  12370. data.params = parts;
  12371. return data;
  12372. },
  12373. find_line: function (haystack, needle, sessionpart) {
  12374. var lines = haystack.split('\r\n');
  12375. for (var i = 0; i < lines.length; i++) {
  12376. if (lines[i].substring(0, needle.length) == needle) {
  12377. return lines[i];
  12378. }
  12379. }
  12380. if (!sessionpart) {
  12381. return false;
  12382. }
  12383. // search session part
  12384. lines = sessionpart.split('\r\n');
  12385. for (var j = 0; j < lines.length; j++) {
  12386. if (lines[j].substring(0, needle.length) == needle) {
  12387. return lines[j];
  12388. }
  12389. }
  12390. return false;
  12391. },
  12392. find_lines: function (haystack, needle, sessionpart) {
  12393. var lines = haystack.split('\r\n'),
  12394. needles = [];
  12395. for (var i = 0; i < lines.length; i++) {
  12396. if (lines[i].substring(0, needle.length) == needle)
  12397. needles.push(lines[i]);
  12398. }
  12399. if (needles.length || !sessionpart) {
  12400. return needles;
  12401. }
  12402. // search session part
  12403. lines = sessionpart.split('\r\n');
  12404. for (var j = 0; j < lines.length; j++) {
  12405. if (lines[j].substring(0, needle.length) == needle) {
  12406. needles.push(lines[j]);
  12407. }
  12408. }
  12409. return needles;
  12410. },
  12411. candidateToJingle: function (line) {
  12412. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  12413. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  12414. if (line.indexOf('candidate:') === 0) {
  12415. line = 'a=' + line;
  12416. } else if (line.substring(0, 12) != 'a=candidate:') {
  12417. console.log('parseCandidate called with a line that is not a candidate line');
  12418. console.log(line);
  12419. return null;
  12420. }
  12421. if (line.substring(line.length - 2) == '\r\n') // chomp it
  12422. line = line.substring(0, line.length - 2);
  12423. var candidate = {},
  12424. elems = line.split(' '),
  12425. i;
  12426. if (elems[6] != 'typ') {
  12427. console.log('did not find typ in the right place');
  12428. console.log(line);
  12429. return null;
  12430. }
  12431. candidate.foundation = elems[0].substring(12);
  12432. candidate.component = elems[1];
  12433. candidate.protocol = elems[2].toLowerCase();
  12434. candidate.priority = elems[3];
  12435. candidate.ip = elems[4];
  12436. candidate.port = elems[5];
  12437. // elems[6] => "typ"
  12438. candidate.type = elems[7];
  12439. candidate.generation = '0'; // default, may be overwritten below
  12440. for (i = 8; i < elems.length; i += 2) {
  12441. switch (elems[i]) {
  12442. case 'raddr':
  12443. candidate['rel-addr'] = elems[i + 1];
  12444. break;
  12445. case 'rport':
  12446. candidate['rel-port'] = elems[i + 1];
  12447. break;
  12448. case 'generation':
  12449. candidate.generation = elems[i + 1];
  12450. break;
  12451. case 'tcptype':
  12452. candidate.tcptype = elems[i + 1];
  12453. break;
  12454. default: // TODO
  12455. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12456. }
  12457. }
  12458. candidate.network = '1';
  12459. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12460. return candidate;
  12461. },
  12462. candidateFromJingle: function (cand) {
  12463. var line = 'a=candidate:';
  12464. line += cand.getAttribute('foundation');
  12465. line += ' ';
  12466. line += cand.getAttribute('component');
  12467. line += ' ';
  12468. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  12469. line += ' ';
  12470. line += cand.getAttribute('priority');
  12471. line += ' ';
  12472. line += cand.getAttribute('ip');
  12473. line += ' ';
  12474. line += cand.getAttribute('port');
  12475. line += ' ';
  12476. line += 'typ';
  12477. line += ' ' + cand.getAttribute('type');
  12478. line += ' ';
  12479. switch (cand.getAttribute('type')) {
  12480. case 'srflx':
  12481. case 'prflx':
  12482. case 'relay':
  12483. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  12484. line += 'raddr';
  12485. line += ' ';
  12486. line += cand.getAttribute('rel-addr');
  12487. line += ' ';
  12488. line += 'rport';
  12489. line += ' ';
  12490. line += cand.getAttribute('rel-port');
  12491. line += ' ';
  12492. }
  12493. break;
  12494. }
  12495. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  12496. line += 'tcptype';
  12497. line += ' ';
  12498. line += cand.getAttribute('tcptype');
  12499. line += ' ';
  12500. }
  12501. line += 'generation';
  12502. line += ' ';
  12503. line += cand.getAttribute('generation') || '0';
  12504. return line + '\r\n';
  12505. }
  12506. };
  12507. module.exports = SDPUtil;
  12508. },{}],51:[function(require,module,exports){
  12509. function TraceablePeerConnection(ice_config, constraints) {
  12510. var self = this;
  12511. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  12512. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  12513. this.updateLog = [];
  12514. this.stats = {};
  12515. this.statsinterval = null;
  12516. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  12517. // override as desired
  12518. this.trace = function (what, info) {
  12519. //console.warn('WTRACE', what, info);
  12520. self.updateLog.push({
  12521. time: new Date(),
  12522. type: what,
  12523. value: info || ""
  12524. });
  12525. };
  12526. this.onicecandidate = null;
  12527. this.peerconnection.onicecandidate = function (event) {
  12528. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  12529. if (self.onicecandidate !== null) {
  12530. self.onicecandidate(event);
  12531. }
  12532. };
  12533. this.onaddstream = null;
  12534. this.peerconnection.onaddstream = function (event) {
  12535. self.trace('onaddstream', event.stream.id);
  12536. if (self.onaddstream !== null) {
  12537. self.onaddstream(event);
  12538. }
  12539. };
  12540. this.onremovestream = null;
  12541. this.peerconnection.onremovestream = function (event) {
  12542. self.trace('onremovestream', event.stream.id);
  12543. if (self.onremovestream !== null) {
  12544. self.onremovestream(event);
  12545. }
  12546. };
  12547. this.onsignalingstatechange = null;
  12548. this.peerconnection.onsignalingstatechange = function (event) {
  12549. self.trace('onsignalingstatechange', self.signalingState);
  12550. if (self.onsignalingstatechange !== null) {
  12551. self.onsignalingstatechange(event);
  12552. }
  12553. };
  12554. this.oniceconnectionstatechange = null;
  12555. this.peerconnection.oniceconnectionstatechange = function (event) {
  12556. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12557. if (self.oniceconnectionstatechange !== null) {
  12558. self.oniceconnectionstatechange(event);
  12559. }
  12560. };
  12561. this.onnegotiationneeded = null;
  12562. this.peerconnection.onnegotiationneeded = function (event) {
  12563. self.trace('onnegotiationneeded');
  12564. if (self.onnegotiationneeded !== null) {
  12565. self.onnegotiationneeded(event);
  12566. }
  12567. };
  12568. self.ondatachannel = null;
  12569. this.peerconnection.ondatachannel = function (event) {
  12570. self.trace('ondatachannel', event);
  12571. if (self.ondatachannel !== null) {
  12572. self.ondatachannel(event);
  12573. }
  12574. };
  12575. if (!navigator.mozGetUserMedia && this.maxstats) {
  12576. this.statsinterval = window.setInterval(function() {
  12577. self.peerconnection.getStats(function(stats) {
  12578. var results = stats.result();
  12579. for (var i = 0; i < results.length; ++i) {
  12580. //console.log(results[i].type, results[i].id, results[i].names())
  12581. var now = new Date();
  12582. results[i].names().forEach(function (name) {
  12583. var id = results[i].id + '-' + name;
  12584. if (!self.stats[id]) {
  12585. self.stats[id] = {
  12586. startTime: now,
  12587. endTime: now,
  12588. values: [],
  12589. times: []
  12590. };
  12591. }
  12592. self.stats[id].values.push(results[i].stat(name));
  12593. self.stats[id].times.push(now.getTime());
  12594. if (self.stats[id].values.length > self.maxstats) {
  12595. self.stats[id].values.shift();
  12596. self.stats[id].times.shift();
  12597. }
  12598. self.stats[id].endTime = now;
  12599. });
  12600. }
  12601. });
  12602. }, 1000);
  12603. }
  12604. };
  12605. dumpSDP = function(description) {
  12606. return 'type: ' + description.type + '\r\n' + description.sdp;
  12607. }
  12608. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  12609. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  12610. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  12611. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  12612. var publicLocalDescription = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  12613. return publicLocalDescription;
  12614. });
  12615. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  12616. var publicRemoteDescription = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  12617. return publicRemoteDescription;
  12618. });
  12619. }
  12620. TraceablePeerConnection.prototype.addStream = function (stream) {
  12621. this.trace('addStream', stream.id);
  12622. APP.simulcast.resetSender();
  12623. try
  12624. {
  12625. this.peerconnection.addStream(stream);
  12626. }
  12627. catch (e)
  12628. {
  12629. console.error(e);
  12630. return;
  12631. }
  12632. };
  12633. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  12634. this.trace('removeStream', stream.id);
  12635. APP.simulcast.resetSender();
  12636. if(stopStreams) {
  12637. stream.getAudioTracks().forEach(function (track) {
  12638. track.stop();
  12639. });
  12640. stream.getVideoTracks().forEach(function (track) {
  12641. track.stop();
  12642. });
  12643. }
  12644. this.peerconnection.removeStream(stream);
  12645. };
  12646. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  12647. this.trace('createDataChannel', label, opts);
  12648. return this.peerconnection.createDataChannel(label, opts);
  12649. };
  12650. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  12651. var self = this;
  12652. description = APP.simulcast.transformLocalDescription(description);
  12653. this.trace('setLocalDescription', dumpSDP(description));
  12654. this.peerconnection.setLocalDescription(description,
  12655. function () {
  12656. self.trace('setLocalDescriptionOnSuccess');
  12657. successCallback();
  12658. },
  12659. function (err) {
  12660. self.trace('setLocalDescriptionOnFailure', err);
  12661. failureCallback(err);
  12662. }
  12663. );
  12664. /*
  12665. if (this.statsinterval === null && this.maxstats > 0) {
  12666. // start gathering stats
  12667. }
  12668. */
  12669. };
  12670. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  12671. var self = this;
  12672. description = APP.simulcast.transformRemoteDescription(description);
  12673. this.trace('setRemoteDescription', dumpSDP(description));
  12674. this.peerconnection.setRemoteDescription(description,
  12675. function () {
  12676. self.trace('setRemoteDescriptionOnSuccess');
  12677. successCallback();
  12678. },
  12679. function (err) {
  12680. self.trace('setRemoteDescriptionOnFailure', err);
  12681. failureCallback(err);
  12682. }
  12683. );
  12684. /*
  12685. if (this.statsinterval === null && this.maxstats > 0) {
  12686. // start gathering stats
  12687. }
  12688. */
  12689. };
  12690. TraceablePeerConnection.prototype.close = function () {
  12691. this.trace('stop');
  12692. if (this.statsinterval !== null) {
  12693. window.clearInterval(this.statsinterval);
  12694. this.statsinterval = null;
  12695. }
  12696. this.peerconnection.close();
  12697. };
  12698. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  12699. var self = this;
  12700. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  12701. this.peerconnection.createOffer(
  12702. function (offer) {
  12703. self.trace('createOfferOnSuccess', dumpSDP(offer));
  12704. successCallback(offer);
  12705. },
  12706. function(err) {
  12707. self.trace('createOfferOnFailure', err);
  12708. failureCallback(err);
  12709. },
  12710. constraints
  12711. );
  12712. };
  12713. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  12714. var self = this;
  12715. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  12716. this.peerconnection.createAnswer(
  12717. function (answer) {
  12718. answer = APP.simulcast.transformAnswer(answer);
  12719. self.trace('createAnswerOnSuccess', dumpSDP(answer));
  12720. successCallback(answer);
  12721. },
  12722. function(err) {
  12723. self.trace('createAnswerOnFailure', err);
  12724. failureCallback(err);
  12725. },
  12726. constraints
  12727. );
  12728. };
  12729. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  12730. var self = this;
  12731. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  12732. this.peerconnection.addIceCandidate(candidate);
  12733. /* maybe later
  12734. this.peerconnection.addIceCandidate(candidate,
  12735. function () {
  12736. self.trace('addIceCandidateOnSuccess');
  12737. successCallback();
  12738. },
  12739. function (err) {
  12740. self.trace('addIceCandidateOnFailure', err);
  12741. failureCallback(err);
  12742. }
  12743. );
  12744. */
  12745. };
  12746. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  12747. if (navigator.mozGetUserMedia) {
  12748. // ignore for now...
  12749. if(!errback)
  12750. errback = function () {
  12751. }
  12752. this.peerconnection.getStats(null,callback,errback);
  12753. } else {
  12754. this.peerconnection.getStats(callback);
  12755. }
  12756. };
  12757. module.exports = TraceablePeerConnection;
  12758. },{}],52:[function(require,module,exports){
  12759. /* global $, $iq, APP, config, connection, UI, messageHandler,
  12760. roomName, sessionTerminated, Strophe, Util */
  12761. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  12762. var Settings = require("../settings/Settings");
  12763. var AuthenticationEvents
  12764. = require("../../service/authentication/AuthenticationEvents");
  12765. /**
  12766. * Contains logic responsible for enabling/disabling functionality available
  12767. * only to moderator users.
  12768. */
  12769. var connection = null;
  12770. var focusUserJid;
  12771. function createExpBackoffTimer(step) {
  12772. var count = 1;
  12773. return function (reset) {
  12774. // Reset call
  12775. if (reset) {
  12776. count = 1;
  12777. return;
  12778. }
  12779. // Calculate next timeout
  12780. var timeout = Math.pow(2, count - 1);
  12781. count += 1;
  12782. return timeout * step;
  12783. };
  12784. }
  12785. var getNextTimeout = createExpBackoffTimer(1000);
  12786. var getNextErrorTimeout = createExpBackoffTimer(1000);
  12787. // External authentication stuff
  12788. var externalAuthEnabled = false;
  12789. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  12790. // it will be enabled automatically if focus detects the component through
  12791. // service discovery.
  12792. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  12793. var eventEmitter = null;
  12794. var Moderator = {
  12795. isModerator: function () {
  12796. return connection && connection.emuc.isModerator();
  12797. },
  12798. isPeerModerator: function (peerJid) {
  12799. return connection &&
  12800. connection.emuc.getMemberRole(peerJid) === 'moderator';
  12801. },
  12802. isExternalAuthEnabled: function () {
  12803. return externalAuthEnabled;
  12804. },
  12805. isSipGatewayEnabled: function () {
  12806. return sipGatewayEnabled;
  12807. },
  12808. setConnection: function (con) {
  12809. connection = con;
  12810. },
  12811. init: function (xmpp, emitter) {
  12812. this.xmppService = xmpp;
  12813. eventEmitter = emitter;
  12814. // Message listener that talks to POPUP window
  12815. function listener(event) {
  12816. if (event.data && event.data.sessionId) {
  12817. if (event.origin !== window.location.origin) {
  12818. console.warn(
  12819. "Ignoring sessionId from different origin: " + event.origin);
  12820. return;
  12821. }
  12822. localStorage.setItem('sessionId', event.data.sessionId);
  12823. // After popup is closed we will authenticate
  12824. }
  12825. }
  12826. // Register
  12827. if (window.addEventListener) {
  12828. window.addEventListener("message", listener, false);
  12829. } else {
  12830. window.attachEvent("onmessage", listener);
  12831. }
  12832. },
  12833. onMucLeft: function (jid) {
  12834. console.info("Someone left is it focus ? " + jid);
  12835. var resource = Strophe.getResourceFromJid(jid);
  12836. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  12837. console.info(
  12838. "Focus has left the room - leaving conference");
  12839. //hangUp();
  12840. // We'd rather reload to have everything re-initialized
  12841. // FIXME: show some message before reload
  12842. location.reload();
  12843. }
  12844. },
  12845. setFocusUserJid: function (focusJid) {
  12846. if (!focusUserJid) {
  12847. focusUserJid = focusJid;
  12848. console.info("Focus jid set to: " + focusUserJid);
  12849. }
  12850. },
  12851. getFocusUserJid: function () {
  12852. return focusUserJid;
  12853. },
  12854. getFocusComponent: function () {
  12855. // Get focus component address
  12856. var focusComponent = config.hosts.focus;
  12857. // If not specified use default: 'focus.domain'
  12858. if (!focusComponent) {
  12859. focusComponent = 'focus.' + config.hosts.domain;
  12860. }
  12861. return focusComponent;
  12862. },
  12863. createConferenceIq: function (roomName) {
  12864. // Generate create conference IQ
  12865. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  12866. // Session Id used for authentication
  12867. var sessionId = localStorage.getItem('sessionId');
  12868. var machineUID = Settings.getSettings().uid;
  12869. console.info(
  12870. "Session ID: " + sessionId + " machine UID: " + machineUID);
  12871. elem.c('conference', {
  12872. xmlns: 'http://jitsi.org/protocol/focus',
  12873. room: roomName,
  12874. 'machine-uid': machineUID
  12875. });
  12876. if (sessionId) {
  12877. elem.attrs({ 'session-id': sessionId});
  12878. }
  12879. if (config.hosts.bridge !== undefined) {
  12880. elem.c(
  12881. 'property',
  12882. { name: 'bridge', value: config.hosts.bridge})
  12883. .up();
  12884. }
  12885. // Tell the focus we have Jigasi configured
  12886. if (config.hosts.call_control !== undefined) {
  12887. elem.c(
  12888. 'property',
  12889. { name: 'call_control', value: config.hosts.call_control})
  12890. .up();
  12891. }
  12892. if (config.channelLastN !== undefined) {
  12893. elem.c(
  12894. 'property',
  12895. { name: 'channelLastN', value: config.channelLastN})
  12896. .up();
  12897. }
  12898. if (config.adaptiveLastN !== undefined) {
  12899. elem.c(
  12900. 'property',
  12901. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  12902. .up();
  12903. }
  12904. if (config.adaptiveSimulcast !== undefined) {
  12905. elem.c(
  12906. 'property',
  12907. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  12908. .up();
  12909. }
  12910. if (config.openSctp !== undefined) {
  12911. elem.c(
  12912. 'property',
  12913. { name: 'openSctp', value: config.openSctp})
  12914. .up();
  12915. }
  12916. if (config.enableFirefoxSupport !== undefined) {
  12917. elem.c(
  12918. 'property',
  12919. { name: 'enableFirefoxHacks',
  12920. value: config.enableFirefoxSupport})
  12921. .up();
  12922. }
  12923. elem.up();
  12924. return elem;
  12925. },
  12926. parseConfigOptions: function (resultIq) {
  12927. Moderator.setFocusUserJid(
  12928. $(resultIq).find('conference').attr('focusjid'));
  12929. var authenticationEnabled
  12930. = $(resultIq).find(
  12931. '>conference>property' +
  12932. '[name=\'authentication\'][value=\'true\']').length > 0;
  12933. console.info("Authentication enabled: " + authenticationEnabled);
  12934. externalAuthEnabled
  12935. = $(resultIq).find(
  12936. '>conference>property' +
  12937. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  12938. console.info('External authentication enabled: ' + externalAuthEnabled);
  12939. if (!externalAuthEnabled) {
  12940. // We expect to receive sessionId in 'internal' authentication mode
  12941. var sessionId
  12942. = $(resultIq).find('conference').attr('session-id');
  12943. if (sessionId) {
  12944. console.info('Received sessionId: ' + sessionId);
  12945. localStorage.setItem('sessionId', sessionId);
  12946. }
  12947. }
  12948. var authIdentity = $(resultIq).find('>conference').attr('identity');
  12949. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  12950. authenticationEnabled, authIdentity);
  12951. // Check if focus has auto-detected Jigasi component(this will be also
  12952. // included if we have passed our host from the config)
  12953. if ($(resultIq).find(
  12954. '>conference>property' +
  12955. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  12956. sipGatewayEnabled = true;
  12957. }
  12958. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  12959. },
  12960. // FIXME: we need to show the fact that we're waiting for the focus
  12961. // to the user(or that focus is not available)
  12962. allocateConferenceFocus: function (roomName, callback) {
  12963. // Try to use focus user JID from the config
  12964. Moderator.setFocusUserJid(config.focusUserJid);
  12965. // Send create conference IQ
  12966. var iq = Moderator.createConferenceIq(roomName);
  12967. var self = this;
  12968. connection.sendIQ(
  12969. iq,
  12970. function (result) {
  12971. // Setup config options
  12972. Moderator.parseConfigOptions(result);
  12973. if ('true' === $(result).find('conference').attr('ready')) {
  12974. // Reset both timers
  12975. getNextTimeout(true);
  12976. getNextErrorTimeout(true);
  12977. // Exec callback
  12978. callback();
  12979. } else {
  12980. var waitMs = getNextTimeout();
  12981. console.info("Waiting for the focus... " + waitMs);
  12982. // Reset error timeout
  12983. getNextErrorTimeout(true);
  12984. window.setTimeout(
  12985. function () {
  12986. Moderator.allocateConferenceFocus(
  12987. roomName, callback);
  12988. }, waitMs);
  12989. }
  12990. },
  12991. function (error) {
  12992. // Invalid session ? remove and try again
  12993. // without session ID to get a new one
  12994. var invalidSession
  12995. = $(error).find('>error>session-invalid').length;
  12996. if (invalidSession) {
  12997. console.info("Session expired! - removing");
  12998. localStorage.removeItem("sessionId");
  12999. }
  13000. // Not authorized to create new room
  13001. if ($(error).find('>error>not-authorized').length) {
  13002. console.warn("Unauthorized to start the conference", error);
  13003. var toDomain
  13004. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13005. if (toDomain === config.hosts.anonymousdomain) {
  13006. // we are connected with anonymous domain and
  13007. // only non anonymous users can create rooms
  13008. // we must authorize the user
  13009. self.xmppService.promptLogin();
  13010. } else {
  13011. // External authentication mode
  13012. eventEmitter.emit(
  13013. XMPPEvents.AUTHENTICATION_REQUIRED,
  13014. function () {
  13015. Moderator.allocateConferenceFocus(
  13016. roomName, callback);
  13017. });
  13018. }
  13019. return;
  13020. }
  13021. var waitMs = getNextErrorTimeout();
  13022. console.error("Focus error, retry after " + waitMs, error);
  13023. // Show message
  13024. var focusComponent = Moderator.getFocusComponent();
  13025. var retrySec = waitMs / 1000;
  13026. // FIXME: message is duplicated ?
  13027. // Do not show in case of session invalid
  13028. // which means just a retry
  13029. if (!invalidSession) {
  13030. APP.UI.messageHandler.notify(
  13031. null, "notify.focus",
  13032. 'Conference focus', 'disconnected', "notify.focusFail",
  13033. focusComponent + " not available - retry in " +
  13034. retrySec + " sec",
  13035. {component: focusComponent, ms: retrySec});
  13036. }
  13037. // Reset response timeout
  13038. getNextTimeout(true);
  13039. window.setTimeout(
  13040. function () {
  13041. Moderator.allocateConferenceFocus(roomName, callback);
  13042. }, waitMs);
  13043. }
  13044. );
  13045. },
  13046. getLoginUrl: function (roomName, urlCallback) {
  13047. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13048. iq.c('login-url', {
  13049. xmlns: 'http://jitsi.org/protocol/focus',
  13050. room: roomName,
  13051. 'machine-uid': Settings.getSettings().uid
  13052. });
  13053. connection.sendIQ(
  13054. iq,
  13055. function (result) {
  13056. var url = $(result).find('login-url').attr('url');
  13057. url = url = decodeURIComponent(url);
  13058. if (url) {
  13059. console.info("Got auth url: " + url);
  13060. urlCallback(url);
  13061. } else {
  13062. console.error(
  13063. "Failed to get auth url from the focus", result);
  13064. }
  13065. },
  13066. function (error) {
  13067. console.error("Get auth url error", error);
  13068. }
  13069. );
  13070. },
  13071. getPopupLoginUrl: function (roomName, urlCallback) {
  13072. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13073. iq.c('login-url', {
  13074. xmlns: 'http://jitsi.org/protocol/focus',
  13075. room: roomName,
  13076. 'machine-uid': Settings.getSettings().uid,
  13077. popup: true
  13078. });
  13079. connection.sendIQ(
  13080. iq,
  13081. function (result) {
  13082. var url = $(result).find('login-url').attr('url');
  13083. url = url = decodeURIComponent(url);
  13084. if (url) {
  13085. console.info("Got POPUP auth url: " + url);
  13086. urlCallback(url);
  13087. } else {
  13088. console.error(
  13089. "Failed to get POPUP auth url from the focus", result);
  13090. }
  13091. },
  13092. function (error) {
  13093. console.error('Get POPUP auth url error', error);
  13094. }
  13095. );
  13096. },
  13097. logout: function (callback) {
  13098. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13099. var sessionId = localStorage.getItem('sessionId');
  13100. if (!sessionId) {
  13101. callback();
  13102. return;
  13103. }
  13104. iq.c('logout', {
  13105. xmlns: 'http://jitsi.org/protocol/focus',
  13106. 'session-id': sessionId
  13107. });
  13108. connection.sendIQ(
  13109. iq,
  13110. function (result) {
  13111. var logoutUrl = $(result).find('logout').attr('logout-url');
  13112. if (logoutUrl) {
  13113. logoutUrl = decodeURIComponent(logoutUrl);
  13114. }
  13115. console.info("Log out OK, url: " + logoutUrl, result);
  13116. localStorage.removeItem('sessionId');
  13117. callback(logoutUrl);
  13118. },
  13119. function (error) {
  13120. console.error("Logout error", error);
  13121. }
  13122. );
  13123. }
  13124. };
  13125. module.exports = Moderator;
  13126. },{"../../service/authentication/AuthenticationEvents":84,"../../service/xmpp/XMPPEvents":88,"../settings/Settings":37}],53:[function(require,module,exports){
  13127. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  13128. Toolbar, Util */
  13129. var Moderator = require("./moderator");
  13130. var recordingToken = null;
  13131. var recordingEnabled;
  13132. /**
  13133. * Whether to use a jirecon component for recording, or use the videobridge
  13134. * through COLIBRI.
  13135. */
  13136. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  13137. /**
  13138. * The ID of the jirecon recording session. Jirecon generates it when we
  13139. * initially start recording, and it needs to be used in subsequent requests
  13140. * to jirecon.
  13141. */
  13142. var jireconRid = null;
  13143. function setRecordingToken(token) {
  13144. recordingToken = token;
  13145. }
  13146. function setRecording(state, token, callback, connection) {
  13147. if (useJirecon){
  13148. setRecordingJirecon(state, token, callback, connection);
  13149. } else {
  13150. setRecordingColibri(state, token, callback, connection);
  13151. }
  13152. }
  13153. function setRecordingJirecon(state, token, callback, connection) {
  13154. if (state == recordingEnabled){
  13155. return;
  13156. }
  13157. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  13158. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  13159. action: state ? 'start' : 'stop',
  13160. mucjid: connection.emuc.roomjid});
  13161. if (!state){
  13162. iq.attrs({rid: jireconRid});
  13163. }
  13164. console.log('Start recording');
  13165. connection.sendIQ(
  13166. iq,
  13167. function (result) {
  13168. // TODO wait for an IQ with the real status, since this is
  13169. // provisional?
  13170. jireconRid = $(result).find('recording').attr('rid');
  13171. console.log('Recording ' + (state ? 'started' : 'stopped') +
  13172. '(jirecon)' + result);
  13173. recordingEnabled = state;
  13174. if (!state){
  13175. jireconRid = null;
  13176. }
  13177. callback(state);
  13178. },
  13179. function (error) {
  13180. console.log('Failed to start recording, error: ', error);
  13181. callback(recordingEnabled);
  13182. });
  13183. }
  13184. // Sends a COLIBRI message which enables or disables (according to 'state')
  13185. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  13186. // with the new recording state, according to the IQ.
  13187. function setRecordingColibri(state, token, callback, connection) {
  13188. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  13189. elem.c('conference', {
  13190. xmlns: 'http://jitsi.org/protocol/colibri'
  13191. });
  13192. elem.c('recording', {state: state, token: token});
  13193. connection.sendIQ(elem,
  13194. function (result) {
  13195. console.log('Set recording "', state, '". Result:', result);
  13196. var recordingElem = $(result).find('>conference>recording');
  13197. var newState = ('true' === recordingElem.attr('state'));
  13198. recordingEnabled = newState;
  13199. callback(newState);
  13200. },
  13201. function (error) {
  13202. console.warn(error);
  13203. callback(recordingEnabled);
  13204. }
  13205. );
  13206. }
  13207. var Recording = {
  13208. toggleRecording: function (tokenEmptyCallback,
  13209. startingCallback, startedCallback, connection) {
  13210. if (!Moderator.isModerator()) {
  13211. console.log(
  13212. 'non-focus, or conference not yet organized:' +
  13213. ' not enabling recording');
  13214. return;
  13215. }
  13216. var self = this;
  13217. // Jirecon does not (currently) support a token.
  13218. if (!recordingToken && !useJirecon) {
  13219. tokenEmptyCallback(function (value) {
  13220. setRecordingToken(value);
  13221. self.toggleRecording(tokenEmptyCallback,
  13222. startingCallback, startedCallback, connection);
  13223. });
  13224. return;
  13225. }
  13226. var oldState = recordingEnabled;
  13227. startingCallback(!oldState);
  13228. setRecording(!oldState,
  13229. recordingToken,
  13230. function (state) {
  13231. console.log("New recording state: ", state);
  13232. if (state === oldState) {
  13233. // FIXME: new focus:
  13234. // this will not work when moderator changes
  13235. // during active session. Then it will assume that
  13236. // recording status has changed to true, but it might have
  13237. // been already true(and we only received actual status from
  13238. // the focus).
  13239. //
  13240. // SO we start with status null, so that it is initialized
  13241. // here and will fail only after second click, so if invalid
  13242. // token was used we have to press the button twice before
  13243. // current status will be fetched and token will be reset.
  13244. //
  13245. // Reliable way would be to return authentication error.
  13246. // Or status update when moderator connects.
  13247. // Or we have to stop recording session when current
  13248. // moderator leaves the room.
  13249. // Failed to change, reset the token because it might
  13250. // have been wrong
  13251. setRecordingToken(null);
  13252. }
  13253. startedCallback(state);
  13254. },
  13255. connection
  13256. );
  13257. }
  13258. }
  13259. module.exports = Recording;
  13260. },{"./moderator":52}],54:[function(require,module,exports){
  13261. /* jshint -W117 */
  13262. /* a simple MUC connection plugin
  13263. * can only handle a single MUC room
  13264. */
  13265. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13266. var Moderator = require("./moderator");
  13267. var JingleSession = require("./JingleSession");
  13268. var bridgeIsDown = false;
  13269. module.exports = function(XMPP, eventEmitter) {
  13270. Strophe.addConnectionPlugin('emuc', {
  13271. connection: null,
  13272. roomjid: null,
  13273. myroomjid: null,
  13274. members: {},
  13275. list_members: [], // so we can elect a new focus
  13276. presMap: {},
  13277. preziMap: {},
  13278. joined: false,
  13279. isOwner: false,
  13280. role: null,
  13281. focusMucJid: null,
  13282. ssrc2jid: {},
  13283. init: function (conn) {
  13284. this.connection = conn;
  13285. },
  13286. initPresenceMap: function (myroomjid) {
  13287. this.presMap['to'] = myroomjid;
  13288. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  13289. },
  13290. doJoin: function (jid, password) {
  13291. this.myroomjid = jid;
  13292. console.info("Joined MUC as " + this.myroomjid);
  13293. this.initPresenceMap(this.myroomjid);
  13294. if (!this.roomjid) {
  13295. this.roomjid = Strophe.getBareJidFromJid(jid);
  13296. // add handlers (just once)
  13297. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  13298. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  13299. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  13300. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  13301. }
  13302. if (password !== undefined) {
  13303. this.presMap['password'] = password;
  13304. }
  13305. this.sendPresence();
  13306. },
  13307. doLeave: function () {
  13308. console.log("do leave", this.myroomjid);
  13309. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  13310. this.presMap.length = 0;
  13311. this.connection.send(pres);
  13312. },
  13313. createNonAnonymousRoom: function () {
  13314. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  13315. var getForm = $iq({type: 'get', to: this.roomjid})
  13316. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  13317. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13318. var self = this;
  13319. this.connection.sendIQ(getForm, function (form) {
  13320. if (!$(form).find(
  13321. '>query>x[xmlns="jabber:x:data"]' +
  13322. '>field[var="muc#roomconfig_whois"]').length) {
  13323. console.error('non-anonymous rooms not supported');
  13324. return;
  13325. }
  13326. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  13327. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13328. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13329. formSubmit.c('field', {'var': 'FORM_TYPE'})
  13330. .c('value')
  13331. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13332. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  13333. .c('value').t('anyone').up().up();
  13334. self.connection.sendIQ(formSubmit);
  13335. }, function (error) {
  13336. console.error("Error getting room configuration form");
  13337. });
  13338. },
  13339. onPresence: function (pres) {
  13340. var from = pres.getAttribute('from');
  13341. // What is this for? A workaround for something?
  13342. if (pres.getAttribute('type')) {
  13343. return true;
  13344. }
  13345. // Parse etherpad tag.
  13346. var etherpad = $(pres).find('>etherpad');
  13347. if (etherpad.length) {
  13348. if (config.etherpad_base && !Moderator.isModerator()) {
  13349. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  13350. }
  13351. }
  13352. // Parse prezi tag.
  13353. var presentation = $(pres).find('>prezi');
  13354. if (presentation.length) {
  13355. var url = presentation.attr('url');
  13356. var current = presentation.find('>current').text();
  13357. console.log('presentation info received from', from, url);
  13358. if (this.preziMap[from] == null) {
  13359. this.preziMap[from] = url;
  13360. $(document).trigger('presentationadded.muc', [from, url, current]);
  13361. }
  13362. else {
  13363. $(document).trigger('gotoslide.muc', [from, url, current]);
  13364. }
  13365. }
  13366. else if (this.preziMap[from] != null) {
  13367. var url = this.preziMap[from];
  13368. delete this.preziMap[from];
  13369. $(document).trigger('presentationremoved.muc', [from, url]);
  13370. }
  13371. // Parse audio info tag.
  13372. var audioMuted = $(pres).find('>audiomuted');
  13373. if (audioMuted.length) {
  13374. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  13375. }
  13376. // Parse video info tag.
  13377. var videoMuted = $(pres).find('>videomuted');
  13378. if (videoMuted.length) {
  13379. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  13380. }
  13381. var stats = $(pres).find('>stats');
  13382. if (stats.length) {
  13383. var statsObj = {};
  13384. Strophe.forEachChild(stats[0], "stat", function (el) {
  13385. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  13386. });
  13387. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  13388. }
  13389. // Parse status.
  13390. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  13391. this.isOwner = true;
  13392. this.createNonAnonymousRoom();
  13393. }
  13394. // Parse roles.
  13395. var member = {};
  13396. member.show = $(pres).find('>show').text();
  13397. member.status = $(pres).find('>status').text();
  13398. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  13399. member.affiliation = tmp.attr('affiliation');
  13400. member.role = tmp.attr('role');
  13401. // Focus recognition
  13402. member.jid = tmp.attr('jid');
  13403. member.isFocus = false;
  13404. if (member.jid
  13405. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  13406. member.isFocus = true;
  13407. }
  13408. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  13409. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  13410. if (from == this.myroomjid) {
  13411. if (member.affiliation == 'owner') this.isOwner = true;
  13412. if (this.role !== member.role) {
  13413. this.role = member.role;
  13414. eventEmitter.emit(XMPPEvents.LOCALROLE_CHANGED,
  13415. from, member, pres, Moderator.isModerator());
  13416. }
  13417. if (!this.joined) {
  13418. this.joined = true;
  13419. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  13420. this.list_members.push(from);
  13421. }
  13422. } else if (this.members[from] === undefined) {
  13423. // new participant
  13424. this.members[from] = member;
  13425. this.list_members.push(from);
  13426. console.log('entered', from, member);
  13427. if (member.isFocus) {
  13428. this.focusMucJid = from;
  13429. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  13430. }
  13431. else {
  13432. var id = $(pres).find('>userID').text();
  13433. var email = $(pres).find('>email');
  13434. if (email.length > 0) {
  13435. id = email.text();
  13436. }
  13437. eventEmitter.emit(XMPPEvents.MUC_ENTER, from, id, member.displayName);
  13438. }
  13439. } else {
  13440. // Presence update for existing participant
  13441. // Watch role change:
  13442. if (this.members[from].role != member.role) {
  13443. this.members[from].role = member.role;
  13444. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  13445. member.role, member.displayName);
  13446. }
  13447. }
  13448. // Always trigger presence to update bindings
  13449. this.parsePresence(from, member, pres);
  13450. // Trigger status message update
  13451. if (member.status) {
  13452. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  13453. }
  13454. return true;
  13455. },
  13456. onPresenceUnavailable: function (pres) {
  13457. var from = pres.getAttribute('from');
  13458. // room destroyed ?
  13459. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13460. '>destroy').length) {
  13461. var reason;
  13462. var reasonSelect = $(pres).find(
  13463. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13464. '>destroy>reason');
  13465. if (reasonSelect.length) {
  13466. reason = reasonSelect.text();
  13467. }
  13468. XMPP.disposeConference(false);
  13469. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  13470. return true;
  13471. }
  13472. // Status code 110 indicates that this notification is "self-presence".
  13473. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  13474. delete this.members[from];
  13475. this.list_members.splice(this.list_members.indexOf(from), 1);
  13476. this.onParticipantLeft(from);
  13477. }
  13478. // If the status code is 110 this means we're leaving and we would like
  13479. // to remove everyone else from our view, so we trigger the event.
  13480. else if (this.list_members.length > 1) {
  13481. for (var i = 0; i < this.list_members.length; i++) {
  13482. var member = this.list_members[i];
  13483. delete this.members[i];
  13484. this.list_members.splice(i, 1);
  13485. this.onParticipantLeft(member);
  13486. }
  13487. }
  13488. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  13489. $(document).trigger('kicked.muc', [from]);
  13490. if (this.myroomjid === from) {
  13491. XMPP.disposeConference(false);
  13492. eventEmitter.emit(XMPPEvents.KICKED);
  13493. }
  13494. }
  13495. return true;
  13496. },
  13497. onPresenceError: function (pres) {
  13498. var from = pres.getAttribute('from');
  13499. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13500. console.log('on password required', from);
  13501. var self = this;
  13502. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  13503. self.doJoin(from, value);
  13504. });
  13505. } else if ($(pres).find(
  13506. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13507. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  13508. if (toDomain === config.hosts.anonymousdomain) {
  13509. // enter the room by replying with 'not-authorized'. This would
  13510. // result in reconnection from authorized domain.
  13511. // We're either missing Jicofo/Prosody config for anonymous
  13512. // domains or something is wrong.
  13513. // XMPP.promptLogin();
  13514. APP.UI.messageHandler.openReportDialog(null, null,
  13515. "dialog.joinError",
  13516. 'Oops ! We couldn`t join the conference.' +
  13517. ' There might be some problem with security' +
  13518. ' configuration. Please contact service' +
  13519. ' administrator.', pres);
  13520. } else {
  13521. console.warn('onPresError ', pres);
  13522. APP.UI.messageHandler.openReportDialog(null, null,
  13523. "dialog.connectError",
  13524. 'Oops! Something went wrong and we couldn`t ' +
  13525. 'connect to the conference.',
  13526. pres);
  13527. }
  13528. } else {
  13529. console.warn('onPresError ', pres);
  13530. APP.UI.messageHandler.openReportDialog(null, null,
  13531. "dialog.connectError",
  13532. 'Oops! Something went wrong and we couldn`t ' +
  13533. 'connect to the conference.',
  13534. pres);
  13535. }
  13536. return true;
  13537. },
  13538. sendMessage: function (body, nickname) {
  13539. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13540. msg.c('body', body).up();
  13541. if (nickname) {
  13542. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  13543. }
  13544. this.connection.send(msg);
  13545. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  13546. },
  13547. setSubject: function (subject) {
  13548. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13549. msg.c('subject', subject);
  13550. this.connection.send(msg);
  13551. console.log("topic changed to " + subject);
  13552. },
  13553. onMessage: function (msg) {
  13554. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  13555. var from = msg.getAttribute('from');
  13556. var nick =
  13557. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  13558. .text() ||
  13559. Strophe.getResourceFromJid(from);
  13560. var txt = $(msg).find('>body').text();
  13561. var type = msg.getAttribute("type");
  13562. if (type == "error") {
  13563. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  13564. $(msg).find('>text').text(), txt);
  13565. return true;
  13566. }
  13567. var subject = $(msg).find('>subject');
  13568. if (subject.length) {
  13569. var subjectText = subject.text();
  13570. if (subjectText || subjectText == "") {
  13571. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  13572. console.log("Subject is changed to " + subjectText);
  13573. }
  13574. }
  13575. if (txt) {
  13576. console.log('chat', nick, txt);
  13577. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  13578. from, nick, txt, this.myroomjid);
  13579. }
  13580. return true;
  13581. },
  13582. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  13583. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  13584. var ob = this;
  13585. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  13586. function (res) {
  13587. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  13588. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13589. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13590. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13591. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  13592. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  13593. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  13594. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  13595. ob.connection.sendIQ(formsubmit,
  13596. onSuccess,
  13597. onError);
  13598. } else {
  13599. onNotSupported();
  13600. }
  13601. }, onError);
  13602. },
  13603. kick: function (jid) {
  13604. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  13605. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  13606. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  13607. .c('reason').t('You have been kicked.').up().up().up();
  13608. this.connection.sendIQ(
  13609. kickIQ,
  13610. function (result) {
  13611. console.log('Kick participant with jid: ', jid, result);
  13612. },
  13613. function (error) {
  13614. console.log('Kick participant error: ', error);
  13615. });
  13616. },
  13617. sendPresence: function () {
  13618. var pres = $pres({to: this.presMap['to'] });
  13619. pres.c('x', {xmlns: this.presMap['xns']});
  13620. if (this.presMap['password']) {
  13621. pres.c('password').t(this.presMap['password']).up();
  13622. }
  13623. pres.up();
  13624. // Send XEP-0115 'c' stanza that contains our capabilities info
  13625. if (this.connection.caps) {
  13626. this.connection.caps.node = config.clientNode;
  13627. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  13628. }
  13629. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  13630. .t(navigator.userAgent).up();
  13631. if (this.presMap['bridgeIsDown']) {
  13632. pres.c('bridgeIsDown').up();
  13633. }
  13634. if (this.presMap['email']) {
  13635. pres.c('email').t(this.presMap['email']).up();
  13636. }
  13637. if (this.presMap['userId']) {
  13638. pres.c('userId').t(this.presMap['userId']).up();
  13639. }
  13640. if (this.presMap['displayName']) {
  13641. // XEP-0172
  13642. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  13643. .t(this.presMap['displayName']).up();
  13644. }
  13645. if (this.presMap['audions']) {
  13646. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  13647. .t(this.presMap['audiomuted']).up();
  13648. }
  13649. if (this.presMap['videons']) {
  13650. pres.c('videomuted', {xmlns: this.presMap['videons']})
  13651. .t(this.presMap['videomuted']).up();
  13652. }
  13653. if (this.presMap['statsns']) {
  13654. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  13655. for (var stat in this.presMap["stats"])
  13656. if (this.presMap["stats"][stat] != null)
  13657. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  13658. pres.up();
  13659. }
  13660. if (this.presMap['prezins']) {
  13661. pres.c('prezi',
  13662. {xmlns: this.presMap['prezins'],
  13663. 'url': this.presMap['preziurl']})
  13664. .c('current').t(this.presMap['prezicurrent']).up().up();
  13665. }
  13666. if (this.presMap['etherpadns']) {
  13667. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  13668. .t(this.presMap['etherpadname']).up();
  13669. }
  13670. if (this.presMap['medians']) {
  13671. pres.c('media', {xmlns: this.presMap['medians']});
  13672. var sourceNumber = 0;
  13673. Object.keys(this.presMap).forEach(function (key) {
  13674. if (key.indexOf('source') >= 0) {
  13675. sourceNumber++;
  13676. }
  13677. });
  13678. if (sourceNumber > 0)
  13679. for (var i = 1; i <= sourceNumber / 3; i++) {
  13680. pres.c('source',
  13681. {type: this.presMap['source' + i + '_type'],
  13682. ssrc: this.presMap['source' + i + '_ssrc'],
  13683. direction: this.presMap['source' + i + '_direction']
  13684. || 'sendrecv' }
  13685. ).up();
  13686. }
  13687. }
  13688. pres.up();
  13689. this.connection.send(pres);
  13690. },
  13691. addDisplayNameToPresence: function (displayName) {
  13692. this.presMap['displayName'] = displayName;
  13693. },
  13694. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  13695. if (!this.presMap['medians'])
  13696. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  13697. this.presMap['source' + sourceNumber + '_type'] = mtype;
  13698. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  13699. this.presMap['source' + sourceNumber + '_direction'] = direction;
  13700. },
  13701. clearPresenceMedia: function () {
  13702. var self = this;
  13703. Object.keys(this.presMap).forEach(function (key) {
  13704. if (key.indexOf('source') != -1) {
  13705. delete self.presMap[key];
  13706. }
  13707. });
  13708. },
  13709. addPreziToPresence: function (url, currentSlide) {
  13710. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  13711. this.presMap['preziurl'] = url;
  13712. this.presMap['prezicurrent'] = currentSlide;
  13713. },
  13714. removePreziFromPresence: function () {
  13715. delete this.presMap['prezins'];
  13716. delete this.presMap['preziurl'];
  13717. delete this.presMap['prezicurrent'];
  13718. },
  13719. addCurrentSlideToPresence: function (currentSlide) {
  13720. this.presMap['prezicurrent'] = currentSlide;
  13721. },
  13722. getPrezi: function (roomjid) {
  13723. return this.preziMap[roomjid];
  13724. },
  13725. addEtherpadToPresence: function (etherpadName) {
  13726. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  13727. this.presMap['etherpadname'] = etherpadName;
  13728. },
  13729. addAudioInfoToPresence: function (isMuted) {
  13730. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  13731. this.presMap['audiomuted'] = isMuted.toString();
  13732. },
  13733. addVideoInfoToPresence: function (isMuted) {
  13734. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  13735. this.presMap['videomuted'] = isMuted.toString();
  13736. },
  13737. addConnectionInfoToPresence: function (stats) {
  13738. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  13739. this.presMap['stats'] = stats;
  13740. },
  13741. findJidFromResource: function (resourceJid) {
  13742. if (resourceJid &&
  13743. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  13744. return this.myroomjid;
  13745. }
  13746. var peerJid = null;
  13747. Object.keys(this.members).some(function (jid) {
  13748. peerJid = jid;
  13749. return Strophe.getResourceFromJid(jid) === resourceJid;
  13750. });
  13751. return peerJid;
  13752. },
  13753. addBridgeIsDownToPresence: function () {
  13754. this.presMap['bridgeIsDown'] = true;
  13755. },
  13756. addEmailToPresence: function (email) {
  13757. this.presMap['email'] = email;
  13758. },
  13759. addUserIdToPresence: function (userId) {
  13760. this.presMap['userId'] = userId;
  13761. },
  13762. isModerator: function () {
  13763. return this.role === 'moderator';
  13764. },
  13765. getMemberRole: function (peerJid) {
  13766. if (this.members[peerJid]) {
  13767. return this.members[peerJid].role;
  13768. }
  13769. return null;
  13770. },
  13771. onParticipantLeft: function (jid) {
  13772. eventEmitter.emit(XMPPEvents.MUC_LEFT, jid);
  13773. this.connection.jingle.terminateByJid(jid);
  13774. if (this.getPrezi(jid)) {
  13775. $(document).trigger('presentationremoved.muc',
  13776. [jid, this.getPrezi(jid)]);
  13777. }
  13778. Moderator.onMucLeft(jid);
  13779. },
  13780. parsePresence: function (from, memeber, pres) {
  13781. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  13782. bridgeIsDown = true;
  13783. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  13784. }
  13785. if(memeber.isFocus)
  13786. return;
  13787. var self = this;
  13788. // Remove old ssrcs coming from the jid
  13789. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  13790. if (self.ssrc2jid[ssrc] == from) {
  13791. delete self.ssrc2jid[ssrc];
  13792. }
  13793. });
  13794. var changedStreams = [];
  13795. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  13796. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  13797. var ssrcV = ssrc.getAttribute('ssrc');
  13798. self.ssrc2jid[ssrcV] = from;
  13799. JingleSession.notReceivedSSRCs.push(ssrcV);
  13800. var type = ssrc.getAttribute('type');
  13801. var direction = ssrc.getAttribute('direction');
  13802. changedStreams.push({type: type, direction: direction});
  13803. });
  13804. eventEmitter.emit(XMPPEvents.CHANGED_STREAMS, from, changedStreams);
  13805. var displayName = !config.displayJids
  13806. ? memeber.displayName : Strophe.getResourceFromJid(from);
  13807. if (displayName && displayName.length > 0)
  13808. {
  13809. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  13810. }
  13811. var id = $(pres).find('>userID').text();
  13812. var email = $(pres).find('>email');
  13813. if(email.length > 0) {
  13814. id = email.text();
  13815. }
  13816. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  13817. }
  13818. });
  13819. };
  13820. },{"../../service/xmpp/XMPPEvents":88,"./JingleSession":47,"./moderator":52}],55:[function(require,module,exports){
  13821. /* jshint -W117 */
  13822. var JingleSession = require("./JingleSession");
  13823. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13824. module.exports = function(XMPP, eventEmitter)
  13825. {
  13826. function CallIncomingJingle(sid, connection) {
  13827. var sess = connection.jingle.sessions[sid];
  13828. // TODO: do we check activecall == null?
  13829. connection.jingle.activecall = sess;
  13830. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  13831. // TODO: check affiliation and/or role
  13832. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  13833. sess.usedrip = true; // not-so-naive trickle ice
  13834. sess.sendAnswer();
  13835. sess.accept();
  13836. };
  13837. Strophe.addConnectionPlugin('jingle', {
  13838. connection: null,
  13839. sessions: {},
  13840. jid2session: {},
  13841. ice_config: {iceServers: []},
  13842. pc_constraints: {},
  13843. activecall: null,
  13844. media_constraints: {
  13845. mandatory: {
  13846. 'OfferToReceiveAudio': true,
  13847. 'OfferToReceiveVideo': true
  13848. }
  13849. // MozDontOfferDataChannel: true when this is firefox
  13850. },
  13851. init: function (conn) {
  13852. this.connection = conn;
  13853. if (this.connection.disco) {
  13854. // http://xmpp.org/extensions/xep-0167.html#support
  13855. // http://xmpp.org/extensions/xep-0176.html#support
  13856. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  13857. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  13858. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  13859. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  13860. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  13861. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  13862. // this is dealt with by SDP O/A so we don't need to annouce this
  13863. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  13864. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  13865. if (config.useRtcpMux) {
  13866. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  13867. }
  13868. if (config.useBundle) {
  13869. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  13870. }
  13871. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  13872. }
  13873. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  13874. },
  13875. onJingle: function (iq) {
  13876. var sid = $(iq).find('jingle').attr('sid');
  13877. var action = $(iq).find('jingle').attr('action');
  13878. var fromJid = iq.getAttribute('from');
  13879. // send ack first
  13880. var ack = $iq({type: 'result',
  13881. to: fromJid,
  13882. id: iq.getAttribute('id')
  13883. });
  13884. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  13885. var sess = this.sessions[sid];
  13886. if ('session-initiate' != action) {
  13887. if (sess === null) {
  13888. ack.type = 'error';
  13889. ack.c('error', {type: 'cancel'})
  13890. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  13891. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  13892. this.connection.send(ack);
  13893. return true;
  13894. }
  13895. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  13896. // local jid is not checked
  13897. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  13898. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  13899. ack.type = 'error';
  13900. ack.c('error', {type: 'cancel'})
  13901. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  13902. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  13903. this.connection.send(ack);
  13904. return true;
  13905. }
  13906. } else if (sess !== undefined) {
  13907. // existing session with same session id
  13908. // this might be out-of-order if the sess.peerjid is the same as from
  13909. ack.type = 'error';
  13910. ack.c('error', {type: 'cancel'})
  13911. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  13912. console.warn('duplicate session id', sid);
  13913. this.connection.send(ack);
  13914. return true;
  13915. }
  13916. // FIXME: check for a defined action
  13917. this.connection.send(ack);
  13918. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  13919. switch (action) {
  13920. case 'session-initiate':
  13921. sess = new JingleSession(
  13922. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  13923. this.connection, XMPP);
  13924. // configure session
  13925. sess.media_constraints = this.media_constraints;
  13926. sess.pc_constraints = this.pc_constraints;
  13927. sess.ice_config = this.ice_config;
  13928. sess.initiate(fromJid, false);
  13929. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  13930. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  13931. this.sessions[sess.sid] = sess;
  13932. this.jid2session[sess.peerjid] = sess;
  13933. // the callback should either
  13934. // .sendAnswer and .accept
  13935. // or .sendTerminate -- not necessarily synchronus
  13936. CallIncomingJingle(sess.sid, this.connection);
  13937. break;
  13938. case 'session-accept':
  13939. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  13940. sess.accept();
  13941. $(document).trigger('callaccepted.jingle', [sess.sid]);
  13942. break;
  13943. case 'session-terminate':
  13944. // If this is not the focus sending the terminate, we have
  13945. // nothing more to do here.
  13946. if (Object.keys(this.sessions).length < 1
  13947. || !(this.sessions[Object.keys(this.sessions)[0]]
  13948. instanceof JingleSession))
  13949. {
  13950. break;
  13951. }
  13952. console.log('terminating...', sess.sid);
  13953. sess.terminate();
  13954. this.terminate(sess.sid);
  13955. if ($(iq).find('>jingle>reason').length) {
  13956. $(document).trigger('callterminated.jingle', [
  13957. sess.sid,
  13958. sess.peerjid,
  13959. $(iq).find('>jingle>reason>:first')[0].tagName,
  13960. $(iq).find('>jingle>reason>text').text()
  13961. ]);
  13962. } else {
  13963. $(document).trigger('callterminated.jingle',
  13964. [sess.sid, sess.peerjid]);
  13965. }
  13966. break;
  13967. case 'transport-info':
  13968. sess.addIceCandidate($(iq).find('>jingle>content'));
  13969. break;
  13970. case 'session-info':
  13971. var affected;
  13972. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  13973. $(document).trigger('ringing.jingle', [sess.sid]);
  13974. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  13975. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  13976. $(document).trigger('mute.jingle', [sess.sid, affected]);
  13977. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  13978. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  13979. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  13980. }
  13981. break;
  13982. case 'addsource': // FIXME: proprietary, un-jingleish
  13983. case 'source-add': // FIXME: proprietary
  13984. sess.addSource($(iq).find('>jingle>content'), fromJid);
  13985. break;
  13986. case 'removesource': // FIXME: proprietary, un-jingleish
  13987. case 'source-remove': // FIXME: proprietary
  13988. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  13989. break;
  13990. default:
  13991. console.warn('jingle action not implemented', action);
  13992. break;
  13993. }
  13994. return true;
  13995. },
  13996. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  13997. var sess = new JingleSession(myjid || this.connection.jid,
  13998. Math.random().toString(36).substr(2, 12), // random string
  13999. this.connection, XMPP);
  14000. // configure session
  14001. sess.media_constraints = this.media_constraints;
  14002. sess.pc_constraints = this.pc_constraints;
  14003. sess.ice_config = this.ice_config;
  14004. sess.initiate(peerjid, true);
  14005. this.sessions[sess.sid] = sess;
  14006. this.jid2session[sess.peerjid] = sess;
  14007. sess.sendOffer();
  14008. return sess;
  14009. },
  14010. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  14011. if (sid === null || sid === undefined) {
  14012. for (sid in this.sessions) {
  14013. if (this.sessions[sid].state != 'ended') {
  14014. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14015. this.sessions[sid].terminate();
  14016. }
  14017. delete this.jid2session[this.sessions[sid].peerjid];
  14018. delete this.sessions[sid];
  14019. }
  14020. } else if (this.sessions.hasOwnProperty(sid)) {
  14021. if (this.sessions[sid].state != 'ended') {
  14022. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14023. this.sessions[sid].terminate();
  14024. }
  14025. delete this.jid2session[this.sessions[sid].peerjid];
  14026. delete this.sessions[sid];
  14027. }
  14028. },
  14029. // Used to terminate a session when an unavailable presence is received.
  14030. terminateByJid: function (jid) {
  14031. if (this.jid2session.hasOwnProperty(jid)) {
  14032. var sess = this.jid2session[jid];
  14033. if (sess) {
  14034. sess.terminate();
  14035. console.log('peer went away silently', jid);
  14036. delete this.sessions[sess.sid];
  14037. delete this.jid2session[jid];
  14038. $(document).trigger('callterminated.jingle',
  14039. [sess.sid, jid], 'gone');
  14040. }
  14041. }
  14042. },
  14043. terminateRemoteByJid: function (jid, reason) {
  14044. if (this.jid2session.hasOwnProperty(jid)) {
  14045. var sess = this.jid2session[jid];
  14046. if (sess) {
  14047. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  14048. sess.terminate();
  14049. console.log('terminate peer with jid', sess.sid, jid);
  14050. delete this.sessions[sess.sid];
  14051. delete this.jid2session[jid];
  14052. $(document).trigger('callterminated.jingle',
  14053. [sess.sid, jid, 'kicked']);
  14054. }
  14055. }
  14056. },
  14057. getStunAndTurnCredentials: function () {
  14058. // get stun and turn configuration from server via xep-0215
  14059. // uses time-limited credentials as described in
  14060. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  14061. //
  14062. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  14063. // for a prosody module which implements this
  14064. //
  14065. // currently, this doesn't work with updateIce and therefore credentials with a long
  14066. // validity have to be fetched before creating the peerconnection
  14067. // TODO: implement refresh via updateIce as described in
  14068. // https://code.google.com/p/webrtc/issues/detail?id=1650
  14069. var self = this;
  14070. this.connection.sendIQ(
  14071. $iq({type: 'get', to: this.connection.domain})
  14072. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  14073. function (res) {
  14074. var iceservers = [];
  14075. $(res).find('>services>service').each(function (idx, el) {
  14076. el = $(el);
  14077. var dict = {};
  14078. var type = el.attr('type');
  14079. switch (type) {
  14080. case 'stun':
  14081. dict.url = 'stun:' + el.attr('host');
  14082. if (el.attr('port')) {
  14083. dict.url += ':' + el.attr('port');
  14084. }
  14085. iceservers.push(dict);
  14086. break;
  14087. case 'turn':
  14088. case 'turns':
  14089. dict.url = type + ':';
  14090. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  14091. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  14092. dict.url += el.attr('username') + '@';
  14093. } else {
  14094. dict.username = el.attr('username'); // only works in M28
  14095. }
  14096. }
  14097. dict.url += el.attr('host');
  14098. if (el.attr('port') && el.attr('port') != '3478') {
  14099. dict.url += ':' + el.attr('port');
  14100. }
  14101. if (el.attr('transport') && el.attr('transport') != 'udp') {
  14102. dict.url += '?transport=' + el.attr('transport');
  14103. }
  14104. if (el.attr('password')) {
  14105. dict.credential = el.attr('password');
  14106. }
  14107. iceservers.push(dict);
  14108. break;
  14109. }
  14110. });
  14111. self.ice_config.iceServers = iceservers;
  14112. },
  14113. function (err) {
  14114. console.warn('getting turn credentials failed', err);
  14115. console.warn('is mod_turncredentials or similar installed?');
  14116. }
  14117. );
  14118. // implement push?
  14119. },
  14120. /**
  14121. * Populates the log data
  14122. */
  14123. populateData: function () {
  14124. var data = {};
  14125. Object.keys(this.sessions).forEach(function (sid) {
  14126. var session = this.sessions[sid];
  14127. if (session.peerconnection && session.peerconnection.updateLog) {
  14128. // FIXME: should probably be a .dump call
  14129. data["jingle_" + session.sid] = {
  14130. updateLog: session.peerconnection.updateLog,
  14131. stats: session.peerconnection.stats,
  14132. url: window.location.href
  14133. };
  14134. }
  14135. });
  14136. return data;
  14137. }
  14138. });
  14139. };
  14140. },{"../../service/xmpp/XMPPEvents":88,"./JingleSession":47}],56:[function(require,module,exports){
  14141. /* global Strophe */
  14142. module.exports = function () {
  14143. Strophe.addConnectionPlugin('logger', {
  14144. // logs raw stanzas and makes them available for download as JSON
  14145. connection: null,
  14146. log: [],
  14147. init: function (conn) {
  14148. this.connection = conn;
  14149. this.connection.rawInput = this.log_incoming.bind(this);
  14150. this.connection.rawOutput = this.log_outgoing.bind(this);
  14151. },
  14152. log_incoming: function (stanza) {
  14153. this.log.push([new Date().getTime(), 'incoming', stanza]);
  14154. },
  14155. log_outgoing: function (stanza) {
  14156. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  14157. }
  14158. });
  14159. };
  14160. },{}],57:[function(require,module,exports){
  14161. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  14162. setAudioMuted, Strophe */
  14163. /**
  14164. * Moderate connection plugin.
  14165. */
  14166. module.exports = function (XMPP) {
  14167. Strophe.addConnectionPlugin('moderate', {
  14168. connection: null,
  14169. init: function (conn) {
  14170. this.connection = conn;
  14171. this.connection.addHandler(this.onMute.bind(this),
  14172. 'http://jitsi.org/jitmeet/audio',
  14173. 'iq',
  14174. 'set',
  14175. null,
  14176. null);
  14177. },
  14178. setMute: function (jid, mute) {
  14179. console.info("set mute", mute);
  14180. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  14181. .c('mute', {
  14182. xmlns: 'http://jitsi.org/jitmeet/audio',
  14183. jid: jid
  14184. })
  14185. .t(mute.toString())
  14186. .up();
  14187. this.connection.sendIQ(
  14188. iqToFocus,
  14189. function (result) {
  14190. console.log('set mute', result);
  14191. },
  14192. function (error) {
  14193. console.log('set mute error', error);
  14194. });
  14195. },
  14196. onMute: function (iq) {
  14197. var from = iq.getAttribute('from');
  14198. if (from !== this.connection.emuc.focusMucJid) {
  14199. console.warn("Ignored mute from non focus peer");
  14200. return false;
  14201. }
  14202. var mute = $(iq).find('mute');
  14203. if (mute.length) {
  14204. var doMuteAudio = mute.text() === "true";
  14205. APP.UI.setAudioMuted(doMuteAudio);
  14206. XMPP.forceMuted = doMuteAudio;
  14207. }
  14208. return true;
  14209. },
  14210. eject: function (jid) {
  14211. // We're not the focus, so can't terminate
  14212. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  14213. this.connection.emuc.kick(jid);
  14214. }
  14215. });
  14216. }
  14217. },{}],58:[function(require,module,exports){
  14218. /* jshint -W117 */
  14219. module.exports = function() {
  14220. Strophe.addConnectionPlugin('rayo',
  14221. {
  14222. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  14223. connection: null,
  14224. init: function (conn) {
  14225. this.connection = conn;
  14226. if (this.connection.disco) {
  14227. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  14228. }
  14229. this.connection.addHandler(
  14230. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  14231. },
  14232. onRayo: function (iq) {
  14233. console.info("Rayo IQ", iq);
  14234. },
  14235. dial: function (to, from, roomName, roomPass) {
  14236. var self = this;
  14237. var req = $iq(
  14238. {
  14239. type: 'set',
  14240. to: this.connection.emuc.focusMucJid
  14241. }
  14242. );
  14243. req.c('dial',
  14244. {
  14245. xmlns: this.RAYO_XMLNS,
  14246. to: to,
  14247. from: from
  14248. });
  14249. req.c('header',
  14250. {
  14251. name: 'JvbRoomName',
  14252. value: roomName
  14253. }).up();
  14254. if (roomPass !== null && roomPass.length) {
  14255. req.c('header',
  14256. {
  14257. name: 'JvbRoomPassword',
  14258. value: roomPass
  14259. }).up();
  14260. }
  14261. this.connection.sendIQ(
  14262. req,
  14263. function (result) {
  14264. console.info('Dial result ', result);
  14265. var resource = $(result).find('ref').attr('uri');
  14266. this.call_resource = resource.substr('xmpp:'.length);
  14267. console.info(
  14268. "Received call resource: " + this.call_resource);
  14269. },
  14270. function (error) {
  14271. console.info('Dial error ', error);
  14272. }
  14273. );
  14274. },
  14275. hang_up: function () {
  14276. if (!this.call_resource) {
  14277. console.warn("No call in progress");
  14278. return;
  14279. }
  14280. var self = this;
  14281. var req = $iq(
  14282. {
  14283. type: 'set',
  14284. to: this.call_resource
  14285. }
  14286. );
  14287. req.c('hangup',
  14288. {
  14289. xmlns: this.RAYO_XMLNS
  14290. });
  14291. this.connection.sendIQ(
  14292. req,
  14293. function (result) {
  14294. console.info('Hangup result ', result);
  14295. self.call_resource = null;
  14296. },
  14297. function (error) {
  14298. console.info('Hangup error ', error);
  14299. self.call_resource = null;
  14300. }
  14301. );
  14302. }
  14303. }
  14304. );
  14305. };
  14306. },{}],59:[function(require,module,exports){
  14307. /**
  14308. * Strophe logger implementation. Logs from level WARN and above.
  14309. */
  14310. module.exports = function () {
  14311. Strophe.log = function (level, msg) {
  14312. switch (level) {
  14313. case Strophe.LogLevel.WARN:
  14314. console.warn("Strophe: " + msg);
  14315. break;
  14316. case Strophe.LogLevel.ERROR:
  14317. case Strophe.LogLevel.FATAL:
  14318. console.error("Strophe: " + msg);
  14319. break;
  14320. }
  14321. };
  14322. Strophe.getStatusString = function (status) {
  14323. switch (status) {
  14324. case Strophe.Status.ERROR:
  14325. return "ERROR";
  14326. case Strophe.Status.CONNECTING:
  14327. return "CONNECTING";
  14328. case Strophe.Status.CONNFAIL:
  14329. return "CONNFAIL";
  14330. case Strophe.Status.AUTHENTICATING:
  14331. return "AUTHENTICATING";
  14332. case Strophe.Status.AUTHFAIL:
  14333. return "AUTHFAIL";
  14334. case Strophe.Status.CONNECTED:
  14335. return "CONNECTED";
  14336. case Strophe.Status.DISCONNECTED:
  14337. return "DISCONNECTED";
  14338. case Strophe.Status.DISCONNECTING:
  14339. return "DISCONNECTING";
  14340. case Strophe.Status.ATTACHED:
  14341. return "ATTACHED";
  14342. default:
  14343. return "unknown";
  14344. }
  14345. };
  14346. };
  14347. },{}],60:[function(require,module,exports){
  14348. var Moderator = require("./moderator");
  14349. var EventEmitter = require("events");
  14350. var Recording = require("./recording");
  14351. var SDP = require("./SDP");
  14352. var Pako = require("pako");
  14353. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  14354. var UIEvents = require("../../service/UI/UIEvents");
  14355. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14356. var eventEmitter = new EventEmitter();
  14357. var connection = null;
  14358. var authenticatedUser = false;
  14359. function connect(jid, password, uiCredentials) {
  14360. var bosh
  14361. = (uiCredentials && uiCredentials.bosh? uiCredentials.bosh : null)
  14362. || config.bosh || '/http-bind';
  14363. connection = new Strophe.Connection(bosh);
  14364. Moderator.setConnection(connection);
  14365. if(uiCredentials) {
  14366. var email = uiCredentials.email;
  14367. var displayName = uiCredentials.displayName;
  14368. if (email) {
  14369. connection.emuc.addEmailToPresence(email);
  14370. } else {
  14371. connection.emuc.addUserIdToPresence(uiCredentials.uid);
  14372. }
  14373. if (displayName) {
  14374. connection.emuc.addDisplayNameToPresence(displayName);
  14375. }
  14376. }
  14377. if (connection.disco) {
  14378. // for chrome, add multistream cap
  14379. }
  14380. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  14381. if (config.useIPv6) {
  14382. // https://code.google.com/p/webrtc/issues/detail?id=2828
  14383. if (!connection.jingle.pc_constraints.optional)
  14384. connection.jingle.pc_constraints.optional = [];
  14385. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  14386. }
  14387. if(!password)
  14388. password = uiCredentials.password;
  14389. var anonymousConnectionFailed = false;
  14390. connection.connect(jid, password, function (status, msg) {
  14391. console.log('Strophe status changed to',
  14392. Strophe.getStatusString(status));
  14393. if (status === Strophe.Status.CONNECTED) {
  14394. if (config.useStunTurn) {
  14395. connection.jingle.getStunAndTurnCredentials();
  14396. }
  14397. APP.UI.disableConnect();
  14398. console.info("My Jabber ID: " + connection.jid);
  14399. if(password)
  14400. authenticatedUser = true;
  14401. maybeDoJoin();
  14402. } else if (status === Strophe.Status.CONNFAIL) {
  14403. if(msg === 'x-strophe-bad-non-anon-jid') {
  14404. anonymousConnectionFailed = true;
  14405. }
  14406. } else if (status === Strophe.Status.DISCONNECTED) {
  14407. if(anonymousConnectionFailed) {
  14408. // prompt user for username and password
  14409. XMPP.promptLogin();
  14410. }
  14411. } else if (status === Strophe.Status.AUTHFAIL) {
  14412. // wrong password or username, prompt user
  14413. XMPP.promptLogin();
  14414. }
  14415. });
  14416. }
  14417. function maybeDoJoin() {
  14418. if (connection && connection.connected &&
  14419. Strophe.getResourceFromJid(connection.jid)
  14420. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  14421. // .connected is true while connecting?
  14422. doJoin();
  14423. }
  14424. }
  14425. function doJoin() {
  14426. var roomName = APP.UI.generateRoomName();
  14427. Moderator.allocateConferenceFocus(
  14428. roomName, APP.UI.checkForNicknameAndJoin);
  14429. }
  14430. function initStrophePlugins()
  14431. {
  14432. require("./strophe.emuc")(XMPP, eventEmitter);
  14433. require("./strophe.jingle")(XMPP, eventEmitter);
  14434. require("./strophe.moderate")(XMPP);
  14435. require("./strophe.util")();
  14436. require("./strophe.rayo")();
  14437. require("./strophe.logger")();
  14438. }
  14439. function registerListeners() {
  14440. APP.RTC.addStreamListener(maybeDoJoin,
  14441. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  14442. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  14443. XMPP.addToPresence("displayName", nickname);
  14444. });
  14445. }
  14446. function setupEvents() {
  14447. $(window).bind('beforeunload', function () {
  14448. if (connection && connection.connected) {
  14449. // ensure signout
  14450. $.ajax({
  14451. type: 'POST',
  14452. url: config.bosh,
  14453. async: false,
  14454. cache: false,
  14455. contentType: 'application/xml',
  14456. data: "<body rid='" + (connection.rid || connection._proto.rid)
  14457. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  14458. + (connection.sid || connection._proto.sid)
  14459. + "' type='terminate'>" +
  14460. "<presence xmlns='jabber:client' type='unavailable'/>" +
  14461. "</body>",
  14462. success: function (data) {
  14463. console.log('signed out');
  14464. console.log(data);
  14465. },
  14466. error: function (XMLHttpRequest, textStatus, errorThrown) {
  14467. console.log('signout error',
  14468. textStatus + ' (' + errorThrown + ')');
  14469. }
  14470. });
  14471. }
  14472. XMPP.disposeConference(true);
  14473. });
  14474. }
  14475. var XMPP = {
  14476. sessionTerminated: false,
  14477. /**
  14478. * Remembers if we were muted by the focus.
  14479. * @type {boolean}
  14480. */
  14481. forceMuted: false,
  14482. start: function (uiCredentials) {
  14483. setupEvents();
  14484. initStrophePlugins();
  14485. registerListeners();
  14486. Moderator.init(this, eventEmitter);
  14487. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  14488. // Force authenticated domain if room is appended with '?login=true'
  14489. if (config.hosts.anonymousdomain &&
  14490. window.location.search.indexOf("login=true") !== -1) {
  14491. configDomain = config.hosts.domain;
  14492. }
  14493. var jid = uiCredentials.jid || configDomain || window.location.hostname;
  14494. connect(jid, null, uiCredentials);
  14495. },
  14496. promptLogin: function () {
  14497. APP.UI.showLoginPopup(connect);
  14498. },
  14499. joinRoom: function(roomName, useNicks, nick)
  14500. {
  14501. var roomjid;
  14502. roomjid = roomName;
  14503. if (useNicks) {
  14504. if (nick) {
  14505. roomjid += '/' + nick;
  14506. } else {
  14507. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  14508. }
  14509. } else {
  14510. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  14511. if(!authenticatedUser)
  14512. tmpJid = tmpJid.substr(0, 8);
  14513. roomjid += '/' + tmpJid;
  14514. }
  14515. connection.emuc.doJoin(roomjid);
  14516. },
  14517. myJid: function () {
  14518. if(!connection)
  14519. return null;
  14520. return connection.emuc.myroomjid;
  14521. },
  14522. myResource: function () {
  14523. if(!connection || ! connection.emuc.myroomjid)
  14524. return null;
  14525. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  14526. },
  14527. disposeConference: function (onUnload) {
  14528. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  14529. var handler = connection.jingle.activecall;
  14530. if (handler && handler.peerconnection) {
  14531. // FIXME: probably removing streams is not required and close() should
  14532. // be enough
  14533. if (APP.RTC.localAudio) {
  14534. handler.peerconnection.removeStream(APP.RTC.localAudio.getOriginalStream(), onUnload);
  14535. }
  14536. if (APP.RTC.localVideo) {
  14537. handler.peerconnection.removeStream(APP.RTC.localVideo.getOriginalStream(), onUnload);
  14538. }
  14539. handler.peerconnection.close();
  14540. }
  14541. connection.jingle.activecall = null;
  14542. if(!onUnload)
  14543. {
  14544. this.sessionTerminated = true;
  14545. connection.emuc.doLeave();
  14546. }
  14547. },
  14548. addListener: function(type, listener)
  14549. {
  14550. eventEmitter.on(type, listener);
  14551. },
  14552. removeListener: function (type, listener) {
  14553. eventEmitter.removeListener(type, listener);
  14554. },
  14555. allocateConferenceFocus: function(roomName, callback) {
  14556. Moderator.allocateConferenceFocus(roomName, callback);
  14557. },
  14558. getLoginUrl: function (roomName, callback) {
  14559. Moderator.getLoginUrl(roomName, callback);
  14560. },
  14561. getPopupLoginUrl: function (roomName, callback) {
  14562. Moderator.getPopupLoginUrl(roomName, callback);
  14563. },
  14564. isModerator: function () {
  14565. return Moderator.isModerator();
  14566. },
  14567. isSipGatewayEnabled: function () {
  14568. return Moderator.isSipGatewayEnabled();
  14569. },
  14570. isExternalAuthEnabled: function () {
  14571. return Moderator.isExternalAuthEnabled();
  14572. },
  14573. switchStreams: function (stream, oldStream, callback) {
  14574. if (connection && connection.jingle.activecall) {
  14575. // FIXME: will block switchInProgress on true value in case of exception
  14576. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  14577. } else {
  14578. // We are done immediately
  14579. console.error("No conference handler");
  14580. APP.UI.messageHandler.showError("dialog.error", 'Error',
  14581. "dialog.unableToSwitch", 'Unable to switch video stream.');
  14582. callback();
  14583. }
  14584. },
  14585. setVideoMute: function (mute, callback, options) {
  14586. if(connection && APP.RTC.localVideo && connection.jingle.activecall)
  14587. {
  14588. connection.jingle.activecall.setVideoMute(mute, callback, options);
  14589. }
  14590. },
  14591. setAudioMute: function (mute, callback) {
  14592. if (!(connection && APP.RTC.localAudio)) {
  14593. return false;
  14594. }
  14595. if (this.forceMuted && !mute) {
  14596. console.info("Asking focus for unmute");
  14597. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  14598. // FIXME: wait for result before resetting muted status
  14599. this.forceMuted = false;
  14600. }
  14601. if (mute == APP.RTC.localAudio.isMuted()) {
  14602. // Nothing to do
  14603. return true;
  14604. }
  14605. // It is not clear what is the right way to handle multiple tracks.
  14606. // So at least make sure that they are all muted or all unmuted and
  14607. // that we send presence just once.
  14608. APP.RTC.localAudio.mute();
  14609. // isMuted is the opposite of audioEnabled
  14610. connection.emuc.addAudioInfoToPresence(mute);
  14611. connection.emuc.sendPresence();
  14612. callback();
  14613. return true;
  14614. },
  14615. // Really mute video, i.e. dont even send black frames
  14616. muteVideo: function (pc, unmute) {
  14617. // FIXME: this probably needs another of those lovely state safeguards...
  14618. // which checks for iceconn == connected and sigstate == stable
  14619. pc.setRemoteDescription(pc.remoteDescription,
  14620. function () {
  14621. pc.createAnswer(
  14622. function (answer) {
  14623. var sdp = new SDP(answer.sdp);
  14624. if (sdp.media.length > 1) {
  14625. if (unmute)
  14626. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  14627. else
  14628. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  14629. sdp.raw = sdp.session + sdp.media.join('');
  14630. answer.sdp = sdp.raw;
  14631. }
  14632. pc.setLocalDescription(answer,
  14633. function () {
  14634. console.log('mute SLD ok');
  14635. },
  14636. function (error) {
  14637. console.log('mute SLD error');
  14638. APP.UI.messageHandler.showError("dialog.error",
  14639. 'Error', "dialog.SLDFailure",
  14640. 'Oops! Something went wrong and we failed to ' +
  14641. 'mute! (SLD Failure)');
  14642. }
  14643. );
  14644. },
  14645. function (error) {
  14646. console.log(error);
  14647. APP.UI.messageHandler.showError();
  14648. }
  14649. );
  14650. },
  14651. function (error) {
  14652. console.log('muteVideo SRD error');
  14653. APP.UI.messageHandler.showError("dialog.error", 'Error',
  14654. "dialog.SRDFailure",
  14655. 'Oops! Something went wrong and we failed to stop video!' +
  14656. '(SRD Failure)');
  14657. }
  14658. );
  14659. },
  14660. toggleRecording: function (tokenEmptyCallback,
  14661. startingCallback, startedCallback) {
  14662. Recording.toggleRecording(tokenEmptyCallback,
  14663. startingCallback, startedCallback, connection);
  14664. },
  14665. addToPresence: function (name, value, dontSend) {
  14666. switch (name)
  14667. {
  14668. case "displayName":
  14669. connection.emuc.addDisplayNameToPresence(value);
  14670. break;
  14671. case "etherpad":
  14672. connection.emuc.addEtherpadToPresence(value);
  14673. break;
  14674. case "prezi":
  14675. connection.emuc.addPreziToPresence(value, 0);
  14676. break;
  14677. case "preziSlide":
  14678. connection.emuc.addCurrentSlideToPresence(value);
  14679. break;
  14680. case "connectionQuality":
  14681. connection.emuc.addConnectionInfoToPresence(value);
  14682. break;
  14683. case "email":
  14684. connection.emuc.addEmailToPresence(value);
  14685. default :
  14686. console.log("Unknown tag for presence.");
  14687. return;
  14688. }
  14689. if(!dontSend)
  14690. connection.emuc.sendPresence();
  14691. },
  14692. sendLogs: function (data) {
  14693. if(!connection.emuc.focusMucJid)
  14694. return;
  14695. var deflate = true;
  14696. var content = JSON.stringify(data);
  14697. if (deflate) {
  14698. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  14699. }
  14700. content = Base64.encode(content);
  14701. // XEP-0337-ish
  14702. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  14703. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  14704. id: 'PeerConnectionStats'});
  14705. message.c('message').t(content).up();
  14706. if (deflate) {
  14707. message.c('tag', {name: "deflated", value: "true"}).up();
  14708. }
  14709. message.up();
  14710. connection.send(message);
  14711. },
  14712. populateData: function () {
  14713. var data = {};
  14714. if (connection.jingle) {
  14715. data = connection.jingle.populateData();
  14716. }
  14717. return data;
  14718. },
  14719. getLogger: function () {
  14720. if(connection.logger)
  14721. return connection.logger.log;
  14722. return null;
  14723. },
  14724. getPrezi: function () {
  14725. return connection.emuc.getPrezi(this.myJid());
  14726. },
  14727. removePreziFromPresence: function () {
  14728. connection.emuc.removePreziFromPresence();
  14729. connection.emuc.sendPresence();
  14730. },
  14731. sendChatMessage: function (message, nickname) {
  14732. connection.emuc.sendMessage(message, nickname);
  14733. },
  14734. setSubject: function (topic) {
  14735. connection.emuc.setSubject(topic);
  14736. },
  14737. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14738. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  14739. },
  14740. dial: function (to, from, roomName,roomPass) {
  14741. connection.rayo.dial(to, from, roomName,roomPass);
  14742. },
  14743. setMute: function (jid, mute) {
  14744. connection.moderate.setMute(jid, mute);
  14745. },
  14746. eject: function (jid) {
  14747. connection.moderate.eject(jid);
  14748. },
  14749. logout: function (callback) {
  14750. Moderator.logout(callback);
  14751. },
  14752. findJidFromResource: function (resource) {
  14753. return connection.emuc.findJidFromResource(resource);
  14754. },
  14755. getMembers: function () {
  14756. return connection.emuc.members;
  14757. },
  14758. getJidFromSSRC: function (ssrc) {
  14759. if(!connection)
  14760. return null;
  14761. return connection.emuc.ssrc2jid[ssrc];
  14762. },
  14763. getMUCJoined: function () {
  14764. return connection.emuc.joined;
  14765. },
  14766. getSessions: function () {
  14767. return connection.jingle.sessions;
  14768. }
  14769. };
  14770. module.exports = XMPP;
  14771. },{"../../service/RTC/StreamEventTypes":82,"../../service/UI/UIEvents":83,"../../service/xmpp/XMPPEvents":88,"./SDP":48,"./moderator":52,"./recording":53,"./strophe.emuc":54,"./strophe.jingle":55,"./strophe.logger":56,"./strophe.moderate":57,"./strophe.rayo":58,"./strophe.util":59,"events":89,"pako":62}],61:[function(require,module,exports){
  14772. // i18next, v1.7.7
  14773. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  14774. // Distributed under MIT license
  14775. // http://i18next.com
  14776. (function() {
  14777. // add indexOf to non ECMA-262 standard compliant browsers
  14778. if (!Array.prototype.indexOf) {
  14779. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  14780. "use strict";
  14781. if (this == null) {
  14782. throw new TypeError();
  14783. }
  14784. var t = Object(this);
  14785. var len = t.length >>> 0;
  14786. if (len === 0) {
  14787. return -1;
  14788. }
  14789. var n = 0;
  14790. if (arguments.length > 0) {
  14791. n = Number(arguments[1]);
  14792. if (n != n) { // shortcut for verifying if it's NaN
  14793. n = 0;
  14794. } else if (n != 0 && n != Infinity && n != -Infinity) {
  14795. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  14796. }
  14797. }
  14798. if (n >= len) {
  14799. return -1;
  14800. }
  14801. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  14802. for (; k < len; k++) {
  14803. if (k in t && t[k] === searchElement) {
  14804. return k;
  14805. }
  14806. }
  14807. return -1;
  14808. }
  14809. }
  14810. // add lastIndexOf to non ECMA-262 standard compliant browsers
  14811. if (!Array.prototype.lastIndexOf) {
  14812. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  14813. "use strict";
  14814. if (this == null) {
  14815. throw new TypeError();
  14816. }
  14817. var t = Object(this);
  14818. var len = t.length >>> 0;
  14819. if (len === 0) {
  14820. return -1;
  14821. }
  14822. var n = len;
  14823. if (arguments.length > 1) {
  14824. n = Number(arguments[1]);
  14825. if (n != n) {
  14826. n = 0;
  14827. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  14828. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  14829. }
  14830. }
  14831. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  14832. for (; k >= 0; k--) {
  14833. if (k in t && t[k] === searchElement) {
  14834. return k;
  14835. }
  14836. }
  14837. return -1;
  14838. };
  14839. }
  14840. // Add string trim for IE8.
  14841. if (typeof String.prototype.trim !== 'function') {
  14842. String.prototype.trim = function() {
  14843. return this.replace(/^\s+|\s+$/g, '');
  14844. }
  14845. }
  14846. var root = this
  14847. , $ = root.jQuery || root.Zepto
  14848. , i18n = {}
  14849. , resStore = {}
  14850. , currentLng
  14851. , replacementCounter = 0
  14852. , languages = []
  14853. , initialized = false
  14854. , sync = {};
  14855. // Export the i18next object for **CommonJS**.
  14856. // If we're not in CommonJS, add `i18n` to the
  14857. // global object or to jquery.
  14858. if (typeof module !== 'undefined' && module.exports) {
  14859. if (!$) {
  14860. try {
  14861. $ = require('jquery');
  14862. } catch(e) {
  14863. // just ignore
  14864. }
  14865. }
  14866. if ($) {
  14867. $.i18n = $.i18n || i18n;
  14868. }
  14869. module.exports = i18n;
  14870. } else {
  14871. if ($) {
  14872. $.i18n = $.i18n || i18n;
  14873. }
  14874. root.i18n = root.i18n || i18n;
  14875. }
  14876. sync = {
  14877. load: function(lngs, options, cb) {
  14878. if (options.useLocalStorage) {
  14879. sync._loadLocal(lngs, options, function(err, store) {
  14880. var missingLngs = [];
  14881. for (var i = 0, len = lngs.length; i < len; i++) {
  14882. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  14883. }
  14884. if (missingLngs.length > 0) {
  14885. sync._fetch(missingLngs, options, function(err, fetched) {
  14886. f.extend(store, fetched);
  14887. sync._storeLocal(fetched);
  14888. cb(null, store);
  14889. });
  14890. } else {
  14891. cb(null, store);
  14892. }
  14893. });
  14894. } else {
  14895. sync._fetch(lngs, options, function(err, store){
  14896. cb(null, store);
  14897. });
  14898. }
  14899. },
  14900. _loadLocal: function(lngs, options, cb) {
  14901. var store = {}
  14902. , nowMS = new Date().getTime();
  14903. if(window.localStorage) {
  14904. var todo = lngs.length;
  14905. f.each(lngs, function(key, lng) {
  14906. var local = window.localStorage.getItem('res_' + lng);
  14907. if (local) {
  14908. local = JSON.parse(local);
  14909. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  14910. store[lng] = local;
  14911. }
  14912. }
  14913. todo--; // wait for all done befor callback
  14914. if (todo === 0) cb(null, store);
  14915. });
  14916. }
  14917. },
  14918. _storeLocal: function(store) {
  14919. if(window.localStorage) {
  14920. for (var m in store) {
  14921. store[m].i18nStamp = new Date().getTime();
  14922. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  14923. }
  14924. }
  14925. return;
  14926. },
  14927. _fetch: function(lngs, options, cb) {
  14928. var ns = options.ns
  14929. , store = {};
  14930. if (!options.dynamicLoad) {
  14931. var todo = ns.namespaces.length * lngs.length
  14932. , errors;
  14933. // load each file individual
  14934. f.each(ns.namespaces, function(nsIndex, nsValue) {
  14935. f.each(lngs, function(lngIndex, lngValue) {
  14936. // Call this once our translation has returned.
  14937. var loadComplete = function(err, data) {
  14938. if (err) {
  14939. errors = errors || [];
  14940. errors.push(err);
  14941. }
  14942. store[lngValue] = store[lngValue] || {};
  14943. store[lngValue][nsValue] = data;
  14944. todo--; // wait for all done befor callback
  14945. if (todo === 0) cb(errors, store);
  14946. };
  14947. if(typeof options.customLoad == 'function'){
  14948. // Use the specified custom callback.
  14949. options.customLoad(lngValue, nsValue, options, loadComplete);
  14950. } else {
  14951. //~ // Use our inbuilt sync.
  14952. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  14953. }
  14954. });
  14955. });
  14956. } else {
  14957. // Call this once our translation has returned.
  14958. var loadComplete = function(err, data) {
  14959. cb(null, data);
  14960. };
  14961. if(typeof options.customLoad == 'function'){
  14962. // Use the specified custom callback.
  14963. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  14964. } else {
  14965. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  14966. // load all needed stuff once
  14967. f.ajax({
  14968. url: url,
  14969. success: function(data, status, xhr) {
  14970. f.log('loaded: ' + url);
  14971. loadComplete(null, data);
  14972. },
  14973. error : function(xhr, status, error) {
  14974. f.log('failed loading: ' + url);
  14975. loadComplete('failed loading resource.json error: ' + error);
  14976. },
  14977. dataType: "json",
  14978. async : options.getAsync
  14979. });
  14980. }
  14981. }
  14982. },
  14983. _fetchOne: function(lng, ns, options, done) {
  14984. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  14985. f.ajax({
  14986. url: url,
  14987. success: function(data, status, xhr) {
  14988. f.log('loaded: ' + url);
  14989. done(null, data);
  14990. },
  14991. error : function(xhr, status, error) {
  14992. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  14993. // file loaded but invalid json, stop waste time !
  14994. f.error('There is a typo in: ' + url);
  14995. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  14996. f.log('Does not exist: ' + url);
  14997. } else {
  14998. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  14999. f.log(theStatus + ' when loading ' + url);
  15000. }
  15001. done(error, {});
  15002. },
  15003. dataType: "json",
  15004. async : options.getAsync
  15005. });
  15006. },
  15007. postMissing: function(lng, ns, key, defaultValue, lngs) {
  15008. var payload = {};
  15009. payload[key] = defaultValue;
  15010. var urls = [];
  15011. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  15012. for (var i = 0; i < o.fallbackLng.length; i++) {
  15013. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  15014. }
  15015. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  15016. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  15017. } else if (o.sendMissingTo === 'all') {
  15018. for (var i = 0, l = lngs.length; i < l; i++) {
  15019. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  15020. }
  15021. }
  15022. for (var y = 0, len = urls.length; y < len; y++) {
  15023. var item = urls[y];
  15024. f.ajax({
  15025. url: item.url,
  15026. type: o.sendType,
  15027. data: payload,
  15028. success: function(data, status, xhr) {
  15029. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  15030. // add key to resStore
  15031. var keys = key.split('.');
  15032. var x = 0;
  15033. var value = resStore[item.lng][ns];
  15034. while (keys[x]) {
  15035. if (x === keys.length - 1) {
  15036. value = value[keys[x]] = defaultValue;
  15037. } else {
  15038. value = value[keys[x]] = value[keys[x]] || {};
  15039. }
  15040. x++;
  15041. }
  15042. },
  15043. error : function(xhr, status, error) {
  15044. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  15045. },
  15046. dataType: "json",
  15047. async : o.postAsync
  15048. });
  15049. }
  15050. },
  15051. reload: reload
  15052. };
  15053. // defaults
  15054. var o = {
  15055. lng: undefined,
  15056. load: 'all',
  15057. preload: [],
  15058. lowerCaseLng: false,
  15059. returnObjectTrees: false,
  15060. fallbackLng: ['dev'],
  15061. fallbackNS: [],
  15062. detectLngQS: 'setLng',
  15063. detectLngFromLocalStorage: false,
  15064. ns: 'translation',
  15065. fallbackOnNull: true,
  15066. fallbackOnEmpty: false,
  15067. fallbackToDefaultNS: false,
  15068. nsseparator: ':',
  15069. keyseparator: '.',
  15070. selectorAttr: 'data-i18n',
  15071. debug: false,
  15072. resGetPath: 'locales/__lng__/__ns__.json',
  15073. resPostPath: 'locales/add/__lng__/__ns__',
  15074. getAsync: true,
  15075. postAsync: true,
  15076. resStore: undefined,
  15077. useLocalStorage: false,
  15078. localStorageExpirationTime: 7*24*60*60*1000,
  15079. dynamicLoad: false,
  15080. sendMissing: false,
  15081. sendMissingTo: 'fallback', // current | all
  15082. sendType: 'POST',
  15083. interpolationPrefix: '__',
  15084. interpolationSuffix: '__',
  15085. defaultVariables: false,
  15086. reusePrefix: '$t(',
  15087. reuseSuffix: ')',
  15088. pluralSuffix: '_plural',
  15089. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  15090. contextNotFound: ['context_not_found', Math.random()].join(''),
  15091. escapeInterpolation: false,
  15092. indefiniteSuffix: '_indefinite',
  15093. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  15094. setJqueryExt: true,
  15095. defaultValueFromContent: true,
  15096. useDataAttrOptions: false,
  15097. cookieExpirationTime: undefined,
  15098. useCookie: true,
  15099. cookieName: 'i18next',
  15100. cookieDomain: undefined,
  15101. objectTreeKeyHandler: undefined,
  15102. postProcess: undefined,
  15103. parseMissingKey: undefined,
  15104. missingKeyHandler: sync.postMissing,
  15105. shortcutFunction: 'sprintf' // or: defaultValue
  15106. };
  15107. function _extend(target, source) {
  15108. if (!source || typeof source === 'function') {
  15109. return target;
  15110. }
  15111. for (var attr in source) { target[attr] = source[attr]; }
  15112. return target;
  15113. }
  15114. function _deepExtend(target, source) {
  15115. for (var prop in source)
  15116. if (prop in target)
  15117. _deepExtend(target[prop], source[prop]);
  15118. else
  15119. target[prop] = source[prop];
  15120. return target;
  15121. }
  15122. function _each(object, callback, args) {
  15123. var name, i = 0,
  15124. length = object.length,
  15125. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  15126. if (args) {
  15127. if (isObj) {
  15128. for (name in object) {
  15129. if (callback.apply(object[name], args) === false) {
  15130. break;
  15131. }
  15132. }
  15133. } else {
  15134. for ( ; i < length; ) {
  15135. if (callback.apply(object[i++], args) === false) {
  15136. break;
  15137. }
  15138. }
  15139. }
  15140. // A special, fast, case for the most common use of each
  15141. } else {
  15142. if (isObj) {
  15143. for (name in object) {
  15144. if (callback.call(object[name], name, object[name]) === false) {
  15145. break;
  15146. }
  15147. }
  15148. } else {
  15149. for ( ; i < length; ) {
  15150. if (callback.call(object[i], i, object[i++]) === false) {
  15151. break;
  15152. }
  15153. }
  15154. }
  15155. }
  15156. return object;
  15157. }
  15158. var _entityMap = {
  15159. "&": "&amp;",
  15160. "<": "&lt;",
  15161. ">": "&gt;",
  15162. '"': '&quot;',
  15163. "'": '&#39;',
  15164. "/": '&#x2F;'
  15165. };
  15166. function _escape(data) {
  15167. if (typeof data === 'string') {
  15168. return data.replace(/[&<>"'\/]/g, function (s) {
  15169. return _entityMap[s];
  15170. });
  15171. }else{
  15172. return data;
  15173. }
  15174. }
  15175. function _ajax(options) {
  15176. // v0.5.0 of https://github.com/goloroden/http.js
  15177. var getXhr = function (callback) {
  15178. // Use the native XHR object if the browser supports it.
  15179. if (window.XMLHttpRequest) {
  15180. return callback(null, new XMLHttpRequest());
  15181. } else if (window.ActiveXObject) {
  15182. // In Internet Explorer check for ActiveX versions of the XHR object.
  15183. try {
  15184. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  15185. } catch (e) {
  15186. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  15187. }
  15188. }
  15189. // If no XHR support was found, throw an error.
  15190. return callback(new Error());
  15191. };
  15192. var encodeUsingUrlEncoding = function (data) {
  15193. if(typeof data === 'string') {
  15194. return data;
  15195. }
  15196. var result = [];
  15197. for(var dataItem in data) {
  15198. if(data.hasOwnProperty(dataItem)) {
  15199. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  15200. }
  15201. }
  15202. return result.join('&');
  15203. };
  15204. var utf8 = function (text) {
  15205. text = text.replace(/\r\n/g, '\n');
  15206. var result = '';
  15207. for(var i = 0; i < text.length; i++) {
  15208. var c = text.charCodeAt(i);
  15209. if(c < 128) {
  15210. result += String.fromCharCode(c);
  15211. } else if((c > 127) && (c < 2048)) {
  15212. result += String.fromCharCode((c >> 6) | 192);
  15213. result += String.fromCharCode((c & 63) | 128);
  15214. } else {
  15215. result += String.fromCharCode((c >> 12) | 224);
  15216. result += String.fromCharCode(((c >> 6) & 63) | 128);
  15217. result += String.fromCharCode((c & 63) | 128);
  15218. }
  15219. }
  15220. return result;
  15221. };
  15222. var base64 = function (text) {
  15223. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15224. text = utf8(text);
  15225. var result = '',
  15226. chr1, chr2, chr3,
  15227. enc1, enc2, enc3, enc4,
  15228. i = 0;
  15229. do {
  15230. chr1 = text.charCodeAt(i++);
  15231. chr2 = text.charCodeAt(i++);
  15232. chr3 = text.charCodeAt(i++);
  15233. enc1 = chr1 >> 2;
  15234. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  15235. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  15236. enc4 = chr3 & 63;
  15237. if(isNaN(chr2)) {
  15238. enc3 = enc4 = 64;
  15239. } else if(isNaN(chr3)) {
  15240. enc4 = 64;
  15241. }
  15242. result +=
  15243. keyStr.charAt(enc1) +
  15244. keyStr.charAt(enc2) +
  15245. keyStr.charAt(enc3) +
  15246. keyStr.charAt(enc4);
  15247. chr1 = chr2 = chr3 = '';
  15248. enc1 = enc2 = enc3 = enc4 = '';
  15249. } while(i < text.length);
  15250. return result;
  15251. };
  15252. var mergeHeaders = function () {
  15253. // Use the first header object as base.
  15254. var result = arguments[0];
  15255. // Iterate through the remaining header objects and add them.
  15256. for(var i = 1; i < arguments.length; i++) {
  15257. var currentHeaders = arguments[i];
  15258. for(var header in currentHeaders) {
  15259. if(currentHeaders.hasOwnProperty(header)) {
  15260. result[header] = currentHeaders[header];
  15261. }
  15262. }
  15263. }
  15264. // Return the merged headers.
  15265. return result;
  15266. };
  15267. var ajax = function (method, url, options, callback) {
  15268. // Adjust parameters.
  15269. if(typeof options === 'function') {
  15270. callback = options;
  15271. options = {};
  15272. }
  15273. // Set default parameter values.
  15274. options.cache = options.cache || false;
  15275. options.data = options.data || {};
  15276. options.headers = options.headers || {};
  15277. options.jsonp = options.jsonp || false;
  15278. options.async = options.async === undefined ? true : options.async;
  15279. // Merge the various header objects.
  15280. var headers = mergeHeaders({
  15281. 'accept': '*/*',
  15282. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  15283. }, ajax.headers, options.headers);
  15284. // Encode the data according to the content-type.
  15285. var payload;
  15286. if (headers['content-type'] === 'application/json') {
  15287. payload = JSON.stringify(options.data);
  15288. } else {
  15289. payload = encodeUsingUrlEncoding(options.data);
  15290. }
  15291. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  15292. // if neccessary.
  15293. if(method === 'GET') {
  15294. // Setup the query string.
  15295. var queryString = [];
  15296. if(payload) {
  15297. queryString.push(payload);
  15298. payload = null;
  15299. }
  15300. // Handle caching.
  15301. if(!options.cache) {
  15302. queryString.push('_=' + (new Date()).getTime());
  15303. }
  15304. // If neccessary prepare the query string for a JSONP call.
  15305. if(options.jsonp) {
  15306. queryString.push('callback=' + options.jsonp);
  15307. queryString.push('jsonp=' + options.jsonp);
  15308. }
  15309. // Merge the query string and attach it to the url.
  15310. queryString = queryString.join('&');
  15311. if (queryString.length > 1) {
  15312. if (url.indexOf('?') > -1) {
  15313. url += '&' + queryString;
  15314. } else {
  15315. url += '?' + queryString;
  15316. }
  15317. }
  15318. // Make a JSONP call if neccessary.
  15319. if(options.jsonp) {
  15320. var head = document.getElementsByTagName('head')[0];
  15321. var script = document.createElement('script');
  15322. script.type = 'text/javascript';
  15323. script.src = url;
  15324. head.appendChild(script);
  15325. return;
  15326. }
  15327. }
  15328. // Since we got here, it is no JSONP request, so make a normal XHR request.
  15329. getXhr(function (err, xhr) {
  15330. if(err) return callback(err);
  15331. // Open the request.
  15332. xhr.open(method, url, options.async);
  15333. // Set the request headers.
  15334. for(var header in headers) {
  15335. if(headers.hasOwnProperty(header)) {
  15336. xhr.setRequestHeader(header, headers[header]);
  15337. }
  15338. }
  15339. // Handle the request events.
  15340. xhr.onreadystatechange = function () {
  15341. if(xhr.readyState === 4) {
  15342. var data = xhr.responseText || '';
  15343. // If no callback is given, return.
  15344. if(!callback) {
  15345. return;
  15346. }
  15347. // Return an object that provides access to the data as text and JSON.
  15348. callback(xhr.status, {
  15349. text: function () {
  15350. return data;
  15351. },
  15352. json: function () {
  15353. try {
  15354. return JSON.parse(data)
  15355. } catch (e) {
  15356. f.error('Can not parse JSON. URL: ' + url);
  15357. return {};
  15358. }
  15359. }
  15360. });
  15361. }
  15362. };
  15363. // Actually send the XHR request.
  15364. xhr.send(payload);
  15365. });
  15366. };
  15367. // Define the external interface.
  15368. var http = {
  15369. authBasic: function (username, password) {
  15370. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  15371. },
  15372. connect: function (url, options, callback) {
  15373. return ajax('CONNECT', url, options, callback);
  15374. },
  15375. del: function (url, options, callback) {
  15376. return ajax('DELETE', url, options, callback);
  15377. },
  15378. get: function (url, options, callback) {
  15379. return ajax('GET', url, options, callback);
  15380. },
  15381. head: function (url, options, callback) {
  15382. return ajax('HEAD', url, options, callback);
  15383. },
  15384. headers: function (headers) {
  15385. ajax.headers = headers || {};
  15386. },
  15387. isAllowed: function (url, verb, callback) {
  15388. this.options(url, function (status, data) {
  15389. callback(data.text().indexOf(verb) !== -1);
  15390. });
  15391. },
  15392. options: function (url, options, callback) {
  15393. return ajax('OPTIONS', url, options, callback);
  15394. },
  15395. patch: function (url, options, callback) {
  15396. return ajax('PATCH', url, options, callback);
  15397. },
  15398. post: function (url, options, callback) {
  15399. return ajax('POST', url, options, callback);
  15400. },
  15401. put: function (url, options, callback) {
  15402. return ajax('PUT', url, options, callback);
  15403. },
  15404. trace: function (url, options, callback) {
  15405. return ajax('TRACE', url, options, callback);
  15406. }
  15407. };
  15408. var methode = options.type ? options.type.toLowerCase() : 'get';
  15409. http[methode](options.url, options, function (status, data) {
  15410. // file: protocol always gives status code 0, so check for data
  15411. if (status === 200 || (status === 0 && data.text())) {
  15412. options.success(data.json(), status, null);
  15413. } else {
  15414. options.error(data.text(), status, null);
  15415. }
  15416. });
  15417. }
  15418. var _cookie = {
  15419. create: function(name,value,minutes,domain) {
  15420. var expires;
  15421. if (minutes) {
  15422. var date = new Date();
  15423. date.setTime(date.getTime()+(minutes*60*1000));
  15424. expires = "; expires="+date.toGMTString();
  15425. }
  15426. else expires = "";
  15427. domain = (domain)? "domain="+domain+";" : "";
  15428. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  15429. },
  15430. read: function(name) {
  15431. var nameEQ = name + "=";
  15432. var ca = document.cookie.split(';');
  15433. for(var i=0;i < ca.length;i++) {
  15434. var c = ca[i];
  15435. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  15436. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  15437. }
  15438. return null;
  15439. },
  15440. remove: function(name) {
  15441. this.create(name,"",-1);
  15442. }
  15443. };
  15444. var cookie_noop = {
  15445. create: function(name,value,minutes,domain) {},
  15446. read: function(name) { return null; },
  15447. remove: function(name) {}
  15448. };
  15449. // move dependent functions to a container so that
  15450. // they can be overriden easier in no jquery environment (node.js)
  15451. var f = {
  15452. extend: $ ? $.extend : _extend,
  15453. deepExtend: _deepExtend,
  15454. each: $ ? $.each : _each,
  15455. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  15456. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  15457. detectLanguage: detectLanguage,
  15458. escape: _escape,
  15459. log: function(str) {
  15460. if (o.debug && typeof console !== "undefined") console.log(str);
  15461. },
  15462. error: function(str) {
  15463. if (typeof console !== "undefined") console.error(str);
  15464. },
  15465. getCountyIndexOfLng: function(lng) {
  15466. var lng_index = 0;
  15467. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  15468. return lng_index;
  15469. },
  15470. toLanguages: function(lng) {
  15471. var log = this.log;
  15472. function applyCase(l) {
  15473. var ret = l;
  15474. if (typeof l === 'string' && l.indexOf('-') > -1) {
  15475. var parts = l.split('-');
  15476. ret = o.lowerCaseLng ?
  15477. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  15478. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  15479. } else {
  15480. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  15481. }
  15482. return ret;
  15483. }
  15484. var languages = [];
  15485. var whitelist = o.lngWhitelist || false;
  15486. var addLanguage = function(language){
  15487. //reject langs not whitelisted
  15488. if(!whitelist || whitelist.indexOf(language) > -1){
  15489. languages.push(language);
  15490. }else{
  15491. log('rejecting non-whitelisted language: ' + language);
  15492. }
  15493. };
  15494. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  15495. var parts = lng.split('-');
  15496. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  15497. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  15498. } else {
  15499. addLanguage(applyCase(lng));
  15500. }
  15501. for (var i = 0; i < o.fallbackLng.length; i++) {
  15502. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  15503. }
  15504. return languages;
  15505. },
  15506. regexEscape: function(str) {
  15507. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  15508. },
  15509. regexReplacementEscape: function(strOrFn) {
  15510. if (typeof strOrFn === 'string') {
  15511. return strOrFn.replace(/\$/g, "$$$$");
  15512. } else {
  15513. return strOrFn;
  15514. }
  15515. },
  15516. localStorage: {
  15517. setItem: function(key, value) {
  15518. if (window.localStorage) {
  15519. try {
  15520. window.localStorage.setItem(key, value);
  15521. } catch (e) {
  15522. f.log('failed to set value for key "' + key + '" to localStorage.');
  15523. }
  15524. }
  15525. }
  15526. }
  15527. };
  15528. function init(options, cb) {
  15529. if (typeof options === 'function') {
  15530. cb = options;
  15531. options = {};
  15532. }
  15533. options = options || {};
  15534. // override defaults with passed in options
  15535. f.extend(o, options);
  15536. delete o.fixLng; /* passed in each time */
  15537. // override functions: .log(), .detectLanguage(), etc
  15538. if (o.functions) {
  15539. delete o.functions;
  15540. f.extend(f, options.functions);
  15541. }
  15542. // create namespace object if namespace is passed in as string
  15543. if (typeof o.ns == 'string') {
  15544. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  15545. }
  15546. // fallback namespaces
  15547. if (typeof o.fallbackNS == 'string') {
  15548. o.fallbackNS = [o.fallbackNS];
  15549. }
  15550. // fallback languages
  15551. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  15552. o.fallbackLng = [o.fallbackLng];
  15553. }
  15554. // escape prefix/suffix
  15555. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  15556. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  15557. if (!o.lng) o.lng = f.detectLanguage();
  15558. languages = f.toLanguages(o.lng);
  15559. currentLng = languages[0];
  15560. f.log('currentLng set to: ' + currentLng);
  15561. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  15562. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  15563. }
  15564. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  15565. f.localStorage.setItem('i18next_lng', currentLng);
  15566. }
  15567. var lngTranslate = translate;
  15568. if (options.fixLng) {
  15569. lngTranslate = function(key, options) {
  15570. options = options || {};
  15571. options.lng = options.lng || lngTranslate.lng;
  15572. return translate(key, options);
  15573. };
  15574. lngTranslate.lng = currentLng;
  15575. }
  15576. pluralExtensions.setCurrentLng(currentLng);
  15577. // add JQuery extensions
  15578. if ($ && o.setJqueryExt) addJqueryFunct();
  15579. // jQuery deferred
  15580. var deferred;
  15581. if ($ && $.Deferred) {
  15582. deferred = $.Deferred();
  15583. }
  15584. // return immidiatly if res are passed in
  15585. if (o.resStore) {
  15586. resStore = o.resStore;
  15587. initialized = true;
  15588. if (cb) cb(lngTranslate);
  15589. if (deferred) deferred.resolve(lngTranslate);
  15590. if (deferred) return deferred.promise();
  15591. return;
  15592. }
  15593. // languages to load
  15594. var lngsToLoad = f.toLanguages(o.lng);
  15595. if (typeof o.preload === 'string') o.preload = [o.preload];
  15596. for (var i = 0, l = o.preload.length; i < l; i++) {
  15597. var pres = f.toLanguages(o.preload[i]);
  15598. for (var y = 0, len = pres.length; y < len; y++) {
  15599. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15600. lngsToLoad.push(pres[y]);
  15601. }
  15602. }
  15603. }
  15604. // else load them
  15605. i18n.sync.load(lngsToLoad, o, function(err, store) {
  15606. resStore = store;
  15607. initialized = true;
  15608. if (cb) cb(lngTranslate);
  15609. if (deferred) deferred.resolve(lngTranslate);
  15610. });
  15611. if (deferred) return deferred.promise();
  15612. }
  15613. function preload(lngs, cb) {
  15614. if (typeof lngs === 'string') lngs = [lngs];
  15615. for (var i = 0, l = lngs.length; i < l; i++) {
  15616. if (o.preload.indexOf(lngs[i]) < 0) {
  15617. o.preload.push(lngs[i]);
  15618. }
  15619. }
  15620. return init(cb);
  15621. }
  15622. function addResourceBundle(lng, ns, resources, deep) {
  15623. if (typeof ns !== 'string') {
  15624. resources = ns;
  15625. ns = o.ns.defaultNs;
  15626. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15627. o.ns.namespaces.push(ns);
  15628. }
  15629. resStore[lng] = resStore[lng] || {};
  15630. resStore[lng][ns] = resStore[lng][ns] || {};
  15631. if (deep) {
  15632. f.deepExtend(resStore[lng][ns], resources);
  15633. } else {
  15634. f.extend(resStore[lng][ns], resources);
  15635. }
  15636. }
  15637. function hasResourceBundle(lng, ns) {
  15638. if (typeof ns !== 'string') {
  15639. ns = o.ns.defaultNs;
  15640. }
  15641. resStore[lng] = resStore[lng] || {};
  15642. var res = resStore[lng][ns] || {};
  15643. var hasValues = false;
  15644. for(var prop in res) {
  15645. if (res.hasOwnProperty(prop)) {
  15646. hasValues = true;
  15647. }
  15648. }
  15649. return hasValues;
  15650. }
  15651. function removeResourceBundle(lng, ns) {
  15652. if (typeof ns !== 'string') {
  15653. ns = o.ns.defaultNs;
  15654. }
  15655. resStore[lng] = resStore[lng] || {};
  15656. resStore[lng][ns] = {};
  15657. }
  15658. function addResource(lng, ns, key, value) {
  15659. if (typeof ns !== 'string') {
  15660. resource = ns;
  15661. ns = o.ns.defaultNs;
  15662. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15663. o.ns.namespaces.push(ns);
  15664. }
  15665. resStore[lng] = resStore[lng] || {};
  15666. resStore[lng][ns] = resStore[lng][ns] || {};
  15667. var keys = key.split(o.keyseparator);
  15668. var x = 0;
  15669. var node = resStore[lng][ns];
  15670. var origRef = node;
  15671. while (keys[x]) {
  15672. if (x == keys.length - 1)
  15673. node[keys[x]] = value;
  15674. else {
  15675. if (node[keys[x]] == null)
  15676. node[keys[x]] = {};
  15677. node = node[keys[x]];
  15678. }
  15679. x++;
  15680. }
  15681. }
  15682. function addResources(lng, ns, resources) {
  15683. if (typeof ns !== 'string') {
  15684. resource = ns;
  15685. ns = o.ns.defaultNs;
  15686. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15687. o.ns.namespaces.push(ns);
  15688. }
  15689. for (var m in resources) {
  15690. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  15691. }
  15692. }
  15693. function setDefaultNamespace(ns) {
  15694. o.ns.defaultNs = ns;
  15695. }
  15696. function loadNamespace(namespace, cb) {
  15697. loadNamespaces([namespace], cb);
  15698. }
  15699. function loadNamespaces(namespaces, cb) {
  15700. var opts = {
  15701. dynamicLoad: o.dynamicLoad,
  15702. resGetPath: o.resGetPath,
  15703. getAsync: o.getAsync,
  15704. customLoad: o.customLoad,
  15705. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  15706. };
  15707. // languages to load
  15708. var lngsToLoad = f.toLanguages(o.lng);
  15709. if (typeof o.preload === 'string') o.preload = [o.preload];
  15710. for (var i = 0, l = o.preload.length; i < l; i++) {
  15711. var pres = f.toLanguages(o.preload[i]);
  15712. for (var y = 0, len = pres.length; y < len; y++) {
  15713. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15714. lngsToLoad.push(pres[y]);
  15715. }
  15716. }
  15717. }
  15718. // check if we have to load
  15719. var lngNeedLoad = [];
  15720. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  15721. var needLoad = false;
  15722. var resSet = resStore[lngsToLoad[a]];
  15723. if (resSet) {
  15724. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  15725. if (!resSet[namespaces[b]]) needLoad = true;
  15726. }
  15727. } else {
  15728. needLoad = true;
  15729. }
  15730. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  15731. }
  15732. if (lngNeedLoad.length) {
  15733. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  15734. var todo = namespaces.length * lngNeedLoad.length;
  15735. // load each file individual
  15736. f.each(namespaces, function(nsIndex, nsValue) {
  15737. // append namespace to namespace array
  15738. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  15739. o.ns.namespaces.push(nsValue);
  15740. }
  15741. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  15742. resStore[lngValue] = resStore[lngValue] || {};
  15743. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  15744. todo--; // wait for all done befor callback
  15745. if (todo === 0 && cb) {
  15746. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  15747. cb();
  15748. }
  15749. });
  15750. });
  15751. });
  15752. } else {
  15753. if (cb) cb();
  15754. }
  15755. }
  15756. function setLng(lng, options, cb) {
  15757. if (typeof options === 'function') {
  15758. cb = options;
  15759. options = {};
  15760. } else if (!options) {
  15761. options = {};
  15762. }
  15763. options.lng = lng;
  15764. return init(options, cb);
  15765. }
  15766. function lng() {
  15767. return currentLng;
  15768. }
  15769. function reload(cb) {
  15770. resStore = {};
  15771. setLng(currentLng, cb);
  15772. }
  15773. function addJqueryFunct() {
  15774. // $.t shortcut
  15775. $.t = $.t || translate;
  15776. function parse(ele, key, options) {
  15777. if (key.length === 0) return;
  15778. var attr = 'text';
  15779. if (key.indexOf('[') === 0) {
  15780. var parts = key.split(']');
  15781. key = parts[1];
  15782. attr = parts[0].substr(1, parts[0].length-1);
  15783. }
  15784. if (key.indexOf(';') === key.length-1) {
  15785. key = key.substr(0, key.length-2);
  15786. }
  15787. var optionsToUse;
  15788. if (attr === 'html') {
  15789. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  15790. ele.html($.t(key, optionsToUse));
  15791. } else if (attr === 'text') {
  15792. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  15793. ele.text($.t(key, optionsToUse));
  15794. } else if (attr === 'prepend') {
  15795. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  15796. ele.prepend($.t(key, optionsToUse));
  15797. } else if (attr === 'append') {
  15798. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  15799. ele.append($.t(key, optionsToUse));
  15800. } else if (attr.indexOf("data-") === 0) {
  15801. var dataAttr = attr.substr(("data-").length);
  15802. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  15803. var translated = $.t(key, optionsToUse);
  15804. //we change into the data cache
  15805. ele.data(dataAttr, translated);
  15806. //we change into the dom
  15807. ele.attr(attr, translated);
  15808. } else {
  15809. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  15810. ele.attr(attr, $.t(key, optionsToUse));
  15811. }
  15812. }
  15813. function localize(ele, options) {
  15814. var key = ele.attr(o.selectorAttr);
  15815. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  15816. if (!key) return;
  15817. var target = ele
  15818. , targetSelector = ele.data("i18n-target");
  15819. if (targetSelector) {
  15820. target = ele.find(targetSelector) || ele;
  15821. }
  15822. if (!options && o.useDataAttrOptions === true) {
  15823. options = ele.data("i18n-options");
  15824. }
  15825. options = options || {};
  15826. if (key.indexOf(';') >= 0) {
  15827. var keys = key.split(';');
  15828. $.each(keys, function(m, k) {
  15829. if (k !== '') parse(target, k, options);
  15830. });
  15831. } else {
  15832. parse(target, key, options);
  15833. }
  15834. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  15835. }
  15836. // fn
  15837. $.fn.i18n = function (options) {
  15838. return this.each(function() {
  15839. // localize element itself
  15840. localize($(this), options);
  15841. // localize childs
  15842. var elements = $(this).find('[' + o.selectorAttr + ']');
  15843. elements.each(function() {
  15844. localize($(this), options);
  15845. });
  15846. });
  15847. };
  15848. }
  15849. function applyReplacement(str, replacementHash, nestedKey, options) {
  15850. if (!str) return str;
  15851. options = options || replacementHash; // first call uses replacement hash combined with options
  15852. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  15853. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  15854. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  15855. , unEscapingSuffix = 'HTML'+suffix;
  15856. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  15857. f.each(hash, function(key, value) {
  15858. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  15859. if (typeof value === 'object' && value !== null) {
  15860. str = applyReplacement(str, value, nextKey, options);
  15861. } else {
  15862. if (options.escapeInterpolation || o.escapeInterpolation) {
  15863. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  15864. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  15865. } else {
  15866. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  15867. }
  15868. // str = options.escapeInterpolation;
  15869. }
  15870. });
  15871. return str;
  15872. }
  15873. // append it to functions
  15874. f.applyReplacement = applyReplacement;
  15875. function applyReuse(translated, options) {
  15876. var comma = ',';
  15877. var options_open = '{';
  15878. var options_close = '}';
  15879. var opts = f.extend({}, options);
  15880. delete opts.postProcess;
  15881. while (translated.indexOf(o.reusePrefix) != -1) {
  15882. replacementCounter++;
  15883. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  15884. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  15885. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  15886. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  15887. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  15888. if (index_of_end_of_closing <= index_of_opening) {
  15889. f.error('there is an missing closing in following translation value', translated);
  15890. return '';
  15891. }
  15892. if (token_without_symbols.indexOf(comma) != -1) {
  15893. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  15894. 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) {
  15895. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  15896. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  15897. try {
  15898. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  15899. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  15900. } catch (e) {
  15901. }
  15902. }
  15903. }
  15904. var translated_token = _translate(token_without_symbols, opts);
  15905. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  15906. }
  15907. return translated;
  15908. }
  15909. function hasContext(options) {
  15910. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  15911. }
  15912. function needsPlural(options, lng) {
  15913. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  15914. }
  15915. function needsIndefiniteArticle(options) {
  15916. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  15917. }
  15918. function exists(key, options) {
  15919. options = options || {};
  15920. var notFound = _getDefaultValue(key, options)
  15921. , found = _find(key, options);
  15922. return found !== undefined || found === notFound;
  15923. }
  15924. function translate(key, options) {
  15925. options = options || {};
  15926. if (!initialized) {
  15927. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  15928. return options.defaultValue || '';
  15929. };
  15930. replacementCounter = 0;
  15931. return _translate.apply(null, arguments);
  15932. }
  15933. function _getDefaultValue(key, options) {
  15934. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  15935. }
  15936. function _injectSprintfProcessor() {
  15937. var values = [];
  15938. // mh: build array from second argument onwards
  15939. for (var i = 1; i < arguments.length; i++) {
  15940. values.push(arguments[i]);
  15941. }
  15942. return {
  15943. postProcess: 'sprintf',
  15944. sprintf: values
  15945. };
  15946. }
  15947. function _translate(potentialKeys, options) {
  15948. if (options && typeof options !== 'object') {
  15949. if (o.shortcutFunction === 'sprintf') {
  15950. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  15951. options = _injectSprintfProcessor.apply(null, arguments);
  15952. } else if (o.shortcutFunction === 'defaultValue') {
  15953. options = {
  15954. defaultValue: options
  15955. }
  15956. }
  15957. } else {
  15958. options = options || {};
  15959. }
  15960. if (typeof o.defaultVariables === 'object') {
  15961. options = f.extend({}, o.defaultVariables, options);
  15962. }
  15963. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  15964. if (typeof potentialKeys === 'string') {
  15965. potentialKeys = [potentialKeys];
  15966. }
  15967. var key = potentialKeys[0];
  15968. if (potentialKeys.length > 1) {
  15969. for (var i = 0; i < potentialKeys.length; i++) {
  15970. key = potentialKeys[i];
  15971. if (exists(key, options)) {
  15972. break;
  15973. }
  15974. }
  15975. }
  15976. var notFound = _getDefaultValue(key, options)
  15977. , found = _find(key, options)
  15978. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  15979. , ns = options.ns || o.ns.defaultNs
  15980. , parts;
  15981. // split ns and key
  15982. if (key.indexOf(o.nsseparator) > -1) {
  15983. parts = key.split(o.nsseparator);
  15984. ns = parts[0];
  15985. key = parts[1];
  15986. }
  15987. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  15988. if (options.lng) {
  15989. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  15990. } else {
  15991. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  15992. }
  15993. }
  15994. var postProcessor = options.postProcess || o.postProcess;
  15995. if (found !== undefined && postProcessor) {
  15996. if (postProcessors[postProcessor]) {
  15997. found = postProcessors[postProcessor](found, key, options);
  15998. }
  15999. }
  16000. // process notFound if function exists
  16001. var splitNotFound = notFound;
  16002. if (notFound.indexOf(o.nsseparator) > -1) {
  16003. parts = notFound.split(o.nsseparator);
  16004. splitNotFound = parts[1];
  16005. }
  16006. if (splitNotFound === key && o.parseMissingKey) {
  16007. notFound = o.parseMissingKey(notFound);
  16008. }
  16009. if (found === undefined) {
  16010. notFound = applyReplacement(notFound, options);
  16011. notFound = applyReuse(notFound, options);
  16012. if (postProcessor && postProcessors[postProcessor]) {
  16013. var val = _getDefaultValue(key, options);
  16014. found = postProcessors[postProcessor](val, key, options);
  16015. }
  16016. }
  16017. return (found !== undefined) ? found : notFound;
  16018. }
  16019. function _find(key, options) {
  16020. options = options || {};
  16021. var optionWithoutCount, translated
  16022. , notFound = _getDefaultValue(key, options)
  16023. , lngs = languages;
  16024. if (!resStore) { return notFound; } // no resStore to translate from
  16025. // CI mode
  16026. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  16027. // passed in lng
  16028. if (options.lngs) lngs = options.lngs;
  16029. if (options.lng) {
  16030. lngs = f.toLanguages(options.lng, options.fallbackLng);
  16031. if (!resStore[lngs[0]]) {
  16032. var oldAsync = o.getAsync;
  16033. o.getAsync = false;
  16034. i18n.sync.load(lngs, o, function(err, store) {
  16035. f.extend(resStore, store);
  16036. o.getAsync = oldAsync;
  16037. });
  16038. }
  16039. }
  16040. var ns = options.ns || o.ns.defaultNs;
  16041. if (key.indexOf(o.nsseparator) > -1) {
  16042. var parts = key.split(o.nsseparator);
  16043. ns = parts[0];
  16044. key = parts[1];
  16045. }
  16046. if (hasContext(options)) {
  16047. optionWithoutCount = f.extend({}, options);
  16048. delete optionWithoutCount.context;
  16049. optionWithoutCount.defaultValue = o.contextNotFound;
  16050. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  16051. translated = translate(contextKey, optionWithoutCount);
  16052. if (translated != o.contextNotFound) {
  16053. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  16054. } // else continue translation with original/nonContext key
  16055. }
  16056. if (needsPlural(options, lngs[0])) {
  16057. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  16058. delete optionWithoutCount.count;
  16059. delete optionWithoutCount.lng;
  16060. optionWithoutCount.defaultValue = o.pluralNotFound;
  16061. var pluralKey;
  16062. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  16063. pluralKey = ns + o.nsseparator + key;
  16064. } else {
  16065. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  16066. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  16067. if (pluralExtension >= 0) {
  16068. pluralKey = pluralKey + '_' + pluralExtension;
  16069. } else if (pluralExtension === 1) {
  16070. pluralKey = ns + o.nsseparator + key; // singular
  16071. }
  16072. }
  16073. translated = translate(pluralKey, optionWithoutCount);
  16074. if (translated != o.pluralNotFound) {
  16075. return applyReplacement(translated, {
  16076. count: options.count,
  16077. interpolationPrefix: options.interpolationPrefix,
  16078. interpolationSuffix: options.interpolationSuffix
  16079. }); // apply replacement for count only
  16080. } else if (lngs.length > 1) {
  16081. // remove failed lng
  16082. var clone = lngs.slice();
  16083. clone.shift();
  16084. options = f.extend(options, { lngs: clone });
  16085. delete options.lng;
  16086. // retry with fallbacks
  16087. translated = translate(ns + o.nsseparator + key, options);
  16088. if (translated != o.pluralNotFound) return translated;
  16089. } else {
  16090. return translated;
  16091. }
  16092. }
  16093. if (needsIndefiniteArticle(options)) {
  16094. var optionsWithoutIndef = f.extend({}, options);
  16095. delete optionsWithoutIndef.indefinite_article;
  16096. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  16097. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  16098. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  16099. translated = translate(indefiniteKey, optionsWithoutIndef);
  16100. if (translated != o.indefiniteNotFound) {
  16101. return translated;
  16102. }
  16103. }
  16104. var found;
  16105. var keys = key.split(o.keyseparator);
  16106. for (var i = 0, len = lngs.length; i < len; i++ ) {
  16107. if (found !== undefined) break;
  16108. var l = lngs[i];
  16109. var x = 0;
  16110. var value = resStore[l] && resStore[l][ns];
  16111. while (keys[x]) {
  16112. value = value && value[keys[x]];
  16113. x++;
  16114. }
  16115. if (value !== undefined) {
  16116. var valueType = Object.prototype.toString.apply(value);
  16117. if (typeof value === 'string') {
  16118. value = applyReplacement(value, options);
  16119. value = applyReuse(value, options);
  16120. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  16121. value = value.join('\n');
  16122. value = applyReplacement(value, options);
  16123. value = applyReuse(value, options);
  16124. } else if (value === null && o.fallbackOnNull === true) {
  16125. value = undefined;
  16126. } else if (value !== null) {
  16127. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  16128. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  16129. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  16130. } else {
  16131. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  16132. 'returned an object instead of string.';
  16133. f.log(value);
  16134. }
  16135. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  16136. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  16137. f.each(value, function(m) {
  16138. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  16139. });
  16140. value = copy;
  16141. }
  16142. }
  16143. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  16144. value = undefined;
  16145. found = value;
  16146. }
  16147. }
  16148. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  16149. // set flag for fallback lookup - avoid recursion
  16150. options.isFallbackLookup = true;
  16151. if (o.fallbackNS.length) {
  16152. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  16153. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  16154. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  16155. /* compare value without namespace */
  16156. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  16157. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  16158. if (foundValue !== notFoundValue) break;
  16159. }
  16160. }
  16161. } else {
  16162. found = _find(key, options); // fallback to default NS
  16163. }
  16164. options.isFallbackLookup = false;
  16165. }
  16166. return found;
  16167. }
  16168. function detectLanguage() {
  16169. var detectedLng;
  16170. var whitelist = o.lngWhitelist || [];
  16171. var userLngChoices = [];
  16172. // get from qs
  16173. var qsParm = [];
  16174. if (typeof window !== 'undefined') {
  16175. (function() {
  16176. var query = window.location.search.substring(1);
  16177. var params = query.split('&');
  16178. for (var i=0; i<params.length; i++) {
  16179. var pos = params[i].indexOf('=');
  16180. if (pos > 0) {
  16181. var key = params[i].substring(0,pos);
  16182. if (key == o.detectLngQS) {
  16183. userLngChoices.push(params[i].substring(pos+1));
  16184. }
  16185. }
  16186. }
  16187. })();
  16188. }
  16189. // get from cookie
  16190. if (o.useCookie && typeof document !== 'undefined') {
  16191. var c = f.cookie.read(o.cookieName);
  16192. if (c) userLngChoices.push(c);
  16193. }
  16194. // get from localStorage
  16195. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  16196. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  16197. }
  16198. // get from navigator
  16199. if (typeof navigator !== 'undefined') {
  16200. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  16201. for (var i=0;i<navigator.languages.length;i++) {
  16202. userLngChoices.push(navigator.languages[i]);
  16203. }
  16204. }
  16205. if (navigator.userLanguage) {
  16206. userLngChoices.push(navigator.userLanguage);
  16207. }
  16208. if (navigator.language) {
  16209. userLngChoices.push(navigator.language);
  16210. }
  16211. }
  16212. (function() {
  16213. for (var i=0;i<userLngChoices.length;i++) {
  16214. var lng = userLngChoices[i];
  16215. if (lng.indexOf('-') > -1) {
  16216. var parts = lng.split('-');
  16217. lng = o.lowerCaseLng ?
  16218. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  16219. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  16220. }
  16221. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  16222. detectedLng = lng;
  16223. break;
  16224. }
  16225. }
  16226. })();
  16227. //fallback
  16228. if (!detectedLng){
  16229. detectedLng = o.fallbackLng[0];
  16230. }
  16231. return detectedLng;
  16232. }
  16233. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  16234. /* [code, name, numbers, pluralsType] */
  16235. var _rules = [
  16236. ["ach", "Acholi", [1,2], 1],
  16237. ["af", "Afrikaans",[1,2], 2],
  16238. ["ak", "Akan", [1,2], 1],
  16239. ["am", "Amharic", [1,2], 1],
  16240. ["an", "Aragonese",[1,2], 2],
  16241. ["ar", "Arabic", [0,1,2,3,11,100],5],
  16242. ["arn", "Mapudungun",[1,2], 1],
  16243. ["ast", "Asturian", [1,2], 2],
  16244. ["ay", "Aymará", [1], 3],
  16245. ["az", "Azerbaijani",[1,2],2],
  16246. ["be", "Belarusian",[1,2,5],4],
  16247. ["bg", "Bulgarian",[1,2], 2],
  16248. ["bn", "Bengali", [1,2], 2],
  16249. ["bo", "Tibetan", [1], 3],
  16250. ["br", "Breton", [1,2], 1],
  16251. ["bs", "Bosnian", [1,2,5],4],
  16252. ["ca", "Catalan", [1,2], 2],
  16253. ["cgg", "Chiga", [1], 3],
  16254. ["cs", "Czech", [1,2,5],6],
  16255. ["csb", "Kashubian",[1,2,5],7],
  16256. ["cy", "Welsh", [1,2,3,8],8],
  16257. ["da", "Danish", [1,2], 2],
  16258. ["de", "German", [1,2], 2],
  16259. ["dev", "Development Fallback", [1,2], 2],
  16260. ["dz", "Dzongkha", [1], 3],
  16261. ["el", "Greek", [1,2], 2],
  16262. ["en", "English", [1,2], 2],
  16263. ["eo", "Esperanto",[1,2], 2],
  16264. ["es", "Spanish", [1,2], 2],
  16265. ["es_ar","Argentinean Spanish", [1,2], 2],
  16266. ["et", "Estonian", [1,2], 2],
  16267. ["eu", "Basque", [1,2], 2],
  16268. ["fa", "Persian", [1], 3],
  16269. ["fi", "Finnish", [1,2], 2],
  16270. ["fil", "Filipino", [1,2], 1],
  16271. ["fo", "Faroese", [1,2], 2],
  16272. ["fr", "French", [1,2], 9],
  16273. ["fur", "Friulian", [1,2], 2],
  16274. ["fy", "Frisian", [1,2], 2],
  16275. ["ga", "Irish", [1,2,3,7,11],10],
  16276. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  16277. ["gl", "Galician", [1,2], 2],
  16278. ["gu", "Gujarati", [1,2], 2],
  16279. ["gun", "Gun", [1,2], 1],
  16280. ["ha", "Hausa", [1,2], 2],
  16281. ["he", "Hebrew", [1,2], 2],
  16282. ["hi", "Hindi", [1,2], 2],
  16283. ["hr", "Croatian", [1,2,5],4],
  16284. ["hu", "Hungarian",[1,2], 2],
  16285. ["hy", "Armenian", [1,2], 2],
  16286. ["ia", "Interlingua",[1,2],2],
  16287. ["id", "Indonesian",[1], 3],
  16288. ["is", "Icelandic",[1,2], 12],
  16289. ["it", "Italian", [1,2], 2],
  16290. ["ja", "Japanese", [1], 3],
  16291. ["jbo", "Lojban", [1], 3],
  16292. ["jv", "Javanese", [0,1], 13],
  16293. ["ka", "Georgian", [1], 3],
  16294. ["kk", "Kazakh", [1], 3],
  16295. ["km", "Khmer", [1], 3],
  16296. ["kn", "Kannada", [1,2], 2],
  16297. ["ko", "Korean", [1], 3],
  16298. ["ku", "Kurdish", [1,2], 2],
  16299. ["kw", "Cornish", [1,2,3,4],14],
  16300. ["ky", "Kyrgyz", [1], 3],
  16301. ["lb", "Letzeburgesch",[1,2],2],
  16302. ["ln", "Lingala", [1,2], 1],
  16303. ["lo", "Lao", [1], 3],
  16304. ["lt", "Lithuanian",[1,2,10],15],
  16305. ["lv", "Latvian", [1,2,0],16],
  16306. ["mai", "Maithili", [1,2], 2],
  16307. ["mfe", "Mauritian Creole",[1,2],1],
  16308. ["mg", "Malagasy", [1,2], 1],
  16309. ["mi", "Maori", [1,2], 1],
  16310. ["mk", "Macedonian",[1,2],17],
  16311. ["ml", "Malayalam",[1,2], 2],
  16312. ["mn", "Mongolian",[1,2], 2],
  16313. ["mnk", "Mandinka", [0,1,2],18],
  16314. ["mr", "Marathi", [1,2], 2],
  16315. ["ms", "Malay", [1], 3],
  16316. ["mt", "Maltese", [1,2,11,20],19],
  16317. ["nah", "Nahuatl", [1,2], 2],
  16318. ["nap", "Neapolitan",[1,2], 2],
  16319. ["nb", "Norwegian Bokmal",[1,2],2],
  16320. ["ne", "Nepali", [1,2], 2],
  16321. ["nl", "Dutch", [1,2], 2],
  16322. ["nn", "Norwegian Nynorsk",[1,2],2],
  16323. ["no", "Norwegian",[1,2], 2],
  16324. ["nso", "Northern Sotho",[1,2],2],
  16325. ["oc", "Occitan", [1,2], 1],
  16326. ["or", "Oriya", [2,1], 2],
  16327. ["pa", "Punjabi", [1,2], 2],
  16328. ["pap", "Papiamento",[1,2], 2],
  16329. ["pl", "Polish", [1,2,5],7],
  16330. ["pms", "Piemontese",[1,2], 2],
  16331. ["ps", "Pashto", [1,2], 2],
  16332. ["pt", "Portuguese",[1,2], 2],
  16333. ["pt_br","Brazilian Portuguese",[1,2], 2],
  16334. ["rm", "Romansh", [1,2], 2],
  16335. ["ro", "Romanian", [1,2,20],20],
  16336. ["ru", "Russian", [1,2,5],4],
  16337. ["sah", "Yakut", [1], 3],
  16338. ["sco", "Scots", [1,2], 2],
  16339. ["se", "Northern Sami",[1,2], 2],
  16340. ["si", "Sinhala", [1,2], 2],
  16341. ["sk", "Slovak", [1,2,5],6],
  16342. ["sl", "Slovenian",[5,1,2,3],21],
  16343. ["so", "Somali", [1,2], 2],
  16344. ["son", "Songhay", [1,2], 2],
  16345. ["sq", "Albanian", [1,2], 2],
  16346. ["sr", "Serbian", [1,2,5],4],
  16347. ["su", "Sundanese",[1], 3],
  16348. ["sv", "Swedish", [1,2], 2],
  16349. ["sw", "Swahili", [1,2], 2],
  16350. ["ta", "Tamil", [1,2], 2],
  16351. ["te", "Telugu", [1,2], 2],
  16352. ["tg", "Tajik", [1,2], 1],
  16353. ["th", "Thai", [1], 3],
  16354. ["ti", "Tigrinya", [1,2], 1],
  16355. ["tk", "Turkmen", [1,2], 2],
  16356. ["tr", "Turkish", [1,2], 1],
  16357. ["tt", "Tatar", [1], 3],
  16358. ["ug", "Uyghur", [1], 3],
  16359. ["uk", "Ukrainian",[1,2,5],4],
  16360. ["ur", "Urdu", [1,2], 2],
  16361. ["uz", "Uzbek", [1,2], 1],
  16362. ["vi", "Vietnamese",[1], 3],
  16363. ["wa", "Walloon", [1,2], 1],
  16364. ["wo", "Wolof", [1], 3],
  16365. ["yo", "Yoruba", [1,2], 2],
  16366. ["zh", "Chinese", [1], 3]
  16367. ];
  16368. var _rulesPluralsTypes = {
  16369. 1: function(n) {return Number(n > 1);},
  16370. 2: function(n) {return Number(n != 1);},
  16371. 3: function(n) {return 0;},
  16372. 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);},
  16373. 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);},
  16374. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  16375. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16376. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  16377. 9: function(n) {return Number(n >= 2);},
  16378. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  16379. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  16380. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  16381. 13: function(n) {return Number(n !== 0);},
  16382. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  16383. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16384. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  16385. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  16386. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  16387. 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);},
  16388. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  16389. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  16390. };
  16391. var pluralExtensions = {
  16392. rules: (function () {
  16393. var l, rules = {};
  16394. for (l=_rules.length; l-- ;) {
  16395. rules[_rules[l][0]] = {
  16396. name: _rules[l][1],
  16397. numbers: _rules[l][2],
  16398. plurals: _rulesPluralsTypes[_rules[l][3]]
  16399. }
  16400. }
  16401. return rules;
  16402. }()),
  16403. // you can add your own pluralExtensions
  16404. addRule: function(lng, obj) {
  16405. pluralExtensions.rules[lng] = obj;
  16406. },
  16407. setCurrentLng: function(lng) {
  16408. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  16409. var parts = lng.split('-');
  16410. pluralExtensions.currentRule = {
  16411. lng: lng,
  16412. rule: pluralExtensions.rules[parts[0]]
  16413. };
  16414. }
  16415. },
  16416. needsPlural: function(lng, count) {
  16417. var parts = lng.split('-');
  16418. var ext;
  16419. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16420. ext = pluralExtensions.currentRule.rule;
  16421. } else {
  16422. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  16423. }
  16424. if (ext && ext.numbers.length <= 1) {
  16425. return false;
  16426. } else {
  16427. return this.get(lng, count) !== 1;
  16428. }
  16429. },
  16430. get: function(lng, count) {
  16431. var parts = lng.split('-');
  16432. function getResult(l, c) {
  16433. var ext;
  16434. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16435. ext = pluralExtensions.currentRule.rule;
  16436. } else {
  16437. ext = pluralExtensions.rules[l];
  16438. }
  16439. if (ext) {
  16440. var i;
  16441. if (ext.noAbs) {
  16442. i = ext.plurals(c);
  16443. } else {
  16444. i = ext.plurals(Math.abs(c));
  16445. }
  16446. var number = ext.numbers[i];
  16447. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  16448. if (number === 2) {
  16449. number = -1; // regular plural
  16450. } else if (number === 1) {
  16451. number = 1; // singular
  16452. }
  16453. }//console.log(count + '-' + number);
  16454. return number;
  16455. } else {
  16456. return c === 1 ? '1' : '-1';
  16457. }
  16458. }
  16459. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  16460. }
  16461. };
  16462. var postProcessors = {};
  16463. var addPostProcessor = function(name, fc) {
  16464. postProcessors[name] = fc;
  16465. };
  16466. // sprintf support
  16467. var sprintf = (function() {
  16468. function get_type(variable) {
  16469. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  16470. }
  16471. function str_repeat(input, multiplier) {
  16472. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  16473. return output.join('');
  16474. }
  16475. var str_format = function() {
  16476. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  16477. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  16478. }
  16479. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  16480. };
  16481. str_format.format = function(parse_tree, argv) {
  16482. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  16483. for (i = 0; i < tree_length; i++) {
  16484. node_type = get_type(parse_tree[i]);
  16485. if (node_type === 'string') {
  16486. output.push(parse_tree[i]);
  16487. }
  16488. else if (node_type === 'array') {
  16489. match = parse_tree[i]; // convenience purposes only
  16490. if (match[2]) { // keyword argument
  16491. arg = argv[cursor];
  16492. for (k = 0; k < match[2].length; k++) {
  16493. if (!arg.hasOwnProperty(match[2][k])) {
  16494. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  16495. }
  16496. arg = arg[match[2][k]];
  16497. }
  16498. }
  16499. else if (match[1]) { // positional argument (explicit)
  16500. arg = argv[match[1]];
  16501. }
  16502. else { // positional argument (implicit)
  16503. arg = argv[cursor++];
  16504. }
  16505. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  16506. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  16507. }
  16508. switch (match[8]) {
  16509. case 'b': arg = arg.toString(2); break;
  16510. case 'c': arg = String.fromCharCode(arg); break;
  16511. case 'd': arg = parseInt(arg, 10); break;
  16512. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  16513. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  16514. case 'o': arg = arg.toString(8); break;
  16515. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  16516. case 'u': arg = Math.abs(arg); break;
  16517. case 'x': arg = arg.toString(16); break;
  16518. case 'X': arg = arg.toString(16).toUpperCase(); break;
  16519. }
  16520. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  16521. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  16522. pad_length = match[6] - String(arg).length;
  16523. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  16524. output.push(match[5] ? arg + pad : pad + arg);
  16525. }
  16526. }
  16527. return output.join('');
  16528. };
  16529. str_format.cache = {};
  16530. str_format.parse = function(fmt) {
  16531. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  16532. while (_fmt) {
  16533. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  16534. parse_tree.push(match[0]);
  16535. }
  16536. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  16537. parse_tree.push('%');
  16538. }
  16539. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  16540. if (match[2]) {
  16541. arg_names |= 1;
  16542. var field_list = [], replacement_field = match[2], field_match = [];
  16543. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16544. field_list.push(field_match[1]);
  16545. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  16546. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16547. field_list.push(field_match[1]);
  16548. }
  16549. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  16550. field_list.push(field_match[1]);
  16551. }
  16552. else {
  16553. throw('[sprintf] huh?');
  16554. }
  16555. }
  16556. }
  16557. else {
  16558. throw('[sprintf] huh?');
  16559. }
  16560. match[2] = field_list;
  16561. }
  16562. else {
  16563. arg_names |= 2;
  16564. }
  16565. if (arg_names === 3) {
  16566. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  16567. }
  16568. parse_tree.push(match);
  16569. }
  16570. else {
  16571. throw('[sprintf] huh?');
  16572. }
  16573. _fmt = _fmt.substring(match[0].length);
  16574. }
  16575. return parse_tree;
  16576. };
  16577. return str_format;
  16578. })();
  16579. var vsprintf = function(fmt, argv) {
  16580. argv.unshift(fmt);
  16581. return sprintf.apply(null, argv);
  16582. };
  16583. addPostProcessor("sprintf", function(val, key, opts) {
  16584. if (!opts.sprintf) return val;
  16585. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  16586. return vsprintf(val, opts.sprintf);
  16587. } else if (typeof opts.sprintf === 'object') {
  16588. return sprintf(val, opts.sprintf);
  16589. }
  16590. return val;
  16591. });
  16592. // public api interface
  16593. i18n.init = init;
  16594. i18n.setLng = setLng;
  16595. i18n.preload = preload;
  16596. i18n.addResourceBundle = addResourceBundle;
  16597. i18n.hasResourceBundle = hasResourceBundle;
  16598. i18n.addResource = addResource;
  16599. i18n.addResources = addResources;
  16600. i18n.removeResourceBundle = removeResourceBundle;
  16601. i18n.loadNamespace = loadNamespace;
  16602. i18n.loadNamespaces = loadNamespaces;
  16603. i18n.setDefaultNamespace = setDefaultNamespace;
  16604. i18n.t = translate;
  16605. i18n.translate = translate;
  16606. i18n.exists = exists;
  16607. i18n.detectLanguage = f.detectLanguage;
  16608. i18n.pluralExtensions = pluralExtensions;
  16609. i18n.sync = sync;
  16610. i18n.functions = f;
  16611. i18n.lng = lng;
  16612. i18n.addPostProcessor = addPostProcessor;
  16613. i18n.options = o;
  16614. })();
  16615. },{"jquery":"jquery"}],62:[function(require,module,exports){
  16616. // Top level file is just a mixin of submodules & constants
  16617. 'use strict';
  16618. var assign = require('./lib/utils/common').assign;
  16619. var deflate = require('./lib/deflate');
  16620. var inflate = require('./lib/inflate');
  16621. var constants = require('./lib/zlib/constants');
  16622. var pako = {};
  16623. assign(pako, deflate, inflate, constants);
  16624. module.exports = pako;
  16625. },{"./lib/deflate":63,"./lib/inflate":64,"./lib/utils/common":65,"./lib/zlib/constants":68}],63:[function(require,module,exports){
  16626. 'use strict';
  16627. var zlib_deflate = require('./zlib/deflate.js');
  16628. var utils = require('./utils/common');
  16629. var strings = require('./utils/strings');
  16630. var msg = require('./zlib/messages');
  16631. var zstream = require('./zlib/zstream');
  16632. /* Public constants ==========================================================*/
  16633. /* ===========================================================================*/
  16634. var Z_NO_FLUSH = 0;
  16635. var Z_FINISH = 4;
  16636. var Z_OK = 0;
  16637. var Z_STREAM_END = 1;
  16638. var Z_DEFAULT_COMPRESSION = -1;
  16639. var Z_DEFAULT_STRATEGY = 0;
  16640. var Z_DEFLATED = 8;
  16641. /* ===========================================================================*/
  16642. /**
  16643. * class Deflate
  16644. *
  16645. * Generic JS-style wrapper for zlib calls. If you don't need
  16646. * streaming behaviour - use more simple functions: [[deflate]],
  16647. * [[deflateRaw]] and [[gzip]].
  16648. **/
  16649. /* internal
  16650. * Deflate.chunks -> Array
  16651. *
  16652. * Chunks of output data, if [[Deflate#onData]] not overriden.
  16653. **/
  16654. /**
  16655. * Deflate.result -> Uint8Array|Array
  16656. *
  16657. * Compressed result, generated by default [[Deflate#onData]]
  16658. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  16659. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  16660. **/
  16661. /**
  16662. * Deflate.err -> Number
  16663. *
  16664. * Error code after deflate finished. 0 (Z_OK) on success.
  16665. * You will not need it in real life, because deflate errors
  16666. * are possible only on wrong options or bad `onData` / `onEnd`
  16667. * custom handlers.
  16668. **/
  16669. /**
  16670. * Deflate.msg -> String
  16671. *
  16672. * Error message, if [[Deflate.err]] != 0
  16673. **/
  16674. /**
  16675. * new Deflate(options)
  16676. * - options (Object): zlib deflate options.
  16677. *
  16678. * Creates new deflator instance with specified params. Throws exception
  16679. * on bad params. Supported options:
  16680. *
  16681. * - `level`
  16682. * - `windowBits`
  16683. * - `memLevel`
  16684. * - `strategy`
  16685. *
  16686. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  16687. * for more information on these.
  16688. *
  16689. * Additional options, for internal needs:
  16690. *
  16691. * - `chunkSize` - size of generated data chunks (16K by default)
  16692. * - `raw` (Boolean) - do raw deflate
  16693. * - `gzip` (Boolean) - create gzip wrapper
  16694. * - `to` (String) - if equal to 'string', then result will be "binary string"
  16695. * (each char code [0..255])
  16696. * - `header` (Object) - custom header for gzip
  16697. * - `text` (Boolean) - true if compressed data believed to be text
  16698. * - `time` (Number) - modification time, unix timestamp
  16699. * - `os` (Number) - operation system code
  16700. * - `extra` (Array) - array of bytes with extra data (max 65536)
  16701. * - `name` (String) - file name (binary string)
  16702. * - `comment` (String) - comment (binary string)
  16703. * - `hcrc` (Boolean) - true if header crc should be added
  16704. *
  16705. * ##### Example:
  16706. *
  16707. * ```javascript
  16708. * var pako = require('pako')
  16709. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  16710. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  16711. *
  16712. * var deflate = new pako.Deflate({ level: 3});
  16713. *
  16714. * deflate.push(chunk1, false);
  16715. * deflate.push(chunk2, true); // true -> last chunk
  16716. *
  16717. * if (deflate.err) { throw new Error(deflate.err); }
  16718. *
  16719. * console.log(deflate.result);
  16720. * ```
  16721. **/
  16722. var Deflate = function(options) {
  16723. this.options = utils.assign({
  16724. level: Z_DEFAULT_COMPRESSION,
  16725. method: Z_DEFLATED,
  16726. chunkSize: 16384,
  16727. windowBits: 15,
  16728. memLevel: 8,
  16729. strategy: Z_DEFAULT_STRATEGY,
  16730. to: ''
  16731. }, options || {});
  16732. var opt = this.options;
  16733. if (opt.raw && (opt.windowBits > 0)) {
  16734. opt.windowBits = -opt.windowBits;
  16735. }
  16736. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  16737. opt.windowBits += 16;
  16738. }
  16739. this.err = 0; // error code, if happens (0 = Z_OK)
  16740. this.msg = ''; // error message
  16741. this.ended = false; // used to avoid multiple onEnd() calls
  16742. this.chunks = []; // chunks of compressed data
  16743. this.strm = new zstream();
  16744. this.strm.avail_out = 0;
  16745. var status = zlib_deflate.deflateInit2(
  16746. this.strm,
  16747. opt.level,
  16748. opt.method,
  16749. opt.windowBits,
  16750. opt.memLevel,
  16751. opt.strategy
  16752. );
  16753. if (status !== Z_OK) {
  16754. throw new Error(msg[status]);
  16755. }
  16756. if (opt.header) {
  16757. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  16758. }
  16759. };
  16760. /**
  16761. * Deflate#push(data[, mode]) -> Boolean
  16762. * - data (Uint8Array|Array|String): input data. Strings will be converted to
  16763. * utf8 byte sequence.
  16764. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  16765. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  16766. *
  16767. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  16768. * new compressed chunks. Returns `true` on success. The last data block must have
  16769. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  16770. * [[Deflate#onEnd]].
  16771. *
  16772. * On fail call [[Deflate#onEnd]] with error code and return false.
  16773. *
  16774. * We strongly recommend to use `Uint8Array` on input for best speed (output
  16775. * array format is detected automatically). Also, don't skip last param and always
  16776. * use the same type in your code (boolean or number). That will improve JS speed.
  16777. *
  16778. * For regular `Array`-s make sure all elements are [0..255].
  16779. *
  16780. * ##### Example
  16781. *
  16782. * ```javascript
  16783. * push(chunk, false); // push one of data chunks
  16784. * ...
  16785. * push(chunk, true); // push last chunk
  16786. * ```
  16787. **/
  16788. Deflate.prototype.push = function(data, mode) {
  16789. var strm = this.strm;
  16790. var chunkSize = this.options.chunkSize;
  16791. var status, _mode;
  16792. if (this.ended) { return false; }
  16793. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  16794. // Convert data if needed
  16795. if (typeof data === 'string') {
  16796. // If we need to compress text, change encoding to utf8.
  16797. strm.input = strings.string2buf(data);
  16798. } else {
  16799. strm.input = data;
  16800. }
  16801. strm.next_in = 0;
  16802. strm.avail_in = strm.input.length;
  16803. do {
  16804. if (strm.avail_out === 0) {
  16805. strm.output = new utils.Buf8(chunkSize);
  16806. strm.next_out = 0;
  16807. strm.avail_out = chunkSize;
  16808. }
  16809. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  16810. if (status !== Z_STREAM_END && status !== Z_OK) {
  16811. this.onEnd(status);
  16812. this.ended = true;
  16813. return false;
  16814. }
  16815. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  16816. if (this.options.to === 'string') {
  16817. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  16818. } else {
  16819. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  16820. }
  16821. }
  16822. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  16823. // Finalize on the last chunk.
  16824. if (_mode === Z_FINISH) {
  16825. status = zlib_deflate.deflateEnd(this.strm);
  16826. this.onEnd(status);
  16827. this.ended = true;
  16828. return status === Z_OK;
  16829. }
  16830. return true;
  16831. };
  16832. /**
  16833. * Deflate#onData(chunk) -> Void
  16834. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  16835. * on js engine support. When string output requested, each chunk
  16836. * will be string.
  16837. *
  16838. * By default, stores data blocks in `chunks[]` property and glue
  16839. * those in `onEnd`. Override this handler, if you need another behaviour.
  16840. **/
  16841. Deflate.prototype.onData = function(chunk) {
  16842. this.chunks.push(chunk);
  16843. };
  16844. /**
  16845. * Deflate#onEnd(status) -> Void
  16846. * - status (Number): deflate status. 0 (Z_OK) on success,
  16847. * other if not.
  16848. *
  16849. * Called once after you tell deflate that input stream complete
  16850. * or error happenned. By default - join collected chunks,
  16851. * free memory and fill `results` / `err` properties.
  16852. **/
  16853. Deflate.prototype.onEnd = function(status) {
  16854. // On success - join
  16855. if (status === Z_OK) {
  16856. if (this.options.to === 'string') {
  16857. this.result = this.chunks.join('');
  16858. } else {
  16859. this.result = utils.flattenChunks(this.chunks);
  16860. }
  16861. }
  16862. this.chunks = [];
  16863. this.err = status;
  16864. this.msg = this.strm.msg;
  16865. };
  16866. /**
  16867. * deflate(data[, options]) -> Uint8Array|Array|String
  16868. * - data (Uint8Array|Array|String): input data to compress.
  16869. * - options (Object): zlib deflate options.
  16870. *
  16871. * Compress `data` with deflate alrorythm and `options`.
  16872. *
  16873. * Supported options are:
  16874. *
  16875. * - level
  16876. * - windowBits
  16877. * - memLevel
  16878. * - strategy
  16879. *
  16880. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  16881. * for more information on these.
  16882. *
  16883. * Sugar (options):
  16884. *
  16885. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  16886. * negative windowBits implicitly.
  16887. * - `to` (String) - if equal to 'string', then result will be "binary string"
  16888. * (each char code [0..255])
  16889. *
  16890. * ##### Example:
  16891. *
  16892. * ```javascript
  16893. * var pako = require('pako')
  16894. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  16895. *
  16896. * console.log(pako.deflate(data));
  16897. * ```
  16898. **/
  16899. function deflate(input, options) {
  16900. var deflator = new Deflate(options);
  16901. deflator.push(input, true);
  16902. // That will never happens, if you don't cheat with options :)
  16903. if (deflator.err) { throw deflator.msg; }
  16904. return deflator.result;
  16905. }
  16906. /**
  16907. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  16908. * - data (Uint8Array|Array|String): input data to compress.
  16909. * - options (Object): zlib deflate options.
  16910. *
  16911. * The same as [[deflate]], but creates raw data, without wrapper
  16912. * (header and adler32 crc).
  16913. **/
  16914. function deflateRaw(input, options) {
  16915. options = options || {};
  16916. options.raw = true;
  16917. return deflate(input, options);
  16918. }
  16919. /**
  16920. * gzip(data[, options]) -> Uint8Array|Array|String
  16921. * - data (Uint8Array|Array|String): input data to compress.
  16922. * - options (Object): zlib deflate options.
  16923. *
  16924. * The same as [[deflate]], but create gzip wrapper instead of
  16925. * deflate one.
  16926. **/
  16927. function gzip(input, options) {
  16928. options = options || {};
  16929. options.gzip = true;
  16930. return deflate(input, options);
  16931. }
  16932. exports.Deflate = Deflate;
  16933. exports.deflate = deflate;
  16934. exports.deflateRaw = deflateRaw;
  16935. exports.gzip = gzip;
  16936. },{"./utils/common":65,"./utils/strings":66,"./zlib/deflate.js":70,"./zlib/messages":75,"./zlib/zstream":77}],64:[function(require,module,exports){
  16937. 'use strict';
  16938. var zlib_inflate = require('./zlib/inflate.js');
  16939. var utils = require('./utils/common');
  16940. var strings = require('./utils/strings');
  16941. var c = require('./zlib/constants');
  16942. var msg = require('./zlib/messages');
  16943. var zstream = require('./zlib/zstream');
  16944. var gzheader = require('./zlib/gzheader');
  16945. /**
  16946. * class Inflate
  16947. *
  16948. * Generic JS-style wrapper for zlib calls. If you don't need
  16949. * streaming behaviour - use more simple functions: [[inflate]]
  16950. * and [[inflateRaw]].
  16951. **/
  16952. /* internal
  16953. * inflate.chunks -> Array
  16954. *
  16955. * Chunks of output data, if [[Inflate#onData]] not overriden.
  16956. **/
  16957. /**
  16958. * Inflate.result -> Uint8Array|Array|String
  16959. *
  16960. * Uncompressed result, generated by default [[Inflate#onData]]
  16961. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  16962. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  16963. **/
  16964. /**
  16965. * Inflate.err -> Number
  16966. *
  16967. * Error code after inflate finished. 0 (Z_OK) on success.
  16968. * Should be checked if broken data possible.
  16969. **/
  16970. /**
  16971. * Inflate.msg -> String
  16972. *
  16973. * Error message, if [[Inflate.err]] != 0
  16974. **/
  16975. /**
  16976. * new Inflate(options)
  16977. * - options (Object): zlib inflate options.
  16978. *
  16979. * Creates new inflator instance with specified params. Throws exception
  16980. * on bad params. Supported options:
  16981. *
  16982. * - `windowBits`
  16983. *
  16984. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  16985. * for more information on these.
  16986. *
  16987. * Additional options, for internal needs:
  16988. *
  16989. * - `chunkSize` - size of generated data chunks (16K by default)
  16990. * - `raw` (Boolean) - do raw inflate
  16991. * - `to` (String) - if equal to 'string', then result will be converted
  16992. * from utf8 to utf16 (javascript) string. When string output requested,
  16993. * chunk length can differ from `chunkSize`, depending on content.
  16994. *
  16995. * By default, when no options set, autodetect deflate/gzip data format via
  16996. * wrapper header.
  16997. *
  16998. * ##### Example:
  16999. *
  17000. * ```javascript
  17001. * var pako = require('pako')
  17002. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17003. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17004. *
  17005. * var inflate = new pako.Inflate({ level: 3});
  17006. *
  17007. * inflate.push(chunk1, false);
  17008. * inflate.push(chunk2, true); // true -> last chunk
  17009. *
  17010. * if (inflate.err) { throw new Error(inflate.err); }
  17011. *
  17012. * console.log(inflate.result);
  17013. * ```
  17014. **/
  17015. var Inflate = function(options) {
  17016. this.options = utils.assign({
  17017. chunkSize: 16384,
  17018. windowBits: 0,
  17019. to: ''
  17020. }, options || {});
  17021. var opt = this.options;
  17022. // Force window size for `raw` data, if not set directly,
  17023. // because we have no header for autodetect.
  17024. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  17025. opt.windowBits = -opt.windowBits;
  17026. if (opt.windowBits === 0) { opt.windowBits = -15; }
  17027. }
  17028. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  17029. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  17030. !(options && options.windowBits)) {
  17031. opt.windowBits += 32;
  17032. }
  17033. // Gzip header has no info about windows size, we can do autodetect only
  17034. // for deflate. So, if window size not set, force it to max when gzip possible
  17035. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  17036. // bit 3 (16) -> gzipped data
  17037. // bit 4 (32) -> autodetect gzip/deflate
  17038. if ((opt.windowBits & 15) === 0) {
  17039. opt.windowBits |= 15;
  17040. }
  17041. }
  17042. this.err = 0; // error code, if happens (0 = Z_OK)
  17043. this.msg = ''; // error message
  17044. this.ended = false; // used to avoid multiple onEnd() calls
  17045. this.chunks = []; // chunks of compressed data
  17046. this.strm = new zstream();
  17047. this.strm.avail_out = 0;
  17048. var status = zlib_inflate.inflateInit2(
  17049. this.strm,
  17050. opt.windowBits
  17051. );
  17052. if (status !== c.Z_OK) {
  17053. throw new Error(msg[status]);
  17054. }
  17055. this.header = new gzheader();
  17056. zlib_inflate.inflateGetHeader(this.strm, this.header);
  17057. };
  17058. /**
  17059. * Inflate#push(data[, mode]) -> Boolean
  17060. * - data (Uint8Array|Array|String): input data
  17061. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17062. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17063. *
  17064. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  17065. * new output chunks. Returns `true` on success. The last data block must have
  17066. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17067. * [[Inflate#onEnd]].
  17068. *
  17069. * On fail call [[Inflate#onEnd]] with error code and return false.
  17070. *
  17071. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17072. * format is detected automatically). Also, don't skip last param and always
  17073. * use the same type in your code (boolean or number). That will improve JS speed.
  17074. *
  17075. * For regular `Array`-s make sure all elements are [0..255].
  17076. *
  17077. * ##### Example
  17078. *
  17079. * ```javascript
  17080. * push(chunk, false); // push one of data chunks
  17081. * ...
  17082. * push(chunk, true); // push last chunk
  17083. * ```
  17084. **/
  17085. Inflate.prototype.push = function(data, mode) {
  17086. var strm = this.strm;
  17087. var chunkSize = this.options.chunkSize;
  17088. var status, _mode;
  17089. var next_out_utf8, tail, utf8str;
  17090. if (this.ended) { return false; }
  17091. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  17092. // Convert data if needed
  17093. if (typeof data === 'string') {
  17094. // Only binary strings can be decompressed on practice
  17095. strm.input = strings.binstring2buf(data);
  17096. } else {
  17097. strm.input = data;
  17098. }
  17099. strm.next_in = 0;
  17100. strm.avail_in = strm.input.length;
  17101. do {
  17102. if (strm.avail_out === 0) {
  17103. strm.output = new utils.Buf8(chunkSize);
  17104. strm.next_out = 0;
  17105. strm.avail_out = chunkSize;
  17106. }
  17107. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  17108. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  17109. this.onEnd(status);
  17110. this.ended = true;
  17111. return false;
  17112. }
  17113. if (strm.next_out) {
  17114. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  17115. if (this.options.to === 'string') {
  17116. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  17117. tail = strm.next_out - next_out_utf8;
  17118. utf8str = strings.buf2string(strm.output, next_out_utf8);
  17119. // move tail
  17120. strm.next_out = tail;
  17121. strm.avail_out = chunkSize - tail;
  17122. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  17123. this.onData(utf8str);
  17124. } else {
  17125. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17126. }
  17127. }
  17128. }
  17129. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  17130. if (status === c.Z_STREAM_END) {
  17131. _mode = c.Z_FINISH;
  17132. }
  17133. // Finalize on the last chunk.
  17134. if (_mode === c.Z_FINISH) {
  17135. status = zlib_inflate.inflateEnd(this.strm);
  17136. this.onEnd(status);
  17137. this.ended = true;
  17138. return status === c.Z_OK;
  17139. }
  17140. return true;
  17141. };
  17142. /**
  17143. * Inflate#onData(chunk) -> Void
  17144. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17145. * on js engine support. When string output requested, each chunk
  17146. * will be string.
  17147. *
  17148. * By default, stores data blocks in `chunks[]` property and glue
  17149. * those in `onEnd`. Override this handler, if you need another behaviour.
  17150. **/
  17151. Inflate.prototype.onData = function(chunk) {
  17152. this.chunks.push(chunk);
  17153. };
  17154. /**
  17155. * Inflate#onEnd(status) -> Void
  17156. * - status (Number): inflate status. 0 (Z_OK) on success,
  17157. * other if not.
  17158. *
  17159. * Called once after you tell inflate that input stream complete
  17160. * or error happenned. By default - join collected chunks,
  17161. * free memory and fill `results` / `err` properties.
  17162. **/
  17163. Inflate.prototype.onEnd = function(status) {
  17164. // On success - join
  17165. if (status === c.Z_OK) {
  17166. if (this.options.to === 'string') {
  17167. // Glue & convert here, until we teach pako to send
  17168. // utf8 alligned strings to onData
  17169. this.result = this.chunks.join('');
  17170. } else {
  17171. this.result = utils.flattenChunks(this.chunks);
  17172. }
  17173. }
  17174. this.chunks = [];
  17175. this.err = status;
  17176. this.msg = this.strm.msg;
  17177. };
  17178. /**
  17179. * inflate(data[, options]) -> Uint8Array|Array|String
  17180. * - data (Uint8Array|Array|String): input data to decompress.
  17181. * - options (Object): zlib inflate options.
  17182. *
  17183. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  17184. * format via wrapper header by default. That's why we don't provide
  17185. * separate `ungzip` method.
  17186. *
  17187. * Supported options are:
  17188. *
  17189. * - windowBits
  17190. *
  17191. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17192. * for more information.
  17193. *
  17194. * Sugar (options):
  17195. *
  17196. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17197. * negative windowBits implicitly.
  17198. * - `to` (String) - if equal to 'string', then result will be converted
  17199. * from utf8 to utf16 (javascript) string. When string output requested,
  17200. * chunk length can differ from `chunkSize`, depending on content.
  17201. *
  17202. *
  17203. * ##### Example:
  17204. *
  17205. * ```javascript
  17206. * var pako = require('pako')
  17207. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  17208. * , output;
  17209. *
  17210. * try {
  17211. * output = pako.inflate(input);
  17212. * } catch (err)
  17213. * console.log(err);
  17214. * }
  17215. * ```
  17216. **/
  17217. function inflate(input, options) {
  17218. var inflator = new Inflate(options);
  17219. inflator.push(input, true);
  17220. // That will never happens, if you don't cheat with options :)
  17221. if (inflator.err) { throw inflator.msg; }
  17222. return inflator.result;
  17223. }
  17224. /**
  17225. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  17226. * - data (Uint8Array|Array|String): input data to decompress.
  17227. * - options (Object): zlib inflate options.
  17228. *
  17229. * The same as [[inflate]], but creates raw data, without wrapper
  17230. * (header and adler32 crc).
  17231. **/
  17232. function inflateRaw(input, options) {
  17233. options = options || {};
  17234. options.raw = true;
  17235. return inflate(input, options);
  17236. }
  17237. /**
  17238. * ungzip(data[, options]) -> Uint8Array|Array|String
  17239. * - data (Uint8Array|Array|String): input data to decompress.
  17240. * - options (Object): zlib inflate options.
  17241. *
  17242. * Just shortcut to [[inflate]], because it autodetects format
  17243. * by header.content. Done for convenience.
  17244. **/
  17245. exports.Inflate = Inflate;
  17246. exports.inflate = inflate;
  17247. exports.inflateRaw = inflateRaw;
  17248. exports.ungzip = inflate;
  17249. },{"./utils/common":65,"./utils/strings":66,"./zlib/constants":68,"./zlib/gzheader":71,"./zlib/inflate.js":73,"./zlib/messages":75,"./zlib/zstream":77}],65:[function(require,module,exports){
  17250. 'use strict';
  17251. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  17252. (typeof Uint16Array !== 'undefined') &&
  17253. (typeof Int32Array !== 'undefined');
  17254. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  17255. var sources = Array.prototype.slice.call(arguments, 1);
  17256. while (sources.length) {
  17257. var source = sources.shift();
  17258. if (!source) { continue; }
  17259. if (typeof(source) !== 'object') {
  17260. throw new TypeError(source + 'must be non-object');
  17261. }
  17262. for (var p in source) {
  17263. if (source.hasOwnProperty(p)) {
  17264. obj[p] = source[p];
  17265. }
  17266. }
  17267. }
  17268. return obj;
  17269. };
  17270. // reduce buffer size, avoiding mem copy
  17271. exports.shrinkBuf = function (buf, size) {
  17272. if (buf.length === size) { return buf; }
  17273. if (buf.subarray) { return buf.subarray(0, size); }
  17274. buf.length = size;
  17275. return buf;
  17276. };
  17277. var fnTyped = {
  17278. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17279. if (src.subarray && dest.subarray) {
  17280. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  17281. return;
  17282. }
  17283. // Fallback to ordinary array
  17284. for(var i=0; i<len; i++) {
  17285. dest[dest_offs + i] = src[src_offs + i];
  17286. }
  17287. },
  17288. // Join array of chunks to single array.
  17289. flattenChunks: function(chunks) {
  17290. var i, l, len, pos, chunk, result;
  17291. // calculate data length
  17292. len = 0;
  17293. for (i=0, l=chunks.length; i<l; i++) {
  17294. len += chunks[i].length;
  17295. }
  17296. // join chunks
  17297. result = new Uint8Array(len);
  17298. pos = 0;
  17299. for (i=0, l=chunks.length; i<l; i++) {
  17300. chunk = chunks[i];
  17301. result.set(chunk, pos);
  17302. pos += chunk.length;
  17303. }
  17304. return result;
  17305. }
  17306. };
  17307. var fnUntyped = {
  17308. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17309. for(var i=0; i<len; i++) {
  17310. dest[dest_offs + i] = src[src_offs + i];
  17311. }
  17312. },
  17313. // Join array of chunks to single array.
  17314. flattenChunks: function(chunks) {
  17315. return [].concat.apply([], chunks);
  17316. }
  17317. };
  17318. // Enable/Disable typed arrays use, for testing
  17319. //
  17320. exports.setTyped = function (on) {
  17321. if (on) {
  17322. exports.Buf8 = Uint8Array;
  17323. exports.Buf16 = Uint16Array;
  17324. exports.Buf32 = Int32Array;
  17325. exports.assign(exports, fnTyped);
  17326. } else {
  17327. exports.Buf8 = Array;
  17328. exports.Buf16 = Array;
  17329. exports.Buf32 = Array;
  17330. exports.assign(exports, fnUntyped);
  17331. }
  17332. };
  17333. exports.setTyped(TYPED_OK);
  17334. },{}],66:[function(require,module,exports){
  17335. // String encode/decode helpers
  17336. 'use strict';
  17337. var utils = require('./common');
  17338. // Quick check if we can use fast array to bin string conversion
  17339. //
  17340. // - apply(Array) can fail on Android 2.2
  17341. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  17342. //
  17343. var STR_APPLY_OK = true;
  17344. var STR_APPLY_UIA_OK = true;
  17345. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  17346. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  17347. // Table with utf8 lengths (calculated by first byte of sequence)
  17348. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  17349. // because max possible codepoint is 0x10ffff
  17350. var _utf8len = new utils.Buf8(256);
  17351. for (var i=0; i<256; i++) {
  17352. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  17353. }
  17354. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  17355. // convert string to array (typed, when possible)
  17356. exports.string2buf = function (str) {
  17357. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  17358. // count binary size
  17359. for (m_pos = 0; m_pos < str_len; m_pos++) {
  17360. c = str.charCodeAt(m_pos);
  17361. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17362. c2 = str.charCodeAt(m_pos+1);
  17363. if ((c2 & 0xfc00) === 0xdc00) {
  17364. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17365. m_pos++;
  17366. }
  17367. }
  17368. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  17369. }
  17370. // allocate buffer
  17371. buf = new utils.Buf8(buf_len);
  17372. // convert
  17373. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  17374. c = str.charCodeAt(m_pos);
  17375. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17376. c2 = str.charCodeAt(m_pos+1);
  17377. if ((c2 & 0xfc00) === 0xdc00) {
  17378. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17379. m_pos++;
  17380. }
  17381. }
  17382. if (c < 0x80) {
  17383. /* one byte */
  17384. buf[i++] = c;
  17385. } else if (c < 0x800) {
  17386. /* two bytes */
  17387. buf[i++] = 0xC0 | (c >>> 6);
  17388. buf[i++] = 0x80 | (c & 0x3f);
  17389. } else if (c < 0x10000) {
  17390. /* three bytes */
  17391. buf[i++] = 0xE0 | (c >>> 12);
  17392. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17393. buf[i++] = 0x80 | (c & 0x3f);
  17394. } else {
  17395. /* four bytes */
  17396. buf[i++] = 0xf0 | (c >>> 18);
  17397. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  17398. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17399. buf[i++] = 0x80 | (c & 0x3f);
  17400. }
  17401. }
  17402. return buf;
  17403. };
  17404. // Helper (used in 2 places)
  17405. function buf2binstring(buf, len) {
  17406. // use fallback for big arrays to avoid stack overflow
  17407. if (len < 65537) {
  17408. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  17409. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  17410. }
  17411. }
  17412. var result = '';
  17413. for(var i=0; i < len; i++) {
  17414. result += String.fromCharCode(buf[i]);
  17415. }
  17416. return result;
  17417. }
  17418. // Convert byte array to binary string
  17419. exports.buf2binstring = function(buf) {
  17420. return buf2binstring(buf, buf.length);
  17421. };
  17422. // Convert binary string (typed, when possible)
  17423. exports.binstring2buf = function(str) {
  17424. var buf = new utils.Buf8(str.length);
  17425. for(var i=0, len=buf.length; i < len; i++) {
  17426. buf[i] = str.charCodeAt(i);
  17427. }
  17428. return buf;
  17429. };
  17430. // convert array to string
  17431. exports.buf2string = function (buf, max) {
  17432. var i, out, c, c_len;
  17433. var len = max || buf.length;
  17434. // Reserve max possible length (2 words per char)
  17435. // NB: by unknown reasons, Array is significantly faster for
  17436. // String.fromCharCode.apply than Uint16Array.
  17437. var utf16buf = new Array(len*2);
  17438. for (out=0, i=0; i<len;) {
  17439. c = buf[i++];
  17440. // quick process ascii
  17441. if (c < 0x80) { utf16buf[out++] = c; continue; }
  17442. c_len = _utf8len[c];
  17443. // skip 5 & 6 byte codes
  17444. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  17445. // apply mask on first byte
  17446. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  17447. // join the rest
  17448. while (c_len > 1 && i < len) {
  17449. c = (c << 6) | (buf[i++] & 0x3f);
  17450. c_len--;
  17451. }
  17452. // terminated by end of string?
  17453. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  17454. if (c < 0x10000) {
  17455. utf16buf[out++] = c;
  17456. } else {
  17457. c -= 0x10000;
  17458. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  17459. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  17460. }
  17461. }
  17462. return buf2binstring(utf16buf, out);
  17463. };
  17464. // Calculate max possible position in utf8 buffer,
  17465. // that will not break sequence. If that's not possible
  17466. // - (very small limits) return max size as is.
  17467. //
  17468. // buf[] - utf8 bytes array
  17469. // max - length limit (mandatory);
  17470. exports.utf8border = function(buf, max) {
  17471. var pos;
  17472. max = max || buf.length;
  17473. if (max > buf.length) { max = buf.length; }
  17474. // go back from last position, until start of sequence found
  17475. pos = max-1;
  17476. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  17477. // Fuckup - very small and broken sequence,
  17478. // return max, because we should return something anyway.
  17479. if (pos < 0) { return max; }
  17480. // If we came to start of buffer - that means vuffer is too small,
  17481. // return max too.
  17482. if (pos === 0) { return max; }
  17483. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  17484. };
  17485. },{"./common":65}],67:[function(require,module,exports){
  17486. 'use strict';
  17487. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  17488. // It doesn't worth to make additional optimizationa as in original.
  17489. // Small size is preferable.
  17490. function adler32(adler, buf, len, pos) {
  17491. var s1 = (adler & 0xffff) |0
  17492. , s2 = ((adler >>> 16) & 0xffff) |0
  17493. , n = 0;
  17494. while (len !== 0) {
  17495. // Set limit ~ twice less than 5552, to keep
  17496. // s2 in 31-bits, because we force signed ints.
  17497. // in other case %= will fail.
  17498. n = len > 2000 ? 2000 : len;
  17499. len -= n;
  17500. do {
  17501. s1 = (s1 + buf[pos++]) |0;
  17502. s2 = (s2 + s1) |0;
  17503. } while (--n);
  17504. s1 %= 65521;
  17505. s2 %= 65521;
  17506. }
  17507. return (s1 | (s2 << 16)) |0;
  17508. }
  17509. module.exports = adler32;
  17510. },{}],68:[function(require,module,exports){
  17511. module.exports = {
  17512. /* Allowed flush values; see deflate() and inflate() below for details */
  17513. Z_NO_FLUSH: 0,
  17514. Z_PARTIAL_FLUSH: 1,
  17515. Z_SYNC_FLUSH: 2,
  17516. Z_FULL_FLUSH: 3,
  17517. Z_FINISH: 4,
  17518. Z_BLOCK: 5,
  17519. Z_TREES: 6,
  17520. /* Return codes for the compression/decompression functions. Negative values
  17521. * are errors, positive values are used for special but normal events.
  17522. */
  17523. Z_OK: 0,
  17524. Z_STREAM_END: 1,
  17525. Z_NEED_DICT: 2,
  17526. Z_ERRNO: -1,
  17527. Z_STREAM_ERROR: -2,
  17528. Z_DATA_ERROR: -3,
  17529. //Z_MEM_ERROR: -4,
  17530. Z_BUF_ERROR: -5,
  17531. //Z_VERSION_ERROR: -6,
  17532. /* compression levels */
  17533. Z_NO_COMPRESSION: 0,
  17534. Z_BEST_SPEED: 1,
  17535. Z_BEST_COMPRESSION: 9,
  17536. Z_DEFAULT_COMPRESSION: -1,
  17537. Z_FILTERED: 1,
  17538. Z_HUFFMAN_ONLY: 2,
  17539. Z_RLE: 3,
  17540. Z_FIXED: 4,
  17541. Z_DEFAULT_STRATEGY: 0,
  17542. /* Possible values of the data_type field (though see inflate()) */
  17543. Z_BINARY: 0,
  17544. Z_TEXT: 1,
  17545. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  17546. Z_UNKNOWN: 2,
  17547. /* The deflate compression method */
  17548. Z_DEFLATED: 8
  17549. //Z_NULL: null // Use -1 or null inline, depending on var type
  17550. };
  17551. },{}],69:[function(require,module,exports){
  17552. 'use strict';
  17553. // Note: we can't get significant speed boost here.
  17554. // So write code to minimize size - no pregenerated tables
  17555. // and array tools dependencies.
  17556. // Use ordinary array, since untyped makes no boost here
  17557. function makeTable() {
  17558. var c, table = [];
  17559. for(var n =0; n < 256; n++){
  17560. c = n;
  17561. for(var k =0; k < 8; k++){
  17562. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  17563. }
  17564. table[n] = c;
  17565. }
  17566. return table;
  17567. }
  17568. // Create table on load. Just 255 signed longs. Not a problem.
  17569. var crcTable = makeTable();
  17570. function crc32(crc, buf, len, pos) {
  17571. var t = crcTable
  17572. , end = pos + len;
  17573. crc = crc ^ (-1);
  17574. for (var i = pos; i < end; i++ ) {
  17575. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  17576. }
  17577. return (crc ^ (-1)); // >>> 0;
  17578. }
  17579. module.exports = crc32;
  17580. },{}],70:[function(require,module,exports){
  17581. 'use strict';
  17582. var utils = require('../utils/common');
  17583. var trees = require('./trees');
  17584. var adler32 = require('./adler32');
  17585. var crc32 = require('./crc32');
  17586. var msg = require('./messages');
  17587. /* Public constants ==========================================================*/
  17588. /* ===========================================================================*/
  17589. /* Allowed flush values; see deflate() and inflate() below for details */
  17590. var Z_NO_FLUSH = 0;
  17591. var Z_PARTIAL_FLUSH = 1;
  17592. //var Z_SYNC_FLUSH = 2;
  17593. var Z_FULL_FLUSH = 3;
  17594. var Z_FINISH = 4;
  17595. var Z_BLOCK = 5;
  17596. //var Z_TREES = 6;
  17597. /* Return codes for the compression/decompression functions. Negative values
  17598. * are errors, positive values are used for special but normal events.
  17599. */
  17600. var Z_OK = 0;
  17601. var Z_STREAM_END = 1;
  17602. //var Z_NEED_DICT = 2;
  17603. //var Z_ERRNO = -1;
  17604. var Z_STREAM_ERROR = -2;
  17605. var Z_DATA_ERROR = -3;
  17606. //var Z_MEM_ERROR = -4;
  17607. var Z_BUF_ERROR = -5;
  17608. //var Z_VERSION_ERROR = -6;
  17609. /* compression levels */
  17610. //var Z_NO_COMPRESSION = 0;
  17611. //var Z_BEST_SPEED = 1;
  17612. //var Z_BEST_COMPRESSION = 9;
  17613. var Z_DEFAULT_COMPRESSION = -1;
  17614. var Z_FILTERED = 1;
  17615. var Z_HUFFMAN_ONLY = 2;
  17616. var Z_RLE = 3;
  17617. var Z_FIXED = 4;
  17618. var Z_DEFAULT_STRATEGY = 0;
  17619. /* Possible values of the data_type field (though see inflate()) */
  17620. //var Z_BINARY = 0;
  17621. //var Z_TEXT = 1;
  17622. //var Z_ASCII = 1; // = Z_TEXT
  17623. var Z_UNKNOWN = 2;
  17624. /* The deflate compression method */
  17625. var Z_DEFLATED = 8;
  17626. /*============================================================================*/
  17627. var MAX_MEM_LEVEL = 9;
  17628. /* Maximum value for memLevel in deflateInit2 */
  17629. var MAX_WBITS = 15;
  17630. /* 32K LZ77 window */
  17631. var DEF_MEM_LEVEL = 8;
  17632. var LENGTH_CODES = 29;
  17633. /* number of length codes, not counting the special END_BLOCK code */
  17634. var LITERALS = 256;
  17635. /* number of literal bytes 0..255 */
  17636. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17637. /* number of Literal or Length codes, including the END_BLOCK code */
  17638. var D_CODES = 30;
  17639. /* number of distance codes */
  17640. var BL_CODES = 19;
  17641. /* number of codes used to transfer the bit lengths */
  17642. var HEAP_SIZE = 2*L_CODES + 1;
  17643. /* maximum heap size */
  17644. var MAX_BITS = 15;
  17645. /* All codes must not exceed MAX_BITS bits */
  17646. var MIN_MATCH = 3;
  17647. var MAX_MATCH = 258;
  17648. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  17649. var PRESET_DICT = 0x20;
  17650. var INIT_STATE = 42;
  17651. var EXTRA_STATE = 69;
  17652. var NAME_STATE = 73;
  17653. var COMMENT_STATE = 91;
  17654. var HCRC_STATE = 103;
  17655. var BUSY_STATE = 113;
  17656. var FINISH_STATE = 666;
  17657. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  17658. var BS_BLOCK_DONE = 2; /* block flush performed */
  17659. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  17660. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  17661. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  17662. function err(strm, errorCode) {
  17663. strm.msg = msg[errorCode];
  17664. return errorCode;
  17665. }
  17666. function rank(f) {
  17667. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  17668. }
  17669. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17670. /* =========================================================================
  17671. * Flush as much pending output as possible. All deflate() output goes
  17672. * through this function so some applications may wish to modify it
  17673. * to avoid allocating a large strm->output buffer and copying into it.
  17674. * (See also read_buf()).
  17675. */
  17676. function flush_pending(strm) {
  17677. var s = strm.state;
  17678. //_tr_flush_bits(s);
  17679. var len = s.pending;
  17680. if (len > strm.avail_out) {
  17681. len = strm.avail_out;
  17682. }
  17683. if (len === 0) { return; }
  17684. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  17685. strm.next_out += len;
  17686. s.pending_out += len;
  17687. strm.total_out += len;
  17688. strm.avail_out -= len;
  17689. s.pending -= len;
  17690. if (s.pending === 0) {
  17691. s.pending_out = 0;
  17692. }
  17693. }
  17694. function flush_block_only (s, last) {
  17695. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  17696. s.block_start = s.strstart;
  17697. flush_pending(s.strm);
  17698. }
  17699. function put_byte(s, b) {
  17700. s.pending_buf[s.pending++] = b;
  17701. }
  17702. /* =========================================================================
  17703. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  17704. * IN assertion: the stream state is correct and there is enough room in
  17705. * pending_buf.
  17706. */
  17707. function putShortMSB(s, b) {
  17708. // put_byte(s, (Byte)(b >> 8));
  17709. // put_byte(s, (Byte)(b & 0xff));
  17710. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  17711. s.pending_buf[s.pending++] = b & 0xff;
  17712. }
  17713. /* ===========================================================================
  17714. * Read a new buffer from the current input stream, update the adler32
  17715. * and total number of bytes read. All deflate() input goes through
  17716. * this function so some applications may wish to modify it to avoid
  17717. * allocating a large strm->input buffer and copying from it.
  17718. * (See also flush_pending()).
  17719. */
  17720. function read_buf(strm, buf, start, size) {
  17721. var len = strm.avail_in;
  17722. if (len > size) { len = size; }
  17723. if (len === 0) { return 0; }
  17724. strm.avail_in -= len;
  17725. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  17726. if (strm.state.wrap === 1) {
  17727. strm.adler = adler32(strm.adler, buf, len, start);
  17728. }
  17729. else if (strm.state.wrap === 2) {
  17730. strm.adler = crc32(strm.adler, buf, len, start);
  17731. }
  17732. strm.next_in += len;
  17733. strm.total_in += len;
  17734. return len;
  17735. }
  17736. /* ===========================================================================
  17737. * Set match_start to the longest match starting at the given string and
  17738. * return its length. Matches shorter or equal to prev_length are discarded,
  17739. * in which case the result is equal to prev_length and match_start is
  17740. * garbage.
  17741. * IN assertions: cur_match is the head of the hash chain for the current
  17742. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  17743. * OUT assertion: the match length is not greater than s->lookahead.
  17744. */
  17745. function longest_match(s, cur_match) {
  17746. var chain_length = s.max_chain_length; /* max hash chain length */
  17747. var scan = s.strstart; /* current string */
  17748. var match; /* matched string */
  17749. var len; /* length of current match */
  17750. var best_len = s.prev_length; /* best match length so far */
  17751. var nice_match = s.nice_match; /* stop if match long enough */
  17752. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  17753. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  17754. var _win = s.window; // shortcut
  17755. var wmask = s.w_mask;
  17756. var prev = s.prev;
  17757. /* Stop when cur_match becomes <= limit. To simplify the code,
  17758. * we prevent matches with the string of window index 0.
  17759. */
  17760. var strend = s.strstart + MAX_MATCH;
  17761. var scan_end1 = _win[scan + best_len - 1];
  17762. var scan_end = _win[scan + best_len];
  17763. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  17764. * It is easy to get rid of this optimization if necessary.
  17765. */
  17766. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  17767. /* Do not waste too much time if we already have a good match: */
  17768. if (s.prev_length >= s.good_match) {
  17769. chain_length >>= 2;
  17770. }
  17771. /* Do not look for matches beyond the end of the input. This is necessary
  17772. * to make deflate deterministic.
  17773. */
  17774. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  17775. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  17776. do {
  17777. // Assert(cur_match < s->strstart, "no future");
  17778. match = cur_match;
  17779. /* Skip to next match if the match length cannot increase
  17780. * or if the match length is less than 2. Note that the checks below
  17781. * for insufficient lookahead only occur occasionally for performance
  17782. * reasons. Therefore uninitialized memory will be accessed, and
  17783. * conditional jumps will be made that depend on those values.
  17784. * However the length of the match is limited to the lookahead, so
  17785. * the output of deflate is not affected by the uninitialized values.
  17786. */
  17787. if (_win[match + best_len] !== scan_end ||
  17788. _win[match + best_len - 1] !== scan_end1 ||
  17789. _win[match] !== _win[scan] ||
  17790. _win[++match] !== _win[scan + 1]) {
  17791. continue;
  17792. }
  17793. /* The check at best_len-1 can be removed because it will be made
  17794. * again later. (This heuristic is not always a win.)
  17795. * It is not necessary to compare scan[2] and match[2] since they
  17796. * are always equal when the other bytes match, given that
  17797. * the hash keys are equal and that HASH_BITS >= 8.
  17798. */
  17799. scan += 2;
  17800. match++;
  17801. // Assert(*scan == *match, "match[2]?");
  17802. /* We check for insufficient lookahead only every 8th comparison;
  17803. * the 256th check will be made at strstart+258.
  17804. */
  17805. do {
  17806. /*jshint noempty:false*/
  17807. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17808. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17809. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17810. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17811. scan < strend);
  17812. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  17813. len = MAX_MATCH - (strend - scan);
  17814. scan = strend - MAX_MATCH;
  17815. if (len > best_len) {
  17816. s.match_start = cur_match;
  17817. best_len = len;
  17818. if (len >= nice_match) {
  17819. break;
  17820. }
  17821. scan_end1 = _win[scan + best_len - 1];
  17822. scan_end = _win[scan + best_len];
  17823. }
  17824. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  17825. if (best_len <= s.lookahead) {
  17826. return best_len;
  17827. }
  17828. return s.lookahead;
  17829. }
  17830. /* ===========================================================================
  17831. * Fill the window when the lookahead becomes insufficient.
  17832. * Updates strstart and lookahead.
  17833. *
  17834. * IN assertion: lookahead < MIN_LOOKAHEAD
  17835. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  17836. * At least one byte has been read, or avail_in == 0; reads are
  17837. * performed for at least two bytes (required for the zip translate_eol
  17838. * option -- not supported here).
  17839. */
  17840. function fill_window(s) {
  17841. var _w_size = s.w_size;
  17842. var p, n, m, more, str;
  17843. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  17844. do {
  17845. more = s.window_size - s.lookahead - s.strstart;
  17846. // JS ints have 32 bit, block below not needed
  17847. /* Deal with !@#$% 64K limit: */
  17848. //if (sizeof(int) <= 2) {
  17849. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  17850. // more = wsize;
  17851. //
  17852. // } else if (more == (unsigned)(-1)) {
  17853. // /* Very unlikely, but possible on 16 bit machine if
  17854. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  17855. // */
  17856. // more--;
  17857. // }
  17858. //}
  17859. /* If the window is almost full and there is insufficient lookahead,
  17860. * move the upper half to the lower one to make room in the upper half.
  17861. */
  17862. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  17863. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  17864. s.match_start -= _w_size;
  17865. s.strstart -= _w_size;
  17866. /* we now have strstart >= MAX_DIST */
  17867. s.block_start -= _w_size;
  17868. /* Slide the hash table (could be avoided with 32 bit values
  17869. at the expense of memory usage). We slide even when level == 0
  17870. to keep the hash table consistent if we switch back to level > 0
  17871. later. (Using level 0 permanently is not an optimal usage of
  17872. zlib, so we don't care about this pathological case.)
  17873. */
  17874. n = s.hash_size;
  17875. p = n;
  17876. do {
  17877. m = s.head[--p];
  17878. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  17879. } while (--n);
  17880. n = _w_size;
  17881. p = n;
  17882. do {
  17883. m = s.prev[--p];
  17884. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  17885. /* If n is not on any hash chain, prev[n] is garbage but
  17886. * its value will never be used.
  17887. */
  17888. } while (--n);
  17889. more += _w_size;
  17890. }
  17891. if (s.strm.avail_in === 0) {
  17892. break;
  17893. }
  17894. /* If there was no sliding:
  17895. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  17896. * more == window_size - lookahead - strstart
  17897. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  17898. * => more >= window_size - 2*WSIZE + 2
  17899. * In the BIG_MEM or MMAP case (not yet supported),
  17900. * window_size == input_size + MIN_LOOKAHEAD &&
  17901. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  17902. * Otherwise, window_size == 2*WSIZE so more >= 2.
  17903. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  17904. */
  17905. //Assert(more >= 2, "more < 2");
  17906. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  17907. s.lookahead += n;
  17908. /* Initialize the hash value now that we have some input: */
  17909. if (s.lookahead + s.insert >= MIN_MATCH) {
  17910. str = s.strstart - s.insert;
  17911. s.ins_h = s.window[str];
  17912. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  17913. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  17914. //#if MIN_MATCH != 3
  17915. // Call update_hash() MIN_MATCH-3 more times
  17916. //#endif
  17917. while (s.insert) {
  17918. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  17919. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  17920. s.prev[str & s.w_mask] = s.head[s.ins_h];
  17921. s.head[s.ins_h] = str;
  17922. str++;
  17923. s.insert--;
  17924. if (s.lookahead + s.insert < MIN_MATCH) {
  17925. break;
  17926. }
  17927. }
  17928. }
  17929. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  17930. * but this is not important since only literal bytes will be emitted.
  17931. */
  17932. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  17933. /* If the WIN_INIT bytes after the end of the current data have never been
  17934. * written, then zero those bytes in order to avoid memory check reports of
  17935. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  17936. * the longest match routines. Update the high water mark for the next
  17937. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  17938. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  17939. */
  17940. // if (s.high_water < s.window_size) {
  17941. // var curr = s.strstart + s.lookahead;
  17942. // var init = 0;
  17943. //
  17944. // if (s.high_water < curr) {
  17945. // /* Previous high water mark below current data -- zero WIN_INIT
  17946. // * bytes or up to end of window, whichever is less.
  17947. // */
  17948. // init = s.window_size - curr;
  17949. // if (init > WIN_INIT)
  17950. // init = WIN_INIT;
  17951. // zmemzero(s->window + curr, (unsigned)init);
  17952. // s->high_water = curr + init;
  17953. // }
  17954. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  17955. // /* High water mark at or above current data, but below current data
  17956. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  17957. // * to end of window, whichever is less.
  17958. // */
  17959. // init = (ulg)curr + WIN_INIT - s->high_water;
  17960. // if (init > s->window_size - s->high_water)
  17961. // init = s->window_size - s->high_water;
  17962. // zmemzero(s->window + s->high_water, (unsigned)init);
  17963. // s->high_water += init;
  17964. // }
  17965. // }
  17966. //
  17967. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  17968. // "not enough room for search");
  17969. }
  17970. /* ===========================================================================
  17971. * Copy without compression as much as possible from the input stream, return
  17972. * the current block state.
  17973. * This function does not insert new strings in the dictionary since
  17974. * uncompressible data is probably not useful. This function is used
  17975. * only for the level=0 compression option.
  17976. * NOTE: this function should be optimized to avoid extra copying from
  17977. * window to pending_buf.
  17978. */
  17979. function deflate_stored(s, flush) {
  17980. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  17981. * to pending_buf_size, and each stored block has a 5 byte header:
  17982. */
  17983. var max_block_size = 0xffff;
  17984. if (max_block_size > s.pending_buf_size - 5) {
  17985. max_block_size = s.pending_buf_size - 5;
  17986. }
  17987. /* Copy as much as possible from input to output: */
  17988. for (;;) {
  17989. /* Fill the window as much as possible: */
  17990. if (s.lookahead <= 1) {
  17991. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  17992. // s->block_start >= (long)s->w_size, "slide too late");
  17993. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  17994. // s.block_start >= s.w_size)) {
  17995. // throw new Error("slide too late");
  17996. // }
  17997. fill_window(s);
  17998. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  17999. return BS_NEED_MORE;
  18000. }
  18001. if (s.lookahead === 0) {
  18002. break;
  18003. }
  18004. /* flush the current block */
  18005. }
  18006. //Assert(s->block_start >= 0L, "block gone");
  18007. // if (s.block_start < 0) throw new Error("block gone");
  18008. s.strstart += s.lookahead;
  18009. s.lookahead = 0;
  18010. /* Emit a stored block if pending_buf will be full: */
  18011. var max_start = s.block_start + max_block_size;
  18012. if (s.strstart === 0 || s.strstart >= max_start) {
  18013. /* strstart == 0 is possible when wraparound on 16-bit machine */
  18014. s.lookahead = s.strstart - max_start;
  18015. s.strstart = max_start;
  18016. /*** FLUSH_BLOCK(s, 0); ***/
  18017. flush_block_only(s, false);
  18018. if (s.strm.avail_out === 0) {
  18019. return BS_NEED_MORE;
  18020. }
  18021. /***/
  18022. }
  18023. /* Flush if we may have to slide, otherwise block_start may become
  18024. * negative and the data will be gone:
  18025. */
  18026. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  18027. /*** FLUSH_BLOCK(s, 0); ***/
  18028. flush_block_only(s, false);
  18029. if (s.strm.avail_out === 0) {
  18030. return BS_NEED_MORE;
  18031. }
  18032. /***/
  18033. }
  18034. }
  18035. s.insert = 0;
  18036. if (flush === Z_FINISH) {
  18037. /*** FLUSH_BLOCK(s, 1); ***/
  18038. flush_block_only(s, true);
  18039. if (s.strm.avail_out === 0) {
  18040. return BS_FINISH_STARTED;
  18041. }
  18042. /***/
  18043. return BS_FINISH_DONE;
  18044. }
  18045. if (s.strstart > s.block_start) {
  18046. /*** FLUSH_BLOCK(s, 0); ***/
  18047. flush_block_only(s, false);
  18048. if (s.strm.avail_out === 0) {
  18049. return BS_NEED_MORE;
  18050. }
  18051. /***/
  18052. }
  18053. return BS_NEED_MORE;
  18054. }
  18055. /* ===========================================================================
  18056. * Compress as much as possible from the input stream, return the current
  18057. * block state.
  18058. * This function does not perform lazy evaluation of matches and inserts
  18059. * new strings in the dictionary only for unmatched strings or for short
  18060. * matches. It is used only for the fast compression options.
  18061. */
  18062. function deflate_fast(s, flush) {
  18063. var hash_head; /* head of the hash chain */
  18064. var bflush; /* set if current block must be flushed */
  18065. for (;;) {
  18066. /* Make sure that we always have enough lookahead, except
  18067. * at the end of the input file. We need MAX_MATCH bytes
  18068. * for the next match, plus MIN_MATCH bytes to insert the
  18069. * string following the next match.
  18070. */
  18071. if (s.lookahead < MIN_LOOKAHEAD) {
  18072. fill_window(s);
  18073. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18074. return BS_NEED_MORE;
  18075. }
  18076. if (s.lookahead === 0) {
  18077. break; /* flush the current block */
  18078. }
  18079. }
  18080. /* Insert the string window[strstart .. strstart+2] in the
  18081. * dictionary, and set hash_head to the head of the hash chain:
  18082. */
  18083. hash_head = 0/*NIL*/;
  18084. if (s.lookahead >= MIN_MATCH) {
  18085. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18086. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18087. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18088. s.head[s.ins_h] = s.strstart;
  18089. /***/
  18090. }
  18091. /* Find the longest match, discarding those <= prev_length.
  18092. * At this point we have always match_length < MIN_MATCH
  18093. */
  18094. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  18095. /* To simplify the code, we prevent matches with the string
  18096. * of window index 0 (in particular we have to avoid a match
  18097. * of the string with itself at the start of the input file).
  18098. */
  18099. s.match_length = longest_match(s, hash_head);
  18100. /* longest_match() sets match_start */
  18101. }
  18102. if (s.match_length >= MIN_MATCH) {
  18103. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  18104. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  18105. s.match_length - MIN_MATCH, bflush); ***/
  18106. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  18107. s.lookahead -= s.match_length;
  18108. /* Insert new strings in the hash table only if the match length
  18109. * is not too large. This saves time but degrades compression.
  18110. */
  18111. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  18112. s.match_length--; /* string at strstart already in table */
  18113. do {
  18114. s.strstart++;
  18115. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18116. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18117. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18118. s.head[s.ins_h] = s.strstart;
  18119. /***/
  18120. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  18121. * always MIN_MATCH bytes ahead.
  18122. */
  18123. } while (--s.match_length !== 0);
  18124. s.strstart++;
  18125. } else
  18126. {
  18127. s.strstart += s.match_length;
  18128. s.match_length = 0;
  18129. s.ins_h = s.window[s.strstart];
  18130. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  18131. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  18132. //#if MIN_MATCH != 3
  18133. // Call UPDATE_HASH() MIN_MATCH-3 more times
  18134. //#endif
  18135. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  18136. * matter since it will be recomputed at next deflate call.
  18137. */
  18138. }
  18139. } else {
  18140. /* No match, output a literal byte */
  18141. //Tracevv((stderr,"%c", s.window[s.strstart]));
  18142. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18143. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18144. s.lookahead--;
  18145. s.strstart++;
  18146. }
  18147. if (bflush) {
  18148. /*** FLUSH_BLOCK(s, 0); ***/
  18149. flush_block_only(s, false);
  18150. if (s.strm.avail_out === 0) {
  18151. return BS_NEED_MORE;
  18152. }
  18153. /***/
  18154. }
  18155. }
  18156. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  18157. if (flush === Z_FINISH) {
  18158. /*** FLUSH_BLOCK(s, 1); ***/
  18159. flush_block_only(s, true);
  18160. if (s.strm.avail_out === 0) {
  18161. return BS_FINISH_STARTED;
  18162. }
  18163. /***/
  18164. return BS_FINISH_DONE;
  18165. }
  18166. if (s.last_lit) {
  18167. /*** FLUSH_BLOCK(s, 0); ***/
  18168. flush_block_only(s, false);
  18169. if (s.strm.avail_out === 0) {
  18170. return BS_NEED_MORE;
  18171. }
  18172. /***/
  18173. }
  18174. return BS_BLOCK_DONE;
  18175. }
  18176. /* ===========================================================================
  18177. * Same as above, but achieves better compression. We use a lazy
  18178. * evaluation for matches: a match is finally adopted only if there is
  18179. * no better match at the next window position.
  18180. */
  18181. function deflate_slow(s, flush) {
  18182. var hash_head; /* head of hash chain */
  18183. var bflush; /* set if current block must be flushed */
  18184. var max_insert;
  18185. /* Process the input block. */
  18186. for (;;) {
  18187. /* Make sure that we always have enough lookahead, except
  18188. * at the end of the input file. We need MAX_MATCH bytes
  18189. * for the next match, plus MIN_MATCH bytes to insert the
  18190. * string following the next match.
  18191. */
  18192. if (s.lookahead < MIN_LOOKAHEAD) {
  18193. fill_window(s);
  18194. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18195. return BS_NEED_MORE;
  18196. }
  18197. if (s.lookahead === 0) { break; } /* flush the current block */
  18198. }
  18199. /* Insert the string window[strstart .. strstart+2] in the
  18200. * dictionary, and set hash_head to the head of the hash chain:
  18201. */
  18202. hash_head = 0/*NIL*/;
  18203. if (s.lookahead >= MIN_MATCH) {
  18204. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18205. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18206. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18207. s.head[s.ins_h] = s.strstart;
  18208. /***/
  18209. }
  18210. /* Find the longest match, discarding those <= prev_length.
  18211. */
  18212. s.prev_length = s.match_length;
  18213. s.prev_match = s.match_start;
  18214. s.match_length = MIN_MATCH-1;
  18215. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  18216. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  18217. /* To simplify the code, we prevent matches with the string
  18218. * of window index 0 (in particular we have to avoid a match
  18219. * of the string with itself at the start of the input file).
  18220. */
  18221. s.match_length = longest_match(s, hash_head);
  18222. /* longest_match() sets match_start */
  18223. if (s.match_length <= 5 &&
  18224. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  18225. /* If prev_match is also MIN_MATCH, match_start is garbage
  18226. * but we will ignore the current match anyway.
  18227. */
  18228. s.match_length = MIN_MATCH-1;
  18229. }
  18230. }
  18231. /* If there was a match at the previous step and the current
  18232. * match is not better, output the previous match:
  18233. */
  18234. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  18235. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  18236. /* Do not insert strings in hash table beyond this. */
  18237. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  18238. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  18239. s.prev_length - MIN_MATCH, bflush);***/
  18240. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  18241. /* Insert in hash table all strings up to the end of the match.
  18242. * strstart-1 and strstart are already inserted. If there is not
  18243. * enough lookahead, the last two strings are not inserted in
  18244. * the hash table.
  18245. */
  18246. s.lookahead -= s.prev_length-1;
  18247. s.prev_length -= 2;
  18248. do {
  18249. if (++s.strstart <= max_insert) {
  18250. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18251. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18252. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18253. s.head[s.ins_h] = s.strstart;
  18254. /***/
  18255. }
  18256. } while (--s.prev_length !== 0);
  18257. s.match_available = 0;
  18258. s.match_length = MIN_MATCH-1;
  18259. s.strstart++;
  18260. if (bflush) {
  18261. /*** FLUSH_BLOCK(s, 0); ***/
  18262. flush_block_only(s, false);
  18263. if (s.strm.avail_out === 0) {
  18264. return BS_NEED_MORE;
  18265. }
  18266. /***/
  18267. }
  18268. } else if (s.match_available) {
  18269. /* If there was no match at the previous position, output a
  18270. * single literal. If there was a match but the current match
  18271. * is longer, truncate the previous match to a single literal.
  18272. */
  18273. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18274. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18275. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18276. if (bflush) {
  18277. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  18278. flush_block_only(s, false);
  18279. /***/
  18280. }
  18281. s.strstart++;
  18282. s.lookahead--;
  18283. if (s.strm.avail_out === 0) {
  18284. return BS_NEED_MORE;
  18285. }
  18286. } else {
  18287. /* There is no previous match to compare with, wait for
  18288. * the next step to decide.
  18289. */
  18290. s.match_available = 1;
  18291. s.strstart++;
  18292. s.lookahead--;
  18293. }
  18294. }
  18295. //Assert (flush != Z_NO_FLUSH, "no flush?");
  18296. if (s.match_available) {
  18297. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18298. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18299. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18300. s.match_available = 0;
  18301. }
  18302. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  18303. if (flush === Z_FINISH) {
  18304. /*** FLUSH_BLOCK(s, 1); ***/
  18305. flush_block_only(s, true);
  18306. if (s.strm.avail_out === 0) {
  18307. return BS_FINISH_STARTED;
  18308. }
  18309. /***/
  18310. return BS_FINISH_DONE;
  18311. }
  18312. if (s.last_lit) {
  18313. /*** FLUSH_BLOCK(s, 0); ***/
  18314. flush_block_only(s, false);
  18315. if (s.strm.avail_out === 0) {
  18316. return BS_NEED_MORE;
  18317. }
  18318. /***/
  18319. }
  18320. return BS_BLOCK_DONE;
  18321. }
  18322. /* ===========================================================================
  18323. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  18324. * one. Do not maintain a hash table. (It will be regenerated if this run of
  18325. * deflate switches away from Z_RLE.)
  18326. */
  18327. function deflate_rle(s, flush) {
  18328. var bflush; /* set if current block must be flushed */
  18329. var prev; /* byte at distance one to match */
  18330. var scan, strend; /* scan goes up to strend for length of run */
  18331. var _win = s.window;
  18332. for (;;) {
  18333. /* Make sure that we always have enough lookahead, except
  18334. * at the end of the input file. We need MAX_MATCH bytes
  18335. * for the longest run, plus one for the unrolled loop.
  18336. */
  18337. if (s.lookahead <= MAX_MATCH) {
  18338. fill_window(s);
  18339. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  18340. return BS_NEED_MORE;
  18341. }
  18342. if (s.lookahead === 0) { break; } /* flush the current block */
  18343. }
  18344. /* See how many times the previous byte repeats */
  18345. s.match_length = 0;
  18346. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  18347. scan = s.strstart - 1;
  18348. prev = _win[scan];
  18349. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  18350. strend = s.strstart + MAX_MATCH;
  18351. do {
  18352. /*jshint noempty:false*/
  18353. } while (prev === _win[++scan] && prev === _win[++scan] &&
  18354. prev === _win[++scan] && prev === _win[++scan] &&
  18355. prev === _win[++scan] && prev === _win[++scan] &&
  18356. prev === _win[++scan] && prev === _win[++scan] &&
  18357. scan < strend);
  18358. s.match_length = MAX_MATCH - (strend - scan);
  18359. if (s.match_length > s.lookahead) {
  18360. s.match_length = s.lookahead;
  18361. }
  18362. }
  18363. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  18364. }
  18365. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  18366. if (s.match_length >= MIN_MATCH) {
  18367. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  18368. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  18369. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  18370. s.lookahead -= s.match_length;
  18371. s.strstart += s.match_length;
  18372. s.match_length = 0;
  18373. } else {
  18374. /* No match, output a literal byte */
  18375. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18376. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18377. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18378. s.lookahead--;
  18379. s.strstart++;
  18380. }
  18381. if (bflush) {
  18382. /*** FLUSH_BLOCK(s, 0); ***/
  18383. flush_block_only(s, false);
  18384. if (s.strm.avail_out === 0) {
  18385. return BS_NEED_MORE;
  18386. }
  18387. /***/
  18388. }
  18389. }
  18390. s.insert = 0;
  18391. if (flush === Z_FINISH) {
  18392. /*** FLUSH_BLOCK(s, 1); ***/
  18393. flush_block_only(s, true);
  18394. if (s.strm.avail_out === 0) {
  18395. return BS_FINISH_STARTED;
  18396. }
  18397. /***/
  18398. return BS_FINISH_DONE;
  18399. }
  18400. if (s.last_lit) {
  18401. /*** FLUSH_BLOCK(s, 0); ***/
  18402. flush_block_only(s, false);
  18403. if (s.strm.avail_out === 0) {
  18404. return BS_NEED_MORE;
  18405. }
  18406. /***/
  18407. }
  18408. return BS_BLOCK_DONE;
  18409. }
  18410. /* ===========================================================================
  18411. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  18412. * (It will be regenerated if this run of deflate switches away from Huffman.)
  18413. */
  18414. function deflate_huff(s, flush) {
  18415. var bflush; /* set if current block must be flushed */
  18416. for (;;) {
  18417. /* Make sure that we have a literal to write. */
  18418. if (s.lookahead === 0) {
  18419. fill_window(s);
  18420. if (s.lookahead === 0) {
  18421. if (flush === Z_NO_FLUSH) {
  18422. return BS_NEED_MORE;
  18423. }
  18424. break; /* flush the current block */
  18425. }
  18426. }
  18427. /* Output a literal byte */
  18428. s.match_length = 0;
  18429. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18430. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18431. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18432. s.lookahead--;
  18433. s.strstart++;
  18434. if (bflush) {
  18435. /*** FLUSH_BLOCK(s, 0); ***/
  18436. flush_block_only(s, false);
  18437. if (s.strm.avail_out === 0) {
  18438. return BS_NEED_MORE;
  18439. }
  18440. /***/
  18441. }
  18442. }
  18443. s.insert = 0;
  18444. if (flush === Z_FINISH) {
  18445. /*** FLUSH_BLOCK(s, 1); ***/
  18446. flush_block_only(s, true);
  18447. if (s.strm.avail_out === 0) {
  18448. return BS_FINISH_STARTED;
  18449. }
  18450. /***/
  18451. return BS_FINISH_DONE;
  18452. }
  18453. if (s.last_lit) {
  18454. /*** FLUSH_BLOCK(s, 0); ***/
  18455. flush_block_only(s, false);
  18456. if (s.strm.avail_out === 0) {
  18457. return BS_NEED_MORE;
  18458. }
  18459. /***/
  18460. }
  18461. return BS_BLOCK_DONE;
  18462. }
  18463. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  18464. * the desired pack level (0..9). The values given below have been tuned to
  18465. * exclude worst case performance for pathological files. Better values may be
  18466. * found for specific files.
  18467. */
  18468. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  18469. this.good_length = good_length;
  18470. this.max_lazy = max_lazy;
  18471. this.nice_length = nice_length;
  18472. this.max_chain = max_chain;
  18473. this.func = func;
  18474. };
  18475. var configuration_table;
  18476. configuration_table = [
  18477. /* good lazy nice chain */
  18478. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  18479. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  18480. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  18481. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  18482. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  18483. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  18484. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  18485. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  18486. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  18487. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  18488. ];
  18489. /* ===========================================================================
  18490. * Initialize the "longest match" routines for a new zlib stream
  18491. */
  18492. function lm_init(s) {
  18493. s.window_size = 2 * s.w_size;
  18494. /*** CLEAR_HASH(s); ***/
  18495. zero(s.head); // Fill with NIL (= 0);
  18496. /* Set the default configuration parameters:
  18497. */
  18498. s.max_lazy_match = configuration_table[s.level].max_lazy;
  18499. s.good_match = configuration_table[s.level].good_length;
  18500. s.nice_match = configuration_table[s.level].nice_length;
  18501. s.max_chain_length = configuration_table[s.level].max_chain;
  18502. s.strstart = 0;
  18503. s.block_start = 0;
  18504. s.lookahead = 0;
  18505. s.insert = 0;
  18506. s.match_length = s.prev_length = MIN_MATCH - 1;
  18507. s.match_available = 0;
  18508. s.ins_h = 0;
  18509. }
  18510. function DeflateState() {
  18511. this.strm = null; /* pointer back to this zlib stream */
  18512. this.status = 0; /* as the name implies */
  18513. this.pending_buf = null; /* output still pending */
  18514. this.pending_buf_size = 0; /* size of pending_buf */
  18515. this.pending_out = 0; /* next pending byte to output to the stream */
  18516. this.pending = 0; /* nb of bytes in the pending buffer */
  18517. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  18518. this.gzhead = null; /* gzip header information to write */
  18519. this.gzindex = 0; /* where in extra, name, or comment */
  18520. this.method = Z_DEFLATED; /* can only be DEFLATED */
  18521. this.last_flush = -1; /* value of flush param for previous deflate call */
  18522. this.w_size = 0; /* LZ77 window size (32K by default) */
  18523. this.w_bits = 0; /* log2(w_size) (8..16) */
  18524. this.w_mask = 0; /* w_size - 1 */
  18525. this.window = null;
  18526. /* Sliding window. Input bytes are read into the second half of the window,
  18527. * and move to the first half later to keep a dictionary of at least wSize
  18528. * bytes. With this organization, matches are limited to a distance of
  18529. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  18530. * performed with a length multiple of the block size.
  18531. */
  18532. this.window_size = 0;
  18533. /* Actual size of window: 2*wSize, except when the user input buffer
  18534. * is directly used as sliding window.
  18535. */
  18536. this.prev = null;
  18537. /* Link to older string with same hash index. To limit the size of this
  18538. * array to 64K, this link is maintained only for the last 32K strings.
  18539. * An index in this array is thus a window index modulo 32K.
  18540. */
  18541. this.head = null; /* Heads of the hash chains or NIL. */
  18542. this.ins_h = 0; /* hash index of string to be inserted */
  18543. this.hash_size = 0; /* number of elements in hash table */
  18544. this.hash_bits = 0; /* log2(hash_size) */
  18545. this.hash_mask = 0; /* hash_size-1 */
  18546. this.hash_shift = 0;
  18547. /* Number of bits by which ins_h must be shifted at each input
  18548. * step. It must be such that after MIN_MATCH steps, the oldest
  18549. * byte no longer takes part in the hash key, that is:
  18550. * hash_shift * MIN_MATCH >= hash_bits
  18551. */
  18552. this.block_start = 0;
  18553. /* Window position at the beginning of the current output block. Gets
  18554. * negative when the window is moved backwards.
  18555. */
  18556. this.match_length = 0; /* length of best match */
  18557. this.prev_match = 0; /* previous match */
  18558. this.match_available = 0; /* set if previous match exists */
  18559. this.strstart = 0; /* start of string to insert */
  18560. this.match_start = 0; /* start of matching string */
  18561. this.lookahead = 0; /* number of valid bytes ahead in window */
  18562. this.prev_length = 0;
  18563. /* Length of the best match at previous step. Matches not greater than this
  18564. * are discarded. This is used in the lazy match evaluation.
  18565. */
  18566. this.max_chain_length = 0;
  18567. /* To speed up deflation, hash chains are never searched beyond this
  18568. * length. A higher limit improves compression ratio but degrades the
  18569. * speed.
  18570. */
  18571. this.max_lazy_match = 0;
  18572. /* Attempt to find a better match only when the current match is strictly
  18573. * smaller than this value. This mechanism is used only for compression
  18574. * levels >= 4.
  18575. */
  18576. // That's alias to max_lazy_match, don't use directly
  18577. //this.max_insert_length = 0;
  18578. /* Insert new strings in the hash table only if the match length is not
  18579. * greater than this length. This saves time but degrades compression.
  18580. * max_insert_length is used only for compression levels <= 3.
  18581. */
  18582. this.level = 0; /* compression level (1..9) */
  18583. this.strategy = 0; /* favor or force Huffman coding*/
  18584. this.good_match = 0;
  18585. /* Use a faster search when the previous match is longer than this */
  18586. this.nice_match = 0; /* Stop searching when current match exceeds this */
  18587. /* used by trees.c: */
  18588. /* Didn't use ct_data typedef below to suppress compiler warning */
  18589. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  18590. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  18591. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  18592. // Use flat array of DOUBLE size, with interleaved fata,
  18593. // because JS does not support effective
  18594. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  18595. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  18596. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  18597. zero(this.dyn_ltree);
  18598. zero(this.dyn_dtree);
  18599. zero(this.bl_tree);
  18600. this.l_desc = null; /* desc. for literal tree */
  18601. this.d_desc = null; /* desc. for distance tree */
  18602. this.bl_desc = null; /* desc. for bit length tree */
  18603. //ush bl_count[MAX_BITS+1];
  18604. this.bl_count = new utils.Buf16(MAX_BITS+1);
  18605. /* number of codes at each bit length for an optimal tree */
  18606. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  18607. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  18608. zero(this.heap);
  18609. this.heap_len = 0; /* number of elements in the heap */
  18610. this.heap_max = 0; /* element of largest frequency */
  18611. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  18612. * The same heap array is used to build all trees.
  18613. */
  18614. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  18615. zero(this.depth);
  18616. /* Depth of each subtree used as tie breaker for trees of equal frequency
  18617. */
  18618. this.l_buf = 0; /* buffer index for literals or lengths */
  18619. this.lit_bufsize = 0;
  18620. /* Size of match buffer for literals/lengths. There are 4 reasons for
  18621. * limiting lit_bufsize to 64K:
  18622. * - frequencies can be kept in 16 bit counters
  18623. * - if compression is not successful for the first block, all input
  18624. * data is still in the window so we can still emit a stored block even
  18625. * when input comes from standard input. (This can also be done for
  18626. * all blocks if lit_bufsize is not greater than 32K.)
  18627. * - if compression is not successful for a file smaller than 64K, we can
  18628. * even emit a stored file instead of a stored block (saving 5 bytes).
  18629. * This is applicable only for zip (not gzip or zlib).
  18630. * - creating new Huffman trees less frequently may not provide fast
  18631. * adaptation to changes in the input data statistics. (Take for
  18632. * example a binary file with poorly compressible code followed by
  18633. * a highly compressible string table.) Smaller buffer sizes give
  18634. * fast adaptation but have of course the overhead of transmitting
  18635. * trees more frequently.
  18636. * - I can't count above 4
  18637. */
  18638. this.last_lit = 0; /* running index in l_buf */
  18639. this.d_buf = 0;
  18640. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  18641. * the same number of elements. To use different lengths, an extra flag
  18642. * array would be necessary.
  18643. */
  18644. this.opt_len = 0; /* bit length of current block with optimal trees */
  18645. this.static_len = 0; /* bit length of current block with static trees */
  18646. this.matches = 0; /* number of string matches in current block */
  18647. this.insert = 0; /* bytes at end of window left to insert */
  18648. this.bi_buf = 0;
  18649. /* Output buffer. bits are inserted starting at the bottom (least
  18650. * significant bits).
  18651. */
  18652. this.bi_valid = 0;
  18653. /* Number of valid bits in bi_buf. All bits above the last valid bit
  18654. * are always zero.
  18655. */
  18656. // Used for window memory init. We safely ignore it for JS. That makes
  18657. // sense only for pointers and memory check tools.
  18658. //this.high_water = 0;
  18659. /* High water mark offset in window for initialized bytes -- bytes above
  18660. * this are set to zero in order to avoid memory check warnings when
  18661. * longest match routines access bytes past the input. This is then
  18662. * updated to the new high water mark.
  18663. */
  18664. }
  18665. function deflateResetKeep(strm) {
  18666. var s;
  18667. if (!strm || !strm.state) {
  18668. return err(strm, Z_STREAM_ERROR);
  18669. }
  18670. strm.total_in = strm.total_out = 0;
  18671. strm.data_type = Z_UNKNOWN;
  18672. s = strm.state;
  18673. s.pending = 0;
  18674. s.pending_out = 0;
  18675. if (s.wrap < 0) {
  18676. s.wrap = -s.wrap;
  18677. /* was made negative by deflate(..., Z_FINISH); */
  18678. }
  18679. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  18680. strm.adler = (s.wrap === 2) ?
  18681. 0 // crc32(0, Z_NULL, 0)
  18682. :
  18683. 1; // adler32(0, Z_NULL, 0)
  18684. s.last_flush = Z_NO_FLUSH;
  18685. trees._tr_init(s);
  18686. return Z_OK;
  18687. }
  18688. function deflateReset(strm) {
  18689. var ret = deflateResetKeep(strm);
  18690. if (ret === Z_OK) {
  18691. lm_init(strm.state);
  18692. }
  18693. return ret;
  18694. }
  18695. function deflateSetHeader(strm, head) {
  18696. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18697. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  18698. strm.state.gzhead = head;
  18699. return Z_OK;
  18700. }
  18701. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  18702. if (!strm) { // === Z_NULL
  18703. return Z_STREAM_ERROR;
  18704. }
  18705. var wrap = 1;
  18706. if (level === Z_DEFAULT_COMPRESSION) {
  18707. level = 6;
  18708. }
  18709. if (windowBits < 0) { /* suppress zlib wrapper */
  18710. wrap = 0;
  18711. windowBits = -windowBits;
  18712. }
  18713. else if (windowBits > 15) {
  18714. wrap = 2; /* write gzip wrapper instead */
  18715. windowBits -= 16;
  18716. }
  18717. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  18718. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  18719. strategy < 0 || strategy > Z_FIXED) {
  18720. return err(strm, Z_STREAM_ERROR);
  18721. }
  18722. if (windowBits === 8) {
  18723. windowBits = 9;
  18724. }
  18725. /* until 256-byte window bug fixed */
  18726. var s = new DeflateState();
  18727. strm.state = s;
  18728. s.strm = strm;
  18729. s.wrap = wrap;
  18730. s.gzhead = null;
  18731. s.w_bits = windowBits;
  18732. s.w_size = 1 << s.w_bits;
  18733. s.w_mask = s.w_size - 1;
  18734. s.hash_bits = memLevel + 7;
  18735. s.hash_size = 1 << s.hash_bits;
  18736. s.hash_mask = s.hash_size - 1;
  18737. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  18738. s.window = new utils.Buf8(s.w_size * 2);
  18739. s.head = new utils.Buf16(s.hash_size);
  18740. s.prev = new utils.Buf16(s.w_size);
  18741. // Don't need mem init magic for JS.
  18742. //s.high_water = 0; /* nothing written to s->window yet */
  18743. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  18744. s.pending_buf_size = s.lit_bufsize * 4;
  18745. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  18746. s.d_buf = s.lit_bufsize >> 1;
  18747. s.l_buf = (1 + 2) * s.lit_bufsize;
  18748. s.level = level;
  18749. s.strategy = strategy;
  18750. s.method = method;
  18751. return deflateReset(strm);
  18752. }
  18753. function deflateInit(strm, level) {
  18754. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  18755. }
  18756. function deflate(strm, flush) {
  18757. var old_flush, s;
  18758. var beg, val; // for gzip header write only
  18759. if (!strm || !strm.state ||
  18760. flush > Z_BLOCK || flush < 0) {
  18761. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  18762. }
  18763. s = strm.state;
  18764. if (!strm.output ||
  18765. (!strm.input && strm.avail_in !== 0) ||
  18766. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  18767. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  18768. }
  18769. s.strm = strm; /* just in case */
  18770. old_flush = s.last_flush;
  18771. s.last_flush = flush;
  18772. /* Write the header */
  18773. if (s.status === INIT_STATE) {
  18774. if (s.wrap === 2) { // GZIP header
  18775. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  18776. put_byte(s, 31);
  18777. put_byte(s, 139);
  18778. put_byte(s, 8);
  18779. if (!s.gzhead) { // s->gzhead == Z_NULL
  18780. put_byte(s, 0);
  18781. put_byte(s, 0);
  18782. put_byte(s, 0);
  18783. put_byte(s, 0);
  18784. put_byte(s, 0);
  18785. put_byte(s, s.level === 9 ? 2 :
  18786. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  18787. 4 : 0));
  18788. put_byte(s, OS_CODE);
  18789. s.status = BUSY_STATE;
  18790. }
  18791. else {
  18792. put_byte(s, (s.gzhead.text ? 1 : 0) +
  18793. (s.gzhead.hcrc ? 2 : 0) +
  18794. (!s.gzhead.extra ? 0 : 4) +
  18795. (!s.gzhead.name ? 0 : 8) +
  18796. (!s.gzhead.comment ? 0 : 16)
  18797. );
  18798. put_byte(s, s.gzhead.time & 0xff);
  18799. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  18800. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  18801. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  18802. put_byte(s, s.level === 9 ? 2 :
  18803. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  18804. 4 : 0));
  18805. put_byte(s, s.gzhead.os & 0xff);
  18806. if (s.gzhead.extra && s.gzhead.extra.length) {
  18807. put_byte(s, s.gzhead.extra.length & 0xff);
  18808. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  18809. }
  18810. if (s.gzhead.hcrc) {
  18811. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  18812. }
  18813. s.gzindex = 0;
  18814. s.status = EXTRA_STATE;
  18815. }
  18816. }
  18817. else // DEFLATE header
  18818. {
  18819. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  18820. var level_flags = -1;
  18821. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  18822. level_flags = 0;
  18823. } else if (s.level < 6) {
  18824. level_flags = 1;
  18825. } else if (s.level === 6) {
  18826. level_flags = 2;
  18827. } else {
  18828. level_flags = 3;
  18829. }
  18830. header |= (level_flags << 6);
  18831. if (s.strstart !== 0) { header |= PRESET_DICT; }
  18832. header += 31 - (header % 31);
  18833. s.status = BUSY_STATE;
  18834. putShortMSB(s, header);
  18835. /* Save the adler32 of the preset dictionary: */
  18836. if (s.strstart !== 0) {
  18837. putShortMSB(s, strm.adler >>> 16);
  18838. putShortMSB(s, strm.adler & 0xffff);
  18839. }
  18840. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  18841. }
  18842. }
  18843. //#ifdef GZIP
  18844. if (s.status === EXTRA_STATE) {
  18845. if (s.gzhead.extra/* != Z_NULL*/) {
  18846. beg = s.pending; /* start of bytes to update crc */
  18847. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  18848. if (s.pending === s.pending_buf_size) {
  18849. if (s.gzhead.hcrc && s.pending > beg) {
  18850. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18851. }
  18852. flush_pending(strm);
  18853. beg = s.pending;
  18854. if (s.pending === s.pending_buf_size) {
  18855. break;
  18856. }
  18857. }
  18858. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  18859. s.gzindex++;
  18860. }
  18861. if (s.gzhead.hcrc && s.pending > beg) {
  18862. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18863. }
  18864. if (s.gzindex === s.gzhead.extra.length) {
  18865. s.gzindex = 0;
  18866. s.status = NAME_STATE;
  18867. }
  18868. }
  18869. else {
  18870. s.status = NAME_STATE;
  18871. }
  18872. }
  18873. if (s.status === NAME_STATE) {
  18874. if (s.gzhead.name/* != Z_NULL*/) {
  18875. beg = s.pending; /* start of bytes to update crc */
  18876. //int val;
  18877. do {
  18878. if (s.pending === s.pending_buf_size) {
  18879. if (s.gzhead.hcrc && s.pending > beg) {
  18880. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18881. }
  18882. flush_pending(strm);
  18883. beg = s.pending;
  18884. if (s.pending === s.pending_buf_size) {
  18885. val = 1;
  18886. break;
  18887. }
  18888. }
  18889. // JS specific: little magic to add zero terminator to end of string
  18890. if (s.gzindex < s.gzhead.name.length) {
  18891. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  18892. } else {
  18893. val = 0;
  18894. }
  18895. put_byte(s, val);
  18896. } while (val !== 0);
  18897. if (s.gzhead.hcrc && s.pending > beg){
  18898. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18899. }
  18900. if (val === 0) {
  18901. s.gzindex = 0;
  18902. s.status = COMMENT_STATE;
  18903. }
  18904. }
  18905. else {
  18906. s.status = COMMENT_STATE;
  18907. }
  18908. }
  18909. if (s.status === COMMENT_STATE) {
  18910. if (s.gzhead.comment/* != Z_NULL*/) {
  18911. beg = s.pending; /* start of bytes to update crc */
  18912. //int val;
  18913. do {
  18914. if (s.pending === s.pending_buf_size) {
  18915. if (s.gzhead.hcrc && s.pending > beg) {
  18916. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18917. }
  18918. flush_pending(strm);
  18919. beg = s.pending;
  18920. if (s.pending === s.pending_buf_size) {
  18921. val = 1;
  18922. break;
  18923. }
  18924. }
  18925. // JS specific: little magic to add zero terminator to end of string
  18926. if (s.gzindex < s.gzhead.comment.length) {
  18927. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  18928. } else {
  18929. val = 0;
  18930. }
  18931. put_byte(s, val);
  18932. } while (val !== 0);
  18933. if (s.gzhead.hcrc && s.pending > beg) {
  18934. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18935. }
  18936. if (val === 0) {
  18937. s.status = HCRC_STATE;
  18938. }
  18939. }
  18940. else {
  18941. s.status = HCRC_STATE;
  18942. }
  18943. }
  18944. if (s.status === HCRC_STATE) {
  18945. if (s.gzhead.hcrc) {
  18946. if (s.pending + 2 > s.pending_buf_size) {
  18947. flush_pending(strm);
  18948. }
  18949. if (s.pending + 2 <= s.pending_buf_size) {
  18950. put_byte(s, strm.adler & 0xff);
  18951. put_byte(s, (strm.adler >> 8) & 0xff);
  18952. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  18953. s.status = BUSY_STATE;
  18954. }
  18955. }
  18956. else {
  18957. s.status = BUSY_STATE;
  18958. }
  18959. }
  18960. //#endif
  18961. /* Flush as much pending output as possible */
  18962. if (s.pending !== 0) {
  18963. flush_pending(strm);
  18964. if (strm.avail_out === 0) {
  18965. /* Since avail_out is 0, deflate will be called again with
  18966. * more output space, but possibly with both pending and
  18967. * avail_in equal to zero. There won't be anything to do,
  18968. * but this is not an error situation so make sure we
  18969. * return OK instead of BUF_ERROR at next call of deflate:
  18970. */
  18971. s.last_flush = -1;
  18972. return Z_OK;
  18973. }
  18974. /* Make sure there is something to do and avoid duplicate consecutive
  18975. * flushes. For repeated and useless calls with Z_FINISH, we keep
  18976. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  18977. */
  18978. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  18979. flush !== Z_FINISH) {
  18980. return err(strm, Z_BUF_ERROR);
  18981. }
  18982. /* User must not provide more input after the first FINISH: */
  18983. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  18984. return err(strm, Z_BUF_ERROR);
  18985. }
  18986. /* Start a new block or continue the current one.
  18987. */
  18988. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  18989. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  18990. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  18991. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  18992. configuration_table[s.level].func(s, flush));
  18993. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  18994. s.status = FINISH_STATE;
  18995. }
  18996. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  18997. if (strm.avail_out === 0) {
  18998. s.last_flush = -1;
  18999. /* avoid BUF_ERROR next call, see above */
  19000. }
  19001. return Z_OK;
  19002. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  19003. * of deflate should use the same flush parameter to make sure
  19004. * that the flush is complete. So we don't have to output an
  19005. * empty block here, this will be done at next call. This also
  19006. * ensures that for a very small output buffer, we emit at most
  19007. * one empty block.
  19008. */
  19009. }
  19010. if (bstate === BS_BLOCK_DONE) {
  19011. if (flush === Z_PARTIAL_FLUSH) {
  19012. trees._tr_align(s);
  19013. }
  19014. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  19015. trees._tr_stored_block(s, 0, 0, false);
  19016. /* For a full flush, this empty block will be recognized
  19017. * as a special marker by inflate_sync().
  19018. */
  19019. if (flush === Z_FULL_FLUSH) {
  19020. /*** CLEAR_HASH(s); ***/ /* forget history */
  19021. zero(s.head); // Fill with NIL (= 0);
  19022. if (s.lookahead === 0) {
  19023. s.strstart = 0;
  19024. s.block_start = 0;
  19025. s.insert = 0;
  19026. }
  19027. }
  19028. }
  19029. flush_pending(strm);
  19030. if (strm.avail_out === 0) {
  19031. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  19032. return Z_OK;
  19033. }
  19034. }
  19035. }
  19036. //Assert(strm->avail_out > 0, "bug2");
  19037. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  19038. if (flush !== Z_FINISH) { return Z_OK; }
  19039. if (s.wrap <= 0) { return Z_STREAM_END; }
  19040. /* Write the trailer */
  19041. if (s.wrap === 2) {
  19042. put_byte(s, strm.adler & 0xff);
  19043. put_byte(s, (strm.adler >> 8) & 0xff);
  19044. put_byte(s, (strm.adler >> 16) & 0xff);
  19045. put_byte(s, (strm.adler >> 24) & 0xff);
  19046. put_byte(s, strm.total_in & 0xff);
  19047. put_byte(s, (strm.total_in >> 8) & 0xff);
  19048. put_byte(s, (strm.total_in >> 16) & 0xff);
  19049. put_byte(s, (strm.total_in >> 24) & 0xff);
  19050. }
  19051. else
  19052. {
  19053. putShortMSB(s, strm.adler >>> 16);
  19054. putShortMSB(s, strm.adler & 0xffff);
  19055. }
  19056. flush_pending(strm);
  19057. /* If avail_out is zero, the application will call deflate again
  19058. * to flush the rest.
  19059. */
  19060. if (s.wrap > 0) { s.wrap = -s.wrap; }
  19061. /* write the trailer only once! */
  19062. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  19063. }
  19064. function deflateEnd(strm) {
  19065. var status;
  19066. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  19067. return Z_STREAM_ERROR;
  19068. }
  19069. status = strm.state.status;
  19070. if (status !== INIT_STATE &&
  19071. status !== EXTRA_STATE &&
  19072. status !== NAME_STATE &&
  19073. status !== COMMENT_STATE &&
  19074. status !== HCRC_STATE &&
  19075. status !== BUSY_STATE &&
  19076. status !== FINISH_STATE
  19077. ) {
  19078. return err(strm, Z_STREAM_ERROR);
  19079. }
  19080. strm.state = null;
  19081. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  19082. }
  19083. /* =========================================================================
  19084. * Copy the source state to the destination state
  19085. */
  19086. //function deflateCopy(dest, source) {
  19087. //
  19088. //}
  19089. exports.deflateInit = deflateInit;
  19090. exports.deflateInit2 = deflateInit2;
  19091. exports.deflateReset = deflateReset;
  19092. exports.deflateResetKeep = deflateResetKeep;
  19093. exports.deflateSetHeader = deflateSetHeader;
  19094. exports.deflate = deflate;
  19095. exports.deflateEnd = deflateEnd;
  19096. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  19097. /* Not implemented
  19098. exports.deflateBound = deflateBound;
  19099. exports.deflateCopy = deflateCopy;
  19100. exports.deflateSetDictionary = deflateSetDictionary;
  19101. exports.deflateParams = deflateParams;
  19102. exports.deflatePending = deflatePending;
  19103. exports.deflatePrime = deflatePrime;
  19104. exports.deflateTune = deflateTune;
  19105. */
  19106. },{"../utils/common":65,"./adler32":67,"./crc32":69,"./messages":75,"./trees":76}],71:[function(require,module,exports){
  19107. 'use strict';
  19108. function GZheader() {
  19109. /* true if compressed data believed to be text */
  19110. this.text = 0;
  19111. /* modification time */
  19112. this.time = 0;
  19113. /* extra flags (not used when writing a gzip file) */
  19114. this.xflags = 0;
  19115. /* operating system */
  19116. this.os = 0;
  19117. /* pointer to extra field or Z_NULL if none */
  19118. this.extra = null;
  19119. /* extra field length (valid if extra != Z_NULL) */
  19120. this.extra_len = 0; // Actually, we don't need it in JS,
  19121. // but leave for few code modifications
  19122. //
  19123. // Setup limits is not necessary because in js we should not preallocate memory
  19124. // for inflate use constant limit in 65536 bytes
  19125. //
  19126. /* space at extra (only when reading header) */
  19127. // this.extra_max = 0;
  19128. /* pointer to zero-terminated file name or Z_NULL */
  19129. this.name = '';
  19130. /* space at name (only when reading header) */
  19131. // this.name_max = 0;
  19132. /* pointer to zero-terminated comment or Z_NULL */
  19133. this.comment = '';
  19134. /* space at comment (only when reading header) */
  19135. // this.comm_max = 0;
  19136. /* true if there was or will be a header crc */
  19137. this.hcrc = 0;
  19138. /* true when done reading gzip header (not used when writing a gzip file) */
  19139. this.done = false;
  19140. }
  19141. module.exports = GZheader;
  19142. },{}],72:[function(require,module,exports){
  19143. 'use strict';
  19144. // See state defs from inflate.js
  19145. var BAD = 30; /* got a data error -- remain here until reset */
  19146. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19147. /*
  19148. Decode literal, length, and distance codes and write out the resulting
  19149. literal and match bytes until either not enough input or output is
  19150. available, an end-of-block is encountered, or a data error is encountered.
  19151. When large enough input and output buffers are supplied to inflate(), for
  19152. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  19153. inflate execution time is spent in this routine.
  19154. Entry assumptions:
  19155. state.mode === LEN
  19156. strm.avail_in >= 6
  19157. strm.avail_out >= 258
  19158. start >= strm.avail_out
  19159. state.bits < 8
  19160. On return, state.mode is one of:
  19161. LEN -- ran out of enough output space or enough available input
  19162. TYPE -- reached end of block code, inflate() to interpret next block
  19163. BAD -- error in block data
  19164. Notes:
  19165. - The maximum input bits used by a length/distance pair is 15 bits for the
  19166. length code, 5 bits for the length extra, 15 bits for the distance code,
  19167. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  19168. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  19169. checking for available input while decoding.
  19170. - The maximum bytes that a single length/distance pair can output is 258
  19171. bytes, which is the maximum length that can be coded. inflate_fast()
  19172. requires strm.avail_out >= 258 for each loop to avoid checking for
  19173. output space.
  19174. */
  19175. module.exports = function inflate_fast(strm, start) {
  19176. var state;
  19177. var _in; /* local strm.input */
  19178. var last; /* have enough input while in < last */
  19179. var _out; /* local strm.output */
  19180. var beg; /* inflate()'s initial strm.output */
  19181. var end; /* while out < end, enough space available */
  19182. //#ifdef INFLATE_STRICT
  19183. var dmax; /* maximum distance from zlib header */
  19184. //#endif
  19185. var wsize; /* window size or zero if not using window */
  19186. var whave; /* valid bytes in the window */
  19187. var wnext; /* window write index */
  19188. var window; /* allocated sliding window, if wsize != 0 */
  19189. var hold; /* local strm.hold */
  19190. var bits; /* local strm.bits */
  19191. var lcode; /* local strm.lencode */
  19192. var dcode; /* local strm.distcode */
  19193. var lmask; /* mask for first level of length codes */
  19194. var dmask; /* mask for first level of distance codes */
  19195. var here; /* retrieved table entry */
  19196. var op; /* code bits, operation, extra bits, or */
  19197. /* window position, window bytes to copy */
  19198. var len; /* match length, unused bytes */
  19199. var dist; /* match distance */
  19200. var from; /* where to copy match from */
  19201. var from_source;
  19202. var input, output; // JS specific, because we have no pointers
  19203. /* copy state to local variables */
  19204. state = strm.state;
  19205. //here = state.here;
  19206. _in = strm.next_in;
  19207. input = strm.input;
  19208. last = _in + (strm.avail_in - 5);
  19209. _out = strm.next_out;
  19210. output = strm.output;
  19211. beg = _out - (start - strm.avail_out);
  19212. end = _out + (strm.avail_out - 257);
  19213. //#ifdef INFLATE_STRICT
  19214. dmax = state.dmax;
  19215. //#endif
  19216. wsize = state.wsize;
  19217. whave = state.whave;
  19218. wnext = state.wnext;
  19219. window = state.window;
  19220. hold = state.hold;
  19221. bits = state.bits;
  19222. lcode = state.lencode;
  19223. dcode = state.distcode;
  19224. lmask = (1 << state.lenbits) - 1;
  19225. dmask = (1 << state.distbits) - 1;
  19226. /* decode literals and length/distances until end-of-block or not enough
  19227. input data or output space */
  19228. top:
  19229. do {
  19230. if (bits < 15) {
  19231. hold += input[_in++] << bits;
  19232. bits += 8;
  19233. hold += input[_in++] << bits;
  19234. bits += 8;
  19235. }
  19236. here = lcode[hold & lmask];
  19237. dolen:
  19238. for (;;) { // Goto emulation
  19239. op = here >>> 24/*here.bits*/;
  19240. hold >>>= op;
  19241. bits -= op;
  19242. op = (here >>> 16) & 0xff/*here.op*/;
  19243. if (op === 0) { /* literal */
  19244. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  19245. // "inflate: literal '%c'\n" :
  19246. // "inflate: literal 0x%02x\n", here.val));
  19247. output[_out++] = here & 0xffff/*here.val*/;
  19248. }
  19249. else if (op & 16) { /* length base */
  19250. len = here & 0xffff/*here.val*/;
  19251. op &= 15; /* number of extra bits */
  19252. if (op) {
  19253. if (bits < op) {
  19254. hold += input[_in++] << bits;
  19255. bits += 8;
  19256. }
  19257. len += hold & ((1 << op) - 1);
  19258. hold >>>= op;
  19259. bits -= op;
  19260. }
  19261. //Tracevv((stderr, "inflate: length %u\n", len));
  19262. if (bits < 15) {
  19263. hold += input[_in++] << bits;
  19264. bits += 8;
  19265. hold += input[_in++] << bits;
  19266. bits += 8;
  19267. }
  19268. here = dcode[hold & dmask];
  19269. dodist:
  19270. for (;;) { // goto emulation
  19271. op = here >>> 24/*here.bits*/;
  19272. hold >>>= op;
  19273. bits -= op;
  19274. op = (here >>> 16) & 0xff/*here.op*/;
  19275. if (op & 16) { /* distance base */
  19276. dist = here & 0xffff/*here.val*/;
  19277. op &= 15; /* number of extra bits */
  19278. if (bits < op) {
  19279. hold += input[_in++] << bits;
  19280. bits += 8;
  19281. if (bits < op) {
  19282. hold += input[_in++] << bits;
  19283. bits += 8;
  19284. }
  19285. }
  19286. dist += hold & ((1 << op) - 1);
  19287. //#ifdef INFLATE_STRICT
  19288. if (dist > dmax) {
  19289. strm.msg = 'invalid distance too far back';
  19290. state.mode = BAD;
  19291. break top;
  19292. }
  19293. //#endif
  19294. hold >>>= op;
  19295. bits -= op;
  19296. //Tracevv((stderr, "inflate: distance %u\n", dist));
  19297. op = _out - beg; /* max distance in output */
  19298. if (dist > op) { /* see if copy from window */
  19299. op = dist - op; /* distance back in window */
  19300. if (op > whave) {
  19301. if (state.sane) {
  19302. strm.msg = 'invalid distance too far back';
  19303. state.mode = BAD;
  19304. break top;
  19305. }
  19306. // (!) This block is disabled in zlib defailts,
  19307. // don't enable it for binary compatibility
  19308. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  19309. // if (len <= op - whave) {
  19310. // do {
  19311. // output[_out++] = 0;
  19312. // } while (--len);
  19313. // continue top;
  19314. // }
  19315. // len -= op - whave;
  19316. // do {
  19317. // output[_out++] = 0;
  19318. // } while (--op > whave);
  19319. // if (op === 0) {
  19320. // from = _out - dist;
  19321. // do {
  19322. // output[_out++] = output[from++];
  19323. // } while (--len);
  19324. // continue top;
  19325. // }
  19326. //#endif
  19327. }
  19328. from = 0; // window index
  19329. from_source = window;
  19330. if (wnext === 0) { /* very common case */
  19331. from += wsize - op;
  19332. if (op < len) { /* some from window */
  19333. len -= op;
  19334. do {
  19335. output[_out++] = window[from++];
  19336. } while (--op);
  19337. from = _out - dist; /* rest from output */
  19338. from_source = output;
  19339. }
  19340. }
  19341. else if (wnext < op) { /* wrap around window */
  19342. from += wsize + wnext - op;
  19343. op -= wnext;
  19344. if (op < len) { /* some from end of window */
  19345. len -= op;
  19346. do {
  19347. output[_out++] = window[from++];
  19348. } while (--op);
  19349. from = 0;
  19350. if (wnext < len) { /* some from start of window */
  19351. op = wnext;
  19352. len -= op;
  19353. do {
  19354. output[_out++] = window[from++];
  19355. } while (--op);
  19356. from = _out - dist; /* rest from output */
  19357. from_source = output;
  19358. }
  19359. }
  19360. }
  19361. else { /* contiguous in window */
  19362. from += wnext - op;
  19363. if (op < len) { /* some from window */
  19364. len -= op;
  19365. do {
  19366. output[_out++] = window[from++];
  19367. } while (--op);
  19368. from = _out - dist; /* rest from output */
  19369. from_source = output;
  19370. }
  19371. }
  19372. while (len > 2) {
  19373. output[_out++] = from_source[from++];
  19374. output[_out++] = from_source[from++];
  19375. output[_out++] = from_source[from++];
  19376. len -= 3;
  19377. }
  19378. if (len) {
  19379. output[_out++] = from_source[from++];
  19380. if (len > 1) {
  19381. output[_out++] = from_source[from++];
  19382. }
  19383. }
  19384. }
  19385. else {
  19386. from = _out - dist; /* copy direct from output */
  19387. do { /* minimum length is three */
  19388. output[_out++] = output[from++];
  19389. output[_out++] = output[from++];
  19390. output[_out++] = output[from++];
  19391. len -= 3;
  19392. } while (len > 2);
  19393. if (len) {
  19394. output[_out++] = output[from++];
  19395. if (len > 1) {
  19396. output[_out++] = output[from++];
  19397. }
  19398. }
  19399. }
  19400. }
  19401. else if ((op & 64) === 0) { /* 2nd level distance code */
  19402. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19403. continue dodist;
  19404. }
  19405. else {
  19406. strm.msg = 'invalid distance code';
  19407. state.mode = BAD;
  19408. break top;
  19409. }
  19410. break; // need to emulate goto via "continue"
  19411. }
  19412. }
  19413. else if ((op & 64) === 0) { /* 2nd level length code */
  19414. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19415. continue dolen;
  19416. }
  19417. else if (op & 32) { /* end-of-block */
  19418. //Tracevv((stderr, "inflate: end of block\n"));
  19419. state.mode = TYPE;
  19420. break top;
  19421. }
  19422. else {
  19423. strm.msg = 'invalid literal/length code';
  19424. state.mode = BAD;
  19425. break top;
  19426. }
  19427. break; // need to emulate goto via "continue"
  19428. }
  19429. } while (_in < last && _out < end);
  19430. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  19431. len = bits >> 3;
  19432. _in -= len;
  19433. bits -= len << 3;
  19434. hold &= (1 << bits) - 1;
  19435. /* update state and return */
  19436. strm.next_in = _in;
  19437. strm.next_out = _out;
  19438. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  19439. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  19440. state.hold = hold;
  19441. state.bits = bits;
  19442. return;
  19443. };
  19444. },{}],73:[function(require,module,exports){
  19445. 'use strict';
  19446. var utils = require('../utils/common');
  19447. var adler32 = require('./adler32');
  19448. var crc32 = require('./crc32');
  19449. var inflate_fast = require('./inffast');
  19450. var inflate_table = require('./inftrees');
  19451. var CODES = 0;
  19452. var LENS = 1;
  19453. var DISTS = 2;
  19454. /* Public constants ==========================================================*/
  19455. /* ===========================================================================*/
  19456. /* Allowed flush values; see deflate() and inflate() below for details */
  19457. //var Z_NO_FLUSH = 0;
  19458. //var Z_PARTIAL_FLUSH = 1;
  19459. //var Z_SYNC_FLUSH = 2;
  19460. //var Z_FULL_FLUSH = 3;
  19461. var Z_FINISH = 4;
  19462. var Z_BLOCK = 5;
  19463. var Z_TREES = 6;
  19464. /* Return codes for the compression/decompression functions. Negative values
  19465. * are errors, positive values are used for special but normal events.
  19466. */
  19467. var Z_OK = 0;
  19468. var Z_STREAM_END = 1;
  19469. var Z_NEED_DICT = 2;
  19470. //var Z_ERRNO = -1;
  19471. var Z_STREAM_ERROR = -2;
  19472. var Z_DATA_ERROR = -3;
  19473. var Z_MEM_ERROR = -4;
  19474. var Z_BUF_ERROR = -5;
  19475. //var Z_VERSION_ERROR = -6;
  19476. /* The deflate compression method */
  19477. var Z_DEFLATED = 8;
  19478. /* STATES ====================================================================*/
  19479. /* ===========================================================================*/
  19480. var HEAD = 1; /* i: waiting for magic header */
  19481. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  19482. var TIME = 3; /* i: waiting for modification time (gzip) */
  19483. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  19484. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  19485. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  19486. var NAME = 7; /* i: waiting for end of file name (gzip) */
  19487. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  19488. var HCRC = 9; /* i: waiting for header crc (gzip) */
  19489. var DICTID = 10; /* i: waiting for dictionary check value */
  19490. var DICT = 11; /* waiting for inflateSetDictionary() call */
  19491. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19492. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  19493. var STORED = 14; /* i: waiting for stored size (length and complement) */
  19494. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  19495. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  19496. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  19497. var LENLENS = 18; /* i: waiting for code length code lengths */
  19498. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  19499. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  19500. var LEN = 21; /* i: waiting for length/lit/eob code */
  19501. var LENEXT = 22; /* i: waiting for length extra bits */
  19502. var DIST = 23; /* i: waiting for distance code */
  19503. var DISTEXT = 24; /* i: waiting for distance extra bits */
  19504. var MATCH = 25; /* o: waiting for output space to copy string */
  19505. var LIT = 26; /* o: waiting for output space to write literal */
  19506. var CHECK = 27; /* i: waiting for 32-bit check value */
  19507. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  19508. var DONE = 29; /* finished check, done -- remain here until reset */
  19509. var BAD = 30; /* got a data error -- remain here until reset */
  19510. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  19511. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  19512. /* ===========================================================================*/
  19513. var ENOUGH_LENS = 852;
  19514. var ENOUGH_DISTS = 592;
  19515. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  19516. var MAX_WBITS = 15;
  19517. /* 32K LZ77 window */
  19518. var DEF_WBITS = MAX_WBITS;
  19519. function ZSWAP32(q) {
  19520. return (((q >>> 24) & 0xff) +
  19521. ((q >>> 8) & 0xff00) +
  19522. ((q & 0xff00) << 8) +
  19523. ((q & 0xff) << 24));
  19524. }
  19525. function InflateState() {
  19526. this.mode = 0; /* current inflate mode */
  19527. this.last = false; /* true if processing last block */
  19528. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  19529. this.havedict = false; /* true if dictionary provided */
  19530. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  19531. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  19532. this.check = 0; /* protected copy of check value */
  19533. this.total = 0; /* protected copy of output count */
  19534. // TODO: may be {}
  19535. this.head = null; /* where to save gzip header information */
  19536. /* sliding window */
  19537. this.wbits = 0; /* log base 2 of requested window size */
  19538. this.wsize = 0; /* window size or zero if not using window */
  19539. this.whave = 0; /* valid bytes in the window */
  19540. this.wnext = 0; /* window write index */
  19541. this.window = null; /* allocated sliding window, if needed */
  19542. /* bit accumulator */
  19543. this.hold = 0; /* input bit accumulator */
  19544. this.bits = 0; /* number of bits in "in" */
  19545. /* for string and stored block copying */
  19546. this.length = 0; /* literal or length of data to copy */
  19547. this.offset = 0; /* distance back to copy string from */
  19548. /* for table and code decoding */
  19549. this.extra = 0; /* extra bits needed */
  19550. /* fixed and dynamic code tables */
  19551. this.lencode = null; /* starting table for length/literal codes */
  19552. this.distcode = null; /* starting table for distance codes */
  19553. this.lenbits = 0; /* index bits for lencode */
  19554. this.distbits = 0; /* index bits for distcode */
  19555. /* dynamic table building */
  19556. this.ncode = 0; /* number of code length code lengths */
  19557. this.nlen = 0; /* number of length code lengths */
  19558. this.ndist = 0; /* number of distance code lengths */
  19559. this.have = 0; /* number of code lengths in lens[] */
  19560. this.next = null; /* next available space in codes[] */
  19561. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  19562. this.work = new utils.Buf16(288); /* work area for code table building */
  19563. /*
  19564. because we don't have pointers in js, we use lencode and distcode directly
  19565. as buffers so we don't need codes
  19566. */
  19567. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  19568. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  19569. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  19570. this.sane = 0; /* if false, allow invalid distance too far */
  19571. this.back = 0; /* bits back of last unprocessed length/lit */
  19572. this.was = 0; /* initial length of match */
  19573. }
  19574. function inflateResetKeep(strm) {
  19575. var state;
  19576. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19577. state = strm.state;
  19578. strm.total_in = strm.total_out = state.total = 0;
  19579. strm.msg = ''; /*Z_NULL*/
  19580. if (state.wrap) { /* to support ill-conceived Java test suite */
  19581. strm.adler = state.wrap & 1;
  19582. }
  19583. state.mode = HEAD;
  19584. state.last = 0;
  19585. state.havedict = 0;
  19586. state.dmax = 32768;
  19587. state.head = null/*Z_NULL*/;
  19588. state.hold = 0;
  19589. state.bits = 0;
  19590. //state.lencode = state.distcode = state.next = state.codes;
  19591. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  19592. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  19593. state.sane = 1;
  19594. state.back = -1;
  19595. //Tracev((stderr, "inflate: reset\n"));
  19596. return Z_OK;
  19597. }
  19598. function inflateReset(strm) {
  19599. var state;
  19600. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19601. state = strm.state;
  19602. state.wsize = 0;
  19603. state.whave = 0;
  19604. state.wnext = 0;
  19605. return inflateResetKeep(strm);
  19606. }
  19607. function inflateReset2(strm, windowBits) {
  19608. var wrap;
  19609. var state;
  19610. /* get the state */
  19611. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19612. state = strm.state;
  19613. /* extract wrap request from windowBits parameter */
  19614. if (windowBits < 0) {
  19615. wrap = 0;
  19616. windowBits = -windowBits;
  19617. }
  19618. else {
  19619. wrap = (windowBits >> 4) + 1;
  19620. if (windowBits < 48) {
  19621. windowBits &= 15;
  19622. }
  19623. }
  19624. /* set number of window bits, free window if different */
  19625. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  19626. return Z_STREAM_ERROR;
  19627. }
  19628. if (state.window !== null && state.wbits !== windowBits) {
  19629. state.window = null;
  19630. }
  19631. /* update state and reset the rest of it */
  19632. state.wrap = wrap;
  19633. state.wbits = windowBits;
  19634. return inflateReset(strm);
  19635. }
  19636. function inflateInit2(strm, windowBits) {
  19637. var ret;
  19638. var state;
  19639. if (!strm) { return Z_STREAM_ERROR; }
  19640. //strm.msg = Z_NULL; /* in case we return an error */
  19641. state = new InflateState();
  19642. //if (state === Z_NULL) return Z_MEM_ERROR;
  19643. //Tracev((stderr, "inflate: allocated\n"));
  19644. strm.state = state;
  19645. state.window = null/*Z_NULL*/;
  19646. ret = inflateReset2(strm, windowBits);
  19647. if (ret !== Z_OK) {
  19648. strm.state = null/*Z_NULL*/;
  19649. }
  19650. return ret;
  19651. }
  19652. function inflateInit(strm) {
  19653. return inflateInit2(strm, DEF_WBITS);
  19654. }
  19655. /*
  19656. Return state with length and distance decoding tables and index sizes set to
  19657. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  19658. If BUILDFIXED is defined, then instead this routine builds the tables the
  19659. first time it's called, and returns those tables the first time and
  19660. thereafter. This reduces the size of the code by about 2K bytes, in
  19661. exchange for a little execution time. However, BUILDFIXED should not be
  19662. used for threaded applications, since the rewriting of the tables and virgin
  19663. may not be thread-safe.
  19664. */
  19665. var virgin = true;
  19666. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  19667. function fixedtables(state) {
  19668. /* build fixed huffman tables if first call (may not be thread safe) */
  19669. if (virgin) {
  19670. var sym;
  19671. lenfix = new utils.Buf32(512);
  19672. distfix = new utils.Buf32(32);
  19673. /* literal/length table */
  19674. sym = 0;
  19675. while (sym < 144) { state.lens[sym++] = 8; }
  19676. while (sym < 256) { state.lens[sym++] = 9; }
  19677. while (sym < 280) { state.lens[sym++] = 7; }
  19678. while (sym < 288) { state.lens[sym++] = 8; }
  19679. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  19680. /* distance table */
  19681. sym = 0;
  19682. while (sym < 32) { state.lens[sym++] = 5; }
  19683. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  19684. /* do this just once */
  19685. virgin = false;
  19686. }
  19687. state.lencode = lenfix;
  19688. state.lenbits = 9;
  19689. state.distcode = distfix;
  19690. state.distbits = 5;
  19691. }
  19692. /*
  19693. Update the window with the last wsize (normally 32K) bytes written before
  19694. returning. If window does not exist yet, create it. This is only called
  19695. when a window is already in use, or when output has been written during this
  19696. inflate call, but the end of the deflate stream has not been reached yet.
  19697. It is also called to create a window for dictionary data when a dictionary
  19698. is loaded.
  19699. Providing output buffers larger than 32K to inflate() should provide a speed
  19700. advantage, since only the last 32K of output is copied to the sliding window
  19701. upon return from inflate(), and since all distances after the first 32K of
  19702. output will fall in the output data, making match copies simpler and faster.
  19703. The advantage may be dependent on the size of the processor's data caches.
  19704. */
  19705. function updatewindow(strm, src, end, copy) {
  19706. var dist;
  19707. var state = strm.state;
  19708. /* if it hasn't been done already, allocate space for the window */
  19709. if (state.window === null) {
  19710. state.wsize = 1 << state.wbits;
  19711. state.wnext = 0;
  19712. state.whave = 0;
  19713. state.window = new utils.Buf8(state.wsize);
  19714. }
  19715. /* copy state->wsize or less output bytes into the circular window */
  19716. if (copy >= state.wsize) {
  19717. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  19718. state.wnext = 0;
  19719. state.whave = state.wsize;
  19720. }
  19721. else {
  19722. dist = state.wsize - state.wnext;
  19723. if (dist > copy) {
  19724. dist = copy;
  19725. }
  19726. //zmemcpy(state->window + state->wnext, end - copy, dist);
  19727. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  19728. copy -= dist;
  19729. if (copy) {
  19730. //zmemcpy(state->window, end - copy, copy);
  19731. utils.arraySet(state.window,src, end - copy, copy, 0);
  19732. state.wnext = copy;
  19733. state.whave = state.wsize;
  19734. }
  19735. else {
  19736. state.wnext += dist;
  19737. if (state.wnext === state.wsize) { state.wnext = 0; }
  19738. if (state.whave < state.wsize) { state.whave += dist; }
  19739. }
  19740. }
  19741. return 0;
  19742. }
  19743. function inflate(strm, flush) {
  19744. var state;
  19745. var input, output; // input/output buffers
  19746. var next; /* next input INDEX */
  19747. var put; /* next output INDEX */
  19748. var have, left; /* available input and output */
  19749. var hold; /* bit buffer */
  19750. var bits; /* bits in bit buffer */
  19751. var _in, _out; /* save starting available input and output */
  19752. var copy; /* number of stored or match bytes to copy */
  19753. var from; /* where to copy match bytes from */
  19754. var from_source;
  19755. var here = 0; /* current decoding table entry */
  19756. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  19757. //var last; /* parent table entry */
  19758. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  19759. var len; /* length to copy for repeats, bits to drop */
  19760. var ret; /* return code */
  19761. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  19762. var opts;
  19763. var n; // temporary var for NEED_BITS
  19764. var order = /* permutation of code lengths */
  19765. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  19766. if (!strm || !strm.state || !strm.output ||
  19767. (!strm.input && strm.avail_in !== 0)) {
  19768. return Z_STREAM_ERROR;
  19769. }
  19770. state = strm.state;
  19771. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  19772. //--- LOAD() ---
  19773. put = strm.next_out;
  19774. output = strm.output;
  19775. left = strm.avail_out;
  19776. next = strm.next_in;
  19777. input = strm.input;
  19778. have = strm.avail_in;
  19779. hold = state.hold;
  19780. bits = state.bits;
  19781. //---
  19782. _in = have;
  19783. _out = left;
  19784. ret = Z_OK;
  19785. inf_leave: // goto emulation
  19786. for (;;) {
  19787. switch (state.mode) {
  19788. case HEAD:
  19789. if (state.wrap === 0) {
  19790. state.mode = TYPEDO;
  19791. break;
  19792. }
  19793. //=== NEEDBITS(16);
  19794. while (bits < 16) {
  19795. if (have === 0) { break inf_leave; }
  19796. have--;
  19797. hold += input[next++] << bits;
  19798. bits += 8;
  19799. }
  19800. //===//
  19801. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  19802. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  19803. //=== CRC2(state.check, hold);
  19804. hbuf[0] = hold & 0xff;
  19805. hbuf[1] = (hold >>> 8) & 0xff;
  19806. state.check = crc32(state.check, hbuf, 2, 0);
  19807. //===//
  19808. //=== INITBITS();
  19809. hold = 0;
  19810. bits = 0;
  19811. //===//
  19812. state.mode = FLAGS;
  19813. break;
  19814. }
  19815. state.flags = 0; /* expect zlib header */
  19816. if (state.head) {
  19817. state.head.done = false;
  19818. }
  19819. if (!(state.wrap & 1) || /* check if zlib header allowed */
  19820. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  19821. strm.msg = 'incorrect header check';
  19822. state.mode = BAD;
  19823. break;
  19824. }
  19825. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  19826. strm.msg = 'unknown compression method';
  19827. state.mode = BAD;
  19828. break;
  19829. }
  19830. //--- DROPBITS(4) ---//
  19831. hold >>>= 4;
  19832. bits -= 4;
  19833. //---//
  19834. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  19835. if (state.wbits === 0) {
  19836. state.wbits = len;
  19837. }
  19838. else if (len > state.wbits) {
  19839. strm.msg = 'invalid window size';
  19840. state.mode = BAD;
  19841. break;
  19842. }
  19843. state.dmax = 1 << len;
  19844. //Tracev((stderr, "inflate: zlib header ok\n"));
  19845. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  19846. state.mode = hold & 0x200 ? DICTID : TYPE;
  19847. //=== INITBITS();
  19848. hold = 0;
  19849. bits = 0;
  19850. //===//
  19851. break;
  19852. case FLAGS:
  19853. //=== NEEDBITS(16); */
  19854. while (bits < 16) {
  19855. if (have === 0) { break inf_leave; }
  19856. have--;
  19857. hold += input[next++] << bits;
  19858. bits += 8;
  19859. }
  19860. //===//
  19861. state.flags = hold;
  19862. if ((state.flags & 0xff) !== Z_DEFLATED) {
  19863. strm.msg = 'unknown compression method';
  19864. state.mode = BAD;
  19865. break;
  19866. }
  19867. if (state.flags & 0xe000) {
  19868. strm.msg = 'unknown header flags set';
  19869. state.mode = BAD;
  19870. break;
  19871. }
  19872. if (state.head) {
  19873. state.head.text = ((hold >> 8) & 1);
  19874. }
  19875. if (state.flags & 0x0200) {
  19876. //=== CRC2(state.check, hold);
  19877. hbuf[0] = hold & 0xff;
  19878. hbuf[1] = (hold >>> 8) & 0xff;
  19879. state.check = crc32(state.check, hbuf, 2, 0);
  19880. //===//
  19881. }
  19882. //=== INITBITS();
  19883. hold = 0;
  19884. bits = 0;
  19885. //===//
  19886. state.mode = TIME;
  19887. /* falls through */
  19888. case TIME:
  19889. //=== NEEDBITS(32); */
  19890. while (bits < 32) {
  19891. if (have === 0) { break inf_leave; }
  19892. have--;
  19893. hold += input[next++] << bits;
  19894. bits += 8;
  19895. }
  19896. //===//
  19897. if (state.head) {
  19898. state.head.time = hold;
  19899. }
  19900. if (state.flags & 0x0200) {
  19901. //=== CRC4(state.check, hold)
  19902. hbuf[0] = hold & 0xff;
  19903. hbuf[1] = (hold >>> 8) & 0xff;
  19904. hbuf[2] = (hold >>> 16) & 0xff;
  19905. hbuf[3] = (hold >>> 24) & 0xff;
  19906. state.check = crc32(state.check, hbuf, 4, 0);
  19907. //===
  19908. }
  19909. //=== INITBITS();
  19910. hold = 0;
  19911. bits = 0;
  19912. //===//
  19913. state.mode = OS;
  19914. /* falls through */
  19915. case OS:
  19916. //=== NEEDBITS(16); */
  19917. while (bits < 16) {
  19918. if (have === 0) { break inf_leave; }
  19919. have--;
  19920. hold += input[next++] << bits;
  19921. bits += 8;
  19922. }
  19923. //===//
  19924. if (state.head) {
  19925. state.head.xflags = (hold & 0xff);
  19926. state.head.os = (hold >> 8);
  19927. }
  19928. if (state.flags & 0x0200) {
  19929. //=== CRC2(state.check, hold);
  19930. hbuf[0] = hold & 0xff;
  19931. hbuf[1] = (hold >>> 8) & 0xff;
  19932. state.check = crc32(state.check, hbuf, 2, 0);
  19933. //===//
  19934. }
  19935. //=== INITBITS();
  19936. hold = 0;
  19937. bits = 0;
  19938. //===//
  19939. state.mode = EXLEN;
  19940. /* falls through */
  19941. case EXLEN:
  19942. if (state.flags & 0x0400) {
  19943. //=== NEEDBITS(16); */
  19944. while (bits < 16) {
  19945. if (have === 0) { break inf_leave; }
  19946. have--;
  19947. hold += input[next++] << bits;
  19948. bits += 8;
  19949. }
  19950. //===//
  19951. state.length = hold;
  19952. if (state.head) {
  19953. state.head.extra_len = hold;
  19954. }
  19955. if (state.flags & 0x0200) {
  19956. //=== CRC2(state.check, hold);
  19957. hbuf[0] = hold & 0xff;
  19958. hbuf[1] = (hold >>> 8) & 0xff;
  19959. state.check = crc32(state.check, hbuf, 2, 0);
  19960. //===//
  19961. }
  19962. //=== INITBITS();
  19963. hold = 0;
  19964. bits = 0;
  19965. //===//
  19966. }
  19967. else if (state.head) {
  19968. state.head.extra = null/*Z_NULL*/;
  19969. }
  19970. state.mode = EXTRA;
  19971. /* falls through */
  19972. case EXTRA:
  19973. if (state.flags & 0x0400) {
  19974. copy = state.length;
  19975. if (copy > have) { copy = have; }
  19976. if (copy) {
  19977. if (state.head) {
  19978. len = state.head.extra_len - state.length;
  19979. if (!state.head.extra) {
  19980. // Use untyped array for more conveniend processing later
  19981. state.head.extra = new Array(state.head.extra_len);
  19982. }
  19983. utils.arraySet(
  19984. state.head.extra,
  19985. input,
  19986. next,
  19987. // extra field is limited to 65536 bytes
  19988. // - no need for additional size check
  19989. copy,
  19990. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  19991. len
  19992. );
  19993. //zmemcpy(state.head.extra + len, next,
  19994. // len + copy > state.head.extra_max ?
  19995. // state.head.extra_max - len : copy);
  19996. }
  19997. if (state.flags & 0x0200) {
  19998. state.check = crc32(state.check, input, copy, next);
  19999. }
  20000. have -= copy;
  20001. next += copy;
  20002. state.length -= copy;
  20003. }
  20004. if (state.length) { break inf_leave; }
  20005. }
  20006. state.length = 0;
  20007. state.mode = NAME;
  20008. /* falls through */
  20009. case NAME:
  20010. if (state.flags & 0x0800) {
  20011. if (have === 0) { break inf_leave; }
  20012. copy = 0;
  20013. do {
  20014. // TODO: 2 or 1 bytes?
  20015. len = input[next + copy++];
  20016. /* use constant limit because in js we should not preallocate memory */
  20017. if (state.head && len &&
  20018. (state.length < 65536 /*state.head.name_max*/)) {
  20019. state.head.name += String.fromCharCode(len);
  20020. }
  20021. } while (len && copy < have);
  20022. if (state.flags & 0x0200) {
  20023. state.check = crc32(state.check, input, copy, next);
  20024. }
  20025. have -= copy;
  20026. next += copy;
  20027. if (len) { break inf_leave; }
  20028. }
  20029. else if (state.head) {
  20030. state.head.name = null;
  20031. }
  20032. state.length = 0;
  20033. state.mode = COMMENT;
  20034. /* falls through */
  20035. case COMMENT:
  20036. if (state.flags & 0x1000) {
  20037. if (have === 0) { break inf_leave; }
  20038. copy = 0;
  20039. do {
  20040. len = input[next + copy++];
  20041. /* use constant limit because in js we should not preallocate memory */
  20042. if (state.head && len &&
  20043. (state.length < 65536 /*state.head.comm_max*/)) {
  20044. state.head.comment += String.fromCharCode(len);
  20045. }
  20046. } while (len && copy < have);
  20047. if (state.flags & 0x0200) {
  20048. state.check = crc32(state.check, input, copy, next);
  20049. }
  20050. have -= copy;
  20051. next += copy;
  20052. if (len) { break inf_leave; }
  20053. }
  20054. else if (state.head) {
  20055. state.head.comment = null;
  20056. }
  20057. state.mode = HCRC;
  20058. /* falls through */
  20059. case HCRC:
  20060. if (state.flags & 0x0200) {
  20061. //=== NEEDBITS(16); */
  20062. while (bits < 16) {
  20063. if (have === 0) { break inf_leave; }
  20064. have--;
  20065. hold += input[next++] << bits;
  20066. bits += 8;
  20067. }
  20068. //===//
  20069. if (hold !== (state.check & 0xffff)) {
  20070. strm.msg = 'header crc mismatch';
  20071. state.mode = BAD;
  20072. break;
  20073. }
  20074. //=== INITBITS();
  20075. hold = 0;
  20076. bits = 0;
  20077. //===//
  20078. }
  20079. if (state.head) {
  20080. state.head.hcrc = ((state.flags >> 9) & 1);
  20081. state.head.done = true;
  20082. }
  20083. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  20084. state.mode = TYPE;
  20085. break;
  20086. case DICTID:
  20087. //=== NEEDBITS(32); */
  20088. while (bits < 32) {
  20089. if (have === 0) { break inf_leave; }
  20090. have--;
  20091. hold += input[next++] << bits;
  20092. bits += 8;
  20093. }
  20094. //===//
  20095. strm.adler = state.check = ZSWAP32(hold);
  20096. //=== INITBITS();
  20097. hold = 0;
  20098. bits = 0;
  20099. //===//
  20100. state.mode = DICT;
  20101. /* falls through */
  20102. case DICT:
  20103. if (state.havedict === 0) {
  20104. //--- RESTORE() ---
  20105. strm.next_out = put;
  20106. strm.avail_out = left;
  20107. strm.next_in = next;
  20108. strm.avail_in = have;
  20109. state.hold = hold;
  20110. state.bits = bits;
  20111. //---
  20112. return Z_NEED_DICT;
  20113. }
  20114. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20115. state.mode = TYPE;
  20116. /* falls through */
  20117. case TYPE:
  20118. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  20119. /* falls through */
  20120. case TYPEDO:
  20121. if (state.last) {
  20122. //--- BYTEBITS() ---//
  20123. hold >>>= bits & 7;
  20124. bits -= bits & 7;
  20125. //---//
  20126. state.mode = CHECK;
  20127. break;
  20128. }
  20129. //=== NEEDBITS(3); */
  20130. while (bits < 3) {
  20131. if (have === 0) { break inf_leave; }
  20132. have--;
  20133. hold += input[next++] << bits;
  20134. bits += 8;
  20135. }
  20136. //===//
  20137. state.last = (hold & 0x01)/*BITS(1)*/;
  20138. //--- DROPBITS(1) ---//
  20139. hold >>>= 1;
  20140. bits -= 1;
  20141. //---//
  20142. switch ((hold & 0x03)/*BITS(2)*/) {
  20143. case 0: /* stored block */
  20144. //Tracev((stderr, "inflate: stored block%s\n",
  20145. // state.last ? " (last)" : ""));
  20146. state.mode = STORED;
  20147. break;
  20148. case 1: /* fixed block */
  20149. fixedtables(state);
  20150. //Tracev((stderr, "inflate: fixed codes block%s\n",
  20151. // state.last ? " (last)" : ""));
  20152. state.mode = LEN_; /* decode codes */
  20153. if (flush === Z_TREES) {
  20154. //--- DROPBITS(2) ---//
  20155. hold >>>= 2;
  20156. bits -= 2;
  20157. //---//
  20158. break inf_leave;
  20159. }
  20160. break;
  20161. case 2: /* dynamic block */
  20162. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  20163. // state.last ? " (last)" : ""));
  20164. state.mode = TABLE;
  20165. break;
  20166. case 3:
  20167. strm.msg = 'invalid block type';
  20168. state.mode = BAD;
  20169. }
  20170. //--- DROPBITS(2) ---//
  20171. hold >>>= 2;
  20172. bits -= 2;
  20173. //---//
  20174. break;
  20175. case STORED:
  20176. //--- BYTEBITS() ---// /* go to byte boundary */
  20177. hold >>>= bits & 7;
  20178. bits -= bits & 7;
  20179. //---//
  20180. //=== NEEDBITS(32); */
  20181. while (bits < 32) {
  20182. if (have === 0) { break inf_leave; }
  20183. have--;
  20184. hold += input[next++] << bits;
  20185. bits += 8;
  20186. }
  20187. //===//
  20188. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  20189. strm.msg = 'invalid stored block lengths';
  20190. state.mode = BAD;
  20191. break;
  20192. }
  20193. state.length = hold & 0xffff;
  20194. //Tracev((stderr, "inflate: stored length %u\n",
  20195. // state.length));
  20196. //=== INITBITS();
  20197. hold = 0;
  20198. bits = 0;
  20199. //===//
  20200. state.mode = COPY_;
  20201. if (flush === Z_TREES) { break inf_leave; }
  20202. /* falls through */
  20203. case COPY_:
  20204. state.mode = COPY;
  20205. /* falls through */
  20206. case COPY:
  20207. copy = state.length;
  20208. if (copy) {
  20209. if (copy > have) { copy = have; }
  20210. if (copy > left) { copy = left; }
  20211. if (copy === 0) { break inf_leave; }
  20212. //--- zmemcpy(put, next, copy); ---
  20213. utils.arraySet(output, input, next, copy, put);
  20214. //---//
  20215. have -= copy;
  20216. next += copy;
  20217. left -= copy;
  20218. put += copy;
  20219. state.length -= copy;
  20220. break;
  20221. }
  20222. //Tracev((stderr, "inflate: stored end\n"));
  20223. state.mode = TYPE;
  20224. break;
  20225. case TABLE:
  20226. //=== NEEDBITS(14); */
  20227. while (bits < 14) {
  20228. if (have === 0) { break inf_leave; }
  20229. have--;
  20230. hold += input[next++] << bits;
  20231. bits += 8;
  20232. }
  20233. //===//
  20234. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  20235. //--- DROPBITS(5) ---//
  20236. hold >>>= 5;
  20237. bits -= 5;
  20238. //---//
  20239. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  20240. //--- DROPBITS(5) ---//
  20241. hold >>>= 5;
  20242. bits -= 5;
  20243. //---//
  20244. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  20245. //--- DROPBITS(4) ---//
  20246. hold >>>= 4;
  20247. bits -= 4;
  20248. //---//
  20249. //#ifndef PKZIP_BUG_WORKAROUND
  20250. if (state.nlen > 286 || state.ndist > 30) {
  20251. strm.msg = 'too many length or distance symbols';
  20252. state.mode = BAD;
  20253. break;
  20254. }
  20255. //#endif
  20256. //Tracev((stderr, "inflate: table sizes ok\n"));
  20257. state.have = 0;
  20258. state.mode = LENLENS;
  20259. /* falls through */
  20260. case LENLENS:
  20261. while (state.have < state.ncode) {
  20262. //=== NEEDBITS(3);
  20263. while (bits < 3) {
  20264. if (have === 0) { break inf_leave; }
  20265. have--;
  20266. hold += input[next++] << bits;
  20267. bits += 8;
  20268. }
  20269. //===//
  20270. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  20271. //--- DROPBITS(3) ---//
  20272. hold >>>= 3;
  20273. bits -= 3;
  20274. //---//
  20275. }
  20276. while (state.have < 19) {
  20277. state.lens[order[state.have++]] = 0;
  20278. }
  20279. // We have separate tables & no pointers. 2 commented lines below not needed.
  20280. //state.next = state.codes;
  20281. //state.lencode = state.next;
  20282. // Switch to use dynamic table
  20283. state.lencode = state.lendyn;
  20284. state.lenbits = 7;
  20285. opts = {bits: state.lenbits};
  20286. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  20287. state.lenbits = opts.bits;
  20288. if (ret) {
  20289. strm.msg = 'invalid code lengths set';
  20290. state.mode = BAD;
  20291. break;
  20292. }
  20293. //Tracev((stderr, "inflate: code lengths ok\n"));
  20294. state.have = 0;
  20295. state.mode = CODELENS;
  20296. /* falls through */
  20297. case CODELENS:
  20298. while (state.have < state.nlen + state.ndist) {
  20299. for (;;) {
  20300. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  20301. here_bits = here >>> 24;
  20302. here_op = (here >>> 16) & 0xff;
  20303. here_val = here & 0xffff;
  20304. if ((here_bits) <= bits) { break; }
  20305. //--- PULLBYTE() ---//
  20306. if (have === 0) { break inf_leave; }
  20307. have--;
  20308. hold += input[next++] << bits;
  20309. bits += 8;
  20310. //---//
  20311. }
  20312. if (here_val < 16) {
  20313. //--- DROPBITS(here.bits) ---//
  20314. hold >>>= here_bits;
  20315. bits -= here_bits;
  20316. //---//
  20317. state.lens[state.have++] = here_val;
  20318. }
  20319. else {
  20320. if (here_val === 16) {
  20321. //=== NEEDBITS(here.bits + 2);
  20322. n = here_bits + 2;
  20323. while (bits < n) {
  20324. if (have === 0) { break inf_leave; }
  20325. have--;
  20326. hold += input[next++] << bits;
  20327. bits += 8;
  20328. }
  20329. //===//
  20330. //--- DROPBITS(here.bits) ---//
  20331. hold >>>= here_bits;
  20332. bits -= here_bits;
  20333. //---//
  20334. if (state.have === 0) {
  20335. strm.msg = 'invalid bit length repeat';
  20336. state.mode = BAD;
  20337. break;
  20338. }
  20339. len = state.lens[state.have - 1];
  20340. copy = 3 + (hold & 0x03);//BITS(2);
  20341. //--- DROPBITS(2) ---//
  20342. hold >>>= 2;
  20343. bits -= 2;
  20344. //---//
  20345. }
  20346. else if (here_val === 17) {
  20347. //=== NEEDBITS(here.bits + 3);
  20348. n = here_bits + 3;
  20349. while (bits < n) {
  20350. if (have === 0) { break inf_leave; }
  20351. have--;
  20352. hold += input[next++] << bits;
  20353. bits += 8;
  20354. }
  20355. //===//
  20356. //--- DROPBITS(here.bits) ---//
  20357. hold >>>= here_bits;
  20358. bits -= here_bits;
  20359. //---//
  20360. len = 0;
  20361. copy = 3 + (hold & 0x07);//BITS(3);
  20362. //--- DROPBITS(3) ---//
  20363. hold >>>= 3;
  20364. bits -= 3;
  20365. //---//
  20366. }
  20367. else {
  20368. //=== NEEDBITS(here.bits + 7);
  20369. n = here_bits + 7;
  20370. while (bits < n) {
  20371. if (have === 0) { break inf_leave; }
  20372. have--;
  20373. hold += input[next++] << bits;
  20374. bits += 8;
  20375. }
  20376. //===//
  20377. //--- DROPBITS(here.bits) ---//
  20378. hold >>>= here_bits;
  20379. bits -= here_bits;
  20380. //---//
  20381. len = 0;
  20382. copy = 11 + (hold & 0x7f);//BITS(7);
  20383. //--- DROPBITS(7) ---//
  20384. hold >>>= 7;
  20385. bits -= 7;
  20386. //---//
  20387. }
  20388. if (state.have + copy > state.nlen + state.ndist) {
  20389. strm.msg = 'invalid bit length repeat';
  20390. state.mode = BAD;
  20391. break;
  20392. }
  20393. while (copy--) {
  20394. state.lens[state.have++] = len;
  20395. }
  20396. }
  20397. }
  20398. /* handle error breaks in while */
  20399. if (state.mode === BAD) { break; }
  20400. /* check for end-of-block code (better have one) */
  20401. if (state.lens[256] === 0) {
  20402. strm.msg = 'invalid code -- missing end-of-block';
  20403. state.mode = BAD;
  20404. break;
  20405. }
  20406. /* build code tables -- note: do not change the lenbits or distbits
  20407. values here (9 and 6) without reading the comments in inftrees.h
  20408. concerning the ENOUGH constants, which depend on those values */
  20409. state.lenbits = 9;
  20410. opts = {bits: state.lenbits};
  20411. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  20412. // We have separate tables & no pointers. 2 commented lines below not needed.
  20413. // state.next_index = opts.table_index;
  20414. state.lenbits = opts.bits;
  20415. // state.lencode = state.next;
  20416. if (ret) {
  20417. strm.msg = 'invalid literal/lengths set';
  20418. state.mode = BAD;
  20419. break;
  20420. }
  20421. state.distbits = 6;
  20422. //state.distcode.copy(state.codes);
  20423. // Switch to use dynamic table
  20424. state.distcode = state.distdyn;
  20425. opts = {bits: state.distbits};
  20426. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  20427. // We have separate tables & no pointers. 2 commented lines below not needed.
  20428. // state.next_index = opts.table_index;
  20429. state.distbits = opts.bits;
  20430. // state.distcode = state.next;
  20431. if (ret) {
  20432. strm.msg = 'invalid distances set';
  20433. state.mode = BAD;
  20434. break;
  20435. }
  20436. //Tracev((stderr, 'inflate: codes ok\n'));
  20437. state.mode = LEN_;
  20438. if (flush === Z_TREES) { break inf_leave; }
  20439. /* falls through */
  20440. case LEN_:
  20441. state.mode = LEN;
  20442. /* falls through */
  20443. case LEN:
  20444. if (have >= 6 && left >= 258) {
  20445. //--- RESTORE() ---
  20446. strm.next_out = put;
  20447. strm.avail_out = left;
  20448. strm.next_in = next;
  20449. strm.avail_in = have;
  20450. state.hold = hold;
  20451. state.bits = bits;
  20452. //---
  20453. inflate_fast(strm, _out);
  20454. //--- LOAD() ---
  20455. put = strm.next_out;
  20456. output = strm.output;
  20457. left = strm.avail_out;
  20458. next = strm.next_in;
  20459. input = strm.input;
  20460. have = strm.avail_in;
  20461. hold = state.hold;
  20462. bits = state.bits;
  20463. //---
  20464. if (state.mode === TYPE) {
  20465. state.back = -1;
  20466. }
  20467. break;
  20468. }
  20469. state.back = 0;
  20470. for (;;) {
  20471. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  20472. here_bits = here >>> 24;
  20473. here_op = (here >>> 16) & 0xff;
  20474. here_val = here & 0xffff;
  20475. if (here_bits <= bits) { break; }
  20476. //--- PULLBYTE() ---//
  20477. if (have === 0) { break inf_leave; }
  20478. have--;
  20479. hold += input[next++] << bits;
  20480. bits += 8;
  20481. //---//
  20482. }
  20483. if (here_op && (here_op & 0xf0) === 0) {
  20484. last_bits = here_bits;
  20485. last_op = here_op;
  20486. last_val = here_val;
  20487. for (;;) {
  20488. here = state.lencode[last_val +
  20489. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20490. here_bits = here >>> 24;
  20491. here_op = (here >>> 16) & 0xff;
  20492. here_val = here & 0xffff;
  20493. if ((last_bits + here_bits) <= bits) { break; }
  20494. //--- PULLBYTE() ---//
  20495. if (have === 0) { break inf_leave; }
  20496. have--;
  20497. hold += input[next++] << bits;
  20498. bits += 8;
  20499. //---//
  20500. }
  20501. //--- DROPBITS(last.bits) ---//
  20502. hold >>>= last_bits;
  20503. bits -= last_bits;
  20504. //---//
  20505. state.back += last_bits;
  20506. }
  20507. //--- DROPBITS(here.bits) ---//
  20508. hold >>>= here_bits;
  20509. bits -= here_bits;
  20510. //---//
  20511. state.back += here_bits;
  20512. state.length = here_val;
  20513. if (here_op === 0) {
  20514. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  20515. // "inflate: literal '%c'\n" :
  20516. // "inflate: literal 0x%02x\n", here.val));
  20517. state.mode = LIT;
  20518. break;
  20519. }
  20520. if (here_op & 32) {
  20521. //Tracevv((stderr, "inflate: end of block\n"));
  20522. state.back = -1;
  20523. state.mode = TYPE;
  20524. break;
  20525. }
  20526. if (here_op & 64) {
  20527. strm.msg = 'invalid literal/length code';
  20528. state.mode = BAD;
  20529. break;
  20530. }
  20531. state.extra = here_op & 15;
  20532. state.mode = LENEXT;
  20533. /* falls through */
  20534. case LENEXT:
  20535. if (state.extra) {
  20536. //=== NEEDBITS(state.extra);
  20537. n = state.extra;
  20538. while (bits < n) {
  20539. if (have === 0) { break inf_leave; }
  20540. have--;
  20541. hold += input[next++] << bits;
  20542. bits += 8;
  20543. }
  20544. //===//
  20545. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20546. //--- DROPBITS(state.extra) ---//
  20547. hold >>>= state.extra;
  20548. bits -= state.extra;
  20549. //---//
  20550. state.back += state.extra;
  20551. }
  20552. //Tracevv((stderr, "inflate: length %u\n", state.length));
  20553. state.was = state.length;
  20554. state.mode = DIST;
  20555. /* falls through */
  20556. case DIST:
  20557. for (;;) {
  20558. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  20559. here_bits = here >>> 24;
  20560. here_op = (here >>> 16) & 0xff;
  20561. here_val = here & 0xffff;
  20562. if ((here_bits) <= bits) { break; }
  20563. //--- PULLBYTE() ---//
  20564. if (have === 0) { break inf_leave; }
  20565. have--;
  20566. hold += input[next++] << bits;
  20567. bits += 8;
  20568. //---//
  20569. }
  20570. if ((here_op & 0xf0) === 0) {
  20571. last_bits = here_bits;
  20572. last_op = here_op;
  20573. last_val = here_val;
  20574. for (;;) {
  20575. here = state.distcode[last_val +
  20576. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20577. here_bits = here >>> 24;
  20578. here_op = (here >>> 16) & 0xff;
  20579. here_val = here & 0xffff;
  20580. if ((last_bits + here_bits) <= bits) { break; }
  20581. //--- PULLBYTE() ---//
  20582. if (have === 0) { break inf_leave; }
  20583. have--;
  20584. hold += input[next++] << bits;
  20585. bits += 8;
  20586. //---//
  20587. }
  20588. //--- DROPBITS(last.bits) ---//
  20589. hold >>>= last_bits;
  20590. bits -= last_bits;
  20591. //---//
  20592. state.back += last_bits;
  20593. }
  20594. //--- DROPBITS(here.bits) ---//
  20595. hold >>>= here_bits;
  20596. bits -= here_bits;
  20597. //---//
  20598. state.back += here_bits;
  20599. if (here_op & 64) {
  20600. strm.msg = 'invalid distance code';
  20601. state.mode = BAD;
  20602. break;
  20603. }
  20604. state.offset = here_val;
  20605. state.extra = (here_op) & 15;
  20606. state.mode = DISTEXT;
  20607. /* falls through */
  20608. case DISTEXT:
  20609. if (state.extra) {
  20610. //=== NEEDBITS(state.extra);
  20611. n = state.extra;
  20612. while (bits < n) {
  20613. if (have === 0) { break inf_leave; }
  20614. have--;
  20615. hold += input[next++] << bits;
  20616. bits += 8;
  20617. }
  20618. //===//
  20619. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20620. //--- DROPBITS(state.extra) ---//
  20621. hold >>>= state.extra;
  20622. bits -= state.extra;
  20623. //---//
  20624. state.back += state.extra;
  20625. }
  20626. //#ifdef INFLATE_STRICT
  20627. if (state.offset > state.dmax) {
  20628. strm.msg = 'invalid distance too far back';
  20629. state.mode = BAD;
  20630. break;
  20631. }
  20632. //#endif
  20633. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  20634. state.mode = MATCH;
  20635. /* falls through */
  20636. case MATCH:
  20637. if (left === 0) { break inf_leave; }
  20638. copy = _out - left;
  20639. if (state.offset > copy) { /* copy from window */
  20640. copy = state.offset - copy;
  20641. if (copy > state.whave) {
  20642. if (state.sane) {
  20643. strm.msg = 'invalid distance too far back';
  20644. state.mode = BAD;
  20645. break;
  20646. }
  20647. // (!) This block is disabled in zlib defailts,
  20648. // don't enable it for binary compatibility
  20649. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  20650. // Trace((stderr, "inflate.c too far\n"));
  20651. // copy -= state.whave;
  20652. // if (copy > state.length) { copy = state.length; }
  20653. // if (copy > left) { copy = left; }
  20654. // left -= copy;
  20655. // state.length -= copy;
  20656. // do {
  20657. // output[put++] = 0;
  20658. // } while (--copy);
  20659. // if (state.length === 0) { state.mode = LEN; }
  20660. // break;
  20661. //#endif
  20662. }
  20663. if (copy > state.wnext) {
  20664. copy -= state.wnext;
  20665. from = state.wsize - copy;
  20666. }
  20667. else {
  20668. from = state.wnext - copy;
  20669. }
  20670. if (copy > state.length) { copy = state.length; }
  20671. from_source = state.window;
  20672. }
  20673. else { /* copy from output */
  20674. from_source = output;
  20675. from = put - state.offset;
  20676. copy = state.length;
  20677. }
  20678. if (copy > left) { copy = left; }
  20679. left -= copy;
  20680. state.length -= copy;
  20681. do {
  20682. output[put++] = from_source[from++];
  20683. } while (--copy);
  20684. if (state.length === 0) { state.mode = LEN; }
  20685. break;
  20686. case LIT:
  20687. if (left === 0) { break inf_leave; }
  20688. output[put++] = state.length;
  20689. left--;
  20690. state.mode = LEN;
  20691. break;
  20692. case CHECK:
  20693. if (state.wrap) {
  20694. //=== NEEDBITS(32);
  20695. while (bits < 32) {
  20696. if (have === 0) { break inf_leave; }
  20697. have--;
  20698. // Use '|' insdead of '+' to make sure that result is signed
  20699. hold |= input[next++] << bits;
  20700. bits += 8;
  20701. }
  20702. //===//
  20703. _out -= left;
  20704. strm.total_out += _out;
  20705. state.total += _out;
  20706. if (_out) {
  20707. strm.adler = state.check =
  20708. /*UPDATE(state.check, put - _out, _out);*/
  20709. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  20710. }
  20711. _out = left;
  20712. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  20713. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  20714. strm.msg = 'incorrect data check';
  20715. state.mode = BAD;
  20716. break;
  20717. }
  20718. //=== INITBITS();
  20719. hold = 0;
  20720. bits = 0;
  20721. //===//
  20722. //Tracev((stderr, "inflate: check matches trailer\n"));
  20723. }
  20724. state.mode = LENGTH;
  20725. /* falls through */
  20726. case LENGTH:
  20727. if (state.wrap && state.flags) {
  20728. //=== NEEDBITS(32);
  20729. while (bits < 32) {
  20730. if (have === 0) { break inf_leave; }
  20731. have--;
  20732. hold += input[next++] << bits;
  20733. bits += 8;
  20734. }
  20735. //===//
  20736. if (hold !== (state.total & 0xffffffff)) {
  20737. strm.msg = 'incorrect length check';
  20738. state.mode = BAD;
  20739. break;
  20740. }
  20741. //=== INITBITS();
  20742. hold = 0;
  20743. bits = 0;
  20744. //===//
  20745. //Tracev((stderr, "inflate: length matches trailer\n"));
  20746. }
  20747. state.mode = DONE;
  20748. /* falls through */
  20749. case DONE:
  20750. ret = Z_STREAM_END;
  20751. break inf_leave;
  20752. case BAD:
  20753. ret = Z_DATA_ERROR;
  20754. break inf_leave;
  20755. case MEM:
  20756. return Z_MEM_ERROR;
  20757. case SYNC:
  20758. /* falls through */
  20759. default:
  20760. return Z_STREAM_ERROR;
  20761. }
  20762. }
  20763. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  20764. /*
  20765. Return from inflate(), updating the total counts and the check value.
  20766. If there was no progress during the inflate() call, return a buffer
  20767. error. Call updatewindow() to create and/or update the window state.
  20768. Note: a memory error from inflate() is non-recoverable.
  20769. */
  20770. //--- RESTORE() ---
  20771. strm.next_out = put;
  20772. strm.avail_out = left;
  20773. strm.next_in = next;
  20774. strm.avail_in = have;
  20775. state.hold = hold;
  20776. state.bits = bits;
  20777. //---
  20778. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  20779. (state.mode < CHECK || flush !== Z_FINISH))) {
  20780. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  20781. state.mode = MEM;
  20782. return Z_MEM_ERROR;
  20783. }
  20784. }
  20785. _in -= strm.avail_in;
  20786. _out -= strm.avail_out;
  20787. strm.total_in += _in;
  20788. strm.total_out += _out;
  20789. state.total += _out;
  20790. if (state.wrap && _out) {
  20791. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  20792. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  20793. }
  20794. strm.data_type = state.bits + (state.last ? 64 : 0) +
  20795. (state.mode === TYPE ? 128 : 0) +
  20796. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  20797. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  20798. ret = Z_BUF_ERROR;
  20799. }
  20800. return ret;
  20801. }
  20802. function inflateEnd(strm) {
  20803. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  20804. return Z_STREAM_ERROR;
  20805. }
  20806. var state = strm.state;
  20807. if (state.window) {
  20808. state.window = null;
  20809. }
  20810. strm.state = null;
  20811. return Z_OK;
  20812. }
  20813. function inflateGetHeader(strm, head) {
  20814. var state;
  20815. /* check state */
  20816. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20817. state = strm.state;
  20818. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  20819. /* save header structure */
  20820. state.head = head;
  20821. head.done = false;
  20822. return Z_OK;
  20823. }
  20824. exports.inflateReset = inflateReset;
  20825. exports.inflateReset2 = inflateReset2;
  20826. exports.inflateResetKeep = inflateResetKeep;
  20827. exports.inflateInit = inflateInit;
  20828. exports.inflateInit2 = inflateInit2;
  20829. exports.inflate = inflate;
  20830. exports.inflateEnd = inflateEnd;
  20831. exports.inflateGetHeader = inflateGetHeader;
  20832. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  20833. /* Not implemented
  20834. exports.inflateCopy = inflateCopy;
  20835. exports.inflateGetDictionary = inflateGetDictionary;
  20836. exports.inflateMark = inflateMark;
  20837. exports.inflatePrime = inflatePrime;
  20838. exports.inflateSetDictionary = inflateSetDictionary;
  20839. exports.inflateSync = inflateSync;
  20840. exports.inflateSyncPoint = inflateSyncPoint;
  20841. exports.inflateUndermine = inflateUndermine;
  20842. */
  20843. },{"../utils/common":65,"./adler32":67,"./crc32":69,"./inffast":72,"./inftrees":74}],74:[function(require,module,exports){
  20844. 'use strict';
  20845. var utils = require('../utils/common');
  20846. var MAXBITS = 15;
  20847. var ENOUGH_LENS = 852;
  20848. var ENOUGH_DISTS = 592;
  20849. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  20850. var CODES = 0;
  20851. var LENS = 1;
  20852. var DISTS = 2;
  20853. var lbase = [ /* Length codes 257..285 base */
  20854. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  20855. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  20856. ];
  20857. var lext = [ /* Length codes 257..285 extra */
  20858. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  20859. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  20860. ];
  20861. var dbase = [ /* Distance codes 0..29 base */
  20862. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  20863. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  20864. 8193, 12289, 16385, 24577, 0, 0
  20865. ];
  20866. var dext = [ /* Distance codes 0..29 extra */
  20867. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  20868. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  20869. 28, 28, 29, 29, 64, 64
  20870. ];
  20871. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  20872. {
  20873. var bits = opts.bits;
  20874. //here = opts.here; /* table entry for duplication */
  20875. var len = 0; /* a code's length in bits */
  20876. var sym = 0; /* index of code symbols */
  20877. var min = 0, max = 0; /* minimum and maximum code lengths */
  20878. var root = 0; /* number of index bits for root table */
  20879. var curr = 0; /* number of index bits for current table */
  20880. var drop = 0; /* code bits to drop for sub-table */
  20881. var left = 0; /* number of prefix codes available */
  20882. var used = 0; /* code entries in table used */
  20883. var huff = 0; /* Huffman code */
  20884. var incr; /* for incrementing code, index */
  20885. var fill; /* index for replicating entries */
  20886. var low; /* low bits for current root entry */
  20887. var mask; /* mask for low root bits */
  20888. var next; /* next available space in table */
  20889. var base = null; /* base value table to use */
  20890. var base_index = 0;
  20891. // var shoextra; /* extra bits table to use */
  20892. var end; /* use base and extra for symbol > end */
  20893. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  20894. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  20895. var extra = null;
  20896. var extra_index = 0;
  20897. var here_bits, here_op, here_val;
  20898. /*
  20899. Process a set of code lengths to create a canonical Huffman code. The
  20900. code lengths are lens[0..codes-1]. Each length corresponds to the
  20901. symbols 0..codes-1. The Huffman code is generated by first sorting the
  20902. symbols by length from short to long, and retaining the symbol order
  20903. for codes with equal lengths. Then the code starts with all zero bits
  20904. for the first code of the shortest length, and the codes are integer
  20905. increments for the same length, and zeros are appended as the length
  20906. increases. For the deflate format, these bits are stored backwards
  20907. from their more natural integer increment ordering, and so when the
  20908. decoding tables are built in the large loop below, the integer codes
  20909. are incremented backwards.
  20910. This routine assumes, but does not check, that all of the entries in
  20911. lens[] are in the range 0..MAXBITS. The caller must assure this.
  20912. 1..MAXBITS is interpreted as that code length. zero means that that
  20913. symbol does not occur in this code.
  20914. The codes are sorted by computing a count of codes for each length,
  20915. creating from that a table of starting indices for each length in the
  20916. sorted table, and then entering the symbols in order in the sorted
  20917. table. The sorted table is work[], with that space being provided by
  20918. the caller.
  20919. The length counts are used for other purposes as well, i.e. finding
  20920. the minimum and maximum length codes, determining if there are any
  20921. codes at all, checking for a valid set of lengths, and looking ahead
  20922. at length counts to determine sub-table sizes when building the
  20923. decoding tables.
  20924. */
  20925. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  20926. for (len = 0; len <= MAXBITS; len++) {
  20927. count[len] = 0;
  20928. }
  20929. for (sym = 0; sym < codes; sym++) {
  20930. count[lens[lens_index + sym]]++;
  20931. }
  20932. /* bound code lengths, force root to be within code lengths */
  20933. root = bits;
  20934. for (max = MAXBITS; max >= 1; max--) {
  20935. if (count[max] !== 0) { break; }
  20936. }
  20937. if (root > max) {
  20938. root = max;
  20939. }
  20940. if (max === 0) { /* no symbols to code at all */
  20941. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  20942. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  20943. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  20944. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  20945. //table.op[opts.table_index] = 64;
  20946. //table.bits[opts.table_index] = 1;
  20947. //table.val[opts.table_index++] = 0;
  20948. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  20949. opts.bits = 1;
  20950. return 0; /* no symbols, but wait for decoding to report error */
  20951. }
  20952. for (min = 1; min < max; min++) {
  20953. if (count[min] !== 0) { break; }
  20954. }
  20955. if (root < min) {
  20956. root = min;
  20957. }
  20958. /* check for an over-subscribed or incomplete set of lengths */
  20959. left = 1;
  20960. for (len = 1; len <= MAXBITS; len++) {
  20961. left <<= 1;
  20962. left -= count[len];
  20963. if (left < 0) {
  20964. return -1;
  20965. } /* over-subscribed */
  20966. }
  20967. if (left > 0 && (type === CODES || max !== 1)) {
  20968. return -1; /* incomplete set */
  20969. }
  20970. /* generate offsets into symbol table for each length for sorting */
  20971. offs[1] = 0;
  20972. for (len = 1; len < MAXBITS; len++) {
  20973. offs[len + 1] = offs[len] + count[len];
  20974. }
  20975. /* sort symbols by length, by symbol order within each length */
  20976. for (sym = 0; sym < codes; sym++) {
  20977. if (lens[lens_index + sym] !== 0) {
  20978. work[offs[lens[lens_index + sym]]++] = sym;
  20979. }
  20980. }
  20981. /*
  20982. Create and fill in decoding tables. In this loop, the table being
  20983. filled is at next and has curr index bits. The code being used is huff
  20984. with length len. That code is converted to an index by dropping drop
  20985. bits off of the bottom. For codes where len is less than drop + curr,
  20986. those top drop + curr - len bits are incremented through all values to
  20987. fill the table with replicated entries.
  20988. root is the number of index bits for the root table. When len exceeds
  20989. root, sub-tables are created pointed to by the root entry with an index
  20990. of the low root bits of huff. This is saved in low to check for when a
  20991. new sub-table should be started. drop is zero when the root table is
  20992. being filled, and drop is root when sub-tables are being filled.
  20993. When a new sub-table is needed, it is necessary to look ahead in the
  20994. code lengths to determine what size sub-table is needed. The length
  20995. counts are used for this, and so count[] is decremented as codes are
  20996. entered in the tables.
  20997. used keeps track of how many table entries have been allocated from the
  20998. provided *table space. It is checked for LENS and DIST tables against
  20999. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  21000. the initial root table size constants. See the comments in inftrees.h
  21001. for more information.
  21002. sym increments through all symbols, and the loop terminates when
  21003. all codes of length max, i.e. all codes, have been processed. This
  21004. routine permits incomplete codes, so another loop after this one fills
  21005. in the rest of the decoding tables with invalid code markers.
  21006. */
  21007. /* set up for code type */
  21008. // poor man optimization - use if-else instead of switch,
  21009. // to avoid deopts in old v8
  21010. if (type === CODES) {
  21011. base = extra = work; /* dummy value--not used */
  21012. end = 19;
  21013. } else if (type === LENS) {
  21014. base = lbase;
  21015. base_index -= 257;
  21016. extra = lext;
  21017. extra_index -= 257;
  21018. end = 256;
  21019. } else { /* DISTS */
  21020. base = dbase;
  21021. extra = dext;
  21022. end = -1;
  21023. }
  21024. /* initialize opts for loop */
  21025. huff = 0; /* starting code */
  21026. sym = 0; /* starting code symbol */
  21027. len = min; /* starting code length */
  21028. next = table_index; /* current table to fill in */
  21029. curr = root; /* current table index bits */
  21030. drop = 0; /* current bits to drop from code for index */
  21031. low = -1; /* trigger new sub-table when len > root */
  21032. used = 1 << root; /* use root table entries */
  21033. mask = used - 1; /* mask for comparing low */
  21034. /* check available table space */
  21035. if ((type === LENS && used > ENOUGH_LENS) ||
  21036. (type === DISTS && used > ENOUGH_DISTS)) {
  21037. return 1;
  21038. }
  21039. var i=0;
  21040. /* process all codes and make table entries */
  21041. for (;;) {
  21042. i++;
  21043. /* create table entry */
  21044. here_bits = len - drop;
  21045. if (work[sym] < end) {
  21046. here_op = 0;
  21047. here_val = work[sym];
  21048. }
  21049. else if (work[sym] > end) {
  21050. here_op = extra[extra_index + work[sym]];
  21051. here_val = base[base_index + work[sym]];
  21052. }
  21053. else {
  21054. here_op = 32 + 64; /* end of block */
  21055. here_val = 0;
  21056. }
  21057. /* replicate for those indices with low len bits equal to huff */
  21058. incr = 1 << (len - drop);
  21059. fill = 1 << curr;
  21060. min = fill; /* save offset to next table */
  21061. do {
  21062. fill -= incr;
  21063. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  21064. } while (fill !== 0);
  21065. /* backwards increment the len-bit code huff */
  21066. incr = 1 << (len - 1);
  21067. while (huff & incr) {
  21068. incr >>= 1;
  21069. }
  21070. if (incr !== 0) {
  21071. huff &= incr - 1;
  21072. huff += incr;
  21073. } else {
  21074. huff = 0;
  21075. }
  21076. /* go to next symbol, update count, len */
  21077. sym++;
  21078. if (--count[len] === 0) {
  21079. if (len === max) { break; }
  21080. len = lens[lens_index + work[sym]];
  21081. }
  21082. /* create new sub-table if needed */
  21083. if (len > root && (huff & mask) !== low) {
  21084. /* if first time, transition to sub-tables */
  21085. if (drop === 0) {
  21086. drop = root;
  21087. }
  21088. /* increment past last table */
  21089. next += min; /* here min is 1 << curr */
  21090. /* determine length of next table */
  21091. curr = len - drop;
  21092. left = 1 << curr;
  21093. while (curr + drop < max) {
  21094. left -= count[curr + drop];
  21095. if (left <= 0) { break; }
  21096. curr++;
  21097. left <<= 1;
  21098. }
  21099. /* check for enough space */
  21100. used += 1 << curr;
  21101. if ((type === LENS && used > ENOUGH_LENS) ||
  21102. (type === DISTS && used > ENOUGH_DISTS)) {
  21103. return 1;
  21104. }
  21105. /* point entry in root table to sub-table */
  21106. low = huff & mask;
  21107. /*table.op[low] = curr;
  21108. table.bits[low] = root;
  21109. table.val[low] = next - opts.table_index;*/
  21110. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  21111. }
  21112. }
  21113. /* fill in remaining table entry if code is incomplete (guaranteed to have
  21114. at most one remaining entry, since if the code is incomplete, the
  21115. maximum code length that was allowed to get this far is one bit) */
  21116. if (huff !== 0) {
  21117. //table.op[next + huff] = 64; /* invalid code marker */
  21118. //table.bits[next + huff] = len - drop;
  21119. //table.val[next + huff] = 0;
  21120. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  21121. }
  21122. /* set return parameters */
  21123. //opts.table_index += used;
  21124. opts.bits = root;
  21125. return 0;
  21126. };
  21127. },{"../utils/common":65}],75:[function(require,module,exports){
  21128. 'use strict';
  21129. module.exports = {
  21130. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  21131. '1': 'stream end', /* Z_STREAM_END 1 */
  21132. '0': '', /* Z_OK 0 */
  21133. '-1': 'file error', /* Z_ERRNO (-1) */
  21134. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  21135. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  21136. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  21137. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  21138. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  21139. };
  21140. },{}],76:[function(require,module,exports){
  21141. 'use strict';
  21142. var utils = require('../utils/common');
  21143. /* Public constants ==========================================================*/
  21144. /* ===========================================================================*/
  21145. //var Z_FILTERED = 1;
  21146. //var Z_HUFFMAN_ONLY = 2;
  21147. //var Z_RLE = 3;
  21148. var Z_FIXED = 4;
  21149. //var Z_DEFAULT_STRATEGY = 0;
  21150. /* Possible values of the data_type field (though see inflate()) */
  21151. var Z_BINARY = 0;
  21152. var Z_TEXT = 1;
  21153. //var Z_ASCII = 1; // = Z_TEXT
  21154. var Z_UNKNOWN = 2;
  21155. /*============================================================================*/
  21156. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  21157. // From zutil.h
  21158. var STORED_BLOCK = 0;
  21159. var STATIC_TREES = 1;
  21160. var DYN_TREES = 2;
  21161. /* The three kinds of block type */
  21162. var MIN_MATCH = 3;
  21163. var MAX_MATCH = 258;
  21164. /* The minimum and maximum match lengths */
  21165. // From deflate.h
  21166. /* ===========================================================================
  21167. * Internal compression state.
  21168. */
  21169. var LENGTH_CODES = 29;
  21170. /* number of length codes, not counting the special END_BLOCK code */
  21171. var LITERALS = 256;
  21172. /* number of literal bytes 0..255 */
  21173. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  21174. /* number of Literal or Length codes, including the END_BLOCK code */
  21175. var D_CODES = 30;
  21176. /* number of distance codes */
  21177. var BL_CODES = 19;
  21178. /* number of codes used to transfer the bit lengths */
  21179. var HEAP_SIZE = 2*L_CODES + 1;
  21180. /* maximum heap size */
  21181. var MAX_BITS = 15;
  21182. /* All codes must not exceed MAX_BITS bits */
  21183. var Buf_size = 16;
  21184. /* size of bit buffer in bi_buf */
  21185. /* ===========================================================================
  21186. * Constants
  21187. */
  21188. var MAX_BL_BITS = 7;
  21189. /* Bit length codes must not exceed MAX_BL_BITS bits */
  21190. var END_BLOCK = 256;
  21191. /* end of block literal code */
  21192. var REP_3_6 = 16;
  21193. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  21194. var REPZ_3_10 = 17;
  21195. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  21196. var REPZ_11_138 = 18;
  21197. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  21198. var extra_lbits = /* extra bits for each length code */
  21199. [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];
  21200. var extra_dbits = /* extra bits for each distance code */
  21201. [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];
  21202. var extra_blbits = /* extra bits for each bit length code */
  21203. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  21204. var bl_order =
  21205. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  21206. /* The lengths of the bit length codes are sent in order of decreasing
  21207. * probability, to avoid transmitting the lengths for unused bit length codes.
  21208. */
  21209. /* ===========================================================================
  21210. * Local data. These are initialized only once.
  21211. */
  21212. // We pre-fill arrays with 0 to avoid uninitialized gaps
  21213. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  21214. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  21215. var static_ltree = new Array((L_CODES+2) * 2);
  21216. zero(static_ltree);
  21217. /* The static literal tree. Since the bit lengths are imposed, there is no
  21218. * need for the L_CODES extra codes used during heap construction. However
  21219. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  21220. * below).
  21221. */
  21222. var static_dtree = new Array(D_CODES * 2);
  21223. zero(static_dtree);
  21224. /* The static distance tree. (Actually a trivial tree since all codes use
  21225. * 5 bits.)
  21226. */
  21227. var _dist_code = new Array(DIST_CODE_LEN);
  21228. zero(_dist_code);
  21229. /* Distance codes. The first 256 values correspond to the distances
  21230. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  21231. * the 15 bit distances.
  21232. */
  21233. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  21234. zero(_length_code);
  21235. /* length code for each normalized match length (0 == MIN_MATCH) */
  21236. var base_length = new Array(LENGTH_CODES);
  21237. zero(base_length);
  21238. /* First normalized length for each code (0 = MIN_MATCH) */
  21239. var base_dist = new Array(D_CODES);
  21240. zero(base_dist);
  21241. /* First normalized distance for each code (0 = distance of 1) */
  21242. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  21243. this.static_tree = static_tree; /* static tree or NULL */
  21244. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  21245. this.extra_base = extra_base; /* base index for extra_bits */
  21246. this.elems = elems; /* max number of elements in the tree */
  21247. this.max_length = max_length; /* max bit length for the codes */
  21248. // show if `static_tree` has data or dummy - needed for monomorphic objects
  21249. this.has_stree = static_tree && static_tree.length;
  21250. };
  21251. var static_l_desc;
  21252. var static_d_desc;
  21253. var static_bl_desc;
  21254. var TreeDesc = function(dyn_tree, stat_desc) {
  21255. this.dyn_tree = dyn_tree; /* the dynamic tree */
  21256. this.max_code = 0; /* largest code with non zero frequency */
  21257. this.stat_desc = stat_desc; /* the corresponding static tree */
  21258. };
  21259. function d_code(dist) {
  21260. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  21261. }
  21262. /* ===========================================================================
  21263. * Output a short LSB first on the stream.
  21264. * IN assertion: there is enough room in pendingBuf.
  21265. */
  21266. function put_short (s, w) {
  21267. // put_byte(s, (uch)((w) & 0xff));
  21268. // put_byte(s, (uch)((ush)(w) >> 8));
  21269. s.pending_buf[s.pending++] = (w) & 0xff;
  21270. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  21271. }
  21272. /* ===========================================================================
  21273. * Send a value on a given number of bits.
  21274. * IN assertion: length <= 16 and value fits in length bits.
  21275. */
  21276. function send_bits(s, value, length) {
  21277. if (s.bi_valid > (Buf_size - length)) {
  21278. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21279. put_short(s, s.bi_buf);
  21280. s.bi_buf = value >> (Buf_size - s.bi_valid);
  21281. s.bi_valid += length - Buf_size;
  21282. } else {
  21283. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21284. s.bi_valid += length;
  21285. }
  21286. }
  21287. function send_code(s, c, tree) {
  21288. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  21289. }
  21290. /* ===========================================================================
  21291. * Reverse the first len bits of a code, using straightforward code (a faster
  21292. * method would use a table)
  21293. * IN assertion: 1 <= len <= 15
  21294. */
  21295. function bi_reverse(code, len) {
  21296. var res = 0;
  21297. do {
  21298. res |= code & 1;
  21299. code >>>= 1;
  21300. res <<= 1;
  21301. } while (--len > 0);
  21302. return res >>> 1;
  21303. }
  21304. /* ===========================================================================
  21305. * Flush the bit buffer, keeping at most 7 bits in it.
  21306. */
  21307. function bi_flush(s) {
  21308. if (s.bi_valid === 16) {
  21309. put_short(s, s.bi_buf);
  21310. s.bi_buf = 0;
  21311. s.bi_valid = 0;
  21312. } else if (s.bi_valid >= 8) {
  21313. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  21314. s.bi_buf >>= 8;
  21315. s.bi_valid -= 8;
  21316. }
  21317. }
  21318. /* ===========================================================================
  21319. * Compute the optimal bit lengths for a tree and update the total bit length
  21320. * for the current block.
  21321. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  21322. * above are the tree nodes sorted by increasing frequency.
  21323. * OUT assertions: the field len is set to the optimal bit length, the
  21324. * array bl_count contains the frequencies for each bit length.
  21325. * The length opt_len is updated; static_len is also updated if stree is
  21326. * not null.
  21327. */
  21328. function gen_bitlen(s, desc)
  21329. // deflate_state *s;
  21330. // tree_desc *desc; /* the tree descriptor */
  21331. {
  21332. var tree = desc.dyn_tree;
  21333. var max_code = desc.max_code;
  21334. var stree = desc.stat_desc.static_tree;
  21335. var has_stree = desc.stat_desc.has_stree;
  21336. var extra = desc.stat_desc.extra_bits;
  21337. var base = desc.stat_desc.extra_base;
  21338. var max_length = desc.stat_desc.max_length;
  21339. var h; /* heap index */
  21340. var n, m; /* iterate over the tree elements */
  21341. var bits; /* bit length */
  21342. var xbits; /* extra bits */
  21343. var f; /* frequency */
  21344. var overflow = 0; /* number of elements with bit length too large */
  21345. for (bits = 0; bits <= MAX_BITS; bits++) {
  21346. s.bl_count[bits] = 0;
  21347. }
  21348. /* In a first pass, compute the optimal bit lengths (which may
  21349. * overflow in the case of the bit length tree).
  21350. */
  21351. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  21352. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  21353. n = s.heap[h];
  21354. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  21355. if (bits > max_length) {
  21356. bits = max_length;
  21357. overflow++;
  21358. }
  21359. tree[n*2 + 1]/*.Len*/ = bits;
  21360. /* We overwrite tree[n].Dad which is no longer needed */
  21361. if (n > max_code) { continue; } /* not a leaf node */
  21362. s.bl_count[bits]++;
  21363. xbits = 0;
  21364. if (n >= base) {
  21365. xbits = extra[n-base];
  21366. }
  21367. f = tree[n * 2]/*.Freq*/;
  21368. s.opt_len += f * (bits + xbits);
  21369. if (has_stree) {
  21370. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  21371. }
  21372. }
  21373. if (overflow === 0) { return; }
  21374. // Trace((stderr,"\nbit length overflow\n"));
  21375. /* This happens for example on obj2 and pic of the Calgary corpus */
  21376. /* Find the first bit length which could increase: */
  21377. do {
  21378. bits = max_length-1;
  21379. while (s.bl_count[bits] === 0) { bits--; }
  21380. s.bl_count[bits]--; /* move one leaf down the tree */
  21381. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  21382. s.bl_count[max_length]--;
  21383. /* The brother of the overflow item also moves one step up,
  21384. * but this does not affect bl_count[max_length]
  21385. */
  21386. overflow -= 2;
  21387. } while (overflow > 0);
  21388. /* Now recompute all bit lengths, scanning in increasing frequency.
  21389. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  21390. * lengths instead of fixing only the wrong ones. This idea is taken
  21391. * from 'ar' written by Haruhiko Okumura.)
  21392. */
  21393. for (bits = max_length; bits !== 0; bits--) {
  21394. n = s.bl_count[bits];
  21395. while (n !== 0) {
  21396. m = s.heap[--h];
  21397. if (m > max_code) { continue; }
  21398. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  21399. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  21400. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  21401. tree[m*2 + 1]/*.Len*/ = bits;
  21402. }
  21403. n--;
  21404. }
  21405. }
  21406. }
  21407. /* ===========================================================================
  21408. * Generate the codes for a given tree and bit counts (which need not be
  21409. * optimal).
  21410. * IN assertion: the array bl_count contains the bit length statistics for
  21411. * the given tree and the field len is set for all tree elements.
  21412. * OUT assertion: the field code is set for all tree elements of non
  21413. * zero code length.
  21414. */
  21415. function gen_codes(tree, max_code, bl_count)
  21416. // ct_data *tree; /* the tree to decorate */
  21417. // int max_code; /* largest code with non zero frequency */
  21418. // ushf *bl_count; /* number of codes at each bit length */
  21419. {
  21420. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  21421. var code = 0; /* running code value */
  21422. var bits; /* bit index */
  21423. var n; /* code index */
  21424. /* The distribution counts are first used to generate the code values
  21425. * without bit reversal.
  21426. */
  21427. for (bits = 1; bits <= MAX_BITS; bits++) {
  21428. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  21429. }
  21430. /* Check that the bit counts in bl_count are consistent. The last code
  21431. * must be all ones.
  21432. */
  21433. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  21434. // "inconsistent bit counts");
  21435. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  21436. for (n = 0; n <= max_code; n++) {
  21437. var len = tree[n*2 + 1]/*.Len*/;
  21438. if (len === 0) { continue; }
  21439. /* Now reverse the bits */
  21440. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  21441. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  21442. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  21443. }
  21444. }
  21445. /* ===========================================================================
  21446. * Initialize the various 'constant' tables.
  21447. */
  21448. function tr_static_init() {
  21449. var n; /* iterates over tree elements */
  21450. var bits; /* bit counter */
  21451. var length; /* length value */
  21452. var code; /* code value */
  21453. var dist; /* distance index */
  21454. var bl_count = new Array(MAX_BITS+1);
  21455. /* number of codes at each bit length for an optimal tree */
  21456. // do check in _tr_init()
  21457. //if (static_init_done) return;
  21458. /* For some embedded targets, global variables are not initialized: */
  21459. /*#ifdef NO_INIT_GLOBAL_POINTERS
  21460. static_l_desc.static_tree = static_ltree;
  21461. static_l_desc.extra_bits = extra_lbits;
  21462. static_d_desc.static_tree = static_dtree;
  21463. static_d_desc.extra_bits = extra_dbits;
  21464. static_bl_desc.extra_bits = extra_blbits;
  21465. #endif*/
  21466. /* Initialize the mapping length (0..255) -> length code (0..28) */
  21467. length = 0;
  21468. for (code = 0; code < LENGTH_CODES-1; code++) {
  21469. base_length[code] = length;
  21470. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  21471. _length_code[length++] = code;
  21472. }
  21473. }
  21474. //Assert (length == 256, "tr_static_init: length != 256");
  21475. /* Note that the length 255 (match length 258) can be represented
  21476. * in two different ways: code 284 + 5 bits or code 285, so we
  21477. * overwrite length_code[255] to use the best encoding:
  21478. */
  21479. _length_code[length-1] = code;
  21480. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  21481. dist = 0;
  21482. for (code = 0 ; code < 16; code++) {
  21483. base_dist[code] = dist;
  21484. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  21485. _dist_code[dist++] = code;
  21486. }
  21487. }
  21488. //Assert (dist == 256, "tr_static_init: dist != 256");
  21489. dist >>= 7; /* from now on, all distances are divided by 128 */
  21490. for ( ; code < D_CODES; code++) {
  21491. base_dist[code] = dist << 7;
  21492. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  21493. _dist_code[256 + dist++] = code;
  21494. }
  21495. }
  21496. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  21497. /* Construct the codes of the static literal tree */
  21498. for (bits = 0; bits <= MAX_BITS; bits++) {
  21499. bl_count[bits] = 0;
  21500. }
  21501. n = 0;
  21502. while (n <= 143) {
  21503. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21504. n++;
  21505. bl_count[8]++;
  21506. }
  21507. while (n <= 255) {
  21508. static_ltree[n*2 + 1]/*.Len*/ = 9;
  21509. n++;
  21510. bl_count[9]++;
  21511. }
  21512. while (n <= 279) {
  21513. static_ltree[n*2 + 1]/*.Len*/ = 7;
  21514. n++;
  21515. bl_count[7]++;
  21516. }
  21517. while (n <= 287) {
  21518. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21519. n++;
  21520. bl_count[8]++;
  21521. }
  21522. /* Codes 286 and 287 do not exist, but we must include them in the
  21523. * tree construction to get a canonical Huffman tree (longest code
  21524. * all ones)
  21525. */
  21526. gen_codes(static_ltree, L_CODES+1, bl_count);
  21527. /* The static distance tree is trivial: */
  21528. for (n = 0; n < D_CODES; n++) {
  21529. static_dtree[n*2 + 1]/*.Len*/ = 5;
  21530. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  21531. }
  21532. // Now data ready and we can init static trees
  21533. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  21534. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  21535. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  21536. //static_init_done = true;
  21537. }
  21538. /* ===========================================================================
  21539. * Initialize a new block.
  21540. */
  21541. function init_block(s) {
  21542. var n; /* iterates over tree elements */
  21543. /* Initialize the trees. */
  21544. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  21545. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  21546. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  21547. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  21548. s.opt_len = s.static_len = 0;
  21549. s.last_lit = s.matches = 0;
  21550. }
  21551. /* ===========================================================================
  21552. * Flush the bit buffer and align the output on a byte boundary
  21553. */
  21554. function bi_windup(s)
  21555. {
  21556. if (s.bi_valid > 8) {
  21557. put_short(s, s.bi_buf);
  21558. } else if (s.bi_valid > 0) {
  21559. //put_byte(s, (Byte)s->bi_buf);
  21560. s.pending_buf[s.pending++] = s.bi_buf;
  21561. }
  21562. s.bi_buf = 0;
  21563. s.bi_valid = 0;
  21564. }
  21565. /* ===========================================================================
  21566. * Copy a stored block, storing first the length and its
  21567. * one's complement if requested.
  21568. */
  21569. function copy_block(s, buf, len, header)
  21570. //DeflateState *s;
  21571. //charf *buf; /* the input data */
  21572. //unsigned len; /* its length */
  21573. //int header; /* true if block header must be written */
  21574. {
  21575. bi_windup(s); /* align on byte boundary */
  21576. if (header) {
  21577. put_short(s, len);
  21578. put_short(s, ~len);
  21579. }
  21580. // while (len--) {
  21581. // put_byte(s, *buf++);
  21582. // }
  21583. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  21584. s.pending += len;
  21585. }
  21586. /* ===========================================================================
  21587. * Compares to subtrees, using the tree depth as tie breaker when
  21588. * the subtrees have equal frequency. This minimizes the worst case length.
  21589. */
  21590. function smaller(tree, n, m, depth) {
  21591. var _n2 = n*2;
  21592. var _m2 = m*2;
  21593. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  21594. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  21595. }
  21596. /* ===========================================================================
  21597. * Restore the heap property by moving down the tree starting at node k,
  21598. * exchanging a node with the smallest of its two sons if necessary, stopping
  21599. * when the heap property is re-established (each father smaller than its
  21600. * two sons).
  21601. */
  21602. function pqdownheap(s, tree, k)
  21603. // deflate_state *s;
  21604. // ct_data *tree; /* the tree to restore */
  21605. // int k; /* node to move down */
  21606. {
  21607. var v = s.heap[k];
  21608. var j = k << 1; /* left son of k */
  21609. while (j <= s.heap_len) {
  21610. /* Set j to the smallest of the two sons: */
  21611. if (j < s.heap_len &&
  21612. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  21613. j++;
  21614. }
  21615. /* Exit if v is smaller than both sons */
  21616. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  21617. /* Exchange v with the smallest son */
  21618. s.heap[k] = s.heap[j];
  21619. k = j;
  21620. /* And continue down the tree, setting j to the left son of k */
  21621. j <<= 1;
  21622. }
  21623. s.heap[k] = v;
  21624. }
  21625. // inlined manually
  21626. // var SMALLEST = 1;
  21627. /* ===========================================================================
  21628. * Send the block data compressed using the given Huffman trees
  21629. */
  21630. function compress_block(s, ltree, dtree)
  21631. // deflate_state *s;
  21632. // const ct_data *ltree; /* literal tree */
  21633. // const ct_data *dtree; /* distance tree */
  21634. {
  21635. var dist; /* distance of matched string */
  21636. var lc; /* match length or unmatched char (if dist == 0) */
  21637. var lx = 0; /* running index in l_buf */
  21638. var code; /* the code to send */
  21639. var extra; /* number of extra bits to send */
  21640. if (s.last_lit !== 0) {
  21641. do {
  21642. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  21643. lc = s.pending_buf[s.l_buf + lx];
  21644. lx++;
  21645. if (dist === 0) {
  21646. send_code(s, lc, ltree); /* send a literal byte */
  21647. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  21648. } else {
  21649. /* Here, lc is the match length - MIN_MATCH */
  21650. code = _length_code[lc];
  21651. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  21652. extra = extra_lbits[code];
  21653. if (extra !== 0) {
  21654. lc -= base_length[code];
  21655. send_bits(s, lc, extra); /* send the extra length bits */
  21656. }
  21657. dist--; /* dist is now the match distance - 1 */
  21658. code = d_code(dist);
  21659. //Assert (code < D_CODES, "bad d_code");
  21660. send_code(s, code, dtree); /* send the distance code */
  21661. extra = extra_dbits[code];
  21662. if (extra !== 0) {
  21663. dist -= base_dist[code];
  21664. send_bits(s, dist, extra); /* send the extra distance bits */
  21665. }
  21666. } /* literal or match pair ? */
  21667. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  21668. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  21669. // "pendingBuf overflow");
  21670. } while (lx < s.last_lit);
  21671. }
  21672. send_code(s, END_BLOCK, ltree);
  21673. }
  21674. /* ===========================================================================
  21675. * Construct one Huffman tree and assigns the code bit strings and lengths.
  21676. * Update the total bit length for the current block.
  21677. * IN assertion: the field freq is set for all tree elements.
  21678. * OUT assertions: the fields len and code are set to the optimal bit length
  21679. * and corresponding code. The length opt_len is updated; static_len is
  21680. * also updated if stree is not null. The field max_code is set.
  21681. */
  21682. function build_tree(s, desc)
  21683. // deflate_state *s;
  21684. // tree_desc *desc; /* the tree descriptor */
  21685. {
  21686. var tree = desc.dyn_tree;
  21687. var stree = desc.stat_desc.static_tree;
  21688. var has_stree = desc.stat_desc.has_stree;
  21689. var elems = desc.stat_desc.elems;
  21690. var n, m; /* iterate over heap elements */
  21691. var max_code = -1; /* largest code with non zero frequency */
  21692. var node; /* new node being created */
  21693. /* Construct the initial heap, with least frequent element in
  21694. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  21695. * heap[0] is not used.
  21696. */
  21697. s.heap_len = 0;
  21698. s.heap_max = HEAP_SIZE;
  21699. for (n = 0; n < elems; n++) {
  21700. if (tree[n * 2]/*.Freq*/ !== 0) {
  21701. s.heap[++s.heap_len] = max_code = n;
  21702. s.depth[n] = 0;
  21703. } else {
  21704. tree[n*2 + 1]/*.Len*/ = 0;
  21705. }
  21706. }
  21707. /* The pkzip format requires that at least one distance code exists,
  21708. * and that at least one bit should be sent even if there is only one
  21709. * possible code. So to avoid special checks later on we force at least
  21710. * two codes of non zero frequency.
  21711. */
  21712. while (s.heap_len < 2) {
  21713. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  21714. tree[node * 2]/*.Freq*/ = 1;
  21715. s.depth[node] = 0;
  21716. s.opt_len--;
  21717. if (has_stree) {
  21718. s.static_len -= stree[node*2 + 1]/*.Len*/;
  21719. }
  21720. /* node is 0 or 1 so it does not have extra bits */
  21721. }
  21722. desc.max_code = max_code;
  21723. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  21724. * establish sub-heaps of increasing lengths:
  21725. */
  21726. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  21727. /* Construct the Huffman tree by repeatedly combining the least two
  21728. * frequent nodes.
  21729. */
  21730. node = elems; /* next internal node of the tree */
  21731. do {
  21732. //pqremove(s, tree, n); /* n = node of least frequency */
  21733. /*** pqremove ***/
  21734. n = s.heap[1/*SMALLEST*/];
  21735. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  21736. pqdownheap(s, tree, 1/*SMALLEST*/);
  21737. /***/
  21738. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  21739. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  21740. s.heap[--s.heap_max] = m;
  21741. /* Create a new node father of n and m */
  21742. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  21743. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  21744. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  21745. /* and insert the new node in the heap */
  21746. s.heap[1/*SMALLEST*/] = node++;
  21747. pqdownheap(s, tree, 1/*SMALLEST*/);
  21748. } while (s.heap_len >= 2);
  21749. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  21750. /* At this point, the fields freq and dad are set. We can now
  21751. * generate the bit lengths.
  21752. */
  21753. gen_bitlen(s, desc);
  21754. /* The field len is now set, we can generate the bit codes */
  21755. gen_codes(tree, max_code, s.bl_count);
  21756. }
  21757. /* ===========================================================================
  21758. * Scan a literal or distance tree to determine the frequencies of the codes
  21759. * in the bit length tree.
  21760. */
  21761. function scan_tree(s, tree, max_code)
  21762. // deflate_state *s;
  21763. // ct_data *tree; /* the tree to be scanned */
  21764. // int max_code; /* and its largest code of non zero frequency */
  21765. {
  21766. var n; /* iterates over all tree elements */
  21767. var prevlen = -1; /* last emitted length */
  21768. var curlen; /* length of current code */
  21769. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  21770. var count = 0; /* repeat count of the current code */
  21771. var max_count = 7; /* max repeat count */
  21772. var min_count = 4; /* min repeat count */
  21773. if (nextlen === 0) {
  21774. max_count = 138;
  21775. min_count = 3;
  21776. }
  21777. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  21778. for (n = 0; n <= max_code; n++) {
  21779. curlen = nextlen;
  21780. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  21781. if (++count < max_count && curlen === nextlen) {
  21782. continue;
  21783. } else if (count < min_count) {
  21784. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  21785. } else if (curlen !== 0) {
  21786. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  21787. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  21788. } else if (count <= 10) {
  21789. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  21790. } else {
  21791. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  21792. }
  21793. count = 0;
  21794. prevlen = curlen;
  21795. if (nextlen === 0) {
  21796. max_count = 138;
  21797. min_count = 3;
  21798. } else if (curlen === nextlen) {
  21799. max_count = 6;
  21800. min_count = 3;
  21801. } else {
  21802. max_count = 7;
  21803. min_count = 4;
  21804. }
  21805. }
  21806. }
  21807. /* ===========================================================================
  21808. * Send a literal or distance tree in compressed form, using the codes in
  21809. * bl_tree.
  21810. */
  21811. function send_tree(s, tree, max_code)
  21812. // deflate_state *s;
  21813. // ct_data *tree; /* the tree to be scanned */
  21814. // int max_code; /* and its largest code of non zero frequency */
  21815. {
  21816. var n; /* iterates over all tree elements */
  21817. var prevlen = -1; /* last emitted length */
  21818. var curlen; /* length of current code */
  21819. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  21820. var count = 0; /* repeat count of the current code */
  21821. var max_count = 7; /* max repeat count */
  21822. var min_count = 4; /* min repeat count */
  21823. /* tree[max_code+1].Len = -1; */ /* guard already set */
  21824. if (nextlen === 0) {
  21825. max_count = 138;
  21826. min_count = 3;
  21827. }
  21828. for (n = 0; n <= max_code; n++) {
  21829. curlen = nextlen;
  21830. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  21831. if (++count < max_count && curlen === nextlen) {
  21832. continue;
  21833. } else if (count < min_count) {
  21834. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  21835. } else if (curlen !== 0) {
  21836. if (curlen !== prevlen) {
  21837. send_code(s, curlen, s.bl_tree);
  21838. count--;
  21839. }
  21840. //Assert(count >= 3 && count <= 6, " 3_6?");
  21841. send_code(s, REP_3_6, s.bl_tree);
  21842. send_bits(s, count-3, 2);
  21843. } else if (count <= 10) {
  21844. send_code(s, REPZ_3_10, s.bl_tree);
  21845. send_bits(s, count-3, 3);
  21846. } else {
  21847. send_code(s, REPZ_11_138, s.bl_tree);
  21848. send_bits(s, count-11, 7);
  21849. }
  21850. count = 0;
  21851. prevlen = curlen;
  21852. if (nextlen === 0) {
  21853. max_count = 138;
  21854. min_count = 3;
  21855. } else if (curlen === nextlen) {
  21856. max_count = 6;
  21857. min_count = 3;
  21858. } else {
  21859. max_count = 7;
  21860. min_count = 4;
  21861. }
  21862. }
  21863. }
  21864. /* ===========================================================================
  21865. * Construct the Huffman tree for the bit lengths and return the index in
  21866. * bl_order of the last bit length code to send.
  21867. */
  21868. function build_bl_tree(s) {
  21869. var max_blindex; /* index of last bit length code of non zero freq */
  21870. /* Determine the bit length frequencies for literal and distance trees */
  21871. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  21872. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  21873. /* Build the bit length tree: */
  21874. build_tree(s, s.bl_desc);
  21875. /* opt_len now includes the length of the tree representations, except
  21876. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  21877. */
  21878. /* Determine the number of bit length codes to send. The pkzip format
  21879. * requires that at least 4 bit length codes be sent. (appnote.txt says
  21880. * 3 but the actual value used is 4.)
  21881. */
  21882. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  21883. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  21884. break;
  21885. }
  21886. }
  21887. /* Update opt_len to include the bit length tree and counts */
  21888. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  21889. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  21890. // s->opt_len, s->static_len));
  21891. return max_blindex;
  21892. }
  21893. /* ===========================================================================
  21894. * Send the header for a block using dynamic Huffman trees: the counts, the
  21895. * lengths of the bit length codes, the literal tree and the distance tree.
  21896. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  21897. */
  21898. function send_all_trees(s, lcodes, dcodes, blcodes)
  21899. // deflate_state *s;
  21900. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  21901. {
  21902. var rank; /* index in bl_order */
  21903. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  21904. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  21905. // "too many codes");
  21906. //Tracev((stderr, "\nbl counts: "));
  21907. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  21908. send_bits(s, dcodes-1, 5);
  21909. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  21910. for (rank = 0; rank < blcodes; rank++) {
  21911. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  21912. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  21913. }
  21914. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  21915. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  21916. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  21917. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  21918. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  21919. }
  21920. /* ===========================================================================
  21921. * Check if the data type is TEXT or BINARY, using the following algorithm:
  21922. * - TEXT if the two conditions below are satisfied:
  21923. * a) There are no non-portable control characters belonging to the
  21924. * "black list" (0..6, 14..25, 28..31).
  21925. * b) There is at least one printable character belonging to the
  21926. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  21927. * - BINARY otherwise.
  21928. * - The following partially-portable control characters form a
  21929. * "gray list" that is ignored in this detection algorithm:
  21930. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  21931. * IN assertion: the fields Freq of dyn_ltree are set.
  21932. */
  21933. function detect_data_type(s) {
  21934. /* black_mask is the bit mask of black-listed bytes
  21935. * set bits 0..6, 14..25, and 28..31
  21936. * 0xf3ffc07f = binary 11110011111111111100000001111111
  21937. */
  21938. var black_mask = 0xf3ffc07f;
  21939. var n;
  21940. /* Check for non-textual ("black-listed") bytes. */
  21941. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  21942. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  21943. return Z_BINARY;
  21944. }
  21945. }
  21946. /* Check for textual ("white-listed") bytes. */
  21947. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  21948. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  21949. return Z_TEXT;
  21950. }
  21951. for (n = 32; n < LITERALS; n++) {
  21952. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  21953. return Z_TEXT;
  21954. }
  21955. }
  21956. /* There are no "black-listed" or "white-listed" bytes:
  21957. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  21958. */
  21959. return Z_BINARY;
  21960. }
  21961. var static_init_done = false;
  21962. /* ===========================================================================
  21963. * Initialize the tree data structures for a new zlib stream.
  21964. */
  21965. function _tr_init(s)
  21966. {
  21967. if (!static_init_done) {
  21968. tr_static_init();
  21969. static_init_done = true;
  21970. }
  21971. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  21972. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  21973. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  21974. s.bi_buf = 0;
  21975. s.bi_valid = 0;
  21976. /* Initialize the first block of the first file: */
  21977. init_block(s);
  21978. }
  21979. /* ===========================================================================
  21980. * Send a stored block
  21981. */
  21982. function _tr_stored_block(s, buf, stored_len, last)
  21983. //DeflateState *s;
  21984. //charf *buf; /* input block */
  21985. //ulg stored_len; /* length of input block */
  21986. //int last; /* one if this is the last block for a file */
  21987. {
  21988. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  21989. copy_block(s, buf, stored_len, true); /* with header */
  21990. }
  21991. /* ===========================================================================
  21992. * Send one empty static block to give enough lookahead for inflate.
  21993. * This takes 10 bits, of which 7 may remain in the bit buffer.
  21994. */
  21995. function _tr_align(s) {
  21996. send_bits(s, STATIC_TREES<<1, 3);
  21997. send_code(s, END_BLOCK, static_ltree);
  21998. bi_flush(s);
  21999. }
  22000. /* ===========================================================================
  22001. * Determine the best encoding for the current block: dynamic trees, static
  22002. * trees or store, and output the encoded block to the zip file.
  22003. */
  22004. function _tr_flush_block(s, buf, stored_len, last)
  22005. //DeflateState *s;
  22006. //charf *buf; /* input block, or NULL if too old */
  22007. //ulg stored_len; /* length of input block */
  22008. //int last; /* one if this is the last block for a file */
  22009. {
  22010. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  22011. var max_blindex = 0; /* index of last bit length code of non zero freq */
  22012. /* Build the Huffman trees unless a stored block is forced */
  22013. if (s.level > 0) {
  22014. /* Check if the file is binary or text */
  22015. if (s.strm.data_type === Z_UNKNOWN) {
  22016. s.strm.data_type = detect_data_type(s);
  22017. }
  22018. /* Construct the literal and distance trees */
  22019. build_tree(s, s.l_desc);
  22020. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  22021. // s->static_len));
  22022. build_tree(s, s.d_desc);
  22023. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  22024. // s->static_len));
  22025. /* At this point, opt_len and static_len are the total bit lengths of
  22026. * the compressed block data, excluding the tree representations.
  22027. */
  22028. /* Build the bit length tree for the above two trees, and get the index
  22029. * in bl_order of the last bit length code to send.
  22030. */
  22031. max_blindex = build_bl_tree(s);
  22032. /* Determine the best encoding. Compute the block lengths in bytes. */
  22033. opt_lenb = (s.opt_len+3+7) >>> 3;
  22034. static_lenb = (s.static_len+3+7) >>> 3;
  22035. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  22036. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  22037. // s->last_lit));
  22038. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  22039. } else {
  22040. // Assert(buf != (char*)0, "lost buf");
  22041. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  22042. }
  22043. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  22044. /* 4: two words for the lengths */
  22045. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  22046. * Otherwise we can't have processed more than WSIZE input bytes since
  22047. * the last block flush, because compression would have been
  22048. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  22049. * transform a block into a stored block.
  22050. */
  22051. _tr_stored_block(s, buf, stored_len, last);
  22052. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  22053. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  22054. compress_block(s, static_ltree, static_dtree);
  22055. } else {
  22056. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  22057. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  22058. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  22059. }
  22060. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  22061. /* The above check is made mod 2^32, for files larger than 512 MB
  22062. * and uLong implemented on 32 bits.
  22063. */
  22064. init_block(s);
  22065. if (last) {
  22066. bi_windup(s);
  22067. }
  22068. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  22069. // s->compressed_len-7*last));
  22070. }
  22071. /* ===========================================================================
  22072. * Save the match info and tally the frequency counts. Return true if
  22073. * the current block must be flushed.
  22074. */
  22075. function _tr_tally(s, dist, lc)
  22076. // deflate_state *s;
  22077. // unsigned dist; /* distance of matched string */
  22078. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  22079. {
  22080. //var out_length, in_length, dcode;
  22081. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  22082. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  22083. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  22084. s.last_lit++;
  22085. if (dist === 0) {
  22086. /* lc is the unmatched char */
  22087. s.dyn_ltree[lc*2]/*.Freq*/++;
  22088. } else {
  22089. s.matches++;
  22090. /* Here, lc is the match length - MIN_MATCH */
  22091. dist--; /* dist = match distance - 1 */
  22092. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  22093. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  22094. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  22095. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  22096. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  22097. }
  22098. // (!) This block is disabled in zlib defailts,
  22099. // don't enable it for binary compatibility
  22100. //#ifdef TRUNCATE_BLOCK
  22101. // /* Try to guess if it is profitable to stop the current block here */
  22102. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  22103. // /* Compute an upper bound for the compressed length */
  22104. // out_length = s.last_lit*8;
  22105. // in_length = s.strstart - s.block_start;
  22106. //
  22107. // for (dcode = 0; dcode < D_CODES; dcode++) {
  22108. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  22109. // }
  22110. // out_length >>>= 3;
  22111. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  22112. // // s->last_lit, in_length, out_length,
  22113. // // 100L - out_length*100L/in_length));
  22114. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  22115. // return true;
  22116. // }
  22117. // }
  22118. //#endif
  22119. return (s.last_lit === s.lit_bufsize-1);
  22120. /* We avoid equality with lit_bufsize because of wraparound at 64K
  22121. * on 16 bit machines and because stored blocks are restricted to
  22122. * 64K-1 bytes.
  22123. */
  22124. }
  22125. exports._tr_init = _tr_init;
  22126. exports._tr_stored_block = _tr_stored_block;
  22127. exports._tr_flush_block = _tr_flush_block;
  22128. exports._tr_tally = _tr_tally;
  22129. exports._tr_align = _tr_align;
  22130. },{"../utils/common":65}],77:[function(require,module,exports){
  22131. 'use strict';
  22132. function ZStream() {
  22133. /* next input byte */
  22134. this.input = null; // JS specific, because we have no pointers
  22135. this.next_in = 0;
  22136. /* number of bytes available at input */
  22137. this.avail_in = 0;
  22138. /* total number of input bytes read so far */
  22139. this.total_in = 0;
  22140. /* next output byte should be put there */
  22141. this.output = null; // JS specific, because we have no pointers
  22142. this.next_out = 0;
  22143. /* remaining free space at output */
  22144. this.avail_out = 0;
  22145. /* total number of bytes output so far */
  22146. this.total_out = 0;
  22147. /* last error message, NULL if no error */
  22148. this.msg = ''/*Z_NULL*/;
  22149. /* not visible by applications */
  22150. this.state = null;
  22151. /* best guess about the data type: binary or text */
  22152. this.data_type = 2/*Z_UNKNOWN*/;
  22153. /* adler32 value of the uncompressed data */
  22154. this.adler = 0;
  22155. }
  22156. module.exports = ZStream;
  22157. },{}],78:[function(require,module,exports){
  22158. var MediaStreamType = {
  22159. VIDEO_TYPE: "Video",
  22160. AUDIO_TYPE: "Audio"
  22161. };
  22162. module.exports = MediaStreamType;
  22163. },{}],79:[function(require,module,exports){
  22164. var RTCBrowserType = {
  22165. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  22166. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  22167. };
  22168. module.exports = RTCBrowserType;
  22169. },{}],80:[function(require,module,exports){
  22170. var RTCEvents = {
  22171. LASTN_CHANGED: "rtc.lastn_changed",
  22172. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  22173. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  22174. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  22175. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  22176. SIMULCAST_START: "rtc.simlcast_start",
  22177. SIMULCAST_STOP: "rtc.simlcast_stop"
  22178. };
  22179. module.exports = RTCEvents;
  22180. },{}],81:[function(require,module,exports){
  22181. var Resolutions = {
  22182. "1080": {
  22183. width: 1920,
  22184. height: 1080,
  22185. order: 7
  22186. },
  22187. "fullhd": {
  22188. width: 1920,
  22189. height: 1080,
  22190. order: 7
  22191. },
  22192. "720": {
  22193. width: 1280,
  22194. height: 720,
  22195. order: 6
  22196. },
  22197. "hd": {
  22198. width: 1280,
  22199. height: 720,
  22200. order: 6
  22201. },
  22202. "960": {
  22203. width: 960,
  22204. height: 720,
  22205. order: 5
  22206. },
  22207. "640": {
  22208. width: 640,
  22209. height: 480,
  22210. order: 4
  22211. },
  22212. "vga": {
  22213. width: 640,
  22214. height: 480,
  22215. order: 4
  22216. },
  22217. "360": {
  22218. width: 640,
  22219. height: 360,
  22220. order: 3
  22221. },
  22222. "320": {
  22223. width: 320,
  22224. height: 240,
  22225. order: 2
  22226. },
  22227. "180": {
  22228. width: 320,
  22229. height: 180,
  22230. order: 1
  22231. }
  22232. };
  22233. module.exports = Resolutions;
  22234. },{}],82:[function(require,module,exports){
  22235. var StreamEventTypes = {
  22236. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  22237. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  22238. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  22239. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  22240. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  22241. };
  22242. module.exports = StreamEventTypes;
  22243. },{}],83:[function(require,module,exports){
  22244. var UIEvents = {
  22245. NICKNAME_CHANGED: "UI.nickname_changed",
  22246. SELECTED_ENDPOINT: "UI.selected_endpoint",
  22247. PINNED_ENDPOINT: "UI.pinned_endpoint"
  22248. };
  22249. module.exports = UIEvents;
  22250. },{}],84:[function(require,module,exports){
  22251. var AuthenticationEvents = {
  22252. /**
  22253. * Event callback arguments:
  22254. * function(authenticationEnabled, userIdentity)
  22255. * authenticationEnabled - indicates whether authentication has been enabled
  22256. * in this session
  22257. * userIdentity - if user has been logged in then it contains user name. If
  22258. * contains 'null' or 'undefined' then user is not logged in.
  22259. */
  22260. IDENTITY_UPDATED: "authentication.identity_updated"
  22261. };
  22262. module.exports = AuthenticationEvents;
  22263. },{}],85:[function(require,module,exports){
  22264. var CQEvents = {
  22265. LOCALSTATS_UPDATED: "cq.localstats_updated",
  22266. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  22267. STOP: "cq.stop"
  22268. };
  22269. module.exports = CQEvents;
  22270. },{}],86:[function(require,module,exports){
  22271. var DesktopSharingEventTypes = {
  22272. INIT: "ds.init",
  22273. SWITCHING_DONE: "ds.switching_done",
  22274. NEW_STREAM_CREATED: "ds.new_stream_created"
  22275. };
  22276. module.exports = DesktopSharingEventTypes;
  22277. },{}],87:[function(require,module,exports){
  22278. module.exports = {
  22279. getLanguages : function () {
  22280. var languages = [];
  22281. for(var lang in this)
  22282. {
  22283. if(typeof this[lang] === "string")
  22284. languages.push(this[lang]);
  22285. }
  22286. return languages;
  22287. },
  22288. EN: "en",
  22289. BG: "bg",
  22290. DE: "de"
  22291. }
  22292. },{}],88:[function(require,module,exports){
  22293. var XMPPEvents = {
  22294. CONFERENCE_CERATED: "xmpp.conferenceCreated.jingle",
  22295. CALL_TERMINATED: "xmpp.callterminated.jingle",
  22296. CALL_INCOMING: "xmpp.callincoming.jingle",
  22297. DISPOSE_CONFERENCE: "xmpp.dispoce_confernce",
  22298. KICKED: "xmpp.kicked",
  22299. BRIDGE_DOWN: "xmpp.bridge_down",
  22300. USER_ID_CHANGED: "xmpp.user_id_changed",
  22301. CHANGED_STREAMS: "xmpp.changed_streams",
  22302. MUC_JOINED: "xmpp.muc_joined",
  22303. MUC_ENTER: "xmpp.muc_enter",
  22304. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  22305. MUC_LEFT: "xmpp.muc_left",
  22306. MUC_DESTROYED: "xmpp.muc_destroyed",
  22307. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  22308. REMOTE_STATS: "xmpp.remote_stats",
  22309. LOCALROLE_CHANGED: "xmpp.localrole_changed",
  22310. PRESENCE_STATUS: "xmpp.presence_status",
  22311. SUBJECT_CHANGED: "xmpp.subject_changed",
  22312. MESSAGE_RECEIVED: "xmpp.message_received",
  22313. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  22314. PASSWORD_REQUIRED: "xmpp.password_required",
  22315. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  22316. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  22317. ETHERPAD: "xmpp.etherpad"
  22318. };
  22319. module.exports = XMPPEvents;
  22320. },{}],89:[function(require,module,exports){
  22321. // Copyright Joyent, Inc. and other Node contributors.
  22322. //
  22323. // Permission is hereby granted, free of charge, to any person obtaining a
  22324. // copy of this software and associated documentation files (the
  22325. // "Software"), to deal in the Software without restriction, including
  22326. // without limitation the rights to use, copy, modify, merge, publish,
  22327. // distribute, sublicense, and/or sell copies of the Software, and to permit
  22328. // persons to whom the Software is furnished to do so, subject to the
  22329. // following conditions:
  22330. //
  22331. // The above copyright notice and this permission notice shall be included
  22332. // in all copies or substantial portions of the Software.
  22333. //
  22334. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  22335. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22336. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  22337. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  22338. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22339. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  22340. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22341. function EventEmitter() {
  22342. this._events = this._events || {};
  22343. this._maxListeners = this._maxListeners || undefined;
  22344. }
  22345. module.exports = EventEmitter;
  22346. // Backwards-compat with node 0.10.x
  22347. EventEmitter.EventEmitter = EventEmitter;
  22348. EventEmitter.prototype._events = undefined;
  22349. EventEmitter.prototype._maxListeners = undefined;
  22350. // By default EventEmitters will print a warning if more than 10 listeners are
  22351. // added to it. This is a useful default which helps finding memory leaks.
  22352. EventEmitter.defaultMaxListeners = 10;
  22353. // Obviously not all Emitters should be limited to 10. This function allows
  22354. // that to be increased. Set to zero for unlimited.
  22355. EventEmitter.prototype.setMaxListeners = function(n) {
  22356. if (!isNumber(n) || n < 0 || isNaN(n))
  22357. throw TypeError('n must be a positive number');
  22358. this._maxListeners = n;
  22359. return this;
  22360. };
  22361. EventEmitter.prototype.emit = function(type) {
  22362. var er, handler, len, args, i, listeners;
  22363. if (!this._events)
  22364. this._events = {};
  22365. // If there is no 'error' event listener then throw.
  22366. if (type === 'error') {
  22367. if (!this._events.error ||
  22368. (isObject(this._events.error) && !this._events.error.length)) {
  22369. er = arguments[1];
  22370. if (er instanceof Error) {
  22371. throw er; // Unhandled 'error' event
  22372. }
  22373. throw TypeError('Uncaught, unspecified "error" event.');
  22374. }
  22375. }
  22376. handler = this._events[type];
  22377. if (isUndefined(handler))
  22378. return false;
  22379. if (isFunction(handler)) {
  22380. switch (arguments.length) {
  22381. // fast cases
  22382. case 1:
  22383. handler.call(this);
  22384. break;
  22385. case 2:
  22386. handler.call(this, arguments[1]);
  22387. break;
  22388. case 3:
  22389. handler.call(this, arguments[1], arguments[2]);
  22390. break;
  22391. // slower
  22392. default:
  22393. len = arguments.length;
  22394. args = new Array(len - 1);
  22395. for (i = 1; i < len; i++)
  22396. args[i - 1] = arguments[i];
  22397. handler.apply(this, args);
  22398. }
  22399. } else if (isObject(handler)) {
  22400. len = arguments.length;
  22401. args = new Array(len - 1);
  22402. for (i = 1; i < len; i++)
  22403. args[i - 1] = arguments[i];
  22404. listeners = handler.slice();
  22405. len = listeners.length;
  22406. for (i = 0; i < len; i++)
  22407. listeners[i].apply(this, args);
  22408. }
  22409. return true;
  22410. };
  22411. EventEmitter.prototype.addListener = function(type, listener) {
  22412. var m;
  22413. if (!isFunction(listener))
  22414. throw TypeError('listener must be a function');
  22415. if (!this._events)
  22416. this._events = {};
  22417. // To avoid recursion in the case that type === "newListener"! Before
  22418. // adding it to the listeners, first emit "newListener".
  22419. if (this._events.newListener)
  22420. this.emit('newListener', type,
  22421. isFunction(listener.listener) ?
  22422. listener.listener : listener);
  22423. if (!this._events[type])
  22424. // Optimize the case of one listener. Don't need the extra array object.
  22425. this._events[type] = listener;
  22426. else if (isObject(this._events[type]))
  22427. // If we've already got an array, just append.
  22428. this._events[type].push(listener);
  22429. else
  22430. // Adding the second element, need to change to array.
  22431. this._events[type] = [this._events[type], listener];
  22432. // Check for listener leak
  22433. if (isObject(this._events[type]) && !this._events[type].warned) {
  22434. var m;
  22435. if (!isUndefined(this._maxListeners)) {
  22436. m = this._maxListeners;
  22437. } else {
  22438. m = EventEmitter.defaultMaxListeners;
  22439. }
  22440. if (m && m > 0 && this._events[type].length > m) {
  22441. this._events[type].warned = true;
  22442. console.error('(node) warning: possible EventEmitter memory ' +
  22443. 'leak detected. %d listeners added. ' +
  22444. 'Use emitter.setMaxListeners() to increase limit.',
  22445. this._events[type].length);
  22446. if (typeof console.trace === 'function') {
  22447. // not supported in IE 10
  22448. console.trace();
  22449. }
  22450. }
  22451. }
  22452. return this;
  22453. };
  22454. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  22455. EventEmitter.prototype.once = function(type, listener) {
  22456. if (!isFunction(listener))
  22457. throw TypeError('listener must be a function');
  22458. var fired = false;
  22459. function g() {
  22460. this.removeListener(type, g);
  22461. if (!fired) {
  22462. fired = true;
  22463. listener.apply(this, arguments);
  22464. }
  22465. }
  22466. g.listener = listener;
  22467. this.on(type, g);
  22468. return this;
  22469. };
  22470. // emits a 'removeListener' event iff the listener was removed
  22471. EventEmitter.prototype.removeListener = function(type, listener) {
  22472. var list, position, length, i;
  22473. if (!isFunction(listener))
  22474. throw TypeError('listener must be a function');
  22475. if (!this._events || !this._events[type])
  22476. return this;
  22477. list = this._events[type];
  22478. length = list.length;
  22479. position = -1;
  22480. if (list === listener ||
  22481. (isFunction(list.listener) && list.listener === listener)) {
  22482. delete this._events[type];
  22483. if (this._events.removeListener)
  22484. this.emit('removeListener', type, listener);
  22485. } else if (isObject(list)) {
  22486. for (i = length; i-- > 0;) {
  22487. if (list[i] === listener ||
  22488. (list[i].listener && list[i].listener === listener)) {
  22489. position = i;
  22490. break;
  22491. }
  22492. }
  22493. if (position < 0)
  22494. return this;
  22495. if (list.length === 1) {
  22496. list.length = 0;
  22497. delete this._events[type];
  22498. } else {
  22499. list.splice(position, 1);
  22500. }
  22501. if (this._events.removeListener)
  22502. this.emit('removeListener', type, listener);
  22503. }
  22504. return this;
  22505. };
  22506. EventEmitter.prototype.removeAllListeners = function(type) {
  22507. var key, listeners;
  22508. if (!this._events)
  22509. return this;
  22510. // not listening for removeListener, no need to emit
  22511. if (!this._events.removeListener) {
  22512. if (arguments.length === 0)
  22513. this._events = {};
  22514. else if (this._events[type])
  22515. delete this._events[type];
  22516. return this;
  22517. }
  22518. // emit removeListener for all listeners on all events
  22519. if (arguments.length === 0) {
  22520. for (key in this._events) {
  22521. if (key === 'removeListener') continue;
  22522. this.removeAllListeners(key);
  22523. }
  22524. this.removeAllListeners('removeListener');
  22525. this._events = {};
  22526. return this;
  22527. }
  22528. listeners = this._events[type];
  22529. if (isFunction(listeners)) {
  22530. this.removeListener(type, listeners);
  22531. } else {
  22532. // LIFO order
  22533. while (listeners.length)
  22534. this.removeListener(type, listeners[listeners.length - 1]);
  22535. }
  22536. delete this._events[type];
  22537. return this;
  22538. };
  22539. EventEmitter.prototype.listeners = function(type) {
  22540. var ret;
  22541. if (!this._events || !this._events[type])
  22542. ret = [];
  22543. else if (isFunction(this._events[type]))
  22544. ret = [this._events[type]];
  22545. else
  22546. ret = this._events[type].slice();
  22547. return ret;
  22548. };
  22549. EventEmitter.listenerCount = function(emitter, type) {
  22550. var ret;
  22551. if (!emitter._events || !emitter._events[type])
  22552. ret = 0;
  22553. else if (isFunction(emitter._events[type]))
  22554. ret = 1;
  22555. else
  22556. ret = emitter._events[type].length;
  22557. return ret;
  22558. };
  22559. function isFunction(arg) {
  22560. return typeof arg === 'function';
  22561. }
  22562. function isNumber(arg) {
  22563. return typeof arg === 'number';
  22564. }
  22565. function isObject(arg) {
  22566. return typeof arg === 'object' && arg !== null;
  22567. }
  22568. function isUndefined(arg) {
  22569. return arg === void 0;
  22570. }
  22571. },{}]},{},[1])(1)
  22572. });