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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748
  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 = 'unsupported_browser.html';
  956. return;
  957. }
  958. if (this.browser !== RTCBrowserType.RTC_BROWSER_CHROME &&
  959. config.enableFirefoxSupport !== true) {
  960. window.location.href = 'unsupported_browser.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",
  1064. "dialog.failedpermissions");
  1065. }
  1066. );
  1067. }
  1068. }
  1069. RTCUtils.prototype.handleLocalStream = function(stream)
  1070. {
  1071. if(window.webkitMediaStream)
  1072. {
  1073. var audioStream = new webkitMediaStream();
  1074. var videoStream = new webkitMediaStream();
  1075. var audioTracks = stream.getAudioTracks();
  1076. var videoTracks = stream.getVideoTracks();
  1077. for (var i = 0; i < audioTracks.length; i++) {
  1078. audioStream.addTrack(audioTracks[i]);
  1079. }
  1080. this.service.createLocalStream(audioStream, "audio");
  1081. for (i = 0; i < videoTracks.length; i++) {
  1082. videoStream.addTrack(videoTracks[i]);
  1083. }
  1084. this.service.createLocalStream(videoStream, "video");
  1085. }
  1086. else
  1087. {//firefox
  1088. this.service.createLocalStream(stream, "stream");
  1089. }
  1090. };
  1091. module.exports = RTCUtils;
  1092. },{"../../service/RTC/RTCBrowserType.js":79,"../../service/RTC/Resolutions":81}],8:[function(require,module,exports){
  1093. var UI = {};
  1094. var VideoLayout = require("./videolayout/VideoLayout.js");
  1095. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1096. var Prezi = require("./prezi/Prezi.js");
  1097. var Etherpad = require("./etherpad/Etherpad.js");
  1098. var Chat = require("./side_pannels/chat/Chat.js");
  1099. var Toolbar = require("./toolbars/Toolbar");
  1100. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1101. var BottomToolbar = require("./toolbars/BottomToolbar");
  1102. var ContactList = require("./side_pannels/contactlist/ContactList");
  1103. var Avatar = require("./avatar/Avatar");
  1104. var EventEmitter = require("events");
  1105. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1106. var Settings = require("./../settings/Settings");
  1107. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1108. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1109. UI.messageHandler = require("./util/MessageHandler");
  1110. var messageHandler = UI.messageHandler;
  1111. var Authentication = require("./authentication/Authentication");
  1112. var UIUtil = require("./util/UIUtil");
  1113. var NicknameHandler = require("./util/NicknameHandler");
  1114. var CQEvents = require("../../service/connectionquality/CQEvents");
  1115. var DesktopSharingEventTypes
  1116. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1117. var RTCEvents = require("../../service/RTC/RTCEvents");
  1118. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1119. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1120. var eventEmitter = new EventEmitter();
  1121. var roomName = null;
  1122. function setupPrezi()
  1123. {
  1124. $("#reloadPresentationLink").click(function()
  1125. {
  1126. Prezi.reloadPresentation();
  1127. });
  1128. }
  1129. function setupChat()
  1130. {
  1131. Chat.init();
  1132. $("#toggle_smileys").click(function() {
  1133. Chat.toggleSmileys();
  1134. });
  1135. }
  1136. function setupToolbars() {
  1137. Toolbar.init(UI);
  1138. Toolbar.setupButtonsFromConfig();
  1139. BottomToolbar.init();
  1140. }
  1141. function streamHandler(stream) {
  1142. switch (stream.type)
  1143. {
  1144. case "audio":
  1145. VideoLayout.changeLocalAudio(stream);
  1146. break;
  1147. case "video":
  1148. VideoLayout.changeLocalVideo(stream);
  1149. break;
  1150. case "stream":
  1151. VideoLayout.changeLocalStream(stream);
  1152. break;
  1153. }
  1154. }
  1155. function onDisposeConference(unload) {
  1156. Toolbar.showAuthenticateButton(false);
  1157. };
  1158. function onDisplayNameChanged(jid, displayName) {
  1159. ContactList.onDisplayNameChange(jid, displayName);
  1160. SettingsMenu.onDisplayNameChange(jid, displayName);
  1161. VideoLayout.onDisplayNameChanged(jid, displayName);
  1162. }
  1163. function registerListeners() {
  1164. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1165. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1166. APP.RTC.addStreamListener(function (stream) {
  1167. VideoLayout.onRemoteStreamAdded(stream);
  1168. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1169. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1170. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1171. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1172. });
  1173. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1174. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1175. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1176. endpointsEnteringLastN, stream);
  1177. });
  1178. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  1179. function (endpointSimulcastLayers) {
  1180. VideoLayout.onSimulcastLayersChanged(endpointSimulcastLayers);
  1181. });
  1182. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGING,
  1183. function (endpointSimulcastLayers) {
  1184. VideoLayout.onSimulcastLayersChanging(endpointSimulcastLayers);
  1185. });
  1186. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1187. {
  1188. var resourceJid;
  1189. if(jid === APP.statistics.LOCAL_JID)
  1190. {
  1191. resourceJid = AudioLevels.LOCAL_LEVEL;
  1192. if(APP.RTC.localAudio.isMuted())
  1193. {
  1194. audioLevel = 0;
  1195. }
  1196. }
  1197. else
  1198. {
  1199. resourceJid = Strophe.getResourceFromJid(jid);
  1200. }
  1201. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1202. UI.getLargeVideoState().userResourceJid);
  1203. });
  1204. APP.desktopsharing.addListener(function () {
  1205. ToolbarToggler.showDesktopSharingButton();
  1206. }, DesktopSharingEventTypes.INIT);
  1207. APP.desktopsharing.addListener(
  1208. Toolbar.changeDesktopSharingButtonState,
  1209. DesktopSharingEventTypes.SWITCHING_DONE);
  1210. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1211. VideoLayout.updateLocalConnectionStats);
  1212. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1213. VideoLayout.updateConnectionStats);
  1214. APP.connectionquality.addListener(CQEvents.STOP,
  1215. VideoLayout.onStatsStop);
  1216. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1217. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  1218. messageHandler.openMessageDialog(
  1219. 'dialog.serviceUnavailable',
  1220. 'dialog.gracefulShutdown'
  1221. );
  1222. });
  1223. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  1224. var title = APP.translation.generateTranslatonHTML(
  1225. "dialog.reservationError");
  1226. var message = APP.translation.generateTranslatonHTML(
  1227. "dialog.reservationErrorMsg", {code: code, msg: msg});
  1228. messageHandler.openDialog(
  1229. title,
  1230. message,
  1231. true, {},
  1232. function (event, value, message, formVals)
  1233. {
  1234. return false;
  1235. }
  1236. );
  1237. });
  1238. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1239. messageHandler.openMessageDialog("dialog.sessTerminated",
  1240. "dialog.kickMessage");
  1241. });
  1242. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1243. //FIXME: use Session Terminated from translation, but
  1244. // 'reason' text comes from XMPP packet and is not translated
  1245. var title = APP.translation.generateTranslatonHTML("dialog.sessTerminated");
  1246. messageHandler.openDialog(
  1247. title, reason, true, {},
  1248. function (event, value, message, formVals)
  1249. {
  1250. return false;
  1251. }
  1252. );
  1253. });
  1254. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1255. messageHandler.showError("dialog.error",
  1256. "dialog.bridgeUnavailable");
  1257. });
  1258. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1259. Avatar.setUserAvatar(from, id);
  1260. });
  1261. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  1262. for(stream in changedStreams)
  1263. {
  1264. // might need to update the direction if participant just went from sendrecv to recvonly
  1265. if (stream.type === 'video' || stream.type === 'screen') {
  1266. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1267. switch (stream.direction) {
  1268. case 'sendrecv':
  1269. el.show();
  1270. break;
  1271. case 'recvonly':
  1272. el.hide();
  1273. // FIXME: Check if we have to change large video
  1274. //VideoLayout.updateLargeVideo(el);
  1275. break;
  1276. }
  1277. }
  1278. }
  1279. });
  1280. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1281. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1282. APP.xmpp.addListener(XMPPEvents.LOCALROLE_CHANGED, onLocalRoleChange);
  1283. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, onMucEntered);
  1284. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1285. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1286. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1287. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1288. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1289. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordReqiured);
  1290. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1291. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1292. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, onAuthenticationRequired);
  1293. }
  1294. /**
  1295. * Mutes/unmutes the local video.
  1296. *
  1297. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1298. * @param options an object which specifies optional arguments such as the
  1299. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1300. * specifies whether the method was initiated in response to a user command (in
  1301. * contrast to an automatic decision taken by the application logic)
  1302. */
  1303. function setVideoMute(mute, options) {
  1304. APP.xmpp.setVideoMute(
  1305. mute,
  1306. function (mute) {
  1307. var video = $('#video');
  1308. var communicativeClass = "icon-camera";
  1309. var muteClass = "icon-camera icon-camera-disabled";
  1310. if (mute) {
  1311. video.removeClass(communicativeClass);
  1312. video.addClass(muteClass);
  1313. } else {
  1314. video.removeClass(muteClass);
  1315. video.addClass(communicativeClass);
  1316. }
  1317. },
  1318. options);
  1319. }
  1320. function bindEvents()
  1321. {
  1322. /**
  1323. * Resizes and repositions videos in full screen mode.
  1324. */
  1325. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1326. function () {
  1327. VideoLayout.resizeLargeVideoContainer();
  1328. VideoLayout.positionLarge();
  1329. }
  1330. );
  1331. $(window).resize(function () {
  1332. VideoLayout.resizeLargeVideoContainer();
  1333. VideoLayout.positionLarge();
  1334. });
  1335. }
  1336. UI.start = function (init) {
  1337. document.title = interfaceConfig.APP_NAME;
  1338. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1339. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1340. {
  1341. $("#videoconference_page").hide();
  1342. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1343. setupWelcomePage();
  1344. return;
  1345. }
  1346. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1347. var leftWatermarkDiv
  1348. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1349. leftWatermarkDiv.css({display: 'block'});
  1350. leftWatermarkDiv.parent().get(0).href
  1351. = interfaceConfig.JITSI_WATERMARK_LINK;
  1352. }
  1353. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1354. var rightWatermarkDiv
  1355. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1356. rightWatermarkDiv.css({display: 'block'});
  1357. rightWatermarkDiv.parent().get(0).href
  1358. = interfaceConfig.BRAND_WATERMARK_LINK;
  1359. rightWatermarkDiv.get(0).style.backgroundImage
  1360. = "url(images/rightwatermark.png)";
  1361. }
  1362. if (interfaceConfig.SHOW_POWERED_BY) {
  1363. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1364. }
  1365. $("#welcome_page").hide();
  1366. VideoLayout.resizeLargeVideoContainer();
  1367. $("#videospace").mousemove(function () {
  1368. return ToolbarToggler.showToolbar();
  1369. });
  1370. // Set the defaults for prompt dialogs.
  1371. jQuery.prompt.setDefaults({persistent: false});
  1372. VideoLayout.init(eventEmitter);
  1373. AudioLevels.init();
  1374. NicknameHandler.init(eventEmitter);
  1375. registerListeners();
  1376. bindEvents();
  1377. setupPrezi();
  1378. setupToolbars();
  1379. setupChat();
  1380. document.title = interfaceConfig.APP_NAME;
  1381. $("#downloadlog").click(function (event) {
  1382. dump(event.target);
  1383. });
  1384. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1385. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1386. {
  1387. $("#videoconference_page").hide();
  1388. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1389. setupWelcomePage();
  1390. return;
  1391. }
  1392. $("#welcome_page").hide();
  1393. document.getElementById('largeVideo').volume = 0;
  1394. if (!$('#settings').is(':visible')) {
  1395. console.log('init');
  1396. init();
  1397. } else {
  1398. loginInfo.onsubmit = function (e) {
  1399. if (e.preventDefault) e.preventDefault();
  1400. $('#settings').hide();
  1401. init();
  1402. };
  1403. }
  1404. toastr.options = {
  1405. "closeButton": true,
  1406. "debug": false,
  1407. "positionClass": "notification-bottom-right",
  1408. "onclick": null,
  1409. "showDuration": "300",
  1410. "hideDuration": "1000",
  1411. "timeOut": "2000",
  1412. "extendedTimeOut": "1000",
  1413. "showEasing": "swing",
  1414. "hideEasing": "linear",
  1415. "showMethod": "fadeIn",
  1416. "hideMethod": "fadeOut",
  1417. "reposition": function() {
  1418. if(PanelToggler.isVisible()) {
  1419. $("#toast-container").addClass("notification-bottom-right-center");
  1420. } else {
  1421. $("#toast-container").removeClass("notification-bottom-right-center");
  1422. }
  1423. },
  1424. "newestOnTop": false
  1425. };
  1426. SettingsMenu.init();
  1427. };
  1428. function chatAddError(errorMessage, originalText)
  1429. {
  1430. return Chat.chatAddError(errorMessage, originalText);
  1431. };
  1432. function chatSetSubject(text)
  1433. {
  1434. return Chat.chatSetSubject(text);
  1435. };
  1436. function updateChatConversation(from, displayName, message) {
  1437. return Chat.updateChatConversation(from, displayName, message);
  1438. };
  1439. function onMucJoined(jid, info) {
  1440. Toolbar.updateRoomUrl(window.location.href);
  1441. document.getElementById('localNick').appendChild(
  1442. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  1443. );
  1444. var settings = Settings.getSettings();
  1445. // Add myself to the contact list.
  1446. ContactList.addContact(jid, settings.email || settings.uid);
  1447. // Once we've joined the muc show the toolbar
  1448. ToolbarToggler.showToolbar();
  1449. var displayName = !config.displayJids
  1450. ? info.displayName : Strophe.getResourceFromJid(jid);
  1451. if (displayName)
  1452. onDisplayNameChanged('localVideoContainer', displayName + ' (me)');
  1453. }
  1454. function initEtherpad(name) {
  1455. Etherpad.init(name);
  1456. };
  1457. function onMucLeft(jid) {
  1458. console.log('left.muc', jid);
  1459. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1460. '>.displayname').html();
  1461. messageHandler.notify(displayName,'notify.somebody',
  1462. 'disconnected',
  1463. 'notify.disconnected');
  1464. // Need to call this with a slight delay, otherwise the element couldn't be
  1465. // found for some reason.
  1466. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1467. window.setTimeout(function () {
  1468. var container = document.getElementById(
  1469. 'participant_' + Strophe.getResourceFromJid(jid));
  1470. if (container) {
  1471. ContactList.removeContact(jid);
  1472. VideoLayout.removeConnectionIndicator(jid);
  1473. // hide here, wait for video to close before removing
  1474. $(container).hide();
  1475. VideoLayout.resizeThumbnails();
  1476. }
  1477. }, 10);
  1478. VideoLayout.participantLeft(jid);
  1479. };
  1480. function onLocalRoleChange(jid, info, pres, isModerator)
  1481. {
  1482. console.info("My role changed, new role: " + info.role);
  1483. onModeratorStatusChanged(isModerator);
  1484. VideoLayout.showModeratorIndicator();
  1485. if (isModerator) {
  1486. Authentication.closeAuthenticationWindow();
  1487. messageHandler.notify(null, "notify.me",
  1488. 'connected', "notify.moderator");
  1489. }
  1490. }
  1491. function onModeratorStatusChanged(isModerator) {
  1492. Toolbar.showSipCallButton(isModerator);
  1493. Toolbar.showRecordingButton(
  1494. isModerator); //&&
  1495. // FIXME:
  1496. // Recording visible if
  1497. // there are at least 2(+ 1 focus) participants
  1498. //Object.keys(connection.emuc.members).length >= 3);
  1499. if (isModerator && config.etherpad_base) {
  1500. Etherpad.init();
  1501. }
  1502. };
  1503. function onPasswordReqiured(callback) {
  1504. // password is required
  1505. Toolbar.lockLockButton();
  1506. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1507. message += APP.translation.translateString(
  1508. "dialog.passwordRequired");
  1509. message += '</h2>' +
  1510. '<input id="lockKey" type="text" placeholder="password" autofocus>';
  1511. messageHandler.openTwoButtonDialog(null, null, null, message,
  1512. true,
  1513. "dialog.Ok",
  1514. function (e, v, m, f) {},
  1515. function (event) {
  1516. document.getElementById('lockKey').focus();
  1517. },
  1518. function (e, v, m, f) {
  1519. if (v) {
  1520. var lockKey = document.getElementById('lockKey');
  1521. if (lockKey.value !== null) {
  1522. Toolbar.setSharedKey(lockKey.value);
  1523. callback(lockKey.value);
  1524. }
  1525. }
  1526. }
  1527. );
  1528. }
  1529. function onMucEntered(jid, id, displayName) {
  1530. messageHandler.notify(displayName,'notify.somebody',
  1531. 'connected',
  1532. 'notify.connected');
  1533. // Add Peer's container
  1534. VideoLayout.ensurePeerContainerExists(jid,id);
  1535. }
  1536. function onMucPresenceStatus( jid, info) {
  1537. VideoLayout.setPresenceStatus(
  1538. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1539. }
  1540. function onMucRoleChanged(role, displayName) {
  1541. VideoLayout.showModeratorIndicator();
  1542. if (role === 'moderator') {
  1543. var messageKey, messageOptions = {};
  1544. if (!displayName) {
  1545. messageKey = "notify.grantedToUnknown";
  1546. }
  1547. else
  1548. {
  1549. messageKey = "notify.grantedTo";
  1550. messageOptions = {to: displayName};
  1551. }
  1552. messageHandler.notify(
  1553. displayName,'notify.somebody',
  1554. 'connected', messageKey,
  1555. messageOptions);
  1556. }
  1557. }
  1558. function onAuthenticationRequired(intervalCallback) {
  1559. Authentication.openAuthenticationDialog(
  1560. roomName, intervalCallback, function () {
  1561. Toolbar.authenticateClicked();
  1562. });
  1563. };
  1564. function onLastNChanged(oldValue, newValue) {
  1565. if (config.muteLocalVideoIfNotInLastN) {
  1566. setVideoMute(!newValue, { 'byUser': false });
  1567. }
  1568. }
  1569. UI.toggleSmileys = function () {
  1570. Chat.toggleSmileys();
  1571. };
  1572. UI.getSettings = function () {
  1573. return Settings.getSettings();
  1574. };
  1575. UI.toggleFilmStrip = function () {
  1576. return BottomToolbar.toggleFilmStrip();
  1577. };
  1578. UI.toggleChat = function () {
  1579. return BottomToolbar.toggleChat();
  1580. };
  1581. UI.toggleContactList = function () {
  1582. return BottomToolbar.toggleContactList();
  1583. };
  1584. UI.inputDisplayNameHandler = function (value) {
  1585. VideoLayout.inputDisplayNameHandler(value);
  1586. };
  1587. UI.getLargeVideoState = function()
  1588. {
  1589. return VideoLayout.getLargeVideoState();
  1590. };
  1591. UI.generateRoomName = function() {
  1592. if(roomName)
  1593. return roomName;
  1594. var roomnode = null;
  1595. var path = window.location.pathname;
  1596. // determinde the room node from the url
  1597. // TODO: just the roomnode or the whole bare jid?
  1598. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1599. // custom function might be responsible for doing the pushstate
  1600. roomnode = config.getroomnode(path);
  1601. } else {
  1602. /* fall back to default strategy
  1603. * this is making assumptions about how the URL->room mapping happens.
  1604. * It currently assumes deployment at root, with a rewrite like the
  1605. * following one (for nginx):
  1606. location ~ ^/([a-zA-Z0-9]+)$ {
  1607. rewrite ^/(.*)$ / break;
  1608. }
  1609. */
  1610. if (path.length > 1) {
  1611. roomnode = path.substr(1).toLowerCase();
  1612. } else {
  1613. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1614. roomnode = word.toLowerCase();
  1615. window.history.pushState('VideoChat',
  1616. 'Room: ' + word, window.location.pathname + word);
  1617. }
  1618. }
  1619. roomName = roomnode + '@' + config.hosts.muc;
  1620. return roomName;
  1621. };
  1622. UI.connectionIndicatorShowMore = function(id)
  1623. {
  1624. return VideoLayout.connectionIndicators[id].showMore();
  1625. };
  1626. UI.getCredentials = function () {
  1627. var settings = this.getSettings();
  1628. return {
  1629. bosh: document.getElementById('boshURL').value,
  1630. password: document.getElementById('password').value,
  1631. jid: document.getElementById('jid').value,
  1632. email: settings.email,
  1633. displayName: settings.displayName,
  1634. uid: settings.uid
  1635. };
  1636. };
  1637. UI.disableConnect = function () {
  1638. document.getElementById('connect').disabled = true;
  1639. };
  1640. UI.showLoginPopup = function(callback)
  1641. {
  1642. console.log('password is required');
  1643. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1644. message += APP.translation.translateString(
  1645. "dialog.passwordRequired");
  1646. message += '</h2>' +
  1647. '<input id="passwordrequired.username" type="text" ' +
  1648. 'placeholder="user@domain.net" autofocus>' +
  1649. '<input id="passwordrequired.password" ' +
  1650. 'type="password" placeholder="user password">';
  1651. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  1652. true,
  1653. "dialog.Ok",
  1654. function (e, v, m, f) {
  1655. if (v) {
  1656. var username = document.getElementById('passwordrequired.username');
  1657. var password = document.getElementById('passwordrequired.password');
  1658. if (username.value !== null && password.value != null) {
  1659. callback(username.value, password.value);
  1660. }
  1661. }
  1662. },
  1663. function (event) {
  1664. document.getElementById('passwordrequired.username').focus();
  1665. }
  1666. );
  1667. }
  1668. UI.checkForNicknameAndJoin = function () {
  1669. Authentication.closeAuthenticationDialog();
  1670. Authentication.stopInterval();
  1671. var nick = null;
  1672. if (config.useNicks) {
  1673. nick = window.prompt('Your nickname (optional)');
  1674. }
  1675. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1676. };
  1677. function dump(elem, filename) {
  1678. elem = elem.parentNode;
  1679. elem.download = filename || 'meetlog.json';
  1680. elem.href = 'data:application/json;charset=utf-8,\n';
  1681. var data = APP.xmpp.populateData();
  1682. var metadata = {};
  1683. metadata.time = new Date();
  1684. metadata.url = window.location.href;
  1685. metadata.ua = navigator.userAgent;
  1686. var log = APP.xmpp.getLogger();
  1687. if (log) {
  1688. metadata.xmpp = log;
  1689. }
  1690. data.metadata = metadata;
  1691. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1692. return false;
  1693. }
  1694. UI.getRoomName = function () {
  1695. return roomName;
  1696. };
  1697. /**
  1698. * Mutes/unmutes the local video.
  1699. */
  1700. UI.toggleVideo = function () {
  1701. UIUtil.buttonClick("#video", "icon-camera icon-camera-disabled");
  1702. setVideoMute(!APP.RTC.localVideo.isMuted());
  1703. };
  1704. /**
  1705. * Mutes / unmutes audio for the local participant.
  1706. */
  1707. UI.toggleAudio = function() {
  1708. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  1709. };
  1710. /**
  1711. * Sets muted audio state for the local participant.
  1712. */
  1713. UI.setAudioMuted = function (mute) {
  1714. if(!APP.xmpp.setAudioMute(mute, function () {
  1715. VideoLayout.showLocalAudioIndicator(mute);
  1716. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1717. }))
  1718. {
  1719. // We still click the button.
  1720. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1721. return;
  1722. }
  1723. }
  1724. UI.addListener = function (type, listener) {
  1725. eventEmitter.on(type, listener);
  1726. }
  1727. UI.clickOnVideo = function (videoNumber) {
  1728. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  1729. if (remoteVideos.length > videoNumber) {
  1730. remoteVideos[videoNumber].click();
  1731. }
  1732. }
  1733. //Used by torture
  1734. UI.showToolbar = function () {
  1735. return ToolbarToggler.showToolbar();
  1736. }
  1737. //Used by torture
  1738. UI.dockToolbar = function (isDock) {
  1739. return ToolbarToggler.dockToolbar(isDock);
  1740. }
  1741. module.exports = UI;
  1742. },{"../../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){
  1743. var CanvasUtil = require("./CanvasUtils");
  1744. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  1745. function initActiveSpeakerAudioLevels() {
  1746. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  1747. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  1748. // Draw a circle.
  1749. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  1750. // Add a shadow around the circle
  1751. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  1752. ASDrawContext.shadowOffsetX = 0;
  1753. ASDrawContext.shadowOffsetY = 0;
  1754. }
  1755. /**
  1756. * The audio Levels plugin.
  1757. */
  1758. var AudioLevels = (function(my) {
  1759. var audioLevelCanvasCache = {};
  1760. my.LOCAL_LEVEL = 'local';
  1761. my.init = function () {
  1762. initActiveSpeakerAudioLevels();
  1763. }
  1764. /**
  1765. * Updates the audio level canvas for the given peerJid. If the canvas
  1766. * didn't exist we create it.
  1767. */
  1768. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  1769. var resourceJid = null;
  1770. var videoSpanId = null;
  1771. if (!peerJid)
  1772. videoSpanId = 'localVideoContainer';
  1773. else {
  1774. resourceJid = Strophe.getResourceFromJid(peerJid);
  1775. videoSpanId = 'participant_' + resourceJid;
  1776. }
  1777. var videoSpan = document.getElementById(videoSpanId);
  1778. if (!videoSpan) {
  1779. if (resourceJid)
  1780. console.error("No video element for jid", resourceJid);
  1781. else
  1782. console.error("No video element for local video.");
  1783. return;
  1784. }
  1785. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  1786. var videoSpaceWidth = $('#remoteVideos').width();
  1787. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  1788. var thumbnailWidth = thumbnailSize[0];
  1789. var thumbnailHeight = thumbnailSize[1];
  1790. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  1791. audioLevelCanvas = document.createElement('canvas');
  1792. audioLevelCanvas.className = "audiolevel";
  1793. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1794. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1795. resizeAudioLevelCanvas( audioLevelCanvas,
  1796. thumbnailWidth,
  1797. thumbnailHeight);
  1798. videoSpan.appendChild(audioLevelCanvas);
  1799. } else {
  1800. audioLevelCanvas = audioLevelCanvas.get(0);
  1801. resizeAudioLevelCanvas( audioLevelCanvas,
  1802. thumbnailWidth,
  1803. thumbnailHeight);
  1804. }
  1805. };
  1806. /**
  1807. * Updates the audio level UI for the given resourceJid.
  1808. *
  1809. * @param resourceJid the resource jid indicating the video element for
  1810. * which we draw the audio level
  1811. * @param audioLevel the newAudio level to render
  1812. */
  1813. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  1814. drawAudioLevelCanvas(resourceJid, audioLevel);
  1815. var videoSpanId = getVideoSpanId(resourceJid);
  1816. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  1817. if (!audioLevelCanvas)
  1818. return;
  1819. var drawContext = audioLevelCanvas.getContext('2d');
  1820. var canvasCache = audioLevelCanvasCache[resourceJid];
  1821. drawContext.clearRect (0, 0,
  1822. audioLevelCanvas.width, audioLevelCanvas.height);
  1823. drawContext.drawImage(canvasCache, 0, 0);
  1824. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  1825. if(!APP.xmpp.myJid()) {
  1826. return;
  1827. }
  1828. resourceJid = APP.xmpp.myResource();
  1829. }
  1830. if(resourceJid === largeVideoResourceJid) {
  1831. window.requestAnimationFrame(function () {
  1832. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  1833. });
  1834. }
  1835. };
  1836. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  1837. if($("#activeSpeaker").css("visibility") == "hidden")
  1838. return;
  1839. ASDrawContext.clearRect(0, 0, 300, 300);
  1840. if(audioLevel == 0)
  1841. return;
  1842. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  1843. // Fill the shape.
  1844. ASDrawContext.fill();
  1845. };
  1846. /**
  1847. * Resizes the given audio level canvas to match the given thumbnail size.
  1848. */
  1849. function resizeAudioLevelCanvas(audioLevelCanvas,
  1850. thumbnailWidth,
  1851. thumbnailHeight) {
  1852. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  1853. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  1854. }
  1855. /**
  1856. * Draws the audio level canvas into the cached canvas object.
  1857. *
  1858. * @param resourceJid the resource jid indicating the video element for
  1859. * which we draw the audio level
  1860. * @param audioLevel the newAudio level to render
  1861. */
  1862. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  1863. if (!audioLevelCanvasCache[resourceJid]) {
  1864. var videoSpanId = getVideoSpanId(resourceJid);
  1865. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  1866. /*
  1867. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  1868. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  1869. * error. Since audio levels are frequently updated, the errors have
  1870. * been observed to pile into the console, strain the CPU.
  1871. */
  1872. if (audioLevelCanvasOrig)
  1873. {
  1874. audioLevelCanvasCache[resourceJid]
  1875. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  1876. }
  1877. }
  1878. var canvas = audioLevelCanvasCache[resourceJid];
  1879. if (!canvas)
  1880. return;
  1881. var drawContext = canvas.getContext('2d');
  1882. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  1883. var shadowLevel = getShadowLevel(audioLevel);
  1884. if (shadowLevel > 0)
  1885. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  1886. CanvasUtil.drawRoundRectGlow( drawContext,
  1887. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  1888. canvas.width - interfaceConfig.CANVAS_EXTRA,
  1889. canvas.height - interfaceConfig.CANVAS_EXTRA,
  1890. interfaceConfig.CANVAS_RADIUS,
  1891. interfaceConfig.SHADOW_COLOR,
  1892. shadowLevel);
  1893. }
  1894. /**
  1895. * Returns the shadow/glow level for the given audio level.
  1896. *
  1897. * @param audioLevel the audio level from which we determine the shadow
  1898. * level
  1899. */
  1900. function getShadowLevel (audioLevel) {
  1901. var shadowLevel = 0;
  1902. if (audioLevel <= 0.3) {
  1903. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  1904. }
  1905. else if (audioLevel <= 0.6) {
  1906. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  1907. }
  1908. else {
  1909. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  1910. }
  1911. return shadowLevel;
  1912. }
  1913. /**
  1914. * Returns the video span id corresponding to the given resourceJid or local
  1915. * user.
  1916. */
  1917. function getVideoSpanId(resourceJid) {
  1918. var videoSpanId = null;
  1919. if (resourceJid === AudioLevels.LOCAL_LEVEL
  1920. || (APP.xmpp.myResource() && resourceJid
  1921. === APP.xmpp.myResource()))
  1922. videoSpanId = 'localVideoContainer';
  1923. else
  1924. videoSpanId = 'participant_' + resourceJid;
  1925. return videoSpanId;
  1926. }
  1927. /**
  1928. * Indicates that the remote video has been resized.
  1929. */
  1930. $(document).bind('remotevideo.resized', function (event, width, height) {
  1931. var resized = false;
  1932. $('#remoteVideos>span>canvas').each(function() {
  1933. var canvas = $(this).get(0);
  1934. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  1935. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  1936. resized = true;
  1937. }
  1938. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  1939. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  1940. resized = true;
  1941. }
  1942. });
  1943. if (resized)
  1944. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  1945. audioLevelCanvasCache[resourceJid].width
  1946. = width + interfaceConfig.CANVAS_EXTRA;
  1947. audioLevelCanvasCache[resourceJid].height
  1948. = height + interfaceConfig.CANVAS_EXTRA;
  1949. });
  1950. });
  1951. return my;
  1952. })(AudioLevels || {});
  1953. module.exports = AudioLevels;
  1954. },{"./CanvasUtils":10}],10:[function(require,module,exports){
  1955. /**
  1956. * Utility class for drawing canvas shapes.
  1957. */
  1958. var CanvasUtil = (function(my) {
  1959. /**
  1960. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  1961. * of the glow.
  1962. *
  1963. * @param drawContext the context of the canvas to draw to
  1964. * @param x the x coordinate of the round rectangle
  1965. * @param y the y coordinate of the round rectangle
  1966. * @param w the width of the round rectangle
  1967. * @param h the height of the round rectangle
  1968. * @param glowColor the color of the glow
  1969. * @param glowWidth the width of the glow
  1970. */
  1971. my.drawRoundRectGlow
  1972. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  1973. // Save the previous state of the context.
  1974. drawContext.save();
  1975. if (w < 2 * r) r = w / 2;
  1976. if (h < 2 * r) r = h / 2;
  1977. // Draw a round rectangle.
  1978. drawContext.beginPath();
  1979. drawContext.moveTo(x+r, y);
  1980. drawContext.arcTo(x+w, y, x+w, y+h, r);
  1981. drawContext.arcTo(x+w, y+h, x, y+h, r);
  1982. drawContext.arcTo(x, y+h, x, y, r);
  1983. drawContext.arcTo(x, y, x+w, y, r);
  1984. drawContext.closePath();
  1985. // Add a shadow around the rectangle
  1986. drawContext.shadowColor = glowColor;
  1987. drawContext.shadowBlur = glowWidth;
  1988. drawContext.shadowOffsetX = 0;
  1989. drawContext.shadowOffsetY = 0;
  1990. // Fill the shape.
  1991. drawContext.fill();
  1992. drawContext.save();
  1993. drawContext.restore();
  1994. // 1) Uncomment this line to use Composite Operation, which is doing the
  1995. // same as the clip function below and is also antialiasing the round
  1996. // border, but is said to be less fast performance wise.
  1997. // drawContext.globalCompositeOperation='destination-out';
  1998. drawContext.beginPath();
  1999. drawContext.moveTo(x+r, y);
  2000. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2001. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2002. drawContext.arcTo(x, y+h, x, y, r);
  2003. drawContext.arcTo(x, y, x+w, y, r);
  2004. drawContext.closePath();
  2005. // 2) Uncomment this line to use Composite Operation, which is doing the
  2006. // same as the clip function below and is also antialiasing the round
  2007. // border, but is said to be less fast performance wise.
  2008. // drawContext.fill();
  2009. // Comment these two lines if choosing to do the same with composite
  2010. // operation above 1 and 2.
  2011. drawContext.clip();
  2012. drawContext.clearRect(0, 0, 277, 200);
  2013. // Restore the previous context state.
  2014. drawContext.restore();
  2015. };
  2016. /**
  2017. * Clones the given canvas.
  2018. *
  2019. * @return the new cloned canvas.
  2020. */
  2021. my.cloneCanvas = function (oldCanvas) {
  2022. /*
  2023. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2024. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2025. * levels are frequently updated, the errors have been observed to pile
  2026. * into the console, strain the CPU.
  2027. */
  2028. if (!oldCanvas)
  2029. return oldCanvas;
  2030. //create a new canvas
  2031. var newCanvas = document.createElement('canvas');
  2032. var context = newCanvas.getContext('2d');
  2033. //set dimensions
  2034. newCanvas.width = oldCanvas.width;
  2035. newCanvas.height = oldCanvas.height;
  2036. //apply the old canvas to the new one
  2037. context.drawImage(oldCanvas, 0, 0);
  2038. //return the new canvas
  2039. return newCanvas;
  2040. };
  2041. return my;
  2042. })(CanvasUtil || {});
  2043. module.exports = CanvasUtil;
  2044. },{}],11:[function(require,module,exports){
  2045. /* Initial "authentication required" dialog */
  2046. var authDialog = null;
  2047. /* Loop retry ID that wits for other user to create the room */
  2048. var authRetryId = null;
  2049. var authenticationWindow = null;
  2050. var Authentication = {
  2051. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2052. // This is the loop that will wait for the room to be created by
  2053. // someone else. 'auth_required.moderator' will bring us back here.
  2054. authRetryId = window.setTimeout(intervalCallback , 5000);
  2055. // Show prompt only if it's not open
  2056. if (authDialog !== null) {
  2057. return;
  2058. }
  2059. // extract room name from 'room@muc.server.net'
  2060. var room = roomName.substr(0, roomName.indexOf('@'));
  2061. var title = APP.translation.generateTranslatonHTML("dialog.Stop");
  2062. var msg = APP.translation.generateTranslatonHTML("dialog.AuthMsg",
  2063. {room: room});
  2064. var button = APP.translation.generateTranslatonHTML(
  2065. "dialog.Authenticate");
  2066. var buttons = {};
  2067. buttons.authenticate = {title: button, value: "authNow"};
  2068. authDialog = APP.UI.messageHandler.openDialog(
  2069. title,
  2070. msg,
  2071. true,
  2072. buttons,
  2073. function (onSubmitEvent, submitValue) {
  2074. // Do not close the dialog yet
  2075. onSubmitEvent.preventDefault();
  2076. // Open login popup
  2077. if (submitValue === 'authNow') {
  2078. callback();
  2079. }
  2080. }
  2081. );
  2082. },
  2083. closeAuthenticationWindow:function () {
  2084. if (authenticationWindow) {
  2085. authenticationWindow.close();
  2086. authenticationWindow = null;
  2087. }
  2088. },
  2089. focusAuthenticationWindow: function () {
  2090. // If auth window exists just bring it to the front
  2091. if (authenticationWindow) {
  2092. authenticationWindow.focus();
  2093. return;
  2094. }
  2095. },
  2096. closeAuthenticationDialog: function () {
  2097. // Close authentication dialog if opened
  2098. if (authDialog) {
  2099. APP.UI.messageHandler.closeDialog();
  2100. authDialog = null;
  2101. }
  2102. },
  2103. createAuthenticationWindow: function (callback, url) {
  2104. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2105. url, 910, 660,
  2106. // On closed
  2107. function () {
  2108. // Close authentication dialog if opened
  2109. if (authDialog) {
  2110. messageHandler.closeDialog();
  2111. authDialog = null;
  2112. }
  2113. callback();
  2114. authenticationWindow = null;
  2115. });
  2116. return authenticationWindow;
  2117. },
  2118. stopInterval: function () {
  2119. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2120. if (authRetryId) {
  2121. window.clearTimeout(authRetryId);
  2122. authRetryId = null;
  2123. }
  2124. }
  2125. };
  2126. module.exports = Authentication;
  2127. },{}],12:[function(require,module,exports){
  2128. var Settings = require("../../settings/Settings");
  2129. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2130. var users = {};
  2131. var activeSpeakerJid;
  2132. function setVisibility(selector, show) {
  2133. if (selector && selector.length > 0) {
  2134. selector.css("visibility", show ? "visible" : "hidden");
  2135. }
  2136. }
  2137. function isUserMuted(jid) {
  2138. // XXX(gp) we may want to rename this method to something like
  2139. // isUserStreaming, for example.
  2140. if (jid && jid != APP.xmpp.myJid()) {
  2141. var resource = Strophe.getResourceFromJid(jid);
  2142. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2143. return true;
  2144. }
  2145. }
  2146. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2147. return null;
  2148. }
  2149. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2150. }
  2151. function getGravatarUrl(id, size) {
  2152. if(id === APP.xmpp.myJid() || !id) {
  2153. id = Settings.getSettings().uid;
  2154. }
  2155. return 'https://www.gravatar.com/avatar/' +
  2156. MD5.hexdigest(id.trim().toLowerCase()) +
  2157. "?d=wavatar&size=" + (size || "30");
  2158. }
  2159. var Avatar = {
  2160. /**
  2161. * Sets the user's avatar in the settings menu(if local user), contact list
  2162. * and thumbnail
  2163. * @param jid jid of the user
  2164. * @param id email or userID to be used as a hash
  2165. */
  2166. setUserAvatar: function (jid, id) {
  2167. if (id) {
  2168. if (users[jid] === id) {
  2169. return;
  2170. }
  2171. users[jid] = id;
  2172. }
  2173. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2174. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2175. var resourceJid = Strophe.getResourceFromJid(jid);
  2176. var thumbnail = $('#participant_' + resourceJid);
  2177. var avatar = $('#avatar_' + resourceJid);
  2178. // set the avatar in the settings menu if it is local user and get the
  2179. // local video container
  2180. if (jid === APP.xmpp.myJid()) {
  2181. $('#avatar').get(0).src = thumbUrl;
  2182. thumbnail = $('#localVideoContainer');
  2183. }
  2184. // set the avatar in the contact list
  2185. var contact = $('#' + resourceJid + '>img');
  2186. if (contact && contact.length > 0) {
  2187. contact.get(0).src = contactListUrl;
  2188. }
  2189. // set the avatar in the thumbnail
  2190. if (avatar && avatar.length > 0) {
  2191. avatar[0].src = thumbUrl;
  2192. } else {
  2193. if (thumbnail && thumbnail.length > 0) {
  2194. avatar = document.createElement('img');
  2195. avatar.id = 'avatar_' + resourceJid;
  2196. avatar.className = 'userAvatar';
  2197. avatar.src = thumbUrl;
  2198. thumbnail.append(avatar);
  2199. }
  2200. }
  2201. //if the user is the current active speaker - update the active speaker
  2202. // avatar
  2203. if (jid === activeSpeakerJid) {
  2204. this.updateActiveSpeakerAvatarSrc(jid);
  2205. }
  2206. },
  2207. /**
  2208. * Hides or shows the user's avatar
  2209. * @param jid jid of the user
  2210. * @param show whether we should show the avatar or not
  2211. * video because there is no dominant speaker and no focused speaker
  2212. */
  2213. showUserAvatar: function (jid, show) {
  2214. if (users[jid]) {
  2215. var resourceJid = Strophe.getResourceFromJid(jid);
  2216. var video = $('#participant_' + resourceJid + '>video');
  2217. var avatar = $('#avatar_' + resourceJid);
  2218. if (jid === APP.xmpp.myJid()) {
  2219. video = $('#localVideoWrapper>video');
  2220. }
  2221. if (show === undefined || show === null) {
  2222. show = isUserMuted(jid);
  2223. }
  2224. //if the user is the currently focused, the dominant speaker or if
  2225. //there is no focused and no dominant speaker and the large video is
  2226. //currently shown
  2227. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2228. setVisibility($("#largeVideo"), !show);
  2229. setVisibility($('#activeSpeaker'), show);
  2230. setVisibility(avatar, false);
  2231. setVisibility(video, false);
  2232. } else {
  2233. if (video && video.length > 0) {
  2234. setVisibility(video, !show);
  2235. setVisibility(avatar, show);
  2236. }
  2237. }
  2238. }
  2239. },
  2240. /**
  2241. * Updates the src of the active speaker avatar
  2242. * @param jid of the current active speaker
  2243. */
  2244. updateActiveSpeakerAvatarSrc: function (jid) {
  2245. if (!jid) {
  2246. jid = APP.xmpp.findJidFromResource(
  2247. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2248. }
  2249. var avatar = $("#activeSpeakerAvatar")[0];
  2250. var url = getGravatarUrl(users[jid],
  2251. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2252. if (jid === activeSpeakerJid && avatar.src === url) {
  2253. return;
  2254. }
  2255. activeSpeakerJid = jid;
  2256. var isMuted = isUserMuted(jid);
  2257. if (jid && isMuted !== null) {
  2258. avatar.src = url;
  2259. setVisibility($("#largeVideo"), !isMuted);
  2260. Avatar.showUserAvatar(jid, isMuted);
  2261. }
  2262. }
  2263. };
  2264. module.exports = Avatar;
  2265. },{"../../../service/RTC/MediaStreamTypes":78,"../../settings/Settings":37,"../videolayout/VideoLayout":31}],13:[function(require,module,exports){
  2266. /* global $, config,
  2267. setLargeVideoVisible, Util */
  2268. var VideoLayout = require("../videolayout/VideoLayout");
  2269. var Prezi = require("../prezi/Prezi");
  2270. var UIUtil = require("../util/UIUtil");
  2271. var etherpadName = null;
  2272. var etherpadIFrame = null;
  2273. var domain = null;
  2274. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2275. /**
  2276. * Resizes the etherpad.
  2277. */
  2278. function resize() {
  2279. if ($('#etherpad>iframe').length) {
  2280. var remoteVideos = $('#remoteVideos');
  2281. var availableHeight
  2282. = window.innerHeight - remoteVideos.outerHeight();
  2283. var availableWidth = UIUtil.getAvailableVideoWidth();
  2284. $('#etherpad>iframe').width(availableWidth);
  2285. $('#etherpad>iframe').height(availableHeight);
  2286. }
  2287. }
  2288. /**
  2289. * Shares the Etherpad name with other participants.
  2290. */
  2291. function shareEtherpad() {
  2292. APP.xmpp.addToPresence("etherpad", etherpadName);
  2293. }
  2294. /**
  2295. * Creates the Etherpad button and adds it to the toolbar.
  2296. */
  2297. function enableEtherpadButton() {
  2298. if (!$('#etherpadButton').is(":visible"))
  2299. $('#etherpadButton').css({display: 'inline-block'});
  2300. }
  2301. /**
  2302. * Creates the IFrame for the etherpad.
  2303. */
  2304. function createIFrame() {
  2305. etherpadIFrame = document.createElement('iframe');
  2306. etherpadIFrame.src = domain + etherpadName + options;
  2307. etherpadIFrame.frameBorder = 0;
  2308. etherpadIFrame.scrolling = "no";
  2309. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2310. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2311. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2312. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2313. etherpadIFrame.onload = function() {
  2314. document.domain = document.domain;
  2315. bubbleIframeMouseMove(etherpadIFrame);
  2316. setTimeout(function() {
  2317. // the iframes inside of the etherpad are
  2318. // not yet loaded when the etherpad iframe is loaded
  2319. var outer = etherpadIFrame.
  2320. contentDocument.getElementsByName("ace_outer")[0];
  2321. bubbleIframeMouseMove(outer);
  2322. var inner = outer.
  2323. contentDocument.getElementsByName("ace_inner")[0];
  2324. bubbleIframeMouseMove(inner);
  2325. }, 2000);
  2326. };
  2327. }
  2328. function bubbleIframeMouseMove(iframe){
  2329. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2330. iframe.contentWindow.onmousemove = function(e){
  2331. if(existingOnMouseMove) existingOnMouseMove(e);
  2332. var evt = document.createEvent("MouseEvents");
  2333. var boundingClientRect = iframe.getBoundingClientRect();
  2334. evt.initMouseEvent(
  2335. "mousemove",
  2336. true, // bubbles
  2337. false, // not cancelable
  2338. window,
  2339. e.detail,
  2340. e.screenX,
  2341. e.screenY,
  2342. e.clientX + boundingClientRect.left,
  2343. e.clientY + boundingClientRect.top,
  2344. e.ctrlKey,
  2345. e.altKey,
  2346. e.shiftKey,
  2347. e.metaKey,
  2348. e.button,
  2349. null // no related element
  2350. );
  2351. iframe.dispatchEvent(evt);
  2352. };
  2353. }
  2354. /**
  2355. * On video selected event.
  2356. */
  2357. $(document).bind('video.selected', function (event, isPresentation) {
  2358. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2359. Etherpad.toggleEtherpad(isPresentation);
  2360. });
  2361. var Etherpad = {
  2362. /**
  2363. * Initializes the etherpad.
  2364. */
  2365. init: function (name) {
  2366. if (config.etherpad_base && !etherpadName) {
  2367. domain = config.etherpad_base;
  2368. if (!name) {
  2369. // In case we're the focus we generate the name.
  2370. etherpadName = Math.random().toString(36).substring(7) +
  2371. '_' + (new Date().getTime()).toString();
  2372. shareEtherpad();
  2373. }
  2374. else
  2375. etherpadName = name;
  2376. enableEtherpadButton();
  2377. /**
  2378. * Resizes the etherpad, when the window is resized.
  2379. */
  2380. $(window).resize(function () {
  2381. resize();
  2382. });
  2383. }
  2384. },
  2385. /**
  2386. * Opens/hides the Etherpad.
  2387. */
  2388. toggleEtherpad: function (isPresentation) {
  2389. if (!etherpadIFrame)
  2390. createIFrame();
  2391. var largeVideo = null;
  2392. if (Prezi.isPresentationVisible())
  2393. largeVideo = $('#presentation>iframe');
  2394. else
  2395. largeVideo = $('#largeVideo');
  2396. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2397. $('#activeSpeaker').css('visibility', 'hidden');
  2398. largeVideo.fadeOut(300, function () {
  2399. if (Prezi.isPresentationVisible()) {
  2400. largeVideo.css({opacity: '0'});
  2401. } else {
  2402. VideoLayout.setLargeVideoVisible(false);
  2403. }
  2404. });
  2405. $('#etherpad>iframe').fadeIn(300, function () {
  2406. document.body.style.background = '#eeeeee';
  2407. $('#etherpad>iframe').css({visibility: 'visible'});
  2408. $('#etherpad').css({zIndex: 2});
  2409. });
  2410. }
  2411. else if ($('#etherpad>iframe')) {
  2412. $('#etherpad>iframe').fadeOut(300, function () {
  2413. $('#etherpad>iframe').css({visibility: 'hidden'});
  2414. $('#etherpad').css({zIndex: 0});
  2415. document.body.style.background = 'black';
  2416. });
  2417. if (!isPresentation) {
  2418. $('#largeVideo').fadeIn(300, function () {
  2419. VideoLayout.setLargeVideoVisible(true);
  2420. });
  2421. }
  2422. }
  2423. resize();
  2424. },
  2425. isVisible: function() {
  2426. var etherpadIframe = $('#etherpad>iframe');
  2427. return etherpadIframe && etherpadIframe.is(':visible');
  2428. }
  2429. };
  2430. module.exports = Etherpad;
  2431. },{"../prezi/Prezi":14,"../util/UIUtil":29,"../videolayout/VideoLayout":31}],14:[function(require,module,exports){
  2432. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2433. var UIUtil = require("../util/UIUtil");
  2434. var VideoLayout = require("../videolayout/VideoLayout");
  2435. var messageHandler = require("../util/MessageHandler");
  2436. var PreziPlayer = require("./PreziPlayer");
  2437. var preziPlayer = null;
  2438. var Prezi = {
  2439. /**
  2440. * Reloads the current presentation.
  2441. */
  2442. reloadPresentation: function() {
  2443. var iframe = document.getElementById(preziPlayer.options.preziId);
  2444. iframe.src = iframe.src;
  2445. },
  2446. /**
  2447. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2448. * otherwise.
  2449. */
  2450. isPresentationVisible: function () {
  2451. return ($('#presentation>iframe') != null
  2452. && $('#presentation>iframe').css('opacity') == 1);
  2453. },
  2454. /**
  2455. * Opens the Prezi dialog, from which the user could choose a presentation
  2456. * to load.
  2457. */
  2458. openPreziDialog: function() {
  2459. var myprezi = APP.xmpp.getPrezi();
  2460. if (myprezi) {
  2461. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  2462. null,
  2463. "dialog.removePreziMsg",
  2464. null,
  2465. false,
  2466. "dialog.Remove",
  2467. function(e,v,m,f) {
  2468. if(v) {
  2469. APP.xmpp.removePreziFromPresence();
  2470. }
  2471. }
  2472. );
  2473. }
  2474. else if (preziPlayer != null) {
  2475. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  2476. null, "dialog.sharePreziMsg",
  2477. null,
  2478. false,
  2479. "dialog.Ok",
  2480. function(e,v,m,f) {
  2481. $.prompt.close();
  2482. }
  2483. );
  2484. }
  2485. else {
  2486. var html = APP.translation.generateTranslatonHTML(
  2487. "dialog.sharePreziTitle");
  2488. var cancelButton = APP.translation.generateTranslatonHTML(
  2489. "dialog.Cancel");
  2490. var shareButton = APP.translation.generateTranslatonHTML(
  2491. "dialog.Share");
  2492. var backButton = APP.translation.generateTranslatonHTML(
  2493. "dialog.Back");
  2494. var buttons = {};
  2495. var buttons1 = {};
  2496. buttons1.button1 = buttons.button1 = {title: cancelButton, value: false};
  2497. buttons.button2 = {title: shareButton, value: true};
  2498. buttons1.button2 = {title: backButton, value: true};
  2499. var linkError = APP.translation.generateTranslatonHTML(
  2500. "dialog.preziLinkError");
  2501. var openPreziState = {
  2502. state0: {
  2503. html: '<h2>' + html + '</h2>' +
  2504. '<input id="preziUrl" type="text" ' +
  2505. 'placeholder="e.g. ' +
  2506. 'http://prezi.com/wz7vhjycl7e6/my-prezi" autofocus>',
  2507. persistent: false,
  2508. buttons: buttons,
  2509. defaultButton: 1,
  2510. submit: function(e,v,m,f){
  2511. e.preventDefault();
  2512. if(v)
  2513. {
  2514. var preziUrl = document.getElementById('preziUrl');
  2515. if (preziUrl.value)
  2516. {
  2517. var urlValue
  2518. = encodeURI(UIUtil.escapeHtml(preziUrl.value));
  2519. if (urlValue.indexOf('http://prezi.com/') != 0
  2520. && urlValue.indexOf('https://prezi.com/') != 0)
  2521. {
  2522. $.prompt.goToState('state1');
  2523. return false;
  2524. }
  2525. else {
  2526. var presIdTmp = urlValue.substring(
  2527. urlValue.indexOf("prezi.com/") + 10);
  2528. if (!isAlphanumeric(presIdTmp)
  2529. || presIdTmp.indexOf('/') < 2) {
  2530. $.prompt.goToState('state1');
  2531. return false;
  2532. }
  2533. else {
  2534. APP.xmpp.addToPresence("prezi", urlValue);
  2535. $.prompt.close();
  2536. }
  2537. }
  2538. }
  2539. }
  2540. else
  2541. $.prompt.close();
  2542. }
  2543. },
  2544. state1: {
  2545. html: '<h2>' + html + '</h2>' +
  2546. linkError,
  2547. persistent: false,
  2548. buttons: buttons1,
  2549. defaultButton: 1,
  2550. submit:function(e,v,m,f) {
  2551. e.preventDefault();
  2552. if(v==0)
  2553. $.prompt.close();
  2554. else
  2555. $.prompt.goToState('state0');
  2556. }
  2557. }
  2558. };
  2559. var focusPreziUrl = function(e) {
  2560. document.getElementById('preziUrl').focus();
  2561. };
  2562. messageHandler.openDialogWithStates(openPreziState, focusPreziUrl, focusPreziUrl);
  2563. }
  2564. }
  2565. };
  2566. /**
  2567. * A new presentation has been added.
  2568. *
  2569. * @param event the event indicating the add of a presentation
  2570. * @param jid the jid from which the presentation was added
  2571. * @param presUrl url of the presentation
  2572. * @param currentSlide the current slide to which we should move
  2573. */
  2574. function presentationAdded(event, jid, presUrl, currentSlide) {
  2575. console.log("presentation added", presUrl);
  2576. var presId = getPresentationId(presUrl);
  2577. var elementId = 'participant_'
  2578. + Strophe.getResourceFromJid(jid)
  2579. + '_' + presId;
  2580. // We explicitly don't specify the peer jid here, because we don't want
  2581. // this video to be dealt with as a peer related one (for example we
  2582. // don't want to show a mute/kick menu for this one, etc.).
  2583. VideoLayout.addRemoteVideoContainer(null, elementId);
  2584. VideoLayout.resizeThumbnails();
  2585. var controlsEnabled = false;
  2586. if (jid === APP.xmpp.myJid())
  2587. controlsEnabled = true;
  2588. setPresentationVisible(true);
  2589. $('#largeVideoContainer').hover(
  2590. function (event) {
  2591. if (Prezi.isPresentationVisible()) {
  2592. var reloadButtonRight = window.innerWidth
  2593. - $('#presentation>iframe').offset().left
  2594. - $('#presentation>iframe').width();
  2595. $('#reloadPresentation').css({ right: reloadButtonRight,
  2596. display:'inline-block'});
  2597. }
  2598. },
  2599. function (event) {
  2600. if (!Prezi.isPresentationVisible())
  2601. $('#reloadPresentation').css({display:'none'});
  2602. else {
  2603. var e = event.toElement || event.relatedTarget;
  2604. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  2605. $('#reloadPresentation').css({display:'none'});
  2606. }
  2607. });
  2608. preziPlayer = new PreziPlayer(
  2609. 'presentation',
  2610. {preziId: presId,
  2611. width: getPresentationWidth(),
  2612. height: getPresentationHeihgt(),
  2613. controls: controlsEnabled,
  2614. debug: true
  2615. });
  2616. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  2617. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  2618. console.log("prezi status", event.value);
  2619. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  2620. if (jid != APP.xmpp.myJid())
  2621. preziPlayer.flyToStep(currentSlide);
  2622. }
  2623. });
  2624. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  2625. console.log("event value", event.value);
  2626. APP.xmpp.addToPresence("preziSlide", event.value);
  2627. });
  2628. $("#" + elementId).css( 'background-image',
  2629. 'url(../images/avatarprezi.png)');
  2630. $("#" + elementId).click(
  2631. function () {
  2632. setPresentationVisible(true);
  2633. }
  2634. );
  2635. };
  2636. /**
  2637. * A presentation has been removed.
  2638. *
  2639. * @param event the event indicating the remove of a presentation
  2640. * @param jid the jid for which the presentation was removed
  2641. * @param the url of the presentation
  2642. */
  2643. function presentationRemoved(event, jid, presUrl) {
  2644. console.log('presentation removed', presUrl);
  2645. var presId = getPresentationId(presUrl);
  2646. setPresentationVisible(false);
  2647. $('#participant_'
  2648. + Strophe.getResourceFromJid(jid)
  2649. + '_' + presId).remove();
  2650. $('#presentation>iframe').remove();
  2651. if (preziPlayer != null) {
  2652. preziPlayer.destroy();
  2653. preziPlayer = null;
  2654. }
  2655. };
  2656. /**
  2657. * Indicates if the given string is an alphanumeric string.
  2658. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  2659. * purpose of checking URIs.
  2660. */
  2661. function isAlphanumeric(unsafeText) {
  2662. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  2663. return regex.test(unsafeText);
  2664. }
  2665. /**
  2666. * Returns the presentation id from the given url.
  2667. */
  2668. function getPresentationId (presUrl) {
  2669. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  2670. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  2671. }
  2672. /**
  2673. * Returns the presentation width.
  2674. */
  2675. function getPresentationWidth() {
  2676. var availableWidth = UIUtil.getAvailableVideoWidth();
  2677. var availableHeight = getPresentationHeihgt();
  2678. var aspectRatio = 16.0 / 9.0;
  2679. if (availableHeight < availableWidth / aspectRatio) {
  2680. availableWidth = Math.floor(availableHeight * aspectRatio);
  2681. }
  2682. return availableWidth;
  2683. }
  2684. /**
  2685. * Returns the presentation height.
  2686. */
  2687. function getPresentationHeihgt() {
  2688. var remoteVideos = $('#remoteVideos');
  2689. return window.innerHeight - remoteVideos.outerHeight();
  2690. }
  2691. /**
  2692. * Resizes the presentation iframe.
  2693. */
  2694. function resize() {
  2695. if ($('#presentation>iframe')) {
  2696. $('#presentation>iframe').width(getPresentationWidth());
  2697. $('#presentation>iframe').height(getPresentationHeihgt());
  2698. }
  2699. }
  2700. /**
  2701. * Shows/hides a presentation.
  2702. */
  2703. function setPresentationVisible(visible) {
  2704. var prezi = $('#presentation>iframe');
  2705. if (visible) {
  2706. // Trigger the video.selected event to indicate a change in the
  2707. // large video.
  2708. $(document).trigger("video.selected", [true]);
  2709. $('#largeVideo').fadeOut(300);
  2710. prezi.fadeIn(300, function() {
  2711. prezi.css({opacity:'1'});
  2712. ToolbarToggler.dockToolbar(true);
  2713. VideoLayout.setLargeVideoVisible(false);
  2714. });
  2715. $('#activeSpeaker').css('visibility', 'hidden');
  2716. }
  2717. else {
  2718. if (prezi.css('opacity') == '1') {
  2719. prezi.fadeOut(300, function () {
  2720. prezi.css({opacity:'0'});
  2721. $('#reloadPresentation').css({display:'none'});
  2722. $('#largeVideo').fadeIn(300, function() {
  2723. VideoLayout.setLargeVideoVisible(true);
  2724. ToolbarToggler.dockToolbar(false);
  2725. });
  2726. });
  2727. }
  2728. }
  2729. }
  2730. /**
  2731. * Presentation has been removed.
  2732. */
  2733. $(document).bind('presentationremoved.muc', presentationRemoved);
  2734. /**
  2735. * Presentation has been added.
  2736. */
  2737. $(document).bind('presentationadded.muc', presentationAdded);
  2738. /*
  2739. * Indicates presentation slide change.
  2740. */
  2741. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  2742. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  2743. preziPlayer.flyToStep(current);
  2744. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  2745. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  2746. preziPlayer.flyToStep(current, i);
  2747. }
  2748. }
  2749. });
  2750. /**
  2751. * On video selected event.
  2752. */
  2753. $(document).bind('video.selected', function (event, isPresentation) {
  2754. if (!isPresentation && $('#presentation>iframe')) {
  2755. setPresentationVisible(false);
  2756. }
  2757. });
  2758. $(window).resize(function () {
  2759. resize();
  2760. });
  2761. module.exports = Prezi;
  2762. },{"../toolbars/ToolbarToggler":25,"../util/MessageHandler":27,"../util/UIUtil":29,"../videolayout/VideoLayout":31,"./PreziPlayer":15}],15:[function(require,module,exports){
  2763. (function() {
  2764. "use strict";
  2765. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  2766. window.PreziPlayer = (function() {
  2767. PreziPlayer.API_VERSION = 1;
  2768. PreziPlayer.CURRENT_STEP = 'currentStep';
  2769. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  2770. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  2771. PreziPlayer.STATUS_LOADING = 'loading';
  2772. PreziPlayer.STATUS_READY = 'ready';
  2773. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  2774. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  2775. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  2776. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  2777. PreziPlayer.EVENT_STATUS = "statusChange";
  2778. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  2779. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  2780. PreziPlayer.domain = "https://prezi.com";
  2781. PreziPlayer.path = "/player/";
  2782. PreziPlayer.players = {};
  2783. PreziPlayer.binded_methods = ['changesHandler'];
  2784. PreziPlayer.createMultiplePlayers = function(optionArray){
  2785. for(var i=0; i<optionArray.length; i++) {
  2786. var optionSet = optionArray[i];
  2787. new PreziPlayer(optionSet.id, optionSet);
  2788. };
  2789. };
  2790. PreziPlayer.messageReceived = function(event){
  2791. var message, item, player;
  2792. try {
  2793. message = JSON.parse(event.data);
  2794. if (message.id && (player = PreziPlayer.players[message.id])) {
  2795. if (player.options.debug === true) {
  2796. if (console && console.log)
  2797. console.log('received', message);
  2798. }
  2799. if (message.type === "changes") {
  2800. player.changesHandler(message);
  2801. }
  2802. for (var i = 0; i < player.callbacks.length; i++) {
  2803. item = player.callbacks[i];
  2804. if (item && message.type === item.event) {
  2805. item.callback(message);
  2806. }
  2807. }
  2808. }
  2809. } catch (e) { }
  2810. };
  2811. function PreziPlayer(id, options) {
  2812. var params, paramString = "", _this = this;
  2813. if (PreziPlayer.players[id]){
  2814. PreziPlayer.players[id].destroy();
  2815. }
  2816. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  2817. var method_name = PreziPlayer.binded_methods[i];
  2818. _this[method_name] = __bind(_this[method_name], _this);
  2819. };
  2820. options = options || {};
  2821. this.options = options;
  2822. this.values = {'status': PreziPlayer.STATUS_LOADING};
  2823. this.values[PreziPlayer.CURRENT_STEP] = 0;
  2824. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  2825. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  2826. this.callbacks = [];
  2827. this.id = id;
  2828. this.embedTo = document.getElementById(id);
  2829. if (!this.embedTo) {
  2830. throw "The element id is not available.";
  2831. }
  2832. this.iframe = document.createElement('iframe');
  2833. params = [
  2834. { name: 'oid', value: options.preziId },
  2835. { name: 'explorable', value: options.explorable ? 1 : 0 },
  2836. { name: 'controls', value: options.controls ? 1 : 0 }
  2837. ];
  2838. for(var i=0; i<params.length; i++) {
  2839. var param = params[i];
  2840. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  2841. };
  2842. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  2843. this.iframe.frameBorder = 0;
  2844. this.iframe.scrolling = "no";
  2845. this.iframe.width = options.width || 640;
  2846. this.iframe.height = options.height || 480;
  2847. this.embedTo.innerHTML = '';
  2848. // JITSI: IN CASE SOMETHING GOES WRONG.
  2849. try {
  2850. this.embedTo.appendChild(this.iframe);
  2851. }
  2852. catch (err) {
  2853. console.log("CATCH ERROR");
  2854. }
  2855. // JITSI: Increase interval from 200 to 500, which fixes prezi
  2856. // crashes for us.
  2857. this.initPollInterval = setInterval(function(){
  2858. _this.sendMessage({'action': 'init'});
  2859. }, 500);
  2860. PreziPlayer.players[id] = this;
  2861. }
  2862. PreziPlayer.prototype.changesHandler = function(message) {
  2863. var key, value, j, item;
  2864. if (this.initPollInterval) {
  2865. clearInterval(this.initPollInterval);
  2866. this.initPollInterval = false;
  2867. }
  2868. for (key in message.data) {
  2869. if (message.data.hasOwnProperty(key)){
  2870. value = message.data[key];
  2871. this.values[key] = value;
  2872. for (j=0; j<this.callbacks.length; j++) {
  2873. item = this.callbacks[j];
  2874. if (item && item.event === key + "Change"){
  2875. item.callback({type: item.event, value: value});
  2876. }
  2877. }
  2878. }
  2879. }
  2880. };
  2881. PreziPlayer.prototype.destroy = function() {
  2882. if (this.initPollInterval) {
  2883. clearInterval(this.initPollInterval);
  2884. this.initPollInterval = false;
  2885. }
  2886. this.embedTo.innerHTML = '';
  2887. };
  2888. PreziPlayer.prototype.sendMessage = function(message) {
  2889. if (this.options.debug === true) {
  2890. if (console && console.log) console.log('sent', message);
  2891. }
  2892. message.version = PreziPlayer.API_VERSION;
  2893. message.id = this.id;
  2894. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  2895. };
  2896. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  2897. PreziPlayer.prototype.flyToNextStep = function() {
  2898. return this.sendMessage({
  2899. 'action': 'present',
  2900. 'data': ['moveToNextStep']
  2901. });
  2902. };
  2903. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  2904. PreziPlayer.prototype.flyToPreviousStep = function() {
  2905. return this.sendMessage({
  2906. 'action': 'present',
  2907. 'data': ['moveToPrevStep']
  2908. });
  2909. };
  2910. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  2911. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  2912. var obj = this;
  2913. // check animation_step
  2914. if (animation_step > 0 &&
  2915. obj.values.animationCountOnSteps &&
  2916. obj.values.animationCountOnSteps[step] <= animation_step) {
  2917. animation_step = obj.values.animationCountOnSteps[step];
  2918. }
  2919. // jump to animation steps by calling flyToNextStep()
  2920. function doAnimationSteps() {
  2921. if (obj.values.isMoving == true) {
  2922. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  2923. return;
  2924. }
  2925. while (animation_step-- > 0) {
  2926. obj.flyToNextStep(); // do the animation steps
  2927. }
  2928. }
  2929. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  2930. // jump to the step
  2931. return this.sendMessage({
  2932. 'action': 'present',
  2933. 'data': ['moveToStep', step]
  2934. });
  2935. };
  2936. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  2937. PreziPlayer.prototype.flyToObject = function(objectId) {
  2938. return this.sendMessage({
  2939. 'action': 'present',
  2940. 'data': ['moveToObject', objectId]
  2941. });
  2942. };
  2943. PreziPlayer.prototype.play = function(defaultDelay) {
  2944. return this.sendMessage({
  2945. 'action': 'present',
  2946. 'data': ['startAutoPlay', defaultDelay]
  2947. });
  2948. };
  2949. PreziPlayer.prototype.stop = function() {
  2950. return this.sendMessage({
  2951. 'action': 'present',
  2952. 'data': ['stopAutoPlay']
  2953. });
  2954. };
  2955. PreziPlayer.prototype.pause = function(defaultDelay) {
  2956. return this.sendMessage({
  2957. 'action': 'present',
  2958. 'data': ['pauseAutoPlay', defaultDelay]
  2959. });
  2960. };
  2961. PreziPlayer.prototype.getCurrentStep = function() {
  2962. return this.values.currentStep;
  2963. };
  2964. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  2965. return this.values.currentAnimationStep;
  2966. };
  2967. PreziPlayer.prototype.getCurrentObject = function() {
  2968. return this.values.currentObject;
  2969. };
  2970. PreziPlayer.prototype.getStatus = function() {
  2971. return this.values.status;
  2972. };
  2973. PreziPlayer.prototype.isPlaying = function() {
  2974. return this.values.isAutoPlaying;
  2975. };
  2976. PreziPlayer.prototype.getStepCount = function() {
  2977. return this.values.stepCount;
  2978. };
  2979. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  2980. return this.values.animationCountOnSteps;
  2981. };
  2982. PreziPlayer.prototype.getTitle = function() {
  2983. return this.values.title;
  2984. };
  2985. PreziPlayer.prototype.setDimensions = function(dims) {
  2986. for (var parameter in dims) {
  2987. this.iframe[parameter] = dims[parameter];
  2988. }
  2989. }
  2990. PreziPlayer.prototype.getDimensions = function() {
  2991. return {
  2992. width: parseInt(this.iframe.width, 10),
  2993. height: parseInt(this.iframe.height, 10)
  2994. }
  2995. }
  2996. PreziPlayer.prototype.on = function(event, callback) {
  2997. this.callbacks.push({
  2998. event: event,
  2999. callback: callback
  3000. });
  3001. };
  3002. PreziPlayer.prototype.off = function(event, callback) {
  3003. var j, item;
  3004. if (event === undefined) {
  3005. this.callbacks = [];
  3006. }
  3007. j = this.callbacks.length;
  3008. while (j--) {
  3009. item = this.callbacks[j];
  3010. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3011. this.callbacks.splice(j, 1);
  3012. }
  3013. }
  3014. };
  3015. if (window.addEventListener) {
  3016. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3017. } else {
  3018. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3019. }
  3020. return PreziPlayer;
  3021. })();
  3022. })();
  3023. module.exports = PreziPlayer;
  3024. },{}],16:[function(require,module,exports){
  3025. var Chat = require("./chat/Chat");
  3026. var ContactList = require("./contactlist/ContactList");
  3027. var Settings = require("./../../settings/Settings");
  3028. var SettingsMenu = require("./settings/SettingsMenu");
  3029. var VideoLayout = require("../videolayout/VideoLayout");
  3030. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3031. var UIUtil = require("../util/UIUtil");
  3032. /**
  3033. * Toggler for the chat, contact list, settings menu, etc..
  3034. */
  3035. var PanelToggler = (function(my) {
  3036. var currentlyOpen = null;
  3037. var buttons = {
  3038. '#chatspace': '#chatBottomButton',
  3039. '#contactlist': '#contactListButton',
  3040. '#settingsmenu': '#settingsButton'
  3041. };
  3042. /**
  3043. * Resizes the video area
  3044. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3045. * @param completeFunction a function to be called when the video space is resized
  3046. */
  3047. var resizeVideoArea = function(isClosing, completeFunction) {
  3048. var videospace = $('#videospace');
  3049. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3050. var videospaceWidth = window.innerWidth - panelSize[0];
  3051. var videospaceHeight = window.innerHeight;
  3052. var videoSize
  3053. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3054. var videoWidth = videoSize[0];
  3055. var videoHeight = videoSize[1];
  3056. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3057. videoHeight,
  3058. videospaceWidth,
  3059. videospaceHeight);
  3060. var horizontalIndent = videoPosition[0];
  3061. var verticalIndent = videoPosition[1];
  3062. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3063. var thumbnailsWidth = thumbnailSize[0];
  3064. var thumbnailsHeight = thumbnailSize[1];
  3065. //for chat
  3066. videospace.animate({
  3067. right: panelSize[0],
  3068. width: videospaceWidth,
  3069. height: videospaceHeight
  3070. },
  3071. {
  3072. queue: false,
  3073. duration: 500,
  3074. complete: completeFunction
  3075. });
  3076. $('#remoteVideos').animate({
  3077. height: thumbnailsHeight
  3078. },
  3079. {
  3080. queue: false,
  3081. duration: 500
  3082. });
  3083. $('#remoteVideos>span').animate({
  3084. height: thumbnailsHeight,
  3085. width: thumbnailsWidth
  3086. },
  3087. {
  3088. queue: false,
  3089. duration: 500,
  3090. complete: function () {
  3091. $(document).trigger(
  3092. "remotevideo.resized",
  3093. [thumbnailsWidth,
  3094. thumbnailsHeight]);
  3095. }
  3096. });
  3097. $('#largeVideoContainer').animate({
  3098. width: videospaceWidth,
  3099. height: videospaceHeight
  3100. },
  3101. {
  3102. queue: false,
  3103. duration: 500
  3104. });
  3105. $('#largeVideo').animate({
  3106. width: videoWidth,
  3107. height: videoHeight,
  3108. top: verticalIndent,
  3109. bottom: verticalIndent,
  3110. left: horizontalIndent,
  3111. right: horizontalIndent
  3112. },
  3113. {
  3114. queue: false,
  3115. duration: 500
  3116. });
  3117. };
  3118. /**
  3119. * Toggles the windows in the side panel
  3120. * @param object the window that should be shown
  3121. * @param selector the selector for the element containing the panel
  3122. * @param onOpenComplete function to be called when the panel is opened
  3123. * @param onOpen function to be called if the window is going to be opened
  3124. * @param onClose function to be called if the window is going to be closed
  3125. */
  3126. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3127. UIUtil.buttonClick(buttons[selector], "active");
  3128. if (object.isVisible()) {
  3129. $("#toast-container").animate({
  3130. right: '5px'
  3131. },
  3132. {
  3133. queue: false,
  3134. duration: 500
  3135. });
  3136. $(selector).hide("slide", {
  3137. direction: "right",
  3138. queue: false,
  3139. duration: 500
  3140. });
  3141. if(typeof onClose === "function") {
  3142. onClose();
  3143. }
  3144. currentlyOpen = null;
  3145. }
  3146. else {
  3147. // Undock the toolbar when the chat is shown and if we're in a
  3148. // video mode.
  3149. if (VideoLayout.isLargeVideoVisible()) {
  3150. ToolbarToggler.dockToolbar(false);
  3151. }
  3152. if(currentlyOpen) {
  3153. var current = $(currentlyOpen);
  3154. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3155. current.css('z-index', 4);
  3156. setTimeout(function () {
  3157. current.css('display', 'none');
  3158. current.css('z-index', 5);
  3159. }, 500);
  3160. }
  3161. $("#toast-container").animate({
  3162. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3163. },
  3164. {
  3165. queue: false,
  3166. duration: 500
  3167. });
  3168. $(selector).show("slide", {
  3169. direction: "right",
  3170. queue: false,
  3171. duration: 500,
  3172. complete: onOpenComplete
  3173. });
  3174. if(typeof onOpen === "function") {
  3175. onOpen();
  3176. }
  3177. currentlyOpen = selector;
  3178. }
  3179. };
  3180. /**
  3181. * Opens / closes the chat area.
  3182. */
  3183. my.toggleChat = function() {
  3184. var chatCompleteFunction = Chat.isVisible() ?
  3185. function() {} : function () {
  3186. Chat.scrollChatToBottom();
  3187. $('#chatspace').trigger('shown');
  3188. };
  3189. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3190. toggle(Chat,
  3191. '#chatspace',
  3192. function () {
  3193. // Request the focus in the nickname field or the chat input field.
  3194. if ($('#nickname').css('visibility') === 'visible') {
  3195. $('#nickinput').focus();
  3196. } else {
  3197. $('#usermsg').focus();
  3198. }
  3199. },
  3200. null,
  3201. Chat.resizeChat,
  3202. null);
  3203. };
  3204. /**
  3205. * Opens / closes the contact list area.
  3206. */
  3207. my.toggleContactList = function () {
  3208. var completeFunction = ContactList.isVisible() ?
  3209. function() {} : function () { $('#contactlist').trigger('shown');};
  3210. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3211. toggle(ContactList,
  3212. '#contactlist',
  3213. null,
  3214. function() {
  3215. ContactList.setVisualNotification(false);
  3216. },
  3217. null);
  3218. };
  3219. /**
  3220. * Opens / closes the settings menu
  3221. */
  3222. my.toggleSettingsMenu = function() {
  3223. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3224. toggle(SettingsMenu,
  3225. '#settingsmenu',
  3226. null,
  3227. function() {
  3228. var settings = Settings.getSettings();
  3229. $('#setDisplayName').get(0).value = settings.displayName;
  3230. $('#setEmail').get(0).value = settings.email;
  3231. },
  3232. null);
  3233. };
  3234. /**
  3235. * Returns the size of the side panel.
  3236. */
  3237. my.getPanelSize = function () {
  3238. var availableHeight = window.innerHeight;
  3239. var availableWidth = window.innerWidth;
  3240. var panelWidth = 200;
  3241. if (availableWidth * 0.2 < 200) {
  3242. panelWidth = availableWidth * 0.2;
  3243. }
  3244. return [panelWidth, availableHeight];
  3245. };
  3246. my.isVisible = function() {
  3247. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3248. };
  3249. return my;
  3250. }(PanelToggler || {}));
  3251. module.exports = PanelToggler;
  3252. },{"../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){
  3253. /* global $, Util, nickname:true */
  3254. var Replacement = require("./Replacement");
  3255. var CommandsProcessor = require("./Commands");
  3256. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3257. var smileys = require("./smileys.json").smileys;
  3258. var NicknameHandler = require("../../util/NicknameHandler");
  3259. var UIUtil = require("../../util/UIUtil");
  3260. var UIEvents = require("../../../../service/UI/UIEvents");
  3261. var notificationInterval = false;
  3262. var unreadMessages = 0;
  3263. /**
  3264. * Shows/hides a visual notification, indicating that a message has arrived.
  3265. */
  3266. function setVisualNotification(show) {
  3267. var unreadMsgElement = document.getElementById('unreadMessages');
  3268. var unreadMsgBottomElement
  3269. = document.getElementById('bottomUnreadMessages');
  3270. var glower = $('#chatButton');
  3271. var bottomGlower = $('#chatBottomButton');
  3272. if (unreadMessages) {
  3273. unreadMsgElement.innerHTML = unreadMessages.toString();
  3274. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3275. ToolbarToggler.dockToolbar(true);
  3276. var chatButtonElement
  3277. = document.getElementById('chatButton').parentNode;
  3278. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3279. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3280. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3281. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3282. unreadMsgElement.setAttribute(
  3283. 'style',
  3284. 'top:' + topIndent +
  3285. '; left:' + leftIndent + ';');
  3286. var chatBottomButtonElement
  3287. = document.getElementById('chatBottomButton').parentNode;
  3288. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3289. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3290. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3291. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3292. unreadMsgBottomElement.setAttribute(
  3293. 'style',
  3294. 'top:' + bottomTopIndent +
  3295. '; left:' + bottomLeftIndent + ';');
  3296. if (!glower.hasClass('icon-chat-simple')) {
  3297. glower.removeClass('icon-chat');
  3298. glower.addClass('icon-chat-simple');
  3299. }
  3300. }
  3301. else {
  3302. unreadMsgElement.innerHTML = '';
  3303. unreadMsgBottomElement.innerHTML = '';
  3304. glower.removeClass('icon-chat-simple');
  3305. glower.addClass('icon-chat');
  3306. }
  3307. if (show && !notificationInterval) {
  3308. notificationInterval = window.setInterval(function () {
  3309. glower.toggleClass('active');
  3310. bottomGlower.toggleClass('active glowing');
  3311. }, 800);
  3312. }
  3313. else if (!show && notificationInterval) {
  3314. window.clearInterval(notificationInterval);
  3315. notificationInterval = false;
  3316. glower.removeClass('active');
  3317. bottomGlower.removeClass('glowing');
  3318. bottomGlower.addClass('active');
  3319. }
  3320. }
  3321. /**
  3322. * Returns the current time in the format it is shown to the user
  3323. * @returns {string}
  3324. */
  3325. function getCurrentTime() {
  3326. var now = new Date();
  3327. var hour = now.getHours();
  3328. var minute = now.getMinutes();
  3329. var second = now.getSeconds();
  3330. if(hour.toString().length === 1) {
  3331. hour = '0'+hour;
  3332. }
  3333. if(minute.toString().length === 1) {
  3334. minute = '0'+minute;
  3335. }
  3336. if(second.toString().length === 1) {
  3337. second = '0'+second;
  3338. }
  3339. return hour+':'+minute+':'+second;
  3340. }
  3341. function toggleSmileys()
  3342. {
  3343. var smileys = $('#smileysContainer');
  3344. if(!smileys.is(':visible')) {
  3345. smileys.show("slide", { direction: "down", duration: 300});
  3346. } else {
  3347. smileys.hide("slide", { direction: "down", duration: 300});
  3348. }
  3349. $('#usermsg').focus();
  3350. }
  3351. function addClickFunction(smiley, number) {
  3352. smiley.onclick = function addSmileyToMessage() {
  3353. var usermsg = $('#usermsg');
  3354. var message = usermsg.val();
  3355. message += smileys['smiley' + number];
  3356. usermsg.val(message);
  3357. usermsg.get(0).setSelectionRange(message.length, message.length);
  3358. toggleSmileys();
  3359. usermsg.focus();
  3360. };
  3361. }
  3362. /**
  3363. * Adds the smileys container to the chat
  3364. */
  3365. function addSmileys() {
  3366. var smileysContainer = document.createElement('div');
  3367. smileysContainer.id = 'smileysContainer';
  3368. for(var i = 1; i <= 21; i++) {
  3369. var smileyContainer = document.createElement('div');
  3370. smileyContainer.id = 'smiley' + i;
  3371. smileyContainer.className = 'smileyContainer';
  3372. var smiley = document.createElement('img');
  3373. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3374. smiley.className = 'smiley';
  3375. addClickFunction(smiley, i);
  3376. smileyContainer.appendChild(smiley);
  3377. smileysContainer.appendChild(smileyContainer);
  3378. }
  3379. $("#chatspace").append(smileysContainer);
  3380. }
  3381. /**
  3382. * Resizes the chat conversation.
  3383. */
  3384. function resizeChatConversation() {
  3385. var msgareaHeight = $('#usermsg').outerHeight();
  3386. var chatspace = $('#chatspace');
  3387. var width = chatspace.width();
  3388. var chat = $('#chatconversation');
  3389. var smileys = $('#smileysarea');
  3390. smileys.height(msgareaHeight);
  3391. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3392. $('#smileysContainer').css('bottom', msgareaHeight);
  3393. chat.width(width - 10);
  3394. chat.height(window.innerHeight - 15 - msgareaHeight);
  3395. }
  3396. /**
  3397. * Chat related user interface.
  3398. */
  3399. var Chat = (function (my) {
  3400. /**
  3401. * Initializes chat related interface.
  3402. */
  3403. my.init = function () {
  3404. if(NicknameHandler.getNickname())
  3405. Chat.setChatConversationMode(true);
  3406. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3407. function (nickname) {
  3408. Chat.setChatConversationMode(true);
  3409. });
  3410. $('#nickinput').keydown(function (event) {
  3411. if (event.keyCode === 13) {
  3412. event.preventDefault();
  3413. var val = UIUtil.escapeHtml(this.value);
  3414. this.value = '';
  3415. if (!NicknameHandler.getNickname()) {
  3416. NicknameHandler.setNickname(val);
  3417. return;
  3418. }
  3419. }
  3420. });
  3421. $('#usermsg').keydown(function (event) {
  3422. if (event.keyCode === 13) {
  3423. event.preventDefault();
  3424. var value = this.value;
  3425. $('#usermsg').val('').trigger('autosize.resize');
  3426. this.focus();
  3427. var command = new CommandsProcessor(value);
  3428. if(command.isCommand())
  3429. {
  3430. command.processCommand();
  3431. }
  3432. else
  3433. {
  3434. var message = UIUtil.escapeHtml(value);
  3435. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3436. }
  3437. }
  3438. });
  3439. var onTextAreaResize = function () {
  3440. resizeChatConversation();
  3441. Chat.scrollChatToBottom();
  3442. };
  3443. $('#usermsg').autosize({callback: onTextAreaResize});
  3444. $("#chatspace").bind("shown",
  3445. function () {
  3446. unreadMessages = 0;
  3447. setVisualNotification(false);
  3448. });
  3449. addSmileys();
  3450. };
  3451. /**
  3452. * Appends the given message to the chat conversation.
  3453. */
  3454. my.updateChatConversation = function (from, displayName, message) {
  3455. var divClassName = '';
  3456. if (APP.xmpp.myJid() === from) {
  3457. divClassName = "localuser";
  3458. }
  3459. else {
  3460. divClassName = "remoteuser";
  3461. if (!Chat.isVisible()) {
  3462. unreadMessages++;
  3463. UIUtil.playSoundNotification('chatNotification');
  3464. setVisualNotification(true);
  3465. }
  3466. }
  3467. // replace links and smileys
  3468. // Strophe already escapes special symbols on sending,
  3469. // so we escape here only tags to avoid double &amp;
  3470. var escMessage = message.replace(/</g, '&lt;').
  3471. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  3472. var escDisplayName = UIUtil.escapeHtml(displayName);
  3473. message = Replacement.processReplacements(escMessage);
  3474. var messageContainer =
  3475. '<div class="chatmessage">'+
  3476. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  3477. '<div class="username ' + divClassName +'">' + escDisplayName +
  3478. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  3479. '</div>' + '<div class="usermessage">' + message + '</div>' +
  3480. '</div>';
  3481. $('#chatconversation').append(messageContainer);
  3482. $('#chatconversation').animate(
  3483. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3484. };
  3485. /**
  3486. * Appends error message to the conversation
  3487. * @param errorMessage the received error message.
  3488. * @param originalText the original message.
  3489. */
  3490. my.chatAddError = function(errorMessage, originalText)
  3491. {
  3492. errorMessage = UIUtil.escapeHtml(errorMessage);
  3493. originalText = UIUtil.escapeHtml(originalText);
  3494. $('#chatconversation').append(
  3495. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  3496. (originalText? (' \"'+ originalText + '\"') : "") +
  3497. ' was not sent.' +
  3498. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  3499. $('#chatconversation').animate(
  3500. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3501. };
  3502. /**
  3503. * Sets the subject to the UI
  3504. * @param subject the subject
  3505. */
  3506. my.chatSetSubject = function(subject)
  3507. {
  3508. if(subject)
  3509. subject = subject.trim();
  3510. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  3511. if(subject === "")
  3512. {
  3513. $("#subject").css({display: "none"});
  3514. }
  3515. else
  3516. {
  3517. $("#subject").css({display: "block"});
  3518. }
  3519. };
  3520. /**
  3521. * Sets the chat conversation mode.
  3522. */
  3523. my.setChatConversationMode = function (isConversationMode) {
  3524. if (isConversationMode) {
  3525. $('#nickname').css({visibility: 'hidden'});
  3526. $('#chatconversation').css({visibility: 'visible'});
  3527. $('#usermsg').css({visibility: 'visible'});
  3528. $('#smileysarea').css({visibility: 'visible'});
  3529. $('#usermsg').focus();
  3530. }
  3531. };
  3532. /**
  3533. * Resizes the chat area.
  3534. */
  3535. my.resizeChat = function () {
  3536. var chatSize = require("../SidePanelToggler").getPanelSize();
  3537. $('#chatspace').width(chatSize[0]);
  3538. $('#chatspace').height(chatSize[1]);
  3539. resizeChatConversation();
  3540. };
  3541. /**
  3542. * Indicates if the chat is currently visible.
  3543. */
  3544. my.isVisible = function () {
  3545. return $('#chatspace').is(":visible");
  3546. };
  3547. /**
  3548. * Shows and hides the window with the smileys
  3549. */
  3550. my.toggleSmileys = toggleSmileys;
  3551. /**
  3552. * Scrolls chat to the bottom.
  3553. */
  3554. my.scrollChatToBottom = function() {
  3555. setTimeout(function () {
  3556. $('#chatconversation').scrollTop(
  3557. $('#chatconversation')[0].scrollHeight);
  3558. }, 5);
  3559. };
  3560. return my;
  3561. }(Chat || {}));
  3562. module.exports = Chat;
  3563. },{"../../../../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){
  3564. var UIUtil = require("../../util/UIUtil");
  3565. /**
  3566. * List with supported commands. The keys are the names of the commands and
  3567. * the value is the function that processes the message.
  3568. * @type {{String: function}}
  3569. */
  3570. var commands = {
  3571. "topic" : processTopic
  3572. };
  3573. /**
  3574. * Extracts the command from the message.
  3575. * @param message the received message
  3576. * @returns {string} the command
  3577. */
  3578. function getCommand(message)
  3579. {
  3580. if(message)
  3581. {
  3582. for(var command in commands)
  3583. {
  3584. if(message.indexOf("/" + command) == 0)
  3585. return command;
  3586. }
  3587. }
  3588. return "";
  3589. };
  3590. /**
  3591. * Processes the data for topic command.
  3592. * @param commandArguments the arguments of the topic command.
  3593. */
  3594. function processTopic(commandArguments)
  3595. {
  3596. var topic = UIUtil.escapeHtml(commandArguments);
  3597. APP.xmpp.setSubject(topic);
  3598. }
  3599. /**
  3600. * Constructs new CommandProccessor instance from a message that
  3601. * handles commands received via chat messages.
  3602. * @param message the message
  3603. * @constructor
  3604. */
  3605. function CommandsProcessor(message)
  3606. {
  3607. var command = getCommand(message);
  3608. /**
  3609. * Returns the name of the command.
  3610. * @returns {String} the command
  3611. */
  3612. this.getCommand = function()
  3613. {
  3614. return command;
  3615. };
  3616. var messageArgument = message.substr(command.length + 2);
  3617. /**
  3618. * Returns the arguments of the command.
  3619. * @returns {string}
  3620. */
  3621. this.getArgument = function()
  3622. {
  3623. return messageArgument;
  3624. };
  3625. }
  3626. /**
  3627. * Checks whether this instance is valid command or not.
  3628. * @returns {boolean}
  3629. */
  3630. CommandsProcessor.prototype.isCommand = function()
  3631. {
  3632. if(this.getCommand())
  3633. return true;
  3634. return false;
  3635. };
  3636. /**
  3637. * Processes the command.
  3638. */
  3639. CommandsProcessor.prototype.processCommand = function()
  3640. {
  3641. if(!this.isCommand())
  3642. return;
  3643. commands[this.getCommand()](this.getArgument());
  3644. };
  3645. module.exports = CommandsProcessor;
  3646. },{"../../util/UIUtil":29}],19:[function(require,module,exports){
  3647. var Smileys = require("./smileys.json");
  3648. /**
  3649. * Processes links and smileys in "body"
  3650. */
  3651. function processReplacements(body)
  3652. {
  3653. //make links clickable
  3654. body = linkify(body);
  3655. //add smileys
  3656. body = smilify(body);
  3657. return body;
  3658. }
  3659. /**
  3660. * Finds and replaces all links in the links in "body"
  3661. * with their <a href=""></a>
  3662. */
  3663. function linkify(inputText)
  3664. {
  3665. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  3666. //URLs starting with http://, https://, or ftp://
  3667. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  3668. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  3669. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  3670. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  3671. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  3672. //Change email addresses to mailto:: links.
  3673. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  3674. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  3675. return replacedText;
  3676. }
  3677. /**
  3678. * Replaces common smiley strings with images
  3679. */
  3680. function smilify(body)
  3681. {
  3682. if(!body) {
  3683. return body;
  3684. }
  3685. var regexs = Smileys["regexs"];
  3686. for(var smiley in regexs) {
  3687. if(regexs.hasOwnProperty(smiley)) {
  3688. body = body.replace(regexs[smiley],
  3689. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  3690. }
  3691. }
  3692. return body;
  3693. }
  3694. module.exports = {
  3695. processReplacements: processReplacements,
  3696. linkify: linkify
  3697. };
  3698. },{"./smileys.json":20}],20:[function(require,module,exports){
  3699. module.exports={
  3700. "smileys": {
  3701. "smiley1": ":)",
  3702. "smiley2": ":(",
  3703. "smiley3": ":D",
  3704. "smiley4": "(y)",
  3705. "smiley5": " :P",
  3706. "smiley6": "(wave)",
  3707. "smiley7": "(blush)",
  3708. "smiley8": "(chuckle)",
  3709. "smiley9": "(shocked)",
  3710. "smiley10": ":*",
  3711. "smiley11": "(n)",
  3712. "smiley12": "(search)",
  3713. "smiley13": " <3",
  3714. "smiley14": "(oops)",
  3715. "smiley15": "(angry)",
  3716. "smiley16": "(angel)",
  3717. "smiley17": "(sick)",
  3718. "smiley18": ";(",
  3719. "smiley19": "(bomb)",
  3720. "smiley20": "(clap)",
  3721. "smiley21": " ;)"
  3722. },
  3723. "regexs": {
  3724. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  3725. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  3726. "smiley1": /(:-\)|:\))/gi,
  3727. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  3728. "smiley5": /(:-P|:P|:-p|:p)/gi,
  3729. "smiley6": /(\(wave\))/gi,
  3730. "smiley7": /(\(blush\))/gi,
  3731. "smiley8": /(\(chuckle\))/gi,
  3732. "smiley9": /(:-0|\(shocked\))/gi,
  3733. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  3734. "smiley11": /(\(n\))/gi,
  3735. "smiley12": /(\(search\))/g,
  3736. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  3737. "smiley14": /(\(oops\))/gi,
  3738. "smiley15": /(\(angry\))/gi,
  3739. "smiley16": /(\(angel\))/gi,
  3740. "smiley17": /(\(sick\))/gi,
  3741. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  3742. "smiley19": /(\(bomb\))/gi,
  3743. "smiley20": /(\(clap\))/gi,
  3744. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  3745. }
  3746. }
  3747. },{}],21:[function(require,module,exports){
  3748. var numberOfContacts = 0;
  3749. var notificationInterval;
  3750. /**
  3751. * Updates the number of participants in the contact list button and sets
  3752. * the glow
  3753. * @param delta indicates whether a new user has joined (1) or someone has
  3754. * left(-1)
  3755. */
  3756. function updateNumberOfParticipants(delta) {
  3757. //when the user is alone we don't show the number of participants
  3758. if(numberOfContacts === 0) {
  3759. $("#numberOfParticipants").text('');
  3760. numberOfContacts += delta;
  3761. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  3762. ContactList.setVisualNotification(true);
  3763. numberOfContacts += delta;
  3764. $("#numberOfParticipants").text(numberOfContacts);
  3765. }
  3766. }
  3767. /**
  3768. * Creates the avatar element.
  3769. *
  3770. * @return the newly created avatar element
  3771. */
  3772. function createAvatar(id) {
  3773. var avatar = document.createElement('img');
  3774. avatar.className = "icon-avatar avatar";
  3775. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  3776. return avatar;
  3777. }
  3778. /**
  3779. * Creates the display name paragraph.
  3780. *
  3781. * @param displayName the display name to set
  3782. */
  3783. function createDisplayNameParagraph(displayName) {
  3784. var p = document.createElement('p');
  3785. p.innerText = displayName;
  3786. return p;
  3787. }
  3788. function stopGlowing(glower) {
  3789. window.clearInterval(notificationInterval);
  3790. notificationInterval = false;
  3791. glower.removeClass('glowing');
  3792. if (!ContactList.isVisible()) {
  3793. glower.removeClass('active');
  3794. }
  3795. }
  3796. /**
  3797. * Contact list.
  3798. */
  3799. var ContactList = {
  3800. /**
  3801. * Indicates if the chat is currently visible.
  3802. *
  3803. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  3804. * otherwise
  3805. */
  3806. isVisible: function () {
  3807. return $('#contactlist').is(":visible");
  3808. },
  3809. /**
  3810. * Adds a contact for the given peerJid if such doesn't yet exist.
  3811. *
  3812. * @param peerJid the peerJid corresponding to the contact
  3813. * @param id the user's email or userId used to get the user's avatar
  3814. */
  3815. ensureAddContact: function (peerJid, id) {
  3816. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3817. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  3818. if (!contact || contact.length <= 0)
  3819. ContactList.addContact(peerJid, id);
  3820. },
  3821. /**
  3822. * Adds a contact for the given peer jid.
  3823. *
  3824. * @param peerJid the jid of the contact to add
  3825. * @param id the email or userId of the user
  3826. */
  3827. addContact: function (peerJid, id) {
  3828. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3829. var contactlist = $('#contactlist>ul');
  3830. var newContact = document.createElement('li');
  3831. newContact.id = resourceJid;
  3832. newContact.className = "clickable";
  3833. newContact.onclick = function (event) {
  3834. if (event.currentTarget.className === "clickable") {
  3835. $(ContactList).trigger('contactclicked', [peerJid]);
  3836. }
  3837. };
  3838. newContact.appendChild(createAvatar(id));
  3839. newContact.appendChild(createDisplayNameParagraph("Participant"));
  3840. var clElement = contactlist.get(0);
  3841. if (resourceJid === APP.xmpp.myResource()
  3842. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  3843. clElement.insertBefore(newContact,
  3844. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  3845. }
  3846. else {
  3847. clElement.appendChild(newContact);
  3848. }
  3849. updateNumberOfParticipants(1);
  3850. },
  3851. /**
  3852. * Removes a contact for the given peer jid.
  3853. *
  3854. * @param peerJid the peerJid corresponding to the contact to remove
  3855. */
  3856. removeContact: function (peerJid) {
  3857. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3858. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  3859. if (contact && contact.length > 0) {
  3860. var contactlist = $('#contactlist>ul');
  3861. contactlist.get(0).removeChild(contact.get(0));
  3862. updateNumberOfParticipants(-1);
  3863. }
  3864. },
  3865. setVisualNotification: function (show, stopGlowingIn) {
  3866. var glower = $('#contactListButton');
  3867. if (show && !notificationInterval) {
  3868. notificationInterval = window.setInterval(function () {
  3869. glower.toggleClass('active glowing');
  3870. }, 800);
  3871. }
  3872. else if (!show && notificationInterval) {
  3873. stopGlowing(glower);
  3874. }
  3875. if (stopGlowingIn) {
  3876. setTimeout(function () {
  3877. stopGlowing(glower);
  3878. }, stopGlowingIn);
  3879. }
  3880. },
  3881. setClickable: function (resourceJid, isClickable) {
  3882. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  3883. if (isClickable) {
  3884. contact.addClass('clickable');
  3885. } else {
  3886. contact.removeClass('clickable');
  3887. }
  3888. },
  3889. onDisplayNameChange: function (peerJid, displayName) {
  3890. if (peerJid === 'localVideoContainer')
  3891. peerJid = APP.xmpp.myJid();
  3892. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3893. var contactName = $('#contactlist #' + resourceJid + '>p');
  3894. if (contactName && displayName && displayName.length > 0)
  3895. contactName.html(displayName);
  3896. }
  3897. };
  3898. module.exports = ContactList;
  3899. },{}],22:[function(require,module,exports){
  3900. var Avatar = require("../../avatar/Avatar");
  3901. var Settings = require("./../../../settings/Settings");
  3902. var UIUtil = require("../../util/UIUtil");
  3903. var languages = require("../../../../service/translation/languages");
  3904. function generateLanguagesSelectBox()
  3905. {
  3906. var currentLang = APP.translation.getCurrentLanguage();
  3907. var html = "<select id=\"languages_selectbox\">";
  3908. var langArray = languages.getLanguages();
  3909. for(var i = 0; i < langArray.length; i++)
  3910. {
  3911. var lang = langArray[i];
  3912. html += "<option ";
  3913. if(lang === currentLang)
  3914. html += "selected ";
  3915. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  3916. html += "</option>";
  3917. }
  3918. return html + "</select>";
  3919. }
  3920. var SettingsMenu = {
  3921. init: function () {
  3922. $("#updateSettings").before(generateLanguagesSelectBox());
  3923. APP.translation.translateElement($("#languages_selectbox"));
  3924. $('#settingsmenu>input').keyup(function(event){
  3925. if(event.keyCode === 13) {//enter
  3926. SettingsMenu.update();
  3927. }
  3928. });
  3929. $("#updateSettings").click(function () {
  3930. SettingsMenu.update();
  3931. });
  3932. },
  3933. update: function() {
  3934. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  3935. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  3936. if(newDisplayName) {
  3937. var displayName = Settings.setDisplayName(newDisplayName);
  3938. APP.xmpp.addToPresence("displayName", displayName, true);
  3939. }
  3940. var language = $("#languages_selectbox").val();
  3941. APP.translation.setLanguage(language);
  3942. Settings.setLanguage(language);
  3943. APP.xmpp.addToPresence("email", newEmail);
  3944. var email = Settings.setEmail(newEmail);
  3945. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  3946. },
  3947. isVisible: function() {
  3948. return $('#settingsmenu').is(':visible');
  3949. },
  3950. setDisplayName: function(newDisplayName) {
  3951. var displayName = Settings.setDisplayName(newDisplayName);
  3952. $('#setDisplayName').get(0).value = displayName;
  3953. },
  3954. onDisplayNameChange: function(peerJid, newDisplayName) {
  3955. if(peerJid === 'localVideoContainer' ||
  3956. peerJid === APP.xmpp.myJid()) {
  3957. this.setDisplayName(newDisplayName);
  3958. }
  3959. }
  3960. };
  3961. module.exports = SettingsMenu;
  3962. },{"../../../../service/translation/languages":87,"../../avatar/Avatar":12,"../../util/UIUtil":29,"./../../../settings/Settings":37}],23:[function(require,module,exports){
  3963. var PanelToggler = require("../side_pannels/SidePanelToggler");
  3964. var buttonHandlers = {
  3965. "bottom_toolbar_contact_list": function () {
  3966. BottomToolbar.toggleContactList();
  3967. },
  3968. "bottom_toolbar_film_strip": function () {
  3969. BottomToolbar.toggleFilmStrip();
  3970. },
  3971. "bottom_toolbar_chat": function () {
  3972. BottomToolbar.toggleChat();
  3973. }
  3974. };
  3975. var BottomToolbar = (function (my) {
  3976. my.init = function () {
  3977. for(var k in buttonHandlers)
  3978. $("#" + k).click(buttonHandlers[k]);
  3979. };
  3980. my.toggleChat = function() {
  3981. PanelToggler.toggleChat();
  3982. };
  3983. my.toggleContactList = function() {
  3984. PanelToggler.toggleContactList();
  3985. };
  3986. my.toggleFilmStrip = function() {
  3987. var filmstrip = $("#remoteVideos");
  3988. filmstrip.toggleClass("hidden");
  3989. };
  3990. $(document).bind("remotevideo.resized", function (event, width, height) {
  3991. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  3992. $('#bottomToolbar').css({bottom: bottom + 'px'});
  3993. });
  3994. return my;
  3995. }(BottomToolbar || {}));
  3996. module.exports = BottomToolbar;
  3997. },{"../side_pannels/SidePanelToggler":16}],24:[function(require,module,exports){
  3998. /* global APP,$, buttonClick, config, lockRoom,
  3999. setSharedKey, Util */
  4000. var messageHandler = require("../util/MessageHandler");
  4001. var BottomToolbar = require("./BottomToolbar");
  4002. var Prezi = require("../prezi/Prezi");
  4003. var Etherpad = require("../etherpad/Etherpad");
  4004. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4005. var Authentication = require("../authentication/Authentication");
  4006. var UIUtil = require("../util/UIUtil");
  4007. var AuthenticationEvents
  4008. = require("../../../service/authentication/AuthenticationEvents");
  4009. var roomUrl = null;
  4010. var sharedKey = '';
  4011. var UI = null;
  4012. var buttonHandlers =
  4013. {
  4014. "toolbar_button_mute": function () {
  4015. return APP.UI.toggleAudio();
  4016. },
  4017. "toolbar_button_camera": function () {
  4018. return APP.UI.toggleVideo();
  4019. },
  4020. /*"toolbar_button_authentication": function () {
  4021. return Toolbar.authenticateClicked();
  4022. },*/
  4023. "toolbar_button_record": function () {
  4024. return toggleRecording();
  4025. },
  4026. "toolbar_button_security": function () {
  4027. return Toolbar.openLockDialog();
  4028. },
  4029. "toolbar_button_link": function () {
  4030. return Toolbar.openLinkDialog();
  4031. },
  4032. "toolbar_button_chat": function () {
  4033. return BottomToolbar.toggleChat();
  4034. },
  4035. "toolbar_button_prezi": function () {
  4036. return Prezi.openPreziDialog();
  4037. },
  4038. "toolbar_button_etherpad": function () {
  4039. return Etherpad.toggleEtherpad(0);
  4040. },
  4041. "toolbar_button_desktopsharing": function () {
  4042. return APP.desktopsharing.toggleScreenSharing();
  4043. },
  4044. "toolbar_button_fullScreen": function()
  4045. {
  4046. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4047. return Toolbar.toggleFullScreen();
  4048. },
  4049. "toolbar_button_sip": function () {
  4050. return callSipButtonClicked();
  4051. },
  4052. "toolbar_button_settings": function () {
  4053. PanelToggler.toggleSettingsMenu();
  4054. },
  4055. "toolbar_button_hangup": function () {
  4056. return hangup();
  4057. },
  4058. "toolbar_button_login": function () {
  4059. Toolbar.authenticateClicked();
  4060. },
  4061. "toolbar_button_logout": function () {
  4062. // Ask for confirmation
  4063. messageHandler.openTwoButtonDialog(
  4064. "dialog.logoutTitle",
  4065. null,
  4066. "dialog.logoutQuestion",
  4067. null,
  4068. false,
  4069. "dialog.Yes",
  4070. function (evt, yes) {
  4071. if (yes) {
  4072. APP.xmpp.logout(function (url) {
  4073. if (url) {
  4074. window.location.href = url;
  4075. } else {
  4076. hangup();
  4077. }
  4078. });
  4079. }
  4080. });
  4081. }
  4082. };
  4083. function hangup() {
  4084. APP.xmpp.disposeConference();
  4085. if(config.enableWelcomePage)
  4086. {
  4087. setTimeout(function()
  4088. {
  4089. window.localStorage.welcomePageDisabled = false;
  4090. window.location.pathname = "/";
  4091. }, 10000);
  4092. }
  4093. var title = APP.translation.generateTranslatonHTML(
  4094. "dialog.sessTerminated");
  4095. var msg = APP.translation.generateTranslatonHTML(
  4096. "dialog.hungUp");
  4097. var button = APP.translation.generateTranslatonHTML(
  4098. "dialog.joinAgain");
  4099. var buttons = {};
  4100. buttons.joinAgain = {title: button, value: true};
  4101. UI.messageHandler.openDialog(
  4102. title,
  4103. msg,
  4104. true,
  4105. buttons,
  4106. function(event, value, message, formVals)
  4107. {
  4108. window.location.reload();
  4109. return false;
  4110. }
  4111. );
  4112. }
  4113. /**
  4114. * Starts or stops the recording for the conference.
  4115. */
  4116. function toggleRecording() {
  4117. APP.xmpp.toggleRecording(function (callback) {
  4118. var msg = APP.translation.generateTranslatonHTML(
  4119. "dialog.recordingToken");
  4120. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  4121. '<h2>' + msg + '</h2>' +
  4122. '<input id="recordingToken" type="text" ' +
  4123. 'placeholder="token" autofocus>',
  4124. false,
  4125. "dialog.Save",
  4126. function (e, v, m, f) {
  4127. if (v) {
  4128. var token = document.getElementById('recordingToken');
  4129. if (token.value) {
  4130. callback(UIUtil.escapeHtml(token.value));
  4131. }
  4132. }
  4133. },
  4134. function (event) {
  4135. document.getElementById('recordingToken').focus();
  4136. },
  4137. function () {
  4138. }
  4139. );
  4140. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4141. }
  4142. /**
  4143. * Locks / unlocks the room.
  4144. */
  4145. function lockRoom(lock) {
  4146. var currentSharedKey = '';
  4147. if (lock)
  4148. currentSharedKey = sharedKey;
  4149. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4150. // password is required
  4151. if (sharedKey)
  4152. {
  4153. console.log('set room password');
  4154. Toolbar.lockLockButton();
  4155. }
  4156. else
  4157. {
  4158. console.log('removed room password');
  4159. Toolbar.unlockLockButton();
  4160. }
  4161. }, function (err) {
  4162. console.warn('setting password failed', err);
  4163. messageHandler.showError("dialog.lockTitle",
  4164. "dialog.lockMessage");
  4165. Toolbar.setSharedKey('');
  4166. }, function () {
  4167. console.warn('room passwords not supported');
  4168. messageHandler.showError("dialog.warning",
  4169. "dialog.passwordNotSupported");
  4170. Toolbar.setSharedKey('');
  4171. });
  4172. };
  4173. /**
  4174. * Invite participants to conference.
  4175. */
  4176. function inviteParticipants() {
  4177. if (roomUrl === null)
  4178. return;
  4179. var sharedKeyText = "";
  4180. if (sharedKey && sharedKey.length > 0) {
  4181. sharedKeyText =
  4182. "This conference is password protected. Please use the " +
  4183. "following pin when joining:%0D%0A%0D%0A" +
  4184. sharedKey + "%0D%0A%0D%0A";
  4185. }
  4186. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4187. var subject = "Invitation to a " + interfaceConfig.APP_NAME + " (" + conferenceName + ")";
  4188. var body = "Hey there, I%27d like to invite you to a " + interfaceConfig.APP_NAME +
  4189. " conference I%27ve just set up.%0D%0A%0D%0A" +
  4190. "Please click on the following link in order" +
  4191. " to join the conference.%0D%0A%0D%0A" +
  4192. roomUrl +
  4193. "%0D%0A%0D%0A" +
  4194. sharedKeyText +
  4195. "Note that " + interfaceConfig.APP_NAME + " is currently" +
  4196. " only supported by Chromium," +
  4197. " Google Chrome and Opera, so you need" +
  4198. " to be using one of these browsers.%0D%0A%0D%0A" +
  4199. "Talk to you in a sec!";
  4200. if (window.localStorage.displayname) {
  4201. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4202. }
  4203. if (interfaceConfig.INVITATION_POWERED_BY) {
  4204. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4205. }
  4206. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4207. }
  4208. function callSipButtonClicked()
  4209. {
  4210. var defaultNumber
  4211. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4212. var sipMsg = APP.translation.generateTranslatonHTML(
  4213. "dialog.sipMsg");
  4214. messageHandler.openTwoButtonDialog(null, null, null,
  4215. '<h2>' + sipMsg + '</h2>' +
  4216. '<input id="sipNumber" type="text"' +
  4217. ' value="' + defaultNumber + '" autofocus>',
  4218. false,
  4219. "dialog.Dial",
  4220. function (e, v, m, f) {
  4221. if (v) {
  4222. var numberInput = document.getElementById('sipNumber');
  4223. if (numberInput.value) {
  4224. APP.xmpp.dial(numberInput.value, 'fromnumber',
  4225. UI.getRoomName(), sharedKey);
  4226. }
  4227. }
  4228. },
  4229. function (event) {
  4230. document.getElementById('sipNumber').focus();
  4231. }
  4232. );
  4233. }
  4234. var Toolbar = (function (my) {
  4235. my.init = function (ui) {
  4236. for(var k in buttonHandlers)
  4237. $("#" + k).click(buttonHandlers[k]);
  4238. UI = ui;
  4239. // Update login info
  4240. APP.xmpp.addListener(
  4241. AuthenticationEvents.IDENTITY_UPDATED,
  4242. function (authenticationEnabled, userIdentity) {
  4243. var loggedIn = false;
  4244. if (userIdentity) {
  4245. loggedIn = true;
  4246. }
  4247. //FIXME: XMPP authentication need improvements for "live" login
  4248. if (!APP.xmpp.isExternalAuthEnabled() && !loggedIn)
  4249. {
  4250. authenticationEnabled = false;
  4251. }
  4252. Toolbar.showAuthenticateButton(authenticationEnabled);
  4253. if (authenticationEnabled) {
  4254. Toolbar.setAuthenticatedIdentity(userIdentity);
  4255. Toolbar.showLoginButton(!loggedIn);
  4256. Toolbar.showLogoutButton(loggedIn);
  4257. }
  4258. }
  4259. );
  4260. },
  4261. /**
  4262. * Sets shared key
  4263. * @param sKey the shared key
  4264. */
  4265. my.setSharedKey = function (sKey) {
  4266. sharedKey = sKey;
  4267. };
  4268. my.authenticateClicked = function () {
  4269. Authentication.focusAuthenticationWindow();
  4270. // Get authentication URL
  4271. if (!APP.xmpp.getMUCJoined()) {
  4272. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4273. // If conference has not been started yet - redirect to login page
  4274. window.location.href = url;
  4275. });
  4276. } else {
  4277. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4278. // Otherwise - open popup with authentication URL
  4279. var authenticationWindow = Authentication.createAuthenticationWindow(
  4280. function () {
  4281. // On popup closed - retry room allocation
  4282. APP.xmpp.allocateConferenceFocus(
  4283. APP.UI.getRoomName(),
  4284. function () { console.info("AUTH DONE"); }
  4285. );
  4286. }, url);
  4287. if (!authenticationWindow) {
  4288. messageHandler.openMessageDialog(
  4289. null, "dialog.popupError");
  4290. }
  4291. });
  4292. }
  4293. };
  4294. /**
  4295. * Updates the room invite url.
  4296. */
  4297. my.updateRoomUrl = function (newRoomUrl) {
  4298. roomUrl = newRoomUrl;
  4299. // If the invite dialog has been already opened we update the information.
  4300. var inviteLink = document.getElementById('inviteLinkRef');
  4301. if (inviteLink) {
  4302. inviteLink.value = roomUrl;
  4303. inviteLink.select();
  4304. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  4305. }
  4306. };
  4307. /**
  4308. * Disables and enables some of the buttons.
  4309. */
  4310. my.setupButtonsFromConfig = function () {
  4311. if (config.disablePrezi)
  4312. {
  4313. $("#prezi_button").css({display: "none"});
  4314. }
  4315. };
  4316. /**
  4317. * Opens the lock room dialog.
  4318. */
  4319. my.openLockDialog = function () {
  4320. // Only the focus is able to set a shared key.
  4321. if (!APP.xmpp.isModerator()) {
  4322. if (sharedKey) {
  4323. messageHandler.openMessageDialog(null,
  4324. "dialog.passwordError");
  4325. } else {
  4326. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  4327. }
  4328. } else {
  4329. if (sharedKey) {
  4330. messageHandler.openTwoButtonDialog(null, null,
  4331. "dialog.passwordCheck",
  4332. null,
  4333. false,
  4334. "dialog.Remove",
  4335. function (e, v) {
  4336. if (v) {
  4337. Toolbar.setSharedKey('');
  4338. lockRoom(false);
  4339. }
  4340. });
  4341. } else {
  4342. var msg = APP.translation.generateTranslatonHTML(
  4343. "dialog.passwordMsg");
  4344. var yourPassword = APP.translation.translateString(
  4345. "dialog.yourPassword");
  4346. messageHandler.openTwoButtonDialog(null, null, null,
  4347. '<h2>' + msg + '</h2>' +
  4348. '<input id="lockKey" type="text"' +
  4349. 'placeholder="' + yourPassword + '" autofocus>',
  4350. false,
  4351. "dialog.Save",
  4352. function (e, v) {
  4353. if (v) {
  4354. var lockKey = document.getElementById('lockKey');
  4355. if (lockKey.value) {
  4356. Toolbar.setSharedKey(UIUtil.escapeHtml(lockKey.value));
  4357. lockRoom(true);
  4358. }
  4359. }
  4360. },
  4361. function () {
  4362. document.getElementById('lockKey').focus();
  4363. }
  4364. );
  4365. }
  4366. }
  4367. };
  4368. /**
  4369. * Opens the invite link dialog.
  4370. */
  4371. my.openLinkDialog = function () {
  4372. var inviteLink;
  4373. if (roomUrl === null) {
  4374. inviteLink = "Your conference is currently being created...";
  4375. } else {
  4376. inviteLink = encodeURI(roomUrl);
  4377. }
  4378. messageHandler.openTwoButtonDialog("dialog.shareLink",
  4379. null, null,
  4380. '<input id="inviteLinkRef" type="text" value="' +
  4381. inviteLink + '" onclick="this.select();" readonly>',
  4382. false,
  4383. "dialog.Invite",
  4384. function (e, v) {
  4385. if (v) {
  4386. if (roomUrl) {
  4387. inviteParticipants();
  4388. }
  4389. }
  4390. },
  4391. function () {
  4392. if (roomUrl) {
  4393. document.getElementById('inviteLinkRef').select();
  4394. } else {
  4395. document.getElementById('jqi_state0_buttonInvite')
  4396. .disabled = true;
  4397. }
  4398. }
  4399. );
  4400. };
  4401. /**
  4402. * Opens the settings dialog.
  4403. */
  4404. my.openSettingsDialog = function () {
  4405. var settings1 = APP.translation.generateTranslatonHTML(
  4406. "dialog.settings1");
  4407. var settings2 = APP.translation.generateTranslatonHTML(
  4408. "dialog.settings2");
  4409. var settings3 = APP.translation.generateTranslatonHTML(
  4410. "dialog.settings3");
  4411. var yourPassword = APP.translation.translateString(
  4412. "dialog.yourPassword");
  4413. messageHandler.openTwoButtonDialog(null,
  4414. '<h2>' + settings1 + '</h2>' +
  4415. '<input type="checkbox" id="initMuted">' +
  4416. settings2 + '<br/>' +
  4417. '<input type="checkbox" id="requireNicknames">' +
  4418. settings3 +
  4419. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  4420. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  4421. null,
  4422. null,
  4423. false,
  4424. "dialog.Save",
  4425. function () {
  4426. document.getElementById('lockKey').focus();
  4427. },
  4428. function (e, v) {
  4429. if (v) {
  4430. if ($('#initMuted').is(":checked")) {
  4431. // it is checked
  4432. }
  4433. if ($('#requireNicknames').is(":checked")) {
  4434. // it is checked
  4435. }
  4436. /*
  4437. var lockKey = document.getElementById('lockKey');
  4438. if (lockKey.value) {
  4439. setSharedKey(lockKey.value);
  4440. lockRoom(true);
  4441. }
  4442. */
  4443. }
  4444. }
  4445. );
  4446. };
  4447. /**
  4448. * Toggles the application in and out of full screen mode
  4449. * (a.k.a. presentation mode in Chrome).
  4450. */
  4451. my.toggleFullScreen = function () {
  4452. var fsElement = document.documentElement;
  4453. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  4454. //Enter Full Screen
  4455. if (fsElement.mozRequestFullScreen) {
  4456. fsElement.mozRequestFullScreen();
  4457. }
  4458. else {
  4459. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  4460. }
  4461. } else {
  4462. //Exit Full Screen
  4463. if (document.mozCancelFullScreen) {
  4464. document.mozCancelFullScreen();
  4465. } else {
  4466. document.webkitCancelFullScreen();
  4467. }
  4468. }
  4469. };
  4470. /**
  4471. * Unlocks the lock button state.
  4472. */
  4473. my.unlockLockButton = function () {
  4474. if ($("#lockIcon").hasClass("icon-security-locked"))
  4475. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4476. };
  4477. /**
  4478. * Updates the lock button state to locked.
  4479. */
  4480. my.lockLockButton = function () {
  4481. if ($("#lockIcon").hasClass("icon-security"))
  4482. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4483. };
  4484. /**
  4485. * Shows or hides authentication button
  4486. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  4487. */
  4488. my.showAuthenticateButton = function (show) {
  4489. if (show) {
  4490. $('#authentication').css({display: "inline"});
  4491. }
  4492. else {
  4493. $('#authentication').css({display: "none"});
  4494. }
  4495. };
  4496. // Shows or hides the 'recording' button.
  4497. my.showRecordingButton = function (show) {
  4498. if (!config.enableRecording) {
  4499. return;
  4500. }
  4501. if (show) {
  4502. $('#recording').css({display: "inline"});
  4503. }
  4504. else {
  4505. $('#recording').css({display: "none"});
  4506. }
  4507. };
  4508. // Sets the state of the recording button
  4509. my.setRecordingButtonState = function (isRecording) {
  4510. if (isRecording) {
  4511. $('#recordButton').removeClass("icon-recEnable");
  4512. $('#recordButton').addClass("icon-recEnable active");
  4513. } else {
  4514. $('#recordButton').removeClass("icon-recEnable active");
  4515. $('#recordButton').addClass("icon-recEnable");
  4516. }
  4517. };
  4518. // Shows or hides SIP calls button
  4519. my.showSipCallButton = function (show) {
  4520. if (APP.xmpp.isSipGatewayEnabled() && show) {
  4521. $('#sipCallButton').css({display: "inline-block"});
  4522. } else {
  4523. $('#sipCallButton').css({display: "none"});
  4524. }
  4525. };
  4526. /**
  4527. * Displays user authenticated identity name(login).
  4528. * @param authIdentity identity name to be displayed.
  4529. */
  4530. my.setAuthenticatedIdentity = function (authIdentity) {
  4531. if (authIdentity) {
  4532. $('#toolbar_auth_identity').css({display: "list-item"});
  4533. $('#toolbar_auth_identity').text(authIdentity);
  4534. } else {
  4535. $('#toolbar_auth_identity').css({display: "none"});
  4536. }
  4537. };
  4538. /**
  4539. * Shows/hides login button.
  4540. * @param show <tt>true</tt> to show
  4541. */
  4542. my.showLoginButton = function (show) {
  4543. if (show) {
  4544. $('#toolbar_button_login').css({display: "list-item"});
  4545. } else {
  4546. $('#toolbar_button_login').css({display: "none"});
  4547. }
  4548. };
  4549. /**
  4550. * Shows/hides logout button.
  4551. * @param show <tt>true</tt> to show
  4552. */
  4553. my.showLogoutButton = function (show) {
  4554. if (show) {
  4555. $('#toolbar_button_logout').css({display: "list-item"});
  4556. } else {
  4557. $('#toolbar_button_logout').css({display: "none"});
  4558. }
  4559. };
  4560. /**
  4561. * Sets the state of the button. The button has blue glow if desktop
  4562. * streaming is active.
  4563. * @param active the state of the desktop streaming.
  4564. */
  4565. my.changeDesktopSharingButtonState = function (active) {
  4566. var button = $("#desktopsharing > a");
  4567. if (active)
  4568. {
  4569. button.addClass("glow");
  4570. }
  4571. else
  4572. {
  4573. button.removeClass("glow");
  4574. }
  4575. };
  4576. return my;
  4577. }(Toolbar || {}));
  4578. module.exports = Toolbar;
  4579. },{"../../../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){
  4580. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  4581. var toolbarTimeoutObject,
  4582. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  4583. function showDesktopSharingButton() {
  4584. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  4585. $('#desktopsharing').css({display: "inline"});
  4586. } else {
  4587. $('#desktopsharing').css({display: "none"});
  4588. }
  4589. }
  4590. /**
  4591. * Hides the toolbar.
  4592. */
  4593. function hideToolbar() {
  4594. var header = $("#header"),
  4595. bottomToolbar = $("#bottomToolbar");
  4596. var isToolbarHover = false;
  4597. header.find('*').each(function () {
  4598. var id = $(this).attr('id');
  4599. if ($("#" + id + ":hover").length > 0) {
  4600. isToolbarHover = true;
  4601. }
  4602. });
  4603. if ($("#bottomToolbar:hover").length > 0) {
  4604. isToolbarHover = true;
  4605. }
  4606. clearTimeout(toolbarTimeoutObject);
  4607. toolbarTimeoutObject = null;
  4608. if (!isToolbarHover) {
  4609. header.hide("slide", { direction: "up", duration: 300});
  4610. $('#subject').animate({top: "-=40"}, 300);
  4611. if ($("#remoteVideos").hasClass("hidden")) {
  4612. bottomToolbar.hide(
  4613. "slide", {direction: "right", duration: 300});
  4614. }
  4615. }
  4616. else {
  4617. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4618. }
  4619. }
  4620. var ToolbarToggler = {
  4621. /**
  4622. * Shows the main toolbar.
  4623. */
  4624. showToolbar: function () {
  4625. var header = $("#header"),
  4626. bottomToolbar = $("#bottomToolbar");
  4627. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  4628. header.show("slide", { direction: "up", duration: 300});
  4629. $('#subject').animate({top: "+=40"}, 300);
  4630. if (!bottomToolbar.is(":visible")) {
  4631. bottomToolbar.show(
  4632. "slide", {direction: "right", duration: 300});
  4633. }
  4634. if (toolbarTimeoutObject) {
  4635. clearTimeout(toolbarTimeoutObject);
  4636. toolbarTimeoutObject = null;
  4637. }
  4638. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4639. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  4640. }
  4641. if (APP.xmpp.isModerator())
  4642. {
  4643. // TODO: Enable settings functionality.
  4644. // Need to uncomment the settings button in index.html.
  4645. // $('#settingsButton').css({visibility:"visible"});
  4646. }
  4647. // Show/hide desktop sharing button
  4648. showDesktopSharingButton();
  4649. },
  4650. /**
  4651. * Docks/undocks the toolbar.
  4652. *
  4653. * @param isDock indicates what operation to perform
  4654. */
  4655. dockToolbar: function (isDock) {
  4656. if (isDock) {
  4657. // First make sure the toolbar is shown.
  4658. if (!$('#header').is(':visible')) {
  4659. this.showToolbar();
  4660. }
  4661. // Then clear the time out, to dock the toolbar.
  4662. if (toolbarTimeoutObject) {
  4663. clearTimeout(toolbarTimeoutObject);
  4664. toolbarTimeoutObject = null;
  4665. }
  4666. }
  4667. else {
  4668. if (!$('#header').is(':visible')) {
  4669. this.showToolbar();
  4670. }
  4671. else {
  4672. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4673. }
  4674. }
  4675. },
  4676. showDesktopSharingButton: showDesktopSharingButton
  4677. };
  4678. module.exports = ToolbarToggler;
  4679. },{}],26:[function(require,module,exports){
  4680. var JitsiPopover = (function () {
  4681. /**
  4682. * Constructs new JitsiPopover and attaches it to the element
  4683. * @param element jquery selector
  4684. * @param options the options for the popover.
  4685. * @constructor
  4686. */
  4687. function JitsiPopover(element, options)
  4688. {
  4689. this.options = {
  4690. skin: "white",
  4691. content: ""
  4692. };
  4693. if(options)
  4694. {
  4695. if(options.skin)
  4696. this.options.skin = options.skin;
  4697. if(options.content)
  4698. this.options.content = options.content;
  4699. }
  4700. this.elementIsHovered = false;
  4701. this.popoverIsHovered = false;
  4702. this.popoverShown = false;
  4703. element.data("jitsi_popover", this);
  4704. this.element = element;
  4705. this.template = ' <div class="jitsipopover ' + this.options.skin +
  4706. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  4707. '<div class="jitsiPopupmenuPadding"></div></div>';
  4708. var self = this;
  4709. this.element.on("mouseenter", function () {
  4710. self.elementIsHovered = true;
  4711. self.show();
  4712. }).on("mouseleave", function () {
  4713. self.elementIsHovered = false;
  4714. setTimeout(function () {
  4715. self.hide();
  4716. }, 10);
  4717. });
  4718. }
  4719. /**
  4720. * Shows the popover
  4721. */
  4722. JitsiPopover.prototype.show = function () {
  4723. this.createPopover();
  4724. this.popoverShown = true;
  4725. };
  4726. /**
  4727. * Hides the popover
  4728. */
  4729. JitsiPopover.prototype.hide = function () {
  4730. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  4731. {
  4732. this.forceHide();
  4733. }
  4734. };
  4735. /**
  4736. * Hides the popover
  4737. */
  4738. JitsiPopover.prototype.forceHide = function () {
  4739. $(".jitsipopover").remove();
  4740. this.popoverShown = false;
  4741. };
  4742. /**
  4743. * Creates the popover html
  4744. */
  4745. JitsiPopover.prototype.createPopover = function () {
  4746. $("body").append(this.template);
  4747. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  4748. var self = this;
  4749. $(".jitsipopover").on("mouseenter", function () {
  4750. self.popoverIsHovered = true;
  4751. }).on("mouseleave", function () {
  4752. self.popoverIsHovered = false;
  4753. self.hide();
  4754. });
  4755. this.refreshPosition();
  4756. };
  4757. /**
  4758. * Refreshes the position of the popover
  4759. */
  4760. JitsiPopover.prototype.refreshPosition = function () {
  4761. $(".jitsipopover").position({
  4762. my: "bottom",
  4763. at: "top",
  4764. collision: "fit",
  4765. of: this.element,
  4766. using: function (position, elements) {
  4767. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  4768. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  4769. $(".jitsipopover > .arrow").css({left: calcLeft});
  4770. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  4771. }
  4772. });
  4773. };
  4774. /**
  4775. * Updates the content of popover.
  4776. * @param content new content
  4777. */
  4778. JitsiPopover.prototype.updateContent = function (content) {
  4779. this.options.content = content;
  4780. if(!this.popoverShown)
  4781. return;
  4782. $(".jitsipopover").remove();
  4783. this.createPopover();
  4784. };
  4785. return JitsiPopover;
  4786. })();
  4787. module.exports = JitsiPopover;
  4788. },{}],27:[function(require,module,exports){
  4789. /* global $, jQuery */
  4790. var messageHandler = (function(my) {
  4791. /**
  4792. * Shows a message to the user.
  4793. *
  4794. * @param titleString the title of the message
  4795. * @param messageString the text of the message
  4796. */
  4797. my.openMessageDialog = function(titleKey, messageKey) {
  4798. var title = null;
  4799. if(titleKey)
  4800. {
  4801. title = APP.translation.generateTranslatonHTML(titleKey);
  4802. }
  4803. var message = APP.translation.generateTranslatonHTML(messageKey);
  4804. $.prompt(message,
  4805. {
  4806. title: title,
  4807. persistent: false
  4808. }
  4809. );
  4810. };
  4811. /**
  4812. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  4813. *
  4814. * @param titleString the title of the message
  4815. * @param msgString the text of the message
  4816. * @param persistent boolean value which determines whether the message is persistent or not
  4817. * @param leftButton the fist button's text
  4818. * @param submitFunction function to be called on submit
  4819. * @param loadedFunction function to be called after the prompt is fully loaded
  4820. * @param closeFunction function to be called after the prompt is closed
  4821. */
  4822. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  4823. persistent, leftButtonKey, submitFunction, loadedFunction,
  4824. closeFunction)
  4825. {
  4826. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  4827. var buttons = {};
  4828. buttons.button1 = {title: leftButton, value: true};
  4829. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel");
  4830. buttons.button2 = {title: cancelButton, value: false};
  4831. var message = msgString, title = titleString;
  4832. if(titleKey)
  4833. {
  4834. title = APP.translation.generateTranslatonHTML(titleKey);
  4835. }
  4836. if(msgKey) {
  4837. message = APP.translation.generateTranslatonHTML(msgKey);
  4838. }
  4839. $.prompt(message, {
  4840. title: title,
  4841. persistent: false,
  4842. buttons: buttons,
  4843. defaultButton: 1,
  4844. loaded: loadedFunction,
  4845. submit: submitFunction,
  4846. close: closeFunction
  4847. });
  4848. };
  4849. /**
  4850. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  4851. *
  4852. * @param titleString the title of the message
  4853. * @param msgString the text of the message
  4854. * @param persistent boolean value which determines whether the message is persistent or not
  4855. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  4856. * that will be passed to submitFunction
  4857. * @param submitFunction function to be called on submit
  4858. * @param loadedFunction function to be called after the prompt is fully loaded
  4859. */
  4860. my.openDialog = function (titleString, msgString, persistent, buttons,
  4861. submitFunction, loadedFunction) {
  4862. var args = {
  4863. title: titleString,
  4864. persistent: persistent,
  4865. buttons: buttons,
  4866. defaultButton: 1,
  4867. loaded: loadedFunction,
  4868. submit: submitFunction
  4869. };
  4870. if (persistent) {
  4871. args.closeText = '';
  4872. }
  4873. return $.prompt(msgString, args);
  4874. };
  4875. /**
  4876. * Closes currently opened dialog.
  4877. */
  4878. my.closeDialog = function () {
  4879. $.prompt.close();
  4880. };
  4881. /**
  4882. * Shows a dialog with different states to the user.
  4883. *
  4884. * @param statesObject object containing all the states of the dialog
  4885. * @param loadedFunction function to be called after the prompt is fully loaded
  4886. * @param stateChangedFunction function to be called when the state of the dialog is changed
  4887. */
  4888. my.openDialogWithStates = function(statesObject, loadedFunction, stateChangedFunction) {
  4889. var myPrompt = $.prompt(statesObject);
  4890. myPrompt.on('impromptu:loaded', loadedFunction);
  4891. myPrompt.on('impromptu:statechanged', stateChangedFunction);
  4892. };
  4893. /**
  4894. * Opens new popup window for given <tt>url</tt> centered over current
  4895. * window.
  4896. *
  4897. * @param url the URL to be displayed in the popup window
  4898. * @param w the width of the popup window
  4899. * @param h the height of the popup window
  4900. * @param onPopupClosed optional callback function called when popup window
  4901. * has been closed.
  4902. *
  4903. * @returns popup window object if opened successfully or undefined
  4904. * in case we failed to open it(popup blocked)
  4905. */
  4906. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  4907. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  4908. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  4909. var popup = window.open(
  4910. url, '_blank',
  4911. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  4912. if (popup && onPopupClosed) {
  4913. var pollTimer = window.setInterval(function () {
  4914. if (popup.closed !== false) {
  4915. window.clearInterval(pollTimer);
  4916. onPopupClosed();
  4917. }
  4918. }, 200);
  4919. }
  4920. return popup;
  4921. };
  4922. /**
  4923. * Shows a dialog prompting the user to send an error report.
  4924. *
  4925. * @param titleString the title of the message
  4926. * @param msgString the text of the message
  4927. * @param error the error that is being reported
  4928. */
  4929. my.openReportDialog = function(titleKey, msgKey, error) {
  4930. my.openMessageDialog(titleKey, msgKey);
  4931. console.log(error);
  4932. //FIXME send the error to the server
  4933. };
  4934. /**
  4935. * Shows an error dialog to the user.
  4936. * @param title the title of the message
  4937. * @param message the text of the messafe
  4938. */
  4939. my.showError = function(titleKey, msgKey) {
  4940. if(!titleKey) {
  4941. titleKey = "dialog.oops";
  4942. }
  4943. if(!msgKey)
  4944. {
  4945. msgKey = "dialog.defaultError";
  4946. }
  4947. messageHandler.openMessageDialog(titleKey, msgKey);
  4948. };
  4949. my.notify = function(displayName, displayNameKey,
  4950. cls, messageKey, messageArguments) {
  4951. var displayNameSpan = '<span class="nickname" ';
  4952. if(displayName)
  4953. {
  4954. displayNameSpan += ">" + displayName;
  4955. }
  4956. else
  4957. {
  4958. displayNameSpan += "data-i18n='" + displayNameKey +
  4959. "'>" + APP.translation.translateString(displayNameKey);
  4960. }
  4961. displayNameSpan += "</span>";
  4962. toastr.info(
  4963. displayNameSpan + '<br>' +
  4964. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  4965. (messageArguments?
  4966. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  4967. : "") + ">" +
  4968. APP.translation.translateString(messageKey,
  4969. messageArguments) +
  4970. '</span>');
  4971. };
  4972. return my;
  4973. }(messageHandler || {}));
  4974. module.exports = messageHandler;
  4975. },{}],28:[function(require,module,exports){
  4976. var UIEvents = require("../../../service/UI/UIEvents");
  4977. var nickname = null;
  4978. var eventEmitter = null;
  4979. var NickanameHandler = {
  4980. init: function (emitter) {
  4981. eventEmitter = emitter;
  4982. var storedDisplayName = window.localStorage.displayname;
  4983. if (storedDisplayName) {
  4984. nickname = storedDisplayName;
  4985. }
  4986. },
  4987. setNickname: function (newNickname) {
  4988. if (!newNickname || nickname === newNickname)
  4989. return;
  4990. nickname = newNickname;
  4991. window.localStorage.displayname = nickname;
  4992. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  4993. },
  4994. getNickname: function () {
  4995. return nickname;
  4996. },
  4997. addListener: function (type, listener) {
  4998. eventEmitter.on(type, listener);
  4999. }
  5000. };
  5001. module.exports = NickanameHandler;
  5002. },{"../../../service/UI/UIEvents":83}],29:[function(require,module,exports){
  5003. /**
  5004. * Created by hristo on 12/22/14.
  5005. */
  5006. module.exports = {
  5007. /**
  5008. * Returns the available video width.
  5009. */
  5010. getAvailableVideoWidth: function () {
  5011. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5012. var rightPanelWidth
  5013. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5014. return window.innerWidth - rightPanelWidth;
  5015. },
  5016. /**
  5017. * Changes the style class of the element given by id.
  5018. */
  5019. buttonClick: function(id, classname) {
  5020. $(id).toggleClass(classname); // add the class to the clicked element
  5021. },
  5022. /**
  5023. * Returns the text width for the given element.
  5024. *
  5025. * @param el the element
  5026. */
  5027. getTextWidth: function (el) {
  5028. return (el.clientWidth + 1);
  5029. },
  5030. /**
  5031. * Returns the text height for the given element.
  5032. *
  5033. * @param el the element
  5034. */
  5035. getTextHeight: function (el) {
  5036. return (el.clientHeight + 1);
  5037. },
  5038. /**
  5039. * Plays the sound given by id.
  5040. *
  5041. * @param id the identifier of the audio element.
  5042. */
  5043. playSoundNotification: function (id) {
  5044. document.getElementById(id).play();
  5045. },
  5046. /**
  5047. * Escapes the given text.
  5048. */
  5049. escapeHtml: function (unsafeText) {
  5050. return $('<div/>').text(unsafeText).html();
  5051. },
  5052. imageToGrayScale: function (canvas) {
  5053. var context = canvas.getContext('2d');
  5054. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5055. var pixels = imgData.data;
  5056. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5057. var grayscale
  5058. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5059. pixels[i ] = grayscale; // red
  5060. pixels[i+1] = grayscale; // green
  5061. pixels[i+2] = grayscale; // blue
  5062. // pixels[i+3] is alpha
  5063. }
  5064. // redraw the image in black & white
  5065. context.putImageData(imgData, 0, 0);
  5066. },
  5067. setTooltip: function (element, key, position) {
  5068. element.setAttribute("data-i18n", "[data-content]" + key);
  5069. element.setAttribute("data-toggle", "popover");
  5070. element.setAttribute("data-placement", position);
  5071. element.setAttribute("data-html", true);
  5072. element.setAttribute("data-container", "body");
  5073. }
  5074. };
  5075. },{"../side_pannels/SidePanelToggler":16}],30:[function(require,module,exports){
  5076. var JitsiPopover = require("../util/JitsiPopover");
  5077. /**
  5078. * Constructs new connection indicator.
  5079. * @param videoContainer the video container associated with the indicator.
  5080. * @constructor
  5081. */
  5082. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5083. {
  5084. this.videoContainer = videoContainer;
  5085. this.bandwidth = null;
  5086. this.packetLoss = null;
  5087. this.bitrate = null;
  5088. this.showMoreValue = false;
  5089. this.resolution = null;
  5090. this.transport = [];
  5091. this.popover = null;
  5092. this.jid = jid;
  5093. this.create();
  5094. this.videoLayout = VideoLayout;
  5095. }
  5096. /**
  5097. * Values for the connection quality
  5098. * @type {{98: string,
  5099. * 81: string,
  5100. * 64: string,
  5101. * 47: string,
  5102. * 30: string,
  5103. * 0: string}}
  5104. */
  5105. ConnectionIndicator.connectionQualityValues = {
  5106. 98: "18px", //full
  5107. 81: "15px",//4 bars
  5108. 64: "11px",//3 bars
  5109. 47: "7px",//2 bars
  5110. 30: "3px",//1 bar
  5111. 0: "0px"//empty
  5112. };
  5113. ConnectionIndicator.getIP = function(value)
  5114. {
  5115. return value.substring(0, value.lastIndexOf(":"));
  5116. };
  5117. ConnectionIndicator.getPort = function(value)
  5118. {
  5119. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5120. };
  5121. ConnectionIndicator.getStringFromArray = function (array) {
  5122. var res = "";
  5123. for(var i = 0; i < array.length; i++)
  5124. {
  5125. res += (i === 0? "" : ", ") + array[i];
  5126. }
  5127. return res;
  5128. };
  5129. /**
  5130. * Generates the html content.
  5131. * @returns {string} the html content.
  5132. */
  5133. ConnectionIndicator.prototype.generateText = function () {
  5134. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5135. var translate = APP.translation.translateString;
  5136. if(this.bitrate === null)
  5137. {
  5138. downloadBitrate = "N/A";
  5139. uploadBitrate = "N/A";
  5140. }
  5141. else
  5142. {
  5143. downloadBitrate =
  5144. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5145. uploadBitrate =
  5146. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5147. }
  5148. if(this.packetLoss === null)
  5149. {
  5150. packetLoss = "N/A";
  5151. }
  5152. else
  5153. {
  5154. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5155. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5156. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5157. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5158. }
  5159. var resolutionValue = null;
  5160. if(this.resolution && this.jid != null)
  5161. {
  5162. var keys = Object.keys(this.resolution);
  5163. if(keys.length == 1)
  5164. {
  5165. for(var ssrc in this.resolution)
  5166. {
  5167. resolutionValue = this.resolution[ssrc];
  5168. }
  5169. }
  5170. else if(keys.length > 1)
  5171. {
  5172. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  5173. resolutionValue = this.resolution[displayedSsrc];
  5174. }
  5175. }
  5176. if(this.jid === null)
  5177. {
  5178. resolution = "";
  5179. if(this.resolution === null || !Object.keys(this.resolution) ||
  5180. Object.keys(this.resolution).length === 0)
  5181. {
  5182. resolution = "N/A";
  5183. }
  5184. else
  5185. for(i in this.resolution)
  5186. {
  5187. resolutionValue = this.resolution[i];
  5188. if(resolutionValue)
  5189. {
  5190. if(resolutionValue.height &&
  5191. resolutionValue.width)
  5192. {
  5193. resolution += (resolution === ""? "" : ", ") +
  5194. resolutionValue.width + "x" +
  5195. resolutionValue.height;
  5196. }
  5197. }
  5198. }
  5199. }
  5200. else if(!resolutionValue ||
  5201. !resolutionValue.height ||
  5202. !resolutionValue.width)
  5203. {
  5204. resolution = "N/A";
  5205. }
  5206. else
  5207. {
  5208. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5209. }
  5210. var result = "<table style='width:100%'>" +
  5211. "<tr>" +
  5212. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5213. translate("connectionindicator.bitrate") + "</span></td>" +
  5214. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5215. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5216. uploadBitrate + "</td>" +
  5217. "</tr><tr>" +
  5218. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5219. translate("connectionindicator.packetloss") + "</span></td>" +
  5220. "<td>" + packetLoss + "</td>" +
  5221. "</tr><tr>" +
  5222. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5223. translate("connectionindicator.resolution") + "</span></td>" +
  5224. "<td>" + resolution + "</td></tr></table>";
  5225. if(this.videoContainer.id == "localVideoContainer") {
  5226. result += "<div class=\"jitsipopover_showmore\" " +
  5227. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5228. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5229. (this.showMoreValue ? "less" : "more") + "'>" +
  5230. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5231. "</div><br />";
  5232. }
  5233. if(this.showMoreValue)
  5234. {
  5235. var downloadBandwidth, uploadBandwidth, transport;
  5236. if(this.bandwidth === null)
  5237. {
  5238. downloadBandwidth = "N/A";
  5239. uploadBandwidth = "N/A";
  5240. }
  5241. else
  5242. {
  5243. downloadBandwidth = this.bandwidth.download?
  5244. this.bandwidth.download + " Kbps" :
  5245. "N/A";
  5246. uploadBandwidth = this.bandwidth.upload?
  5247. this.bandwidth.upload + " Kbps" :
  5248. "N/A";
  5249. }
  5250. if(!this.transport || this.transport.length === 0)
  5251. {
  5252. transport = "<tr>" +
  5253. "<td><span class='jitsipopover_blue' " +
  5254. "data-i18n='connectionindicator.address'>" +
  5255. translate("connectionindicator.address") + "</span></td>" +
  5256. "<td> N/A</td></tr>";
  5257. }
  5258. else
  5259. {
  5260. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5261. for(i = 0; i < this.transport.length; i++)
  5262. {
  5263. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5264. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5265. var localIP =
  5266. ConnectionIndicator.getIP(this.transport[i].localip);
  5267. var localPort =
  5268. ConnectionIndicator.getPort(this.transport[i].localip);
  5269. if(data.remoteIP.indexOf(ip) == -1)
  5270. {
  5271. data.remoteIP.push(ip);
  5272. }
  5273. if(data.remotePort.indexOf(port) == -1)
  5274. {
  5275. data.remotePort.push(port);
  5276. }
  5277. if(data.localIP.indexOf(localIP) == -1)
  5278. {
  5279. data.localIP.push(localIP);
  5280. }
  5281. if(data.localPort.indexOf(localPort) == -1)
  5282. {
  5283. data.localPort.push(localPort);
  5284. }
  5285. }
  5286. var local_address_key = "connectionindicator.localaddress";
  5287. var remote_address_key = "connectionindicator.remoteaddress";
  5288. var localTransport =
  5289. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5290. local_address_key +"' data-i18n-options='" +
  5291. JSON.stringify({count: data.localIP.length}) + "'>" +
  5292. translate(local_address_key, {count: data.localIP.length}) +
  5293. "</span></td><td> " +
  5294. ConnectionIndicator.getStringFromArray(data.localIP) +
  5295. "</td></tr>";
  5296. transport =
  5297. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5298. remote_address_key + "' data-i18n-options='" +
  5299. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  5300. translate(remote_address_key,
  5301. {count: data.remoteIP.length}) +
  5302. "</span></td><td> " +
  5303. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5304. "</td></tr>";
  5305. var key_remote = "connectionindicator.remoteport",
  5306. key_local = "connectionindicator.localport";
  5307. transport += "<tr>" +
  5308. "<td>" +
  5309. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5310. "' data-i18n-options='" +
  5311. JSON.stringify({count: this.transport.length}) + "'>" +
  5312. translate(key_remote, {count: this.transport.length}) +
  5313. "</span></td><td>";
  5314. localTransport += "<tr>" +
  5315. "<td>" +
  5316. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5317. "' data-i18n-options='" +
  5318. JSON.stringify({count: this.transport.length}) + "'>" +
  5319. translate(key_local, {count: this.transport.length}) +
  5320. "</span></td><td>";
  5321. transport +=
  5322. ConnectionIndicator.getStringFromArray(data.remotePort);
  5323. localTransport +=
  5324. ConnectionIndicator.getStringFromArray(data.localPort);
  5325. transport += "</td></tr>";
  5326. transport += localTransport + "</td></tr>";
  5327. transport +="<tr>" +
  5328. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5329. translate("connectionindicator.transport") + "</span></td>" +
  5330. "<td>" + this.transport[0].type + "</td></tr>";
  5331. }
  5332. result += "<table style='width:100%'>" +
  5333. "<tr>" +
  5334. "<td>" +
  5335. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5336. translate("connectionindicator.bandwidth") + "</span>" +
  5337. "</td><td>" +
  5338. "<span class='jitsipopover_green'>&darr;</span>" +
  5339. downloadBandwidth +
  5340. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5341. uploadBandwidth + "</td></tr>";
  5342. result += transport + "</table>";
  5343. }
  5344. return result;
  5345. };
  5346. /**
  5347. * Shows or hide the additional information.
  5348. */
  5349. ConnectionIndicator.prototype.showMore = function () {
  5350. this.showMoreValue = !this.showMoreValue;
  5351. this.updatePopoverData();
  5352. };
  5353. function createIcon(classes)
  5354. {
  5355. var icon = document.createElement("span");
  5356. for(var i in classes)
  5357. {
  5358. icon.classList.add(classes[i]);
  5359. }
  5360. icon.appendChild(
  5361. document.createElement("i")).classList.add("icon-connection");
  5362. return icon;
  5363. }
  5364. /**
  5365. * Creates the indicator
  5366. */
  5367. ConnectionIndicator.prototype.create = function () {
  5368. this.connectionIndicatorContainer = document.createElement("div");
  5369. this.connectionIndicatorContainer.className = "connectionindicator";
  5370. this.connectionIndicatorContainer.style.display = "none";
  5371. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5372. this.popover = new JitsiPopover(
  5373. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5374. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5375. APP.translation.translateString("connectionindicator.na") + "</div>",
  5376. skin: "black"});
  5377. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5378. createIcon(["connection", "connection_empty"]));
  5379. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5380. createIcon(["connection", "connection_full"]));
  5381. };
  5382. /**
  5383. * Removes the indicator
  5384. */
  5385. ConnectionIndicator.prototype.remove = function()
  5386. {
  5387. this.connectionIndicatorContainer.remove();
  5388. this.popover.forceHide();
  5389. };
  5390. /**
  5391. * Updates the data of the indicator
  5392. * @param percent the percent of connection quality
  5393. * @param object the statistics data.
  5394. */
  5395. ConnectionIndicator.prototype.updateConnectionQuality =
  5396. function (percent, object) {
  5397. if(percent === null)
  5398. {
  5399. this.connectionIndicatorContainer.style.display = "none";
  5400. this.popover.forceHide();
  5401. return;
  5402. }
  5403. else
  5404. {
  5405. if(this.connectionIndicatorContainer.style.display == "none") {
  5406. this.connectionIndicatorContainer.style.display = "block";
  5407. this.videoLayout.updateMutePosition(this.videoContainer.id);
  5408. }
  5409. }
  5410. this.bandwidth = object.bandwidth;
  5411. this.bitrate = object.bitrate;
  5412. this.packetLoss = object.packetLoss;
  5413. this.transport = object.transport;
  5414. if(object.resolution)
  5415. {
  5416. this.resolution = object.resolution;
  5417. }
  5418. for(var quality in ConnectionIndicator.connectionQualityValues)
  5419. {
  5420. if(percent >= quality)
  5421. {
  5422. this.fullIcon.style.width =
  5423. ConnectionIndicator.connectionQualityValues[quality];
  5424. }
  5425. }
  5426. this.updatePopoverData();
  5427. };
  5428. /**
  5429. * Updates the resolution
  5430. * @param resolution the new resolution
  5431. */
  5432. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  5433. this.resolution = resolution;
  5434. this.updatePopoverData();
  5435. };
  5436. /**
  5437. * Updates the content of the popover
  5438. */
  5439. ConnectionIndicator.prototype.updatePopoverData = function () {
  5440. this.popover.updateContent(
  5441. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  5442. APP.translation.translateElement($(".connection_info"));
  5443. };
  5444. /**
  5445. * Hides the popover
  5446. */
  5447. ConnectionIndicator.prototype.hide = function () {
  5448. this.popover.forceHide();
  5449. };
  5450. /**
  5451. * Hides the indicator
  5452. */
  5453. ConnectionIndicator.prototype.hideIndicator = function () {
  5454. this.connectionIndicatorContainer.style.display = "none";
  5455. if(this.popover)
  5456. this.popover.forceHide();
  5457. };
  5458. module.exports = ConnectionIndicator;
  5459. },{"../util/JitsiPopover":26}],31:[function(require,module,exports){
  5460. var AudioLevels = require("../audio_levels/AudioLevels");
  5461. var Avatar = require("../avatar/Avatar");
  5462. var Chat = require("../side_pannels/chat/Chat");
  5463. var ContactList = require("../side_pannels/contactlist/ContactList");
  5464. var UIUtil = require("../util/UIUtil");
  5465. var ConnectionIndicator = require("./ConnectionIndicator");
  5466. var NicknameHandler = require("../util/NicknameHandler");
  5467. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  5468. var UIEvents = require("../../../service/UI/UIEvents");
  5469. var currentDominantSpeaker = null;
  5470. var lastNCount = config.channelLastN;
  5471. var localLastNCount = config.channelLastN;
  5472. var localLastNSet = [];
  5473. var lastNEndpointsCache = [];
  5474. var lastNPickupJid = null;
  5475. var largeVideoState = {
  5476. updateInProgress: false,
  5477. newSrc: ''
  5478. };
  5479. var eventEmitter = null;
  5480. /**
  5481. * Currently focused video "src"(displayed in large video).
  5482. * @type {String}
  5483. */
  5484. var focusedVideoInfo = null;
  5485. /**
  5486. * Indicates if we have muted our audio before the conference has started.
  5487. * @type {boolean}
  5488. */
  5489. var preMuted = false;
  5490. var mutedAudios = {};
  5491. var flipXLocalVideo = true;
  5492. var currentVideoWidth = null;
  5493. var currentVideoHeight = null;
  5494. var localVideoSrc = null;
  5495. function videoactive( videoelem) {
  5496. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  5497. // ignore mixedmslabela0 and v0
  5498. videoelem.show();
  5499. VideoLayout.resizeThumbnails();
  5500. var videoParent = videoelem.parent();
  5501. var parentResourceJid = null;
  5502. if (videoParent)
  5503. parentResourceJid
  5504. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  5505. // Update the large video to the last added video only if there's no
  5506. // current dominant, focused speaker or prezi playing or update it to
  5507. // the current dominant speaker.
  5508. if ((!focusedVideoInfo &&
  5509. !VideoLayout.getDominantSpeakerResourceJid() &&
  5510. !require("../prezi/Prezi").isPresentationVisible()) ||
  5511. (parentResourceJid &&
  5512. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  5513. VideoLayout.updateLargeVideo(
  5514. APP.RTC.getVideoSrc(videoelem[0]),
  5515. 1,
  5516. parentResourceJid);
  5517. }
  5518. VideoLayout.showModeratorIndicator();
  5519. }
  5520. }
  5521. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  5522. // XXX(gp) so, every call to this function is *always* preceded by a call
  5523. // to the RTC.attachMediaStream() function but that call is *not* followed
  5524. // by an update to the videoSrcToSsrc map!
  5525. //
  5526. // The above way of doing things results in video SRCs that don't correspond
  5527. // to any SSRC for a short period of time (to be more precise, for as long
  5528. // the waitForRemoteVideo takes to complete). This causes problems (see
  5529. // bellow).
  5530. //
  5531. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  5532. // a second time in here and only then update the videoSrcToSsrc map? Why
  5533. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  5534. // is called the first time? I actually do that in the lastN changed event
  5535. // handler because the "orphan" video SRC is causing troubles there. The
  5536. // purpose of this method would then be to fire the "videoactive.jingle".
  5537. //
  5538. // Food for though I guess :-)
  5539. if (selector.removed || !selector.parent().is(":visible")) {
  5540. console.warn("Media removed before had started", selector);
  5541. return;
  5542. }
  5543. if (stream.id === 'mixedmslabel') return;
  5544. if (selector[0].currentTime > 0) {
  5545. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  5546. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  5547. videoactive(selector);
  5548. } else {
  5549. setTimeout(function () {
  5550. waitForRemoteVideo(selector, ssrc, stream, jid);
  5551. }, 250);
  5552. }
  5553. }
  5554. /**
  5555. * Returns an array of the video horizontal and vertical indents,
  5556. * so that if fits its parent.
  5557. *
  5558. * @return an array with 2 elements, the horizontal indent and the vertical
  5559. * indent
  5560. */
  5561. function getCameraVideoPosition(videoWidth,
  5562. videoHeight,
  5563. videoSpaceWidth,
  5564. videoSpaceHeight) {
  5565. // Parent height isn't completely calculated when we position the video in
  5566. // full screen mode and this is why we use the screen height in this case.
  5567. // Need to think it further at some point and implement it properly.
  5568. var isFullScreen = document.fullScreen ||
  5569. document.mozFullScreen ||
  5570. document.webkitIsFullScreen;
  5571. if (isFullScreen)
  5572. videoSpaceHeight = window.innerHeight;
  5573. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5574. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  5575. return [horizontalIndent, verticalIndent];
  5576. }
  5577. /**
  5578. * Returns an array of the video horizontal and vertical indents.
  5579. * Centers horizontally and top aligns vertically.
  5580. *
  5581. * @return an array with 2 elements, the horizontal indent and the vertical
  5582. * indent
  5583. */
  5584. function getDesktopVideoPosition(videoWidth,
  5585. videoHeight,
  5586. videoSpaceWidth,
  5587. videoSpaceHeight) {
  5588. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5589. var verticalIndent = 0;// Top aligned
  5590. return [horizontalIndent, verticalIndent];
  5591. }
  5592. /**
  5593. * Returns an array of the video dimensions, so that it covers the screen.
  5594. * It leaves no empty areas, but some parts of the video might not be visible.
  5595. *
  5596. * @return an array with 2 elements, the video width and the video height
  5597. */
  5598. function getCameraVideoSize(videoWidth,
  5599. videoHeight,
  5600. videoSpaceWidth,
  5601. videoSpaceHeight) {
  5602. if (!videoWidth)
  5603. videoWidth = currentVideoWidth;
  5604. if (!videoHeight)
  5605. videoHeight = currentVideoHeight;
  5606. var aspectRatio = videoWidth / videoHeight;
  5607. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5608. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5609. if (availableWidth / aspectRatio < videoSpaceHeight) {
  5610. availableHeight = videoSpaceHeight;
  5611. availableWidth = availableHeight * aspectRatio;
  5612. }
  5613. if (availableHeight * aspectRatio < videoSpaceWidth) {
  5614. availableWidth = videoSpaceWidth;
  5615. availableHeight = availableWidth / aspectRatio;
  5616. }
  5617. return [availableWidth, availableHeight];
  5618. }
  5619. /**
  5620. * Sets the display name for the given video span id.
  5621. */
  5622. function setDisplayName(videoSpanId, displayName) {
  5623. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  5624. var defaultLocalDisplayName = interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME;
  5625. // If we already have a display name for this video.
  5626. if (nameSpan.length > 0) {
  5627. var nameSpanElement = nameSpan.get(0);
  5628. if (nameSpanElement.id === 'localDisplayName' &&
  5629. $('#localDisplayName').text() !== displayName) {
  5630. if (displayName && displayName.length > 0)
  5631. $('#localDisplayName').html(displayName + ' (me)');
  5632. else
  5633. $('#localDisplayName').text(defaultLocalDisplayName);
  5634. } else {
  5635. if (displayName && displayName.length > 0)
  5636. $('#' + videoSpanId + '_name').html(displayName);
  5637. else
  5638. $('#' + videoSpanId + '_name').text(interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  5639. }
  5640. } else {
  5641. var editButton = null;
  5642. nameSpan = document.createElement('span');
  5643. nameSpan.className = 'displayname';
  5644. $('#' + videoSpanId)[0].appendChild(nameSpan);
  5645. if (videoSpanId === 'localVideoContainer') {
  5646. editButton = createEditDisplayNameButton();
  5647. nameSpan.innerText = defaultLocalDisplayName;
  5648. }
  5649. else {
  5650. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  5651. }
  5652. if (displayName && displayName.length > 0) {
  5653. nameSpan.innerText = displayName;
  5654. }
  5655. if (!editButton) {
  5656. nameSpan.id = videoSpanId + '_name';
  5657. } else {
  5658. nameSpan.id = 'localDisplayName';
  5659. $('#' + videoSpanId)[0].appendChild(editButton);
  5660. //translates popover of edit button
  5661. APP.translation.translateElement($("a.displayname"));
  5662. var editableText = document.createElement('input');
  5663. editableText.className = 'displayname';
  5664. editableText.type = 'text';
  5665. editableText.id = 'editDisplayName';
  5666. if (displayName && displayName.length) {
  5667. editableText.value
  5668. = displayName.substring(0, displayName.indexOf(' (me)'));
  5669. }
  5670. editableText.setAttribute('style', 'display:none;');
  5671. editableText.setAttribute('placeholder', 'ex. Jane Pink');
  5672. $('#' + videoSpanId)[0].appendChild(editableText);
  5673. $('#localVideoContainer .displayname')
  5674. .bind("click", function (e) {
  5675. e.preventDefault();
  5676. e.stopPropagation();
  5677. $('#localDisplayName').hide();
  5678. $('#editDisplayName').show();
  5679. $('#editDisplayName').focus();
  5680. $('#editDisplayName').select();
  5681. $('#editDisplayName').one("focusout", function (e) {
  5682. VideoLayout.inputDisplayNameHandler(this.value);
  5683. });
  5684. $('#editDisplayName').on('keydown', function (e) {
  5685. if (e.keyCode === 13) {
  5686. e.preventDefault();
  5687. VideoLayout.inputDisplayNameHandler(this.value);
  5688. }
  5689. });
  5690. });
  5691. }
  5692. }
  5693. }
  5694. /**
  5695. * Gets the selector of video thumbnail container for the user identified by
  5696. * given <tt>userJid</tt>
  5697. * @param resourceJid user's Jid for whom we want to get the video container.
  5698. */
  5699. function getParticipantContainer(resourceJid)
  5700. {
  5701. if (!resourceJid)
  5702. return null;
  5703. if (resourceJid === APP.xmpp.myResource())
  5704. return $("#localVideoContainer");
  5705. else
  5706. return $("#participant_" + resourceJid);
  5707. }
  5708. /**
  5709. * Sets the size and position of the given video element.
  5710. *
  5711. * @param video the video element to position
  5712. * @param width the desired video width
  5713. * @param height the desired video height
  5714. * @param horizontalIndent the left and right indent
  5715. * @param verticalIndent the top and bottom indent
  5716. */
  5717. function positionVideo(video,
  5718. width,
  5719. height,
  5720. horizontalIndent,
  5721. verticalIndent) {
  5722. video.width(width);
  5723. video.height(height);
  5724. video.css({ top: verticalIndent + 'px',
  5725. bottom: verticalIndent + 'px',
  5726. left: horizontalIndent + 'px',
  5727. right: horizontalIndent + 'px'});
  5728. }
  5729. /**
  5730. * Adds the remote video menu element for the given <tt>jid</tt> in the
  5731. * given <tt>parentElement</tt>.
  5732. *
  5733. * @param jid the jid indicating the video for which we're adding a menu.
  5734. * @param parentElement the parent element where this menu will be added
  5735. */
  5736. function addRemoteVideoMenu(jid, parentElement) {
  5737. var spanElement = document.createElement('span');
  5738. spanElement.className = 'remotevideomenu';
  5739. parentElement.appendChild(spanElement);
  5740. var menuElement = document.createElement('i');
  5741. menuElement.className = 'fa fa-angle-down';
  5742. menuElement.title = 'Remote user controls';
  5743. spanElement.appendChild(menuElement);
  5744. // <ul class="popupmenu">
  5745. // <li><a href="#">Mute</a></li>
  5746. // <li><a href="#">Eject</a></li>
  5747. // </ul>
  5748. var popupmenuElement = document.createElement('ul');
  5749. popupmenuElement.className = 'popupmenu';
  5750. popupmenuElement.id
  5751. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  5752. spanElement.appendChild(popupmenuElement);
  5753. var muteMenuItem = document.createElement('li');
  5754. var muteLinkItem = document.createElement('a');
  5755. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  5756. if (!mutedAudios[jid]) {
  5757. muteLinkItem.innerHTML = mutedIndicator +
  5758. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  5759. muteLinkItem.className = 'mutelink';
  5760. }
  5761. else {
  5762. muteLinkItem.innerHTML = mutedIndicator +
  5763. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  5764. muteLinkItem.className = 'mutelink disabled';
  5765. }
  5766. muteLinkItem.onclick = function(){
  5767. if ($(this).attr('disabled') != undefined) {
  5768. event.preventDefault();
  5769. }
  5770. var isMute = mutedAudios[jid] == true;
  5771. APP.xmpp.setMute(jid, !isMute);
  5772. popupmenuElement.setAttribute('style', 'display:none;');
  5773. if (isMute) {
  5774. this.innerHTML = mutedIndicator +
  5775. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  5776. this.className = 'mutelink disabled';
  5777. }
  5778. else {
  5779. this.innerHTML = mutedIndicator +
  5780. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  5781. this.className = 'mutelink';
  5782. }
  5783. };
  5784. muteMenuItem.appendChild(muteLinkItem);
  5785. popupmenuElement.appendChild(muteMenuItem);
  5786. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  5787. var ejectMenuItem = document.createElement('li');
  5788. var ejectLinkItem = document.createElement('a');
  5789. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  5790. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  5791. ejectLinkItem.onclick = function(){
  5792. APP.xmpp.eject(jid);
  5793. popupmenuElement.setAttribute('style', 'display:none;');
  5794. };
  5795. ejectMenuItem.appendChild(ejectLinkItem);
  5796. popupmenuElement.appendChild(ejectMenuItem);
  5797. var paddingSpan = document.createElement('span');
  5798. paddingSpan.className = 'popupmenuPadding';
  5799. popupmenuElement.appendChild(paddingSpan);
  5800. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  5801. }
  5802. /**
  5803. * Removes remote video menu element from video element identified by
  5804. * given <tt>videoElementId</tt>.
  5805. *
  5806. * @param videoElementId the id of local or remote video element.
  5807. */
  5808. function removeRemoteVideoMenu(videoElementId) {
  5809. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  5810. if (menuSpan.length) {
  5811. menuSpan.remove();
  5812. }
  5813. }
  5814. /**
  5815. * Updates the data for the indicator
  5816. * @param id the id of the indicator
  5817. * @param percent the percent for connection quality
  5818. * @param object the data
  5819. */
  5820. function updateStatsIndicator(id, percent, object) {
  5821. if(VideoLayout.connectionIndicators[id])
  5822. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  5823. }
  5824. /**
  5825. * Returns an array of the video dimensions, so that it keeps it's aspect
  5826. * ratio and fits available area with it's larger dimension. This method
  5827. * ensures that whole video will be visible and can leave empty areas.
  5828. *
  5829. * @return an array with 2 elements, the video width and the video height
  5830. */
  5831. function getDesktopVideoSize(videoWidth,
  5832. videoHeight,
  5833. videoSpaceWidth,
  5834. videoSpaceHeight) {
  5835. if (!videoWidth)
  5836. videoWidth = currentVideoWidth;
  5837. if (!videoHeight)
  5838. videoHeight = currentVideoHeight;
  5839. var aspectRatio = videoWidth / videoHeight;
  5840. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5841. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5842. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  5843. if (availableWidth / aspectRatio >= videoSpaceHeight)
  5844. {
  5845. availableHeight = videoSpaceHeight;
  5846. availableWidth = availableHeight * aspectRatio;
  5847. }
  5848. if (availableHeight * aspectRatio >= videoSpaceWidth)
  5849. {
  5850. availableWidth = videoSpaceWidth;
  5851. availableHeight = availableWidth / aspectRatio;
  5852. }
  5853. return [availableWidth, availableHeight];
  5854. }
  5855. /**
  5856. * Creates the edit display name button.
  5857. *
  5858. * @returns the edit button
  5859. */
  5860. function createEditDisplayNameButton() {
  5861. var editButton = document.createElement('a');
  5862. editButton.className = 'displayname';
  5863. UIUtil.setTooltip(editButton,
  5864. "videothumbnail.editnickname",
  5865. "top");
  5866. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  5867. return editButton;
  5868. }
  5869. /**
  5870. * Creates the element indicating the moderator(owner) of the conference.
  5871. *
  5872. * @param parentElement the parent element where the owner indicator will
  5873. * be added
  5874. */
  5875. function createModeratorIndicatorElement(parentElement) {
  5876. var moderatorIndicator = document.createElement('i');
  5877. moderatorIndicator.className = 'fa fa-star';
  5878. parentElement.appendChild(moderatorIndicator);
  5879. UIUtil.setTooltip(parentElement,
  5880. "videothumbnail.moderator",
  5881. "top");
  5882. }
  5883. var VideoLayout = (function (my) {
  5884. my.connectionIndicators = {};
  5885. // By default we use camera
  5886. my.getVideoSize = getCameraVideoSize;
  5887. my.getVideoPosition = getCameraVideoPosition;
  5888. my.init = function (emitter) {
  5889. // Listen for large video size updates
  5890. document.getElementById('largeVideo')
  5891. .addEventListener('loadedmetadata', function (e) {
  5892. currentVideoWidth = this.videoWidth;
  5893. currentVideoHeight = this.videoHeight;
  5894. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  5895. });
  5896. eventEmitter = emitter;
  5897. };
  5898. my.isInLastN = function(resource) {
  5899. return lastNCount < 0 // lastN is disabled, return true
  5900. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  5901. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  5902. };
  5903. my.changeLocalStream = function (stream) {
  5904. VideoLayout.changeLocalVideo(stream);
  5905. };
  5906. my.changeLocalAudio = function(stream) {
  5907. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  5908. document.getElementById('localAudio').autoplay = true;
  5909. document.getElementById('localAudio').volume = 0;
  5910. if (preMuted) {
  5911. if(!APP.UI.setAudioMuted(true))
  5912. {
  5913. preMuted = mute;
  5914. }
  5915. preMuted = false;
  5916. }
  5917. };
  5918. my.changeLocalVideo = function(stream) {
  5919. var flipX = true;
  5920. if(stream.videoType == "screen")
  5921. flipX = false;
  5922. var localVideo = document.createElement('video');
  5923. localVideo.id = 'localVideo_' +
  5924. APP.RTC.getStreamID(stream.getOriginalStream());
  5925. localVideo.autoplay = true;
  5926. localVideo.volume = 0; // is it required if audio is separated ?
  5927. localVideo.oncontextmenu = function () { return false; };
  5928. var localVideoContainer = document.getElementById('localVideoWrapper');
  5929. localVideoContainer.appendChild(localVideo);
  5930. // Set default display name.
  5931. setDisplayName('localVideoContainer');
  5932. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  5933. VideoLayout.connectionIndicators["localVideoContainer"]
  5934. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  5935. }
  5936. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  5937. var localVideoSelector = $('#' + localVideo.id);
  5938. function localVideoClick(event) {
  5939. event.stopPropagation();
  5940. VideoLayout.handleVideoThumbClicked(
  5941. APP.RTC.getVideoSrc(localVideo),
  5942. false,
  5943. APP.xmpp.myResource());
  5944. }
  5945. // Add click handler to both video and video wrapper elements in case
  5946. // there's no video.
  5947. localVideoSelector.click(localVideoClick);
  5948. $('#localVideoContainer').click(localVideoClick);
  5949. // Add hover handler
  5950. $('#localVideoContainer').hover(
  5951. function() {
  5952. VideoLayout.showDisplayName('localVideoContainer', true);
  5953. },
  5954. function() {
  5955. if (!VideoLayout.isLargeVideoVisible()
  5956. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  5957. VideoLayout.showDisplayName('localVideoContainer', false);
  5958. }
  5959. );
  5960. // Add stream ended handler
  5961. stream.getOriginalStream().onended = function () {
  5962. localVideoContainer.removeChild(localVideo);
  5963. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  5964. };
  5965. // Flip video x axis if needed
  5966. flipXLocalVideo = flipX;
  5967. if (flipX) {
  5968. localVideoSelector.addClass("flipVideoX");
  5969. }
  5970. // Attach WebRTC stream
  5971. var videoStream = APP.simulcast.getLocalVideoStream();
  5972. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  5973. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  5974. var myResourceJid = APP.xmpp.myResource();
  5975. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  5976. myResourceJid);
  5977. };
  5978. /**
  5979. * Checks if removed video is currently displayed and tries to display
  5980. * another one instead.
  5981. * @param removedVideoSrc src stream identifier of the video.
  5982. */
  5983. my.updateRemovedVideo = function(removedVideoSrc) {
  5984. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  5985. // this is currently displayed as large
  5986. // pick the last visible video in the row
  5987. // if nobody else is left, this picks the local video
  5988. var pick
  5989. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  5990. .get(0);
  5991. if (!pick) {
  5992. console.info("Last visible video no longer exists");
  5993. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  5994. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  5995. // Try local video
  5996. console.info("Fallback to local video...");
  5997. pick = $('#remoteVideos>span>span>video').get(0);
  5998. }
  5999. }
  6000. // mute if localvideo
  6001. if (pick) {
  6002. var container = pick.parentNode;
  6003. var jid = null;
  6004. if(container)
  6005. {
  6006. if(container.id == "localVideoWrapper")
  6007. {
  6008. jid = APP.xmpp.myResource();
  6009. }
  6010. else
  6011. {
  6012. jid = VideoLayout.getPeerContainerResourceJid(container);
  6013. }
  6014. }
  6015. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(pick), pick.volume, jid);
  6016. } else {
  6017. console.warn("Failed to elect large video");
  6018. }
  6019. }
  6020. };
  6021. my.onRemoteStreamAdded = function (stream) {
  6022. var container;
  6023. var remotes = document.getElementById('remoteVideos');
  6024. if (stream.peerjid) {
  6025. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6026. container = document.getElementById(
  6027. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6028. } else {
  6029. var id = stream.getOriginalStream().id;
  6030. if (id !== 'mixedmslabel'
  6031. // FIXME: default stream is added always with new focus
  6032. // (to be investigated)
  6033. && id !== 'default') {
  6034. console.error('can not associate stream',
  6035. id,
  6036. 'with a participant');
  6037. // We don't want to add it here since it will cause troubles
  6038. return;
  6039. }
  6040. // FIXME: for the mixed ms we dont need a video -- currently
  6041. container = document.createElement('span');
  6042. container.id = 'mixedstream';
  6043. container.className = 'videocontainer';
  6044. remotes.appendChild(container);
  6045. UIUtil.playSoundNotification('userJoined');
  6046. }
  6047. if (container) {
  6048. VideoLayout.addRemoteStreamElement( container,
  6049. stream.sid,
  6050. stream.getOriginalStream(),
  6051. stream.peerjid,
  6052. stream.ssrc);
  6053. }
  6054. }
  6055. my.getLargeVideoState = function () {
  6056. return largeVideoState;
  6057. };
  6058. /**
  6059. * Updates the large video with the given new video source.
  6060. */
  6061. my.updateLargeVideo = function(newSrc, vol, resourceJid) {
  6062. console.log('hover in', newSrc);
  6063. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc) {
  6064. $('#activeSpeaker').css('visibility', 'hidden');
  6065. // Due to the simulcast the localVideoSrc may have changed when the
  6066. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6067. // isVideoSrcDesktop methods will not function correctly.
  6068. //
  6069. // Also, again due to the simulcast, the updateLargeVideo method can
  6070. // be called multiple times almost simultaneously. Therefore, we
  6071. // store the state here and update only once.
  6072. largeVideoState.newSrc = newSrc;
  6073. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6074. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(resourceJid);
  6075. if(largeVideoState.userResourceJid) {
  6076. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6077. } else {
  6078. largeVideoState.oldResourceJid = null;
  6079. }
  6080. largeVideoState.userResourceJid = resourceJid;
  6081. // Screen stream is already rotated
  6082. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6083. var userChanged = false;
  6084. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6085. userChanged = true;
  6086. // we want the notification to trigger even if userJid is undefined,
  6087. // or null.
  6088. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6089. largeVideoState.userResourceJid);
  6090. }
  6091. if (!largeVideoState.updateInProgress) {
  6092. largeVideoState.updateInProgress = true;
  6093. var doUpdate = function () {
  6094. Avatar.updateActiveSpeakerAvatarSrc(
  6095. APP.xmpp.findJidFromResource(
  6096. largeVideoState.userResourceJid));
  6097. if (!userChanged && largeVideoState.preload &&
  6098. largeVideoState.preload !== null &&
  6099. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  6100. {
  6101. console.info('Switching to preloaded video');
  6102. var attributes = $('#largeVideo').prop("attributes");
  6103. // loop through largeVideo attributes and apply them on
  6104. // preload.
  6105. $.each(attributes, function () {
  6106. if (this.name !== 'id' && this.name !== 'src') {
  6107. largeVideoState.preload.attr(this.name, this.value);
  6108. }
  6109. });
  6110. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  6111. $('#largeVideo').attr('id', 'previousLargeVideo');
  6112. largeVideoState.preload.attr('id', 'largeVideo');
  6113. $('#previousLargeVideo').remove();
  6114. largeVideoState.preload.on('loadedmetadata', function (e) {
  6115. currentVideoWidth = this.videoWidth;
  6116. currentVideoHeight = this.videoHeight;
  6117. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6118. });
  6119. largeVideoState.preload = null;
  6120. largeVideoState.preload_ssrc = 0;
  6121. } else {
  6122. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6123. }
  6124. var videoTransform = document.getElementById('largeVideo')
  6125. .style.webkitTransform;
  6126. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6127. document.getElementById('largeVideo').style.webkitTransform
  6128. = "scaleX(-1)";
  6129. }
  6130. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6131. document.getElementById('largeVideo').style.webkitTransform
  6132. = "none";
  6133. }
  6134. // Change the way we'll be measuring and positioning large video
  6135. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6136. ? getDesktopVideoSize
  6137. : getCameraVideoSize;
  6138. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6139. ? getDesktopVideoPosition
  6140. : getCameraVideoPosition;
  6141. // Only if the large video is currently visible.
  6142. // Disable previous dominant speaker video.
  6143. if (largeVideoState.oldResourceJid) {
  6144. VideoLayout.enableDominantSpeaker(
  6145. largeVideoState.oldResourceJid,
  6146. false);
  6147. }
  6148. // Enable new dominant speaker in the remote videos section.
  6149. if (largeVideoState.userResourceJid) {
  6150. VideoLayout.enableDominantSpeaker(
  6151. largeVideoState.userResourceJid,
  6152. true);
  6153. }
  6154. if (userChanged && largeVideoState.isVisible) {
  6155. // using "this" should be ok because we're called
  6156. // from within the fadeOut event.
  6157. $(this).fadeIn(300);
  6158. }
  6159. if(userChanged) {
  6160. Avatar.showUserAvatar(
  6161. APP.xmpp.findJidFromResource(
  6162. largeVideoState.oldResourceJid));
  6163. }
  6164. largeVideoState.updateInProgress = false;
  6165. };
  6166. if (userChanged) {
  6167. $('#largeVideo').fadeOut(300, doUpdate);
  6168. } else {
  6169. doUpdate();
  6170. }
  6171. }
  6172. } else {
  6173. Avatar.showUserAvatar(
  6174. APP.xmpp.findJidFromResource(
  6175. largeVideoState.userResourceJid));
  6176. }
  6177. };
  6178. my.handleVideoThumbClicked = function(videoSrc,
  6179. noPinnedEndpointChangedEvent,
  6180. resourceJid) {
  6181. // Restore style for previously focused video
  6182. var oldContainer = null;
  6183. if(focusedVideoInfo) {
  6184. var focusResourceJid = focusedVideoInfo.resourceJid;
  6185. oldContainer = getParticipantContainer(focusResourceJid);
  6186. }
  6187. if (oldContainer) {
  6188. oldContainer.removeClass("videoContainerFocused");
  6189. }
  6190. // Unlock current focused.
  6191. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6192. {
  6193. focusedVideoInfo = null;
  6194. var dominantSpeakerVideo = null;
  6195. // Enable the currently set dominant speaker.
  6196. if (currentDominantSpeaker) {
  6197. dominantSpeakerVideo
  6198. = $('#participant_' + currentDominantSpeaker + '>video')
  6199. .get(0);
  6200. if (dominantSpeakerVideo) {
  6201. VideoLayout.updateLargeVideo(
  6202. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6203. 1,
  6204. currentDominantSpeaker);
  6205. }
  6206. }
  6207. if (!noPinnedEndpointChangedEvent) {
  6208. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6209. }
  6210. return;
  6211. }
  6212. // Lock new video
  6213. focusedVideoInfo = {
  6214. src: videoSrc,
  6215. resourceJid: resourceJid
  6216. };
  6217. // Update focused/pinned interface.
  6218. if (resourceJid)
  6219. {
  6220. var container = getParticipantContainer(resourceJid);
  6221. container.addClass("videoContainerFocused");
  6222. if (!noPinnedEndpointChangedEvent) {
  6223. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6224. }
  6225. }
  6226. if ($('#largeVideo').attr('src') === videoSrc &&
  6227. VideoLayout.isLargeVideoOnTop()) {
  6228. return;
  6229. }
  6230. // Triggers a "video.selected" event. The "false" parameter indicates
  6231. // this isn't a prezi.
  6232. $(document).trigger("video.selected", [false]);
  6233. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6234. $('audio').each(function (idx, el) {
  6235. if (el.id.indexOf('mixedmslabel') !== -1) {
  6236. el.volume = 0;
  6237. el.volume = 1;
  6238. }
  6239. });
  6240. };
  6241. /**
  6242. * Positions the large video.
  6243. *
  6244. * @param videoWidth the stream video width
  6245. * @param videoHeight the stream video height
  6246. */
  6247. my.positionLarge = function (videoWidth, videoHeight) {
  6248. var videoSpaceWidth = $('#videospace').width();
  6249. var videoSpaceHeight = window.innerHeight;
  6250. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6251. videoHeight,
  6252. videoSpaceWidth,
  6253. videoSpaceHeight);
  6254. var largeVideoWidth = videoSize[0];
  6255. var largeVideoHeight = videoSize[1];
  6256. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6257. largeVideoHeight,
  6258. videoSpaceWidth,
  6259. videoSpaceHeight);
  6260. var horizontalIndent = videoPosition[0];
  6261. var verticalIndent = videoPosition[1];
  6262. positionVideo($('#largeVideo'),
  6263. largeVideoWidth,
  6264. largeVideoHeight,
  6265. horizontalIndent, verticalIndent);
  6266. };
  6267. /**
  6268. * Shows/hides the large video.
  6269. */
  6270. my.setLargeVideoVisible = function(isVisible) {
  6271. var resourceJid = largeVideoState.userResourceJid;
  6272. if (isVisible) {
  6273. $('#largeVideo').css({visibility: 'visible'});
  6274. $('.watermark').css({visibility: 'visible'});
  6275. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6276. }
  6277. else {
  6278. $('#largeVideo').css({visibility: 'hidden'});
  6279. $('#activeSpeaker').css('visibility', 'hidden');
  6280. $('.watermark').css({visibility: 'hidden'});
  6281. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6282. if(focusedVideoInfo) {
  6283. var focusResourceJid = focusedVideoInfo.resourceJid;
  6284. var oldContainer = getParticipantContainer(focusResourceJid);
  6285. if (oldContainer && oldContainer.length > 0) {
  6286. oldContainer.removeClass("videoContainerFocused");
  6287. }
  6288. focusedVideoInfo = null;
  6289. if(focusResourceJid) {
  6290. Avatar.showUserAvatar(
  6291. APP.xmpp.findJidFromResource(focusResourceJid));
  6292. }
  6293. }
  6294. }
  6295. };
  6296. /**
  6297. * Indicates if the large video is currently visible.
  6298. *
  6299. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6300. */
  6301. my.isLargeVideoVisible = function() {
  6302. return $('#largeVideo').is(':visible');
  6303. };
  6304. my.isLargeVideoOnTop = function () {
  6305. var Etherpad = require("../etherpad/Etherpad");
  6306. var Prezi = require("../prezi/Prezi");
  6307. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6308. };
  6309. /**
  6310. * Checks if container for participant identified by given peerJid exists
  6311. * in the document and creates it eventually.
  6312. *
  6313. * @param peerJid peer Jid to check.
  6314. * @param userId user email or id for setting the avatar
  6315. *
  6316. * @return Returns <tt>true</tt> if the peer container exists,
  6317. * <tt>false</tt> - otherwise
  6318. */
  6319. my.ensurePeerContainerExists = function(peerJid, userId) {
  6320. ContactList.ensureAddContact(peerJid, userId);
  6321. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6322. var videoSpanId = 'participant_' + resourceJid;
  6323. if (!$('#' + videoSpanId).length) {
  6324. var container =
  6325. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6326. Avatar.setUserAvatar(peerJid, userId);
  6327. // Set default display name.
  6328. setDisplayName(videoSpanId);
  6329. VideoLayout.connectionIndicators[videoSpanId] =
  6330. new ConnectionIndicator(container, peerJid, VideoLayout);
  6331. var nickfield = document.createElement('span');
  6332. nickfield.className = "nick";
  6333. nickfield.appendChild(document.createTextNode(resourceJid));
  6334. container.appendChild(nickfield);
  6335. // In case this is not currently in the last n we don't show it.
  6336. if (localLastNCount
  6337. && localLastNCount > 0
  6338. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  6339. showPeerContainer(resourceJid, 'hide');
  6340. }
  6341. else
  6342. VideoLayout.resizeThumbnails();
  6343. }
  6344. };
  6345. my.addRemoteVideoContainer = function(peerJid, spanId) {
  6346. var container = document.createElement('span');
  6347. container.id = spanId;
  6348. container.className = 'videocontainer';
  6349. var remotes = document.getElementById('remoteVideos');
  6350. remotes.appendChild(container);
  6351. // If the peerJid is null then this video span couldn't be directly
  6352. // associated with a participant (this could happen in the case of prezi).
  6353. if (APP.xmpp.isModerator() && peerJid !== null)
  6354. addRemoteVideoMenu(peerJid, container);
  6355. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  6356. return container;
  6357. };
  6358. /**
  6359. * Creates an audio or video stream element.
  6360. */
  6361. my.createStreamElement = function (sid, stream) {
  6362. var isVideo = stream.getVideoTracks().length > 0;
  6363. var element = isVideo
  6364. ? document.createElement('video')
  6365. : document.createElement('audio');
  6366. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  6367. + sid + '_' + APP.RTC.getStreamID(stream);
  6368. element.id = id;
  6369. element.autoplay = true;
  6370. element.oncontextmenu = function () { return false; };
  6371. return element;
  6372. };
  6373. my.addRemoteStreamElement
  6374. = function (container, sid, stream, peerJid, thessrc) {
  6375. var newElementId = null;
  6376. var isVideo = stream.getVideoTracks().length > 0;
  6377. if (container) {
  6378. var streamElement = VideoLayout.createStreamElement(sid, stream);
  6379. newElementId = streamElement.id;
  6380. container.appendChild(streamElement);
  6381. var sel = $('#' + newElementId);
  6382. sel.hide();
  6383. // If the container is currently visible we attach the stream.
  6384. if (!isVideo
  6385. || (container.offsetParent !== null && isVideo)) {
  6386. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6387. APP.RTC.attachMediaStream(sel, videoStream);
  6388. if (isVideo)
  6389. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  6390. }
  6391. stream.onended = function () {
  6392. console.log('stream ended', this);
  6393. VideoLayout.removeRemoteStreamElement(
  6394. stream, isVideo, container);
  6395. // NOTE(gp) it seems that under certain circumstances, the
  6396. // onended event is not fired and thus the contact list is not
  6397. // updated.
  6398. //
  6399. // The onended event of a stream should be fired when the SSRCs
  6400. // corresponding to that stream are removed from the SDP; but
  6401. // this doesn't seem to always be the case, resulting in ghost
  6402. // contacts.
  6403. //
  6404. // In an attempt to fix the ghost contacts problem, I'm moving
  6405. // the removeContact() method call in app.js, inside the
  6406. // 'muc.left' event handler.
  6407. //if (peerJid)
  6408. // ContactList.removeContact(peerJid);
  6409. };
  6410. // Add click handler.
  6411. container.onclick = function (event) {
  6412. /*
  6413. * FIXME It turns out that videoThumb may not exist (if there is
  6414. * no actual video).
  6415. */
  6416. var videoThumb = $('#' + container.id + '>video').get(0);
  6417. if (videoThumb) {
  6418. VideoLayout.handleVideoThumbClicked(
  6419. APP.RTC.getVideoSrc(videoThumb),
  6420. false,
  6421. Strophe.getResourceFromJid(peerJid));
  6422. }
  6423. event.stopPropagation();
  6424. event.preventDefault();
  6425. return false;
  6426. };
  6427. // Add hover handler
  6428. $(container).hover(
  6429. function() {
  6430. VideoLayout.showDisplayName(container.id, true);
  6431. },
  6432. function() {
  6433. var videoSrc = null;
  6434. if ($('#' + container.id + '>video')
  6435. && $('#' + container.id + '>video').length > 0) {
  6436. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  6437. }
  6438. // If the video has been "pinned" by the user we want to
  6439. // keep the display name on place.
  6440. if (!VideoLayout.isLargeVideoVisible()
  6441. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6442. VideoLayout.showDisplayName(container.id, false);
  6443. }
  6444. );
  6445. }
  6446. return newElementId;
  6447. };
  6448. /**
  6449. * Removes the remote stream element corresponding to the given stream and
  6450. * parent container.
  6451. *
  6452. * @param stream the stream
  6453. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  6454. * @param container
  6455. */
  6456. my.removeRemoteStreamElement = function (stream, isVideo, container) {
  6457. if (!container)
  6458. return;
  6459. var select = null;
  6460. var removedVideoSrc = null;
  6461. if (isVideo) {
  6462. select = $('#' + container.id + '>video');
  6463. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  6464. }
  6465. else
  6466. select = $('#' + container.id + '>audio');
  6467. // Mark video as removed to cancel waiting loop(if video is removed
  6468. // before has started)
  6469. select.removed = true;
  6470. select.remove();
  6471. var audioCount = $('#' + container.id + '>audio').length;
  6472. var videoCount = $('#' + container.id + '>video').length;
  6473. if (!audioCount && !videoCount) {
  6474. console.log("Remove whole user", container.id);
  6475. if(VideoLayout.connectionIndicators[container.id])
  6476. VideoLayout.connectionIndicators[container.id].remove();
  6477. // Remove whole container
  6478. container.remove();
  6479. UIUtil.playSoundNotification('userLeft');
  6480. VideoLayout.resizeThumbnails();
  6481. }
  6482. if (removedVideoSrc)
  6483. VideoLayout.updateRemovedVideo(removedVideoSrc);
  6484. };
  6485. /**
  6486. * Show/hide peer container for the given resourceJid.
  6487. */
  6488. function showPeerContainer(resourceJid, state) {
  6489. var peerContainer = $('#participant_' + resourceJid);
  6490. if (!peerContainer)
  6491. return;
  6492. var isHide = state === 'hide';
  6493. var resizeThumbnails = false;
  6494. if (!isHide) {
  6495. if (!peerContainer.is(':visible')) {
  6496. resizeThumbnails = true;
  6497. peerContainer.show();
  6498. }
  6499. var jid = APP.xmpp.findJidFromResource(resourceJid);
  6500. if (state == 'show')
  6501. {
  6502. // peerContainer.css('-webkit-filter', '');
  6503. Avatar.showUserAvatar(jid, false);
  6504. }
  6505. else // if (state == 'avatar')
  6506. {
  6507. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  6508. Avatar.showUserAvatar(jid, true);
  6509. }
  6510. }
  6511. else if (peerContainer.is(':visible') && isHide)
  6512. {
  6513. resizeThumbnails = true;
  6514. peerContainer.hide();
  6515. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  6516. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  6517. }
  6518. if (resizeThumbnails) {
  6519. VideoLayout.resizeThumbnails();
  6520. }
  6521. // We want to be able to pin a participant from the contact list, even
  6522. // if he's not in the lastN set!
  6523. // ContactList.setClickable(resourceJid, !isHide);
  6524. };
  6525. my.inputDisplayNameHandler = function (name) {
  6526. NicknameHandler.setNickname(name);
  6527. if (!$('#localDisplayName').is(":visible")) {
  6528. if (NicknameHandler.getNickname())
  6529. $('#localDisplayName').text(NicknameHandler.getNickname() + " (me)");
  6530. else
  6531. $('#localDisplayName')
  6532. .text(interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6533. $('#localDisplayName').show();
  6534. }
  6535. $('#editDisplayName').hide();
  6536. };
  6537. /**
  6538. * Shows/hides the display name on the remote video.
  6539. * @param videoSpanId the identifier of the video span element
  6540. * @param isShow indicates if the display name should be shown or hidden
  6541. */
  6542. my.showDisplayName = function(videoSpanId, isShow) {
  6543. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  6544. if (isShow) {
  6545. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  6546. nameSpan.setAttribute("style", "display:inline-block;");
  6547. }
  6548. else {
  6549. if (nameSpan)
  6550. nameSpan.setAttribute("style", "display:none;");
  6551. }
  6552. };
  6553. /**
  6554. * Shows the presence status message for the given video.
  6555. */
  6556. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  6557. if (!$('#' + videoSpanId).length) {
  6558. // No container
  6559. return;
  6560. }
  6561. var statusSpan = $('#' + videoSpanId + '>span.status');
  6562. if (!statusSpan.length) {
  6563. //Add status span
  6564. statusSpan = document.createElement('span');
  6565. statusSpan.className = 'status';
  6566. statusSpan.id = videoSpanId + '_status';
  6567. $('#' + videoSpanId)[0].appendChild(statusSpan);
  6568. statusSpan = $('#' + videoSpanId + '>span.status');
  6569. }
  6570. // Display status
  6571. if (statusMsg && statusMsg.length) {
  6572. $('#' + videoSpanId + '_status').text(statusMsg);
  6573. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  6574. }
  6575. else {
  6576. // Hide
  6577. statusSpan.get(0).setAttribute("style", "display:none;");
  6578. }
  6579. };
  6580. /**
  6581. * Shows a visual indicator for the moderator of the conference.
  6582. */
  6583. my.showModeratorIndicator = function () {
  6584. var isModerator = APP.xmpp.isModerator();
  6585. if (isModerator) {
  6586. var indicatorSpan = $('#localVideoContainer .focusindicator');
  6587. if (indicatorSpan.children().length === 0)
  6588. {
  6589. createModeratorIndicatorElement(indicatorSpan[0]);
  6590. //translates text in focus indicator
  6591. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  6592. }
  6593. }
  6594. var members = APP.xmpp.getMembers();
  6595. Object.keys(members).forEach(function (jid) {
  6596. if (Strophe.getResourceFromJid(jid) === 'focus') {
  6597. // Skip server side focus
  6598. return;
  6599. }
  6600. var resourceJid = Strophe.getResourceFromJid(jid);
  6601. var videoSpanId = 'participant_' + resourceJid;
  6602. var videoContainer = document.getElementById(videoSpanId);
  6603. if (!videoContainer) {
  6604. console.error("No video container for " + jid);
  6605. return;
  6606. }
  6607. var member = members[jid];
  6608. if (member.role === 'moderator') {
  6609. // Remove menu if peer is moderator
  6610. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  6611. if (menuSpan.length) {
  6612. removeRemoteVideoMenu(videoSpanId);
  6613. }
  6614. // Show moderator indicator
  6615. var indicatorSpan
  6616. = $('#' + videoSpanId + ' .focusindicator');
  6617. if (!indicatorSpan || indicatorSpan.length === 0) {
  6618. indicatorSpan = document.createElement('span');
  6619. indicatorSpan.className = 'focusindicator';
  6620. videoContainer.appendChild(indicatorSpan);
  6621. createModeratorIndicatorElement(indicatorSpan);
  6622. //translates text in focus indicators
  6623. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  6624. }
  6625. } else if (isModerator) {
  6626. // We are moderator, but user is not - add menu
  6627. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  6628. addRemoteVideoMenu(
  6629. jid,
  6630. document.getElementById('participant_' + resourceJid));
  6631. }
  6632. }
  6633. });
  6634. };
  6635. /**
  6636. * Shows video muted indicator over small videos.
  6637. */
  6638. my.showVideoIndicator = function(videoSpanId, isMuted) {
  6639. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6640. if (isMuted === 'false') {
  6641. if (videoMutedSpan.length > 0) {
  6642. videoMutedSpan.remove();
  6643. }
  6644. }
  6645. else {
  6646. if(videoMutedSpan.length == 0) {
  6647. videoMutedSpan = document.createElement('span');
  6648. videoMutedSpan.className = 'videoMuted';
  6649. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  6650. var mutedIndicator = document.createElement('i');
  6651. mutedIndicator.className = 'icon-camera-disabled';
  6652. UIUtil.setTooltip(mutedIndicator,
  6653. "videothumbnail.videomute",
  6654. "top");
  6655. videoMutedSpan.appendChild(mutedIndicator);
  6656. //translate texts for muted indicator
  6657. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  6658. }
  6659. VideoLayout.updateMutePosition(videoSpanId);
  6660. }
  6661. };
  6662. my.updateMutePosition = function (videoSpanId) {
  6663. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6664. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  6665. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6666. if(connectionIndicator.length > 0
  6667. && connectionIndicator[0].style.display != "none") {
  6668. audioMutedSpan.css({right: "23px"});
  6669. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  6670. }
  6671. else
  6672. {
  6673. audioMutedSpan.css({right: "0px"});
  6674. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  6675. }
  6676. }
  6677. /**
  6678. * Shows audio muted indicator over small videos.
  6679. * @param {string} isMuted
  6680. */
  6681. my.showAudioIndicator = function(videoSpanId, isMuted) {
  6682. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6683. if (isMuted === 'false') {
  6684. if (audioMutedSpan.length > 0) {
  6685. audioMutedSpan.popover('hide');
  6686. audioMutedSpan.remove();
  6687. }
  6688. }
  6689. else {
  6690. if(audioMutedSpan.length == 0 ) {
  6691. audioMutedSpan = document.createElement('span');
  6692. audioMutedSpan.className = 'audioMuted';
  6693. UIUtil.setTooltip(audioMutedSpan,
  6694. "videothumbnail.mute",
  6695. "top");
  6696. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  6697. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  6698. var mutedIndicator = document.createElement('i');
  6699. mutedIndicator.className = 'icon-mic-disabled';
  6700. audioMutedSpan.appendChild(mutedIndicator);
  6701. }
  6702. VideoLayout.updateMutePosition(videoSpanId);
  6703. }
  6704. };
  6705. /*
  6706. * Shows or hides the audio muted indicator over the local thumbnail video.
  6707. * @param {boolean} isMuted
  6708. */
  6709. my.showLocalAudioIndicator = function(isMuted) {
  6710. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  6711. };
  6712. /**
  6713. * Resizes the large video container.
  6714. */
  6715. my.resizeLargeVideoContainer = function () {
  6716. Chat.resizeChat();
  6717. var availableHeight = window.innerHeight;
  6718. var availableWidth = UIUtil.getAvailableVideoWidth();
  6719. if (availableWidth < 0 || availableHeight < 0) return;
  6720. $('#videospace').width(availableWidth);
  6721. $('#videospace').height(availableHeight);
  6722. $('#largeVideoContainer').width(availableWidth);
  6723. $('#largeVideoContainer').height(availableHeight);
  6724. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  6725. var top = availableHeight / 2 - avatarSize / 4 * 3;
  6726. $('#activeSpeaker').css('top', top);
  6727. VideoLayout.resizeThumbnails();
  6728. };
  6729. /**
  6730. * Resizes thumbnails.
  6731. */
  6732. my.resizeThumbnails = function() {
  6733. var videoSpaceWidth = $('#remoteVideos').width();
  6734. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  6735. var width = thumbnailSize[0];
  6736. var height = thumbnailSize[1];
  6737. // size videos so that while keeping AR and max height, we have a
  6738. // nice fit
  6739. $('#remoteVideos').height(height);
  6740. $('#remoteVideos>span').width(width);
  6741. $('#remoteVideos>span').height(height);
  6742. $('.userAvatar').css('left', (width - height) / 2);
  6743. $(document).trigger("remotevideo.resized", [width, height]);
  6744. };
  6745. /**
  6746. * Enables the dominant speaker UI.
  6747. *
  6748. * @param resourceJid the jid indicating the video element to
  6749. * activate/deactivate
  6750. * @param isEnable indicates if the dominant speaker should be enabled or
  6751. * disabled
  6752. */
  6753. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  6754. var videoSpanId = null;
  6755. var videoContainerId = null;
  6756. if (resourceJid
  6757. === APP.xmpp.myResource()) {
  6758. videoSpanId = 'localVideoWrapper';
  6759. videoContainerId = 'localVideoContainer';
  6760. }
  6761. else {
  6762. videoSpanId = 'participant_' + resourceJid;
  6763. videoContainerId = videoSpanId;
  6764. }
  6765. var displayName = resourceJid;
  6766. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  6767. if (nameSpan.length > 0)
  6768. displayName = nameSpan.html();
  6769. console.log("UI enable dominant speaker",
  6770. displayName,
  6771. resourceJid,
  6772. isEnable);
  6773. videoSpan = document.getElementById(videoContainerId);
  6774. if (!videoSpan) {
  6775. return;
  6776. }
  6777. var video = $('#' + videoSpanId + '>video');
  6778. if (video && video.length > 0) {
  6779. if (isEnable) {
  6780. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  6781. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  6782. if (!videoSpan.classList.contains("dominantspeaker"))
  6783. videoSpan.classList.add("dominantspeaker");
  6784. }
  6785. else {
  6786. VideoLayout.showDisplayName(videoContainerId, false);
  6787. if (videoSpan.classList.contains("dominantspeaker"))
  6788. videoSpan.classList.remove("dominantspeaker");
  6789. }
  6790. Avatar.showUserAvatar(
  6791. APP.xmpp.findJidFromResource(resourceJid));
  6792. }
  6793. };
  6794. /**
  6795. * Calculates the thumbnail size.
  6796. *
  6797. * @param videoSpaceWidth the width of the video space
  6798. */
  6799. my.calculateThumbnailSize = function (videoSpaceWidth) {
  6800. // Calculate the available height, which is the inner window height minus
  6801. // 39px for the header minus 2px for the delimiter lines on the top and
  6802. // bottom of the large video, minus the 36px space inside the remoteVideos
  6803. // container used for highlighting shadow.
  6804. var availableHeight = 100;
  6805. var numvids = $('#remoteVideos>span:visible').length;
  6806. if (localLastNCount && localLastNCount > 0) {
  6807. numvids = Math.min(localLastNCount + 1, numvids);
  6808. }
  6809. // Remove the 3px borders arround videos and border around the remote
  6810. // videos area and the 4 pixels between the local video and the others
  6811. //TODO: Find out where the 4 pixels come from and remove them
  6812. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  6813. var availableWidth = availableWinWidth / numvids;
  6814. var aspectRatio = 16.0 / 9.0;
  6815. var maxHeight = Math.min(160, availableHeight);
  6816. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  6817. if (availableHeight < availableWidth / aspectRatio) {
  6818. availableWidth = Math.floor(availableHeight * aspectRatio);
  6819. }
  6820. return [availableWidth, availableHeight];
  6821. };
  6822. /**
  6823. * Updates the remote video menu.
  6824. *
  6825. * @param jid the jid indicating the video for which we're adding a menu.
  6826. * @param isMuted indicates the current mute state
  6827. */
  6828. my.updateRemoteVideoMenu = function(jid, isMuted) {
  6829. var muteMenuItem
  6830. = $('#remote_popupmenu_'
  6831. + Strophe.getResourceFromJid(jid)
  6832. + '>li>a.mutelink');
  6833. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  6834. if (muteMenuItem.length) {
  6835. var muteLink = muteMenuItem.get(0);
  6836. if (isMuted === 'true') {
  6837. muteLink.innerHTML = mutedIndicator + ' Muted';
  6838. muteLink.className = 'mutelink disabled';
  6839. }
  6840. else {
  6841. muteLink.innerHTML = mutedIndicator + ' Mute';
  6842. muteLink.className = 'mutelink';
  6843. }
  6844. }
  6845. };
  6846. /**
  6847. * Returns the current dominant speaker resource jid.
  6848. */
  6849. my.getDominantSpeakerResourceJid = function () {
  6850. return currentDominantSpeaker;
  6851. };
  6852. /**
  6853. * Returns the corresponding resource jid to the given peer container
  6854. * DOM element.
  6855. *
  6856. * @return the corresponding resource jid to the given peer container
  6857. * DOM element
  6858. */
  6859. my.getPeerContainerResourceJid = function (containerElement) {
  6860. var i = containerElement.id.indexOf('participant_');
  6861. if (i >= 0)
  6862. return containerElement.id.substring(i + 12);
  6863. };
  6864. /**
  6865. * On contact list item clicked.
  6866. */
  6867. $(ContactList).bind('contactclicked', function(event, jid) {
  6868. if (!jid) {
  6869. return;
  6870. }
  6871. var resource = Strophe.getResourceFromJid(jid);
  6872. var videoContainer = $("#participant_" + resource);
  6873. if (videoContainer.length > 0) {
  6874. var videoThumb = $('video', videoContainer).get(0);
  6875. // It is not always the case that a videoThumb exists (if there is
  6876. // no actual video).
  6877. if (videoThumb) {
  6878. if (videoThumb.src && videoThumb.src != '') {
  6879. // We have a video src, great! Let's update the large video
  6880. // now.
  6881. VideoLayout.handleVideoThumbClicked(
  6882. videoThumb.src,
  6883. false,
  6884. Strophe.getResourceFromJid(jid));
  6885. } else {
  6886. // If we don't have a video src for jid, there's absolutely
  6887. // no point in calling handleVideoThumbClicked; Quite
  6888. // simply, it won't work because it needs an src to attach
  6889. // to the large video.
  6890. //
  6891. // Instead, we trigger the pinned endpoint changed event to
  6892. // let the bridge adjust its lastN set for myjid and store
  6893. // the pinned user in the lastNPickupJid variable to be
  6894. // picked up later by the lastN changed event handler.
  6895. lastNPickupJid = jid;
  6896. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  6897. Strophe.getResourceFromJid(jid));
  6898. }
  6899. } else if (jid == APP.xmpp.myJid()) {
  6900. $("#localVideoContainer").click();
  6901. }
  6902. }
  6903. });
  6904. /**
  6905. * On audio muted event.
  6906. */
  6907. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  6908. /*
  6909. // FIXME: but focus can not mute in this case ? - check
  6910. if (jid === xmpp.myJid()) {
  6911. // The local mute indicator is controlled locally
  6912. return;
  6913. }*/
  6914. var videoSpanId = null;
  6915. if (jid === APP.xmpp.myJid()) {
  6916. videoSpanId = 'localVideoContainer';
  6917. } else {
  6918. VideoLayout.ensurePeerContainerExists(jid);
  6919. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  6920. }
  6921. mutedAudios[jid] = isMuted;
  6922. if (APP.xmpp.isModerator()) {
  6923. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  6924. }
  6925. if (videoSpanId)
  6926. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  6927. });
  6928. /**
  6929. * On video muted event.
  6930. */
  6931. $(document).bind('videomuted.muc', function (event, jid, value) {
  6932. var isMuted = (value === "true");
  6933. if(!APP.RTC.muteRemoteVideoStream(jid, isMuted))
  6934. return;
  6935. Avatar.showUserAvatar(jid, isMuted);
  6936. var videoSpanId = null;
  6937. if (jid === APP.xmpp.myJid()) {
  6938. videoSpanId = 'localVideoContainer';
  6939. } else {
  6940. VideoLayout.ensurePeerContainerExists(jid);
  6941. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  6942. }
  6943. if (videoSpanId)
  6944. VideoLayout.showVideoIndicator(videoSpanId, value);
  6945. });
  6946. /**
  6947. * Display name changed.
  6948. */
  6949. my.onDisplayNameChanged =
  6950. function (jid, displayName, status) {
  6951. if (jid === 'localVideoContainer'
  6952. || jid === APP.xmpp.myJid()) {
  6953. setDisplayName('localVideoContainer',
  6954. displayName);
  6955. } else {
  6956. VideoLayout.ensurePeerContainerExists(jid);
  6957. setDisplayName(
  6958. 'participant_' + Strophe.getResourceFromJid(jid),
  6959. displayName,
  6960. status);
  6961. }
  6962. };
  6963. /**
  6964. * On dominant speaker changed event.
  6965. */
  6966. my.onDominantSpeakerChanged = function (resourceJid) {
  6967. // We ignore local user events.
  6968. if (resourceJid
  6969. === APP.xmpp.myResource())
  6970. return;
  6971. // Update the current dominant speaker.
  6972. if (resourceJid !== currentDominantSpeaker) {
  6973. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  6974. newSpeakerVideoSpanId = "participant_" + resourceJid;
  6975. if($("#" + oldSpeakerVideoSpanId + ">span.displayname").text() ===
  6976. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME) {
  6977. setDisplayName(oldSpeakerVideoSpanId, null);
  6978. }
  6979. if($("#" + newSpeakerVideoSpanId + ">span.displayname").text() ===
  6980. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME) {
  6981. setDisplayName(newSpeakerVideoSpanId,
  6982. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  6983. }
  6984. currentDominantSpeaker = resourceJid;
  6985. } else {
  6986. return;
  6987. }
  6988. // Obtain container for new dominant speaker.
  6989. var container = document.getElementById(
  6990. 'participant_' + resourceJid);
  6991. // Local video will not have container found, but that's ok
  6992. // since we don't want to switch to local video.
  6993. if (container && !focusedVideoInfo)
  6994. {
  6995. var video = container.getElementsByTagName("video");
  6996. // Update the large video if the video source is already available,
  6997. // otherwise wait for the "videoactive.jingle" event.
  6998. if (video.length && video[0].currentTime > 0)
  6999. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  7000. }
  7001. };
  7002. /**
  7003. * On last N change event.
  7004. *
  7005. * @param lastNEndpoints the list of last N endpoints
  7006. * @param endpointsEnteringLastN the list currently entering last N
  7007. * endpoints
  7008. */
  7009. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7010. endpointsEnteringLastN,
  7011. stream) {
  7012. if (lastNCount !== lastNEndpoints.length)
  7013. lastNCount = lastNEndpoints.length;
  7014. lastNEndpointsCache = lastNEndpoints;
  7015. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7016. //
  7017. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7018. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7019. // so E sees them. C is only in E's local LastN set.
  7020. //
  7021. // If F starts talking and LastN = 3, then E should see thumbnails for
  7022. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7023. // enters E's local LastN ejecting C.
  7024. // Increase the local LastN set size, if necessary.
  7025. if (lastNCount > localLastNCount) {
  7026. localLastNCount = lastNCount;
  7027. }
  7028. // Update the local LastN set preserving the order in which the
  7029. // endpoints appeared in the LastN/local LastN set.
  7030. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7031. for (var i = 0; i < localLastNSet.length; i++) {
  7032. if (nextLocalLastNSet.length >= localLastNCount) {
  7033. break;
  7034. }
  7035. var resourceJid = localLastNSet[i];
  7036. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7037. nextLocalLastNSet.push(resourceJid);
  7038. }
  7039. }
  7040. localLastNSet = nextLocalLastNSet;
  7041. var updateLargeVideo = false;
  7042. // Handle LastN/local LastN changes.
  7043. $('#remoteVideos>span').each(function( index, element ) {
  7044. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7045. var isReceived = true;
  7046. if (resourceJid
  7047. && lastNEndpoints.indexOf(resourceJid) < 0
  7048. && localLastNSet.indexOf(resourceJid) < 0) {
  7049. console.log("Remove from last N", resourceJid);
  7050. showPeerContainer(resourceJid, 'hide');
  7051. isReceived = false;
  7052. } else if (resourceJid
  7053. && $('#participant_' + resourceJid).is(':visible')
  7054. && lastNEndpoints.indexOf(resourceJid) < 0
  7055. && localLastNSet.indexOf(resourceJid) >= 0) {
  7056. showPeerContainer(resourceJid, 'avatar');
  7057. isReceived = false;
  7058. }
  7059. if (!isReceived) {
  7060. // resourceJid has dropped out of the server side lastN set, so
  7061. // it is no longer being received. If resourceJid was being
  7062. // displayed in the large video we have to switch to another
  7063. // user.
  7064. var largeVideoResource = largeVideoState.userResourceJid;
  7065. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7066. updateLargeVideo = true;
  7067. }
  7068. }
  7069. });
  7070. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7071. endpointsEnteringLastN = lastNEndpoints;
  7072. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7073. endpointsEnteringLastN.forEach(function (resourceJid) {
  7074. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7075. showPeerContainer(resourceJid, 'show');
  7076. if (!isVisible) {
  7077. console.log("Add to last N", resourceJid);
  7078. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7079. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7080. var sel = $('#participant_' + resourceJid + '>video');
  7081. var videoStream = APP.simulcast.getReceivingVideoStream(
  7082. mediaStream.stream);
  7083. APP.RTC.attachMediaStream(sel, videoStream);
  7084. if (lastNPickupJid == mediaStream.peerjid) {
  7085. // Clean up the lastN pickup jid.
  7086. lastNPickupJid = null;
  7087. // Don't fire the events again, they've already
  7088. // been fired in the contact list click handler.
  7089. VideoLayout.handleVideoThumbClicked(
  7090. $(sel).attr('src'),
  7091. false,
  7092. Strophe.getResourceFromJid(mediaStream.peerjid));
  7093. updateLargeVideo = false;
  7094. }
  7095. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7096. }
  7097. })
  7098. }
  7099. // The endpoint that was being shown in the large video has dropped out
  7100. // of the lastN set and there was no lastN pickup jid. We need to update
  7101. // the large video now.
  7102. if (updateLargeVideo) {
  7103. var resource, container, src;
  7104. var myResource
  7105. = APP.xmpp.myResource();
  7106. // Find out which endpoint to show in the large video.
  7107. for (var i = 0; i < lastNEndpoints.length; i++) {
  7108. resource = lastNEndpoints[i];
  7109. if (!resource || resource === myResource)
  7110. continue;
  7111. container = $("#participant_" + resource);
  7112. if (container.length == 0)
  7113. continue;
  7114. src = $('video', container).attr('src');
  7115. if (!src)
  7116. continue;
  7117. // videoSrcToSsrc needs to be update for this call to succeed.
  7118. VideoLayout.updateLargeVideo(src);
  7119. break;
  7120. }
  7121. }
  7122. };
  7123. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  7124. endpointSimulcastLayers.forEach(function (esl) {
  7125. var resource = esl.endpoint;
  7126. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7127. // then ignore the event (= do not preload anything).
  7128. //
  7129. // The bridge could probably stop sending this message if it's for
  7130. // an endpoint that's not in lastN.
  7131. if (lastNCount != -1
  7132. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7133. return;
  7134. }
  7135. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7136. // Get session and stream from primary ssrc.
  7137. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7138. var sid = res.sid;
  7139. var electedStream = res.stream;
  7140. if (sid && electedStream) {
  7141. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7142. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7143. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  7144. if (preload) {
  7145. if (largeVideoState.preload)
  7146. {
  7147. $(largeVideoState.preload).remove();
  7148. }
  7149. console.info('Preloading remote video');
  7150. largeVideoState.preload = $('<video autoplay></video>');
  7151. // ssrcs are unique in an rtp session
  7152. largeVideoState.preload_ssrc = primarySSRC;
  7153. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  7154. }
  7155. } else {
  7156. console.error('Could not find a stream or a session.', sid, electedStream);
  7157. }
  7158. });
  7159. };
  7160. /**
  7161. * On simulcast layers changed event.
  7162. */
  7163. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  7164. endpointSimulcastLayers.forEach(function (esl) {
  7165. var resource = esl.endpoint;
  7166. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7167. // then ignore the event (= do not change large video/thumbnail
  7168. // SRCs).
  7169. //
  7170. // Note that even if we ignore the "changed" event in this event
  7171. // handler, the bridge must continue sending these events because
  7172. // the simulcast code in simulcast.js uses it to know what's going
  7173. // to be streamed by the bridge when/if the endpoint gets back into
  7174. // the lastN set.
  7175. if (lastNCount != -1
  7176. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7177. return;
  7178. }
  7179. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7180. // Get session and stream from primary ssrc.
  7181. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7182. var sid = res.sid;
  7183. var electedStream = res.stream;
  7184. if (sid && electedStream) {
  7185. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7186. console.info('Switching simulcast substream.');
  7187. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7188. var msidParts = msid.split(' ');
  7189. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  7190. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  7191. == largeVideoState.userResourceJid);
  7192. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  7193. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  7194. var electedStreamUrl;
  7195. if (largeVideoState.preload_ssrc == primarySSRC)
  7196. {
  7197. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  7198. }
  7199. else
  7200. {
  7201. if (largeVideoState.preload
  7202. && largeVideoState.preload != null) {
  7203. $(largeVideoState.preload).remove();
  7204. }
  7205. largeVideoState.preload_ssrc = 0;
  7206. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  7207. }
  7208. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  7209. if (updateLargeVideo) {
  7210. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  7211. Strophe.getResourceFromJid(jid));
  7212. }
  7213. if (updateFocusedVideoSrc) {
  7214. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  7215. }
  7216. var videoId;
  7217. if(resource == APP.xmpp.myResource())
  7218. {
  7219. videoId = "localVideoContainer";
  7220. }
  7221. else
  7222. {
  7223. videoId = "participant_" + resource;
  7224. }
  7225. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  7226. if(connectionIndicator)
  7227. connectionIndicator.updatePopoverData();
  7228. } else {
  7229. console.error('Could not find a stream or a sid.', sid, electedStream);
  7230. }
  7231. });
  7232. };
  7233. /**
  7234. * Updates local stats
  7235. * @param percent
  7236. * @param object
  7237. */
  7238. my.updateLocalConnectionStats = function (percent, object) {
  7239. var resolution = null;
  7240. if(object.resolution !== null)
  7241. {
  7242. resolution = object.resolution;
  7243. object.resolution = resolution[APP.xmpp.myJid()];
  7244. delete resolution[APP.xmpp.myJid()];
  7245. }
  7246. updateStatsIndicator("localVideoContainer", percent, object);
  7247. for(var jid in resolution)
  7248. {
  7249. if(resolution[jid] === null)
  7250. continue;
  7251. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7252. if(VideoLayout.connectionIndicators[id])
  7253. {
  7254. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7255. }
  7256. }
  7257. };
  7258. /**
  7259. * Updates remote stats.
  7260. * @param jid the jid associated with the stats
  7261. * @param percent the connection quality percent
  7262. * @param object the stats data
  7263. */
  7264. my.updateConnectionStats = function (jid, percent, object) {
  7265. var resourceJid = Strophe.getResourceFromJid(jid);
  7266. var videoSpanId = 'participant_' + resourceJid;
  7267. updateStatsIndicator(videoSpanId, percent, object);
  7268. };
  7269. /**
  7270. * Removes the connection
  7271. * @param jid
  7272. */
  7273. my.removeConnectionIndicator = function (jid) {
  7274. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7275. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7276. };
  7277. /**
  7278. * Hides the connection indicator
  7279. * @param jid
  7280. */
  7281. my.hideConnectionIndicator = function (jid) {
  7282. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7283. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7284. };
  7285. /**
  7286. * Hides all the indicators
  7287. */
  7288. my.onStatsStop = function () {
  7289. for(var indicator in VideoLayout.connectionIndicators)
  7290. {
  7291. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7292. }
  7293. };
  7294. my.participantLeft = function (jid) {
  7295. // Unlock large video
  7296. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7297. {
  7298. console.info("Focused video owner has left the conference");
  7299. focusedVideoInfo = null;
  7300. }
  7301. }
  7302. return my;
  7303. }(VideoLayout || {}));
  7304. module.exports = VideoLayout;
  7305. },{"../../../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){
  7306. //var nouns = [
  7307. //];
  7308. var pluralNouns = [
  7309. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7310. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  7311. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  7312. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  7313. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  7314. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  7315. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  7316. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  7317. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  7318. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  7319. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  7320. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  7321. ];
  7322. //var places = [
  7323. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  7324. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  7325. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  7326. // "Bridge"
  7327. //];
  7328. var verbs = [
  7329. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  7330. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  7331. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  7332. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  7333. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  7334. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  7335. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  7336. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  7337. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  7338. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  7339. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  7340. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  7341. ];
  7342. var adverbs = [
  7343. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  7344. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  7345. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  7346. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  7347. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  7348. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  7349. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  7350. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  7351. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  7352. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  7353. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  7354. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  7355. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  7356. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  7357. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  7358. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  7359. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  7360. ];
  7361. var adjectives = [
  7362. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  7363. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  7364. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  7365. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  7366. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  7367. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  7368. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  7369. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  7370. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  7371. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  7372. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  7373. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  7374. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  7375. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  7376. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  7377. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  7378. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  7379. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  7380. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  7381. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  7382. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  7383. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  7384. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  7385. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  7386. "Zealous"
  7387. ];
  7388. //var pronouns = [
  7389. //];
  7390. //var conjunctions = [
  7391. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  7392. //];
  7393. /*
  7394. * Maps a string (category name) to the array of words from that category.
  7395. */
  7396. var CATEGORIES =
  7397. {
  7398. //"_NOUN_": nouns,
  7399. "_PLURALNOUN_": pluralNouns,
  7400. //"_PLACE_": places,
  7401. "_VERB_": verbs,
  7402. "_ADVERB_": adverbs,
  7403. "_ADJECTIVE_": adjectives
  7404. //"_PRONOUN_": pronouns,
  7405. //"_CONJUNCTION_": conjunctions,
  7406. };
  7407. var PATTERNS = [
  7408. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  7409. // BeautifulFungiOrSpaghetti
  7410. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  7411. // AmazinglyScaryToy
  7412. //"_ADVERB__ADJECTIVE__NOUN_",
  7413. // NeitherTrashNorRifle
  7414. //"Neither_NOUN_Nor_NOUN_",
  7415. //"Either_NOUN_Or_NOUN_",
  7416. // EitherCopulateOrInvestigate
  7417. //"Either_VERB_Or_VERB_",
  7418. //"Neither_VERB_Nor_VERB_",
  7419. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  7420. //"The_ADVERB__ADJECTIVE__NOUN_",
  7421. //"The_ADVERB__ADJECTIVE__NOUN_s",
  7422. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  7423. // WolvesComputeBadly
  7424. //"_PLURALNOUN__VERB__ADVERB_",
  7425. // UniteFacilitateAndMerge
  7426. //"_VERB__VERB_And_VERB_",
  7427. //NastyWitchesAtThePub
  7428. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  7429. ];
  7430. /*
  7431. * Returns a random element from the array 'arr'
  7432. */
  7433. function randomElement(arr)
  7434. {
  7435. return arr[Math.floor(Math.random() * arr.length)];
  7436. }
  7437. /*
  7438. * Returns true if the string 's' contains one of the
  7439. * template strings.
  7440. */
  7441. function hasTemplate(s)
  7442. {
  7443. for (var template in CATEGORIES){
  7444. if (s.indexOf(template) >= 0){
  7445. return true;
  7446. }
  7447. }
  7448. }
  7449. /**
  7450. * Generates new room name.
  7451. */
  7452. var RoomNameGenerator = {
  7453. generateRoomWithoutSeparator: function()
  7454. {
  7455. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  7456. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  7457. var name = randomElement(PATTERNS);
  7458. var word;
  7459. while (hasTemplate(name)){
  7460. for (var template in CATEGORIES){
  7461. word = randomElement(CATEGORIES[template]);
  7462. name = name.replace(template, word);
  7463. }
  7464. }
  7465. return name;
  7466. }
  7467. }
  7468. module.exports = RoomNameGenerator;
  7469. },{}],33:[function(require,module,exports){
  7470. var animateTimeout, updateTimeout;
  7471. var RoomNameGenerator = require("./RoomnameGenerator");
  7472. function enter_room()
  7473. {
  7474. var val = $("#enter_room_field").val();
  7475. if(!val) {
  7476. val = $("#enter_room_field").attr("room_name");
  7477. }
  7478. if (val) {
  7479. window.location.pathname = "/" + val;
  7480. }
  7481. }
  7482. function animate(word) {
  7483. var currentVal = $("#enter_room_field").attr("placeholder");
  7484. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  7485. animateTimeout = setTimeout(function() {
  7486. animate(word.substring(1, word.length))
  7487. }, 70);
  7488. }
  7489. function update_roomname()
  7490. {
  7491. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  7492. $("#enter_room_field").attr("room_name", word);
  7493. $("#enter_room_field").attr("placeholder", "");
  7494. clearTimeout(animateTimeout);
  7495. animate(word);
  7496. updateTimeout = setTimeout(update_roomname, 10000);
  7497. }
  7498. function setupWelcomePage()
  7499. {
  7500. $("#videoconference_page").hide();
  7501. $("#domain_name").text(
  7502. window.location.protocol + "//" + window.location.host + "/");
  7503. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7504. var leftWatermarkDiv
  7505. = $("#welcome_page_header div[class='watermark leftwatermark']");
  7506. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  7507. {
  7508. leftWatermarkDiv.css({display: 'block'});
  7509. leftWatermarkDiv.parent().get(0).href
  7510. = interfaceConfig.JITSI_WATERMARK_LINK;
  7511. }
  7512. }
  7513. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7514. var rightWatermarkDiv
  7515. = $("#welcome_page_header div[class='watermark rightwatermark']");
  7516. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  7517. rightWatermarkDiv.css({display: 'block'});
  7518. rightWatermarkDiv.parent().get(0).href
  7519. = interfaceConfig.BRAND_WATERMARK_LINK;
  7520. rightWatermarkDiv.get(0).style.backgroundImage
  7521. = "url(images/rightwatermark.png)";
  7522. }
  7523. }
  7524. if (interfaceConfig.SHOW_POWERED_BY) {
  7525. $("#welcome_page_header>a[class='poweredby']")
  7526. .css({display: 'block'});
  7527. }
  7528. $("#enter_room_button").click(function()
  7529. {
  7530. enter_room();
  7531. });
  7532. $("#enter_room_field").keydown(function (event) {
  7533. if (event.keyCode === 13 /* enter */) {
  7534. enter_room();
  7535. }
  7536. });
  7537. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  7538. var updateTimeout;
  7539. var animateTimeout;
  7540. $("#reload_roomname").click(function () {
  7541. clearTimeout(updateTimeout);
  7542. clearTimeout(animateTimeout);
  7543. update_roomname();
  7544. });
  7545. $("#reload_roomname").show();
  7546. update_roomname();
  7547. }
  7548. $("#disable_welcome").click(function () {
  7549. window.localStorage.welcomePageDisabled
  7550. = $("#disable_welcome").is(":checked");
  7551. });
  7552. }
  7553. module.exports = setupWelcomePage;
  7554. },{"./RoomnameGenerator":32}],34:[function(require,module,exports){
  7555. var EventEmitter = require("events");
  7556. var eventEmitter = new EventEmitter();
  7557. var CQEvents = require("../../service/connectionquality/CQEvents");
  7558. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7559. /**
  7560. * local stats
  7561. * @type {{}}
  7562. */
  7563. var stats = {};
  7564. /**
  7565. * remote stats
  7566. * @type {{}}
  7567. */
  7568. var remoteStats = {};
  7569. /**
  7570. * Interval for sending statistics to other participants
  7571. * @type {null}
  7572. */
  7573. var sendIntervalId = null;
  7574. /**
  7575. * Start statistics sending.
  7576. */
  7577. function startSendingStats() {
  7578. sendStats();
  7579. sendIntervalId = setInterval(sendStats, 10000);
  7580. }
  7581. /**
  7582. * Sends statistics to other participants
  7583. */
  7584. function sendStats() {
  7585. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  7586. }
  7587. /**
  7588. * Converts statistics to format for sending through XMPP
  7589. * @param stats the statistics
  7590. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  7591. */
  7592. function convertToMUCStats(stats) {
  7593. return {
  7594. "bitrate_download": stats.bitrate.download,
  7595. "bitrate_upload": stats.bitrate.upload,
  7596. "packetLoss_total": stats.packetLoss.total,
  7597. "packetLoss_download": stats.packetLoss.download,
  7598. "packetLoss_upload": stats.packetLoss.upload
  7599. };
  7600. }
  7601. /**
  7602. * Converts statitistics to format used by VideoLayout
  7603. * @param stats
  7604. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  7605. */
  7606. function parseMUCStats(stats) {
  7607. return {
  7608. bitrate: {
  7609. download: stats.bitrate_download,
  7610. upload: stats.bitrate_upload
  7611. },
  7612. packetLoss: {
  7613. total: stats.packetLoss_total,
  7614. download: stats.packetLoss_download,
  7615. upload: stats.packetLoss_upload
  7616. }
  7617. };
  7618. }
  7619. var ConnectionQuality = {
  7620. init: function () {
  7621. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  7622. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  7623. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  7624. },
  7625. /**
  7626. * Updates the local statistics
  7627. * @param data new statistics
  7628. */
  7629. updateLocalStats: function (data) {
  7630. stats = data;
  7631. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  7632. if (sendIntervalId == null) {
  7633. startSendingStats();
  7634. }
  7635. },
  7636. /**
  7637. * Updates remote statistics
  7638. * @param jid the jid associated with the statistics
  7639. * @param data the statistics
  7640. */
  7641. updateRemoteStats: function (jid, data) {
  7642. if (data == null || data.packetLoss_total == null) {
  7643. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  7644. return;
  7645. }
  7646. remoteStats[jid] = parseMUCStats(data);
  7647. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  7648. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  7649. },
  7650. /**
  7651. * Stops statistics sending.
  7652. */
  7653. stopSendingStats: function () {
  7654. clearInterval(sendIntervalId);
  7655. sendIntervalId = null;
  7656. //notify UI about stopping statistics gathering
  7657. eventEmitter.emit(CQEvents.STOP);
  7658. },
  7659. /**
  7660. * Returns the local statistics.
  7661. */
  7662. getStats: function () {
  7663. return stats;
  7664. },
  7665. addListener: function (type, listener) {
  7666. eventEmitter.on(type, listener);
  7667. }
  7668. };
  7669. module.exports = ConnectionQuality;
  7670. },{"../../service/connectionquality/CQEvents":85,"../../service/xmpp/XMPPEvents":88,"events":89}],35:[function(require,module,exports){
  7671. /* global $, alert, changeLocalVideo, chrome, config, getConferenceHandler, getUserMediaWithConstraints */
  7672. /**
  7673. * Indicates that desktop stream is currently in use(for toggle purpose).
  7674. * @type {boolean}
  7675. */
  7676. var isUsingScreenStream = false;
  7677. /**
  7678. * Indicates that switch stream operation is in progress and prevent from triggering new events.
  7679. * @type {boolean}
  7680. */
  7681. var switchInProgress = false;
  7682. /**
  7683. * Method used to get screen sharing stream.
  7684. *
  7685. * @type {function (stream_callback, failure_callback}
  7686. */
  7687. var obtainDesktopStream = null;
  7688. /**
  7689. * Flag used to cache desktop sharing enabled state. Do not use directly as it can be <tt>null</tt>.
  7690. * @type {null|boolean}
  7691. */
  7692. var _desktopSharingEnabled = null;
  7693. var EventEmitter = require("events");
  7694. var eventEmitter = new EventEmitter();
  7695. var DesktopSharingEventTypes = require("../../service/desktopsharing/DesktopSharingEventTypes");
  7696. /**
  7697. * Method obtains desktop stream from WebRTC 'screen' source.
  7698. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  7699. */
  7700. function obtainWebRTCScreen(streamCallback, failCallback) {
  7701. APP.RTC.getUserMediaWithConstraints(
  7702. ['screen'],
  7703. streamCallback,
  7704. failCallback
  7705. );
  7706. }
  7707. /**
  7708. * Constructs inline install URL for Chrome desktop streaming extension.
  7709. * The 'chromeExtensionId' must be defined in config.js.
  7710. * @returns {string}
  7711. */
  7712. function getWebStoreInstallUrl()
  7713. {
  7714. return "https://chrome.google.com/webstore/detail/" + config.chromeExtensionId;
  7715. }
  7716. /**
  7717. * Checks whether extension update is required.
  7718. * @param minVersion minimal required version
  7719. * @param extVersion current extension version
  7720. * @returns {boolean}
  7721. */
  7722. function isUpdateRequired(minVersion, extVersion)
  7723. {
  7724. try
  7725. {
  7726. var s1 = minVersion.split('.');
  7727. var s2 = extVersion.split('.');
  7728. var len = Math.max(s1.length, s2.length);
  7729. for (var i = 0; i < len; i++)
  7730. {
  7731. var n1 = 0,
  7732. n2 = 0;
  7733. if (i < s1.length)
  7734. n1 = parseInt(s1[i]);
  7735. if (i < s2.length)
  7736. n2 = parseInt(s2[i]);
  7737. if (isNaN(n1) || isNaN(n2))
  7738. {
  7739. return true;
  7740. }
  7741. else if (n1 !== n2)
  7742. {
  7743. return n1 > n2;
  7744. }
  7745. }
  7746. // will happen if boths version has identical numbers in
  7747. // their components (even if one of them is longer, has more components)
  7748. return false;
  7749. }
  7750. catch (e)
  7751. {
  7752. console.error("Failed to parse extension version", e);
  7753. APP.UI.messageHandler.showError("dialog.error",
  7754. "dialog.detectext");
  7755. return true;
  7756. }
  7757. }
  7758. function checkExtInstalled(isInstalledCallback) {
  7759. if (!chrome.runtime) {
  7760. // No API, so no extension for sure
  7761. isInstalledCallback(false);
  7762. return;
  7763. }
  7764. chrome.runtime.sendMessage(
  7765. config.chromeExtensionId,
  7766. { getVersion: true },
  7767. function (response) {
  7768. if (!response || !response.version) {
  7769. // Communication failure - assume that no endpoint exists
  7770. console.warn("Extension not installed?: " + chrome.runtime.lastError);
  7771. isInstalledCallback(false);
  7772. } else {
  7773. // Check installed extension version
  7774. var extVersion = response.version;
  7775. console.log('Extension version is: ' + extVersion);
  7776. var updateRequired = isUpdateRequired(config.minChromeExtVersion, extVersion);
  7777. if (updateRequired) {
  7778. alert(
  7779. 'Jitsi Desktop Streamer requires update. ' +
  7780. 'Changes will take effect after next Chrome restart.');
  7781. }
  7782. isInstalledCallback(!updateRequired);
  7783. }
  7784. }
  7785. );
  7786. }
  7787. function doGetStreamFromExtension(streamCallback, failCallback) {
  7788. // Sends 'getStream' msg to the extension. Extension id must be defined in the config.
  7789. chrome.runtime.sendMessage(
  7790. config.chromeExtensionId,
  7791. { getStream: true, sources: config.desktopSharingSources },
  7792. function (response) {
  7793. if (!response) {
  7794. failCallback(chrome.runtime.lastError);
  7795. return;
  7796. }
  7797. console.log("Response from extension: " + response);
  7798. if (response.streamId) {
  7799. APP.RTC.getUserMediaWithConstraints(
  7800. ['desktop'],
  7801. function (stream) {
  7802. streamCallback(stream);
  7803. },
  7804. failCallback,
  7805. null, null, null,
  7806. response.streamId);
  7807. } else {
  7808. failCallback("Extension failed to get the stream");
  7809. }
  7810. }
  7811. );
  7812. }
  7813. /**
  7814. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop' stream for returned stream token.
  7815. */
  7816. function obtainScreenFromExtension(streamCallback, failCallback) {
  7817. checkExtInstalled(
  7818. function (isInstalled) {
  7819. if (isInstalled) {
  7820. doGetStreamFromExtension(streamCallback, failCallback);
  7821. } else {
  7822. chrome.webstore.install(
  7823. getWebStoreInstallUrl(),
  7824. function (arg) {
  7825. console.log("Extension installed successfully", arg);
  7826. // We need to reload the page in order to get the access to chrome.runtime
  7827. window.location.reload(false);
  7828. },
  7829. function (arg) {
  7830. console.log("Failed to install the extension", arg);
  7831. failCallback(arg);
  7832. APP.UI.messageHandler.showError("dialog.error",
  7833. "dialog.failtoinstall");
  7834. }
  7835. );
  7836. }
  7837. }
  7838. );
  7839. }
  7840. /**
  7841. * Call this method to toggle desktop sharing feature.
  7842. * @param method pass "ext" to use chrome extension for desktop capture(chrome extension required),
  7843. * pass "webrtc" to use WebRTC "screen" desktop source('chrome://flags/#enable-usermedia-screen-capture'
  7844. * must be enabled), pass any other string or nothing in order to disable this feature completely.
  7845. */
  7846. function setDesktopSharing(method) {
  7847. // Check if we are running chrome
  7848. if (!navigator.webkitGetUserMedia) {
  7849. obtainDesktopStream = null;
  7850. console.info("Desktop sharing disabled");
  7851. } else if (method == "ext") {
  7852. obtainDesktopStream = obtainScreenFromExtension;
  7853. console.info("Using Chrome extension for desktop sharing");
  7854. } else if (method == "webrtc") {
  7855. obtainDesktopStream = obtainWebRTCScreen;
  7856. console.info("Using Chrome WebRTC for desktop sharing");
  7857. }
  7858. // Reset enabled cache
  7859. _desktopSharingEnabled = null;
  7860. }
  7861. /**
  7862. * Initializes <link rel=chrome-webstore-item /> with extension id set in config.js to support inline installs.
  7863. * Host site must be selected as main website of published extension.
  7864. */
  7865. function initInlineInstalls()
  7866. {
  7867. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  7868. }
  7869. function getSwitchStreamFailed(error) {
  7870. console.error("Failed to obtain the stream to switch to", error);
  7871. switchInProgress = false;
  7872. }
  7873. function streamSwitchDone() {
  7874. switchInProgress = false;
  7875. eventEmitter.emit(
  7876. DesktopSharingEventTypes.SWITCHING_DONE,
  7877. isUsingScreenStream);
  7878. }
  7879. function newStreamCreated(stream)
  7880. {
  7881. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  7882. stream, isUsingScreenStream, streamSwitchDone);
  7883. }
  7884. module.exports = {
  7885. isUsingScreenStream: function () {
  7886. return isUsingScreenStream;
  7887. },
  7888. /**
  7889. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available and enabled.
  7890. */
  7891. isDesktopSharingEnabled: function () {
  7892. if (_desktopSharingEnabled === null) {
  7893. if (obtainDesktopStream === obtainScreenFromExtension) {
  7894. // Parse chrome version
  7895. var userAgent = navigator.userAgent.toLowerCase();
  7896. // We can assume that user agent is chrome, because it's enforced when 'ext' streaming method is set
  7897. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  7898. console.log("Chrome version" + userAgent, ver);
  7899. _desktopSharingEnabled = ver >= 34;
  7900. } else {
  7901. _desktopSharingEnabled = obtainDesktopStream === obtainWebRTCScreen;
  7902. }
  7903. }
  7904. return _desktopSharingEnabled;
  7905. },
  7906. init: function () {
  7907. setDesktopSharing(config.desktopSharing);
  7908. // Initialize Chrome extension inline installs
  7909. if (config.chromeExtensionId) {
  7910. initInlineInstalls();
  7911. }
  7912. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  7913. },
  7914. addListener: function(listener, type)
  7915. {
  7916. eventEmitter.on(type, listener);
  7917. },
  7918. removeListener: function (listener,type) {
  7919. eventEmitter.removeListener(type, listener);
  7920. },
  7921. /*
  7922. * Toggles screen sharing.
  7923. */
  7924. toggleScreenSharing: function () {
  7925. if (switchInProgress || !obtainDesktopStream) {
  7926. console.warn("Switch in progress or no method defined");
  7927. return;
  7928. }
  7929. switchInProgress = true;
  7930. if (!isUsingScreenStream)
  7931. {
  7932. // Switch to desktop stream
  7933. obtainDesktopStream(
  7934. function (stream) {
  7935. // We now use screen stream
  7936. isUsingScreenStream = true;
  7937. // Hook 'ended' event to restore camera when screen stream stops
  7938. stream.addEventListener('ended',
  7939. function (e) {
  7940. if (!switchInProgress && isUsingScreenStream) {
  7941. toggleScreenSharing();
  7942. }
  7943. }
  7944. );
  7945. newStreamCreated(stream);
  7946. },
  7947. getSwitchStreamFailed);
  7948. } else {
  7949. // Disable screen stream
  7950. APP.RTC.getUserMediaWithConstraints(
  7951. ['video'],
  7952. function (stream) {
  7953. // We are now using camera stream
  7954. isUsingScreenStream = false;
  7955. newStreamCreated(stream);
  7956. },
  7957. getSwitchStreamFailed, config.resolution || '360'
  7958. );
  7959. }
  7960. }
  7961. };
  7962. },{"../../service/desktopsharing/DesktopSharingEventTypes":86,"events":89}],36:[function(require,module,exports){
  7963. //maps keycode to character, id of popover for given function and function
  7964. var shortcuts = {
  7965. 67: {
  7966. character: "C",
  7967. id: "toggleChatPopover",
  7968. function: APP.UI.toggleChat
  7969. },
  7970. 70: {
  7971. character: "F",
  7972. id: "filmstripPopover",
  7973. function: APP.UI.toggleFilmStrip
  7974. },
  7975. 77: {
  7976. character: "M",
  7977. id: "mutePopover",
  7978. function: APP.UI.toggleAudio
  7979. },
  7980. 84: {
  7981. character: "T",
  7982. function: function() {
  7983. if(!APP.RTC.localAudio.isMuted()) {
  7984. APP.UI.toggleAudio();
  7985. }
  7986. }
  7987. },
  7988. 86: {
  7989. character: "V",
  7990. id: "toggleVideoPopover",
  7991. function: APP.UI.toggleVideo
  7992. }
  7993. };
  7994. var KeyboardShortcut = {
  7995. init: function () {
  7996. window.onkeyup = function(e) {
  7997. var keycode = e.which;
  7998. if(!($(":focus").is("input[type=text]") ||
  7999. $(":focus").is("input[type=password]") ||
  8000. $(":focus").is("textarea"))) {
  8001. if (typeof shortcuts[keycode] === "object") {
  8002. shortcuts[keycode].function();
  8003. }
  8004. else if (keycode >= "0".charCodeAt(0) &&
  8005. keycode <= "9".charCodeAt(0)) {
  8006. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8007. }
  8008. //esc while the smileys are visible hides them
  8009. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8010. APP.UI.toggleSmileys();
  8011. }
  8012. };
  8013. window.onkeydown = function(e) {
  8014. if(!($(":focus").is("input[type=text]") ||
  8015. $(":focus").is("input[type=password]") ||
  8016. $(":focus").is("textarea"))) {
  8017. if(e.which === "T".charCodeAt(0)) {
  8018. if(APP.RTC.localAudio.isMuted()) {
  8019. APP.UI.toggleAudio();
  8020. }
  8021. }
  8022. }
  8023. };
  8024. var self = this;
  8025. $('body').popover({ selector: '[data-toggle=popover]',
  8026. trigger: 'click hover',
  8027. content: function() {
  8028. return this.getAttribute("content") +
  8029. self.getShortcut(this.getAttribute("shortcut"));
  8030. }
  8031. });
  8032. },
  8033. /**
  8034. *
  8035. * @param id indicates the popover associated with the shortcut
  8036. * @returns {string} the keyboard shortcut used for the id given
  8037. */
  8038. getShortcut: function (id) {
  8039. for (var keycode in shortcuts) {
  8040. if (shortcuts.hasOwnProperty(keycode)) {
  8041. if (shortcuts[keycode].id === id) {
  8042. return " (" + shortcuts[keycode].character + ")";
  8043. }
  8044. }
  8045. }
  8046. return "";
  8047. }
  8048. };
  8049. module.exports = KeyboardShortcut;
  8050. },{}],37:[function(require,module,exports){
  8051. var email = '';
  8052. var displayName = '';
  8053. var userId;
  8054. var language = null;
  8055. function supportsLocalStorage() {
  8056. try {
  8057. return 'localStorage' in window && window.localStorage !== null;
  8058. } catch (e) {
  8059. console.log("localstorage is not supported");
  8060. return false;
  8061. }
  8062. }
  8063. function generateUniqueId() {
  8064. function _p8() {
  8065. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8066. }
  8067. return _p8() + _p8() + _p8() + _p8();
  8068. }
  8069. if (supportsLocalStorage()) {
  8070. if (!window.localStorage.jitsiMeetId) {
  8071. window.localStorage.jitsiMeetId = generateUniqueId();
  8072. console.log("generated id", window.localStorage.jitsiMeetId);
  8073. }
  8074. userId = window.localStorage.jitsiMeetId || '';
  8075. email = window.localStorage.email || '';
  8076. displayName = window.localStorage.displayname || '';
  8077. language = window.localStorage.language;
  8078. } else {
  8079. console.log("local storage is not supported");
  8080. userId = generateUniqueId();
  8081. }
  8082. var Settings =
  8083. {
  8084. setDisplayName: function (newDisplayName) {
  8085. displayName = newDisplayName;
  8086. window.localStorage.displayname = displayName;
  8087. return displayName;
  8088. },
  8089. setEmail: function (newEmail)
  8090. {
  8091. email = newEmail;
  8092. window.localStorage.email = newEmail;
  8093. return email;
  8094. },
  8095. getSettings: function () {
  8096. return {
  8097. email: email,
  8098. displayName: displayName,
  8099. uid: userId,
  8100. language: language
  8101. };
  8102. },
  8103. setLanguage: function (lang) {
  8104. language = lang;
  8105. window.localStorage.language = lang;
  8106. }
  8107. };
  8108. module.exports = Settings;
  8109. },{}],38:[function(require,module,exports){
  8110. /**
  8111. *
  8112. * @constructor
  8113. */
  8114. function SimulcastLogger(name, lvl) {
  8115. this.name = name;
  8116. this.lvl = lvl;
  8117. }
  8118. SimulcastLogger.prototype.log = function (text) {
  8119. if (this.lvl) {
  8120. console.log(text);
  8121. }
  8122. };
  8123. SimulcastLogger.prototype.info = function (text) {
  8124. if (this.lvl > 1) {
  8125. console.info(text);
  8126. }
  8127. };
  8128. SimulcastLogger.prototype.fine = function (text) {
  8129. if (this.lvl > 2) {
  8130. console.log(text);
  8131. }
  8132. };
  8133. SimulcastLogger.prototype.error = function (text) {
  8134. console.error(text);
  8135. };
  8136. module.exports = SimulcastLogger;
  8137. },{}],39:[function(require,module,exports){
  8138. var SimulcastLogger = require("./SimulcastLogger");
  8139. var SimulcastUtils = require("./SimulcastUtils");
  8140. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  8141. function SimulcastReceiver() {
  8142. this.simulcastUtils = new SimulcastUtils();
  8143. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  8144. }
  8145. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  8146. SimulcastReceiver.prototype._remoteMaps = {
  8147. msid2Quality: {},
  8148. ssrc2Msid: {},
  8149. msid2ssrc: {},
  8150. receivingVideoStreams: {}
  8151. };
  8152. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  8153. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8154. };
  8155. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  8156. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  8157. };
  8158. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  8159. var sb;
  8160. this.logger.info('Ensuring x-google-conference flag...')
  8161. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8162. // TODO(gp) do that for the audio as well as suggested by fippo.
  8163. // Add the google conference flag
  8164. sb = this.simulcastUtils._getVideoSources(lines);
  8165. sb = ['a=x-google-flag:conference'].concat(sb);
  8166. this.simulcastUtils._replaceVideoSources(lines, sb);
  8167. }
  8168. };
  8169. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  8170. this._restoreRemoteVideoSources(sb);
  8171. };
  8172. /**
  8173. * Restores the simulcast groups of the remote description. In
  8174. * transformRemoteDescription we remove those in order for the set remote
  8175. * description to succeed. The focus needs the signal the groups to new
  8176. * participants.
  8177. *
  8178. * @param desc
  8179. * @returns {*}
  8180. */
  8181. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  8182. var sb;
  8183. if (!this.simulcastUtils.isValidDescription(desc)) {
  8184. return desc;
  8185. }
  8186. if (config.enableSimulcast) {
  8187. sb = desc.sdp.split('\r\n');
  8188. this._restoreSimulcastGroups(sb);
  8189. desc = new RTCSessionDescription({
  8190. type: desc.type,
  8191. sdp: sb.join('\r\n')
  8192. });
  8193. }
  8194. return desc;
  8195. };
  8196. SimulcastUtils.prototype._ensureOrder = function (lines) {
  8197. var videoSources, sb;
  8198. videoSources = this.parseMedia(lines, ['video'])[0];
  8199. sb = this._compileVideoSources(videoSources);
  8200. this._replaceVideoSources(lines, sb);
  8201. };
  8202. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  8203. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  8204. videoSource, quality;
  8205. // (re) initialize the remote maps.
  8206. this._remoteMaps.msid2Quality = {};
  8207. this._remoteMaps.ssrc2Msid = {};
  8208. this._remoteMaps.msid2ssrc = {};
  8209. var self = this;
  8210. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  8211. remoteVideoSources.groups.forEach(function (group) {
  8212. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  8213. quality = 0;
  8214. group.ssrcs.forEach(function (ssrc) {
  8215. videoSource = remoteVideoSources.sources[ssrc];
  8216. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  8217. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  8218. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  8219. });
  8220. }
  8221. });
  8222. }
  8223. };
  8224. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  8225. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  8226. };
  8227. /**
  8228. * Returns a stream with single video track, the one currently being
  8229. * received by this endpoint.
  8230. *
  8231. * @param stream the remote simulcast stream.
  8232. * @returns {webkitMediaStream}
  8233. */
  8234. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  8235. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  8236. var self = this;
  8237. if (config.enableSimulcast) {
  8238. stream.getVideoTracks().some(function (track) {
  8239. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  8240. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  8241. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  8242. if (msid == [stream.id, track.id].join(' ')) {
  8243. electedTrack = track;
  8244. return true;
  8245. }
  8246. });
  8247. });
  8248. if (!electedTrack) {
  8249. // we don't have an elected track, choose by initial quality.
  8250. tracks = stream.getVideoTracks();
  8251. for (i = 0; i < tracks.length; i++) {
  8252. msid = [stream.id, tracks[i].id].join(' ');
  8253. if (this._remoteMaps.msid2Quality[msid] === quality) {
  8254. electedTrack = tracks[i];
  8255. break;
  8256. }
  8257. }
  8258. // TODO(gp) if the initialQuality could not be satisfied, lower
  8259. // the requirement and try again.
  8260. }
  8261. }
  8262. return (electedTrack)
  8263. ? new webkitMediaStream([electedTrack])
  8264. : stream;
  8265. };
  8266. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  8267. var resource = Strophe.getResourceFromJid(jid);
  8268. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  8269. // If we haven't receiving a "changed" event yet, then we must be receiving
  8270. // low quality (that the sender always streams).
  8271. if(!ssrc)
  8272. {
  8273. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8274. var remoteStream = remoteStreamObject.getOriginalStream();
  8275. var tracks = remoteStream.getVideoTracks();
  8276. if (tracks) {
  8277. for (var k = 0; k < tracks.length; k++) {
  8278. var track = tracks[k];
  8279. var msid = [remoteStream.id, track.id].join(' ');
  8280. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  8281. var quality = this._remoteMaps.msid2Quality[msid];
  8282. if (quality == 0) {
  8283. ssrc = _ssrc;
  8284. }
  8285. }
  8286. }
  8287. }
  8288. return ssrc;
  8289. };
  8290. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  8291. {
  8292. var sid, electedStream;
  8293. var i, j, k;
  8294. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  8295. if(jid && APP.RTC.remoteStreams[jid])
  8296. {
  8297. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8298. var remoteStream = remoteStreamObject.getOriginalStream();
  8299. var tracks = remoteStream.getVideoTracks();
  8300. if (tracks) {
  8301. for (k = 0; k < tracks.length; k++) {
  8302. var track = tracks[k];
  8303. var msid = [remoteStream.id, track.id].join(' ');
  8304. var tmp = this._remoteMaps.msid2ssrc[msid];
  8305. if (tmp == ssrc) {
  8306. electedStream = new webkitMediaStream([track]);
  8307. sid = remoteStreamObject.sid;
  8308. // stream found, stop.
  8309. break;
  8310. }
  8311. }
  8312. }
  8313. }
  8314. else
  8315. {
  8316. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  8317. }
  8318. return {
  8319. sid: sid,
  8320. stream: electedStream
  8321. };
  8322. };
  8323. /**
  8324. * Gets the fully qualified msid (stream.id + track.id) associated to the
  8325. * SSRC.
  8326. *
  8327. * @param ssrc
  8328. * @returns {*}
  8329. */
  8330. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  8331. return this._remoteMaps.ssrc2Msid[ssrc];
  8332. };
  8333. /**
  8334. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  8335. * either gets confused and thinks this is an FID group or, if an FID group
  8336. * is already present, it fails to set the remote description.
  8337. *
  8338. * @param desc
  8339. * @returns {*}
  8340. */
  8341. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  8342. if (desc && desc.sdp) {
  8343. var sb = desc.sdp.split('\r\n');
  8344. this._updateRemoteMaps(sb);
  8345. this._cacheRemoteVideoSources(sb);
  8346. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  8347. // need the simulcast group in the _updateRemoteMaps() method.
  8348. this.simulcastUtils._removeSimulcastGroup(sb);
  8349. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  8350. // We don't need the goog conference flag if we're not doing
  8351. // simulcast.
  8352. this._ensureGoogConference(sb);
  8353. }
  8354. desc = new RTCSessionDescription({
  8355. type: desc.type,
  8356. sdp: sb.join('\r\n')
  8357. });
  8358. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  8359. }
  8360. return desc;
  8361. };
  8362. module.exports = SimulcastReceiver;
  8363. },{"../../service/RTC/MediaStreamTypes":78,"./SimulcastLogger":38,"./SimulcastUtils":41}],40:[function(require,module,exports){
  8364. var SimulcastLogger = require("./SimulcastLogger");
  8365. var SimulcastUtils = require("./SimulcastUtils");
  8366. function SimulcastSender() {
  8367. this.simulcastUtils = new SimulcastUtils();
  8368. this.logger = new SimulcastLogger('SimulcastSender', 1);
  8369. }
  8370. SimulcastSender.prototype.displayedLocalVideoStream = null;
  8371. SimulcastSender.prototype._generateGuid = (function () {
  8372. function s4() {
  8373. return Math.floor((1 + Math.random()) * 0x10000)
  8374. .toString(16)
  8375. .substring(1);
  8376. }
  8377. return function () {
  8378. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  8379. s4() + '-' + s4() + s4() + s4();
  8380. };
  8381. }());
  8382. // Returns a random integer between min (included) and max (excluded)
  8383. // Using Math.round() gives a non-uniform distribution!
  8384. SimulcastSender.prototype._generateRandomSSRC = function () {
  8385. var min = 0, max = 0xffffffff;
  8386. return Math.floor(Math.random() * (max - min)) + min;
  8387. };
  8388. SimulcastSender.prototype.getLocalVideoStream = function () {
  8389. return (this.displayedLocalVideoStream != null)
  8390. ? this.displayedLocalVideoStream
  8391. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  8392. : APP.RTC.localVideo.getOriginalStream();
  8393. };
  8394. function NativeSimulcastSender() {
  8395. SimulcastSender.call(this); // call the super constructor.
  8396. }
  8397. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8398. NativeSimulcastSender.prototype._localExplosionMap = {};
  8399. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  8400. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  8401. NativeSimulcastSender.prototype.reset = function () {
  8402. this._localExplosionMap = {};
  8403. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  8404. };
  8405. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  8406. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8407. };
  8408. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  8409. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  8410. };
  8411. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  8412. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  8413. this.logger.info('Appending simulcast group...');
  8414. // Get the primary SSRC information.
  8415. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8416. // Start building the SIM SSRC group.
  8417. ssrcGroup = ['a=ssrc-group:SIM'];
  8418. // The video source buffer.
  8419. sb = [];
  8420. // Create the simulcast sub-streams.
  8421. for (i = 0; i < numOfSubs; i++) {
  8422. // TODO(gp) prevent SSRC collision.
  8423. simSSRC = this._generateRandomSSRC();
  8424. ssrcGroup.push(simSSRC);
  8425. if (videoSources.base) {
  8426. sb.splice.apply(sb, [sb.length, 0].concat(
  8427. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  8428. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  8429. ));
  8430. }
  8431. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  8432. }
  8433. // Add the group sim layers.
  8434. sb.splice(0, 0, ssrcGroup.join(' '))
  8435. this.simulcastUtils._replaceVideoSources(lines, sb);
  8436. };
  8437. // Does the actual patching.
  8438. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  8439. this.logger.info('Ensuring simulcast group...');
  8440. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8441. this._appendSimulcastGroup(lines);
  8442. this._cacheLocalVideoSources(lines);
  8443. } else {
  8444. // verify that the ssrcs participating in the SIM group are present
  8445. // in the SDP (needed for presence).
  8446. this._restoreLocalVideoSources(lines);
  8447. }
  8448. };
  8449. /**
  8450. * Produces a single stream with multiple tracks for local video sources.
  8451. *
  8452. * @param lines
  8453. * @private
  8454. */
  8455. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  8456. var sb, msid, sid, tid, videoSources, self;
  8457. this.logger.info('Exploding local video sources...');
  8458. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8459. self = this;
  8460. if (videoSources.groups && videoSources.groups.length !== 0) {
  8461. videoSources.groups.forEach(function (group) {
  8462. if (group.semantics === 'SIM') {
  8463. group.ssrcs.forEach(function (ssrc) {
  8464. // Get the msid for this ssrc..
  8465. if (self._localExplosionMap[ssrc]) {
  8466. // .. either from the explosion map..
  8467. msid = self._localExplosionMap[ssrc];
  8468. } else {
  8469. // .. or generate a new one (msid).
  8470. sid = videoSources.sources[ssrc].msid
  8471. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  8472. tid = self._generateGuid();
  8473. msid = [sid, tid].join(' ');
  8474. self._localExplosionMap[ssrc] = msid;
  8475. }
  8476. // Assign it to the source object.
  8477. videoSources.sources[ssrc].msid = msid;
  8478. // TODO(gp) Change the msid of associated sources.
  8479. });
  8480. }
  8481. });
  8482. }
  8483. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8484. this.simulcastUtils._replaceVideoSources(lines, sb);
  8485. };
  8486. /**
  8487. * GUM for simulcast.
  8488. *
  8489. * @param constraints
  8490. * @param success
  8491. * @param err
  8492. */
  8493. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8494. // There's nothing special to do for native simulcast, so just do a normal GUM.
  8495. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8496. success(hqStream);
  8497. }, err);
  8498. };
  8499. /**
  8500. * Prepares the local description for public usage (i.e. to be signaled
  8501. * through Jingle to the focus).
  8502. *
  8503. * @param desc
  8504. * @returns {RTCSessionDescription}
  8505. */
  8506. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8507. var sb;
  8508. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8509. return desc;
  8510. }
  8511. sb = desc.sdp.split('\r\n');
  8512. this._explodeSimulcastSenderSources(sb);
  8513. desc = new RTCSessionDescription({
  8514. type: desc.type,
  8515. sdp: sb.join('\r\n')
  8516. });
  8517. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  8518. return desc;
  8519. };
  8520. /**
  8521. * Ensures that the simulcast group is present in the answer, _if_ native
  8522. * simulcast is enabled,
  8523. *
  8524. * @param desc
  8525. * @returns {*}
  8526. */
  8527. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  8528. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8529. return desc;
  8530. }
  8531. var sb = desc.sdp.split('\r\n');
  8532. // Even if we have enabled native simulcasting previously
  8533. // (with a call to SLD with an appropriate SDP, for example),
  8534. // createAnswer seems to consistently generate incomplete SDP
  8535. // with missing SSRCS.
  8536. //
  8537. // So, subsequent calls to SLD will have missing SSRCS and presence
  8538. // won't have the complete list of SRCs.
  8539. this._ensureSimulcastGroup(sb);
  8540. desc = new RTCSessionDescription({
  8541. type: desc.type,
  8542. sdp: sb.join('\r\n')
  8543. });
  8544. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  8545. return desc;
  8546. };
  8547. /**
  8548. *
  8549. *
  8550. * @param desc
  8551. * @returns {*}
  8552. */
  8553. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8554. return desc;
  8555. };
  8556. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8557. // Nothing to do here, native simulcast does that auto-magically.
  8558. };
  8559. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  8560. function SimpleSimulcastSender() {
  8561. SimulcastSender.call(this);
  8562. }
  8563. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8564. SimpleSimulcastSender.prototype.localStream = null;
  8565. SimpleSimulcastSender.prototype._localMaps = {
  8566. msids: [],
  8567. msid2ssrc: {}
  8568. };
  8569. /**
  8570. * Groups local video sources together in the ssrc-group:SIM group.
  8571. *
  8572. * @param lines
  8573. * @private
  8574. */
  8575. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  8576. var sb, videoSources, ssrcs = [], ssrc;
  8577. this.logger.info('Grouping local video sources...');
  8578. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8579. for (ssrc in videoSources.sources) {
  8580. // jitsi-meet destroys/creates streams at various places causing
  8581. // the original local stream ids to change. The only thing that
  8582. // remains unchanged is the trackid.
  8583. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  8584. }
  8585. var self = this;
  8586. // TODO(gp) add only "free" sources.
  8587. this._localMaps.msids.forEach(function (msid) {
  8588. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  8589. });
  8590. if (!videoSources.groups) {
  8591. videoSources.groups = [];
  8592. }
  8593. videoSources.groups.push({
  8594. 'semantics': 'SIM',
  8595. 'ssrcs': ssrcs
  8596. });
  8597. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8598. this.simulcastUtils._replaceVideoSources(lines, sb);
  8599. };
  8600. /**
  8601. * GUM for simulcast.
  8602. *
  8603. * @param constraints
  8604. * @param success
  8605. * @param err
  8606. */
  8607. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8608. // TODO(gp) what if we request a resolution not supported by the hardware?
  8609. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  8610. var lqConstraints = {
  8611. audio: false,
  8612. video: {
  8613. mandatory: {
  8614. maxWidth: 320,
  8615. maxHeight: 180,
  8616. maxFrameRate: 15
  8617. }
  8618. }
  8619. };
  8620. this.logger.info('HQ constraints: ', constraints);
  8621. this.logger.info('LQ constraints: ', lqConstraints);
  8622. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  8623. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  8624. // reason appears to be that Chrome only acquires the cam once and
  8625. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  8626. var self = this;
  8627. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8628. self.localStream = hqStream;
  8629. // reset local maps.
  8630. self._localMaps.msids = [];
  8631. self._localMaps.msid2ssrc = {};
  8632. // add hq trackid to local map
  8633. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  8634. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  8635. self.displayedLocalVideoStream = lqStream;
  8636. // NOTE(gp) The specification says Array.forEach() will visit
  8637. // the array elements in numeric order, and that it doesn't
  8638. // visit elements that don't exist.
  8639. // add lq trackid to local map
  8640. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  8641. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  8642. success(self.localStream);
  8643. }, err);
  8644. }, err);
  8645. };
  8646. /**
  8647. * Prepares the local description for public usage (i.e. to be signaled
  8648. * through Jingle to the focus).
  8649. *
  8650. * @param desc
  8651. * @returns {RTCSessionDescription}
  8652. */
  8653. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8654. var sb;
  8655. if (!this.simulcastUtils.isValidDescription(desc)) {
  8656. return desc;
  8657. }
  8658. sb = desc.sdp.split('\r\n');
  8659. this._groupLocalVideoSources(sb);
  8660. desc = new RTCSessionDescription({
  8661. type: desc.type,
  8662. sdp: sb.join('\r\n')
  8663. });
  8664. this.logger.fine('Grouped local video sources');
  8665. this.logger.fine(desc.sdp);
  8666. return desc;
  8667. };
  8668. /**
  8669. * Ensures that the simulcast group is present in the answer, _if_ native
  8670. * simulcast is enabled,
  8671. *
  8672. * @param desc
  8673. * @returns {*}
  8674. */
  8675. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  8676. return desc;
  8677. };
  8678. /**
  8679. *
  8680. *
  8681. * @param desc
  8682. * @returns {*}
  8683. */
  8684. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8685. var sb = desc.sdp.split('\r\n');
  8686. this.simulcastUtils._removeSimulcastGroup(sb);
  8687. desc = new RTCSessionDescription({
  8688. type: desc.type,
  8689. sdp: sb.join('\r\n')
  8690. });
  8691. this.logger.fine('Transformed local description');
  8692. this.logger.fine(desc.sdp);
  8693. return desc;
  8694. };
  8695. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8696. var trackid;
  8697. var self = this;
  8698. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  8699. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  8700. // Search for the track id that corresponds to the ssrc
  8701. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  8702. trackid = tid;
  8703. return true;
  8704. }
  8705. }) && self.localStream.getVideoTracks().some(function (track) {
  8706. // Start/stop the track that corresponds to the track id
  8707. if (track.id === trackid) {
  8708. track.enabled = enabled;
  8709. return true;
  8710. }
  8711. })) {
  8712. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  8713. $(document).trigger(enabled
  8714. ? 'simulcastlayerstarted'
  8715. : 'simulcastlayerstopped');
  8716. } else {
  8717. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  8718. }
  8719. };
  8720. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  8721. function NoSimulcastSender() {
  8722. SimulcastSender.call(this);
  8723. }
  8724. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8725. /**
  8726. * GUM for simulcast.
  8727. *
  8728. * @param constraints
  8729. * @param success
  8730. * @param err
  8731. */
  8732. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8733. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8734. success(hqStream);
  8735. }, err);
  8736. };
  8737. /**
  8738. * Prepares the local description for public usage (i.e. to be signaled
  8739. * through Jingle to the focus).
  8740. *
  8741. * @param desc
  8742. * @returns {RTCSessionDescription}
  8743. */
  8744. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8745. return desc;
  8746. };
  8747. /**
  8748. * Ensures that the simulcast group is present in the answer, _if_ native
  8749. * simulcast is enabled,
  8750. *
  8751. * @param desc
  8752. * @returns {*}
  8753. */
  8754. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  8755. return desc;
  8756. };
  8757. /**
  8758. *
  8759. *
  8760. * @param desc
  8761. * @returns {*}
  8762. */
  8763. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8764. return desc;
  8765. };
  8766. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8767. };
  8768. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  8769. module.exports = {
  8770. "native": NativeSimulcastSender,
  8771. "no": NoSimulcastSender
  8772. }
  8773. },{"./SimulcastLogger":38,"./SimulcastUtils":41}],41:[function(require,module,exports){
  8774. var SimulcastLogger = require("./SimulcastLogger");
  8775. /**
  8776. *
  8777. * @constructor
  8778. */
  8779. function SimulcastUtils() {
  8780. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  8781. }
  8782. /**
  8783. *
  8784. * @type {{}}
  8785. * @private
  8786. */
  8787. SimulcastUtils.prototype._emptyCompoundIndex = {};
  8788. /**
  8789. *
  8790. * @param lines
  8791. * @param videoSources
  8792. * @private
  8793. */
  8794. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  8795. var i, inVideo = false, index = -1, howMany = 0;
  8796. this.logger.info('Replacing video sources...');
  8797. for (i = 0; i < lines.length; i++) {
  8798. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  8799. // Out of video.
  8800. break;
  8801. }
  8802. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  8803. // In video.
  8804. inVideo = true;
  8805. }
  8806. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  8807. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  8808. if (index === -1) {
  8809. index = i;
  8810. }
  8811. howMany++;
  8812. }
  8813. }
  8814. // efficiency baby ;)
  8815. lines.splice.apply(lines,
  8816. [index, howMany].concat(videoSources));
  8817. };
  8818. SimulcastUtils.prototype.isValidDescription = function (desc)
  8819. {
  8820. return desc && desc != null
  8821. && desc.type && desc.type != ''
  8822. && desc.sdp && desc.sdp != '';
  8823. };
  8824. SimulcastUtils.prototype._getVideoSources = function (lines) {
  8825. var i, inVideo = false, sb = [];
  8826. this.logger.info('Getting video sources...');
  8827. for (i = 0; i < lines.length; i++) {
  8828. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  8829. // Out of video.
  8830. break;
  8831. }
  8832. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  8833. // In video.
  8834. inVideo = true;
  8835. }
  8836. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  8837. // In SSRC.
  8838. sb.push(lines[i]);
  8839. }
  8840. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  8841. sb.push(lines[i]);
  8842. }
  8843. }
  8844. return sb;
  8845. };
  8846. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  8847. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  8848. ssrc_attribute, group, semantics, skip = true;
  8849. this.logger.info('Parsing media sources...');
  8850. for (i = 0; i < lines.length; i++) {
  8851. if (lines[i].substring(0, 'm='.length) === 'm=') {
  8852. type = lines[i]
  8853. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  8854. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  8855. if (!skip) {
  8856. cur_media = {
  8857. 'type': type,
  8858. 'sources': {},
  8859. 'groups': []
  8860. };
  8861. res.push(cur_media);
  8862. }
  8863. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  8864. idx = lines[i].indexOf(' ');
  8865. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  8866. if (cur_media.sources[ssrc] === undefined) {
  8867. cur_ssrc = {'ssrc': ssrc};
  8868. cur_media.sources[ssrc] = cur_ssrc;
  8869. }
  8870. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  8871. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  8872. if (cur_media.base === undefined) {
  8873. cur_media.base = cur_ssrc;
  8874. }
  8875. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  8876. idx = lines[i].indexOf(' ');
  8877. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  8878. ssrcs = lines[i].substr(idx).trim().split(' ');
  8879. group = {
  8880. 'semantics': semantics,
  8881. 'ssrcs': ssrcs
  8882. };
  8883. cur_media.groups.push(group);
  8884. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  8885. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  8886. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  8887. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  8888. cur_media.direction = lines[i].substring('a='.length);
  8889. }
  8890. }
  8891. return res;
  8892. };
  8893. /**
  8894. * The _indexOfArray() method returns the first a CompoundIndex at which a
  8895. * given element can be found in the array, or _emptyCompoundIndex if it is
  8896. * not present.
  8897. *
  8898. * Example:
  8899. *
  8900. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  8901. *
  8902. * returns {row: 2, column: 14}
  8903. *
  8904. * @param needle
  8905. * @param haystack
  8906. * @param start
  8907. * @returns {}
  8908. * @private
  8909. */
  8910. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  8911. var length = haystack.length, idx, i;
  8912. if (!start) {
  8913. start = 0;
  8914. }
  8915. for (i = start; i < length; i++) {
  8916. idx = haystack[i].indexOf(needle);
  8917. if (idx !== -1) {
  8918. return {row: i, column: idx};
  8919. }
  8920. }
  8921. return this._emptyCompoundIndex;
  8922. };
  8923. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  8924. var i;
  8925. for (i = lines.length - 1; i >= 0; i--) {
  8926. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  8927. lines.splice(i, 1);
  8928. }
  8929. }
  8930. };
  8931. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  8932. var sb = [], ssrc, addedSSRCs = [];
  8933. this.logger.info('Compiling video sources...');
  8934. // Add the groups
  8935. if (videoSources.groups && videoSources.groups.length !== 0) {
  8936. videoSources.groups.forEach(function (group) {
  8937. if (group.ssrcs && group.ssrcs.length !== 0) {
  8938. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  8939. // if (group.semantics !== 'SIM') {
  8940. group.ssrcs.forEach(function (ssrc) {
  8941. addedSSRCs.push(ssrc);
  8942. sb.splice.apply(sb, [sb.length, 0].concat([
  8943. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  8944. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  8945. });
  8946. //}
  8947. }
  8948. });
  8949. }
  8950. // Then add any free sources.
  8951. if (videoSources.sources) {
  8952. for (ssrc in videoSources.sources) {
  8953. if (addedSSRCs.indexOf(ssrc) === -1) {
  8954. sb.splice.apply(sb, [sb.length, 0].concat([
  8955. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  8956. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  8957. }
  8958. }
  8959. }
  8960. return sb;
  8961. };
  8962. module.exports = SimulcastUtils;
  8963. },{"./SimulcastLogger":38}],42:[function(require,module,exports){
  8964. /*jslint plusplus: true */
  8965. /*jslint nomen: true*/
  8966. var SimulcastSender = require("./SimulcastSender");
  8967. var NoSimulcastSender = SimulcastSender["no"];
  8968. var NativeSimulcastSender = SimulcastSender["native"];
  8969. var SimulcastReceiver = require("./SimulcastReceiver");
  8970. var SimulcastUtils = require("./SimulcastUtils");
  8971. var RTCEvents = require("../../service/RTC/RTCEvents");
  8972. /**
  8973. *
  8974. * @constructor
  8975. */
  8976. function SimulcastManager() {
  8977. // Create the simulcast utilities.
  8978. this.simulcastUtils = new SimulcastUtils();
  8979. // Create remote simulcast.
  8980. this.simulcastReceiver = new SimulcastReceiver();
  8981. // Initialize local simulcast.
  8982. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  8983. // account constraints.
  8984. if (!config.enableSimulcast) {
  8985. this.simulcastSender = new NoSimulcastSender();
  8986. } else {
  8987. var isChromium = window.chrome,
  8988. vendorName = window.navigator.vendor;
  8989. if(isChromium !== null && isChromium !== undefined
  8990. /* skip opera */
  8991. && vendorName === "Google Inc."
  8992. /* skip Chromium as suggested by fippo */
  8993. && !window.navigator.appVersion.match(/Chromium\//) ) {
  8994. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  8995. if (ver > 37) {
  8996. this.simulcastSender = new NativeSimulcastSender();
  8997. } else {
  8998. this.simulcastSender = new NoSimulcastSender();
  8999. }
  9000. } else {
  9001. this.simulcastSender = new NoSimulcastSender();
  9002. }
  9003. }
  9004. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  9005. function (endpointSimulcastLayers) {
  9006. endpointSimulcastLayers.forEach(function (esl) {
  9007. var ssrc = esl.simulcastLayer.primarySSRC;
  9008. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  9009. });
  9010. });
  9011. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  9012. var ssrc = simulcastLayer.primarySSRC;
  9013. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  9014. });
  9015. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  9016. var ssrc = simulcastLayer.primarySSRC;
  9017. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  9018. });
  9019. }
  9020. /**
  9021. * Restores the simulcast groups of the remote description. In
  9022. * transformRemoteDescription we remove those in order for the set remote
  9023. * description to succeed. The focus needs the signal the groups to new
  9024. * participants.
  9025. *
  9026. * @param desc
  9027. * @returns {*}
  9028. */
  9029. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  9030. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  9031. };
  9032. /**
  9033. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9034. * either gets confused and thinks this is an FID group or, if an FID group
  9035. * is already present, it fails to set the remote description.
  9036. *
  9037. * @param desc
  9038. * @returns {*}
  9039. */
  9040. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  9041. return this.simulcastReceiver.transformRemoteDescription(desc);
  9042. };
  9043. /**
  9044. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9045. * SSRC.
  9046. *
  9047. * @param ssrc
  9048. * @returns {*}
  9049. */
  9050. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9051. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  9052. };
  9053. /**
  9054. * Returns a stream with single video track, the one currently being
  9055. * received by this endpoint.
  9056. *
  9057. * @param stream the remote simulcast stream.
  9058. * @returns {webkitMediaStream}
  9059. */
  9060. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  9061. return this.simulcastReceiver.getReceivingVideoStream(stream);
  9062. };
  9063. /**
  9064. *
  9065. *
  9066. * @param desc
  9067. * @returns {*}
  9068. */
  9069. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  9070. return this.simulcastSender.transformLocalDescription(desc);
  9071. };
  9072. /**
  9073. *
  9074. * @returns {*}
  9075. */
  9076. SimulcastManager.prototype.getLocalVideoStream = function() {
  9077. return this.simulcastSender.getLocalVideoStream();
  9078. };
  9079. /**
  9080. * GUM for simulcast.
  9081. *
  9082. * @param constraints
  9083. * @param success
  9084. * @param err
  9085. */
  9086. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  9087. this.simulcastSender.getUserMedia(constraints, success, err);
  9088. };
  9089. /**
  9090. * Prepares the local description for public usage (i.e. to be signaled
  9091. * through Jingle to the focus).
  9092. *
  9093. * @param desc
  9094. * @returns {RTCSessionDescription}
  9095. */
  9096. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  9097. return this.simulcastSender.reverseTransformLocalDescription(desc);
  9098. };
  9099. /**
  9100. * Ensures that the simulcast group is present in the answer, _if_ native
  9101. * simulcast is enabled,
  9102. *
  9103. * @param desc
  9104. * @returns {*}
  9105. */
  9106. SimulcastManager.prototype.transformAnswer = function (desc) {
  9107. return this.simulcastSender.transformAnswer(desc);
  9108. };
  9109. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  9110. return this.simulcastReceiver.getReceivingSSRC(jid);
  9111. };
  9112. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  9113. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  9114. };
  9115. /**
  9116. *
  9117. * @param lines
  9118. * @param mediatypes
  9119. * @returns {*}
  9120. */
  9121. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  9122. var sb = lines.sdp.split('\r\n');
  9123. return this.simulcastUtils.parseMedia(sb, mediatypes);
  9124. };
  9125. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  9126. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  9127. };
  9128. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  9129. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  9130. };
  9131. SimulcastManager.prototype.resetSender = function() {
  9132. if (typeof this.simulcastSender.reset === 'function'){
  9133. this.simulcastSender.reset();
  9134. }
  9135. };
  9136. var simulcast = new SimulcastManager();
  9137. module.exports = simulcast;
  9138. },{"../../service/RTC/RTCEvents":80,"./SimulcastReceiver":39,"./SimulcastSender":40,"./SimulcastUtils":41}],43:[function(require,module,exports){
  9139. /**
  9140. * Provides statistics for the local stream.
  9141. */
  9142. /**
  9143. * Size of the webaudio analizer buffer.
  9144. * @type {number}
  9145. */
  9146. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  9147. /**
  9148. * Value of the webaudio analizer smoothing time parameter.
  9149. * @type {number}
  9150. */
  9151. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  9152. /**
  9153. * Converts time domain data array to audio level.
  9154. * @param array the time domain data array.
  9155. * @returns {number} the audio level
  9156. */
  9157. function timeDomainDataToAudioLevel(samples) {
  9158. var maxVolume = 0;
  9159. var length = samples.length;
  9160. for (var i = 0; i < length; i++) {
  9161. if (maxVolume < samples[i])
  9162. maxVolume = samples[i];
  9163. }
  9164. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  9165. };
  9166. /**
  9167. * Animates audio level change
  9168. * @param newLevel the new audio level
  9169. * @param lastLevel the last audio level
  9170. * @returns {Number} the audio level to be set
  9171. */
  9172. function animateLevel(newLevel, lastLevel)
  9173. {
  9174. var value = 0;
  9175. var diff = lastLevel - newLevel;
  9176. if(diff > 0.2)
  9177. {
  9178. value = lastLevel - 0.2;
  9179. }
  9180. else if(diff < -0.4)
  9181. {
  9182. value = lastLevel + 0.4;
  9183. }
  9184. else
  9185. {
  9186. value = newLevel;
  9187. }
  9188. return parseFloat(value.toFixed(3));
  9189. }
  9190. /**
  9191. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  9192. *
  9193. * @param stream the local stream
  9194. * @param interval stats refresh interval given in ms.
  9195. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  9196. * update.
  9197. * @constructor
  9198. */
  9199. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  9200. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  9201. this.stream = stream;
  9202. this.intervalId = null;
  9203. this.intervalMilis = interval;
  9204. this.eventEmitter = eventEmitter;
  9205. this.audioLevel = 0;
  9206. this.statisticsService = statisticsService;
  9207. }
  9208. /**
  9209. * Starts the collecting the statistics.
  9210. */
  9211. LocalStatsCollector.prototype.start = function () {
  9212. if (config.disableAudioLevels || !window.AudioContext)
  9213. return;
  9214. var context = new AudioContext();
  9215. var analyser = context.createAnalyser();
  9216. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  9217. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  9218. var source = context.createMediaStreamSource(this.stream);
  9219. source.connect(analyser);
  9220. var self = this;
  9221. this.intervalId = setInterval(
  9222. function () {
  9223. var array = new Uint8Array(analyser.frequencyBinCount);
  9224. analyser.getByteTimeDomainData(array);
  9225. var audioLevel = timeDomainDataToAudioLevel(array);
  9226. if(audioLevel != self.audioLevel) {
  9227. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  9228. self.eventEmitter.emit(
  9229. "statistics.audioLevel",
  9230. self.statisticsService.LOCAL_JID,
  9231. self.audioLevel);
  9232. }
  9233. },
  9234. this.intervalMilis
  9235. );
  9236. };
  9237. /**
  9238. * Stops collecting the statistics.
  9239. */
  9240. LocalStatsCollector.prototype.stop = function () {
  9241. if (this.intervalId) {
  9242. clearInterval(this.intervalId);
  9243. this.intervalId = null;
  9244. }
  9245. };
  9246. module.exports = LocalStatsCollector;
  9247. },{}],44:[function(require,module,exports){
  9248. /* global ssrc2jid */
  9249. /* jshint -W117 */
  9250. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9251. /**
  9252. * Calculates packet lost percent using the number of lost packets and the
  9253. * number of all packet.
  9254. * @param lostPackets the number of lost packets
  9255. * @param totalPackets the number of all packets.
  9256. * @returns {number} packet loss percent
  9257. */
  9258. function calculatePacketLoss(lostPackets, totalPackets) {
  9259. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  9260. return 0;
  9261. return Math.round((lostPackets/totalPackets)*100);
  9262. }
  9263. function getStatValue(item, name) {
  9264. if(!keyMap[APP.RTC.getBrowserType()][name])
  9265. throw "The property isn't supported!";
  9266. var key = keyMap[APP.RTC.getBrowserType()][name];
  9267. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  9268. }
  9269. /**
  9270. * Peer statistics data holder.
  9271. * @constructor
  9272. */
  9273. function PeerStats()
  9274. {
  9275. this.ssrc2Loss = {};
  9276. this.ssrc2AudioLevel = {};
  9277. this.ssrc2bitrate = {};
  9278. this.ssrc2resolution = {};
  9279. }
  9280. /**
  9281. * The bandwidth
  9282. * @type {{}}
  9283. */
  9284. PeerStats.bandwidth = {};
  9285. /**
  9286. * The bit rate
  9287. * @type {{}}
  9288. */
  9289. PeerStats.bitrate = {};
  9290. /**
  9291. * The packet loss rate
  9292. * @type {{}}
  9293. */
  9294. PeerStats.packetLoss = null;
  9295. /**
  9296. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  9297. * represented by this instance.
  9298. * @param ssrc audio or video RTP stream SSRC.
  9299. * @param lossRate new packet loss rate value to be set.
  9300. */
  9301. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  9302. {
  9303. this.ssrc2Loss[ssrc] = lossRate;
  9304. };
  9305. /**
  9306. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  9307. * represented by this instance.
  9308. * @param ssrc audio or video RTP stream SSRC.
  9309. * @param resolution new resolution value to be set.
  9310. */
  9311. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  9312. {
  9313. if(resolution === null && this.ssrc2resolution[ssrc])
  9314. {
  9315. delete this.ssrc2resolution[ssrc];
  9316. }
  9317. else if(resolution !== null)
  9318. this.ssrc2resolution[ssrc] = resolution;
  9319. };
  9320. /**
  9321. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  9322. * represented by this instance.
  9323. * @param ssrc audio or video RTP stream SSRC.
  9324. * @param bitrate new bitrate value to be set.
  9325. */
  9326. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  9327. {
  9328. if(this.ssrc2bitrate[ssrc])
  9329. {
  9330. this.ssrc2bitrate[ssrc].download += bitrate.download;
  9331. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  9332. }
  9333. else {
  9334. this.ssrc2bitrate[ssrc] = bitrate;
  9335. }
  9336. };
  9337. /**
  9338. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  9339. * the stream which belongs to the peer represented by this instance.
  9340. * @param ssrc RTP stream SSRC for which current audio level value will be
  9341. * updated.
  9342. * @param audioLevel the new audio level value to be set. Value is truncated to
  9343. * fit the range from 0 to 1.
  9344. */
  9345. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  9346. {
  9347. // Range limit 0 - 1
  9348. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  9349. };
  9350. function formatAudioLevel(audioLevel) {
  9351. return Math.min(Math.max(audioLevel, 0), 1);
  9352. }
  9353. /**
  9354. * Array with the transport information.
  9355. * @type {Array}
  9356. */
  9357. PeerStats.transport = [];
  9358. /**
  9359. * <tt>StatsCollector</tt> registers for stats updates of given
  9360. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  9361. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  9362. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9363. * instance as an event source.
  9364. *
  9365. * @param peerconnection webRTC peer connection object.
  9366. * @param interval stats refresh interval given in ms.
  9367. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  9368. * called on stats update.
  9369. * @constructor
  9370. */
  9371. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  9372. {
  9373. this.peerconnection = peerconnection;
  9374. this.baselineAudioLevelsReport = null;
  9375. this.currentAudioLevelsReport = null;
  9376. this.currentStatsReport = null;
  9377. this.baselineStatsReport = null;
  9378. this.audioLevelsIntervalId = null;
  9379. this.eventEmitter = eventEmitter;
  9380. /**
  9381. * Gather PeerConnection stats once every this many milliseconds.
  9382. */
  9383. this.GATHER_INTERVAL = 15000;
  9384. /**
  9385. * Log stats via the focus once every this many milliseconds.
  9386. */
  9387. this.LOG_INTERVAL = 60000;
  9388. /**
  9389. * Gather stats and store them in this.statsToBeLogged.
  9390. */
  9391. this.gatherStatsIntervalId = null;
  9392. /**
  9393. * Send the stats already saved in this.statsToBeLogged to be logged via
  9394. * the focus.
  9395. */
  9396. this.logStatsIntervalId = null;
  9397. /**
  9398. * Stores the statistics which will be send to the focus to be logged.
  9399. */
  9400. this.statsToBeLogged =
  9401. {
  9402. timestamps: [],
  9403. stats: {}
  9404. };
  9405. // Updates stats interval
  9406. this.audioLevelsIntervalMilis = audioLevelsInterval;
  9407. this.statsIntervalId = null;
  9408. this.statsIntervalMilis = statsInterval;
  9409. // Map of jids to PeerStats
  9410. this.jid2stats = {};
  9411. }
  9412. module.exports = StatsCollector;
  9413. /**
  9414. * Stops stats updates.
  9415. */
  9416. StatsCollector.prototype.stop = function () {
  9417. if (this.audioLevelsIntervalId) {
  9418. clearInterval(this.audioLevelsIntervalId);
  9419. this.audioLevelsIntervalId = null;
  9420. }
  9421. if (this.statsIntervalId)
  9422. {
  9423. clearInterval(this.statsIntervalId);
  9424. this.statsIntervalId = null;
  9425. }
  9426. if(this.logStatsIntervalId)
  9427. {
  9428. clearInterval(this.logStatsIntervalId);
  9429. this.logStatsIntervalId = null;
  9430. }
  9431. if(this.gatherStatsIntervalId)
  9432. {
  9433. clearInterval(this.gatherStatsIntervalId);
  9434. this.gatherStatsIntervalId = null;
  9435. }
  9436. };
  9437. /**
  9438. * Callback passed to <tt>getStats</tt> method.
  9439. * @param error an error that occurred on <tt>getStats</tt> call.
  9440. */
  9441. StatsCollector.prototype.errorCallback = function (error)
  9442. {
  9443. console.error("Get stats error", error);
  9444. this.stop();
  9445. };
  9446. /**
  9447. * Starts stats updates.
  9448. */
  9449. StatsCollector.prototype.start = function ()
  9450. {
  9451. var self = this;
  9452. if(!config.disableAudioLevels) {
  9453. console.debug("set audio levels interval");
  9454. this.audioLevelsIntervalId = setInterval(
  9455. function () {
  9456. // Interval updates
  9457. self.peerconnection.getStats(
  9458. function (report) {
  9459. var results = null;
  9460. if (!report || !report.result ||
  9461. typeof report.result != 'function') {
  9462. results = report;
  9463. }
  9464. else {
  9465. results = report.result();
  9466. }
  9467. //console.error("Got interval report", results);
  9468. self.currentAudioLevelsReport = results;
  9469. self.processAudioLevelReport();
  9470. self.baselineAudioLevelsReport =
  9471. self.currentAudioLevelsReport;
  9472. },
  9473. self.errorCallback
  9474. );
  9475. },
  9476. self.audioLevelsIntervalMilis
  9477. );
  9478. }
  9479. if(!config.disableStats) {
  9480. console.debug("set stats interval");
  9481. this.statsIntervalId = setInterval(
  9482. function () {
  9483. // Interval updates
  9484. self.peerconnection.getStats(
  9485. function (report) {
  9486. var results = null;
  9487. if (!report || !report.result ||
  9488. typeof report.result != 'function') {
  9489. //firefox
  9490. results = report;
  9491. }
  9492. else {
  9493. //chrome
  9494. results = report.result();
  9495. }
  9496. //console.error("Got interval report", results);
  9497. self.currentStatsReport = results;
  9498. try {
  9499. self.processStatsReport();
  9500. }
  9501. catch (e) {
  9502. console.error("Unsupported key:" + e, e);
  9503. }
  9504. self.baselineStatsReport = self.currentStatsReport;
  9505. },
  9506. self.errorCallback
  9507. );
  9508. },
  9509. self.statsIntervalMilis
  9510. );
  9511. }
  9512. if (config.logStats) {
  9513. this.gatherStatsIntervalId = setInterval(
  9514. function () {
  9515. self.peerconnection.getStats(
  9516. function (report) {
  9517. self.addStatsToBeLogged(report.result());
  9518. },
  9519. function () {
  9520. }
  9521. );
  9522. },
  9523. this.GATHER_INTERVAL
  9524. );
  9525. this.logStatsIntervalId = setInterval(
  9526. function() { self.logStats(); },
  9527. this.LOG_INTERVAL);
  9528. }
  9529. };
  9530. /**
  9531. * Checks whether a certain record should be included in the logged statistics.
  9532. */
  9533. function acceptStat(reportId, reportType, statName) {
  9534. if (reportType == "googCandidatePair" && statName == "googChannelId")
  9535. return false;
  9536. if (reportType == "ssrc") {
  9537. if (statName == "googTrackId" ||
  9538. statName == "transportId" ||
  9539. statName == "ssrc")
  9540. return false;
  9541. }
  9542. return true;
  9543. }
  9544. /**
  9545. * Checks whether a certain record should be included in the logged statistics.
  9546. */
  9547. function acceptReport(id, type) {
  9548. if (id.substring(0, 15) == "googCertificate" ||
  9549. id.substring(0, 9) == "googTrack" ||
  9550. id.substring(0, 20) == "googLibjingleSession")
  9551. return false;
  9552. if (type == "googComponent")
  9553. return false;
  9554. return true;
  9555. }
  9556. /**
  9557. * Converts the stats to the format used for logging, and saves the data in
  9558. * this.statsToBeLogged.
  9559. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  9560. */
  9561. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  9562. var self = this;
  9563. var num_records = this.statsToBeLogged.timestamps.length;
  9564. this.statsToBeLogged.timestamps.push(new Date().getTime());
  9565. reports.map(function (report) {
  9566. if (!acceptReport(report.id, report.type))
  9567. return;
  9568. var stat = self.statsToBeLogged.stats[report.id];
  9569. if (!stat) {
  9570. stat = self.statsToBeLogged.stats[report.id] = {};
  9571. }
  9572. stat.type = report.type;
  9573. report.names().map(function (name) {
  9574. if (!acceptStat(report.id, report.type, name))
  9575. return;
  9576. var values = stat[name];
  9577. if (!values) {
  9578. values = stat[name] = [];
  9579. }
  9580. while (values.length < num_records) {
  9581. values.push(null);
  9582. }
  9583. values.push(report.stat(name));
  9584. });
  9585. });
  9586. };
  9587. StatsCollector.prototype.logStats = function () {
  9588. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  9589. return;
  9590. // Reset the stats
  9591. this.statsToBeLogged.stats = {};
  9592. this.statsToBeLogged.timestamps = [];
  9593. };
  9594. var keyMap = {};
  9595. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  9596. "ssrc": "ssrc",
  9597. "packetsReceived": "packetsReceived",
  9598. "packetsLost": "packetsLost",
  9599. "packetsSent": "packetsSent",
  9600. "bytesReceived": "bytesReceived",
  9601. "bytesSent": "bytesSent"
  9602. };
  9603. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  9604. "receiveBandwidth": "googAvailableReceiveBandwidth",
  9605. "sendBandwidth": "googAvailableSendBandwidth",
  9606. "remoteAddress": "googRemoteAddress",
  9607. "transportType": "googTransportType",
  9608. "localAddress": "googLocalAddress",
  9609. "activeConnection": "googActiveConnection",
  9610. "ssrc": "ssrc",
  9611. "packetsReceived": "packetsReceived",
  9612. "packetsSent": "packetsSent",
  9613. "packetsLost": "packetsLost",
  9614. "bytesReceived": "bytesReceived",
  9615. "bytesSent": "bytesSent",
  9616. "googFrameHeightReceived": "googFrameHeightReceived",
  9617. "googFrameWidthReceived": "googFrameWidthReceived",
  9618. "googFrameHeightSent": "googFrameHeightSent",
  9619. "googFrameWidthSent": "googFrameWidthSent",
  9620. "audioInputLevel": "audioInputLevel",
  9621. "audioOutputLevel": "audioOutputLevel"
  9622. };
  9623. /**
  9624. * Stats processing logic.
  9625. */
  9626. StatsCollector.prototype.processStatsReport = function () {
  9627. if (!this.baselineStatsReport) {
  9628. return;
  9629. }
  9630. for (var idx in this.currentStatsReport) {
  9631. var now = this.currentStatsReport[idx];
  9632. try {
  9633. if (getStatValue(now, 'receiveBandwidth') ||
  9634. getStatValue(now, 'sendBandwidth')) {
  9635. PeerStats.bandwidth = {
  9636. "download": Math.round(
  9637. (getStatValue(now, 'receiveBandwidth')) / 1000),
  9638. "upload": Math.round(
  9639. (getStatValue(now, 'sendBandwidth')) / 1000)
  9640. };
  9641. }
  9642. }
  9643. catch(e){/*not supported*/}
  9644. if(now.type == 'googCandidatePair')
  9645. {
  9646. var ip, type, localIP, active;
  9647. try {
  9648. ip = getStatValue(now, 'remoteAddress');
  9649. type = getStatValue(now, "transportType");
  9650. localIP = getStatValue(now, "localAddress");
  9651. active = getStatValue(now, "activeConnection");
  9652. }
  9653. catch(e){/*not supported*/}
  9654. if(!ip || !type || !localIP || active != "true")
  9655. continue;
  9656. var addressSaved = false;
  9657. for(var i = 0; i < PeerStats.transport.length; i++)
  9658. {
  9659. if(PeerStats.transport[i].ip == ip &&
  9660. PeerStats.transport[i].type == type &&
  9661. PeerStats.transport[i].localip == localIP)
  9662. {
  9663. addressSaved = true;
  9664. }
  9665. }
  9666. if(addressSaved)
  9667. continue;
  9668. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  9669. continue;
  9670. }
  9671. if(now.type == "candidatepair")
  9672. {
  9673. if(now.state == "succeeded")
  9674. continue;
  9675. var local = this.currentStatsReport[now.localCandidateId];
  9676. var remote = this.currentStatsReport[now.remoteCandidateId];
  9677. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  9678. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  9679. }
  9680. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  9681. now.type != "inboundrtp") {
  9682. continue;
  9683. }
  9684. var before = this.baselineStatsReport[idx];
  9685. if (!before) {
  9686. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9687. continue;
  9688. }
  9689. var ssrc = getStatValue(now, 'ssrc');
  9690. if(!ssrc)
  9691. continue;
  9692. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9693. if (!jid && (Date.now() - now.timestamp) < 3000) {
  9694. console.warn("No jid for ssrc: " + ssrc);
  9695. continue;
  9696. }
  9697. var jidStats = this.jid2stats[jid];
  9698. if (!jidStats) {
  9699. jidStats = new PeerStats();
  9700. this.jid2stats[jid] = jidStats;
  9701. }
  9702. var isDownloadStream = true;
  9703. var key = 'packetsReceived';
  9704. if (!getStatValue(now, key))
  9705. {
  9706. isDownloadStream = false;
  9707. key = 'packetsSent';
  9708. if (!getStatValue(now, key))
  9709. {
  9710. console.warn("No packetsReceived nor packetSent stat found");
  9711. continue;
  9712. }
  9713. }
  9714. var packetsNow = getStatValue(now, key);
  9715. if(!packetsNow || packetsNow < 0)
  9716. packetsNow = 0;
  9717. var packetsBefore = getStatValue(before, key);
  9718. if(!packetsBefore || packetsBefore < 0)
  9719. packetsBefore = 0;
  9720. var packetRate = packetsNow - packetsBefore;
  9721. if(!packetRate || packetRate < 0)
  9722. packetRate = 0;
  9723. var currentLoss = getStatValue(now, 'packetsLost');
  9724. if(!currentLoss || currentLoss < 0)
  9725. currentLoss = 0;
  9726. var previousLoss = getStatValue(before, 'packetsLost');
  9727. if(!previousLoss || previousLoss < 0)
  9728. previousLoss = 0;
  9729. var lossRate = currentLoss - previousLoss;
  9730. if(!lossRate || lossRate < 0)
  9731. lossRate = 0;
  9732. var packetsTotal = (packetRate + lossRate);
  9733. jidStats.setSsrcLoss(ssrc,
  9734. {"packetsTotal": packetsTotal,
  9735. "packetsLost": lossRate,
  9736. "isDownloadStream": isDownloadStream});
  9737. var bytesReceived = 0, bytesSent = 0;
  9738. if(getStatValue(now, "bytesReceived"))
  9739. {
  9740. bytesReceived = getStatValue(now, "bytesReceived") -
  9741. getStatValue(before, "bytesReceived");
  9742. }
  9743. if(getStatValue(now, "bytesSent"))
  9744. {
  9745. bytesSent = getStatValue(now, "bytesSent") -
  9746. getStatValue(before, "bytesSent");
  9747. }
  9748. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  9749. if(bytesReceived <= 0 || time <= 0)
  9750. {
  9751. bytesReceived = 0;
  9752. }
  9753. else
  9754. {
  9755. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  9756. }
  9757. if(bytesSent <= 0 || time <= 0)
  9758. {
  9759. bytesSent = 0;
  9760. }
  9761. else
  9762. {
  9763. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  9764. }
  9765. jidStats.setSsrcBitrate(ssrc, {
  9766. "download": bytesReceived,
  9767. "upload": bytesSent});
  9768. var resolution = {height: null, width: null};
  9769. try {
  9770. if (getStatValue(now, "googFrameHeightReceived") &&
  9771. getStatValue(now, "googFrameWidthReceived")) {
  9772. resolution.height = getStatValue(now, "googFrameHeightReceived");
  9773. resolution.width = getStatValue(now, "googFrameWidthReceived");
  9774. }
  9775. else if (getStatValue(now, "googFrameHeightSent") &&
  9776. getStatValue(now, "googFrameWidthSent")) {
  9777. resolution.height = getStatValue(now, "googFrameHeightSent");
  9778. resolution.width = getStatValue(now, "googFrameWidthSent");
  9779. }
  9780. }
  9781. catch(e){/*not supported*/}
  9782. if(resolution.height && resolution.width)
  9783. {
  9784. jidStats.setSsrcResolution(ssrc, resolution);
  9785. }
  9786. else
  9787. {
  9788. jidStats.setSsrcResolution(ssrc, null);
  9789. }
  9790. }
  9791. var self = this;
  9792. // Jid stats
  9793. var totalPackets = {download: 0, upload: 0};
  9794. var lostPackets = {download: 0, upload: 0};
  9795. var bitrateDownload = 0;
  9796. var bitrateUpload = 0;
  9797. var resolutions = {};
  9798. Object.keys(this.jid2stats).forEach(
  9799. function (jid)
  9800. {
  9801. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  9802. function (ssrc)
  9803. {
  9804. var type = "upload";
  9805. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  9806. type = "download";
  9807. totalPackets[type] +=
  9808. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  9809. lostPackets[type] +=
  9810. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  9811. }
  9812. );
  9813. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  9814. function (ssrc) {
  9815. bitrateDownload +=
  9816. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  9817. bitrateUpload +=
  9818. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  9819. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  9820. }
  9821. );
  9822. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  9823. }
  9824. );
  9825. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  9826. PeerStats.packetLoss = {
  9827. total:
  9828. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  9829. totalPackets.download + totalPackets.upload),
  9830. download:
  9831. calculatePacketLoss(lostPackets.download, totalPackets.download),
  9832. upload:
  9833. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  9834. };
  9835. this.eventEmitter.emit("statistics.connectionstats",
  9836. {
  9837. "bitrate": PeerStats.bitrate,
  9838. "packetLoss": PeerStats.packetLoss,
  9839. "bandwidth": PeerStats.bandwidth,
  9840. "resolution": resolutions,
  9841. "transport": PeerStats.transport
  9842. });
  9843. PeerStats.transport = [];
  9844. };
  9845. /**
  9846. * Stats processing logic.
  9847. */
  9848. StatsCollector.prototype.processAudioLevelReport = function ()
  9849. {
  9850. if (!this.baselineAudioLevelsReport)
  9851. {
  9852. return;
  9853. }
  9854. for (var idx in this.currentAudioLevelsReport)
  9855. {
  9856. var now = this.currentAudioLevelsReport[idx];
  9857. if (now.type != 'ssrc')
  9858. {
  9859. continue;
  9860. }
  9861. var before = this.baselineAudioLevelsReport[idx];
  9862. if (!before)
  9863. {
  9864. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9865. continue;
  9866. }
  9867. var ssrc = getStatValue(now, 'ssrc');
  9868. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9869. if (!jid && (Date.now() - now.timestamp) < 3000)
  9870. {
  9871. console.warn("No jid for ssrc: " + ssrc);
  9872. continue;
  9873. }
  9874. var jidStats = this.jid2stats[jid];
  9875. if (!jidStats)
  9876. {
  9877. jidStats = new PeerStats();
  9878. this.jid2stats[jid] = jidStats;
  9879. }
  9880. // Audio level
  9881. var audioLevel = null;
  9882. try {
  9883. audioLevel = getStatValue(now, 'audioInputLevel');
  9884. if (!audioLevel)
  9885. audioLevel = getStatValue(now, 'audioOutputLevel');
  9886. }
  9887. catch(e) {/*not supported*/
  9888. console.warn("Audio Levels are not available in the statistics.");
  9889. clearInterval(this.audioLevelsIntervalId);
  9890. return;
  9891. }
  9892. if (audioLevel)
  9893. {
  9894. // TODO: can't find specs about what this value really is,
  9895. // but it seems to vary between 0 and around 32k.
  9896. audioLevel = audioLevel / 32767;
  9897. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  9898. if(jid != APP.xmpp.myJid())
  9899. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  9900. }
  9901. }
  9902. };
  9903. },{"../../service/RTC/RTCBrowserType":79}],45:[function(require,module,exports){
  9904. /**
  9905. * Created by hristo on 8/4/14.
  9906. */
  9907. var LocalStats = require("./LocalStatsCollector.js");
  9908. var RTPStats = require("./RTPStatsCollector.js");
  9909. var EventEmitter = require("events");
  9910. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  9911. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9912. var eventEmitter = new EventEmitter();
  9913. var localStats = null;
  9914. var rtpStats = null;
  9915. function stopLocal()
  9916. {
  9917. if(localStats)
  9918. {
  9919. localStats.stop();
  9920. localStats = null;
  9921. }
  9922. }
  9923. function stopRemote()
  9924. {
  9925. if(rtpStats)
  9926. {
  9927. rtpStats.stop();
  9928. eventEmitter.emit("statistics.stop");
  9929. rtpStats = null;
  9930. }
  9931. }
  9932. function startRemoteStats (peerconnection) {
  9933. if(rtpStats)
  9934. {
  9935. rtpStats.stop();
  9936. rtpStats = null;
  9937. }
  9938. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  9939. rtpStats.start();
  9940. }
  9941. function onStreamCreated(stream)
  9942. {
  9943. if(stream.getOriginalStream().getAudioTracks().length === 0)
  9944. return;
  9945. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  9946. eventEmitter);
  9947. localStats.start();
  9948. }
  9949. function onDisposeConference(onUnload) {
  9950. stopRemote();
  9951. if(onUnload) {
  9952. stopLocal();
  9953. eventEmitter.removeAllListeners();
  9954. }
  9955. }
  9956. var statistics =
  9957. {
  9958. /**
  9959. * Indicates that this audio level is for local jid.
  9960. * @type {string}
  9961. */
  9962. LOCAL_JID: 'local',
  9963. addAudioLevelListener: function(listener)
  9964. {
  9965. eventEmitter.on("statistics.audioLevel", listener);
  9966. },
  9967. removeAudioLevelListener: function(listener)
  9968. {
  9969. eventEmitter.removeListener("statistics.audioLevel", listener);
  9970. },
  9971. addConnectionStatsListener: function(listener)
  9972. {
  9973. eventEmitter.on("statistics.connectionstats", listener);
  9974. },
  9975. removeConnectionStatsListener: function(listener)
  9976. {
  9977. eventEmitter.removeListener("statistics.connectionstats", listener);
  9978. },
  9979. addRemoteStatsStopListener: function(listener)
  9980. {
  9981. eventEmitter.on("statistics.stop", listener);
  9982. },
  9983. removeRemoteStatsStopListener: function(listener)
  9984. {
  9985. eventEmitter.removeListener("statistics.stop", listener);
  9986. },
  9987. stop: function () {
  9988. stopLocal();
  9989. stopRemote();
  9990. if(eventEmitter)
  9991. {
  9992. eventEmitter.removeAllListeners();
  9993. }
  9994. },
  9995. stopRemoteStatistics: function()
  9996. {
  9997. stopRemote();
  9998. },
  9999. start: function () {
  10000. APP.RTC.addStreamListener(onStreamCreated,
  10001. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10002. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10003. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10004. startRemoteStats(event.peerconnection);
  10005. });
  10006. }
  10007. };
  10008. module.exports = statistics;
  10009. },{"../../service/RTC/StreamEventTypes.js":82,"../../service/xmpp/XMPPEvents":88,"./LocalStatsCollector.js":43,"./RTPStatsCollector.js":44,"events":89}],46:[function(require,module,exports){
  10010. var i18n = require("i18next-client");
  10011. var languages = require("../../service/translation/languages");
  10012. var Settings = require("../settings/Settings");
  10013. var DEFAULT_LANG = languages.EN;
  10014. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10015. return value.replace("__app__", interfaceConfig.APP_NAME);
  10016. });
  10017. var defaultOptions = {
  10018. detectLngQS: "lang",
  10019. useCookie: false,
  10020. fallbackLng: DEFAULT_LANG,
  10021. load: "unspecific",
  10022. resGetPath: 'lang/__ns__-__lng__.json',
  10023. ns: {
  10024. namespaces: ['main', 'languages'],
  10025. defaultNs: 'main'
  10026. },
  10027. lngWhitelist : languages.getLanguages(),
  10028. fallbackOnNull: true,
  10029. fallbackOnEmpty: true,
  10030. useDataAttrOptions: true,
  10031. defaultValueFromContent: false,
  10032. app: interfaceConfig.APP_NAME,
  10033. getAsync: false,
  10034. defaultValueFromContent: false,
  10035. customLoad: function(lng, ns, options, done) {
  10036. var resPath = "lang/__ns__-__lng__.json";
  10037. if(lng === languages.EN)
  10038. resPath = "lang/__ns__.json";
  10039. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10040. i18n.functions.ajax({
  10041. url: url,
  10042. success: function(data, status, xhr) {
  10043. i18n.functions.log('loaded: ' + url);
  10044. done(null, data);
  10045. },
  10046. error : function(xhr, status, error) {
  10047. if ((status && status == 200) ||
  10048. (xhr && xhr.status && xhr.status == 200)) {
  10049. // file loaded but invalid json, stop waste time !
  10050. i18n.functions.error('There is a typo in: ' + url);
  10051. } else if ((status && status == 404) ||
  10052. (xhr && xhr.status && xhr.status == 404)) {
  10053. i18n.functions.log('Does not exist: ' + url);
  10054. } else {
  10055. var theStatus = status ? status :
  10056. ((xhr && xhr.status) ? xhr.status : null);
  10057. i18n.functions.log(theStatus + ' when loading ' + url);
  10058. }
  10059. done(error, {});
  10060. },
  10061. dataType: "json",
  10062. async : options.getAsync
  10063. });
  10064. }
  10065. // options for caching
  10066. // useLocalStorage: true,
  10067. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10068. };
  10069. function initCompleted(t)
  10070. {
  10071. $("[data-i18n]").i18n();
  10072. }
  10073. function checkForParameter() {
  10074. var query = window.location.search.substring(1);
  10075. var vars = query.split("&");
  10076. for (var i=0;i<vars.length;i++) {
  10077. var pair = vars[i].split("=");
  10078. if(pair[0] == "lang")
  10079. {
  10080. return pair[1];
  10081. }
  10082. }
  10083. return null;
  10084. }
  10085. module.exports = {
  10086. init: function (lang) {
  10087. var options = defaultOptions;
  10088. if(!lang)
  10089. {
  10090. lang = checkForParameter();
  10091. if(!lang)
  10092. {
  10093. var settings = Settings.getSettings();
  10094. if(settings)
  10095. lang = settings.language;
  10096. }
  10097. }
  10098. if(lang) {
  10099. options.lng = lang;
  10100. }
  10101. i18n.init(options, initCompleted);
  10102. },
  10103. translateString: function (key, options) {
  10104. return i18n.t(key, options);
  10105. },
  10106. setLanguage: function (lang) {
  10107. if(!lang)
  10108. lang = DEFAULT_LANG;
  10109. i18n.setLng(lang, defaultOptions, initCompleted);
  10110. },
  10111. getCurrentLanguage: function () {
  10112. return i18n.lng();
  10113. },
  10114. translateElement: function (selector) {
  10115. selector.i18n();
  10116. },
  10117. generateTranslatonHTML: function (key, options) {
  10118. var str = "<span data-i18n=\"" + key + "\"";
  10119. if(options)
  10120. {
  10121. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10122. }
  10123. str += ">";
  10124. str += this.translateString(key, options);
  10125. str += "</span>";
  10126. return str;
  10127. }
  10128. };
  10129. },{"../../service/translation/languages":87,"../settings/Settings":37,"i18next-client":61}],47:[function(require,module,exports){
  10130. /* jshint -W117 */
  10131. var TraceablePeerConnection = require("./TraceablePeerConnection");
  10132. var SDPDiffer = require("./SDPDiffer");
  10133. var SDPUtil = require("./SDPUtil");
  10134. var SDP = require("./SDP");
  10135. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10136. // Jingle stuff
  10137. function JingleSession(me, sid, connection, service) {
  10138. this.me = me;
  10139. this.sid = sid;
  10140. this.connection = connection;
  10141. this.initiator = null;
  10142. this.responder = null;
  10143. this.isInitiator = null;
  10144. this.peerjid = null;
  10145. this.state = null;
  10146. this.localSDP = null;
  10147. this.remoteSDP = null;
  10148. this.relayedStreams = [];
  10149. this.startTime = null;
  10150. this.stopTime = null;
  10151. this.media_constraints = null;
  10152. this.pc_constraints = null;
  10153. this.ice_config = {};
  10154. this.drip_container = [];
  10155. this.service = service;
  10156. this.usetrickle = true;
  10157. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  10158. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  10159. this.hadstuncandidate = false;
  10160. this.hadturncandidate = false;
  10161. this.lasticecandidate = false;
  10162. this.statsinterval = null;
  10163. this.reason = null;
  10164. this.addssrc = [];
  10165. this.removessrc = [];
  10166. this.pendingop = null;
  10167. this.switchstreams = false;
  10168. this.wait = true;
  10169. this.localStreamsSSRC = null;
  10170. /**
  10171. * The indicator which determines whether the (local) video has been muted
  10172. * in response to a user command in contrast to an automatic decision made
  10173. * by the application logic.
  10174. */
  10175. this.videoMuteByUser = false;
  10176. }
  10177. //TODO: this array must be removed when firefox implement multistream support
  10178. JingleSession.notReceivedSSRCs = [];
  10179. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  10180. var self = this;
  10181. if (this.state !== null) {
  10182. console.error('attempt to initiate on session ' + this.sid +
  10183. 'in state ' + this.state);
  10184. return;
  10185. }
  10186. this.isInitiator = isInitiator;
  10187. this.state = 'pending';
  10188. this.initiator = isInitiator ? this.me : peerjid;
  10189. this.responder = !isInitiator ? this.me : peerjid;
  10190. this.peerjid = peerjid;
  10191. this.hadstuncandidate = false;
  10192. this.hadturncandidate = false;
  10193. this.lasticecandidate = false;
  10194. this.peerconnection
  10195. = new TraceablePeerConnection(
  10196. this.connection.jingle.ice_config,
  10197. this.connection.jingle.pc_constraints );
  10198. this.peerconnection.onicecandidate = function (event) {
  10199. self.sendIceCandidate(event.candidate);
  10200. };
  10201. this.peerconnection.onaddstream = function (event) {
  10202. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  10203. self.remoteStreamAdded(event);
  10204. };
  10205. this.peerconnection.onremovestream = function (event) {
  10206. // Remove the stream from remoteStreams
  10207. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  10208. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  10209. };
  10210. this.peerconnection.onsignalingstatechange = function (event) {
  10211. if (!(self && self.peerconnection)) return;
  10212. };
  10213. this.peerconnection.oniceconnectionstatechange = function (event) {
  10214. if (!(self && self.peerconnection)) return;
  10215. switch (self.peerconnection.iceConnectionState) {
  10216. case 'connected':
  10217. this.startTime = new Date();
  10218. break;
  10219. case 'disconnected':
  10220. this.stopTime = new Date();
  10221. break;
  10222. }
  10223. onIceConnectionStateChange(self.sid, self);
  10224. };
  10225. // add any local and relayed stream
  10226. APP.RTC.localStreams.forEach(function(stream) {
  10227. self.peerconnection.addStream(stream.getOriginalStream());
  10228. });
  10229. this.relayedStreams.forEach(function(stream) {
  10230. self.peerconnection.addStream(stream);
  10231. });
  10232. };
  10233. function onIceConnectionStateChange(sid, session) {
  10234. switch (session.peerconnection.iceConnectionState) {
  10235. case 'checking':
  10236. session.timeChecking = (new Date()).getTime();
  10237. session.firstconnect = true;
  10238. break;
  10239. case 'completed': // on caller side
  10240. case 'connected':
  10241. if (session.firstconnect) {
  10242. session.firstconnect = false;
  10243. var metadata = {};
  10244. metadata.setupTime
  10245. = (new Date()).getTime() - session.timeChecking;
  10246. session.peerconnection.getStats(function (res) {
  10247. if(res && res.result) {
  10248. res.result().forEach(function (report) {
  10249. if (report.type == 'googCandidatePair' &&
  10250. report.stat('googActiveConnection') == 'true') {
  10251. metadata.localCandidateType
  10252. = report.stat('googLocalCandidateType');
  10253. metadata.remoteCandidateType
  10254. = report.stat('googRemoteCandidateType');
  10255. // log pair as well so we can get nice pie
  10256. // charts
  10257. metadata.candidatePair
  10258. = report.stat('googLocalCandidateType') +
  10259. ';' +
  10260. report.stat('googRemoteCandidateType');
  10261. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  10262. {
  10263. metadata.ipv6 = true;
  10264. }
  10265. }
  10266. });
  10267. }
  10268. });
  10269. }
  10270. break;
  10271. }
  10272. }
  10273. JingleSession.prototype.accept = function () {
  10274. var self = this;
  10275. this.state = 'active';
  10276. var pranswer = this.peerconnection.localDescription;
  10277. if (!pranswer || pranswer.type != 'pranswer') {
  10278. return;
  10279. }
  10280. console.log('going from pranswer to answer');
  10281. if (this.usetrickle) {
  10282. // remove candidates already sent from session-accept
  10283. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  10284. for (var i = 0; i < lines.length; i++) {
  10285. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  10286. }
  10287. }
  10288. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  10289. // FIXME: change any inactive to sendrecv or whatever they were originally
  10290. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  10291. }
  10292. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  10293. var prsdp = new SDP(pranswer.sdp);
  10294. var accept = $iq({to: this.peerjid,
  10295. type: 'set'})
  10296. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10297. action: 'session-accept',
  10298. initiator: this.initiator,
  10299. responder: this.responder,
  10300. sid: this.sid });
  10301. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10302. var sdp = this.peerconnection.localDescription.sdp;
  10303. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  10304. // FIXME: change any inactive to sendrecv or whatever they were originally
  10305. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  10306. }
  10307. var self = this;
  10308. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  10309. function () {
  10310. //console.log('setLocalDescription success');
  10311. self.setLocalDescription();
  10312. self.connection.sendIQ(accept,
  10313. function () {
  10314. var ack = {};
  10315. ack.source = 'answer';
  10316. $(document).trigger('ack.jingle', [self.sid, ack]);
  10317. },
  10318. function (stanza) {
  10319. var error = ($(stanza).find('error').length) ? {
  10320. code: $(stanza).find('error').attr('code'),
  10321. reason: $(stanza).find('error :first')[0].tagName
  10322. }:{};
  10323. error.source = 'answer';
  10324. JingleSession.onJingleError(self.sid, error);
  10325. },
  10326. 10000);
  10327. },
  10328. function (e) {
  10329. console.error('setLocalDescription failed', e);
  10330. }
  10331. );
  10332. };
  10333. JingleSession.prototype.terminate = function (reason) {
  10334. this.state = 'ended';
  10335. this.reason = reason;
  10336. this.peerconnection.close();
  10337. if (this.statsinterval !== null) {
  10338. window.clearInterval(this.statsinterval);
  10339. this.statsinterval = null;
  10340. }
  10341. };
  10342. JingleSession.prototype.active = function () {
  10343. return this.state == 'active';
  10344. };
  10345. JingleSession.prototype.sendIceCandidate = function (candidate) {
  10346. var self = this;
  10347. if (candidate && !this.lasticecandidate) {
  10348. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  10349. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  10350. if (!(ice && jcand)) {
  10351. console.error('failed to get ice && jcand');
  10352. return;
  10353. }
  10354. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10355. if (jcand.type === 'srflx') {
  10356. this.hadstuncandidate = true;
  10357. } else if (jcand.type === 'relay') {
  10358. this.hadturncandidate = true;
  10359. }
  10360. if (this.usetrickle) {
  10361. if (this.usedrip) {
  10362. if (this.drip_container.length === 0) {
  10363. // start 20ms callout
  10364. window.setTimeout(function () {
  10365. if (self.drip_container.length === 0) return;
  10366. self.sendIceCandidates(self.drip_container);
  10367. self.drip_container = [];
  10368. }, 20);
  10369. }
  10370. this.drip_container.push(candidate);
  10371. return;
  10372. } else {
  10373. self.sendIceCandidate([candidate]);
  10374. }
  10375. }
  10376. } else {
  10377. //console.log('sendIceCandidate: last candidate.');
  10378. if (!this.usetrickle) {
  10379. //console.log('should send full offer now...');
  10380. var init = $iq({to: this.peerjid,
  10381. type: 'set'})
  10382. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10383. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  10384. initiator: this.initiator,
  10385. sid: this.sid});
  10386. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  10387. var self = this;
  10388. var sendJingle = function (ssrc) {
  10389. if(!ssrc)
  10390. ssrc = {};
  10391. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  10392. self.connection.sendIQ(init,
  10393. function () {
  10394. //console.log('session initiate ack');
  10395. var ack = {};
  10396. ack.source = 'offer';
  10397. $(document).trigger('ack.jingle', [self.sid, ack]);
  10398. },
  10399. function (stanza) {
  10400. self.state = 'error';
  10401. self.peerconnection.close();
  10402. var error = ($(stanza).find('error').length) ? {
  10403. code: $(stanza).find('error').attr('code'),
  10404. reason: $(stanza).find('error :first')[0].tagName,
  10405. }:{};
  10406. error.source = 'offer';
  10407. JingleSession.onJingleError(self.sid, error);
  10408. },
  10409. 10000);
  10410. }
  10411. sendJingle();
  10412. }
  10413. this.lasticecandidate = true;
  10414. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  10415. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  10416. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  10417. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  10418. }
  10419. }
  10420. };
  10421. JingleSession.prototype.sendIceCandidates = function (candidates) {
  10422. console.log('sendIceCandidates', candidates);
  10423. var cand = $iq({to: this.peerjid, type: 'set'})
  10424. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10425. action: 'transport-info',
  10426. initiator: this.initiator,
  10427. sid: this.sid});
  10428. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  10429. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  10430. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  10431. if (cands.length > 0) {
  10432. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  10433. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10434. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  10435. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  10436. }).c('transport', ice);
  10437. for (var i = 0; i < cands.length; i++) {
  10438. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  10439. }
  10440. // add fingerprint
  10441. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  10442. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  10443. tmp.required = true;
  10444. cand.c(
  10445. 'fingerprint',
  10446. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  10447. .t(tmp.fingerprint);
  10448. delete tmp.fingerprint;
  10449. cand.attrs(tmp);
  10450. cand.up();
  10451. }
  10452. cand.up(); // transport
  10453. cand.up(); // content
  10454. }
  10455. }
  10456. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  10457. //console.log('was this the last candidate', this.lasticecandidate);
  10458. this.connection.sendIQ(cand,
  10459. function () {
  10460. var ack = {};
  10461. ack.source = 'transportinfo';
  10462. $(document).trigger('ack.jingle', [this.sid, ack]);
  10463. },
  10464. function (stanza) {
  10465. var error = ($(stanza).find('error').length) ? {
  10466. code: $(stanza).find('error').attr('code'),
  10467. reason: $(stanza).find('error :first')[0].tagName,
  10468. }:{};
  10469. error.source = 'transportinfo';
  10470. JingleSession.onJingleError(this.sid, error);
  10471. },
  10472. 10000);
  10473. };
  10474. JingleSession.prototype.sendOffer = function () {
  10475. //console.log('sendOffer...');
  10476. var self = this;
  10477. this.peerconnection.createOffer(function (sdp) {
  10478. self.createdOffer(sdp);
  10479. },
  10480. function (e) {
  10481. console.error('createOffer failed', e);
  10482. },
  10483. this.media_constraints
  10484. );
  10485. };
  10486. JingleSession.prototype.createdOffer = function (sdp) {
  10487. //console.log('createdOffer', sdp);
  10488. var self = this;
  10489. this.localSDP = new SDP(sdp.sdp);
  10490. //this.localSDP.mangle();
  10491. var sendJingle = function () {
  10492. var init = $iq({to: this.peerjid,
  10493. type: 'set'})
  10494. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10495. action: 'session-initiate',
  10496. initiator: this.initiator,
  10497. sid: this.sid});
  10498. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10499. self.connection.sendIQ(init,
  10500. function () {
  10501. var ack = {};
  10502. ack.source = 'offer';
  10503. $(document).trigger('ack.jingle', [self.sid, ack]);
  10504. },
  10505. function (stanza) {
  10506. self.state = 'error';
  10507. self.peerconnection.close();
  10508. var error = ($(stanza).find('error').length) ? {
  10509. code: $(stanza).find('error').attr('code'),
  10510. reason: $(stanza).find('error :first')[0].tagName,
  10511. }:{};
  10512. error.source = 'offer';
  10513. JingleSession.onJingleError(self.sid, error);
  10514. },
  10515. 10000);
  10516. }
  10517. sdp.sdp = this.localSDP.raw;
  10518. this.peerconnection.setLocalDescription(sdp,
  10519. function () {
  10520. if(self.usetrickle)
  10521. {
  10522. sendJingle();
  10523. }
  10524. self.setLocalDescription();
  10525. //console.log('setLocalDescription success');
  10526. },
  10527. function (e) {
  10528. console.error('setLocalDescription failed', e);
  10529. }
  10530. );
  10531. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10532. for (var i = 0; i < cands.length; i++) {
  10533. var cand = SDPUtil.parse_icecandidate(cands[i]);
  10534. if (cand.type == 'srflx') {
  10535. this.hadstuncandidate = true;
  10536. } else if (cand.type == 'relay') {
  10537. this.hadturncandidate = true;
  10538. }
  10539. }
  10540. };
  10541. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  10542. //console.log('setting remote description... ', desctype);
  10543. this.remoteSDP = new SDP('');
  10544. this.remoteSDP.fromJingle(elem);
  10545. if (this.peerconnection.remoteDescription !== null) {
  10546. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  10547. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  10548. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  10549. for (var i = 0; i < pranswer.media.length; i++) {
  10550. // make sure we have ice ufrag and pwd
  10551. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  10552. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  10553. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  10554. } else {
  10555. console.warn('no ice ufrag?');
  10556. }
  10557. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  10558. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  10559. } else {
  10560. console.warn('no ice pwd?');
  10561. }
  10562. }
  10563. // copy over candidates
  10564. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  10565. for (var j = 0; j < lines.length; j++) {
  10566. this.remoteSDP.media[i] += lines[j] + '\r\n';
  10567. }
  10568. }
  10569. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10570. }
  10571. }
  10572. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  10573. this.peerconnection.setRemoteDescription(remotedesc,
  10574. function () {
  10575. //console.log('setRemoteDescription success');
  10576. },
  10577. function (e) {
  10578. console.error('setRemoteDescription error', e);
  10579. JingleSession.onJingleFatalError(self, e);
  10580. }
  10581. );
  10582. };
  10583. JingleSession.prototype.addIceCandidate = function (elem) {
  10584. var self = this;
  10585. if (this.peerconnection.signalingState == 'closed') {
  10586. return;
  10587. }
  10588. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  10589. console.log('trickle ice candidate arriving before session accept...');
  10590. // create a PRANSWER for setRemoteDescription
  10591. if (!this.remoteSDP) {
  10592. var cobbled = 'v=0\r\n' +
  10593. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  10594. 's=-\r\n' +
  10595. 't=0 0\r\n';
  10596. // first, take some things from the local description
  10597. for (var i = 0; i < this.localSDP.media.length; i++) {
  10598. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  10599. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  10600. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  10601. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  10602. }
  10603. cobbled += 'a=inactive\r\n';
  10604. }
  10605. this.remoteSDP = new SDP(cobbled);
  10606. }
  10607. // then add things like ice and dtls from remote candidate
  10608. elem.each(function () {
  10609. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  10610. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10611. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10612. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  10613. var tmp = $(this).find('transport');
  10614. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  10615. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  10616. tmp = $(this).find('transport>fingerprint');
  10617. if (tmp.length) {
  10618. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  10619. } else {
  10620. console.log('no dtls fingerprint (webrtc issue #1718?)');
  10621. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  10622. }
  10623. break;
  10624. }
  10625. }
  10626. }
  10627. });
  10628. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10629. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  10630. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  10631. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  10632. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  10633. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  10634. }).length == this.remoteSDP.media.length;
  10635. if (iscomplete) {
  10636. console.log('setting pranswer');
  10637. try {
  10638. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  10639. function() {
  10640. },
  10641. function(e) {
  10642. console.log('setRemoteDescription pranswer failed', e.toString());
  10643. });
  10644. } catch (e) {
  10645. console.error('setting pranswer failed', e);
  10646. }
  10647. } else {
  10648. //console.log('not yet setting pranswer');
  10649. }
  10650. }
  10651. // operate on each content element
  10652. elem.each(function () {
  10653. // would love to deactivate this, but firefox still requires it
  10654. var idx = -1;
  10655. var i;
  10656. for (i = 0; i < self.remoteSDP.media.length; i++) {
  10657. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10658. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10659. idx = i;
  10660. break;
  10661. }
  10662. }
  10663. if (idx == -1) { // fall back to localdescription
  10664. for (i = 0; i < self.localSDP.media.length; i++) {
  10665. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10666. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10667. idx = i;
  10668. break;
  10669. }
  10670. }
  10671. }
  10672. var name = $(this).attr('name');
  10673. // TODO: check ice-pwd and ice-ufrag?
  10674. $(this).find('transport>candidate').each(function () {
  10675. var line, candidate;
  10676. line = SDPUtil.candidateFromJingle(this);
  10677. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  10678. sdpMid: name,
  10679. candidate: line});
  10680. try {
  10681. self.peerconnection.addIceCandidate(candidate);
  10682. } catch (e) {
  10683. console.error('addIceCandidate failed', e.toString(), line);
  10684. }
  10685. });
  10686. });
  10687. };
  10688. JingleSession.prototype.sendAnswer = function (provisional) {
  10689. //console.log('createAnswer', provisional);
  10690. var self = this;
  10691. this.peerconnection.createAnswer(
  10692. function (sdp) {
  10693. self.createdAnswer(sdp, provisional);
  10694. },
  10695. function (e) {
  10696. console.error('createAnswer failed', e);
  10697. },
  10698. this.media_constraints
  10699. );
  10700. };
  10701. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  10702. //console.log('createAnswer callback');
  10703. var self = this;
  10704. this.localSDP = new SDP(sdp.sdp);
  10705. //this.localSDP.mangle();
  10706. this.usepranswer = provisional === true;
  10707. if (this.usetrickle) {
  10708. if (this.usepranswer) {
  10709. sdp.type = 'pranswer';
  10710. for (var i = 0; i < this.localSDP.media.length; i++) {
  10711. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  10712. }
  10713. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  10714. }
  10715. }
  10716. var self = this;
  10717. var sendJingle = function (ssrcs) {
  10718. var accept = $iq({to: self.peerjid,
  10719. type: 'set'})
  10720. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10721. action: 'session-accept',
  10722. initiator: self.initiator,
  10723. responder: self.responder,
  10724. sid: self.sid });
  10725. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  10726. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  10727. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  10728. self.connection.sendIQ(accept,
  10729. function () {
  10730. var ack = {};
  10731. ack.source = 'answer';
  10732. $(document).trigger('ack.jingle', [self.sid, ack]);
  10733. },
  10734. function (stanza) {
  10735. var error = ($(stanza).find('error').length) ? {
  10736. code: $(stanza).find('error').attr('code'),
  10737. reason: $(stanza).find('error :first')[0].tagName,
  10738. }:{};
  10739. error.source = 'answer';
  10740. JingleSession.onJingleError(self.sid, error);
  10741. },
  10742. 10000);
  10743. }
  10744. sdp.sdp = this.localSDP.raw;
  10745. this.peerconnection.setLocalDescription(sdp,
  10746. function () {
  10747. //console.log('setLocalDescription success');
  10748. if (self.usetrickle && !self.usepranswer) {
  10749. sendJingle();
  10750. }
  10751. self.setLocalDescription();
  10752. },
  10753. function (e) {
  10754. console.error('setLocalDescription failed', e);
  10755. }
  10756. );
  10757. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10758. for (var j = 0; j < cands.length; j++) {
  10759. var cand = SDPUtil.parse_icecandidate(cands[j]);
  10760. if (cand.type == 'srflx') {
  10761. this.hadstuncandidate = true;
  10762. } else if (cand.type == 'relay') {
  10763. this.hadturncandidate = true;
  10764. }
  10765. }
  10766. };
  10767. JingleSession.prototype.sendTerminate = function (reason, text) {
  10768. var self = this,
  10769. term = $iq({to: this.peerjid,
  10770. type: 'set'})
  10771. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10772. action: 'session-terminate',
  10773. initiator: this.initiator,
  10774. sid: this.sid})
  10775. .c('reason')
  10776. .c(reason || 'success');
  10777. if (text) {
  10778. term.up().c('text').t(text);
  10779. }
  10780. this.connection.sendIQ(term,
  10781. function () {
  10782. self.peerconnection.close();
  10783. self.peerconnection = null;
  10784. self.terminate();
  10785. var ack = {};
  10786. ack.source = 'terminate';
  10787. $(document).trigger('ack.jingle', [self.sid, ack]);
  10788. },
  10789. function (stanza) {
  10790. var error = ($(stanza).find('error').length) ? {
  10791. code: $(stanza).find('error').attr('code'),
  10792. reason: $(stanza).find('error :first')[0].tagName,
  10793. }:{};
  10794. $(document).trigger('ack.jingle', [self.sid, error]);
  10795. },
  10796. 10000);
  10797. if (this.statsinterval !== null) {
  10798. window.clearInterval(this.statsinterval);
  10799. this.statsinterval = null;
  10800. }
  10801. };
  10802. JingleSession.prototype.addSource = function (elem, fromJid) {
  10803. var self = this;
  10804. // FIXME: dirty waiting
  10805. if (!this.peerconnection.localDescription)
  10806. {
  10807. console.warn("addSource - localDescription not ready yet")
  10808. setTimeout(function()
  10809. {
  10810. self.addSource(elem, fromJid);
  10811. },
  10812. 200
  10813. );
  10814. return;
  10815. }
  10816. console.log('addssrc', new Date().getTime());
  10817. console.log('ice', this.peerconnection.iceConnectionState);
  10818. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10819. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10820. $(elem).each(function (idx, content) {
  10821. var name = $(content).attr('name');
  10822. var lines = '';
  10823. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10824. var semantics = this.getAttribute('semantics');
  10825. var ssrcs = $(this).find('>source').map(function () {
  10826. return this.getAttribute('ssrc');
  10827. }).get();
  10828. if (ssrcs.length != 0) {
  10829. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10830. }
  10831. });
  10832. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  10833. tmp.each(function () {
  10834. var ssrc = $(this).attr('ssrc');
  10835. if(mySdp.containsSSRC(ssrc)){
  10836. /**
  10837. * This happens when multiple participants change their streams at the same time and
  10838. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  10839. * addssrc are scheduled for update IQ. See
  10840. */
  10841. console.warn("Got add stream request for my own ssrc: "+ssrc);
  10842. return;
  10843. }
  10844. $(this).find('>parameter').each(function () {
  10845. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  10846. if ($(this).attr('value') && $(this).attr('value').length)
  10847. lines += ':' + $(this).attr('value');
  10848. lines += '\r\n';
  10849. });
  10850. });
  10851. sdp.media.forEach(function(media, idx) {
  10852. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  10853. return;
  10854. sdp.media[idx] += lines;
  10855. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  10856. self.addssrc[idx] += lines;
  10857. });
  10858. sdp.raw = sdp.session + sdp.media.join('');
  10859. });
  10860. this.modifySources();
  10861. };
  10862. JingleSession.prototype.removeSource = function (elem, fromJid) {
  10863. var self = this;
  10864. // FIXME: dirty waiting
  10865. if (!this.peerconnection.localDescription)
  10866. {
  10867. console.warn("removeSource - localDescription not ready yet")
  10868. setTimeout(function()
  10869. {
  10870. self.removeSource(elem, fromJid);
  10871. },
  10872. 200
  10873. );
  10874. return;
  10875. }
  10876. console.log('removessrc', new Date().getTime());
  10877. console.log('ice', this.peerconnection.iceConnectionState);
  10878. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10879. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10880. $(elem).each(function (idx, content) {
  10881. var name = $(content).attr('name');
  10882. var lines = '';
  10883. tmp = $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10884. var semantics = this.getAttribute('semantics');
  10885. var ssrcs = $(this).find('>source').map(function () {
  10886. return this.getAttribute('ssrc');
  10887. }).get();
  10888. if (ssrcs.length != 0) {
  10889. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10890. }
  10891. });
  10892. tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  10893. tmp.each(function () {
  10894. var ssrc = $(this).attr('ssrc');
  10895. // This should never happen, but can be useful for bug detection
  10896. if(mySdp.containsSSRC(ssrc)){
  10897. console.error("Got remove stream request for my own ssrc: "+ssrc);
  10898. return;
  10899. }
  10900. $(this).find('>parameter').each(function () {
  10901. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  10902. if ($(this).attr('value') && $(this).attr('value').length)
  10903. lines += ':' + $(this).attr('value');
  10904. lines += '\r\n';
  10905. });
  10906. });
  10907. sdp.media.forEach(function(media, idx) {
  10908. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  10909. return;
  10910. sdp.media[idx] += lines;
  10911. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  10912. self.removessrc[idx] += lines;
  10913. });
  10914. sdp.raw = sdp.session + sdp.media.join('');
  10915. });
  10916. this.modifySources();
  10917. };
  10918. JingleSession.prototype.modifySources = function (successCallback) {
  10919. var self = this;
  10920. if (this.peerconnection.signalingState == 'closed') return;
  10921. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  10922. // There is nothing to do since scheduled job might have been executed by another succeeding call
  10923. this.setLocalDescription();
  10924. if(successCallback){
  10925. successCallback();
  10926. }
  10927. return;
  10928. }
  10929. // FIXME: this is a big hack
  10930. // https://code.google.com/p/webrtc/issues/detail?id=2688
  10931. // ^ has been fixed.
  10932. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
  10933. console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
  10934. this.wait = true;
  10935. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  10936. return;
  10937. }
  10938. if (this.wait) {
  10939. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  10940. this.wait = false;
  10941. return;
  10942. }
  10943. // Reset switch streams flag
  10944. this.switchstreams = false;
  10945. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10946. // add sources
  10947. this.addssrc.forEach(function(lines, idx) {
  10948. sdp.media[idx] += lines;
  10949. });
  10950. this.addssrc = [];
  10951. // remove sources
  10952. this.removessrc.forEach(function(lines, idx) {
  10953. lines = lines.split('\r\n');
  10954. lines.pop(); // remove empty last element;
  10955. lines.forEach(function(line) {
  10956. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  10957. });
  10958. });
  10959. this.removessrc = [];
  10960. // FIXME:
  10961. // this was a hack for the situation when only one peer exists
  10962. // in the conference.
  10963. // check if still required and remove
  10964. if (sdp.media[0])
  10965. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  10966. if (sdp.media[1])
  10967. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  10968. sdp.raw = sdp.session + sdp.media.join('');
  10969. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  10970. function() {
  10971. if(self.signalingState == 'closed') {
  10972. console.error("createAnswer attempt on closed state");
  10973. return;
  10974. }
  10975. self.peerconnection.createAnswer(
  10976. function(modifiedAnswer) {
  10977. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  10978. if (self.pendingop !== null) {
  10979. var sdp = new SDP(modifiedAnswer.sdp);
  10980. if (sdp.media.length > 1) {
  10981. switch(self.pendingop) {
  10982. case 'mute':
  10983. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  10984. break;
  10985. case 'unmute':
  10986. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  10987. break;
  10988. }
  10989. sdp.raw = sdp.session + sdp.media.join('');
  10990. modifiedAnswer.sdp = sdp.raw;
  10991. }
  10992. self.pendingop = null;
  10993. }
  10994. // FIXME: pushing down an answer while ice connection state
  10995. // is still checking is bad...
  10996. //console.log(self.peerconnection.iceConnectionState);
  10997. // trying to work around another chrome bug
  10998. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  10999. self.peerconnection.setLocalDescription(modifiedAnswer,
  11000. function() {
  11001. //console.log('modified setLocalDescription ok');
  11002. self.setLocalDescription();
  11003. if(successCallback){
  11004. successCallback();
  11005. }
  11006. },
  11007. function(error) {
  11008. console.error('modified setLocalDescription failed', error);
  11009. }
  11010. );
  11011. },
  11012. function(error) {
  11013. console.error('modified answer failed', error);
  11014. }
  11015. );
  11016. },
  11017. function(error) {
  11018. console.error('modify failed', error);
  11019. }
  11020. );
  11021. };
  11022. /**
  11023. * Switches video streams.
  11024. * @param new_stream new stream that will be used as video of this session.
  11025. * @param oldStream old video stream of this session.
  11026. * @param success_callback callback executed after successful stream switch.
  11027. */
  11028. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback) {
  11029. var self = this;
  11030. // Remember SDP to figure out added/removed SSRCs
  11031. var oldSdp = null;
  11032. if(self.peerconnection) {
  11033. if(self.peerconnection.localDescription) {
  11034. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11035. }
  11036. self.peerconnection.removeStream(oldStream, true);
  11037. self.peerconnection.addStream(new_stream);
  11038. }
  11039. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11040. // Conference is not active
  11041. if(!oldSdp || !self.peerconnection) {
  11042. success_callback();
  11043. return;
  11044. }
  11045. self.switchstreams = true;
  11046. self.modifySources(function() {
  11047. console.log('modify sources done');
  11048. success_callback();
  11049. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11050. console.log("SDPs", oldSdp, newSdp);
  11051. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11052. });
  11053. };
  11054. /**
  11055. * Figures out added/removed ssrcs and send update IQs.
  11056. * @param old_sdp SDP object for old description.
  11057. * @param new_sdp SDP object for new description.
  11058. */
  11059. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11060. if (!(this.peerconnection.signalingState == 'stable' &&
  11061. this.peerconnection.iceConnectionState == 'connected')){
  11062. console.log("Too early to send updates");
  11063. return;
  11064. }
  11065. // send source-remove IQ.
  11066. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11067. var remove = $iq({to: this.peerjid, type: 'set'})
  11068. .c('jingle', {
  11069. xmlns: 'urn:xmpp:jingle:1',
  11070. action: 'source-remove',
  11071. initiator: this.initiator,
  11072. sid: this.sid
  11073. }
  11074. );
  11075. var removed = sdpDiffer.toJingle(remove);
  11076. if (removed) {
  11077. this.connection.sendIQ(remove,
  11078. function (res) {
  11079. console.info('got remove result', res);
  11080. },
  11081. function (err) {
  11082. console.error('got remove error', err);
  11083. }
  11084. );
  11085. } else {
  11086. console.log('removal not necessary');
  11087. }
  11088. // send source-add IQ.
  11089. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11090. var add = $iq({to: this.peerjid, type: 'set'})
  11091. .c('jingle', {
  11092. xmlns: 'urn:xmpp:jingle:1',
  11093. action: 'source-add',
  11094. initiator: this.initiator,
  11095. sid: this.sid
  11096. }
  11097. );
  11098. var added = sdpDiffer.toJingle(add);
  11099. if (added) {
  11100. this.connection.sendIQ(add,
  11101. function (res) {
  11102. console.info('got add result', res);
  11103. },
  11104. function (err) {
  11105. console.error('got add error', err);
  11106. }
  11107. );
  11108. } else {
  11109. console.log('addition not necessary');
  11110. }
  11111. };
  11112. /**
  11113. * Determines whether the (local) video is mute i.e. all video tracks are
  11114. * disabled.
  11115. *
  11116. * @return <tt>true</tt> if the (local) video is mute i.e. all video tracks are
  11117. * disabled; otherwise, <tt>false</tt>
  11118. */
  11119. JingleSession.prototype.isVideoMute = function () {
  11120. var tracks = APP.RTC.localVideo.getVideoTracks();
  11121. var mute = true;
  11122. for (var i = 0; i < tracks.length; ++i) {
  11123. if (tracks[i].enabled) {
  11124. mute = false;
  11125. break;
  11126. }
  11127. }
  11128. return mute;
  11129. };
  11130. /**
  11131. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  11132. *
  11133. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  11134. * tracks; otherwise, <tt>false</tt>
  11135. * @param callback a function to be invoked with <tt>mute</tt> after all video
  11136. * tracks have been enabled/disabled. The function may, optionally, return
  11137. * another function which is to be invoked after the whole mute/unmute operation
  11138. * has completed successfully.
  11139. * @param options an object which specifies optional arguments such as the
  11140. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  11141. * specifies whether the method was initiated in response to a user command (in
  11142. * contrast to an automatic decision made by the application logic)
  11143. */
  11144. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  11145. var byUser;
  11146. if (options) {
  11147. byUser = options.byUser;
  11148. if (typeof byUser === 'undefined') {
  11149. byUser = true;
  11150. }
  11151. } else {
  11152. byUser = true;
  11153. }
  11154. // The user's command to mute the (local) video takes precedence over any
  11155. // automatic decision made by the application logic.
  11156. if (byUser) {
  11157. this.videoMuteByUser = mute;
  11158. } else if (this.videoMuteByUser) {
  11159. return;
  11160. }
  11161. var self = this;
  11162. var localCallback = function (mute) {
  11163. self.connection.emuc.addVideoInfoToPresence(mute);
  11164. self.connection.emuc.sendPresence();
  11165. return callback(mute)
  11166. };
  11167. if (mute == APP.RTC.localVideo.isMuted())
  11168. {
  11169. // Even if no change occurs, the specified callback is to be executed.
  11170. // The specified callback may, optionally, return a successCallback
  11171. // which is to be executed as well.
  11172. var successCallback = localCallback(mute);
  11173. if (successCallback) {
  11174. successCallback();
  11175. }
  11176. } else {
  11177. APP.RTC.localVideo.setMute(!mute);
  11178. this.hardMuteVideo(mute);
  11179. this.modifySources(localCallback(mute));
  11180. }
  11181. };
  11182. // SDP-based mute by going recvonly/sendrecv
  11183. // FIXME: should probably black out the screen as well
  11184. JingleSession.prototype.toggleVideoMute = function (callback) {
  11185. this.service.setVideoMute(APP.RTC.localVideo.isMuted(), callback);
  11186. };
  11187. JingleSession.prototype.hardMuteVideo = function (muted) {
  11188. this.pendingop = muted ? 'mute' : 'unmute';
  11189. };
  11190. JingleSession.prototype.sendMute = function (muted, content) {
  11191. var info = $iq({to: this.peerjid,
  11192. type: 'set'})
  11193. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11194. action: 'session-info',
  11195. initiator: this.initiator,
  11196. sid: this.sid });
  11197. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11198. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  11199. if (content) {
  11200. info.attrs({'name': content});
  11201. }
  11202. this.connection.send(info);
  11203. };
  11204. JingleSession.prototype.sendRinging = function () {
  11205. var info = $iq({to: this.peerjid,
  11206. type: 'set'})
  11207. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11208. action: 'session-info',
  11209. initiator: this.initiator,
  11210. sid: this.sid });
  11211. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11212. this.connection.send(info);
  11213. };
  11214. JingleSession.prototype.getStats = function (interval) {
  11215. var self = this;
  11216. var recv = {audio: 0, video: 0};
  11217. var lost = {audio: 0, video: 0};
  11218. var lastrecv = {audio: 0, video: 0};
  11219. var lastlost = {audio: 0, video: 0};
  11220. var loss = {audio: 0, video: 0};
  11221. var delta = {audio: 0, video: 0};
  11222. this.statsinterval = window.setInterval(function () {
  11223. if (self && self.peerconnection && self.peerconnection.getStats) {
  11224. self.peerconnection.getStats(function (stats) {
  11225. var results = stats.result();
  11226. // TODO: there are so much statistics you can get from this..
  11227. for (var i = 0; i < results.length; ++i) {
  11228. if (results[i].type == 'ssrc') {
  11229. var packetsrecv = results[i].stat('packetsReceived');
  11230. var packetslost = results[i].stat('packetsLost');
  11231. if (packetsrecv && packetslost) {
  11232. packetsrecv = parseInt(packetsrecv, 10);
  11233. packetslost = parseInt(packetslost, 10);
  11234. if (results[i].stat('googFrameRateReceived')) {
  11235. lastlost.video = lost.video;
  11236. lastrecv.video = recv.video;
  11237. recv.video = packetsrecv;
  11238. lost.video = packetslost;
  11239. } else {
  11240. lastlost.audio = lost.audio;
  11241. lastrecv.audio = recv.audio;
  11242. recv.audio = packetsrecv;
  11243. lost.audio = packetslost;
  11244. }
  11245. }
  11246. }
  11247. }
  11248. delta.audio = recv.audio - lastrecv.audio;
  11249. delta.video = recv.video - lastrecv.video;
  11250. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  11251. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  11252. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  11253. });
  11254. }
  11255. }, interval || 3000);
  11256. return this.statsinterval;
  11257. };
  11258. JingleSession.onJingleError = function (session, error)
  11259. {
  11260. console.error("Jingle error", error);
  11261. }
  11262. JingleSession.onJingleFatalError = function (session, error)
  11263. {
  11264. this.service.sessionTerminated = true;
  11265. this.connection.emuc.doLeave();
  11266. APP.UI.messageHandler.showError("dialog.sorry",
  11267. "dialog.internalError");
  11268. }
  11269. JingleSession.prototype.setLocalDescription = function () {
  11270. // put our ssrcs into presence so other clients can identify our stream
  11271. var newssrcs = [];
  11272. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  11273. media.forEach(function (media) {
  11274. if(Object.keys(media.sources).length > 0) {
  11275. // TODO(gp) maybe exclude FID streams?
  11276. Object.keys(media.sources).forEach(function (ssrc) {
  11277. newssrcs.push({
  11278. 'ssrc': ssrc,
  11279. 'type': media.type,
  11280. 'direction': media.direction
  11281. });
  11282. });
  11283. }
  11284. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  11285. {
  11286. newssrcs.push({
  11287. 'ssrc': this.localStreamsSSRC[media.type],
  11288. 'type': media.type,
  11289. 'direction': media.direction
  11290. });
  11291. }
  11292. });
  11293. console.log('new ssrcs', newssrcs);
  11294. // Have to clear presence map to get rid of removed streams
  11295. this.connection.emuc.clearPresenceMedia();
  11296. if (newssrcs.length > 0) {
  11297. for (var i = 1; i <= newssrcs.length; i ++) {
  11298. // Change video type to screen
  11299. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  11300. newssrcs[i-1].type = 'screen';
  11301. }
  11302. this.connection.emuc.addMediaToPresence(i,
  11303. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  11304. }
  11305. this.connection.emuc.sendPresence();
  11306. }
  11307. }
  11308. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11309. function sendKeyframe(pc) {
  11310. console.log('sendkeyframe', pc.iceConnectionState);
  11311. if (pc.iceConnectionState !== 'connected') return; // safe...
  11312. pc.setRemoteDescription(
  11313. pc.remoteDescription,
  11314. function () {
  11315. pc.createAnswer(
  11316. function (modifiedAnswer) {
  11317. pc.setLocalDescription(
  11318. modifiedAnswer,
  11319. function () {
  11320. // noop
  11321. },
  11322. function (error) {
  11323. console.log('triggerKeyframe setLocalDescription failed', error);
  11324. APP.UI.messageHandler.showError();
  11325. }
  11326. );
  11327. },
  11328. function (error) {
  11329. console.log('triggerKeyframe createAnswer failed', error);
  11330. APP.UI.messageHandler.showError();
  11331. }
  11332. );
  11333. },
  11334. function (error) {
  11335. console.log('triggerKeyframe setRemoteDescription failed', error);
  11336. APP.UI.messageHandler.showError();
  11337. }
  11338. );
  11339. }
  11340. JingleSession.prototype.remoteStreamAdded = function (data) {
  11341. var self = this;
  11342. var thessrc;
  11343. var ssrc2jid = this.connection.emuc.ssrc2jid;
  11344. // look up an associated JID for a stream id
  11345. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  11346. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  11347. var ssrclines
  11348. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  11349. ssrclines = ssrclines.filter(function (line) {
  11350. // NOTE(gp) previously we filtered on the mslabel, but that property
  11351. // is not always present.
  11352. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  11353. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  11354. });
  11355. if (ssrclines.length) {
  11356. thessrc = ssrclines[0].substring(7).split(' ')[0];
  11357. // We signal our streams (through Jingle to the focus) before we set
  11358. // our presence (through which peers associate remote streams to
  11359. // jids). So, it might arrive that a remote stream is added but
  11360. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  11361. // successfully set. Here we wait for up to a second for the
  11362. // presence to arrive.
  11363. if (!ssrc2jid[thessrc]) {
  11364. // TODO(gp) limit wait duration to 1 sec.
  11365. setTimeout(function(d) {
  11366. return function() {
  11367. self.remoteStreamAdded(d);
  11368. }
  11369. }(data), 250);
  11370. return;
  11371. }
  11372. // ok to overwrite the one from focus? might save work in colibri.js
  11373. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  11374. if (ssrc2jid[thessrc]) {
  11375. data.peerjid = ssrc2jid[thessrc];
  11376. }
  11377. }
  11378. }
  11379. //TODO: this code should be removed when firefox implement multistream support
  11380. if(APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_FIREFOX)
  11381. {
  11382. if((JingleSession.notReceivedSSRCs.length == 0) ||
  11383. !ssrc2jid[JingleSession.notReceivedSSRCs[JingleSession.notReceivedSSRCs.length - 1]])
  11384. {
  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. thessrc = JingleSession.notReceivedSSRCs.pop();
  11394. if (ssrc2jid[thessrc]) {
  11395. data.peerjid = ssrc2jid[thessrc];
  11396. }
  11397. }
  11398. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  11399. var isVideo = data.stream.getVideoTracks().length > 0;
  11400. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11401. if (isVideo &&
  11402. data.peerjid && this.peerjid === data.peerjid &&
  11403. data.stream.getVideoTracks().length === 0 &&
  11404. APP.RTC.localVideo.getTracks().length > 0) {
  11405. window.setTimeout(function () {
  11406. sendKeyframe(self.peerconnection);
  11407. }, 3000);
  11408. }
  11409. }
  11410. module.exports = JingleSession;
  11411. },{"../../service/RTC/RTCBrowserType":79,"./SDP":48,"./SDPDiffer":49,"./SDPUtil":50,"./TraceablePeerConnection":51}],48:[function(require,module,exports){
  11412. /* jshint -W117 */
  11413. var SDPUtil = require("./SDPUtil");
  11414. // SDP STUFF
  11415. function SDP(sdp) {
  11416. this.media = sdp.split('\r\nm=');
  11417. for (var i = 1; i < this.media.length; i++) {
  11418. this.media[i] = 'm=' + this.media[i];
  11419. if (i != this.media.length - 1) {
  11420. this.media[i] += '\r\n';
  11421. }
  11422. }
  11423. this.session = this.media.shift() + '\r\n';
  11424. this.raw = this.session + this.media.join('');
  11425. }
  11426. /**
  11427. * Returns map of MediaChannel mapped per channel idx.
  11428. */
  11429. SDP.prototype.getMediaSsrcMap = function() {
  11430. var self = this;
  11431. var media_ssrcs = {};
  11432. var tmp;
  11433. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  11434. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  11435. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  11436. var media = {
  11437. mediaindex: mediaindex,
  11438. mid: mid,
  11439. ssrcs: {},
  11440. ssrcGroups: []
  11441. };
  11442. media_ssrcs[mediaindex] = media;
  11443. tmp.forEach(function (line) {
  11444. var linessrc = line.substring(7).split(' ')[0];
  11445. // allocate new ChannelSsrc
  11446. if(!media.ssrcs[linessrc]) {
  11447. media.ssrcs[linessrc] = {
  11448. ssrc: linessrc,
  11449. lines: []
  11450. };
  11451. }
  11452. media.ssrcs[linessrc].lines.push(line);
  11453. });
  11454. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  11455. tmp.forEach(function(line){
  11456. var semantics = line.substr(0, idx).substr(13);
  11457. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11458. if (ssrcs.length != 0) {
  11459. media.ssrcGroups.push({
  11460. semantics: semantics,
  11461. ssrcs: ssrcs
  11462. });
  11463. }
  11464. });
  11465. }
  11466. return media_ssrcs;
  11467. };
  11468. /**
  11469. * Returns <tt>true</tt> if this SDP contains given SSRC.
  11470. * @param ssrc the ssrc to check.
  11471. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  11472. */
  11473. SDP.prototype.containsSSRC = function(ssrc) {
  11474. var medias = this.getMediaSsrcMap();
  11475. var contains = false;
  11476. Object.keys(medias).forEach(function(mediaindex){
  11477. var media = medias[mediaindex];
  11478. //console.log("Check", channel, ssrc);
  11479. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  11480. contains = true;
  11481. }
  11482. });
  11483. return contains;
  11484. };
  11485. // remove iSAC and CN from SDP
  11486. SDP.prototype.mangle = function () {
  11487. var i, j, mline, lines, rtpmap, newdesc;
  11488. for (i = 0; i < this.media.length; i++) {
  11489. lines = this.media[i].split('\r\n');
  11490. lines.pop(); // remove empty last element
  11491. mline = SDPUtil.parse_mline(lines.shift());
  11492. if (mline.media != 'audio')
  11493. continue;
  11494. newdesc = '';
  11495. mline.fmt.length = 0;
  11496. for (j = 0; j < lines.length; j++) {
  11497. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  11498. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  11499. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  11500. continue;
  11501. mline.fmt.push(rtpmap.id);
  11502. newdesc += lines[j] + '\r\n';
  11503. } else {
  11504. newdesc += lines[j] + '\r\n';
  11505. }
  11506. }
  11507. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  11508. this.media[i] += newdesc;
  11509. }
  11510. this.raw = this.session + this.media.join('');
  11511. };
  11512. // remove lines matching prefix from session section
  11513. SDP.prototype.removeSessionLines = function(prefix) {
  11514. var self = this;
  11515. var lines = SDPUtil.find_lines(this.session, prefix);
  11516. lines.forEach(function(line) {
  11517. self.session = self.session.replace(line + '\r\n', '');
  11518. });
  11519. this.raw = this.session + this.media.join('');
  11520. return lines;
  11521. }
  11522. // remove lines matching prefix from a media section specified by mediaindex
  11523. // TODO: non-numeric mediaindex could match mid
  11524. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  11525. var self = this;
  11526. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  11527. lines.forEach(function(line) {
  11528. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  11529. });
  11530. this.raw = this.session + this.media.join('');
  11531. return lines;
  11532. }
  11533. // add content's to a jingle element
  11534. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  11535. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  11536. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  11537. var self = this;
  11538. // new bundle plan
  11539. if (SDPUtil.find_line(this.session, 'a=group:')) {
  11540. lines = SDPUtil.find_lines(this.session, 'a=group:');
  11541. for (i = 0; i < lines.length; i++) {
  11542. tmp = lines[i].split(' ');
  11543. var semantics = tmp.shift().substr(8);
  11544. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  11545. for (j = 0; j < tmp.length; j++) {
  11546. elem.c('content', {name: tmp[j]}).up();
  11547. }
  11548. elem.up();
  11549. }
  11550. }
  11551. for (i = 0; i < this.media.length; i++) {
  11552. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  11553. if (!(mline.media === 'audio' ||
  11554. mline.media === 'video' ||
  11555. mline.media === 'application'))
  11556. {
  11557. continue;
  11558. }
  11559. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  11560. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  11561. } else {
  11562. if(ssrcs && ssrcs[mline.media])
  11563. {
  11564. ssrc = ssrcs[mline.media];
  11565. }
  11566. else
  11567. ssrc = false;
  11568. }
  11569. elem.c('content', {creator: thecreator, name: mline.media});
  11570. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  11571. // prefer identifier from a=mid if present
  11572. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  11573. elem.attrs({ name: mid });
  11574. }
  11575. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  11576. {
  11577. elem.c('description',
  11578. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  11579. media: mline.media });
  11580. if (ssrc) {
  11581. elem.attrs({ssrc: ssrc});
  11582. }
  11583. for (j = 0; j < mline.fmt.length; j++) {
  11584. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  11585. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  11586. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  11587. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  11588. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  11589. for (k = 0; k < tmp.length; k++) {
  11590. elem.c('parameter', tmp[k]).up();
  11591. }
  11592. }
  11593. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  11594. elem.up();
  11595. }
  11596. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  11597. elem.c('encryption', {required: 1});
  11598. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  11599. crypto.forEach(function(line) {
  11600. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  11601. });
  11602. elem.up(); // end of encryption
  11603. }
  11604. if (ssrc) {
  11605. // new style mapping
  11606. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11607. // FIXME: group by ssrc and support multiple different ssrcs
  11608. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  11609. if(ssrclines.length > 0) {
  11610. ssrclines.forEach(function (line) {
  11611. idx = line.indexOf(' ');
  11612. var linessrc = line.substr(0, idx).substr(7);
  11613. if (linessrc != ssrc) {
  11614. elem.up();
  11615. ssrc = linessrc;
  11616. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11617. }
  11618. var kv = line.substr(idx + 1);
  11619. elem.c('parameter');
  11620. if (kv.indexOf(':') == -1) {
  11621. elem.attrs({ name: kv });
  11622. } else {
  11623. elem.attrs({ name: kv.split(':', 2)[0] });
  11624. elem.attrs({ value: kv.split(':', 2)[1] });
  11625. }
  11626. elem.up();
  11627. });
  11628. elem.up();
  11629. }
  11630. else
  11631. {
  11632. elem.up();
  11633. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11634. elem.c('parameter');
  11635. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  11636. elem.up();
  11637. var msid = null;
  11638. if(mline.media == "audio")
  11639. {
  11640. msid = APP.RTC.localAudio.getId();
  11641. }
  11642. else
  11643. {
  11644. msid = APP.RTC.localVideo.getId();
  11645. }
  11646. if(msid != null)
  11647. {
  11648. msid = msid.replace(/[\{,\}]/g,"");
  11649. elem.c('parameter');
  11650. elem.attrs({name: "msid", value:msid});
  11651. elem.up();
  11652. elem.c('parameter');
  11653. elem.attrs({name: "mslabel", value:msid});
  11654. elem.up();
  11655. elem.c('parameter');
  11656. elem.attrs({name: "label", value:msid});
  11657. elem.up();
  11658. elem.up();
  11659. }
  11660. }
  11661. // XEP-0339 handle ssrc-group attributes
  11662. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  11663. ssrc_group_lines.forEach(function(line) {
  11664. idx = line.indexOf(' ');
  11665. var semantics = line.substr(0, idx).substr(13);
  11666. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11667. if (ssrcs.length != 0) {
  11668. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11669. ssrcs.forEach(function(ssrc) {
  11670. elem.c('source', { ssrc: ssrc })
  11671. .up();
  11672. });
  11673. elem.up();
  11674. }
  11675. });
  11676. }
  11677. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  11678. elem.c('rtcp-mux').up();
  11679. }
  11680. // XEP-0293 -- map a=rtcp-fb:*
  11681. this.RtcpFbToJingle(i, elem, '*');
  11682. // XEP-0294
  11683. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  11684. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  11685. for (j = 0; j < lines.length; j++) {
  11686. tmp = SDPUtil.parse_extmap(lines[j]);
  11687. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  11688. uri: tmp.uri,
  11689. id: tmp.value });
  11690. if (tmp.hasOwnProperty('direction')) {
  11691. switch (tmp.direction) {
  11692. case 'sendonly':
  11693. elem.attrs({senders: 'responder'});
  11694. break;
  11695. case 'recvonly':
  11696. elem.attrs({senders: 'initiator'});
  11697. break;
  11698. case 'sendrecv':
  11699. elem.attrs({senders: 'both'});
  11700. break;
  11701. case 'inactive':
  11702. elem.attrs({senders: 'none'});
  11703. break;
  11704. }
  11705. }
  11706. // TODO: handle params
  11707. elem.up();
  11708. }
  11709. }
  11710. elem.up(); // end of description
  11711. }
  11712. // map ice-ufrag/pwd, dtls fingerprint, candidates
  11713. this.TransportToJingle(i, elem);
  11714. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  11715. elem.attrs({senders: 'both'});
  11716. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  11717. elem.attrs({senders: 'initiator'});
  11718. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  11719. elem.attrs({senders: 'responder'});
  11720. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  11721. elem.attrs({senders: 'none'});
  11722. }
  11723. if (mline.port == '0') {
  11724. // estos hack to reject an m-line
  11725. elem.attrs({senders: 'rejected'});
  11726. }
  11727. elem.up(); // end of content
  11728. }
  11729. elem.up();
  11730. return elem;
  11731. };
  11732. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  11733. var i = mediaindex;
  11734. var tmp;
  11735. var self = this;
  11736. elem.c('transport');
  11737. // XEP-0343 DTLS/SCTP
  11738. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  11739. {
  11740. var sctpmap = SDPUtil.find_line(
  11741. this.media[i], 'a=sctpmap:', self.session);
  11742. if (sctpmap)
  11743. {
  11744. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  11745. elem.c('sctpmap',
  11746. {
  11747. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  11748. number: sctpAttrs[0], /* SCTP port */
  11749. protocol: sctpAttrs[1], /* protocol */
  11750. });
  11751. // Optional stream count attribute
  11752. if (sctpAttrs.length > 2)
  11753. elem.attrs({ streams: sctpAttrs[2]});
  11754. elem.up();
  11755. }
  11756. }
  11757. // XEP-0320
  11758. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  11759. fingerprints.forEach(function(line) {
  11760. tmp = SDPUtil.parse_fingerprint(line);
  11761. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  11762. elem.c('fingerprint').t(tmp.fingerprint);
  11763. delete tmp.fingerprint;
  11764. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  11765. if (line) {
  11766. tmp.setup = line.substr(8);
  11767. }
  11768. elem.attrs(tmp);
  11769. elem.up(); // end of fingerprint
  11770. });
  11771. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  11772. if (tmp) {
  11773. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11774. elem.attrs(tmp);
  11775. // XEP-0176
  11776. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  11777. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  11778. lines.forEach(function (line) {
  11779. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  11780. });
  11781. }
  11782. }
  11783. elem.up(); // end of transport
  11784. }
  11785. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  11786. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  11787. lines.forEach(function (line) {
  11788. var tmp = SDPUtil.parse_rtcpfb(line);
  11789. if (tmp.type == 'trr-int') {
  11790. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  11791. elem.up();
  11792. } else {
  11793. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  11794. if (tmp.params.length > 0) {
  11795. elem.attrs({'subtype': tmp.params[0]});
  11796. }
  11797. elem.up();
  11798. }
  11799. });
  11800. };
  11801. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  11802. var media = '';
  11803. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11804. if (tmp.length) {
  11805. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  11806. if (tmp.attr('value')) {
  11807. media += tmp.attr('value');
  11808. } else {
  11809. media += '0';
  11810. }
  11811. media += '\r\n';
  11812. }
  11813. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11814. tmp.each(function () {
  11815. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  11816. if ($(this).attr('subtype')) {
  11817. media += ' ' + $(this).attr('subtype');
  11818. }
  11819. media += '\r\n';
  11820. });
  11821. return media;
  11822. };
  11823. // construct an SDP from a jingle stanza
  11824. SDP.prototype.fromJingle = function (jingle) {
  11825. var self = this;
  11826. this.raw = 'v=0\r\n' +
  11827. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11828. 's=-\r\n' +
  11829. 't=0 0\r\n';
  11830. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  11831. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  11832. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  11833. var contents = $(group).find('>content').map(function (idx, content) {
  11834. return content.getAttribute('name');
  11835. }).get();
  11836. if (contents.length > 0) {
  11837. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  11838. }
  11839. });
  11840. }
  11841. this.session = this.raw;
  11842. jingle.find('>content').each(function () {
  11843. var m = self.jingle2media($(this));
  11844. self.media.push(m);
  11845. });
  11846. // reconstruct msid-semantic -- apparently not necessary
  11847. /*
  11848. var msid = SDPUtil.parse_ssrc(this.raw);
  11849. if (msid.hasOwnProperty('mslabel')) {
  11850. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  11851. }
  11852. */
  11853. this.raw = this.session + this.media.join('');
  11854. };
  11855. // translate a jingle content element into an an SDP media part
  11856. SDP.prototype.jingle2media = function (content) {
  11857. var media = '',
  11858. desc = content.find('description'),
  11859. ssrc = desc.attr('ssrc'),
  11860. self = this,
  11861. tmp;
  11862. var sctp = content.find(
  11863. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  11864. tmp = { media: desc.attr('media') };
  11865. tmp.port = '1';
  11866. if (content.attr('senders') == 'rejected') {
  11867. // estos hack to reject an m-line.
  11868. tmp.port = '0';
  11869. }
  11870. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  11871. if (sctp.length)
  11872. tmp.proto = 'DTLS/SCTP';
  11873. else
  11874. tmp.proto = 'RTP/SAVPF';
  11875. } else {
  11876. tmp.proto = 'RTP/AVPF';
  11877. }
  11878. if (!sctp.length)
  11879. {
  11880. tmp.fmt = desc.find('payload-type').map(
  11881. function () { return this.getAttribute('id'); }).get();
  11882. media += SDPUtil.build_mline(tmp) + '\r\n';
  11883. }
  11884. else
  11885. {
  11886. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  11887. media += 'a=sctpmap:' + sctp.attr('number') +
  11888. ' ' + sctp.attr('protocol');
  11889. var streamCount = sctp.attr('streams');
  11890. if (streamCount)
  11891. media += ' ' + streamCount + '\r\n';
  11892. else
  11893. media += '\r\n';
  11894. }
  11895. media += 'c=IN IP4 0.0.0.0\r\n';
  11896. if (!sctp.length)
  11897. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  11898. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  11899. if (tmp.length) {
  11900. if (tmp.attr('ufrag')) {
  11901. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  11902. }
  11903. if (tmp.attr('pwd')) {
  11904. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  11905. }
  11906. tmp.find('>fingerprint').each(function () {
  11907. // FIXME: check namespace at some point
  11908. media += 'a=fingerprint:' + this.getAttribute('hash');
  11909. media += ' ' + $(this).text();
  11910. media += '\r\n';
  11911. if (this.getAttribute('setup')) {
  11912. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  11913. }
  11914. });
  11915. }
  11916. switch (content.attr('senders')) {
  11917. case 'initiator':
  11918. media += 'a=sendonly\r\n';
  11919. break;
  11920. case 'responder':
  11921. media += 'a=recvonly\r\n';
  11922. break;
  11923. case 'none':
  11924. media += 'a=inactive\r\n';
  11925. break;
  11926. case 'both':
  11927. media += 'a=sendrecv\r\n';
  11928. break;
  11929. }
  11930. media += 'a=mid:' + content.attr('name') + '\r\n';
  11931. // <description><rtcp-mux/></description>
  11932. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  11933. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  11934. if (desc.find('rtcp-mux').length) {
  11935. media += 'a=rtcp-mux\r\n';
  11936. }
  11937. if (desc.find('encryption').length) {
  11938. desc.find('encryption>crypto').each(function () {
  11939. media += 'a=crypto:' + this.getAttribute('tag');
  11940. media += ' ' + this.getAttribute('crypto-suite');
  11941. media += ' ' + this.getAttribute('key-params');
  11942. if (this.getAttribute('session-params')) {
  11943. media += ' ' + this.getAttribute('session-params');
  11944. }
  11945. media += '\r\n';
  11946. });
  11947. }
  11948. desc.find('payload-type').each(function () {
  11949. media += SDPUtil.build_rtpmap(this) + '\r\n';
  11950. if ($(this).find('>parameter').length) {
  11951. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  11952. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  11953. media += '\r\n';
  11954. }
  11955. // xep-0293
  11956. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  11957. });
  11958. // xep-0293
  11959. media += self.RtcpFbFromJingle(desc, '*');
  11960. // xep-0294
  11961. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  11962. tmp.each(function () {
  11963. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  11964. });
  11965. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  11966. media += SDPUtil.candidateFromJingle(this);
  11967. });
  11968. // XEP-0339 handle ssrc-group attributes
  11969. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11970. var semantics = this.getAttribute('semantics');
  11971. var ssrcs = $(this).find('>source').map(function() {
  11972. return this.getAttribute('ssrc');
  11973. }).get();
  11974. if (ssrcs.length != 0) {
  11975. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11976. }
  11977. });
  11978. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  11979. tmp.each(function () {
  11980. var ssrc = this.getAttribute('ssrc');
  11981. $(this).find('>parameter').each(function () {
  11982. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  11983. if (this.getAttribute('value') && this.getAttribute('value').length)
  11984. media += ':' + this.getAttribute('value');
  11985. media += '\r\n';
  11986. });
  11987. });
  11988. return media;
  11989. };
  11990. module.exports = SDP;
  11991. },{"./SDPUtil":50}],49:[function(require,module,exports){
  11992. function SDPDiffer(mySDP, otherSDP) {
  11993. this.mySDP = mySDP;
  11994. this.otherSDP = otherSDP;
  11995. }
  11996. /**
  11997. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  11998. * @param otherSdp the other SDP to check ssrc with.
  11999. */
  12000. SDPDiffer.prototype.getNewMedia = function() {
  12001. // this could be useful in Array.prototype.
  12002. function arrayEquals(array) {
  12003. // if the other array is a falsy value, return
  12004. if (!array)
  12005. return false;
  12006. // compare lengths - can save a lot of time
  12007. if (this.length != array.length)
  12008. return false;
  12009. for (var i = 0, l=this.length; i < l; i++) {
  12010. // Check if we have nested arrays
  12011. if (this[i] instanceof Array && array[i] instanceof Array) {
  12012. // recurse into the nested arrays
  12013. if (!this[i].equals(array[i]))
  12014. return false;
  12015. }
  12016. else if (this[i] != array[i]) {
  12017. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12018. return false;
  12019. }
  12020. }
  12021. return true;
  12022. }
  12023. var myMedias = this.mySDP.getMediaSsrcMap();
  12024. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12025. var newMedia = {};
  12026. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12027. var myMedia = myMedias[othersMediaIdx];
  12028. var othersMedia = othersMedias[othersMediaIdx];
  12029. if(!myMedia && othersMedia) {
  12030. // Add whole channel
  12031. newMedia[othersMediaIdx] = othersMedia;
  12032. return;
  12033. }
  12034. // Look for new ssrcs accross the channel
  12035. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12036. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12037. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12038. if(!newMedia[othersMediaIdx]){
  12039. newMedia[othersMediaIdx] = {
  12040. mediaindex: othersMedia.mediaindex,
  12041. mid: othersMedia.mid,
  12042. ssrcs: {},
  12043. ssrcGroups: []
  12044. };
  12045. }
  12046. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12047. }
  12048. });
  12049. // Look for new ssrc groups across the channels
  12050. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12051. // try to match the other ssrc-group with an ssrc-group of ours
  12052. var matched = false;
  12053. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12054. var mySsrcGroup = myMedia.ssrcGroups[i];
  12055. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12056. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12057. matched = true;
  12058. break;
  12059. }
  12060. }
  12061. if (!matched) {
  12062. // Allocate channel if we've found an ssrc-group that doesn't
  12063. // exist in our channel
  12064. if(!newMedia[othersMediaIdx]){
  12065. newMedia[othersMediaIdx] = {
  12066. mediaindex: othersMedia.mediaindex,
  12067. mid: othersMedia.mid,
  12068. ssrcs: {},
  12069. ssrcGroups: []
  12070. };
  12071. }
  12072. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12073. }
  12074. });
  12075. });
  12076. return newMedia;
  12077. };
  12078. /**
  12079. * Sends SSRC update IQ.
  12080. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12081. * @param sid session identifier that will be put into the IQ.
  12082. * @param initiator initiator identifier.
  12083. * @param toJid destination Jid
  12084. * @param isAdd indicates if this is remove or add operation.
  12085. */
  12086. SDPDiffer.prototype.toJingle = function(modify) {
  12087. var sdpMediaSsrcs = this.getNewMedia();
  12088. var self = this;
  12089. // FIXME: only announce video ssrcs since we mix audio and dont need
  12090. // the audio ssrcs therefore
  12091. var modified = false;
  12092. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12093. modified = true;
  12094. var media = sdpMediaSsrcs[mediaindex];
  12095. modify.c('content', {name: media.mid});
  12096. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12097. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12098. // generate sources from lines
  12099. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12100. var mediaSsrc = media.ssrcs[ssrcNum];
  12101. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12102. modify.attrs({ssrc: mediaSsrc.ssrc});
  12103. // iterate over ssrc lines
  12104. mediaSsrc.lines.forEach(function (line) {
  12105. var idx = line.indexOf(' ');
  12106. var kv = line.substr(idx + 1);
  12107. modify.c('parameter');
  12108. if (kv.indexOf(':') == -1) {
  12109. modify.attrs({ name: kv });
  12110. } else {
  12111. modify.attrs({ name: kv.split(':', 2)[0] });
  12112. modify.attrs({ value: kv.split(':', 2)[1] });
  12113. }
  12114. modify.up(); // end of parameter
  12115. });
  12116. modify.up(); // end of source
  12117. });
  12118. // generate source groups from lines
  12119. media.ssrcGroups.forEach(function(ssrcGroup) {
  12120. if (ssrcGroup.ssrcs.length != 0) {
  12121. modify.c('ssrc-group', {
  12122. semantics: ssrcGroup.semantics,
  12123. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12124. });
  12125. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12126. modify.c('source', { ssrc: ssrc })
  12127. .up(); // end of source
  12128. });
  12129. modify.up(); // end of ssrc-group
  12130. }
  12131. });
  12132. modify.up(); // end of description
  12133. modify.up(); // end of content
  12134. });
  12135. return modified;
  12136. };
  12137. module.exports = SDPDiffer;
  12138. },{}],50:[function(require,module,exports){
  12139. SDPUtil = {
  12140. iceparams: function (mediadesc, sessiondesc) {
  12141. var data = null;
  12142. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  12143. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  12144. data = {
  12145. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  12146. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  12147. };
  12148. }
  12149. return data;
  12150. },
  12151. parse_iceufrag: function (line) {
  12152. return line.substring(12);
  12153. },
  12154. build_iceufrag: function (frag) {
  12155. return 'a=ice-ufrag:' + frag;
  12156. },
  12157. parse_icepwd: function (line) {
  12158. return line.substring(10);
  12159. },
  12160. build_icepwd: function (pwd) {
  12161. return 'a=ice-pwd:' + pwd;
  12162. },
  12163. parse_mid: function (line) {
  12164. return line.substring(6);
  12165. },
  12166. parse_mline: function (line) {
  12167. var parts = line.substring(2).split(' '),
  12168. data = {};
  12169. data.media = parts.shift();
  12170. data.port = parts.shift();
  12171. data.proto = parts.shift();
  12172. if (parts[parts.length - 1] === '') { // trailing whitespace
  12173. parts.pop();
  12174. }
  12175. data.fmt = parts;
  12176. return data;
  12177. },
  12178. build_mline: function (mline) {
  12179. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  12180. },
  12181. parse_rtpmap: function (line) {
  12182. var parts = line.substring(9).split(' '),
  12183. data = {};
  12184. data.id = parts.shift();
  12185. parts = parts[0].split('/');
  12186. data.name = parts.shift();
  12187. data.clockrate = parts.shift();
  12188. data.channels = parts.length ? parts.shift() : '1';
  12189. return data;
  12190. },
  12191. /**
  12192. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  12193. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  12194. * @returns [SCTP port number, protocol, streams]
  12195. */
  12196. parse_sctpmap: function (line)
  12197. {
  12198. var parts = line.substring(10).split(' ');
  12199. var sctpPort = parts[0];
  12200. var protocol = parts[1];
  12201. // Stream count is optional
  12202. var streamCount = parts.length > 2 ? parts[2] : null;
  12203. return [sctpPort, protocol, streamCount];// SCTP port
  12204. },
  12205. build_rtpmap: function (el) {
  12206. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  12207. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  12208. line += '/' + el.getAttribute('channels');
  12209. }
  12210. return line;
  12211. },
  12212. parse_crypto: function (line) {
  12213. var parts = line.substring(9).split(' '),
  12214. data = {};
  12215. data.tag = parts.shift();
  12216. data['crypto-suite'] = parts.shift();
  12217. data['key-params'] = parts.shift();
  12218. if (parts.length) {
  12219. data['session-params'] = parts.join(' ');
  12220. }
  12221. return data;
  12222. },
  12223. parse_fingerprint: function (line) { // RFC 4572
  12224. var parts = line.substring(14).split(' '),
  12225. data = {};
  12226. data.hash = parts.shift();
  12227. data.fingerprint = parts.shift();
  12228. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  12229. return data;
  12230. },
  12231. parse_fmtp: function (line) {
  12232. var parts = line.split(' '),
  12233. i, key, value,
  12234. data = [];
  12235. parts.shift();
  12236. parts = parts.join(' ').split(';');
  12237. for (i = 0; i < parts.length; i++) {
  12238. key = parts[i].split('=')[0];
  12239. while (key.length && key[0] == ' ') {
  12240. key = key.substring(1);
  12241. }
  12242. value = parts[i].split('=')[1];
  12243. if (key && value) {
  12244. data.push({name: key, value: value});
  12245. } else if (key) {
  12246. // rfc 4733 (DTMF) style stuff
  12247. data.push({name: '', value: key});
  12248. }
  12249. }
  12250. return data;
  12251. },
  12252. parse_icecandidate: function (line) {
  12253. var candidate = {},
  12254. elems = line.split(' ');
  12255. candidate.foundation = elems[0].substring(12);
  12256. candidate.component = elems[1];
  12257. candidate.protocol = elems[2].toLowerCase();
  12258. candidate.priority = elems[3];
  12259. candidate.ip = elems[4];
  12260. candidate.port = elems[5];
  12261. // elems[6] => "typ"
  12262. candidate.type = elems[7];
  12263. candidate.generation = 0; // default value, may be overwritten below
  12264. for (var i = 8; i < elems.length; i += 2) {
  12265. switch (elems[i]) {
  12266. case 'raddr':
  12267. candidate['rel-addr'] = elems[i + 1];
  12268. break;
  12269. case 'rport':
  12270. candidate['rel-port'] = elems[i + 1];
  12271. break;
  12272. case 'generation':
  12273. candidate.generation = elems[i + 1];
  12274. break;
  12275. case 'tcptype':
  12276. candidate.tcptype = elems[i + 1];
  12277. break;
  12278. default: // TODO
  12279. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12280. }
  12281. }
  12282. candidate.network = '1';
  12283. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12284. return candidate;
  12285. },
  12286. build_icecandidate: function (cand) {
  12287. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  12288. line += ' ';
  12289. switch (cand.type) {
  12290. case 'srflx':
  12291. case 'prflx':
  12292. case 'relay':
  12293. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  12294. line += 'raddr';
  12295. line += ' ';
  12296. line += cand['rel-addr'];
  12297. line += ' ';
  12298. line += 'rport';
  12299. line += ' ';
  12300. line += cand['rel-port'];
  12301. line += ' ';
  12302. }
  12303. break;
  12304. }
  12305. if (cand.hasOwnAttribute('tcptype')) {
  12306. line += 'tcptype';
  12307. line += ' ';
  12308. line += cand.tcptype;
  12309. line += ' ';
  12310. }
  12311. line += 'generation';
  12312. line += ' ';
  12313. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  12314. return line;
  12315. },
  12316. parse_ssrc: function (desc) {
  12317. // proprietary mapping of a=ssrc lines
  12318. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  12319. // and parse according to that
  12320. var lines = desc.split('\r\n'),
  12321. data = {};
  12322. for (var i = 0; i < lines.length; i++) {
  12323. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  12324. var idx = lines[i].indexOf(' ');
  12325. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  12326. }
  12327. }
  12328. return data;
  12329. },
  12330. parse_rtcpfb: function (line) {
  12331. var parts = line.substr(10).split(' ');
  12332. var data = {};
  12333. data.pt = parts.shift();
  12334. data.type = parts.shift();
  12335. data.params = parts;
  12336. return data;
  12337. },
  12338. parse_extmap: function (line) {
  12339. var parts = line.substr(9).split(' ');
  12340. var data = {};
  12341. data.value = parts.shift();
  12342. if (data.value.indexOf('/') != -1) {
  12343. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  12344. data.value = data.value.substr(0, data.value.indexOf('/'));
  12345. } else {
  12346. data.direction = 'both';
  12347. }
  12348. data.uri = parts.shift();
  12349. data.params = parts;
  12350. return data;
  12351. },
  12352. find_line: function (haystack, needle, sessionpart) {
  12353. var lines = haystack.split('\r\n');
  12354. for (var i = 0; i < lines.length; i++) {
  12355. if (lines[i].substring(0, needle.length) == needle) {
  12356. return lines[i];
  12357. }
  12358. }
  12359. if (!sessionpart) {
  12360. return false;
  12361. }
  12362. // search session part
  12363. lines = sessionpart.split('\r\n');
  12364. for (var j = 0; j < lines.length; j++) {
  12365. if (lines[j].substring(0, needle.length) == needle) {
  12366. return lines[j];
  12367. }
  12368. }
  12369. return false;
  12370. },
  12371. find_lines: function (haystack, needle, sessionpart) {
  12372. var lines = haystack.split('\r\n'),
  12373. needles = [];
  12374. for (var i = 0; i < lines.length; i++) {
  12375. if (lines[i].substring(0, needle.length) == needle)
  12376. needles.push(lines[i]);
  12377. }
  12378. if (needles.length || !sessionpart) {
  12379. return needles;
  12380. }
  12381. // search session part
  12382. lines = sessionpart.split('\r\n');
  12383. for (var j = 0; j < lines.length; j++) {
  12384. if (lines[j].substring(0, needle.length) == needle) {
  12385. needles.push(lines[j]);
  12386. }
  12387. }
  12388. return needles;
  12389. },
  12390. candidateToJingle: function (line) {
  12391. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  12392. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  12393. if (line.indexOf('candidate:') === 0) {
  12394. line = 'a=' + line;
  12395. } else if (line.substring(0, 12) != 'a=candidate:') {
  12396. console.log('parseCandidate called with a line that is not a candidate line');
  12397. console.log(line);
  12398. return null;
  12399. }
  12400. if (line.substring(line.length - 2) == '\r\n') // chomp it
  12401. line = line.substring(0, line.length - 2);
  12402. var candidate = {},
  12403. elems = line.split(' '),
  12404. i;
  12405. if (elems[6] != 'typ') {
  12406. console.log('did not find typ in the right place');
  12407. console.log(line);
  12408. return null;
  12409. }
  12410. candidate.foundation = elems[0].substring(12);
  12411. candidate.component = elems[1];
  12412. candidate.protocol = elems[2].toLowerCase();
  12413. candidate.priority = elems[3];
  12414. candidate.ip = elems[4];
  12415. candidate.port = elems[5];
  12416. // elems[6] => "typ"
  12417. candidate.type = elems[7];
  12418. candidate.generation = '0'; // default, may be overwritten below
  12419. for (i = 8; i < elems.length; i += 2) {
  12420. switch (elems[i]) {
  12421. case 'raddr':
  12422. candidate['rel-addr'] = elems[i + 1];
  12423. break;
  12424. case 'rport':
  12425. candidate['rel-port'] = elems[i + 1];
  12426. break;
  12427. case 'generation':
  12428. candidate.generation = elems[i + 1];
  12429. break;
  12430. case 'tcptype':
  12431. candidate.tcptype = elems[i + 1];
  12432. break;
  12433. default: // TODO
  12434. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12435. }
  12436. }
  12437. candidate.network = '1';
  12438. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12439. return candidate;
  12440. },
  12441. candidateFromJingle: function (cand) {
  12442. var line = 'a=candidate:';
  12443. line += cand.getAttribute('foundation');
  12444. line += ' ';
  12445. line += cand.getAttribute('component');
  12446. line += ' ';
  12447. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  12448. line += ' ';
  12449. line += cand.getAttribute('priority');
  12450. line += ' ';
  12451. line += cand.getAttribute('ip');
  12452. line += ' ';
  12453. line += cand.getAttribute('port');
  12454. line += ' ';
  12455. line += 'typ';
  12456. line += ' ' + cand.getAttribute('type');
  12457. line += ' ';
  12458. switch (cand.getAttribute('type')) {
  12459. case 'srflx':
  12460. case 'prflx':
  12461. case 'relay':
  12462. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  12463. line += 'raddr';
  12464. line += ' ';
  12465. line += cand.getAttribute('rel-addr');
  12466. line += ' ';
  12467. line += 'rport';
  12468. line += ' ';
  12469. line += cand.getAttribute('rel-port');
  12470. line += ' ';
  12471. }
  12472. break;
  12473. }
  12474. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  12475. line += 'tcptype';
  12476. line += ' ';
  12477. line += cand.getAttribute('tcptype');
  12478. line += ' ';
  12479. }
  12480. line += 'generation';
  12481. line += ' ';
  12482. line += cand.getAttribute('generation') || '0';
  12483. return line + '\r\n';
  12484. }
  12485. };
  12486. module.exports = SDPUtil;
  12487. },{}],51:[function(require,module,exports){
  12488. function TraceablePeerConnection(ice_config, constraints) {
  12489. var self = this;
  12490. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  12491. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  12492. this.updateLog = [];
  12493. this.stats = {};
  12494. this.statsinterval = null;
  12495. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  12496. // override as desired
  12497. this.trace = function (what, info) {
  12498. //console.warn('WTRACE', what, info);
  12499. self.updateLog.push({
  12500. time: new Date(),
  12501. type: what,
  12502. value: info || ""
  12503. });
  12504. };
  12505. this.onicecandidate = null;
  12506. this.peerconnection.onicecandidate = function (event) {
  12507. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  12508. if (self.onicecandidate !== null) {
  12509. self.onicecandidate(event);
  12510. }
  12511. };
  12512. this.onaddstream = null;
  12513. this.peerconnection.onaddstream = function (event) {
  12514. self.trace('onaddstream', event.stream.id);
  12515. if (self.onaddstream !== null) {
  12516. self.onaddstream(event);
  12517. }
  12518. };
  12519. this.onremovestream = null;
  12520. this.peerconnection.onremovestream = function (event) {
  12521. self.trace('onremovestream', event.stream.id);
  12522. if (self.onremovestream !== null) {
  12523. self.onremovestream(event);
  12524. }
  12525. };
  12526. this.onsignalingstatechange = null;
  12527. this.peerconnection.onsignalingstatechange = function (event) {
  12528. self.trace('onsignalingstatechange', self.signalingState);
  12529. if (self.onsignalingstatechange !== null) {
  12530. self.onsignalingstatechange(event);
  12531. }
  12532. };
  12533. this.oniceconnectionstatechange = null;
  12534. this.peerconnection.oniceconnectionstatechange = function (event) {
  12535. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12536. if (self.oniceconnectionstatechange !== null) {
  12537. self.oniceconnectionstatechange(event);
  12538. }
  12539. };
  12540. this.onnegotiationneeded = null;
  12541. this.peerconnection.onnegotiationneeded = function (event) {
  12542. self.trace('onnegotiationneeded');
  12543. if (self.onnegotiationneeded !== null) {
  12544. self.onnegotiationneeded(event);
  12545. }
  12546. };
  12547. self.ondatachannel = null;
  12548. this.peerconnection.ondatachannel = function (event) {
  12549. self.trace('ondatachannel', event);
  12550. if (self.ondatachannel !== null) {
  12551. self.ondatachannel(event);
  12552. }
  12553. };
  12554. if (!navigator.mozGetUserMedia && this.maxstats) {
  12555. this.statsinterval = window.setInterval(function() {
  12556. self.peerconnection.getStats(function(stats) {
  12557. var results = stats.result();
  12558. for (var i = 0; i < results.length; ++i) {
  12559. //console.log(results[i].type, results[i].id, results[i].names())
  12560. var now = new Date();
  12561. results[i].names().forEach(function (name) {
  12562. var id = results[i].id + '-' + name;
  12563. if (!self.stats[id]) {
  12564. self.stats[id] = {
  12565. startTime: now,
  12566. endTime: now,
  12567. values: [],
  12568. times: []
  12569. };
  12570. }
  12571. self.stats[id].values.push(results[i].stat(name));
  12572. self.stats[id].times.push(now.getTime());
  12573. if (self.stats[id].values.length > self.maxstats) {
  12574. self.stats[id].values.shift();
  12575. self.stats[id].times.shift();
  12576. }
  12577. self.stats[id].endTime = now;
  12578. });
  12579. }
  12580. });
  12581. }, 1000);
  12582. }
  12583. };
  12584. dumpSDP = function(description) {
  12585. return 'type: ' + description.type + '\r\n' + description.sdp;
  12586. }
  12587. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  12588. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  12589. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  12590. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  12591. var publicLocalDescription = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  12592. return publicLocalDescription;
  12593. });
  12594. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  12595. var publicRemoteDescription = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  12596. return publicRemoteDescription;
  12597. });
  12598. }
  12599. TraceablePeerConnection.prototype.addStream = function (stream) {
  12600. this.trace('addStream', stream.id);
  12601. APP.simulcast.resetSender();
  12602. try
  12603. {
  12604. this.peerconnection.addStream(stream);
  12605. }
  12606. catch (e)
  12607. {
  12608. console.error(e);
  12609. return;
  12610. }
  12611. };
  12612. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  12613. this.trace('removeStream', stream.id);
  12614. APP.simulcast.resetSender();
  12615. if(stopStreams) {
  12616. stream.getAudioTracks().forEach(function (track) {
  12617. track.stop();
  12618. });
  12619. stream.getVideoTracks().forEach(function (track) {
  12620. track.stop();
  12621. });
  12622. }
  12623. this.peerconnection.removeStream(stream);
  12624. };
  12625. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  12626. this.trace('createDataChannel', label, opts);
  12627. return this.peerconnection.createDataChannel(label, opts);
  12628. };
  12629. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  12630. var self = this;
  12631. description = APP.simulcast.transformLocalDescription(description);
  12632. this.trace('setLocalDescription', dumpSDP(description));
  12633. this.peerconnection.setLocalDescription(description,
  12634. function () {
  12635. self.trace('setLocalDescriptionOnSuccess');
  12636. successCallback();
  12637. },
  12638. function (err) {
  12639. self.trace('setLocalDescriptionOnFailure', err);
  12640. failureCallback(err);
  12641. }
  12642. );
  12643. /*
  12644. if (this.statsinterval === null && this.maxstats > 0) {
  12645. // start gathering stats
  12646. }
  12647. */
  12648. };
  12649. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  12650. var self = this;
  12651. description = APP.simulcast.transformRemoteDescription(description);
  12652. this.trace('setRemoteDescription', dumpSDP(description));
  12653. this.peerconnection.setRemoteDescription(description,
  12654. function () {
  12655. self.trace('setRemoteDescriptionOnSuccess');
  12656. successCallback();
  12657. },
  12658. function (err) {
  12659. self.trace('setRemoteDescriptionOnFailure', err);
  12660. failureCallback(err);
  12661. }
  12662. );
  12663. /*
  12664. if (this.statsinterval === null && this.maxstats > 0) {
  12665. // start gathering stats
  12666. }
  12667. */
  12668. };
  12669. TraceablePeerConnection.prototype.close = function () {
  12670. this.trace('stop');
  12671. if (this.statsinterval !== null) {
  12672. window.clearInterval(this.statsinterval);
  12673. this.statsinterval = null;
  12674. }
  12675. this.peerconnection.close();
  12676. };
  12677. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  12678. var self = this;
  12679. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  12680. this.peerconnection.createOffer(
  12681. function (offer) {
  12682. self.trace('createOfferOnSuccess', dumpSDP(offer));
  12683. successCallback(offer);
  12684. },
  12685. function(err) {
  12686. self.trace('createOfferOnFailure', err);
  12687. failureCallback(err);
  12688. },
  12689. constraints
  12690. );
  12691. };
  12692. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  12693. var self = this;
  12694. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  12695. this.peerconnection.createAnswer(
  12696. function (answer) {
  12697. answer = APP.simulcast.transformAnswer(answer);
  12698. self.trace('createAnswerOnSuccess', dumpSDP(answer));
  12699. successCallback(answer);
  12700. },
  12701. function(err) {
  12702. self.trace('createAnswerOnFailure', err);
  12703. failureCallback(err);
  12704. },
  12705. constraints
  12706. );
  12707. };
  12708. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  12709. var self = this;
  12710. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  12711. this.peerconnection.addIceCandidate(candidate);
  12712. /* maybe later
  12713. this.peerconnection.addIceCandidate(candidate,
  12714. function () {
  12715. self.trace('addIceCandidateOnSuccess');
  12716. successCallback();
  12717. },
  12718. function (err) {
  12719. self.trace('addIceCandidateOnFailure', err);
  12720. failureCallback(err);
  12721. }
  12722. );
  12723. */
  12724. };
  12725. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  12726. if (navigator.mozGetUserMedia) {
  12727. // ignore for now...
  12728. if(!errback)
  12729. errback = function () {
  12730. }
  12731. this.peerconnection.getStats(null,callback,errback);
  12732. } else {
  12733. this.peerconnection.getStats(callback);
  12734. }
  12735. };
  12736. module.exports = TraceablePeerConnection;
  12737. },{}],52:[function(require,module,exports){
  12738. /* global $, $iq, APP, config, connection, UI, messageHandler,
  12739. roomName, sessionTerminated, Strophe, Util */
  12740. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  12741. var Settings = require("../settings/Settings");
  12742. var AuthenticationEvents
  12743. = require("../../service/authentication/AuthenticationEvents");
  12744. /**
  12745. * Contains logic responsible for enabling/disabling functionality available
  12746. * only to moderator users.
  12747. */
  12748. var connection = null;
  12749. var focusUserJid;
  12750. function createExpBackoffTimer(step) {
  12751. var count = 1;
  12752. return function (reset) {
  12753. // Reset call
  12754. if (reset) {
  12755. count = 1;
  12756. return;
  12757. }
  12758. // Calculate next timeout
  12759. var timeout = Math.pow(2, count - 1);
  12760. count += 1;
  12761. return timeout * step;
  12762. };
  12763. }
  12764. var getNextTimeout = createExpBackoffTimer(1000);
  12765. var getNextErrorTimeout = createExpBackoffTimer(1000);
  12766. // External authentication stuff
  12767. var externalAuthEnabled = false;
  12768. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  12769. // it will be enabled automatically if focus detects the component through
  12770. // service discovery.
  12771. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  12772. var eventEmitter = null;
  12773. var Moderator = {
  12774. isModerator: function () {
  12775. return connection && connection.emuc.isModerator();
  12776. },
  12777. isPeerModerator: function (peerJid) {
  12778. return connection &&
  12779. connection.emuc.getMemberRole(peerJid) === 'moderator';
  12780. },
  12781. isExternalAuthEnabled: function () {
  12782. return externalAuthEnabled;
  12783. },
  12784. isSipGatewayEnabled: function () {
  12785. return sipGatewayEnabled;
  12786. },
  12787. setConnection: function (con) {
  12788. connection = con;
  12789. },
  12790. init: function (xmpp, emitter) {
  12791. this.xmppService = xmpp;
  12792. eventEmitter = emitter;
  12793. // Message listener that talks to POPUP window
  12794. function listener(event) {
  12795. if (event.data && event.data.sessionId) {
  12796. if (event.origin !== window.location.origin) {
  12797. console.warn(
  12798. "Ignoring sessionId from different origin: " + event.origin);
  12799. return;
  12800. }
  12801. localStorage.setItem('sessionId', event.data.sessionId);
  12802. // After popup is closed we will authenticate
  12803. }
  12804. }
  12805. // Register
  12806. if (window.addEventListener) {
  12807. window.addEventListener("message", listener, false);
  12808. } else {
  12809. window.attachEvent("onmessage", listener);
  12810. }
  12811. },
  12812. onMucLeft: function (jid) {
  12813. console.info("Someone left is it focus ? " + jid);
  12814. var resource = Strophe.getResourceFromJid(jid);
  12815. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  12816. console.info(
  12817. "Focus has left the room - leaving conference");
  12818. //hangUp();
  12819. // We'd rather reload to have everything re-initialized
  12820. // FIXME: show some message before reload
  12821. location.reload();
  12822. }
  12823. },
  12824. setFocusUserJid: function (focusJid) {
  12825. if (!focusUserJid) {
  12826. focusUserJid = focusJid;
  12827. console.info("Focus jid set to: " + focusUserJid);
  12828. }
  12829. },
  12830. getFocusUserJid: function () {
  12831. return focusUserJid;
  12832. },
  12833. getFocusComponent: function () {
  12834. // Get focus component address
  12835. var focusComponent = config.hosts.focus;
  12836. // If not specified use default: 'focus.domain'
  12837. if (!focusComponent) {
  12838. focusComponent = 'focus.' + config.hosts.domain;
  12839. }
  12840. return focusComponent;
  12841. },
  12842. createConferenceIq: function (roomName) {
  12843. // Generate create conference IQ
  12844. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  12845. // Session Id used for authentication
  12846. var sessionId = localStorage.getItem('sessionId');
  12847. var machineUID = Settings.getSettings().uid;
  12848. console.info(
  12849. "Session ID: " + sessionId + " machine UID: " + machineUID);
  12850. elem.c('conference', {
  12851. xmlns: 'http://jitsi.org/protocol/focus',
  12852. room: roomName,
  12853. 'machine-uid': machineUID
  12854. });
  12855. if (sessionId) {
  12856. elem.attrs({ 'session-id': sessionId});
  12857. }
  12858. if (config.hosts.bridge !== undefined) {
  12859. elem.c(
  12860. 'property',
  12861. { name: 'bridge', value: config.hosts.bridge})
  12862. .up();
  12863. }
  12864. // Tell the focus we have Jigasi configured
  12865. if (config.hosts.call_control !== undefined) {
  12866. elem.c(
  12867. 'property',
  12868. { name: 'call_control', value: config.hosts.call_control})
  12869. .up();
  12870. }
  12871. if (config.channelLastN !== undefined) {
  12872. elem.c(
  12873. 'property',
  12874. { name: 'channelLastN', value: config.channelLastN})
  12875. .up();
  12876. }
  12877. if (config.adaptiveLastN !== undefined) {
  12878. elem.c(
  12879. 'property',
  12880. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  12881. .up();
  12882. }
  12883. if (config.adaptiveSimulcast !== undefined) {
  12884. elem.c(
  12885. 'property',
  12886. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  12887. .up();
  12888. }
  12889. if (config.openSctp !== undefined) {
  12890. elem.c(
  12891. 'property',
  12892. { name: 'openSctp', value: config.openSctp})
  12893. .up();
  12894. }
  12895. if (config.enableFirefoxSupport !== undefined) {
  12896. elem.c(
  12897. 'property',
  12898. { name: 'enableFirefoxHacks',
  12899. value: config.enableFirefoxSupport})
  12900. .up();
  12901. }
  12902. elem.up();
  12903. return elem;
  12904. },
  12905. parseConfigOptions: function (resultIq) {
  12906. Moderator.setFocusUserJid(
  12907. $(resultIq).find('conference').attr('focusjid'));
  12908. var authenticationEnabled
  12909. = $(resultIq).find(
  12910. '>conference>property' +
  12911. '[name=\'authentication\'][value=\'true\']').length > 0;
  12912. console.info("Authentication enabled: " + authenticationEnabled);
  12913. externalAuthEnabled
  12914. = $(resultIq).find(
  12915. '>conference>property' +
  12916. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  12917. console.info('External authentication enabled: ' + externalAuthEnabled);
  12918. if (!externalAuthEnabled) {
  12919. // We expect to receive sessionId in 'internal' authentication mode
  12920. var sessionId
  12921. = $(resultIq).find('conference').attr('session-id');
  12922. if (sessionId) {
  12923. console.info('Received sessionId: ' + sessionId);
  12924. localStorage.setItem('sessionId', sessionId);
  12925. }
  12926. }
  12927. var authIdentity = $(resultIq).find('>conference').attr('identity');
  12928. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  12929. authenticationEnabled, authIdentity);
  12930. // Check if focus has auto-detected Jigasi component(this will be also
  12931. // included if we have passed our host from the config)
  12932. if ($(resultIq).find(
  12933. '>conference>property' +
  12934. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  12935. sipGatewayEnabled = true;
  12936. }
  12937. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  12938. },
  12939. // FIXME: we need to show the fact that we're waiting for the focus
  12940. // to the user(or that focus is not available)
  12941. allocateConferenceFocus: function (roomName, callback) {
  12942. // Try to use focus user JID from the config
  12943. Moderator.setFocusUserJid(config.focusUserJid);
  12944. // Send create conference IQ
  12945. var iq = Moderator.createConferenceIq(roomName);
  12946. var self = this;
  12947. connection.sendIQ(
  12948. iq,
  12949. function (result) {
  12950. // Setup config options
  12951. Moderator.parseConfigOptions(result);
  12952. if ('true' === $(result).find('conference').attr('ready')) {
  12953. // Reset both timers
  12954. getNextTimeout(true);
  12955. getNextErrorTimeout(true);
  12956. // Exec callback
  12957. callback();
  12958. } else {
  12959. var waitMs = getNextTimeout();
  12960. console.info("Waiting for the focus... " + waitMs);
  12961. // Reset error timeout
  12962. getNextErrorTimeout(true);
  12963. window.setTimeout(
  12964. function () {
  12965. Moderator.allocateConferenceFocus(
  12966. roomName, callback);
  12967. }, waitMs);
  12968. }
  12969. },
  12970. function (error) {
  12971. // Invalid session ? remove and try again
  12972. // without session ID to get a new one
  12973. var invalidSession
  12974. = $(error).find('>error>session-invalid').length;
  12975. if (invalidSession) {
  12976. console.info("Session expired! - removing");
  12977. localStorage.removeItem("sessionId");
  12978. }
  12979. if ($(error).find('>error>graceful-shutdown').length) {
  12980. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  12981. return;
  12982. }
  12983. // Check for error returned by the reservation system
  12984. var reservationErr = $(error).find('>error>reservation-error');
  12985. if (reservationErr.length) {
  12986. // Trigger error event
  12987. var errorCode = reservationErr.attr('error-code');
  12988. var errorMsg;
  12989. if ($(error).find('>error>text')) {
  12990. errorMsg = $(error).find('>error>text').text();
  12991. }
  12992. eventEmitter.emit(
  12993. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  12994. return;
  12995. }
  12996. // Not authorized to create new room
  12997. if ($(error).find('>error>not-authorized').length) {
  12998. console.warn("Unauthorized to start the conference", error);
  12999. var toDomain
  13000. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13001. if (toDomain === config.hosts.anonymousdomain) {
  13002. // we are connected with anonymous domain and
  13003. // only non anonymous users can create rooms
  13004. // we must authorize the user
  13005. self.xmppService.promptLogin();
  13006. } else {
  13007. // External authentication mode
  13008. eventEmitter.emit(
  13009. XMPPEvents.AUTHENTICATION_REQUIRED,
  13010. function () {
  13011. Moderator.allocateConferenceFocus(
  13012. roomName, callback);
  13013. });
  13014. }
  13015. return;
  13016. }
  13017. var waitMs = getNextErrorTimeout();
  13018. console.error("Focus error, retry after " + waitMs, error);
  13019. // Show message
  13020. var focusComponent = Moderator.getFocusComponent();
  13021. var retrySec = waitMs / 1000;
  13022. // FIXME: message is duplicated ?
  13023. // Do not show in case of session invalid
  13024. // which means just a retry
  13025. if (!invalidSession) {
  13026. APP.UI.messageHandler.notify(
  13027. null, "notify.focus",
  13028. 'disconnected', "notify.focusFail",
  13029. {component: focusComponent, ms: retrySec});
  13030. }
  13031. // Reset response timeout
  13032. getNextTimeout(true);
  13033. window.setTimeout(
  13034. function () {
  13035. Moderator.allocateConferenceFocus(roomName, callback);
  13036. }, waitMs);
  13037. }
  13038. );
  13039. },
  13040. getLoginUrl: function (roomName, urlCallback) {
  13041. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13042. iq.c('login-url', {
  13043. xmlns: 'http://jitsi.org/protocol/focus',
  13044. room: roomName,
  13045. 'machine-uid': Settings.getSettings().uid
  13046. });
  13047. connection.sendIQ(
  13048. iq,
  13049. function (result) {
  13050. var url = $(result).find('login-url').attr('url');
  13051. url = url = decodeURIComponent(url);
  13052. if (url) {
  13053. console.info("Got auth url: " + url);
  13054. urlCallback(url);
  13055. } else {
  13056. console.error(
  13057. "Failed to get auth url from the focus", result);
  13058. }
  13059. },
  13060. function (error) {
  13061. console.error("Get auth url error", error);
  13062. }
  13063. );
  13064. },
  13065. getPopupLoginUrl: function (roomName, urlCallback) {
  13066. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13067. iq.c('login-url', {
  13068. xmlns: 'http://jitsi.org/protocol/focus',
  13069. room: roomName,
  13070. 'machine-uid': Settings.getSettings().uid,
  13071. popup: true
  13072. });
  13073. connection.sendIQ(
  13074. iq,
  13075. function (result) {
  13076. var url = $(result).find('login-url').attr('url');
  13077. url = url = decodeURIComponent(url);
  13078. if (url) {
  13079. console.info("Got POPUP auth url: " + url);
  13080. urlCallback(url);
  13081. } else {
  13082. console.error(
  13083. "Failed to get POPUP auth url from the focus", result);
  13084. }
  13085. },
  13086. function (error) {
  13087. console.error('Get POPUP auth url error', error);
  13088. }
  13089. );
  13090. },
  13091. logout: function (callback) {
  13092. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13093. var sessionId = localStorage.getItem('sessionId');
  13094. if (!sessionId) {
  13095. callback();
  13096. return;
  13097. }
  13098. iq.c('logout', {
  13099. xmlns: 'http://jitsi.org/protocol/focus',
  13100. 'session-id': sessionId
  13101. });
  13102. connection.sendIQ(
  13103. iq,
  13104. function (result) {
  13105. var logoutUrl = $(result).find('logout').attr('logout-url');
  13106. if (logoutUrl) {
  13107. logoutUrl = decodeURIComponent(logoutUrl);
  13108. }
  13109. console.info("Log out OK, url: " + logoutUrl, result);
  13110. localStorage.removeItem('sessionId');
  13111. callback(logoutUrl);
  13112. },
  13113. function (error) {
  13114. console.error("Logout error", error);
  13115. }
  13116. );
  13117. }
  13118. };
  13119. module.exports = Moderator;
  13120. },{"../../service/authentication/AuthenticationEvents":84,"../../service/xmpp/XMPPEvents":88,"../settings/Settings":37}],53:[function(require,module,exports){
  13121. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  13122. Toolbar, Util */
  13123. var Moderator = require("./moderator");
  13124. var recordingToken = null;
  13125. var recordingEnabled;
  13126. /**
  13127. * Whether to use a jirecon component for recording, or use the videobridge
  13128. * through COLIBRI.
  13129. */
  13130. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  13131. /**
  13132. * The ID of the jirecon recording session. Jirecon generates it when we
  13133. * initially start recording, and it needs to be used in subsequent requests
  13134. * to jirecon.
  13135. */
  13136. var jireconRid = null;
  13137. function setRecordingToken(token) {
  13138. recordingToken = token;
  13139. }
  13140. function setRecording(state, token, callback, connection) {
  13141. if (useJirecon){
  13142. setRecordingJirecon(state, token, callback, connection);
  13143. } else {
  13144. setRecordingColibri(state, token, callback, connection);
  13145. }
  13146. }
  13147. function setRecordingJirecon(state, token, callback, connection) {
  13148. if (state == recordingEnabled){
  13149. return;
  13150. }
  13151. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  13152. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  13153. action: state ? 'start' : 'stop',
  13154. mucjid: connection.emuc.roomjid});
  13155. if (!state){
  13156. iq.attrs({rid: jireconRid});
  13157. }
  13158. console.log('Start recording');
  13159. connection.sendIQ(
  13160. iq,
  13161. function (result) {
  13162. // TODO wait for an IQ with the real status, since this is
  13163. // provisional?
  13164. jireconRid = $(result).find('recording').attr('rid');
  13165. console.log('Recording ' + (state ? 'started' : 'stopped') +
  13166. '(jirecon)' + result);
  13167. recordingEnabled = state;
  13168. if (!state){
  13169. jireconRid = null;
  13170. }
  13171. callback(state);
  13172. },
  13173. function (error) {
  13174. console.log('Failed to start recording, error: ', error);
  13175. callback(recordingEnabled);
  13176. });
  13177. }
  13178. // Sends a COLIBRI message which enables or disables (according to 'state')
  13179. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  13180. // with the new recording state, according to the IQ.
  13181. function setRecordingColibri(state, token, callback, connection) {
  13182. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  13183. elem.c('conference', {
  13184. xmlns: 'http://jitsi.org/protocol/colibri'
  13185. });
  13186. elem.c('recording', {state: state, token: token});
  13187. connection.sendIQ(elem,
  13188. function (result) {
  13189. console.log('Set recording "', state, '". Result:', result);
  13190. var recordingElem = $(result).find('>conference>recording');
  13191. var newState = ('true' === recordingElem.attr('state'));
  13192. recordingEnabled = newState;
  13193. callback(newState);
  13194. },
  13195. function (error) {
  13196. console.warn(error);
  13197. callback(recordingEnabled);
  13198. }
  13199. );
  13200. }
  13201. var Recording = {
  13202. toggleRecording: function (tokenEmptyCallback,
  13203. startingCallback, startedCallback, connection) {
  13204. if (!Moderator.isModerator()) {
  13205. console.log(
  13206. 'non-focus, or conference not yet organized:' +
  13207. ' not enabling recording');
  13208. return;
  13209. }
  13210. var self = this;
  13211. // Jirecon does not (currently) support a token.
  13212. if (!recordingToken && !useJirecon) {
  13213. tokenEmptyCallback(function (value) {
  13214. setRecordingToken(value);
  13215. self.toggleRecording(tokenEmptyCallback,
  13216. startingCallback, startedCallback, connection);
  13217. });
  13218. return;
  13219. }
  13220. var oldState = recordingEnabled;
  13221. startingCallback(!oldState);
  13222. setRecording(!oldState,
  13223. recordingToken,
  13224. function (state) {
  13225. console.log("New recording state: ", state);
  13226. if (state === oldState) {
  13227. // FIXME: new focus:
  13228. // this will not work when moderator changes
  13229. // during active session. Then it will assume that
  13230. // recording status has changed to true, but it might have
  13231. // been already true(and we only received actual status from
  13232. // the focus).
  13233. //
  13234. // SO we start with status null, so that it is initialized
  13235. // here and will fail only after second click, so if invalid
  13236. // token was used we have to press the button twice before
  13237. // current status will be fetched and token will be reset.
  13238. //
  13239. // Reliable way would be to return authentication error.
  13240. // Or status update when moderator connects.
  13241. // Or we have to stop recording session when current
  13242. // moderator leaves the room.
  13243. // Failed to change, reset the token because it might
  13244. // have been wrong
  13245. setRecordingToken(null);
  13246. }
  13247. startedCallback(state);
  13248. },
  13249. connection
  13250. );
  13251. }
  13252. }
  13253. module.exports = Recording;
  13254. },{"./moderator":52}],54:[function(require,module,exports){
  13255. /* jshint -W117 */
  13256. /* a simple MUC connection plugin
  13257. * can only handle a single MUC room
  13258. */
  13259. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13260. var Moderator = require("./moderator");
  13261. var JingleSession = require("./JingleSession");
  13262. var bridgeIsDown = false;
  13263. module.exports = function(XMPP, eventEmitter) {
  13264. Strophe.addConnectionPlugin('emuc', {
  13265. connection: null,
  13266. roomjid: null,
  13267. myroomjid: null,
  13268. members: {},
  13269. list_members: [], // so we can elect a new focus
  13270. presMap: {},
  13271. preziMap: {},
  13272. joined: false,
  13273. isOwner: false,
  13274. role: null,
  13275. focusMucJid: null,
  13276. ssrc2jid: {},
  13277. init: function (conn) {
  13278. this.connection = conn;
  13279. },
  13280. initPresenceMap: function (myroomjid) {
  13281. this.presMap['to'] = myroomjid;
  13282. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  13283. },
  13284. doJoin: function (jid, password) {
  13285. this.myroomjid = jid;
  13286. console.info("Joined MUC as " + this.myroomjid);
  13287. this.initPresenceMap(this.myroomjid);
  13288. if (!this.roomjid) {
  13289. this.roomjid = Strophe.getBareJidFromJid(jid);
  13290. // add handlers (just once)
  13291. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  13292. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  13293. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  13294. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  13295. }
  13296. if (password !== undefined) {
  13297. this.presMap['password'] = password;
  13298. }
  13299. this.sendPresence();
  13300. },
  13301. doLeave: function () {
  13302. console.log("do leave", this.myroomjid);
  13303. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  13304. this.presMap.length = 0;
  13305. this.connection.send(pres);
  13306. },
  13307. createNonAnonymousRoom: function () {
  13308. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  13309. var getForm = $iq({type: 'get', to: this.roomjid})
  13310. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  13311. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13312. var self = this;
  13313. this.connection.sendIQ(getForm, function (form) {
  13314. if (!$(form).find(
  13315. '>query>x[xmlns="jabber:x:data"]' +
  13316. '>field[var="muc#roomconfig_whois"]').length) {
  13317. console.error('non-anonymous rooms not supported');
  13318. return;
  13319. }
  13320. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  13321. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13322. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13323. formSubmit.c('field', {'var': 'FORM_TYPE'})
  13324. .c('value')
  13325. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13326. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  13327. .c('value').t('anyone').up().up();
  13328. self.connection.sendIQ(formSubmit);
  13329. }, function (error) {
  13330. console.error("Error getting room configuration form");
  13331. });
  13332. },
  13333. onPresence: function (pres) {
  13334. var from = pres.getAttribute('from');
  13335. // What is this for? A workaround for something?
  13336. if (pres.getAttribute('type')) {
  13337. return true;
  13338. }
  13339. // Parse etherpad tag.
  13340. var etherpad = $(pres).find('>etherpad');
  13341. if (etherpad.length) {
  13342. if (config.etherpad_base && !Moderator.isModerator()) {
  13343. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  13344. }
  13345. }
  13346. // Parse prezi tag.
  13347. var presentation = $(pres).find('>prezi');
  13348. if (presentation.length) {
  13349. var url = presentation.attr('url');
  13350. var current = presentation.find('>current').text();
  13351. console.log('presentation info received from', from, url);
  13352. if (this.preziMap[from] == null) {
  13353. this.preziMap[from] = url;
  13354. $(document).trigger('presentationadded.muc', [from, url, current]);
  13355. }
  13356. else {
  13357. $(document).trigger('gotoslide.muc', [from, url, current]);
  13358. }
  13359. }
  13360. else if (this.preziMap[from] != null) {
  13361. var url = this.preziMap[from];
  13362. delete this.preziMap[from];
  13363. $(document).trigger('presentationremoved.muc', [from, url]);
  13364. }
  13365. // Parse audio info tag.
  13366. var audioMuted = $(pres).find('>audiomuted');
  13367. if (audioMuted.length) {
  13368. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  13369. }
  13370. // Parse video info tag.
  13371. var videoMuted = $(pres).find('>videomuted');
  13372. if (videoMuted.length) {
  13373. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  13374. }
  13375. var stats = $(pres).find('>stats');
  13376. if (stats.length) {
  13377. var statsObj = {};
  13378. Strophe.forEachChild(stats[0], "stat", function (el) {
  13379. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  13380. });
  13381. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  13382. }
  13383. // Parse status.
  13384. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  13385. this.isOwner = true;
  13386. this.createNonAnonymousRoom();
  13387. }
  13388. // Parse roles.
  13389. var member = {};
  13390. member.show = $(pres).find('>show').text();
  13391. member.status = $(pres).find('>status').text();
  13392. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  13393. member.affiliation = tmp.attr('affiliation');
  13394. member.role = tmp.attr('role');
  13395. // Focus recognition
  13396. member.jid = tmp.attr('jid');
  13397. member.isFocus = false;
  13398. if (member.jid
  13399. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  13400. member.isFocus = true;
  13401. }
  13402. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  13403. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  13404. if (from == this.myroomjid) {
  13405. if (member.affiliation == 'owner') this.isOwner = true;
  13406. if (this.role !== member.role) {
  13407. this.role = member.role;
  13408. eventEmitter.emit(XMPPEvents.LOCALROLE_CHANGED,
  13409. from, member, pres, Moderator.isModerator());
  13410. }
  13411. if (!this.joined) {
  13412. this.joined = true;
  13413. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  13414. this.list_members.push(from);
  13415. }
  13416. } else if (this.members[from] === undefined) {
  13417. // new participant
  13418. this.members[from] = member;
  13419. this.list_members.push(from);
  13420. console.log('entered', from, member);
  13421. if (member.isFocus) {
  13422. this.focusMucJid = from;
  13423. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  13424. }
  13425. else {
  13426. var id = $(pres).find('>userID').text();
  13427. var email = $(pres).find('>email');
  13428. if (email.length > 0) {
  13429. id = email.text();
  13430. }
  13431. eventEmitter.emit(XMPPEvents.MUC_ENTER, from, id, member.displayName);
  13432. }
  13433. } else {
  13434. // Presence update for existing participant
  13435. // Watch role change:
  13436. if (this.members[from].role != member.role) {
  13437. this.members[from].role = member.role;
  13438. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  13439. member.role, member.displayName);
  13440. }
  13441. }
  13442. // Always trigger presence to update bindings
  13443. this.parsePresence(from, member, pres);
  13444. // Trigger status message update
  13445. if (member.status) {
  13446. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  13447. }
  13448. return true;
  13449. },
  13450. onPresenceUnavailable: function (pres) {
  13451. var from = pres.getAttribute('from');
  13452. // room destroyed ?
  13453. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13454. '>destroy').length) {
  13455. var reason;
  13456. var reasonSelect = $(pres).find(
  13457. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13458. '>destroy>reason');
  13459. if (reasonSelect.length) {
  13460. reason = reasonSelect.text();
  13461. }
  13462. XMPP.disposeConference(false);
  13463. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  13464. return true;
  13465. }
  13466. // Status code 110 indicates that this notification is "self-presence".
  13467. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  13468. delete this.members[from];
  13469. this.list_members.splice(this.list_members.indexOf(from), 1);
  13470. this.onParticipantLeft(from);
  13471. }
  13472. // If the status code is 110 this means we're leaving and we would like
  13473. // to remove everyone else from our view, so we trigger the event.
  13474. else if (this.list_members.length > 1) {
  13475. for (var i = 0; i < this.list_members.length; i++) {
  13476. var member = this.list_members[i];
  13477. delete this.members[i];
  13478. this.list_members.splice(i, 1);
  13479. this.onParticipantLeft(member);
  13480. }
  13481. }
  13482. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  13483. $(document).trigger('kicked.muc', [from]);
  13484. if (this.myroomjid === from) {
  13485. XMPP.disposeConference(false);
  13486. eventEmitter.emit(XMPPEvents.KICKED);
  13487. }
  13488. }
  13489. return true;
  13490. },
  13491. onPresenceError: function (pres) {
  13492. var from = pres.getAttribute('from');
  13493. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13494. console.log('on password required', from);
  13495. var self = this;
  13496. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  13497. self.doJoin(from, value);
  13498. });
  13499. } else if ($(pres).find(
  13500. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13501. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  13502. if (toDomain === config.hosts.anonymousdomain) {
  13503. // enter the room by replying with 'not-authorized'. This would
  13504. // result in reconnection from authorized domain.
  13505. // We're either missing Jicofo/Prosody config for anonymous
  13506. // domains or something is wrong.
  13507. // XMPP.promptLogin();
  13508. APP.UI.messageHandler.openReportDialog(null,
  13509. "dialog.joinError", pres);
  13510. } else {
  13511. console.warn('onPresError ', pres);
  13512. APP.UI.messageHandler.openReportDialog(null,
  13513. "dialog.connectError",
  13514. pres);
  13515. }
  13516. } else {
  13517. console.warn('onPresError ', pres);
  13518. APP.UI.messageHandler.openReportDialog(null,
  13519. "dialog.connectError",
  13520. pres);
  13521. }
  13522. return true;
  13523. },
  13524. sendMessage: function (body, nickname) {
  13525. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13526. msg.c('body', body).up();
  13527. if (nickname) {
  13528. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  13529. }
  13530. this.connection.send(msg);
  13531. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  13532. },
  13533. setSubject: function (subject) {
  13534. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13535. msg.c('subject', subject);
  13536. this.connection.send(msg);
  13537. console.log("topic changed to " + subject);
  13538. },
  13539. onMessage: function (msg) {
  13540. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  13541. var from = msg.getAttribute('from');
  13542. var nick =
  13543. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  13544. .text() ||
  13545. Strophe.getResourceFromJid(from);
  13546. var txt = $(msg).find('>body').text();
  13547. var type = msg.getAttribute("type");
  13548. if (type == "error") {
  13549. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  13550. $(msg).find('>text').text(), txt);
  13551. return true;
  13552. }
  13553. var subject = $(msg).find('>subject');
  13554. if (subject.length) {
  13555. var subjectText = subject.text();
  13556. if (subjectText || subjectText == "") {
  13557. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  13558. console.log("Subject is changed to " + subjectText);
  13559. }
  13560. }
  13561. if (txt) {
  13562. console.log('chat', nick, txt);
  13563. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  13564. from, nick, txt, this.myroomjid);
  13565. }
  13566. return true;
  13567. },
  13568. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  13569. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  13570. var ob = this;
  13571. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  13572. function (res) {
  13573. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  13574. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13575. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13576. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13577. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  13578. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  13579. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  13580. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  13581. ob.connection.sendIQ(formsubmit,
  13582. onSuccess,
  13583. onError);
  13584. } else {
  13585. onNotSupported();
  13586. }
  13587. }, onError);
  13588. },
  13589. kick: function (jid) {
  13590. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  13591. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  13592. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  13593. .c('reason').t('You have been kicked.').up().up().up();
  13594. this.connection.sendIQ(
  13595. kickIQ,
  13596. function (result) {
  13597. console.log('Kick participant with jid: ', jid, result);
  13598. },
  13599. function (error) {
  13600. console.log('Kick participant error: ', error);
  13601. });
  13602. },
  13603. sendPresence: function () {
  13604. var pres = $pres({to: this.presMap['to'] });
  13605. pres.c('x', {xmlns: this.presMap['xns']});
  13606. if (this.presMap['password']) {
  13607. pres.c('password').t(this.presMap['password']).up();
  13608. }
  13609. pres.up();
  13610. // Send XEP-0115 'c' stanza that contains our capabilities info
  13611. if (this.connection.caps) {
  13612. this.connection.caps.node = config.clientNode;
  13613. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  13614. }
  13615. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  13616. .t(navigator.userAgent).up();
  13617. if (this.presMap['bridgeIsDown']) {
  13618. pres.c('bridgeIsDown').up();
  13619. }
  13620. if (this.presMap['email']) {
  13621. pres.c('email').t(this.presMap['email']).up();
  13622. }
  13623. if (this.presMap['userId']) {
  13624. pres.c('userId').t(this.presMap['userId']).up();
  13625. }
  13626. if (this.presMap['displayName']) {
  13627. // XEP-0172
  13628. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  13629. .t(this.presMap['displayName']).up();
  13630. }
  13631. if (this.presMap['audions']) {
  13632. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  13633. .t(this.presMap['audiomuted']).up();
  13634. }
  13635. if (this.presMap['videons']) {
  13636. pres.c('videomuted', {xmlns: this.presMap['videons']})
  13637. .t(this.presMap['videomuted']).up();
  13638. }
  13639. if (this.presMap['statsns']) {
  13640. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  13641. for (var stat in this.presMap["stats"])
  13642. if (this.presMap["stats"][stat] != null)
  13643. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  13644. pres.up();
  13645. }
  13646. if (this.presMap['prezins']) {
  13647. pres.c('prezi',
  13648. {xmlns: this.presMap['prezins'],
  13649. 'url': this.presMap['preziurl']})
  13650. .c('current').t(this.presMap['prezicurrent']).up().up();
  13651. }
  13652. if (this.presMap['etherpadns']) {
  13653. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  13654. .t(this.presMap['etherpadname']).up();
  13655. }
  13656. if (this.presMap['medians']) {
  13657. pres.c('media', {xmlns: this.presMap['medians']});
  13658. var sourceNumber = 0;
  13659. Object.keys(this.presMap).forEach(function (key) {
  13660. if (key.indexOf('source') >= 0) {
  13661. sourceNumber++;
  13662. }
  13663. });
  13664. if (sourceNumber > 0)
  13665. for (var i = 1; i <= sourceNumber / 3; i++) {
  13666. pres.c('source',
  13667. {type: this.presMap['source' + i + '_type'],
  13668. ssrc: this.presMap['source' + i + '_ssrc'],
  13669. direction: this.presMap['source' + i + '_direction']
  13670. || 'sendrecv' }
  13671. ).up();
  13672. }
  13673. }
  13674. pres.up();
  13675. this.connection.send(pres);
  13676. },
  13677. addDisplayNameToPresence: function (displayName) {
  13678. this.presMap['displayName'] = displayName;
  13679. },
  13680. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  13681. if (!this.presMap['medians'])
  13682. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  13683. this.presMap['source' + sourceNumber + '_type'] = mtype;
  13684. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  13685. this.presMap['source' + sourceNumber + '_direction'] = direction;
  13686. },
  13687. clearPresenceMedia: function () {
  13688. var self = this;
  13689. Object.keys(this.presMap).forEach(function (key) {
  13690. if (key.indexOf('source') != -1) {
  13691. delete self.presMap[key];
  13692. }
  13693. });
  13694. },
  13695. addPreziToPresence: function (url, currentSlide) {
  13696. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  13697. this.presMap['preziurl'] = url;
  13698. this.presMap['prezicurrent'] = currentSlide;
  13699. },
  13700. removePreziFromPresence: function () {
  13701. delete this.presMap['prezins'];
  13702. delete this.presMap['preziurl'];
  13703. delete this.presMap['prezicurrent'];
  13704. },
  13705. addCurrentSlideToPresence: function (currentSlide) {
  13706. this.presMap['prezicurrent'] = currentSlide;
  13707. },
  13708. getPrezi: function (roomjid) {
  13709. return this.preziMap[roomjid];
  13710. },
  13711. addEtherpadToPresence: function (etherpadName) {
  13712. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  13713. this.presMap['etherpadname'] = etherpadName;
  13714. },
  13715. addAudioInfoToPresence: function (isMuted) {
  13716. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  13717. this.presMap['audiomuted'] = isMuted.toString();
  13718. },
  13719. addVideoInfoToPresence: function (isMuted) {
  13720. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  13721. this.presMap['videomuted'] = isMuted.toString();
  13722. },
  13723. addConnectionInfoToPresence: function (stats) {
  13724. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  13725. this.presMap['stats'] = stats;
  13726. },
  13727. findJidFromResource: function (resourceJid) {
  13728. if (resourceJid &&
  13729. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  13730. return this.myroomjid;
  13731. }
  13732. var peerJid = null;
  13733. Object.keys(this.members).some(function (jid) {
  13734. peerJid = jid;
  13735. return Strophe.getResourceFromJid(jid) === resourceJid;
  13736. });
  13737. return peerJid;
  13738. },
  13739. addBridgeIsDownToPresence: function () {
  13740. this.presMap['bridgeIsDown'] = true;
  13741. },
  13742. addEmailToPresence: function (email) {
  13743. this.presMap['email'] = email;
  13744. },
  13745. addUserIdToPresence: function (userId) {
  13746. this.presMap['userId'] = userId;
  13747. },
  13748. isModerator: function () {
  13749. return this.role === 'moderator';
  13750. },
  13751. getMemberRole: function (peerJid) {
  13752. if (this.members[peerJid]) {
  13753. return this.members[peerJid].role;
  13754. }
  13755. return null;
  13756. },
  13757. onParticipantLeft: function (jid) {
  13758. eventEmitter.emit(XMPPEvents.MUC_LEFT, jid);
  13759. this.connection.jingle.terminateByJid(jid);
  13760. if (this.getPrezi(jid)) {
  13761. $(document).trigger('presentationremoved.muc',
  13762. [jid, this.getPrezi(jid)]);
  13763. }
  13764. Moderator.onMucLeft(jid);
  13765. },
  13766. parsePresence: function (from, memeber, pres) {
  13767. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  13768. bridgeIsDown = true;
  13769. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  13770. }
  13771. if(memeber.isFocus)
  13772. return;
  13773. var self = this;
  13774. // Remove old ssrcs coming from the jid
  13775. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  13776. if (self.ssrc2jid[ssrc] == from) {
  13777. delete self.ssrc2jid[ssrc];
  13778. }
  13779. });
  13780. var changedStreams = [];
  13781. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  13782. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  13783. var ssrcV = ssrc.getAttribute('ssrc');
  13784. self.ssrc2jid[ssrcV] = from;
  13785. JingleSession.notReceivedSSRCs.push(ssrcV);
  13786. var type = ssrc.getAttribute('type');
  13787. var direction = ssrc.getAttribute('direction');
  13788. changedStreams.push({type: type, direction: direction});
  13789. });
  13790. eventEmitter.emit(XMPPEvents.CHANGED_STREAMS, from, changedStreams);
  13791. var displayName = !config.displayJids
  13792. ? memeber.displayName : Strophe.getResourceFromJid(from);
  13793. if (displayName && displayName.length > 0)
  13794. {
  13795. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  13796. }
  13797. var id = $(pres).find('>userID').text();
  13798. var email = $(pres).find('>email');
  13799. if(email.length > 0) {
  13800. id = email.text();
  13801. }
  13802. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  13803. }
  13804. });
  13805. };
  13806. },{"../../service/xmpp/XMPPEvents":88,"./JingleSession":47,"./moderator":52}],55:[function(require,module,exports){
  13807. /* jshint -W117 */
  13808. var JingleSession = require("./JingleSession");
  13809. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13810. module.exports = function(XMPP, eventEmitter)
  13811. {
  13812. function CallIncomingJingle(sid, connection) {
  13813. var sess = connection.jingle.sessions[sid];
  13814. // TODO: do we check activecall == null?
  13815. connection.jingle.activecall = sess;
  13816. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  13817. // TODO: check affiliation and/or role
  13818. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  13819. sess.usedrip = true; // not-so-naive trickle ice
  13820. sess.sendAnswer();
  13821. sess.accept();
  13822. };
  13823. Strophe.addConnectionPlugin('jingle', {
  13824. connection: null,
  13825. sessions: {},
  13826. jid2session: {},
  13827. ice_config: {iceServers: []},
  13828. pc_constraints: {},
  13829. activecall: null,
  13830. media_constraints: {
  13831. mandatory: {
  13832. 'OfferToReceiveAudio': true,
  13833. 'OfferToReceiveVideo': true
  13834. }
  13835. // MozDontOfferDataChannel: true when this is firefox
  13836. },
  13837. init: function (conn) {
  13838. this.connection = conn;
  13839. if (this.connection.disco) {
  13840. // http://xmpp.org/extensions/xep-0167.html#support
  13841. // http://xmpp.org/extensions/xep-0176.html#support
  13842. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  13843. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  13844. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  13845. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  13846. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  13847. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  13848. // this is dealt with by SDP O/A so we don't need to annouce this
  13849. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  13850. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  13851. if (config.useRtcpMux) {
  13852. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  13853. }
  13854. if (config.useBundle) {
  13855. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  13856. }
  13857. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  13858. }
  13859. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  13860. },
  13861. onJingle: function (iq) {
  13862. var sid = $(iq).find('jingle').attr('sid');
  13863. var action = $(iq).find('jingle').attr('action');
  13864. var fromJid = iq.getAttribute('from');
  13865. // send ack first
  13866. var ack = $iq({type: 'result',
  13867. to: fromJid,
  13868. id: iq.getAttribute('id')
  13869. });
  13870. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  13871. var sess = this.sessions[sid];
  13872. if ('session-initiate' != action) {
  13873. if (sess === null) {
  13874. ack.type = 'error';
  13875. ack.c('error', {type: 'cancel'})
  13876. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  13877. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  13878. this.connection.send(ack);
  13879. return true;
  13880. }
  13881. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  13882. // local jid is not checked
  13883. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  13884. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  13885. ack.type = 'error';
  13886. ack.c('error', {type: 'cancel'})
  13887. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  13888. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  13889. this.connection.send(ack);
  13890. return true;
  13891. }
  13892. } else if (sess !== undefined) {
  13893. // existing session with same session id
  13894. // this might be out-of-order if the sess.peerjid is the same as from
  13895. ack.type = 'error';
  13896. ack.c('error', {type: 'cancel'})
  13897. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  13898. console.warn('duplicate session id', sid);
  13899. this.connection.send(ack);
  13900. return true;
  13901. }
  13902. // FIXME: check for a defined action
  13903. this.connection.send(ack);
  13904. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  13905. switch (action) {
  13906. case 'session-initiate':
  13907. sess = new JingleSession(
  13908. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  13909. this.connection, XMPP);
  13910. // configure session
  13911. sess.media_constraints = this.media_constraints;
  13912. sess.pc_constraints = this.pc_constraints;
  13913. sess.ice_config = this.ice_config;
  13914. sess.initiate(fromJid, false);
  13915. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  13916. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  13917. this.sessions[sess.sid] = sess;
  13918. this.jid2session[sess.peerjid] = sess;
  13919. // the callback should either
  13920. // .sendAnswer and .accept
  13921. // or .sendTerminate -- not necessarily synchronus
  13922. CallIncomingJingle(sess.sid, this.connection);
  13923. break;
  13924. case 'session-accept':
  13925. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  13926. sess.accept();
  13927. $(document).trigger('callaccepted.jingle', [sess.sid]);
  13928. break;
  13929. case 'session-terminate':
  13930. // If this is not the focus sending the terminate, we have
  13931. // nothing more to do here.
  13932. if (Object.keys(this.sessions).length < 1
  13933. || !(this.sessions[Object.keys(this.sessions)[0]]
  13934. instanceof JingleSession))
  13935. {
  13936. break;
  13937. }
  13938. console.log('terminating...', sess.sid);
  13939. sess.terminate();
  13940. this.terminate(sess.sid);
  13941. if ($(iq).find('>jingle>reason').length) {
  13942. $(document).trigger('callterminated.jingle', [
  13943. sess.sid,
  13944. sess.peerjid,
  13945. $(iq).find('>jingle>reason>:first')[0].tagName,
  13946. $(iq).find('>jingle>reason>text').text()
  13947. ]);
  13948. } else {
  13949. $(document).trigger('callterminated.jingle',
  13950. [sess.sid, sess.peerjid]);
  13951. }
  13952. break;
  13953. case 'transport-info':
  13954. sess.addIceCandidate($(iq).find('>jingle>content'));
  13955. break;
  13956. case 'session-info':
  13957. var affected;
  13958. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  13959. $(document).trigger('ringing.jingle', [sess.sid]);
  13960. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  13961. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  13962. $(document).trigger('mute.jingle', [sess.sid, affected]);
  13963. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  13964. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  13965. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  13966. }
  13967. break;
  13968. case 'addsource': // FIXME: proprietary, un-jingleish
  13969. case 'source-add': // FIXME: proprietary
  13970. sess.addSource($(iq).find('>jingle>content'), fromJid);
  13971. break;
  13972. case 'removesource': // FIXME: proprietary, un-jingleish
  13973. case 'source-remove': // FIXME: proprietary
  13974. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  13975. break;
  13976. default:
  13977. console.warn('jingle action not implemented', action);
  13978. break;
  13979. }
  13980. return true;
  13981. },
  13982. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  13983. var sess = new JingleSession(myjid || this.connection.jid,
  13984. Math.random().toString(36).substr(2, 12), // random string
  13985. this.connection, XMPP);
  13986. // configure session
  13987. sess.media_constraints = this.media_constraints;
  13988. sess.pc_constraints = this.pc_constraints;
  13989. sess.ice_config = this.ice_config;
  13990. sess.initiate(peerjid, true);
  13991. this.sessions[sess.sid] = sess;
  13992. this.jid2session[sess.peerjid] = sess;
  13993. sess.sendOffer();
  13994. return sess;
  13995. },
  13996. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  13997. if (sid === null || sid === undefined) {
  13998. for (sid in this.sessions) {
  13999. if (this.sessions[sid].state != 'ended') {
  14000. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14001. this.sessions[sid].terminate();
  14002. }
  14003. delete this.jid2session[this.sessions[sid].peerjid];
  14004. delete this.sessions[sid];
  14005. }
  14006. } else if (this.sessions.hasOwnProperty(sid)) {
  14007. if (this.sessions[sid].state != 'ended') {
  14008. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14009. this.sessions[sid].terminate();
  14010. }
  14011. delete this.jid2session[this.sessions[sid].peerjid];
  14012. delete this.sessions[sid];
  14013. }
  14014. },
  14015. // Used to terminate a session when an unavailable presence is received.
  14016. terminateByJid: function (jid) {
  14017. if (this.jid2session.hasOwnProperty(jid)) {
  14018. var sess = this.jid2session[jid];
  14019. if (sess) {
  14020. sess.terminate();
  14021. console.log('peer went away silently', jid);
  14022. delete this.sessions[sess.sid];
  14023. delete this.jid2session[jid];
  14024. $(document).trigger('callterminated.jingle',
  14025. [sess.sid, jid], 'gone');
  14026. }
  14027. }
  14028. },
  14029. terminateRemoteByJid: function (jid, reason) {
  14030. if (this.jid2session.hasOwnProperty(jid)) {
  14031. var sess = this.jid2session[jid];
  14032. if (sess) {
  14033. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  14034. sess.terminate();
  14035. console.log('terminate peer with jid', sess.sid, jid);
  14036. delete this.sessions[sess.sid];
  14037. delete this.jid2session[jid];
  14038. $(document).trigger('callterminated.jingle',
  14039. [sess.sid, jid, 'kicked']);
  14040. }
  14041. }
  14042. },
  14043. getStunAndTurnCredentials: function () {
  14044. // get stun and turn configuration from server via xep-0215
  14045. // uses time-limited credentials as described in
  14046. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  14047. //
  14048. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  14049. // for a prosody module which implements this
  14050. //
  14051. // currently, this doesn't work with updateIce and therefore credentials with a long
  14052. // validity have to be fetched before creating the peerconnection
  14053. // TODO: implement refresh via updateIce as described in
  14054. // https://code.google.com/p/webrtc/issues/detail?id=1650
  14055. var self = this;
  14056. this.connection.sendIQ(
  14057. $iq({type: 'get', to: this.connection.domain})
  14058. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  14059. function (res) {
  14060. var iceservers = [];
  14061. $(res).find('>services>service').each(function (idx, el) {
  14062. el = $(el);
  14063. var dict = {};
  14064. var type = el.attr('type');
  14065. switch (type) {
  14066. case 'stun':
  14067. dict.url = 'stun:' + el.attr('host');
  14068. if (el.attr('port')) {
  14069. dict.url += ':' + el.attr('port');
  14070. }
  14071. iceservers.push(dict);
  14072. break;
  14073. case 'turn':
  14074. case 'turns':
  14075. dict.url = type + ':';
  14076. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  14077. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  14078. dict.url += el.attr('username') + '@';
  14079. } else {
  14080. dict.username = el.attr('username'); // only works in M28
  14081. }
  14082. }
  14083. dict.url += el.attr('host');
  14084. if (el.attr('port') && el.attr('port') != '3478') {
  14085. dict.url += ':' + el.attr('port');
  14086. }
  14087. if (el.attr('transport') && el.attr('transport') != 'udp') {
  14088. dict.url += '?transport=' + el.attr('transport');
  14089. }
  14090. if (el.attr('password')) {
  14091. dict.credential = el.attr('password');
  14092. }
  14093. iceservers.push(dict);
  14094. break;
  14095. }
  14096. });
  14097. self.ice_config.iceServers = iceservers;
  14098. },
  14099. function (err) {
  14100. console.warn('getting turn credentials failed', err);
  14101. console.warn('is mod_turncredentials or similar installed?');
  14102. }
  14103. );
  14104. // implement push?
  14105. },
  14106. /**
  14107. * Populates the log data
  14108. */
  14109. populateData: function () {
  14110. var data = {};
  14111. Object.keys(this.sessions).forEach(function (sid) {
  14112. var session = this.sessions[sid];
  14113. if (session.peerconnection && session.peerconnection.updateLog) {
  14114. // FIXME: should probably be a .dump call
  14115. data["jingle_" + session.sid] = {
  14116. updateLog: session.peerconnection.updateLog,
  14117. stats: session.peerconnection.stats,
  14118. url: window.location.href
  14119. };
  14120. }
  14121. });
  14122. return data;
  14123. }
  14124. });
  14125. };
  14126. },{"../../service/xmpp/XMPPEvents":88,"./JingleSession":47}],56:[function(require,module,exports){
  14127. /* global Strophe */
  14128. module.exports = function () {
  14129. Strophe.addConnectionPlugin('logger', {
  14130. // logs raw stanzas and makes them available for download as JSON
  14131. connection: null,
  14132. log: [],
  14133. init: function (conn) {
  14134. this.connection = conn;
  14135. this.connection.rawInput = this.log_incoming.bind(this);
  14136. this.connection.rawOutput = this.log_outgoing.bind(this);
  14137. },
  14138. log_incoming: function (stanza) {
  14139. this.log.push([new Date().getTime(), 'incoming', stanza]);
  14140. },
  14141. log_outgoing: function (stanza) {
  14142. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  14143. }
  14144. });
  14145. };
  14146. },{}],57:[function(require,module,exports){
  14147. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  14148. setAudioMuted, Strophe */
  14149. /**
  14150. * Moderate connection plugin.
  14151. */
  14152. module.exports = function (XMPP) {
  14153. Strophe.addConnectionPlugin('moderate', {
  14154. connection: null,
  14155. init: function (conn) {
  14156. this.connection = conn;
  14157. this.connection.addHandler(this.onMute.bind(this),
  14158. 'http://jitsi.org/jitmeet/audio',
  14159. 'iq',
  14160. 'set',
  14161. null,
  14162. null);
  14163. },
  14164. setMute: function (jid, mute) {
  14165. console.info("set mute", mute);
  14166. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  14167. .c('mute', {
  14168. xmlns: 'http://jitsi.org/jitmeet/audio',
  14169. jid: jid
  14170. })
  14171. .t(mute.toString())
  14172. .up();
  14173. this.connection.sendIQ(
  14174. iqToFocus,
  14175. function (result) {
  14176. console.log('set mute', result);
  14177. },
  14178. function (error) {
  14179. console.log('set mute error', error);
  14180. });
  14181. },
  14182. onMute: function (iq) {
  14183. var from = iq.getAttribute('from');
  14184. if (from !== this.connection.emuc.focusMucJid) {
  14185. console.warn("Ignored mute from non focus peer");
  14186. return false;
  14187. }
  14188. var mute = $(iq).find('mute');
  14189. if (mute.length) {
  14190. var doMuteAudio = mute.text() === "true";
  14191. APP.UI.setAudioMuted(doMuteAudio);
  14192. XMPP.forceMuted = doMuteAudio;
  14193. }
  14194. return true;
  14195. },
  14196. eject: function (jid) {
  14197. // We're not the focus, so can't terminate
  14198. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  14199. this.connection.emuc.kick(jid);
  14200. }
  14201. });
  14202. }
  14203. },{}],58:[function(require,module,exports){
  14204. /* jshint -W117 */
  14205. module.exports = function() {
  14206. Strophe.addConnectionPlugin('rayo',
  14207. {
  14208. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  14209. connection: null,
  14210. init: function (conn) {
  14211. this.connection = conn;
  14212. if (this.connection.disco) {
  14213. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  14214. }
  14215. this.connection.addHandler(
  14216. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  14217. },
  14218. onRayo: function (iq) {
  14219. console.info("Rayo IQ", iq);
  14220. },
  14221. dial: function (to, from, roomName, roomPass) {
  14222. var self = this;
  14223. var req = $iq(
  14224. {
  14225. type: 'set',
  14226. to: this.connection.emuc.focusMucJid
  14227. }
  14228. );
  14229. req.c('dial',
  14230. {
  14231. xmlns: this.RAYO_XMLNS,
  14232. to: to,
  14233. from: from
  14234. });
  14235. req.c('header',
  14236. {
  14237. name: 'JvbRoomName',
  14238. value: roomName
  14239. }).up();
  14240. if (roomPass !== null && roomPass.length) {
  14241. req.c('header',
  14242. {
  14243. name: 'JvbRoomPassword',
  14244. value: roomPass
  14245. }).up();
  14246. }
  14247. this.connection.sendIQ(
  14248. req,
  14249. function (result) {
  14250. console.info('Dial result ', result);
  14251. var resource = $(result).find('ref').attr('uri');
  14252. this.call_resource = resource.substr('xmpp:'.length);
  14253. console.info(
  14254. "Received call resource: " + this.call_resource);
  14255. },
  14256. function (error) {
  14257. console.info('Dial error ', error);
  14258. }
  14259. );
  14260. },
  14261. hang_up: function () {
  14262. if (!this.call_resource) {
  14263. console.warn("No call in progress");
  14264. return;
  14265. }
  14266. var self = this;
  14267. var req = $iq(
  14268. {
  14269. type: 'set',
  14270. to: this.call_resource
  14271. }
  14272. );
  14273. req.c('hangup',
  14274. {
  14275. xmlns: this.RAYO_XMLNS
  14276. });
  14277. this.connection.sendIQ(
  14278. req,
  14279. function (result) {
  14280. console.info('Hangup result ', result);
  14281. self.call_resource = null;
  14282. },
  14283. function (error) {
  14284. console.info('Hangup error ', error);
  14285. self.call_resource = null;
  14286. }
  14287. );
  14288. }
  14289. }
  14290. );
  14291. };
  14292. },{}],59:[function(require,module,exports){
  14293. /**
  14294. * Strophe logger implementation. Logs from level WARN and above.
  14295. */
  14296. module.exports = function () {
  14297. Strophe.log = function (level, msg) {
  14298. switch (level) {
  14299. case Strophe.LogLevel.WARN:
  14300. console.warn("Strophe: " + msg);
  14301. break;
  14302. case Strophe.LogLevel.ERROR:
  14303. case Strophe.LogLevel.FATAL:
  14304. console.error("Strophe: " + msg);
  14305. break;
  14306. }
  14307. };
  14308. Strophe.getStatusString = function (status) {
  14309. switch (status) {
  14310. case Strophe.Status.ERROR:
  14311. return "ERROR";
  14312. case Strophe.Status.CONNECTING:
  14313. return "CONNECTING";
  14314. case Strophe.Status.CONNFAIL:
  14315. return "CONNFAIL";
  14316. case Strophe.Status.AUTHENTICATING:
  14317. return "AUTHENTICATING";
  14318. case Strophe.Status.AUTHFAIL:
  14319. return "AUTHFAIL";
  14320. case Strophe.Status.CONNECTED:
  14321. return "CONNECTED";
  14322. case Strophe.Status.DISCONNECTED:
  14323. return "DISCONNECTED";
  14324. case Strophe.Status.DISCONNECTING:
  14325. return "DISCONNECTING";
  14326. case Strophe.Status.ATTACHED:
  14327. return "ATTACHED";
  14328. default:
  14329. return "unknown";
  14330. }
  14331. };
  14332. };
  14333. },{}],60:[function(require,module,exports){
  14334. var Moderator = require("./moderator");
  14335. var EventEmitter = require("events");
  14336. var Recording = require("./recording");
  14337. var SDP = require("./SDP");
  14338. var Pako = require("pako");
  14339. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  14340. var UIEvents = require("../../service/UI/UIEvents");
  14341. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14342. var eventEmitter = new EventEmitter();
  14343. var connection = null;
  14344. var authenticatedUser = false;
  14345. function connect(jid, password, uiCredentials) {
  14346. var bosh
  14347. = (uiCredentials && uiCredentials.bosh? uiCredentials.bosh : null)
  14348. || config.bosh || '/http-bind';
  14349. connection = new Strophe.Connection(bosh);
  14350. Moderator.setConnection(connection);
  14351. if(uiCredentials) {
  14352. var email = uiCredentials.email;
  14353. var displayName = uiCredentials.displayName;
  14354. if (email) {
  14355. connection.emuc.addEmailToPresence(email);
  14356. } else {
  14357. connection.emuc.addUserIdToPresence(uiCredentials.uid);
  14358. }
  14359. if (displayName) {
  14360. connection.emuc.addDisplayNameToPresence(displayName);
  14361. }
  14362. }
  14363. if (connection.disco) {
  14364. // for chrome, add multistream cap
  14365. }
  14366. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  14367. if (config.useIPv6) {
  14368. // https://code.google.com/p/webrtc/issues/detail?id=2828
  14369. if (!connection.jingle.pc_constraints.optional)
  14370. connection.jingle.pc_constraints.optional = [];
  14371. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  14372. }
  14373. if(!password)
  14374. password = uiCredentials.password;
  14375. var anonymousConnectionFailed = false;
  14376. connection.connect(jid, password, function (status, msg) {
  14377. console.log('Strophe status changed to',
  14378. Strophe.getStatusString(status));
  14379. if (status === Strophe.Status.CONNECTED) {
  14380. if (config.useStunTurn) {
  14381. connection.jingle.getStunAndTurnCredentials();
  14382. }
  14383. APP.UI.disableConnect();
  14384. console.info("My Jabber ID: " + connection.jid);
  14385. if(password)
  14386. authenticatedUser = true;
  14387. maybeDoJoin();
  14388. } else if (status === Strophe.Status.CONNFAIL) {
  14389. if(msg === 'x-strophe-bad-non-anon-jid') {
  14390. anonymousConnectionFailed = true;
  14391. }
  14392. } else if (status === Strophe.Status.DISCONNECTED) {
  14393. if(anonymousConnectionFailed) {
  14394. // prompt user for username and password
  14395. XMPP.promptLogin();
  14396. }
  14397. } else if (status === Strophe.Status.AUTHFAIL) {
  14398. // wrong password or username, prompt user
  14399. XMPP.promptLogin();
  14400. }
  14401. });
  14402. }
  14403. function maybeDoJoin() {
  14404. if (connection && connection.connected &&
  14405. Strophe.getResourceFromJid(connection.jid)
  14406. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  14407. // .connected is true while connecting?
  14408. doJoin();
  14409. }
  14410. }
  14411. function doJoin() {
  14412. var roomName = APP.UI.generateRoomName();
  14413. Moderator.allocateConferenceFocus(
  14414. roomName, APP.UI.checkForNicknameAndJoin);
  14415. }
  14416. function initStrophePlugins()
  14417. {
  14418. require("./strophe.emuc")(XMPP, eventEmitter);
  14419. require("./strophe.jingle")(XMPP, eventEmitter);
  14420. require("./strophe.moderate")(XMPP);
  14421. require("./strophe.util")();
  14422. require("./strophe.rayo")();
  14423. require("./strophe.logger")();
  14424. }
  14425. function registerListeners() {
  14426. APP.RTC.addStreamListener(maybeDoJoin,
  14427. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  14428. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  14429. XMPP.addToPresence("displayName", nickname);
  14430. });
  14431. }
  14432. function setupEvents() {
  14433. $(window).bind('beforeunload', function () {
  14434. if (connection && connection.connected) {
  14435. // ensure signout
  14436. $.ajax({
  14437. type: 'POST',
  14438. url: config.bosh,
  14439. async: false,
  14440. cache: false,
  14441. contentType: 'application/xml',
  14442. data: "<body rid='" + (connection.rid || connection._proto.rid)
  14443. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  14444. + (connection.sid || connection._proto.sid)
  14445. + "' type='terminate'>" +
  14446. "<presence xmlns='jabber:client' type='unavailable'/>" +
  14447. "</body>",
  14448. success: function (data) {
  14449. console.log('signed out');
  14450. console.log(data);
  14451. },
  14452. error: function (XMLHttpRequest, textStatus, errorThrown) {
  14453. console.log('signout error',
  14454. textStatus + ' (' + errorThrown + ')');
  14455. }
  14456. });
  14457. }
  14458. XMPP.disposeConference(true);
  14459. });
  14460. }
  14461. var XMPP = {
  14462. sessionTerminated: false,
  14463. /**
  14464. * Remembers if we were muted by the focus.
  14465. * @type {boolean}
  14466. */
  14467. forceMuted: false,
  14468. start: function (uiCredentials) {
  14469. setupEvents();
  14470. initStrophePlugins();
  14471. registerListeners();
  14472. Moderator.init(this, eventEmitter);
  14473. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  14474. // Force authenticated domain if room is appended with '?login=true'
  14475. if (config.hosts.anonymousdomain &&
  14476. window.location.search.indexOf("login=true") !== -1) {
  14477. configDomain = config.hosts.domain;
  14478. }
  14479. var jid = uiCredentials.jid || configDomain || window.location.hostname;
  14480. connect(jid, null, uiCredentials);
  14481. },
  14482. promptLogin: function () {
  14483. APP.UI.showLoginPopup(connect);
  14484. },
  14485. joinRoom: function(roomName, useNicks, nick)
  14486. {
  14487. var roomjid;
  14488. roomjid = roomName;
  14489. if (useNicks) {
  14490. if (nick) {
  14491. roomjid += '/' + nick;
  14492. } else {
  14493. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  14494. }
  14495. } else {
  14496. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  14497. if(!authenticatedUser)
  14498. tmpJid = tmpJid.substr(0, 8);
  14499. roomjid += '/' + tmpJid;
  14500. }
  14501. connection.emuc.doJoin(roomjid);
  14502. },
  14503. myJid: function () {
  14504. if(!connection)
  14505. return null;
  14506. return connection.emuc.myroomjid;
  14507. },
  14508. myResource: function () {
  14509. if(!connection || ! connection.emuc.myroomjid)
  14510. return null;
  14511. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  14512. },
  14513. disposeConference: function (onUnload) {
  14514. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  14515. var handler = connection.jingle.activecall;
  14516. if (handler && handler.peerconnection) {
  14517. // FIXME: probably removing streams is not required and close() should
  14518. // be enough
  14519. if (APP.RTC.localAudio) {
  14520. handler.peerconnection.removeStream(APP.RTC.localAudio.getOriginalStream(), onUnload);
  14521. }
  14522. if (APP.RTC.localVideo) {
  14523. handler.peerconnection.removeStream(APP.RTC.localVideo.getOriginalStream(), onUnload);
  14524. }
  14525. handler.peerconnection.close();
  14526. }
  14527. connection.jingle.activecall = null;
  14528. if(!onUnload)
  14529. {
  14530. this.sessionTerminated = true;
  14531. connection.emuc.doLeave();
  14532. }
  14533. },
  14534. addListener: function(type, listener)
  14535. {
  14536. eventEmitter.on(type, listener);
  14537. },
  14538. removeListener: function (type, listener) {
  14539. eventEmitter.removeListener(type, listener);
  14540. },
  14541. allocateConferenceFocus: function(roomName, callback) {
  14542. Moderator.allocateConferenceFocus(roomName, callback);
  14543. },
  14544. getLoginUrl: function (roomName, callback) {
  14545. Moderator.getLoginUrl(roomName, callback);
  14546. },
  14547. getPopupLoginUrl: function (roomName, callback) {
  14548. Moderator.getPopupLoginUrl(roomName, callback);
  14549. },
  14550. isModerator: function () {
  14551. return Moderator.isModerator();
  14552. },
  14553. isSipGatewayEnabled: function () {
  14554. return Moderator.isSipGatewayEnabled();
  14555. },
  14556. isExternalAuthEnabled: function () {
  14557. return Moderator.isExternalAuthEnabled();
  14558. },
  14559. switchStreams: function (stream, oldStream, callback) {
  14560. if (connection && connection.jingle.activecall) {
  14561. // FIXME: will block switchInProgress on true value in case of exception
  14562. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  14563. } else {
  14564. // We are done immediately
  14565. console.error("No conference handler");
  14566. APP.UI.messageHandler.showError("dialog.error",
  14567. "dialog.unableToSwitch");
  14568. callback();
  14569. }
  14570. },
  14571. setVideoMute: function (mute, callback, options) {
  14572. if(connection && APP.RTC.localVideo && connection.jingle.activecall)
  14573. {
  14574. connection.jingle.activecall.setVideoMute(mute, callback, options);
  14575. }
  14576. },
  14577. setAudioMute: function (mute, callback) {
  14578. if (!(connection && APP.RTC.localAudio)) {
  14579. return false;
  14580. }
  14581. if (this.forceMuted && !mute) {
  14582. console.info("Asking focus for unmute");
  14583. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  14584. // FIXME: wait for result before resetting muted status
  14585. this.forceMuted = false;
  14586. }
  14587. if (mute == APP.RTC.localAudio.isMuted()) {
  14588. // Nothing to do
  14589. return true;
  14590. }
  14591. // It is not clear what is the right way to handle multiple tracks.
  14592. // So at least make sure that they are all muted or all unmuted and
  14593. // that we send presence just once.
  14594. APP.RTC.localAudio.mute();
  14595. // isMuted is the opposite of audioEnabled
  14596. connection.emuc.addAudioInfoToPresence(mute);
  14597. connection.emuc.sendPresence();
  14598. callback();
  14599. return true;
  14600. },
  14601. // Really mute video, i.e. dont even send black frames
  14602. muteVideo: function (pc, unmute) {
  14603. // FIXME: this probably needs another of those lovely state safeguards...
  14604. // which checks for iceconn == connected and sigstate == stable
  14605. pc.setRemoteDescription(pc.remoteDescription,
  14606. function () {
  14607. pc.createAnswer(
  14608. function (answer) {
  14609. var sdp = new SDP(answer.sdp);
  14610. if (sdp.media.length > 1) {
  14611. if (unmute)
  14612. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  14613. else
  14614. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  14615. sdp.raw = sdp.session + sdp.media.join('');
  14616. answer.sdp = sdp.raw;
  14617. }
  14618. pc.setLocalDescription(answer,
  14619. function () {
  14620. console.log('mute SLD ok');
  14621. },
  14622. function (error) {
  14623. console.log('mute SLD error');
  14624. APP.UI.messageHandler.showError("dialog.error",
  14625. "dialog.SLDFailure");
  14626. }
  14627. );
  14628. },
  14629. function (error) {
  14630. console.log(error);
  14631. APP.UI.messageHandler.showError();
  14632. }
  14633. );
  14634. },
  14635. function (error) {
  14636. console.log('muteVideo SRD error');
  14637. APP.UI.messageHandler.showError("dialog.error",
  14638. "dialog.SRDFailure");
  14639. }
  14640. );
  14641. },
  14642. toggleRecording: function (tokenEmptyCallback,
  14643. startingCallback, startedCallback) {
  14644. Recording.toggleRecording(tokenEmptyCallback,
  14645. startingCallback, startedCallback, connection);
  14646. },
  14647. addToPresence: function (name, value, dontSend) {
  14648. switch (name)
  14649. {
  14650. case "displayName":
  14651. connection.emuc.addDisplayNameToPresence(value);
  14652. break;
  14653. case "etherpad":
  14654. connection.emuc.addEtherpadToPresence(value);
  14655. break;
  14656. case "prezi":
  14657. connection.emuc.addPreziToPresence(value, 0);
  14658. break;
  14659. case "preziSlide":
  14660. connection.emuc.addCurrentSlideToPresence(value);
  14661. break;
  14662. case "connectionQuality":
  14663. connection.emuc.addConnectionInfoToPresence(value);
  14664. break;
  14665. case "email":
  14666. connection.emuc.addEmailToPresence(value);
  14667. default :
  14668. console.log("Unknown tag for presence.");
  14669. return;
  14670. }
  14671. if(!dontSend)
  14672. connection.emuc.sendPresence();
  14673. },
  14674. /**
  14675. * Sends 'data' as a log message to the focus. Returns true iff a message
  14676. * was sent.
  14677. * @param data
  14678. * @returns {boolean} true iff a message was sent.
  14679. */
  14680. sendLogs: function (data) {
  14681. if(!connection.emuc.focusMucJid)
  14682. return false;
  14683. var deflate = true;
  14684. var content = JSON.stringify(data);
  14685. if (deflate) {
  14686. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  14687. }
  14688. content = Base64.encode(content);
  14689. // XEP-0337-ish
  14690. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  14691. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  14692. id: 'PeerConnectionStats'});
  14693. message.c('message').t(content).up();
  14694. if (deflate) {
  14695. message.c('tag', {name: "deflated", value: "true"}).up();
  14696. }
  14697. message.up();
  14698. connection.send(message);
  14699. return true;
  14700. },
  14701. populateData: function () {
  14702. var data = {};
  14703. if (connection.jingle) {
  14704. data = connection.jingle.populateData();
  14705. }
  14706. return data;
  14707. },
  14708. getLogger: function () {
  14709. if(connection.logger)
  14710. return connection.logger.log;
  14711. return null;
  14712. },
  14713. getPrezi: function () {
  14714. return connection.emuc.getPrezi(this.myJid());
  14715. },
  14716. removePreziFromPresence: function () {
  14717. connection.emuc.removePreziFromPresence();
  14718. connection.emuc.sendPresence();
  14719. },
  14720. sendChatMessage: function (message, nickname) {
  14721. connection.emuc.sendMessage(message, nickname);
  14722. },
  14723. setSubject: function (topic) {
  14724. connection.emuc.setSubject(topic);
  14725. },
  14726. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14727. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  14728. },
  14729. dial: function (to, from, roomName,roomPass) {
  14730. connection.rayo.dial(to, from, roomName,roomPass);
  14731. },
  14732. setMute: function (jid, mute) {
  14733. connection.moderate.setMute(jid, mute);
  14734. },
  14735. eject: function (jid) {
  14736. connection.moderate.eject(jid);
  14737. },
  14738. logout: function (callback) {
  14739. Moderator.logout(callback);
  14740. },
  14741. findJidFromResource: function (resource) {
  14742. return connection.emuc.findJidFromResource(resource);
  14743. },
  14744. getMembers: function () {
  14745. return connection.emuc.members;
  14746. },
  14747. getJidFromSSRC: function (ssrc) {
  14748. if(!connection)
  14749. return null;
  14750. return connection.emuc.ssrc2jid[ssrc];
  14751. },
  14752. getMUCJoined: function () {
  14753. return connection.emuc.joined;
  14754. },
  14755. getSessions: function () {
  14756. return connection.jingle.sessions;
  14757. }
  14758. };
  14759. module.exports = XMPP;
  14760. },{"../../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){
  14761. // i18next, v1.7.7
  14762. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  14763. // Distributed under MIT license
  14764. // http://i18next.com
  14765. (function() {
  14766. // add indexOf to non ECMA-262 standard compliant browsers
  14767. if (!Array.prototype.indexOf) {
  14768. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  14769. "use strict";
  14770. if (this == null) {
  14771. throw new TypeError();
  14772. }
  14773. var t = Object(this);
  14774. var len = t.length >>> 0;
  14775. if (len === 0) {
  14776. return -1;
  14777. }
  14778. var n = 0;
  14779. if (arguments.length > 0) {
  14780. n = Number(arguments[1]);
  14781. if (n != n) { // shortcut for verifying if it's NaN
  14782. n = 0;
  14783. } else if (n != 0 && n != Infinity && n != -Infinity) {
  14784. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  14785. }
  14786. }
  14787. if (n >= len) {
  14788. return -1;
  14789. }
  14790. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  14791. for (; k < len; k++) {
  14792. if (k in t && t[k] === searchElement) {
  14793. return k;
  14794. }
  14795. }
  14796. return -1;
  14797. }
  14798. }
  14799. // add lastIndexOf to non ECMA-262 standard compliant browsers
  14800. if (!Array.prototype.lastIndexOf) {
  14801. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  14802. "use strict";
  14803. if (this == null) {
  14804. throw new TypeError();
  14805. }
  14806. var t = Object(this);
  14807. var len = t.length >>> 0;
  14808. if (len === 0) {
  14809. return -1;
  14810. }
  14811. var n = len;
  14812. if (arguments.length > 1) {
  14813. n = Number(arguments[1]);
  14814. if (n != n) {
  14815. n = 0;
  14816. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  14817. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  14818. }
  14819. }
  14820. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  14821. for (; k >= 0; k--) {
  14822. if (k in t && t[k] === searchElement) {
  14823. return k;
  14824. }
  14825. }
  14826. return -1;
  14827. };
  14828. }
  14829. // Add string trim for IE8.
  14830. if (typeof String.prototype.trim !== 'function') {
  14831. String.prototype.trim = function() {
  14832. return this.replace(/^\s+|\s+$/g, '');
  14833. }
  14834. }
  14835. var root = this
  14836. , $ = root.jQuery || root.Zepto
  14837. , i18n = {}
  14838. , resStore = {}
  14839. , currentLng
  14840. , replacementCounter = 0
  14841. , languages = []
  14842. , initialized = false
  14843. , sync = {};
  14844. // Export the i18next object for **CommonJS**.
  14845. // If we're not in CommonJS, add `i18n` to the
  14846. // global object or to jquery.
  14847. if (typeof module !== 'undefined' && module.exports) {
  14848. if (!$) {
  14849. try {
  14850. $ = require('jquery');
  14851. } catch(e) {
  14852. // just ignore
  14853. }
  14854. }
  14855. if ($) {
  14856. $.i18n = $.i18n || i18n;
  14857. }
  14858. module.exports = i18n;
  14859. } else {
  14860. if ($) {
  14861. $.i18n = $.i18n || i18n;
  14862. }
  14863. root.i18n = root.i18n || i18n;
  14864. }
  14865. sync = {
  14866. load: function(lngs, options, cb) {
  14867. if (options.useLocalStorage) {
  14868. sync._loadLocal(lngs, options, function(err, store) {
  14869. var missingLngs = [];
  14870. for (var i = 0, len = lngs.length; i < len; i++) {
  14871. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  14872. }
  14873. if (missingLngs.length > 0) {
  14874. sync._fetch(missingLngs, options, function(err, fetched) {
  14875. f.extend(store, fetched);
  14876. sync._storeLocal(fetched);
  14877. cb(null, store);
  14878. });
  14879. } else {
  14880. cb(null, store);
  14881. }
  14882. });
  14883. } else {
  14884. sync._fetch(lngs, options, function(err, store){
  14885. cb(null, store);
  14886. });
  14887. }
  14888. },
  14889. _loadLocal: function(lngs, options, cb) {
  14890. var store = {}
  14891. , nowMS = new Date().getTime();
  14892. if(window.localStorage) {
  14893. var todo = lngs.length;
  14894. f.each(lngs, function(key, lng) {
  14895. var local = window.localStorage.getItem('res_' + lng);
  14896. if (local) {
  14897. local = JSON.parse(local);
  14898. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  14899. store[lng] = local;
  14900. }
  14901. }
  14902. todo--; // wait for all done befor callback
  14903. if (todo === 0) cb(null, store);
  14904. });
  14905. }
  14906. },
  14907. _storeLocal: function(store) {
  14908. if(window.localStorage) {
  14909. for (var m in store) {
  14910. store[m].i18nStamp = new Date().getTime();
  14911. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  14912. }
  14913. }
  14914. return;
  14915. },
  14916. _fetch: function(lngs, options, cb) {
  14917. var ns = options.ns
  14918. , store = {};
  14919. if (!options.dynamicLoad) {
  14920. var todo = ns.namespaces.length * lngs.length
  14921. , errors;
  14922. // load each file individual
  14923. f.each(ns.namespaces, function(nsIndex, nsValue) {
  14924. f.each(lngs, function(lngIndex, lngValue) {
  14925. // Call this once our translation has returned.
  14926. var loadComplete = function(err, data) {
  14927. if (err) {
  14928. errors = errors || [];
  14929. errors.push(err);
  14930. }
  14931. store[lngValue] = store[lngValue] || {};
  14932. store[lngValue][nsValue] = data;
  14933. todo--; // wait for all done befor callback
  14934. if (todo === 0) cb(errors, store);
  14935. };
  14936. if(typeof options.customLoad == 'function'){
  14937. // Use the specified custom callback.
  14938. options.customLoad(lngValue, nsValue, options, loadComplete);
  14939. } else {
  14940. //~ // Use our inbuilt sync.
  14941. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  14942. }
  14943. });
  14944. });
  14945. } else {
  14946. // Call this once our translation has returned.
  14947. var loadComplete = function(err, data) {
  14948. cb(null, data);
  14949. };
  14950. if(typeof options.customLoad == 'function'){
  14951. // Use the specified custom callback.
  14952. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  14953. } else {
  14954. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  14955. // load all needed stuff once
  14956. f.ajax({
  14957. url: url,
  14958. success: function(data, status, xhr) {
  14959. f.log('loaded: ' + url);
  14960. loadComplete(null, data);
  14961. },
  14962. error : function(xhr, status, error) {
  14963. f.log('failed loading: ' + url);
  14964. loadComplete('failed loading resource.json error: ' + error);
  14965. },
  14966. dataType: "json",
  14967. async : options.getAsync
  14968. });
  14969. }
  14970. }
  14971. },
  14972. _fetchOne: function(lng, ns, options, done) {
  14973. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  14974. f.ajax({
  14975. url: url,
  14976. success: function(data, status, xhr) {
  14977. f.log('loaded: ' + url);
  14978. done(null, data);
  14979. },
  14980. error : function(xhr, status, error) {
  14981. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  14982. // file loaded but invalid json, stop waste time !
  14983. f.error('There is a typo in: ' + url);
  14984. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  14985. f.log('Does not exist: ' + url);
  14986. } else {
  14987. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  14988. f.log(theStatus + ' when loading ' + url);
  14989. }
  14990. done(error, {});
  14991. },
  14992. dataType: "json",
  14993. async : options.getAsync
  14994. });
  14995. },
  14996. postMissing: function(lng, ns, key, defaultValue, lngs) {
  14997. var payload = {};
  14998. payload[key] = defaultValue;
  14999. var urls = [];
  15000. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  15001. for (var i = 0; i < o.fallbackLng.length; i++) {
  15002. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  15003. }
  15004. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  15005. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  15006. } else if (o.sendMissingTo === 'all') {
  15007. for (var i = 0, l = lngs.length; i < l; i++) {
  15008. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  15009. }
  15010. }
  15011. for (var y = 0, len = urls.length; y < len; y++) {
  15012. var item = urls[y];
  15013. f.ajax({
  15014. url: item.url,
  15015. type: o.sendType,
  15016. data: payload,
  15017. success: function(data, status, xhr) {
  15018. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  15019. // add key to resStore
  15020. var keys = key.split('.');
  15021. var x = 0;
  15022. var value = resStore[item.lng][ns];
  15023. while (keys[x]) {
  15024. if (x === keys.length - 1) {
  15025. value = value[keys[x]] = defaultValue;
  15026. } else {
  15027. value = value[keys[x]] = value[keys[x]] || {};
  15028. }
  15029. x++;
  15030. }
  15031. },
  15032. error : function(xhr, status, error) {
  15033. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  15034. },
  15035. dataType: "json",
  15036. async : o.postAsync
  15037. });
  15038. }
  15039. },
  15040. reload: reload
  15041. };
  15042. // defaults
  15043. var o = {
  15044. lng: undefined,
  15045. load: 'all',
  15046. preload: [],
  15047. lowerCaseLng: false,
  15048. returnObjectTrees: false,
  15049. fallbackLng: ['dev'],
  15050. fallbackNS: [],
  15051. detectLngQS: 'setLng',
  15052. detectLngFromLocalStorage: false,
  15053. ns: 'translation',
  15054. fallbackOnNull: true,
  15055. fallbackOnEmpty: false,
  15056. fallbackToDefaultNS: false,
  15057. nsseparator: ':',
  15058. keyseparator: '.',
  15059. selectorAttr: 'data-i18n',
  15060. debug: false,
  15061. resGetPath: 'locales/__lng__/__ns__.json',
  15062. resPostPath: 'locales/add/__lng__/__ns__',
  15063. getAsync: true,
  15064. postAsync: true,
  15065. resStore: undefined,
  15066. useLocalStorage: false,
  15067. localStorageExpirationTime: 7*24*60*60*1000,
  15068. dynamicLoad: false,
  15069. sendMissing: false,
  15070. sendMissingTo: 'fallback', // current | all
  15071. sendType: 'POST',
  15072. interpolationPrefix: '__',
  15073. interpolationSuffix: '__',
  15074. defaultVariables: false,
  15075. reusePrefix: '$t(',
  15076. reuseSuffix: ')',
  15077. pluralSuffix: '_plural',
  15078. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  15079. contextNotFound: ['context_not_found', Math.random()].join(''),
  15080. escapeInterpolation: false,
  15081. indefiniteSuffix: '_indefinite',
  15082. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  15083. setJqueryExt: true,
  15084. defaultValueFromContent: true,
  15085. useDataAttrOptions: false,
  15086. cookieExpirationTime: undefined,
  15087. useCookie: true,
  15088. cookieName: 'i18next',
  15089. cookieDomain: undefined,
  15090. objectTreeKeyHandler: undefined,
  15091. postProcess: undefined,
  15092. parseMissingKey: undefined,
  15093. missingKeyHandler: sync.postMissing,
  15094. shortcutFunction: 'sprintf' // or: defaultValue
  15095. };
  15096. function _extend(target, source) {
  15097. if (!source || typeof source === 'function') {
  15098. return target;
  15099. }
  15100. for (var attr in source) { target[attr] = source[attr]; }
  15101. return target;
  15102. }
  15103. function _deepExtend(target, source) {
  15104. for (var prop in source)
  15105. if (prop in target)
  15106. _deepExtend(target[prop], source[prop]);
  15107. else
  15108. target[prop] = source[prop];
  15109. return target;
  15110. }
  15111. function _each(object, callback, args) {
  15112. var name, i = 0,
  15113. length = object.length,
  15114. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  15115. if (args) {
  15116. if (isObj) {
  15117. for (name in object) {
  15118. if (callback.apply(object[name], args) === false) {
  15119. break;
  15120. }
  15121. }
  15122. } else {
  15123. for ( ; i < length; ) {
  15124. if (callback.apply(object[i++], args) === false) {
  15125. break;
  15126. }
  15127. }
  15128. }
  15129. // A special, fast, case for the most common use of each
  15130. } else {
  15131. if (isObj) {
  15132. for (name in object) {
  15133. if (callback.call(object[name], name, object[name]) === false) {
  15134. break;
  15135. }
  15136. }
  15137. } else {
  15138. for ( ; i < length; ) {
  15139. if (callback.call(object[i], i, object[i++]) === false) {
  15140. break;
  15141. }
  15142. }
  15143. }
  15144. }
  15145. return object;
  15146. }
  15147. var _entityMap = {
  15148. "&": "&amp;",
  15149. "<": "&lt;",
  15150. ">": "&gt;",
  15151. '"': '&quot;',
  15152. "'": '&#39;',
  15153. "/": '&#x2F;'
  15154. };
  15155. function _escape(data) {
  15156. if (typeof data === 'string') {
  15157. return data.replace(/[&<>"'\/]/g, function (s) {
  15158. return _entityMap[s];
  15159. });
  15160. }else{
  15161. return data;
  15162. }
  15163. }
  15164. function _ajax(options) {
  15165. // v0.5.0 of https://github.com/goloroden/http.js
  15166. var getXhr = function (callback) {
  15167. // Use the native XHR object if the browser supports it.
  15168. if (window.XMLHttpRequest) {
  15169. return callback(null, new XMLHttpRequest());
  15170. } else if (window.ActiveXObject) {
  15171. // In Internet Explorer check for ActiveX versions of the XHR object.
  15172. try {
  15173. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  15174. } catch (e) {
  15175. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  15176. }
  15177. }
  15178. // If no XHR support was found, throw an error.
  15179. return callback(new Error());
  15180. };
  15181. var encodeUsingUrlEncoding = function (data) {
  15182. if(typeof data === 'string') {
  15183. return data;
  15184. }
  15185. var result = [];
  15186. for(var dataItem in data) {
  15187. if(data.hasOwnProperty(dataItem)) {
  15188. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  15189. }
  15190. }
  15191. return result.join('&');
  15192. };
  15193. var utf8 = function (text) {
  15194. text = text.replace(/\r\n/g, '\n');
  15195. var result = '';
  15196. for(var i = 0; i < text.length; i++) {
  15197. var c = text.charCodeAt(i);
  15198. if(c < 128) {
  15199. result += String.fromCharCode(c);
  15200. } else if((c > 127) && (c < 2048)) {
  15201. result += String.fromCharCode((c >> 6) | 192);
  15202. result += String.fromCharCode((c & 63) | 128);
  15203. } else {
  15204. result += String.fromCharCode((c >> 12) | 224);
  15205. result += String.fromCharCode(((c >> 6) & 63) | 128);
  15206. result += String.fromCharCode((c & 63) | 128);
  15207. }
  15208. }
  15209. return result;
  15210. };
  15211. var base64 = function (text) {
  15212. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15213. text = utf8(text);
  15214. var result = '',
  15215. chr1, chr2, chr3,
  15216. enc1, enc2, enc3, enc4,
  15217. i = 0;
  15218. do {
  15219. chr1 = text.charCodeAt(i++);
  15220. chr2 = text.charCodeAt(i++);
  15221. chr3 = text.charCodeAt(i++);
  15222. enc1 = chr1 >> 2;
  15223. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  15224. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  15225. enc4 = chr3 & 63;
  15226. if(isNaN(chr2)) {
  15227. enc3 = enc4 = 64;
  15228. } else if(isNaN(chr3)) {
  15229. enc4 = 64;
  15230. }
  15231. result +=
  15232. keyStr.charAt(enc1) +
  15233. keyStr.charAt(enc2) +
  15234. keyStr.charAt(enc3) +
  15235. keyStr.charAt(enc4);
  15236. chr1 = chr2 = chr3 = '';
  15237. enc1 = enc2 = enc3 = enc4 = '';
  15238. } while(i < text.length);
  15239. return result;
  15240. };
  15241. var mergeHeaders = function () {
  15242. // Use the first header object as base.
  15243. var result = arguments[0];
  15244. // Iterate through the remaining header objects and add them.
  15245. for(var i = 1; i < arguments.length; i++) {
  15246. var currentHeaders = arguments[i];
  15247. for(var header in currentHeaders) {
  15248. if(currentHeaders.hasOwnProperty(header)) {
  15249. result[header] = currentHeaders[header];
  15250. }
  15251. }
  15252. }
  15253. // Return the merged headers.
  15254. return result;
  15255. };
  15256. var ajax = function (method, url, options, callback) {
  15257. // Adjust parameters.
  15258. if(typeof options === 'function') {
  15259. callback = options;
  15260. options = {};
  15261. }
  15262. // Set default parameter values.
  15263. options.cache = options.cache || false;
  15264. options.data = options.data || {};
  15265. options.headers = options.headers || {};
  15266. options.jsonp = options.jsonp || false;
  15267. options.async = options.async === undefined ? true : options.async;
  15268. // Merge the various header objects.
  15269. var headers = mergeHeaders({
  15270. 'accept': '*/*',
  15271. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  15272. }, ajax.headers, options.headers);
  15273. // Encode the data according to the content-type.
  15274. var payload;
  15275. if (headers['content-type'] === 'application/json') {
  15276. payload = JSON.stringify(options.data);
  15277. } else {
  15278. payload = encodeUsingUrlEncoding(options.data);
  15279. }
  15280. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  15281. // if neccessary.
  15282. if(method === 'GET') {
  15283. // Setup the query string.
  15284. var queryString = [];
  15285. if(payload) {
  15286. queryString.push(payload);
  15287. payload = null;
  15288. }
  15289. // Handle caching.
  15290. if(!options.cache) {
  15291. queryString.push('_=' + (new Date()).getTime());
  15292. }
  15293. // If neccessary prepare the query string for a JSONP call.
  15294. if(options.jsonp) {
  15295. queryString.push('callback=' + options.jsonp);
  15296. queryString.push('jsonp=' + options.jsonp);
  15297. }
  15298. // Merge the query string and attach it to the url.
  15299. queryString = queryString.join('&');
  15300. if (queryString.length > 1) {
  15301. if (url.indexOf('?') > -1) {
  15302. url += '&' + queryString;
  15303. } else {
  15304. url += '?' + queryString;
  15305. }
  15306. }
  15307. // Make a JSONP call if neccessary.
  15308. if(options.jsonp) {
  15309. var head = document.getElementsByTagName('head')[0];
  15310. var script = document.createElement('script');
  15311. script.type = 'text/javascript';
  15312. script.src = url;
  15313. head.appendChild(script);
  15314. return;
  15315. }
  15316. }
  15317. // Since we got here, it is no JSONP request, so make a normal XHR request.
  15318. getXhr(function (err, xhr) {
  15319. if(err) return callback(err);
  15320. // Open the request.
  15321. xhr.open(method, url, options.async);
  15322. // Set the request headers.
  15323. for(var header in headers) {
  15324. if(headers.hasOwnProperty(header)) {
  15325. xhr.setRequestHeader(header, headers[header]);
  15326. }
  15327. }
  15328. // Handle the request events.
  15329. xhr.onreadystatechange = function () {
  15330. if(xhr.readyState === 4) {
  15331. var data = xhr.responseText || '';
  15332. // If no callback is given, return.
  15333. if(!callback) {
  15334. return;
  15335. }
  15336. // Return an object that provides access to the data as text and JSON.
  15337. callback(xhr.status, {
  15338. text: function () {
  15339. return data;
  15340. },
  15341. json: function () {
  15342. try {
  15343. return JSON.parse(data)
  15344. } catch (e) {
  15345. f.error('Can not parse JSON. URL: ' + url);
  15346. return {};
  15347. }
  15348. }
  15349. });
  15350. }
  15351. };
  15352. // Actually send the XHR request.
  15353. xhr.send(payload);
  15354. });
  15355. };
  15356. // Define the external interface.
  15357. var http = {
  15358. authBasic: function (username, password) {
  15359. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  15360. },
  15361. connect: function (url, options, callback) {
  15362. return ajax('CONNECT', url, options, callback);
  15363. },
  15364. del: function (url, options, callback) {
  15365. return ajax('DELETE', url, options, callback);
  15366. },
  15367. get: function (url, options, callback) {
  15368. return ajax('GET', url, options, callback);
  15369. },
  15370. head: function (url, options, callback) {
  15371. return ajax('HEAD', url, options, callback);
  15372. },
  15373. headers: function (headers) {
  15374. ajax.headers = headers || {};
  15375. },
  15376. isAllowed: function (url, verb, callback) {
  15377. this.options(url, function (status, data) {
  15378. callback(data.text().indexOf(verb) !== -1);
  15379. });
  15380. },
  15381. options: function (url, options, callback) {
  15382. return ajax('OPTIONS', url, options, callback);
  15383. },
  15384. patch: function (url, options, callback) {
  15385. return ajax('PATCH', url, options, callback);
  15386. },
  15387. post: function (url, options, callback) {
  15388. return ajax('POST', url, options, callback);
  15389. },
  15390. put: function (url, options, callback) {
  15391. return ajax('PUT', url, options, callback);
  15392. },
  15393. trace: function (url, options, callback) {
  15394. return ajax('TRACE', url, options, callback);
  15395. }
  15396. };
  15397. var methode = options.type ? options.type.toLowerCase() : 'get';
  15398. http[methode](options.url, options, function (status, data) {
  15399. // file: protocol always gives status code 0, so check for data
  15400. if (status === 200 || (status === 0 && data.text())) {
  15401. options.success(data.json(), status, null);
  15402. } else {
  15403. options.error(data.text(), status, null);
  15404. }
  15405. });
  15406. }
  15407. var _cookie = {
  15408. create: function(name,value,minutes,domain) {
  15409. var expires;
  15410. if (minutes) {
  15411. var date = new Date();
  15412. date.setTime(date.getTime()+(minutes*60*1000));
  15413. expires = "; expires="+date.toGMTString();
  15414. }
  15415. else expires = "";
  15416. domain = (domain)? "domain="+domain+";" : "";
  15417. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  15418. },
  15419. read: function(name) {
  15420. var nameEQ = name + "=";
  15421. var ca = document.cookie.split(';');
  15422. for(var i=0;i < ca.length;i++) {
  15423. var c = ca[i];
  15424. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  15425. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  15426. }
  15427. return null;
  15428. },
  15429. remove: function(name) {
  15430. this.create(name,"",-1);
  15431. }
  15432. };
  15433. var cookie_noop = {
  15434. create: function(name,value,minutes,domain) {},
  15435. read: function(name) { return null; },
  15436. remove: function(name) {}
  15437. };
  15438. // move dependent functions to a container so that
  15439. // they can be overriden easier in no jquery environment (node.js)
  15440. var f = {
  15441. extend: $ ? $.extend : _extend,
  15442. deepExtend: _deepExtend,
  15443. each: $ ? $.each : _each,
  15444. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  15445. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  15446. detectLanguage: detectLanguage,
  15447. escape: _escape,
  15448. log: function(str) {
  15449. if (o.debug && typeof console !== "undefined") console.log(str);
  15450. },
  15451. error: function(str) {
  15452. if (typeof console !== "undefined") console.error(str);
  15453. },
  15454. getCountyIndexOfLng: function(lng) {
  15455. var lng_index = 0;
  15456. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  15457. return lng_index;
  15458. },
  15459. toLanguages: function(lng) {
  15460. var log = this.log;
  15461. function applyCase(l) {
  15462. var ret = l;
  15463. if (typeof l === 'string' && l.indexOf('-') > -1) {
  15464. var parts = l.split('-');
  15465. ret = o.lowerCaseLng ?
  15466. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  15467. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  15468. } else {
  15469. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  15470. }
  15471. return ret;
  15472. }
  15473. var languages = [];
  15474. var whitelist = o.lngWhitelist || false;
  15475. var addLanguage = function(language){
  15476. //reject langs not whitelisted
  15477. if(!whitelist || whitelist.indexOf(language) > -1){
  15478. languages.push(language);
  15479. }else{
  15480. log('rejecting non-whitelisted language: ' + language);
  15481. }
  15482. };
  15483. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  15484. var parts = lng.split('-');
  15485. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  15486. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  15487. } else {
  15488. addLanguage(applyCase(lng));
  15489. }
  15490. for (var i = 0; i < o.fallbackLng.length; i++) {
  15491. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  15492. }
  15493. return languages;
  15494. },
  15495. regexEscape: function(str) {
  15496. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  15497. },
  15498. regexReplacementEscape: function(strOrFn) {
  15499. if (typeof strOrFn === 'string') {
  15500. return strOrFn.replace(/\$/g, "$$$$");
  15501. } else {
  15502. return strOrFn;
  15503. }
  15504. },
  15505. localStorage: {
  15506. setItem: function(key, value) {
  15507. if (window.localStorage) {
  15508. try {
  15509. window.localStorage.setItem(key, value);
  15510. } catch (e) {
  15511. f.log('failed to set value for key "' + key + '" to localStorage.');
  15512. }
  15513. }
  15514. }
  15515. }
  15516. };
  15517. function init(options, cb) {
  15518. if (typeof options === 'function') {
  15519. cb = options;
  15520. options = {};
  15521. }
  15522. options = options || {};
  15523. // override defaults with passed in options
  15524. f.extend(o, options);
  15525. delete o.fixLng; /* passed in each time */
  15526. // override functions: .log(), .detectLanguage(), etc
  15527. if (o.functions) {
  15528. delete o.functions;
  15529. f.extend(f, options.functions);
  15530. }
  15531. // create namespace object if namespace is passed in as string
  15532. if (typeof o.ns == 'string') {
  15533. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  15534. }
  15535. // fallback namespaces
  15536. if (typeof o.fallbackNS == 'string') {
  15537. o.fallbackNS = [o.fallbackNS];
  15538. }
  15539. // fallback languages
  15540. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  15541. o.fallbackLng = [o.fallbackLng];
  15542. }
  15543. // escape prefix/suffix
  15544. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  15545. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  15546. if (!o.lng) o.lng = f.detectLanguage();
  15547. languages = f.toLanguages(o.lng);
  15548. currentLng = languages[0];
  15549. f.log('currentLng set to: ' + currentLng);
  15550. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  15551. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  15552. }
  15553. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  15554. f.localStorage.setItem('i18next_lng', currentLng);
  15555. }
  15556. var lngTranslate = translate;
  15557. if (options.fixLng) {
  15558. lngTranslate = function(key, options) {
  15559. options = options || {};
  15560. options.lng = options.lng || lngTranslate.lng;
  15561. return translate(key, options);
  15562. };
  15563. lngTranslate.lng = currentLng;
  15564. }
  15565. pluralExtensions.setCurrentLng(currentLng);
  15566. // add JQuery extensions
  15567. if ($ && o.setJqueryExt) addJqueryFunct();
  15568. // jQuery deferred
  15569. var deferred;
  15570. if ($ && $.Deferred) {
  15571. deferred = $.Deferred();
  15572. }
  15573. // return immidiatly if res are passed in
  15574. if (o.resStore) {
  15575. resStore = o.resStore;
  15576. initialized = true;
  15577. if (cb) cb(lngTranslate);
  15578. if (deferred) deferred.resolve(lngTranslate);
  15579. if (deferred) return deferred.promise();
  15580. return;
  15581. }
  15582. // languages to load
  15583. var lngsToLoad = f.toLanguages(o.lng);
  15584. if (typeof o.preload === 'string') o.preload = [o.preload];
  15585. for (var i = 0, l = o.preload.length; i < l; i++) {
  15586. var pres = f.toLanguages(o.preload[i]);
  15587. for (var y = 0, len = pres.length; y < len; y++) {
  15588. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15589. lngsToLoad.push(pres[y]);
  15590. }
  15591. }
  15592. }
  15593. // else load them
  15594. i18n.sync.load(lngsToLoad, o, function(err, store) {
  15595. resStore = store;
  15596. initialized = true;
  15597. if (cb) cb(lngTranslate);
  15598. if (deferred) deferred.resolve(lngTranslate);
  15599. });
  15600. if (deferred) return deferred.promise();
  15601. }
  15602. function preload(lngs, cb) {
  15603. if (typeof lngs === 'string') lngs = [lngs];
  15604. for (var i = 0, l = lngs.length; i < l; i++) {
  15605. if (o.preload.indexOf(lngs[i]) < 0) {
  15606. o.preload.push(lngs[i]);
  15607. }
  15608. }
  15609. return init(cb);
  15610. }
  15611. function addResourceBundle(lng, ns, resources, deep) {
  15612. if (typeof ns !== 'string') {
  15613. resources = ns;
  15614. ns = o.ns.defaultNs;
  15615. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15616. o.ns.namespaces.push(ns);
  15617. }
  15618. resStore[lng] = resStore[lng] || {};
  15619. resStore[lng][ns] = resStore[lng][ns] || {};
  15620. if (deep) {
  15621. f.deepExtend(resStore[lng][ns], resources);
  15622. } else {
  15623. f.extend(resStore[lng][ns], resources);
  15624. }
  15625. }
  15626. function hasResourceBundle(lng, ns) {
  15627. if (typeof ns !== 'string') {
  15628. ns = o.ns.defaultNs;
  15629. }
  15630. resStore[lng] = resStore[lng] || {};
  15631. var res = resStore[lng][ns] || {};
  15632. var hasValues = false;
  15633. for(var prop in res) {
  15634. if (res.hasOwnProperty(prop)) {
  15635. hasValues = true;
  15636. }
  15637. }
  15638. return hasValues;
  15639. }
  15640. function removeResourceBundle(lng, ns) {
  15641. if (typeof ns !== 'string') {
  15642. ns = o.ns.defaultNs;
  15643. }
  15644. resStore[lng] = resStore[lng] || {};
  15645. resStore[lng][ns] = {};
  15646. }
  15647. function addResource(lng, ns, key, value) {
  15648. if (typeof ns !== 'string') {
  15649. resource = ns;
  15650. ns = o.ns.defaultNs;
  15651. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15652. o.ns.namespaces.push(ns);
  15653. }
  15654. resStore[lng] = resStore[lng] || {};
  15655. resStore[lng][ns] = resStore[lng][ns] || {};
  15656. var keys = key.split(o.keyseparator);
  15657. var x = 0;
  15658. var node = resStore[lng][ns];
  15659. var origRef = node;
  15660. while (keys[x]) {
  15661. if (x == keys.length - 1)
  15662. node[keys[x]] = value;
  15663. else {
  15664. if (node[keys[x]] == null)
  15665. node[keys[x]] = {};
  15666. node = node[keys[x]];
  15667. }
  15668. x++;
  15669. }
  15670. }
  15671. function addResources(lng, ns, resources) {
  15672. if (typeof ns !== 'string') {
  15673. resource = ns;
  15674. ns = o.ns.defaultNs;
  15675. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15676. o.ns.namespaces.push(ns);
  15677. }
  15678. for (var m in resources) {
  15679. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  15680. }
  15681. }
  15682. function setDefaultNamespace(ns) {
  15683. o.ns.defaultNs = ns;
  15684. }
  15685. function loadNamespace(namespace, cb) {
  15686. loadNamespaces([namespace], cb);
  15687. }
  15688. function loadNamespaces(namespaces, cb) {
  15689. var opts = {
  15690. dynamicLoad: o.dynamicLoad,
  15691. resGetPath: o.resGetPath,
  15692. getAsync: o.getAsync,
  15693. customLoad: o.customLoad,
  15694. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  15695. };
  15696. // languages to load
  15697. var lngsToLoad = f.toLanguages(o.lng);
  15698. if (typeof o.preload === 'string') o.preload = [o.preload];
  15699. for (var i = 0, l = o.preload.length; i < l; i++) {
  15700. var pres = f.toLanguages(o.preload[i]);
  15701. for (var y = 0, len = pres.length; y < len; y++) {
  15702. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15703. lngsToLoad.push(pres[y]);
  15704. }
  15705. }
  15706. }
  15707. // check if we have to load
  15708. var lngNeedLoad = [];
  15709. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  15710. var needLoad = false;
  15711. var resSet = resStore[lngsToLoad[a]];
  15712. if (resSet) {
  15713. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  15714. if (!resSet[namespaces[b]]) needLoad = true;
  15715. }
  15716. } else {
  15717. needLoad = true;
  15718. }
  15719. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  15720. }
  15721. if (lngNeedLoad.length) {
  15722. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  15723. var todo = namespaces.length * lngNeedLoad.length;
  15724. // load each file individual
  15725. f.each(namespaces, function(nsIndex, nsValue) {
  15726. // append namespace to namespace array
  15727. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  15728. o.ns.namespaces.push(nsValue);
  15729. }
  15730. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  15731. resStore[lngValue] = resStore[lngValue] || {};
  15732. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  15733. todo--; // wait for all done befor callback
  15734. if (todo === 0 && cb) {
  15735. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  15736. cb();
  15737. }
  15738. });
  15739. });
  15740. });
  15741. } else {
  15742. if (cb) cb();
  15743. }
  15744. }
  15745. function setLng(lng, options, cb) {
  15746. if (typeof options === 'function') {
  15747. cb = options;
  15748. options = {};
  15749. } else if (!options) {
  15750. options = {};
  15751. }
  15752. options.lng = lng;
  15753. return init(options, cb);
  15754. }
  15755. function lng() {
  15756. return currentLng;
  15757. }
  15758. function reload(cb) {
  15759. resStore = {};
  15760. setLng(currentLng, cb);
  15761. }
  15762. function addJqueryFunct() {
  15763. // $.t shortcut
  15764. $.t = $.t || translate;
  15765. function parse(ele, key, options) {
  15766. if (key.length === 0) return;
  15767. var attr = 'text';
  15768. if (key.indexOf('[') === 0) {
  15769. var parts = key.split(']');
  15770. key = parts[1];
  15771. attr = parts[0].substr(1, parts[0].length-1);
  15772. }
  15773. if (key.indexOf(';') === key.length-1) {
  15774. key = key.substr(0, key.length-2);
  15775. }
  15776. var optionsToUse;
  15777. if (attr === 'html') {
  15778. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  15779. ele.html($.t(key, optionsToUse));
  15780. } else if (attr === 'text') {
  15781. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  15782. ele.text($.t(key, optionsToUse));
  15783. } else if (attr === 'prepend') {
  15784. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  15785. ele.prepend($.t(key, optionsToUse));
  15786. } else if (attr === 'append') {
  15787. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  15788. ele.append($.t(key, optionsToUse));
  15789. } else if (attr.indexOf("data-") === 0) {
  15790. var dataAttr = attr.substr(("data-").length);
  15791. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  15792. var translated = $.t(key, optionsToUse);
  15793. //we change into the data cache
  15794. ele.data(dataAttr, translated);
  15795. //we change into the dom
  15796. ele.attr(attr, translated);
  15797. } else {
  15798. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  15799. ele.attr(attr, $.t(key, optionsToUse));
  15800. }
  15801. }
  15802. function localize(ele, options) {
  15803. var key = ele.attr(o.selectorAttr);
  15804. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  15805. if (!key) return;
  15806. var target = ele
  15807. , targetSelector = ele.data("i18n-target");
  15808. if (targetSelector) {
  15809. target = ele.find(targetSelector) || ele;
  15810. }
  15811. if (!options && o.useDataAttrOptions === true) {
  15812. options = ele.data("i18n-options");
  15813. }
  15814. options = options || {};
  15815. if (key.indexOf(';') >= 0) {
  15816. var keys = key.split(';');
  15817. $.each(keys, function(m, k) {
  15818. if (k !== '') parse(target, k, options);
  15819. });
  15820. } else {
  15821. parse(target, key, options);
  15822. }
  15823. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  15824. }
  15825. // fn
  15826. $.fn.i18n = function (options) {
  15827. return this.each(function() {
  15828. // localize element itself
  15829. localize($(this), options);
  15830. // localize childs
  15831. var elements = $(this).find('[' + o.selectorAttr + ']');
  15832. elements.each(function() {
  15833. localize($(this), options);
  15834. });
  15835. });
  15836. };
  15837. }
  15838. function applyReplacement(str, replacementHash, nestedKey, options) {
  15839. if (!str) return str;
  15840. options = options || replacementHash; // first call uses replacement hash combined with options
  15841. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  15842. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  15843. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  15844. , unEscapingSuffix = 'HTML'+suffix;
  15845. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  15846. f.each(hash, function(key, value) {
  15847. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  15848. if (typeof value === 'object' && value !== null) {
  15849. str = applyReplacement(str, value, nextKey, options);
  15850. } else {
  15851. if (options.escapeInterpolation || o.escapeInterpolation) {
  15852. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  15853. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  15854. } else {
  15855. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  15856. }
  15857. // str = options.escapeInterpolation;
  15858. }
  15859. });
  15860. return str;
  15861. }
  15862. // append it to functions
  15863. f.applyReplacement = applyReplacement;
  15864. function applyReuse(translated, options) {
  15865. var comma = ',';
  15866. var options_open = '{';
  15867. var options_close = '}';
  15868. var opts = f.extend({}, options);
  15869. delete opts.postProcess;
  15870. while (translated.indexOf(o.reusePrefix) != -1) {
  15871. replacementCounter++;
  15872. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  15873. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  15874. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  15875. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  15876. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  15877. if (index_of_end_of_closing <= index_of_opening) {
  15878. f.error('there is an missing closing in following translation value', translated);
  15879. return '';
  15880. }
  15881. if (token_without_symbols.indexOf(comma) != -1) {
  15882. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  15883. 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) {
  15884. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  15885. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  15886. try {
  15887. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  15888. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  15889. } catch (e) {
  15890. }
  15891. }
  15892. }
  15893. var translated_token = _translate(token_without_symbols, opts);
  15894. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  15895. }
  15896. return translated;
  15897. }
  15898. function hasContext(options) {
  15899. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  15900. }
  15901. function needsPlural(options, lng) {
  15902. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  15903. }
  15904. function needsIndefiniteArticle(options) {
  15905. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  15906. }
  15907. function exists(key, options) {
  15908. options = options || {};
  15909. var notFound = _getDefaultValue(key, options)
  15910. , found = _find(key, options);
  15911. return found !== undefined || found === notFound;
  15912. }
  15913. function translate(key, options) {
  15914. options = options || {};
  15915. if (!initialized) {
  15916. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  15917. return options.defaultValue || '';
  15918. };
  15919. replacementCounter = 0;
  15920. return _translate.apply(null, arguments);
  15921. }
  15922. function _getDefaultValue(key, options) {
  15923. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  15924. }
  15925. function _injectSprintfProcessor() {
  15926. var values = [];
  15927. // mh: build array from second argument onwards
  15928. for (var i = 1; i < arguments.length; i++) {
  15929. values.push(arguments[i]);
  15930. }
  15931. return {
  15932. postProcess: 'sprintf',
  15933. sprintf: values
  15934. };
  15935. }
  15936. function _translate(potentialKeys, options) {
  15937. if (options && typeof options !== 'object') {
  15938. if (o.shortcutFunction === 'sprintf') {
  15939. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  15940. options = _injectSprintfProcessor.apply(null, arguments);
  15941. } else if (o.shortcutFunction === 'defaultValue') {
  15942. options = {
  15943. defaultValue: options
  15944. }
  15945. }
  15946. } else {
  15947. options = options || {};
  15948. }
  15949. if (typeof o.defaultVariables === 'object') {
  15950. options = f.extend({}, o.defaultVariables, options);
  15951. }
  15952. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  15953. if (typeof potentialKeys === 'string') {
  15954. potentialKeys = [potentialKeys];
  15955. }
  15956. var key = potentialKeys[0];
  15957. if (potentialKeys.length > 1) {
  15958. for (var i = 0; i < potentialKeys.length; i++) {
  15959. key = potentialKeys[i];
  15960. if (exists(key, options)) {
  15961. break;
  15962. }
  15963. }
  15964. }
  15965. var notFound = _getDefaultValue(key, options)
  15966. , found = _find(key, options)
  15967. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  15968. , ns = options.ns || o.ns.defaultNs
  15969. , parts;
  15970. // split ns and key
  15971. if (key.indexOf(o.nsseparator) > -1) {
  15972. parts = key.split(o.nsseparator);
  15973. ns = parts[0];
  15974. key = parts[1];
  15975. }
  15976. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  15977. if (options.lng) {
  15978. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  15979. } else {
  15980. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  15981. }
  15982. }
  15983. var postProcessor = options.postProcess || o.postProcess;
  15984. if (found !== undefined && postProcessor) {
  15985. if (postProcessors[postProcessor]) {
  15986. found = postProcessors[postProcessor](found, key, options);
  15987. }
  15988. }
  15989. // process notFound if function exists
  15990. var splitNotFound = notFound;
  15991. if (notFound.indexOf(o.nsseparator) > -1) {
  15992. parts = notFound.split(o.nsseparator);
  15993. splitNotFound = parts[1];
  15994. }
  15995. if (splitNotFound === key && o.parseMissingKey) {
  15996. notFound = o.parseMissingKey(notFound);
  15997. }
  15998. if (found === undefined) {
  15999. notFound = applyReplacement(notFound, options);
  16000. notFound = applyReuse(notFound, options);
  16001. if (postProcessor && postProcessors[postProcessor]) {
  16002. var val = _getDefaultValue(key, options);
  16003. found = postProcessors[postProcessor](val, key, options);
  16004. }
  16005. }
  16006. return (found !== undefined) ? found : notFound;
  16007. }
  16008. function _find(key, options) {
  16009. options = options || {};
  16010. var optionWithoutCount, translated
  16011. , notFound = _getDefaultValue(key, options)
  16012. , lngs = languages;
  16013. if (!resStore) { return notFound; } // no resStore to translate from
  16014. // CI mode
  16015. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  16016. // passed in lng
  16017. if (options.lngs) lngs = options.lngs;
  16018. if (options.lng) {
  16019. lngs = f.toLanguages(options.lng, options.fallbackLng);
  16020. if (!resStore[lngs[0]]) {
  16021. var oldAsync = o.getAsync;
  16022. o.getAsync = false;
  16023. i18n.sync.load(lngs, o, function(err, store) {
  16024. f.extend(resStore, store);
  16025. o.getAsync = oldAsync;
  16026. });
  16027. }
  16028. }
  16029. var ns = options.ns || o.ns.defaultNs;
  16030. if (key.indexOf(o.nsseparator) > -1) {
  16031. var parts = key.split(o.nsseparator);
  16032. ns = parts[0];
  16033. key = parts[1];
  16034. }
  16035. if (hasContext(options)) {
  16036. optionWithoutCount = f.extend({}, options);
  16037. delete optionWithoutCount.context;
  16038. optionWithoutCount.defaultValue = o.contextNotFound;
  16039. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  16040. translated = translate(contextKey, optionWithoutCount);
  16041. if (translated != o.contextNotFound) {
  16042. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  16043. } // else continue translation with original/nonContext key
  16044. }
  16045. if (needsPlural(options, lngs[0])) {
  16046. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  16047. delete optionWithoutCount.count;
  16048. delete optionWithoutCount.lng;
  16049. optionWithoutCount.defaultValue = o.pluralNotFound;
  16050. var pluralKey;
  16051. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  16052. pluralKey = ns + o.nsseparator + key;
  16053. } else {
  16054. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  16055. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  16056. if (pluralExtension >= 0) {
  16057. pluralKey = pluralKey + '_' + pluralExtension;
  16058. } else if (pluralExtension === 1) {
  16059. pluralKey = ns + o.nsseparator + key; // singular
  16060. }
  16061. }
  16062. translated = translate(pluralKey, optionWithoutCount);
  16063. if (translated != o.pluralNotFound) {
  16064. return applyReplacement(translated, {
  16065. count: options.count,
  16066. interpolationPrefix: options.interpolationPrefix,
  16067. interpolationSuffix: options.interpolationSuffix
  16068. }); // apply replacement for count only
  16069. } else if (lngs.length > 1) {
  16070. // remove failed lng
  16071. var clone = lngs.slice();
  16072. clone.shift();
  16073. options = f.extend(options, { lngs: clone });
  16074. delete options.lng;
  16075. // retry with fallbacks
  16076. translated = translate(ns + o.nsseparator + key, options);
  16077. if (translated != o.pluralNotFound) return translated;
  16078. } else {
  16079. return translated;
  16080. }
  16081. }
  16082. if (needsIndefiniteArticle(options)) {
  16083. var optionsWithoutIndef = f.extend({}, options);
  16084. delete optionsWithoutIndef.indefinite_article;
  16085. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  16086. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  16087. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  16088. translated = translate(indefiniteKey, optionsWithoutIndef);
  16089. if (translated != o.indefiniteNotFound) {
  16090. return translated;
  16091. }
  16092. }
  16093. var found;
  16094. var keys = key.split(o.keyseparator);
  16095. for (var i = 0, len = lngs.length; i < len; i++ ) {
  16096. if (found !== undefined) break;
  16097. var l = lngs[i];
  16098. var x = 0;
  16099. var value = resStore[l] && resStore[l][ns];
  16100. while (keys[x]) {
  16101. value = value && value[keys[x]];
  16102. x++;
  16103. }
  16104. if (value !== undefined) {
  16105. var valueType = Object.prototype.toString.apply(value);
  16106. if (typeof value === 'string') {
  16107. value = applyReplacement(value, options);
  16108. value = applyReuse(value, options);
  16109. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  16110. value = value.join('\n');
  16111. value = applyReplacement(value, options);
  16112. value = applyReuse(value, options);
  16113. } else if (value === null && o.fallbackOnNull === true) {
  16114. value = undefined;
  16115. } else if (value !== null) {
  16116. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  16117. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  16118. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  16119. } else {
  16120. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  16121. 'returned an object instead of string.';
  16122. f.log(value);
  16123. }
  16124. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  16125. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  16126. f.each(value, function(m) {
  16127. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  16128. });
  16129. value = copy;
  16130. }
  16131. }
  16132. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  16133. value = undefined;
  16134. found = value;
  16135. }
  16136. }
  16137. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  16138. // set flag for fallback lookup - avoid recursion
  16139. options.isFallbackLookup = true;
  16140. if (o.fallbackNS.length) {
  16141. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  16142. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  16143. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  16144. /* compare value without namespace */
  16145. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  16146. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  16147. if (foundValue !== notFoundValue) break;
  16148. }
  16149. }
  16150. } else {
  16151. found = _find(key, options); // fallback to default NS
  16152. }
  16153. options.isFallbackLookup = false;
  16154. }
  16155. return found;
  16156. }
  16157. function detectLanguage() {
  16158. var detectedLng;
  16159. var whitelist = o.lngWhitelist || [];
  16160. var userLngChoices = [];
  16161. // get from qs
  16162. var qsParm = [];
  16163. if (typeof window !== 'undefined') {
  16164. (function() {
  16165. var query = window.location.search.substring(1);
  16166. var params = query.split('&');
  16167. for (var i=0; i<params.length; i++) {
  16168. var pos = params[i].indexOf('=');
  16169. if (pos > 0) {
  16170. var key = params[i].substring(0,pos);
  16171. if (key == o.detectLngQS) {
  16172. userLngChoices.push(params[i].substring(pos+1));
  16173. }
  16174. }
  16175. }
  16176. })();
  16177. }
  16178. // get from cookie
  16179. if (o.useCookie && typeof document !== 'undefined') {
  16180. var c = f.cookie.read(o.cookieName);
  16181. if (c) userLngChoices.push(c);
  16182. }
  16183. // get from localStorage
  16184. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  16185. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  16186. }
  16187. // get from navigator
  16188. if (typeof navigator !== 'undefined') {
  16189. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  16190. for (var i=0;i<navigator.languages.length;i++) {
  16191. userLngChoices.push(navigator.languages[i]);
  16192. }
  16193. }
  16194. if (navigator.userLanguage) {
  16195. userLngChoices.push(navigator.userLanguage);
  16196. }
  16197. if (navigator.language) {
  16198. userLngChoices.push(navigator.language);
  16199. }
  16200. }
  16201. (function() {
  16202. for (var i=0;i<userLngChoices.length;i++) {
  16203. var lng = userLngChoices[i];
  16204. if (lng.indexOf('-') > -1) {
  16205. var parts = lng.split('-');
  16206. lng = o.lowerCaseLng ?
  16207. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  16208. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  16209. }
  16210. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  16211. detectedLng = lng;
  16212. break;
  16213. }
  16214. }
  16215. })();
  16216. //fallback
  16217. if (!detectedLng){
  16218. detectedLng = o.fallbackLng[0];
  16219. }
  16220. return detectedLng;
  16221. }
  16222. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  16223. /* [code, name, numbers, pluralsType] */
  16224. var _rules = [
  16225. ["ach", "Acholi", [1,2], 1],
  16226. ["af", "Afrikaans",[1,2], 2],
  16227. ["ak", "Akan", [1,2], 1],
  16228. ["am", "Amharic", [1,2], 1],
  16229. ["an", "Aragonese",[1,2], 2],
  16230. ["ar", "Arabic", [0,1,2,3,11,100],5],
  16231. ["arn", "Mapudungun",[1,2], 1],
  16232. ["ast", "Asturian", [1,2], 2],
  16233. ["ay", "Aymará", [1], 3],
  16234. ["az", "Azerbaijani",[1,2],2],
  16235. ["be", "Belarusian",[1,2,5],4],
  16236. ["bg", "Bulgarian",[1,2], 2],
  16237. ["bn", "Bengali", [1,2], 2],
  16238. ["bo", "Tibetan", [1], 3],
  16239. ["br", "Breton", [1,2], 1],
  16240. ["bs", "Bosnian", [1,2,5],4],
  16241. ["ca", "Catalan", [1,2], 2],
  16242. ["cgg", "Chiga", [1], 3],
  16243. ["cs", "Czech", [1,2,5],6],
  16244. ["csb", "Kashubian",[1,2,5],7],
  16245. ["cy", "Welsh", [1,2,3,8],8],
  16246. ["da", "Danish", [1,2], 2],
  16247. ["de", "German", [1,2], 2],
  16248. ["dev", "Development Fallback", [1,2], 2],
  16249. ["dz", "Dzongkha", [1], 3],
  16250. ["el", "Greek", [1,2], 2],
  16251. ["en", "English", [1,2], 2],
  16252. ["eo", "Esperanto",[1,2], 2],
  16253. ["es", "Spanish", [1,2], 2],
  16254. ["es_ar","Argentinean Spanish", [1,2], 2],
  16255. ["et", "Estonian", [1,2], 2],
  16256. ["eu", "Basque", [1,2], 2],
  16257. ["fa", "Persian", [1], 3],
  16258. ["fi", "Finnish", [1,2], 2],
  16259. ["fil", "Filipino", [1,2], 1],
  16260. ["fo", "Faroese", [1,2], 2],
  16261. ["fr", "French", [1,2], 9],
  16262. ["fur", "Friulian", [1,2], 2],
  16263. ["fy", "Frisian", [1,2], 2],
  16264. ["ga", "Irish", [1,2,3,7,11],10],
  16265. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  16266. ["gl", "Galician", [1,2], 2],
  16267. ["gu", "Gujarati", [1,2], 2],
  16268. ["gun", "Gun", [1,2], 1],
  16269. ["ha", "Hausa", [1,2], 2],
  16270. ["he", "Hebrew", [1,2], 2],
  16271. ["hi", "Hindi", [1,2], 2],
  16272. ["hr", "Croatian", [1,2,5],4],
  16273. ["hu", "Hungarian",[1,2], 2],
  16274. ["hy", "Armenian", [1,2], 2],
  16275. ["ia", "Interlingua",[1,2],2],
  16276. ["id", "Indonesian",[1], 3],
  16277. ["is", "Icelandic",[1,2], 12],
  16278. ["it", "Italian", [1,2], 2],
  16279. ["ja", "Japanese", [1], 3],
  16280. ["jbo", "Lojban", [1], 3],
  16281. ["jv", "Javanese", [0,1], 13],
  16282. ["ka", "Georgian", [1], 3],
  16283. ["kk", "Kazakh", [1], 3],
  16284. ["km", "Khmer", [1], 3],
  16285. ["kn", "Kannada", [1,2], 2],
  16286. ["ko", "Korean", [1], 3],
  16287. ["ku", "Kurdish", [1,2], 2],
  16288. ["kw", "Cornish", [1,2,3,4],14],
  16289. ["ky", "Kyrgyz", [1], 3],
  16290. ["lb", "Letzeburgesch",[1,2],2],
  16291. ["ln", "Lingala", [1,2], 1],
  16292. ["lo", "Lao", [1], 3],
  16293. ["lt", "Lithuanian",[1,2,10],15],
  16294. ["lv", "Latvian", [1,2,0],16],
  16295. ["mai", "Maithili", [1,2], 2],
  16296. ["mfe", "Mauritian Creole",[1,2],1],
  16297. ["mg", "Malagasy", [1,2], 1],
  16298. ["mi", "Maori", [1,2], 1],
  16299. ["mk", "Macedonian",[1,2],17],
  16300. ["ml", "Malayalam",[1,2], 2],
  16301. ["mn", "Mongolian",[1,2], 2],
  16302. ["mnk", "Mandinka", [0,1,2],18],
  16303. ["mr", "Marathi", [1,2], 2],
  16304. ["ms", "Malay", [1], 3],
  16305. ["mt", "Maltese", [1,2,11,20],19],
  16306. ["nah", "Nahuatl", [1,2], 2],
  16307. ["nap", "Neapolitan",[1,2], 2],
  16308. ["nb", "Norwegian Bokmal",[1,2],2],
  16309. ["ne", "Nepali", [1,2], 2],
  16310. ["nl", "Dutch", [1,2], 2],
  16311. ["nn", "Norwegian Nynorsk",[1,2],2],
  16312. ["no", "Norwegian",[1,2], 2],
  16313. ["nso", "Northern Sotho",[1,2],2],
  16314. ["oc", "Occitan", [1,2], 1],
  16315. ["or", "Oriya", [2,1], 2],
  16316. ["pa", "Punjabi", [1,2], 2],
  16317. ["pap", "Papiamento",[1,2], 2],
  16318. ["pl", "Polish", [1,2,5],7],
  16319. ["pms", "Piemontese",[1,2], 2],
  16320. ["ps", "Pashto", [1,2], 2],
  16321. ["pt", "Portuguese",[1,2], 2],
  16322. ["pt_br","Brazilian Portuguese",[1,2], 2],
  16323. ["rm", "Romansh", [1,2], 2],
  16324. ["ro", "Romanian", [1,2,20],20],
  16325. ["ru", "Russian", [1,2,5],4],
  16326. ["sah", "Yakut", [1], 3],
  16327. ["sco", "Scots", [1,2], 2],
  16328. ["se", "Northern Sami",[1,2], 2],
  16329. ["si", "Sinhala", [1,2], 2],
  16330. ["sk", "Slovak", [1,2,5],6],
  16331. ["sl", "Slovenian",[5,1,2,3],21],
  16332. ["so", "Somali", [1,2], 2],
  16333. ["son", "Songhay", [1,2], 2],
  16334. ["sq", "Albanian", [1,2], 2],
  16335. ["sr", "Serbian", [1,2,5],4],
  16336. ["su", "Sundanese",[1], 3],
  16337. ["sv", "Swedish", [1,2], 2],
  16338. ["sw", "Swahili", [1,2], 2],
  16339. ["ta", "Tamil", [1,2], 2],
  16340. ["te", "Telugu", [1,2], 2],
  16341. ["tg", "Tajik", [1,2], 1],
  16342. ["th", "Thai", [1], 3],
  16343. ["ti", "Tigrinya", [1,2], 1],
  16344. ["tk", "Turkmen", [1,2], 2],
  16345. ["tr", "Turkish", [1,2], 1],
  16346. ["tt", "Tatar", [1], 3],
  16347. ["ug", "Uyghur", [1], 3],
  16348. ["uk", "Ukrainian",[1,2,5],4],
  16349. ["ur", "Urdu", [1,2], 2],
  16350. ["uz", "Uzbek", [1,2], 1],
  16351. ["vi", "Vietnamese",[1], 3],
  16352. ["wa", "Walloon", [1,2], 1],
  16353. ["wo", "Wolof", [1], 3],
  16354. ["yo", "Yoruba", [1,2], 2],
  16355. ["zh", "Chinese", [1], 3]
  16356. ];
  16357. var _rulesPluralsTypes = {
  16358. 1: function(n) {return Number(n > 1);},
  16359. 2: function(n) {return Number(n != 1);},
  16360. 3: function(n) {return 0;},
  16361. 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);},
  16362. 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);},
  16363. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  16364. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16365. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  16366. 9: function(n) {return Number(n >= 2);},
  16367. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  16368. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  16369. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  16370. 13: function(n) {return Number(n !== 0);},
  16371. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  16372. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16373. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  16374. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  16375. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  16376. 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);},
  16377. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  16378. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  16379. };
  16380. var pluralExtensions = {
  16381. rules: (function () {
  16382. var l, rules = {};
  16383. for (l=_rules.length; l-- ;) {
  16384. rules[_rules[l][0]] = {
  16385. name: _rules[l][1],
  16386. numbers: _rules[l][2],
  16387. plurals: _rulesPluralsTypes[_rules[l][3]]
  16388. }
  16389. }
  16390. return rules;
  16391. }()),
  16392. // you can add your own pluralExtensions
  16393. addRule: function(lng, obj) {
  16394. pluralExtensions.rules[lng] = obj;
  16395. },
  16396. setCurrentLng: function(lng) {
  16397. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  16398. var parts = lng.split('-');
  16399. pluralExtensions.currentRule = {
  16400. lng: lng,
  16401. rule: pluralExtensions.rules[parts[0]]
  16402. };
  16403. }
  16404. },
  16405. needsPlural: function(lng, count) {
  16406. var parts = lng.split('-');
  16407. var ext;
  16408. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16409. ext = pluralExtensions.currentRule.rule;
  16410. } else {
  16411. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  16412. }
  16413. if (ext && ext.numbers.length <= 1) {
  16414. return false;
  16415. } else {
  16416. return this.get(lng, count) !== 1;
  16417. }
  16418. },
  16419. get: function(lng, count) {
  16420. var parts = lng.split('-');
  16421. function getResult(l, c) {
  16422. var ext;
  16423. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16424. ext = pluralExtensions.currentRule.rule;
  16425. } else {
  16426. ext = pluralExtensions.rules[l];
  16427. }
  16428. if (ext) {
  16429. var i;
  16430. if (ext.noAbs) {
  16431. i = ext.plurals(c);
  16432. } else {
  16433. i = ext.plurals(Math.abs(c));
  16434. }
  16435. var number = ext.numbers[i];
  16436. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  16437. if (number === 2) {
  16438. number = -1; // regular plural
  16439. } else if (number === 1) {
  16440. number = 1; // singular
  16441. }
  16442. }//console.log(count + '-' + number);
  16443. return number;
  16444. } else {
  16445. return c === 1 ? '1' : '-1';
  16446. }
  16447. }
  16448. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  16449. }
  16450. };
  16451. var postProcessors = {};
  16452. var addPostProcessor = function(name, fc) {
  16453. postProcessors[name] = fc;
  16454. };
  16455. // sprintf support
  16456. var sprintf = (function() {
  16457. function get_type(variable) {
  16458. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  16459. }
  16460. function str_repeat(input, multiplier) {
  16461. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  16462. return output.join('');
  16463. }
  16464. var str_format = function() {
  16465. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  16466. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  16467. }
  16468. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  16469. };
  16470. str_format.format = function(parse_tree, argv) {
  16471. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  16472. for (i = 0; i < tree_length; i++) {
  16473. node_type = get_type(parse_tree[i]);
  16474. if (node_type === 'string') {
  16475. output.push(parse_tree[i]);
  16476. }
  16477. else if (node_type === 'array') {
  16478. match = parse_tree[i]; // convenience purposes only
  16479. if (match[2]) { // keyword argument
  16480. arg = argv[cursor];
  16481. for (k = 0; k < match[2].length; k++) {
  16482. if (!arg.hasOwnProperty(match[2][k])) {
  16483. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  16484. }
  16485. arg = arg[match[2][k]];
  16486. }
  16487. }
  16488. else if (match[1]) { // positional argument (explicit)
  16489. arg = argv[match[1]];
  16490. }
  16491. else { // positional argument (implicit)
  16492. arg = argv[cursor++];
  16493. }
  16494. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  16495. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  16496. }
  16497. switch (match[8]) {
  16498. case 'b': arg = arg.toString(2); break;
  16499. case 'c': arg = String.fromCharCode(arg); break;
  16500. case 'd': arg = parseInt(arg, 10); break;
  16501. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  16502. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  16503. case 'o': arg = arg.toString(8); break;
  16504. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  16505. case 'u': arg = Math.abs(arg); break;
  16506. case 'x': arg = arg.toString(16); break;
  16507. case 'X': arg = arg.toString(16).toUpperCase(); break;
  16508. }
  16509. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  16510. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  16511. pad_length = match[6] - String(arg).length;
  16512. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  16513. output.push(match[5] ? arg + pad : pad + arg);
  16514. }
  16515. }
  16516. return output.join('');
  16517. };
  16518. str_format.cache = {};
  16519. str_format.parse = function(fmt) {
  16520. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  16521. while (_fmt) {
  16522. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  16523. parse_tree.push(match[0]);
  16524. }
  16525. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  16526. parse_tree.push('%');
  16527. }
  16528. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  16529. if (match[2]) {
  16530. arg_names |= 1;
  16531. var field_list = [], replacement_field = match[2], field_match = [];
  16532. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16533. field_list.push(field_match[1]);
  16534. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  16535. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16536. field_list.push(field_match[1]);
  16537. }
  16538. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  16539. field_list.push(field_match[1]);
  16540. }
  16541. else {
  16542. throw('[sprintf] huh?');
  16543. }
  16544. }
  16545. }
  16546. else {
  16547. throw('[sprintf] huh?');
  16548. }
  16549. match[2] = field_list;
  16550. }
  16551. else {
  16552. arg_names |= 2;
  16553. }
  16554. if (arg_names === 3) {
  16555. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  16556. }
  16557. parse_tree.push(match);
  16558. }
  16559. else {
  16560. throw('[sprintf] huh?');
  16561. }
  16562. _fmt = _fmt.substring(match[0].length);
  16563. }
  16564. return parse_tree;
  16565. };
  16566. return str_format;
  16567. })();
  16568. var vsprintf = function(fmt, argv) {
  16569. argv.unshift(fmt);
  16570. return sprintf.apply(null, argv);
  16571. };
  16572. addPostProcessor("sprintf", function(val, key, opts) {
  16573. if (!opts.sprintf) return val;
  16574. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  16575. return vsprintf(val, opts.sprintf);
  16576. } else if (typeof opts.sprintf === 'object') {
  16577. return sprintf(val, opts.sprintf);
  16578. }
  16579. return val;
  16580. });
  16581. // public api interface
  16582. i18n.init = init;
  16583. i18n.setLng = setLng;
  16584. i18n.preload = preload;
  16585. i18n.addResourceBundle = addResourceBundle;
  16586. i18n.hasResourceBundle = hasResourceBundle;
  16587. i18n.addResource = addResource;
  16588. i18n.addResources = addResources;
  16589. i18n.removeResourceBundle = removeResourceBundle;
  16590. i18n.loadNamespace = loadNamespace;
  16591. i18n.loadNamespaces = loadNamespaces;
  16592. i18n.setDefaultNamespace = setDefaultNamespace;
  16593. i18n.t = translate;
  16594. i18n.translate = translate;
  16595. i18n.exists = exists;
  16596. i18n.detectLanguage = f.detectLanguage;
  16597. i18n.pluralExtensions = pluralExtensions;
  16598. i18n.sync = sync;
  16599. i18n.functions = f;
  16600. i18n.lng = lng;
  16601. i18n.addPostProcessor = addPostProcessor;
  16602. i18n.options = o;
  16603. })();
  16604. },{"jquery":"jquery"}],62:[function(require,module,exports){
  16605. // Top level file is just a mixin of submodules & constants
  16606. 'use strict';
  16607. var assign = require('./lib/utils/common').assign;
  16608. var deflate = require('./lib/deflate');
  16609. var inflate = require('./lib/inflate');
  16610. var constants = require('./lib/zlib/constants');
  16611. var pako = {};
  16612. assign(pako, deflate, inflate, constants);
  16613. module.exports = pako;
  16614. },{"./lib/deflate":63,"./lib/inflate":64,"./lib/utils/common":65,"./lib/zlib/constants":68}],63:[function(require,module,exports){
  16615. 'use strict';
  16616. var zlib_deflate = require('./zlib/deflate.js');
  16617. var utils = require('./utils/common');
  16618. var strings = require('./utils/strings');
  16619. var msg = require('./zlib/messages');
  16620. var zstream = require('./zlib/zstream');
  16621. /* Public constants ==========================================================*/
  16622. /* ===========================================================================*/
  16623. var Z_NO_FLUSH = 0;
  16624. var Z_FINISH = 4;
  16625. var Z_OK = 0;
  16626. var Z_STREAM_END = 1;
  16627. var Z_DEFAULT_COMPRESSION = -1;
  16628. var Z_DEFAULT_STRATEGY = 0;
  16629. var Z_DEFLATED = 8;
  16630. /* ===========================================================================*/
  16631. /**
  16632. * class Deflate
  16633. *
  16634. * Generic JS-style wrapper for zlib calls. If you don't need
  16635. * streaming behaviour - use more simple functions: [[deflate]],
  16636. * [[deflateRaw]] and [[gzip]].
  16637. **/
  16638. /* internal
  16639. * Deflate.chunks -> Array
  16640. *
  16641. * Chunks of output data, if [[Deflate#onData]] not overriden.
  16642. **/
  16643. /**
  16644. * Deflate.result -> Uint8Array|Array
  16645. *
  16646. * Compressed result, generated by default [[Deflate#onData]]
  16647. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  16648. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  16649. **/
  16650. /**
  16651. * Deflate.err -> Number
  16652. *
  16653. * Error code after deflate finished. 0 (Z_OK) on success.
  16654. * You will not need it in real life, because deflate errors
  16655. * are possible only on wrong options or bad `onData` / `onEnd`
  16656. * custom handlers.
  16657. **/
  16658. /**
  16659. * Deflate.msg -> String
  16660. *
  16661. * Error message, if [[Deflate.err]] != 0
  16662. **/
  16663. /**
  16664. * new Deflate(options)
  16665. * - options (Object): zlib deflate options.
  16666. *
  16667. * Creates new deflator instance with specified params. Throws exception
  16668. * on bad params. Supported options:
  16669. *
  16670. * - `level`
  16671. * - `windowBits`
  16672. * - `memLevel`
  16673. * - `strategy`
  16674. *
  16675. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  16676. * for more information on these.
  16677. *
  16678. * Additional options, for internal needs:
  16679. *
  16680. * - `chunkSize` - size of generated data chunks (16K by default)
  16681. * - `raw` (Boolean) - do raw deflate
  16682. * - `gzip` (Boolean) - create gzip wrapper
  16683. * - `to` (String) - if equal to 'string', then result will be "binary string"
  16684. * (each char code [0..255])
  16685. * - `header` (Object) - custom header for gzip
  16686. * - `text` (Boolean) - true if compressed data believed to be text
  16687. * - `time` (Number) - modification time, unix timestamp
  16688. * - `os` (Number) - operation system code
  16689. * - `extra` (Array) - array of bytes with extra data (max 65536)
  16690. * - `name` (String) - file name (binary string)
  16691. * - `comment` (String) - comment (binary string)
  16692. * - `hcrc` (Boolean) - true if header crc should be added
  16693. *
  16694. * ##### Example:
  16695. *
  16696. * ```javascript
  16697. * var pako = require('pako')
  16698. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  16699. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  16700. *
  16701. * var deflate = new pako.Deflate({ level: 3});
  16702. *
  16703. * deflate.push(chunk1, false);
  16704. * deflate.push(chunk2, true); // true -> last chunk
  16705. *
  16706. * if (deflate.err) { throw new Error(deflate.err); }
  16707. *
  16708. * console.log(deflate.result);
  16709. * ```
  16710. **/
  16711. var Deflate = function(options) {
  16712. this.options = utils.assign({
  16713. level: Z_DEFAULT_COMPRESSION,
  16714. method: Z_DEFLATED,
  16715. chunkSize: 16384,
  16716. windowBits: 15,
  16717. memLevel: 8,
  16718. strategy: Z_DEFAULT_STRATEGY,
  16719. to: ''
  16720. }, options || {});
  16721. var opt = this.options;
  16722. if (opt.raw && (opt.windowBits > 0)) {
  16723. opt.windowBits = -opt.windowBits;
  16724. }
  16725. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  16726. opt.windowBits += 16;
  16727. }
  16728. this.err = 0; // error code, if happens (0 = Z_OK)
  16729. this.msg = ''; // error message
  16730. this.ended = false; // used to avoid multiple onEnd() calls
  16731. this.chunks = []; // chunks of compressed data
  16732. this.strm = new zstream();
  16733. this.strm.avail_out = 0;
  16734. var status = zlib_deflate.deflateInit2(
  16735. this.strm,
  16736. opt.level,
  16737. opt.method,
  16738. opt.windowBits,
  16739. opt.memLevel,
  16740. opt.strategy
  16741. );
  16742. if (status !== Z_OK) {
  16743. throw new Error(msg[status]);
  16744. }
  16745. if (opt.header) {
  16746. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  16747. }
  16748. };
  16749. /**
  16750. * Deflate#push(data[, mode]) -> Boolean
  16751. * - data (Uint8Array|Array|String): input data. Strings will be converted to
  16752. * utf8 byte sequence.
  16753. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  16754. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  16755. *
  16756. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  16757. * new compressed chunks. Returns `true` on success. The last data block must have
  16758. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  16759. * [[Deflate#onEnd]].
  16760. *
  16761. * On fail call [[Deflate#onEnd]] with error code and return false.
  16762. *
  16763. * We strongly recommend to use `Uint8Array` on input for best speed (output
  16764. * array format is detected automatically). Also, don't skip last param and always
  16765. * use the same type in your code (boolean or number). That will improve JS speed.
  16766. *
  16767. * For regular `Array`-s make sure all elements are [0..255].
  16768. *
  16769. * ##### Example
  16770. *
  16771. * ```javascript
  16772. * push(chunk, false); // push one of data chunks
  16773. * ...
  16774. * push(chunk, true); // push last chunk
  16775. * ```
  16776. **/
  16777. Deflate.prototype.push = function(data, mode) {
  16778. var strm = this.strm;
  16779. var chunkSize = this.options.chunkSize;
  16780. var status, _mode;
  16781. if (this.ended) { return false; }
  16782. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  16783. // Convert data if needed
  16784. if (typeof data === 'string') {
  16785. // If we need to compress text, change encoding to utf8.
  16786. strm.input = strings.string2buf(data);
  16787. } else {
  16788. strm.input = data;
  16789. }
  16790. strm.next_in = 0;
  16791. strm.avail_in = strm.input.length;
  16792. do {
  16793. if (strm.avail_out === 0) {
  16794. strm.output = new utils.Buf8(chunkSize);
  16795. strm.next_out = 0;
  16796. strm.avail_out = chunkSize;
  16797. }
  16798. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  16799. if (status !== Z_STREAM_END && status !== Z_OK) {
  16800. this.onEnd(status);
  16801. this.ended = true;
  16802. return false;
  16803. }
  16804. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  16805. if (this.options.to === 'string') {
  16806. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  16807. } else {
  16808. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  16809. }
  16810. }
  16811. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  16812. // Finalize on the last chunk.
  16813. if (_mode === Z_FINISH) {
  16814. status = zlib_deflate.deflateEnd(this.strm);
  16815. this.onEnd(status);
  16816. this.ended = true;
  16817. return status === Z_OK;
  16818. }
  16819. return true;
  16820. };
  16821. /**
  16822. * Deflate#onData(chunk) -> Void
  16823. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  16824. * on js engine support. When string output requested, each chunk
  16825. * will be string.
  16826. *
  16827. * By default, stores data blocks in `chunks[]` property and glue
  16828. * those in `onEnd`. Override this handler, if you need another behaviour.
  16829. **/
  16830. Deflate.prototype.onData = function(chunk) {
  16831. this.chunks.push(chunk);
  16832. };
  16833. /**
  16834. * Deflate#onEnd(status) -> Void
  16835. * - status (Number): deflate status. 0 (Z_OK) on success,
  16836. * other if not.
  16837. *
  16838. * Called once after you tell deflate that input stream complete
  16839. * or error happenned. By default - join collected chunks,
  16840. * free memory and fill `results` / `err` properties.
  16841. **/
  16842. Deflate.prototype.onEnd = function(status) {
  16843. // On success - join
  16844. if (status === Z_OK) {
  16845. if (this.options.to === 'string') {
  16846. this.result = this.chunks.join('');
  16847. } else {
  16848. this.result = utils.flattenChunks(this.chunks);
  16849. }
  16850. }
  16851. this.chunks = [];
  16852. this.err = status;
  16853. this.msg = this.strm.msg;
  16854. };
  16855. /**
  16856. * deflate(data[, options]) -> Uint8Array|Array|String
  16857. * - data (Uint8Array|Array|String): input data to compress.
  16858. * - options (Object): zlib deflate options.
  16859. *
  16860. * Compress `data` with deflate alrorythm and `options`.
  16861. *
  16862. * Supported options are:
  16863. *
  16864. * - level
  16865. * - windowBits
  16866. * - memLevel
  16867. * - strategy
  16868. *
  16869. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  16870. * for more information on these.
  16871. *
  16872. * Sugar (options):
  16873. *
  16874. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  16875. * negative windowBits implicitly.
  16876. * - `to` (String) - if equal to 'string', then result will be "binary string"
  16877. * (each char code [0..255])
  16878. *
  16879. * ##### Example:
  16880. *
  16881. * ```javascript
  16882. * var pako = require('pako')
  16883. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  16884. *
  16885. * console.log(pako.deflate(data));
  16886. * ```
  16887. **/
  16888. function deflate(input, options) {
  16889. var deflator = new Deflate(options);
  16890. deflator.push(input, true);
  16891. // That will never happens, if you don't cheat with options :)
  16892. if (deflator.err) { throw deflator.msg; }
  16893. return deflator.result;
  16894. }
  16895. /**
  16896. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  16897. * - data (Uint8Array|Array|String): input data to compress.
  16898. * - options (Object): zlib deflate options.
  16899. *
  16900. * The same as [[deflate]], but creates raw data, without wrapper
  16901. * (header and adler32 crc).
  16902. **/
  16903. function deflateRaw(input, options) {
  16904. options = options || {};
  16905. options.raw = true;
  16906. return deflate(input, options);
  16907. }
  16908. /**
  16909. * gzip(data[, options]) -> Uint8Array|Array|String
  16910. * - data (Uint8Array|Array|String): input data to compress.
  16911. * - options (Object): zlib deflate options.
  16912. *
  16913. * The same as [[deflate]], but create gzip wrapper instead of
  16914. * deflate one.
  16915. **/
  16916. function gzip(input, options) {
  16917. options = options || {};
  16918. options.gzip = true;
  16919. return deflate(input, options);
  16920. }
  16921. exports.Deflate = Deflate;
  16922. exports.deflate = deflate;
  16923. exports.deflateRaw = deflateRaw;
  16924. exports.gzip = gzip;
  16925. },{"./utils/common":65,"./utils/strings":66,"./zlib/deflate.js":70,"./zlib/messages":75,"./zlib/zstream":77}],64:[function(require,module,exports){
  16926. 'use strict';
  16927. var zlib_inflate = require('./zlib/inflate.js');
  16928. var utils = require('./utils/common');
  16929. var strings = require('./utils/strings');
  16930. var c = require('./zlib/constants');
  16931. var msg = require('./zlib/messages');
  16932. var zstream = require('./zlib/zstream');
  16933. var gzheader = require('./zlib/gzheader');
  16934. /**
  16935. * class Inflate
  16936. *
  16937. * Generic JS-style wrapper for zlib calls. If you don't need
  16938. * streaming behaviour - use more simple functions: [[inflate]]
  16939. * and [[inflateRaw]].
  16940. **/
  16941. /* internal
  16942. * inflate.chunks -> Array
  16943. *
  16944. * Chunks of output data, if [[Inflate#onData]] not overriden.
  16945. **/
  16946. /**
  16947. * Inflate.result -> Uint8Array|Array|String
  16948. *
  16949. * Uncompressed result, generated by default [[Inflate#onData]]
  16950. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  16951. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  16952. **/
  16953. /**
  16954. * Inflate.err -> Number
  16955. *
  16956. * Error code after inflate finished. 0 (Z_OK) on success.
  16957. * Should be checked if broken data possible.
  16958. **/
  16959. /**
  16960. * Inflate.msg -> String
  16961. *
  16962. * Error message, if [[Inflate.err]] != 0
  16963. **/
  16964. /**
  16965. * new Inflate(options)
  16966. * - options (Object): zlib inflate options.
  16967. *
  16968. * Creates new inflator instance with specified params. Throws exception
  16969. * on bad params. Supported options:
  16970. *
  16971. * - `windowBits`
  16972. *
  16973. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  16974. * for more information on these.
  16975. *
  16976. * Additional options, for internal needs:
  16977. *
  16978. * - `chunkSize` - size of generated data chunks (16K by default)
  16979. * - `raw` (Boolean) - do raw inflate
  16980. * - `to` (String) - if equal to 'string', then result will be converted
  16981. * from utf8 to utf16 (javascript) string. When string output requested,
  16982. * chunk length can differ from `chunkSize`, depending on content.
  16983. *
  16984. * By default, when no options set, autodetect deflate/gzip data format via
  16985. * wrapper header.
  16986. *
  16987. * ##### Example:
  16988. *
  16989. * ```javascript
  16990. * var pako = require('pako')
  16991. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  16992. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  16993. *
  16994. * var inflate = new pako.Inflate({ level: 3});
  16995. *
  16996. * inflate.push(chunk1, false);
  16997. * inflate.push(chunk2, true); // true -> last chunk
  16998. *
  16999. * if (inflate.err) { throw new Error(inflate.err); }
  17000. *
  17001. * console.log(inflate.result);
  17002. * ```
  17003. **/
  17004. var Inflate = function(options) {
  17005. this.options = utils.assign({
  17006. chunkSize: 16384,
  17007. windowBits: 0,
  17008. to: ''
  17009. }, options || {});
  17010. var opt = this.options;
  17011. // Force window size for `raw` data, if not set directly,
  17012. // because we have no header for autodetect.
  17013. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  17014. opt.windowBits = -opt.windowBits;
  17015. if (opt.windowBits === 0) { opt.windowBits = -15; }
  17016. }
  17017. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  17018. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  17019. !(options && options.windowBits)) {
  17020. opt.windowBits += 32;
  17021. }
  17022. // Gzip header has no info about windows size, we can do autodetect only
  17023. // for deflate. So, if window size not set, force it to max when gzip possible
  17024. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  17025. // bit 3 (16) -> gzipped data
  17026. // bit 4 (32) -> autodetect gzip/deflate
  17027. if ((opt.windowBits & 15) === 0) {
  17028. opt.windowBits |= 15;
  17029. }
  17030. }
  17031. this.err = 0; // error code, if happens (0 = Z_OK)
  17032. this.msg = ''; // error message
  17033. this.ended = false; // used to avoid multiple onEnd() calls
  17034. this.chunks = []; // chunks of compressed data
  17035. this.strm = new zstream();
  17036. this.strm.avail_out = 0;
  17037. var status = zlib_inflate.inflateInit2(
  17038. this.strm,
  17039. opt.windowBits
  17040. );
  17041. if (status !== c.Z_OK) {
  17042. throw new Error(msg[status]);
  17043. }
  17044. this.header = new gzheader();
  17045. zlib_inflate.inflateGetHeader(this.strm, this.header);
  17046. };
  17047. /**
  17048. * Inflate#push(data[, mode]) -> Boolean
  17049. * - data (Uint8Array|Array|String): input data
  17050. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17051. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17052. *
  17053. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  17054. * new output chunks. Returns `true` on success. The last data block must have
  17055. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17056. * [[Inflate#onEnd]].
  17057. *
  17058. * On fail call [[Inflate#onEnd]] with error code and return false.
  17059. *
  17060. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17061. * format is detected automatically). Also, don't skip last param and always
  17062. * use the same type in your code (boolean or number). That will improve JS speed.
  17063. *
  17064. * For regular `Array`-s make sure all elements are [0..255].
  17065. *
  17066. * ##### Example
  17067. *
  17068. * ```javascript
  17069. * push(chunk, false); // push one of data chunks
  17070. * ...
  17071. * push(chunk, true); // push last chunk
  17072. * ```
  17073. **/
  17074. Inflate.prototype.push = function(data, mode) {
  17075. var strm = this.strm;
  17076. var chunkSize = this.options.chunkSize;
  17077. var status, _mode;
  17078. var next_out_utf8, tail, utf8str;
  17079. if (this.ended) { return false; }
  17080. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  17081. // Convert data if needed
  17082. if (typeof data === 'string') {
  17083. // Only binary strings can be decompressed on practice
  17084. strm.input = strings.binstring2buf(data);
  17085. } else {
  17086. strm.input = data;
  17087. }
  17088. strm.next_in = 0;
  17089. strm.avail_in = strm.input.length;
  17090. do {
  17091. if (strm.avail_out === 0) {
  17092. strm.output = new utils.Buf8(chunkSize);
  17093. strm.next_out = 0;
  17094. strm.avail_out = chunkSize;
  17095. }
  17096. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  17097. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  17098. this.onEnd(status);
  17099. this.ended = true;
  17100. return false;
  17101. }
  17102. if (strm.next_out) {
  17103. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  17104. if (this.options.to === 'string') {
  17105. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  17106. tail = strm.next_out - next_out_utf8;
  17107. utf8str = strings.buf2string(strm.output, next_out_utf8);
  17108. // move tail
  17109. strm.next_out = tail;
  17110. strm.avail_out = chunkSize - tail;
  17111. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  17112. this.onData(utf8str);
  17113. } else {
  17114. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17115. }
  17116. }
  17117. }
  17118. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  17119. if (status === c.Z_STREAM_END) {
  17120. _mode = c.Z_FINISH;
  17121. }
  17122. // Finalize on the last chunk.
  17123. if (_mode === c.Z_FINISH) {
  17124. status = zlib_inflate.inflateEnd(this.strm);
  17125. this.onEnd(status);
  17126. this.ended = true;
  17127. return status === c.Z_OK;
  17128. }
  17129. return true;
  17130. };
  17131. /**
  17132. * Inflate#onData(chunk) -> Void
  17133. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17134. * on js engine support. When string output requested, each chunk
  17135. * will be string.
  17136. *
  17137. * By default, stores data blocks in `chunks[]` property and glue
  17138. * those in `onEnd`. Override this handler, if you need another behaviour.
  17139. **/
  17140. Inflate.prototype.onData = function(chunk) {
  17141. this.chunks.push(chunk);
  17142. };
  17143. /**
  17144. * Inflate#onEnd(status) -> Void
  17145. * - status (Number): inflate status. 0 (Z_OK) on success,
  17146. * other if not.
  17147. *
  17148. * Called once after you tell inflate that input stream complete
  17149. * or error happenned. By default - join collected chunks,
  17150. * free memory and fill `results` / `err` properties.
  17151. **/
  17152. Inflate.prototype.onEnd = function(status) {
  17153. // On success - join
  17154. if (status === c.Z_OK) {
  17155. if (this.options.to === 'string') {
  17156. // Glue & convert here, until we teach pako to send
  17157. // utf8 alligned strings to onData
  17158. this.result = this.chunks.join('');
  17159. } else {
  17160. this.result = utils.flattenChunks(this.chunks);
  17161. }
  17162. }
  17163. this.chunks = [];
  17164. this.err = status;
  17165. this.msg = this.strm.msg;
  17166. };
  17167. /**
  17168. * inflate(data[, options]) -> Uint8Array|Array|String
  17169. * - data (Uint8Array|Array|String): input data to decompress.
  17170. * - options (Object): zlib inflate options.
  17171. *
  17172. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  17173. * format via wrapper header by default. That's why we don't provide
  17174. * separate `ungzip` method.
  17175. *
  17176. * Supported options are:
  17177. *
  17178. * - windowBits
  17179. *
  17180. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17181. * for more information.
  17182. *
  17183. * Sugar (options):
  17184. *
  17185. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17186. * negative windowBits implicitly.
  17187. * - `to` (String) - if equal to 'string', then result will be converted
  17188. * from utf8 to utf16 (javascript) string. When string output requested,
  17189. * chunk length can differ from `chunkSize`, depending on content.
  17190. *
  17191. *
  17192. * ##### Example:
  17193. *
  17194. * ```javascript
  17195. * var pako = require('pako')
  17196. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  17197. * , output;
  17198. *
  17199. * try {
  17200. * output = pako.inflate(input);
  17201. * } catch (err)
  17202. * console.log(err);
  17203. * }
  17204. * ```
  17205. **/
  17206. function inflate(input, options) {
  17207. var inflator = new Inflate(options);
  17208. inflator.push(input, true);
  17209. // That will never happens, if you don't cheat with options :)
  17210. if (inflator.err) { throw inflator.msg; }
  17211. return inflator.result;
  17212. }
  17213. /**
  17214. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  17215. * - data (Uint8Array|Array|String): input data to decompress.
  17216. * - options (Object): zlib inflate options.
  17217. *
  17218. * The same as [[inflate]], but creates raw data, without wrapper
  17219. * (header and adler32 crc).
  17220. **/
  17221. function inflateRaw(input, options) {
  17222. options = options || {};
  17223. options.raw = true;
  17224. return inflate(input, options);
  17225. }
  17226. /**
  17227. * ungzip(data[, options]) -> Uint8Array|Array|String
  17228. * - data (Uint8Array|Array|String): input data to decompress.
  17229. * - options (Object): zlib inflate options.
  17230. *
  17231. * Just shortcut to [[inflate]], because it autodetects format
  17232. * by header.content. Done for convenience.
  17233. **/
  17234. exports.Inflate = Inflate;
  17235. exports.inflate = inflate;
  17236. exports.inflateRaw = inflateRaw;
  17237. exports.ungzip = inflate;
  17238. },{"./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){
  17239. 'use strict';
  17240. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  17241. (typeof Uint16Array !== 'undefined') &&
  17242. (typeof Int32Array !== 'undefined');
  17243. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  17244. var sources = Array.prototype.slice.call(arguments, 1);
  17245. while (sources.length) {
  17246. var source = sources.shift();
  17247. if (!source) { continue; }
  17248. if (typeof(source) !== 'object') {
  17249. throw new TypeError(source + 'must be non-object');
  17250. }
  17251. for (var p in source) {
  17252. if (source.hasOwnProperty(p)) {
  17253. obj[p] = source[p];
  17254. }
  17255. }
  17256. }
  17257. return obj;
  17258. };
  17259. // reduce buffer size, avoiding mem copy
  17260. exports.shrinkBuf = function (buf, size) {
  17261. if (buf.length === size) { return buf; }
  17262. if (buf.subarray) { return buf.subarray(0, size); }
  17263. buf.length = size;
  17264. return buf;
  17265. };
  17266. var fnTyped = {
  17267. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17268. if (src.subarray && dest.subarray) {
  17269. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  17270. return;
  17271. }
  17272. // Fallback to ordinary array
  17273. for(var i=0; i<len; i++) {
  17274. dest[dest_offs + i] = src[src_offs + i];
  17275. }
  17276. },
  17277. // Join array of chunks to single array.
  17278. flattenChunks: function(chunks) {
  17279. var i, l, len, pos, chunk, result;
  17280. // calculate data length
  17281. len = 0;
  17282. for (i=0, l=chunks.length; i<l; i++) {
  17283. len += chunks[i].length;
  17284. }
  17285. // join chunks
  17286. result = new Uint8Array(len);
  17287. pos = 0;
  17288. for (i=0, l=chunks.length; i<l; i++) {
  17289. chunk = chunks[i];
  17290. result.set(chunk, pos);
  17291. pos += chunk.length;
  17292. }
  17293. return result;
  17294. }
  17295. };
  17296. var fnUntyped = {
  17297. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17298. for(var i=0; i<len; i++) {
  17299. dest[dest_offs + i] = src[src_offs + i];
  17300. }
  17301. },
  17302. // Join array of chunks to single array.
  17303. flattenChunks: function(chunks) {
  17304. return [].concat.apply([], chunks);
  17305. }
  17306. };
  17307. // Enable/Disable typed arrays use, for testing
  17308. //
  17309. exports.setTyped = function (on) {
  17310. if (on) {
  17311. exports.Buf8 = Uint8Array;
  17312. exports.Buf16 = Uint16Array;
  17313. exports.Buf32 = Int32Array;
  17314. exports.assign(exports, fnTyped);
  17315. } else {
  17316. exports.Buf8 = Array;
  17317. exports.Buf16 = Array;
  17318. exports.Buf32 = Array;
  17319. exports.assign(exports, fnUntyped);
  17320. }
  17321. };
  17322. exports.setTyped(TYPED_OK);
  17323. },{}],66:[function(require,module,exports){
  17324. // String encode/decode helpers
  17325. 'use strict';
  17326. var utils = require('./common');
  17327. // Quick check if we can use fast array to bin string conversion
  17328. //
  17329. // - apply(Array) can fail on Android 2.2
  17330. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  17331. //
  17332. var STR_APPLY_OK = true;
  17333. var STR_APPLY_UIA_OK = true;
  17334. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  17335. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  17336. // Table with utf8 lengths (calculated by first byte of sequence)
  17337. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  17338. // because max possible codepoint is 0x10ffff
  17339. var _utf8len = new utils.Buf8(256);
  17340. for (var i=0; i<256; i++) {
  17341. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  17342. }
  17343. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  17344. // convert string to array (typed, when possible)
  17345. exports.string2buf = function (str) {
  17346. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  17347. // count binary size
  17348. for (m_pos = 0; m_pos < str_len; m_pos++) {
  17349. c = str.charCodeAt(m_pos);
  17350. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17351. c2 = str.charCodeAt(m_pos+1);
  17352. if ((c2 & 0xfc00) === 0xdc00) {
  17353. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17354. m_pos++;
  17355. }
  17356. }
  17357. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  17358. }
  17359. // allocate buffer
  17360. buf = new utils.Buf8(buf_len);
  17361. // convert
  17362. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  17363. c = str.charCodeAt(m_pos);
  17364. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17365. c2 = str.charCodeAt(m_pos+1);
  17366. if ((c2 & 0xfc00) === 0xdc00) {
  17367. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17368. m_pos++;
  17369. }
  17370. }
  17371. if (c < 0x80) {
  17372. /* one byte */
  17373. buf[i++] = c;
  17374. } else if (c < 0x800) {
  17375. /* two bytes */
  17376. buf[i++] = 0xC0 | (c >>> 6);
  17377. buf[i++] = 0x80 | (c & 0x3f);
  17378. } else if (c < 0x10000) {
  17379. /* three bytes */
  17380. buf[i++] = 0xE0 | (c >>> 12);
  17381. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17382. buf[i++] = 0x80 | (c & 0x3f);
  17383. } else {
  17384. /* four bytes */
  17385. buf[i++] = 0xf0 | (c >>> 18);
  17386. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  17387. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17388. buf[i++] = 0x80 | (c & 0x3f);
  17389. }
  17390. }
  17391. return buf;
  17392. };
  17393. // Helper (used in 2 places)
  17394. function buf2binstring(buf, len) {
  17395. // use fallback for big arrays to avoid stack overflow
  17396. if (len < 65537) {
  17397. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  17398. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  17399. }
  17400. }
  17401. var result = '';
  17402. for(var i=0; i < len; i++) {
  17403. result += String.fromCharCode(buf[i]);
  17404. }
  17405. return result;
  17406. }
  17407. // Convert byte array to binary string
  17408. exports.buf2binstring = function(buf) {
  17409. return buf2binstring(buf, buf.length);
  17410. };
  17411. // Convert binary string (typed, when possible)
  17412. exports.binstring2buf = function(str) {
  17413. var buf = new utils.Buf8(str.length);
  17414. for(var i=0, len=buf.length; i < len; i++) {
  17415. buf[i] = str.charCodeAt(i);
  17416. }
  17417. return buf;
  17418. };
  17419. // convert array to string
  17420. exports.buf2string = function (buf, max) {
  17421. var i, out, c, c_len;
  17422. var len = max || buf.length;
  17423. // Reserve max possible length (2 words per char)
  17424. // NB: by unknown reasons, Array is significantly faster for
  17425. // String.fromCharCode.apply than Uint16Array.
  17426. var utf16buf = new Array(len*2);
  17427. for (out=0, i=0; i<len;) {
  17428. c = buf[i++];
  17429. // quick process ascii
  17430. if (c < 0x80) { utf16buf[out++] = c; continue; }
  17431. c_len = _utf8len[c];
  17432. // skip 5 & 6 byte codes
  17433. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  17434. // apply mask on first byte
  17435. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  17436. // join the rest
  17437. while (c_len > 1 && i < len) {
  17438. c = (c << 6) | (buf[i++] & 0x3f);
  17439. c_len--;
  17440. }
  17441. // terminated by end of string?
  17442. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  17443. if (c < 0x10000) {
  17444. utf16buf[out++] = c;
  17445. } else {
  17446. c -= 0x10000;
  17447. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  17448. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  17449. }
  17450. }
  17451. return buf2binstring(utf16buf, out);
  17452. };
  17453. // Calculate max possible position in utf8 buffer,
  17454. // that will not break sequence. If that's not possible
  17455. // - (very small limits) return max size as is.
  17456. //
  17457. // buf[] - utf8 bytes array
  17458. // max - length limit (mandatory);
  17459. exports.utf8border = function(buf, max) {
  17460. var pos;
  17461. max = max || buf.length;
  17462. if (max > buf.length) { max = buf.length; }
  17463. // go back from last position, until start of sequence found
  17464. pos = max-1;
  17465. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  17466. // Fuckup - very small and broken sequence,
  17467. // return max, because we should return something anyway.
  17468. if (pos < 0) { return max; }
  17469. // If we came to start of buffer - that means vuffer is too small,
  17470. // return max too.
  17471. if (pos === 0) { return max; }
  17472. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  17473. };
  17474. },{"./common":65}],67:[function(require,module,exports){
  17475. 'use strict';
  17476. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  17477. // It doesn't worth to make additional optimizationa as in original.
  17478. // Small size is preferable.
  17479. function adler32(adler, buf, len, pos) {
  17480. var s1 = (adler & 0xffff) |0
  17481. , s2 = ((adler >>> 16) & 0xffff) |0
  17482. , n = 0;
  17483. while (len !== 0) {
  17484. // Set limit ~ twice less than 5552, to keep
  17485. // s2 in 31-bits, because we force signed ints.
  17486. // in other case %= will fail.
  17487. n = len > 2000 ? 2000 : len;
  17488. len -= n;
  17489. do {
  17490. s1 = (s1 + buf[pos++]) |0;
  17491. s2 = (s2 + s1) |0;
  17492. } while (--n);
  17493. s1 %= 65521;
  17494. s2 %= 65521;
  17495. }
  17496. return (s1 | (s2 << 16)) |0;
  17497. }
  17498. module.exports = adler32;
  17499. },{}],68:[function(require,module,exports){
  17500. module.exports = {
  17501. /* Allowed flush values; see deflate() and inflate() below for details */
  17502. Z_NO_FLUSH: 0,
  17503. Z_PARTIAL_FLUSH: 1,
  17504. Z_SYNC_FLUSH: 2,
  17505. Z_FULL_FLUSH: 3,
  17506. Z_FINISH: 4,
  17507. Z_BLOCK: 5,
  17508. Z_TREES: 6,
  17509. /* Return codes for the compression/decompression functions. Negative values
  17510. * are errors, positive values are used for special but normal events.
  17511. */
  17512. Z_OK: 0,
  17513. Z_STREAM_END: 1,
  17514. Z_NEED_DICT: 2,
  17515. Z_ERRNO: -1,
  17516. Z_STREAM_ERROR: -2,
  17517. Z_DATA_ERROR: -3,
  17518. //Z_MEM_ERROR: -4,
  17519. Z_BUF_ERROR: -5,
  17520. //Z_VERSION_ERROR: -6,
  17521. /* compression levels */
  17522. Z_NO_COMPRESSION: 0,
  17523. Z_BEST_SPEED: 1,
  17524. Z_BEST_COMPRESSION: 9,
  17525. Z_DEFAULT_COMPRESSION: -1,
  17526. Z_FILTERED: 1,
  17527. Z_HUFFMAN_ONLY: 2,
  17528. Z_RLE: 3,
  17529. Z_FIXED: 4,
  17530. Z_DEFAULT_STRATEGY: 0,
  17531. /* Possible values of the data_type field (though see inflate()) */
  17532. Z_BINARY: 0,
  17533. Z_TEXT: 1,
  17534. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  17535. Z_UNKNOWN: 2,
  17536. /* The deflate compression method */
  17537. Z_DEFLATED: 8
  17538. //Z_NULL: null // Use -1 or null inline, depending on var type
  17539. };
  17540. },{}],69:[function(require,module,exports){
  17541. 'use strict';
  17542. // Note: we can't get significant speed boost here.
  17543. // So write code to minimize size - no pregenerated tables
  17544. // and array tools dependencies.
  17545. // Use ordinary array, since untyped makes no boost here
  17546. function makeTable() {
  17547. var c, table = [];
  17548. for(var n =0; n < 256; n++){
  17549. c = n;
  17550. for(var k =0; k < 8; k++){
  17551. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  17552. }
  17553. table[n] = c;
  17554. }
  17555. return table;
  17556. }
  17557. // Create table on load. Just 255 signed longs. Not a problem.
  17558. var crcTable = makeTable();
  17559. function crc32(crc, buf, len, pos) {
  17560. var t = crcTable
  17561. , end = pos + len;
  17562. crc = crc ^ (-1);
  17563. for (var i = pos; i < end; i++ ) {
  17564. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  17565. }
  17566. return (crc ^ (-1)); // >>> 0;
  17567. }
  17568. module.exports = crc32;
  17569. },{}],70:[function(require,module,exports){
  17570. 'use strict';
  17571. var utils = require('../utils/common');
  17572. var trees = require('./trees');
  17573. var adler32 = require('./adler32');
  17574. var crc32 = require('./crc32');
  17575. var msg = require('./messages');
  17576. /* Public constants ==========================================================*/
  17577. /* ===========================================================================*/
  17578. /* Allowed flush values; see deflate() and inflate() below for details */
  17579. var Z_NO_FLUSH = 0;
  17580. var Z_PARTIAL_FLUSH = 1;
  17581. //var Z_SYNC_FLUSH = 2;
  17582. var Z_FULL_FLUSH = 3;
  17583. var Z_FINISH = 4;
  17584. var Z_BLOCK = 5;
  17585. //var Z_TREES = 6;
  17586. /* Return codes for the compression/decompression functions. Negative values
  17587. * are errors, positive values are used for special but normal events.
  17588. */
  17589. var Z_OK = 0;
  17590. var Z_STREAM_END = 1;
  17591. //var Z_NEED_DICT = 2;
  17592. //var Z_ERRNO = -1;
  17593. var Z_STREAM_ERROR = -2;
  17594. var Z_DATA_ERROR = -3;
  17595. //var Z_MEM_ERROR = -4;
  17596. var Z_BUF_ERROR = -5;
  17597. //var Z_VERSION_ERROR = -6;
  17598. /* compression levels */
  17599. //var Z_NO_COMPRESSION = 0;
  17600. //var Z_BEST_SPEED = 1;
  17601. //var Z_BEST_COMPRESSION = 9;
  17602. var Z_DEFAULT_COMPRESSION = -1;
  17603. var Z_FILTERED = 1;
  17604. var Z_HUFFMAN_ONLY = 2;
  17605. var Z_RLE = 3;
  17606. var Z_FIXED = 4;
  17607. var Z_DEFAULT_STRATEGY = 0;
  17608. /* Possible values of the data_type field (though see inflate()) */
  17609. //var Z_BINARY = 0;
  17610. //var Z_TEXT = 1;
  17611. //var Z_ASCII = 1; // = Z_TEXT
  17612. var Z_UNKNOWN = 2;
  17613. /* The deflate compression method */
  17614. var Z_DEFLATED = 8;
  17615. /*============================================================================*/
  17616. var MAX_MEM_LEVEL = 9;
  17617. /* Maximum value for memLevel in deflateInit2 */
  17618. var MAX_WBITS = 15;
  17619. /* 32K LZ77 window */
  17620. var DEF_MEM_LEVEL = 8;
  17621. var LENGTH_CODES = 29;
  17622. /* number of length codes, not counting the special END_BLOCK code */
  17623. var LITERALS = 256;
  17624. /* number of literal bytes 0..255 */
  17625. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17626. /* number of Literal or Length codes, including the END_BLOCK code */
  17627. var D_CODES = 30;
  17628. /* number of distance codes */
  17629. var BL_CODES = 19;
  17630. /* number of codes used to transfer the bit lengths */
  17631. var HEAP_SIZE = 2*L_CODES + 1;
  17632. /* maximum heap size */
  17633. var MAX_BITS = 15;
  17634. /* All codes must not exceed MAX_BITS bits */
  17635. var MIN_MATCH = 3;
  17636. var MAX_MATCH = 258;
  17637. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  17638. var PRESET_DICT = 0x20;
  17639. var INIT_STATE = 42;
  17640. var EXTRA_STATE = 69;
  17641. var NAME_STATE = 73;
  17642. var COMMENT_STATE = 91;
  17643. var HCRC_STATE = 103;
  17644. var BUSY_STATE = 113;
  17645. var FINISH_STATE = 666;
  17646. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  17647. var BS_BLOCK_DONE = 2; /* block flush performed */
  17648. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  17649. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  17650. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  17651. function err(strm, errorCode) {
  17652. strm.msg = msg[errorCode];
  17653. return errorCode;
  17654. }
  17655. function rank(f) {
  17656. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  17657. }
  17658. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17659. /* =========================================================================
  17660. * Flush as much pending output as possible. All deflate() output goes
  17661. * through this function so some applications may wish to modify it
  17662. * to avoid allocating a large strm->output buffer and copying into it.
  17663. * (See also read_buf()).
  17664. */
  17665. function flush_pending(strm) {
  17666. var s = strm.state;
  17667. //_tr_flush_bits(s);
  17668. var len = s.pending;
  17669. if (len > strm.avail_out) {
  17670. len = strm.avail_out;
  17671. }
  17672. if (len === 0) { return; }
  17673. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  17674. strm.next_out += len;
  17675. s.pending_out += len;
  17676. strm.total_out += len;
  17677. strm.avail_out -= len;
  17678. s.pending -= len;
  17679. if (s.pending === 0) {
  17680. s.pending_out = 0;
  17681. }
  17682. }
  17683. function flush_block_only (s, last) {
  17684. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  17685. s.block_start = s.strstart;
  17686. flush_pending(s.strm);
  17687. }
  17688. function put_byte(s, b) {
  17689. s.pending_buf[s.pending++] = b;
  17690. }
  17691. /* =========================================================================
  17692. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  17693. * IN assertion: the stream state is correct and there is enough room in
  17694. * pending_buf.
  17695. */
  17696. function putShortMSB(s, b) {
  17697. // put_byte(s, (Byte)(b >> 8));
  17698. // put_byte(s, (Byte)(b & 0xff));
  17699. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  17700. s.pending_buf[s.pending++] = b & 0xff;
  17701. }
  17702. /* ===========================================================================
  17703. * Read a new buffer from the current input stream, update the adler32
  17704. * and total number of bytes read. All deflate() input goes through
  17705. * this function so some applications may wish to modify it to avoid
  17706. * allocating a large strm->input buffer and copying from it.
  17707. * (See also flush_pending()).
  17708. */
  17709. function read_buf(strm, buf, start, size) {
  17710. var len = strm.avail_in;
  17711. if (len > size) { len = size; }
  17712. if (len === 0) { return 0; }
  17713. strm.avail_in -= len;
  17714. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  17715. if (strm.state.wrap === 1) {
  17716. strm.adler = adler32(strm.adler, buf, len, start);
  17717. }
  17718. else if (strm.state.wrap === 2) {
  17719. strm.adler = crc32(strm.adler, buf, len, start);
  17720. }
  17721. strm.next_in += len;
  17722. strm.total_in += len;
  17723. return len;
  17724. }
  17725. /* ===========================================================================
  17726. * Set match_start to the longest match starting at the given string and
  17727. * return its length. Matches shorter or equal to prev_length are discarded,
  17728. * in which case the result is equal to prev_length and match_start is
  17729. * garbage.
  17730. * IN assertions: cur_match is the head of the hash chain for the current
  17731. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  17732. * OUT assertion: the match length is not greater than s->lookahead.
  17733. */
  17734. function longest_match(s, cur_match) {
  17735. var chain_length = s.max_chain_length; /* max hash chain length */
  17736. var scan = s.strstart; /* current string */
  17737. var match; /* matched string */
  17738. var len; /* length of current match */
  17739. var best_len = s.prev_length; /* best match length so far */
  17740. var nice_match = s.nice_match; /* stop if match long enough */
  17741. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  17742. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  17743. var _win = s.window; // shortcut
  17744. var wmask = s.w_mask;
  17745. var prev = s.prev;
  17746. /* Stop when cur_match becomes <= limit. To simplify the code,
  17747. * we prevent matches with the string of window index 0.
  17748. */
  17749. var strend = s.strstart + MAX_MATCH;
  17750. var scan_end1 = _win[scan + best_len - 1];
  17751. var scan_end = _win[scan + best_len];
  17752. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  17753. * It is easy to get rid of this optimization if necessary.
  17754. */
  17755. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  17756. /* Do not waste too much time if we already have a good match: */
  17757. if (s.prev_length >= s.good_match) {
  17758. chain_length >>= 2;
  17759. }
  17760. /* Do not look for matches beyond the end of the input. This is necessary
  17761. * to make deflate deterministic.
  17762. */
  17763. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  17764. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  17765. do {
  17766. // Assert(cur_match < s->strstart, "no future");
  17767. match = cur_match;
  17768. /* Skip to next match if the match length cannot increase
  17769. * or if the match length is less than 2. Note that the checks below
  17770. * for insufficient lookahead only occur occasionally for performance
  17771. * reasons. Therefore uninitialized memory will be accessed, and
  17772. * conditional jumps will be made that depend on those values.
  17773. * However the length of the match is limited to the lookahead, so
  17774. * the output of deflate is not affected by the uninitialized values.
  17775. */
  17776. if (_win[match + best_len] !== scan_end ||
  17777. _win[match + best_len - 1] !== scan_end1 ||
  17778. _win[match] !== _win[scan] ||
  17779. _win[++match] !== _win[scan + 1]) {
  17780. continue;
  17781. }
  17782. /* The check at best_len-1 can be removed because it will be made
  17783. * again later. (This heuristic is not always a win.)
  17784. * It is not necessary to compare scan[2] and match[2] since they
  17785. * are always equal when the other bytes match, given that
  17786. * the hash keys are equal and that HASH_BITS >= 8.
  17787. */
  17788. scan += 2;
  17789. match++;
  17790. // Assert(*scan == *match, "match[2]?");
  17791. /* We check for insufficient lookahead only every 8th comparison;
  17792. * the 256th check will be made at strstart+258.
  17793. */
  17794. do {
  17795. /*jshint noempty:false*/
  17796. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17797. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17798. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17799. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  17800. scan < strend);
  17801. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  17802. len = MAX_MATCH - (strend - scan);
  17803. scan = strend - MAX_MATCH;
  17804. if (len > best_len) {
  17805. s.match_start = cur_match;
  17806. best_len = len;
  17807. if (len >= nice_match) {
  17808. break;
  17809. }
  17810. scan_end1 = _win[scan + best_len - 1];
  17811. scan_end = _win[scan + best_len];
  17812. }
  17813. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  17814. if (best_len <= s.lookahead) {
  17815. return best_len;
  17816. }
  17817. return s.lookahead;
  17818. }
  17819. /* ===========================================================================
  17820. * Fill the window when the lookahead becomes insufficient.
  17821. * Updates strstart and lookahead.
  17822. *
  17823. * IN assertion: lookahead < MIN_LOOKAHEAD
  17824. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  17825. * At least one byte has been read, or avail_in == 0; reads are
  17826. * performed for at least two bytes (required for the zip translate_eol
  17827. * option -- not supported here).
  17828. */
  17829. function fill_window(s) {
  17830. var _w_size = s.w_size;
  17831. var p, n, m, more, str;
  17832. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  17833. do {
  17834. more = s.window_size - s.lookahead - s.strstart;
  17835. // JS ints have 32 bit, block below not needed
  17836. /* Deal with !@#$% 64K limit: */
  17837. //if (sizeof(int) <= 2) {
  17838. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  17839. // more = wsize;
  17840. //
  17841. // } else if (more == (unsigned)(-1)) {
  17842. // /* Very unlikely, but possible on 16 bit machine if
  17843. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  17844. // */
  17845. // more--;
  17846. // }
  17847. //}
  17848. /* If the window is almost full and there is insufficient lookahead,
  17849. * move the upper half to the lower one to make room in the upper half.
  17850. */
  17851. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  17852. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  17853. s.match_start -= _w_size;
  17854. s.strstart -= _w_size;
  17855. /* we now have strstart >= MAX_DIST */
  17856. s.block_start -= _w_size;
  17857. /* Slide the hash table (could be avoided with 32 bit values
  17858. at the expense of memory usage). We slide even when level == 0
  17859. to keep the hash table consistent if we switch back to level > 0
  17860. later. (Using level 0 permanently is not an optimal usage of
  17861. zlib, so we don't care about this pathological case.)
  17862. */
  17863. n = s.hash_size;
  17864. p = n;
  17865. do {
  17866. m = s.head[--p];
  17867. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  17868. } while (--n);
  17869. n = _w_size;
  17870. p = n;
  17871. do {
  17872. m = s.prev[--p];
  17873. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  17874. /* If n is not on any hash chain, prev[n] is garbage but
  17875. * its value will never be used.
  17876. */
  17877. } while (--n);
  17878. more += _w_size;
  17879. }
  17880. if (s.strm.avail_in === 0) {
  17881. break;
  17882. }
  17883. /* If there was no sliding:
  17884. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  17885. * more == window_size - lookahead - strstart
  17886. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  17887. * => more >= window_size - 2*WSIZE + 2
  17888. * In the BIG_MEM or MMAP case (not yet supported),
  17889. * window_size == input_size + MIN_LOOKAHEAD &&
  17890. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  17891. * Otherwise, window_size == 2*WSIZE so more >= 2.
  17892. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  17893. */
  17894. //Assert(more >= 2, "more < 2");
  17895. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  17896. s.lookahead += n;
  17897. /* Initialize the hash value now that we have some input: */
  17898. if (s.lookahead + s.insert >= MIN_MATCH) {
  17899. str = s.strstart - s.insert;
  17900. s.ins_h = s.window[str];
  17901. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  17902. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  17903. //#if MIN_MATCH != 3
  17904. // Call update_hash() MIN_MATCH-3 more times
  17905. //#endif
  17906. while (s.insert) {
  17907. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  17908. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  17909. s.prev[str & s.w_mask] = s.head[s.ins_h];
  17910. s.head[s.ins_h] = str;
  17911. str++;
  17912. s.insert--;
  17913. if (s.lookahead + s.insert < MIN_MATCH) {
  17914. break;
  17915. }
  17916. }
  17917. }
  17918. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  17919. * but this is not important since only literal bytes will be emitted.
  17920. */
  17921. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  17922. /* If the WIN_INIT bytes after the end of the current data have never been
  17923. * written, then zero those bytes in order to avoid memory check reports of
  17924. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  17925. * the longest match routines. Update the high water mark for the next
  17926. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  17927. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  17928. */
  17929. // if (s.high_water < s.window_size) {
  17930. // var curr = s.strstart + s.lookahead;
  17931. // var init = 0;
  17932. //
  17933. // if (s.high_water < curr) {
  17934. // /* Previous high water mark below current data -- zero WIN_INIT
  17935. // * bytes or up to end of window, whichever is less.
  17936. // */
  17937. // init = s.window_size - curr;
  17938. // if (init > WIN_INIT)
  17939. // init = WIN_INIT;
  17940. // zmemzero(s->window + curr, (unsigned)init);
  17941. // s->high_water = curr + init;
  17942. // }
  17943. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  17944. // /* High water mark at or above current data, but below current data
  17945. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  17946. // * to end of window, whichever is less.
  17947. // */
  17948. // init = (ulg)curr + WIN_INIT - s->high_water;
  17949. // if (init > s->window_size - s->high_water)
  17950. // init = s->window_size - s->high_water;
  17951. // zmemzero(s->window + s->high_water, (unsigned)init);
  17952. // s->high_water += init;
  17953. // }
  17954. // }
  17955. //
  17956. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  17957. // "not enough room for search");
  17958. }
  17959. /* ===========================================================================
  17960. * Copy without compression as much as possible from the input stream, return
  17961. * the current block state.
  17962. * This function does not insert new strings in the dictionary since
  17963. * uncompressible data is probably not useful. This function is used
  17964. * only for the level=0 compression option.
  17965. * NOTE: this function should be optimized to avoid extra copying from
  17966. * window to pending_buf.
  17967. */
  17968. function deflate_stored(s, flush) {
  17969. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  17970. * to pending_buf_size, and each stored block has a 5 byte header:
  17971. */
  17972. var max_block_size = 0xffff;
  17973. if (max_block_size > s.pending_buf_size - 5) {
  17974. max_block_size = s.pending_buf_size - 5;
  17975. }
  17976. /* Copy as much as possible from input to output: */
  17977. for (;;) {
  17978. /* Fill the window as much as possible: */
  17979. if (s.lookahead <= 1) {
  17980. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  17981. // s->block_start >= (long)s->w_size, "slide too late");
  17982. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  17983. // s.block_start >= s.w_size)) {
  17984. // throw new Error("slide too late");
  17985. // }
  17986. fill_window(s);
  17987. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  17988. return BS_NEED_MORE;
  17989. }
  17990. if (s.lookahead === 0) {
  17991. break;
  17992. }
  17993. /* flush the current block */
  17994. }
  17995. //Assert(s->block_start >= 0L, "block gone");
  17996. // if (s.block_start < 0) throw new Error("block gone");
  17997. s.strstart += s.lookahead;
  17998. s.lookahead = 0;
  17999. /* Emit a stored block if pending_buf will be full: */
  18000. var max_start = s.block_start + max_block_size;
  18001. if (s.strstart === 0 || s.strstart >= max_start) {
  18002. /* strstart == 0 is possible when wraparound on 16-bit machine */
  18003. s.lookahead = s.strstart - max_start;
  18004. s.strstart = max_start;
  18005. /*** FLUSH_BLOCK(s, 0); ***/
  18006. flush_block_only(s, false);
  18007. if (s.strm.avail_out === 0) {
  18008. return BS_NEED_MORE;
  18009. }
  18010. /***/
  18011. }
  18012. /* Flush if we may have to slide, otherwise block_start may become
  18013. * negative and the data will be gone:
  18014. */
  18015. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  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. }
  18024. s.insert = 0;
  18025. if (flush === Z_FINISH) {
  18026. /*** FLUSH_BLOCK(s, 1); ***/
  18027. flush_block_only(s, true);
  18028. if (s.strm.avail_out === 0) {
  18029. return BS_FINISH_STARTED;
  18030. }
  18031. /***/
  18032. return BS_FINISH_DONE;
  18033. }
  18034. if (s.strstart > s.block_start) {
  18035. /*** FLUSH_BLOCK(s, 0); ***/
  18036. flush_block_only(s, false);
  18037. if (s.strm.avail_out === 0) {
  18038. return BS_NEED_MORE;
  18039. }
  18040. /***/
  18041. }
  18042. return BS_NEED_MORE;
  18043. }
  18044. /* ===========================================================================
  18045. * Compress as much as possible from the input stream, return the current
  18046. * block state.
  18047. * This function does not perform lazy evaluation of matches and inserts
  18048. * new strings in the dictionary only for unmatched strings or for short
  18049. * matches. It is used only for the fast compression options.
  18050. */
  18051. function deflate_fast(s, flush) {
  18052. var hash_head; /* head of the hash chain */
  18053. var bflush; /* set if current block must be flushed */
  18054. for (;;) {
  18055. /* Make sure that we always have enough lookahead, except
  18056. * at the end of the input file. We need MAX_MATCH bytes
  18057. * for the next match, plus MIN_MATCH bytes to insert the
  18058. * string following the next match.
  18059. */
  18060. if (s.lookahead < MIN_LOOKAHEAD) {
  18061. fill_window(s);
  18062. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18063. return BS_NEED_MORE;
  18064. }
  18065. if (s.lookahead === 0) {
  18066. break; /* flush the current block */
  18067. }
  18068. }
  18069. /* Insert the string window[strstart .. strstart+2] in the
  18070. * dictionary, and set hash_head to the head of the hash chain:
  18071. */
  18072. hash_head = 0/*NIL*/;
  18073. if (s.lookahead >= MIN_MATCH) {
  18074. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18075. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18076. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18077. s.head[s.ins_h] = s.strstart;
  18078. /***/
  18079. }
  18080. /* Find the longest match, discarding those <= prev_length.
  18081. * At this point we have always match_length < MIN_MATCH
  18082. */
  18083. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  18084. /* To simplify the code, we prevent matches with the string
  18085. * of window index 0 (in particular we have to avoid a match
  18086. * of the string with itself at the start of the input file).
  18087. */
  18088. s.match_length = longest_match(s, hash_head);
  18089. /* longest_match() sets match_start */
  18090. }
  18091. if (s.match_length >= MIN_MATCH) {
  18092. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  18093. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  18094. s.match_length - MIN_MATCH, bflush); ***/
  18095. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  18096. s.lookahead -= s.match_length;
  18097. /* Insert new strings in the hash table only if the match length
  18098. * is not too large. This saves time but degrades compression.
  18099. */
  18100. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  18101. s.match_length--; /* string at strstart already in table */
  18102. do {
  18103. s.strstart++;
  18104. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18105. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18106. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18107. s.head[s.ins_h] = s.strstart;
  18108. /***/
  18109. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  18110. * always MIN_MATCH bytes ahead.
  18111. */
  18112. } while (--s.match_length !== 0);
  18113. s.strstart++;
  18114. } else
  18115. {
  18116. s.strstart += s.match_length;
  18117. s.match_length = 0;
  18118. s.ins_h = s.window[s.strstart];
  18119. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  18120. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  18121. //#if MIN_MATCH != 3
  18122. // Call UPDATE_HASH() MIN_MATCH-3 more times
  18123. //#endif
  18124. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  18125. * matter since it will be recomputed at next deflate call.
  18126. */
  18127. }
  18128. } else {
  18129. /* No match, output a literal byte */
  18130. //Tracevv((stderr,"%c", s.window[s.strstart]));
  18131. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18132. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18133. s.lookahead--;
  18134. s.strstart++;
  18135. }
  18136. if (bflush) {
  18137. /*** FLUSH_BLOCK(s, 0); ***/
  18138. flush_block_only(s, false);
  18139. if (s.strm.avail_out === 0) {
  18140. return BS_NEED_MORE;
  18141. }
  18142. /***/
  18143. }
  18144. }
  18145. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  18146. if (flush === Z_FINISH) {
  18147. /*** FLUSH_BLOCK(s, 1); ***/
  18148. flush_block_only(s, true);
  18149. if (s.strm.avail_out === 0) {
  18150. return BS_FINISH_STARTED;
  18151. }
  18152. /***/
  18153. return BS_FINISH_DONE;
  18154. }
  18155. if (s.last_lit) {
  18156. /*** FLUSH_BLOCK(s, 0); ***/
  18157. flush_block_only(s, false);
  18158. if (s.strm.avail_out === 0) {
  18159. return BS_NEED_MORE;
  18160. }
  18161. /***/
  18162. }
  18163. return BS_BLOCK_DONE;
  18164. }
  18165. /* ===========================================================================
  18166. * Same as above, but achieves better compression. We use a lazy
  18167. * evaluation for matches: a match is finally adopted only if there is
  18168. * no better match at the next window position.
  18169. */
  18170. function deflate_slow(s, flush) {
  18171. var hash_head; /* head of hash chain */
  18172. var bflush; /* set if current block must be flushed */
  18173. var max_insert;
  18174. /* Process the input block. */
  18175. for (;;) {
  18176. /* Make sure that we always have enough lookahead, except
  18177. * at the end of the input file. We need MAX_MATCH bytes
  18178. * for the next match, plus MIN_MATCH bytes to insert the
  18179. * string following the next match.
  18180. */
  18181. if (s.lookahead < MIN_LOOKAHEAD) {
  18182. fill_window(s);
  18183. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18184. return BS_NEED_MORE;
  18185. }
  18186. if (s.lookahead === 0) { break; } /* flush the current block */
  18187. }
  18188. /* Insert the string window[strstart .. strstart+2] in the
  18189. * dictionary, and set hash_head to the head of the hash chain:
  18190. */
  18191. hash_head = 0/*NIL*/;
  18192. if (s.lookahead >= MIN_MATCH) {
  18193. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18194. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18195. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18196. s.head[s.ins_h] = s.strstart;
  18197. /***/
  18198. }
  18199. /* Find the longest match, discarding those <= prev_length.
  18200. */
  18201. s.prev_length = s.match_length;
  18202. s.prev_match = s.match_start;
  18203. s.match_length = MIN_MATCH-1;
  18204. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  18205. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  18206. /* To simplify the code, we prevent matches with the string
  18207. * of window index 0 (in particular we have to avoid a match
  18208. * of the string with itself at the start of the input file).
  18209. */
  18210. s.match_length = longest_match(s, hash_head);
  18211. /* longest_match() sets match_start */
  18212. if (s.match_length <= 5 &&
  18213. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  18214. /* If prev_match is also MIN_MATCH, match_start is garbage
  18215. * but we will ignore the current match anyway.
  18216. */
  18217. s.match_length = MIN_MATCH-1;
  18218. }
  18219. }
  18220. /* If there was a match at the previous step and the current
  18221. * match is not better, output the previous match:
  18222. */
  18223. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  18224. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  18225. /* Do not insert strings in hash table beyond this. */
  18226. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  18227. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  18228. s.prev_length - MIN_MATCH, bflush);***/
  18229. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  18230. /* Insert in hash table all strings up to the end of the match.
  18231. * strstart-1 and strstart are already inserted. If there is not
  18232. * enough lookahead, the last two strings are not inserted in
  18233. * the hash table.
  18234. */
  18235. s.lookahead -= s.prev_length-1;
  18236. s.prev_length -= 2;
  18237. do {
  18238. if (++s.strstart <= max_insert) {
  18239. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18240. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18241. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18242. s.head[s.ins_h] = s.strstart;
  18243. /***/
  18244. }
  18245. } while (--s.prev_length !== 0);
  18246. s.match_available = 0;
  18247. s.match_length = MIN_MATCH-1;
  18248. s.strstart++;
  18249. if (bflush) {
  18250. /*** FLUSH_BLOCK(s, 0); ***/
  18251. flush_block_only(s, false);
  18252. if (s.strm.avail_out === 0) {
  18253. return BS_NEED_MORE;
  18254. }
  18255. /***/
  18256. }
  18257. } else if (s.match_available) {
  18258. /* If there was no match at the previous position, output a
  18259. * single literal. If there was a match but the current match
  18260. * is longer, truncate the previous match to a single literal.
  18261. */
  18262. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18263. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18264. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18265. if (bflush) {
  18266. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  18267. flush_block_only(s, false);
  18268. /***/
  18269. }
  18270. s.strstart++;
  18271. s.lookahead--;
  18272. if (s.strm.avail_out === 0) {
  18273. return BS_NEED_MORE;
  18274. }
  18275. } else {
  18276. /* There is no previous match to compare with, wait for
  18277. * the next step to decide.
  18278. */
  18279. s.match_available = 1;
  18280. s.strstart++;
  18281. s.lookahead--;
  18282. }
  18283. }
  18284. //Assert (flush != Z_NO_FLUSH, "no flush?");
  18285. if (s.match_available) {
  18286. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18287. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18288. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18289. s.match_available = 0;
  18290. }
  18291. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  18292. if (flush === Z_FINISH) {
  18293. /*** FLUSH_BLOCK(s, 1); ***/
  18294. flush_block_only(s, true);
  18295. if (s.strm.avail_out === 0) {
  18296. return BS_FINISH_STARTED;
  18297. }
  18298. /***/
  18299. return BS_FINISH_DONE;
  18300. }
  18301. if (s.last_lit) {
  18302. /*** FLUSH_BLOCK(s, 0); ***/
  18303. flush_block_only(s, false);
  18304. if (s.strm.avail_out === 0) {
  18305. return BS_NEED_MORE;
  18306. }
  18307. /***/
  18308. }
  18309. return BS_BLOCK_DONE;
  18310. }
  18311. /* ===========================================================================
  18312. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  18313. * one. Do not maintain a hash table. (It will be regenerated if this run of
  18314. * deflate switches away from Z_RLE.)
  18315. */
  18316. function deflate_rle(s, flush) {
  18317. var bflush; /* set if current block must be flushed */
  18318. var prev; /* byte at distance one to match */
  18319. var scan, strend; /* scan goes up to strend for length of run */
  18320. var _win = s.window;
  18321. for (;;) {
  18322. /* Make sure that we always have enough lookahead, except
  18323. * at the end of the input file. We need MAX_MATCH bytes
  18324. * for the longest run, plus one for the unrolled loop.
  18325. */
  18326. if (s.lookahead <= MAX_MATCH) {
  18327. fill_window(s);
  18328. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  18329. return BS_NEED_MORE;
  18330. }
  18331. if (s.lookahead === 0) { break; } /* flush the current block */
  18332. }
  18333. /* See how many times the previous byte repeats */
  18334. s.match_length = 0;
  18335. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  18336. scan = s.strstart - 1;
  18337. prev = _win[scan];
  18338. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  18339. strend = s.strstart + MAX_MATCH;
  18340. do {
  18341. /*jshint noempty:false*/
  18342. } while (prev === _win[++scan] && prev === _win[++scan] &&
  18343. prev === _win[++scan] && prev === _win[++scan] &&
  18344. prev === _win[++scan] && prev === _win[++scan] &&
  18345. prev === _win[++scan] && prev === _win[++scan] &&
  18346. scan < strend);
  18347. s.match_length = MAX_MATCH - (strend - scan);
  18348. if (s.match_length > s.lookahead) {
  18349. s.match_length = s.lookahead;
  18350. }
  18351. }
  18352. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  18353. }
  18354. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  18355. if (s.match_length >= MIN_MATCH) {
  18356. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  18357. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  18358. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  18359. s.lookahead -= s.match_length;
  18360. s.strstart += s.match_length;
  18361. s.match_length = 0;
  18362. } else {
  18363. /* No match, output a literal byte */
  18364. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18365. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18366. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18367. s.lookahead--;
  18368. s.strstart++;
  18369. }
  18370. if (bflush) {
  18371. /*** FLUSH_BLOCK(s, 0); ***/
  18372. flush_block_only(s, false);
  18373. if (s.strm.avail_out === 0) {
  18374. return BS_NEED_MORE;
  18375. }
  18376. /***/
  18377. }
  18378. }
  18379. s.insert = 0;
  18380. if (flush === Z_FINISH) {
  18381. /*** FLUSH_BLOCK(s, 1); ***/
  18382. flush_block_only(s, true);
  18383. if (s.strm.avail_out === 0) {
  18384. return BS_FINISH_STARTED;
  18385. }
  18386. /***/
  18387. return BS_FINISH_DONE;
  18388. }
  18389. if (s.last_lit) {
  18390. /*** FLUSH_BLOCK(s, 0); ***/
  18391. flush_block_only(s, false);
  18392. if (s.strm.avail_out === 0) {
  18393. return BS_NEED_MORE;
  18394. }
  18395. /***/
  18396. }
  18397. return BS_BLOCK_DONE;
  18398. }
  18399. /* ===========================================================================
  18400. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  18401. * (It will be regenerated if this run of deflate switches away from Huffman.)
  18402. */
  18403. function deflate_huff(s, flush) {
  18404. var bflush; /* set if current block must be flushed */
  18405. for (;;) {
  18406. /* Make sure that we have a literal to write. */
  18407. if (s.lookahead === 0) {
  18408. fill_window(s);
  18409. if (s.lookahead === 0) {
  18410. if (flush === Z_NO_FLUSH) {
  18411. return BS_NEED_MORE;
  18412. }
  18413. break; /* flush the current block */
  18414. }
  18415. }
  18416. /* Output a literal byte */
  18417. s.match_length = 0;
  18418. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18419. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18420. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18421. s.lookahead--;
  18422. s.strstart++;
  18423. if (bflush) {
  18424. /*** FLUSH_BLOCK(s, 0); ***/
  18425. flush_block_only(s, false);
  18426. if (s.strm.avail_out === 0) {
  18427. return BS_NEED_MORE;
  18428. }
  18429. /***/
  18430. }
  18431. }
  18432. s.insert = 0;
  18433. if (flush === Z_FINISH) {
  18434. /*** FLUSH_BLOCK(s, 1); ***/
  18435. flush_block_only(s, true);
  18436. if (s.strm.avail_out === 0) {
  18437. return BS_FINISH_STARTED;
  18438. }
  18439. /***/
  18440. return BS_FINISH_DONE;
  18441. }
  18442. if (s.last_lit) {
  18443. /*** FLUSH_BLOCK(s, 0); ***/
  18444. flush_block_only(s, false);
  18445. if (s.strm.avail_out === 0) {
  18446. return BS_NEED_MORE;
  18447. }
  18448. /***/
  18449. }
  18450. return BS_BLOCK_DONE;
  18451. }
  18452. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  18453. * the desired pack level (0..9). The values given below have been tuned to
  18454. * exclude worst case performance for pathological files. Better values may be
  18455. * found for specific files.
  18456. */
  18457. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  18458. this.good_length = good_length;
  18459. this.max_lazy = max_lazy;
  18460. this.nice_length = nice_length;
  18461. this.max_chain = max_chain;
  18462. this.func = func;
  18463. };
  18464. var configuration_table;
  18465. configuration_table = [
  18466. /* good lazy nice chain */
  18467. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  18468. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  18469. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  18470. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  18471. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  18472. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  18473. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  18474. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  18475. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  18476. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  18477. ];
  18478. /* ===========================================================================
  18479. * Initialize the "longest match" routines for a new zlib stream
  18480. */
  18481. function lm_init(s) {
  18482. s.window_size = 2 * s.w_size;
  18483. /*** CLEAR_HASH(s); ***/
  18484. zero(s.head); // Fill with NIL (= 0);
  18485. /* Set the default configuration parameters:
  18486. */
  18487. s.max_lazy_match = configuration_table[s.level].max_lazy;
  18488. s.good_match = configuration_table[s.level].good_length;
  18489. s.nice_match = configuration_table[s.level].nice_length;
  18490. s.max_chain_length = configuration_table[s.level].max_chain;
  18491. s.strstart = 0;
  18492. s.block_start = 0;
  18493. s.lookahead = 0;
  18494. s.insert = 0;
  18495. s.match_length = s.prev_length = MIN_MATCH - 1;
  18496. s.match_available = 0;
  18497. s.ins_h = 0;
  18498. }
  18499. function DeflateState() {
  18500. this.strm = null; /* pointer back to this zlib stream */
  18501. this.status = 0; /* as the name implies */
  18502. this.pending_buf = null; /* output still pending */
  18503. this.pending_buf_size = 0; /* size of pending_buf */
  18504. this.pending_out = 0; /* next pending byte to output to the stream */
  18505. this.pending = 0; /* nb of bytes in the pending buffer */
  18506. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  18507. this.gzhead = null; /* gzip header information to write */
  18508. this.gzindex = 0; /* where in extra, name, or comment */
  18509. this.method = Z_DEFLATED; /* can only be DEFLATED */
  18510. this.last_flush = -1; /* value of flush param for previous deflate call */
  18511. this.w_size = 0; /* LZ77 window size (32K by default) */
  18512. this.w_bits = 0; /* log2(w_size) (8..16) */
  18513. this.w_mask = 0; /* w_size - 1 */
  18514. this.window = null;
  18515. /* Sliding window. Input bytes are read into the second half of the window,
  18516. * and move to the first half later to keep a dictionary of at least wSize
  18517. * bytes. With this organization, matches are limited to a distance of
  18518. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  18519. * performed with a length multiple of the block size.
  18520. */
  18521. this.window_size = 0;
  18522. /* Actual size of window: 2*wSize, except when the user input buffer
  18523. * is directly used as sliding window.
  18524. */
  18525. this.prev = null;
  18526. /* Link to older string with same hash index. To limit the size of this
  18527. * array to 64K, this link is maintained only for the last 32K strings.
  18528. * An index in this array is thus a window index modulo 32K.
  18529. */
  18530. this.head = null; /* Heads of the hash chains or NIL. */
  18531. this.ins_h = 0; /* hash index of string to be inserted */
  18532. this.hash_size = 0; /* number of elements in hash table */
  18533. this.hash_bits = 0; /* log2(hash_size) */
  18534. this.hash_mask = 0; /* hash_size-1 */
  18535. this.hash_shift = 0;
  18536. /* Number of bits by which ins_h must be shifted at each input
  18537. * step. It must be such that after MIN_MATCH steps, the oldest
  18538. * byte no longer takes part in the hash key, that is:
  18539. * hash_shift * MIN_MATCH >= hash_bits
  18540. */
  18541. this.block_start = 0;
  18542. /* Window position at the beginning of the current output block. Gets
  18543. * negative when the window is moved backwards.
  18544. */
  18545. this.match_length = 0; /* length of best match */
  18546. this.prev_match = 0; /* previous match */
  18547. this.match_available = 0; /* set if previous match exists */
  18548. this.strstart = 0; /* start of string to insert */
  18549. this.match_start = 0; /* start of matching string */
  18550. this.lookahead = 0; /* number of valid bytes ahead in window */
  18551. this.prev_length = 0;
  18552. /* Length of the best match at previous step. Matches not greater than this
  18553. * are discarded. This is used in the lazy match evaluation.
  18554. */
  18555. this.max_chain_length = 0;
  18556. /* To speed up deflation, hash chains are never searched beyond this
  18557. * length. A higher limit improves compression ratio but degrades the
  18558. * speed.
  18559. */
  18560. this.max_lazy_match = 0;
  18561. /* Attempt to find a better match only when the current match is strictly
  18562. * smaller than this value. This mechanism is used only for compression
  18563. * levels >= 4.
  18564. */
  18565. // That's alias to max_lazy_match, don't use directly
  18566. //this.max_insert_length = 0;
  18567. /* Insert new strings in the hash table only if the match length is not
  18568. * greater than this length. This saves time but degrades compression.
  18569. * max_insert_length is used only for compression levels <= 3.
  18570. */
  18571. this.level = 0; /* compression level (1..9) */
  18572. this.strategy = 0; /* favor or force Huffman coding*/
  18573. this.good_match = 0;
  18574. /* Use a faster search when the previous match is longer than this */
  18575. this.nice_match = 0; /* Stop searching when current match exceeds this */
  18576. /* used by trees.c: */
  18577. /* Didn't use ct_data typedef below to suppress compiler warning */
  18578. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  18579. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  18580. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  18581. // Use flat array of DOUBLE size, with interleaved fata,
  18582. // because JS does not support effective
  18583. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  18584. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  18585. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  18586. zero(this.dyn_ltree);
  18587. zero(this.dyn_dtree);
  18588. zero(this.bl_tree);
  18589. this.l_desc = null; /* desc. for literal tree */
  18590. this.d_desc = null; /* desc. for distance tree */
  18591. this.bl_desc = null; /* desc. for bit length tree */
  18592. //ush bl_count[MAX_BITS+1];
  18593. this.bl_count = new utils.Buf16(MAX_BITS+1);
  18594. /* number of codes at each bit length for an optimal tree */
  18595. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  18596. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  18597. zero(this.heap);
  18598. this.heap_len = 0; /* number of elements in the heap */
  18599. this.heap_max = 0; /* element of largest frequency */
  18600. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  18601. * The same heap array is used to build all trees.
  18602. */
  18603. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  18604. zero(this.depth);
  18605. /* Depth of each subtree used as tie breaker for trees of equal frequency
  18606. */
  18607. this.l_buf = 0; /* buffer index for literals or lengths */
  18608. this.lit_bufsize = 0;
  18609. /* Size of match buffer for literals/lengths. There are 4 reasons for
  18610. * limiting lit_bufsize to 64K:
  18611. * - frequencies can be kept in 16 bit counters
  18612. * - if compression is not successful for the first block, all input
  18613. * data is still in the window so we can still emit a stored block even
  18614. * when input comes from standard input. (This can also be done for
  18615. * all blocks if lit_bufsize is not greater than 32K.)
  18616. * - if compression is not successful for a file smaller than 64K, we can
  18617. * even emit a stored file instead of a stored block (saving 5 bytes).
  18618. * This is applicable only for zip (not gzip or zlib).
  18619. * - creating new Huffman trees less frequently may not provide fast
  18620. * adaptation to changes in the input data statistics. (Take for
  18621. * example a binary file with poorly compressible code followed by
  18622. * a highly compressible string table.) Smaller buffer sizes give
  18623. * fast adaptation but have of course the overhead of transmitting
  18624. * trees more frequently.
  18625. * - I can't count above 4
  18626. */
  18627. this.last_lit = 0; /* running index in l_buf */
  18628. this.d_buf = 0;
  18629. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  18630. * the same number of elements. To use different lengths, an extra flag
  18631. * array would be necessary.
  18632. */
  18633. this.opt_len = 0; /* bit length of current block with optimal trees */
  18634. this.static_len = 0; /* bit length of current block with static trees */
  18635. this.matches = 0; /* number of string matches in current block */
  18636. this.insert = 0; /* bytes at end of window left to insert */
  18637. this.bi_buf = 0;
  18638. /* Output buffer. bits are inserted starting at the bottom (least
  18639. * significant bits).
  18640. */
  18641. this.bi_valid = 0;
  18642. /* Number of valid bits in bi_buf. All bits above the last valid bit
  18643. * are always zero.
  18644. */
  18645. // Used for window memory init. We safely ignore it for JS. That makes
  18646. // sense only for pointers and memory check tools.
  18647. //this.high_water = 0;
  18648. /* High water mark offset in window for initialized bytes -- bytes above
  18649. * this are set to zero in order to avoid memory check warnings when
  18650. * longest match routines access bytes past the input. This is then
  18651. * updated to the new high water mark.
  18652. */
  18653. }
  18654. function deflateResetKeep(strm) {
  18655. var s;
  18656. if (!strm || !strm.state) {
  18657. return err(strm, Z_STREAM_ERROR);
  18658. }
  18659. strm.total_in = strm.total_out = 0;
  18660. strm.data_type = Z_UNKNOWN;
  18661. s = strm.state;
  18662. s.pending = 0;
  18663. s.pending_out = 0;
  18664. if (s.wrap < 0) {
  18665. s.wrap = -s.wrap;
  18666. /* was made negative by deflate(..., Z_FINISH); */
  18667. }
  18668. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  18669. strm.adler = (s.wrap === 2) ?
  18670. 0 // crc32(0, Z_NULL, 0)
  18671. :
  18672. 1; // adler32(0, Z_NULL, 0)
  18673. s.last_flush = Z_NO_FLUSH;
  18674. trees._tr_init(s);
  18675. return Z_OK;
  18676. }
  18677. function deflateReset(strm) {
  18678. var ret = deflateResetKeep(strm);
  18679. if (ret === Z_OK) {
  18680. lm_init(strm.state);
  18681. }
  18682. return ret;
  18683. }
  18684. function deflateSetHeader(strm, head) {
  18685. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18686. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  18687. strm.state.gzhead = head;
  18688. return Z_OK;
  18689. }
  18690. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  18691. if (!strm) { // === Z_NULL
  18692. return Z_STREAM_ERROR;
  18693. }
  18694. var wrap = 1;
  18695. if (level === Z_DEFAULT_COMPRESSION) {
  18696. level = 6;
  18697. }
  18698. if (windowBits < 0) { /* suppress zlib wrapper */
  18699. wrap = 0;
  18700. windowBits = -windowBits;
  18701. }
  18702. else if (windowBits > 15) {
  18703. wrap = 2; /* write gzip wrapper instead */
  18704. windowBits -= 16;
  18705. }
  18706. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  18707. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  18708. strategy < 0 || strategy > Z_FIXED) {
  18709. return err(strm, Z_STREAM_ERROR);
  18710. }
  18711. if (windowBits === 8) {
  18712. windowBits = 9;
  18713. }
  18714. /* until 256-byte window bug fixed */
  18715. var s = new DeflateState();
  18716. strm.state = s;
  18717. s.strm = strm;
  18718. s.wrap = wrap;
  18719. s.gzhead = null;
  18720. s.w_bits = windowBits;
  18721. s.w_size = 1 << s.w_bits;
  18722. s.w_mask = s.w_size - 1;
  18723. s.hash_bits = memLevel + 7;
  18724. s.hash_size = 1 << s.hash_bits;
  18725. s.hash_mask = s.hash_size - 1;
  18726. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  18727. s.window = new utils.Buf8(s.w_size * 2);
  18728. s.head = new utils.Buf16(s.hash_size);
  18729. s.prev = new utils.Buf16(s.w_size);
  18730. // Don't need mem init magic for JS.
  18731. //s.high_water = 0; /* nothing written to s->window yet */
  18732. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  18733. s.pending_buf_size = s.lit_bufsize * 4;
  18734. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  18735. s.d_buf = s.lit_bufsize >> 1;
  18736. s.l_buf = (1 + 2) * s.lit_bufsize;
  18737. s.level = level;
  18738. s.strategy = strategy;
  18739. s.method = method;
  18740. return deflateReset(strm);
  18741. }
  18742. function deflateInit(strm, level) {
  18743. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  18744. }
  18745. function deflate(strm, flush) {
  18746. var old_flush, s;
  18747. var beg, val; // for gzip header write only
  18748. if (!strm || !strm.state ||
  18749. flush > Z_BLOCK || flush < 0) {
  18750. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  18751. }
  18752. s = strm.state;
  18753. if (!strm.output ||
  18754. (!strm.input && strm.avail_in !== 0) ||
  18755. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  18756. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  18757. }
  18758. s.strm = strm; /* just in case */
  18759. old_flush = s.last_flush;
  18760. s.last_flush = flush;
  18761. /* Write the header */
  18762. if (s.status === INIT_STATE) {
  18763. if (s.wrap === 2) { // GZIP header
  18764. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  18765. put_byte(s, 31);
  18766. put_byte(s, 139);
  18767. put_byte(s, 8);
  18768. if (!s.gzhead) { // s->gzhead == Z_NULL
  18769. put_byte(s, 0);
  18770. put_byte(s, 0);
  18771. put_byte(s, 0);
  18772. put_byte(s, 0);
  18773. put_byte(s, 0);
  18774. put_byte(s, s.level === 9 ? 2 :
  18775. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  18776. 4 : 0));
  18777. put_byte(s, OS_CODE);
  18778. s.status = BUSY_STATE;
  18779. }
  18780. else {
  18781. put_byte(s, (s.gzhead.text ? 1 : 0) +
  18782. (s.gzhead.hcrc ? 2 : 0) +
  18783. (!s.gzhead.extra ? 0 : 4) +
  18784. (!s.gzhead.name ? 0 : 8) +
  18785. (!s.gzhead.comment ? 0 : 16)
  18786. );
  18787. put_byte(s, s.gzhead.time & 0xff);
  18788. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  18789. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  18790. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  18791. put_byte(s, s.level === 9 ? 2 :
  18792. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  18793. 4 : 0));
  18794. put_byte(s, s.gzhead.os & 0xff);
  18795. if (s.gzhead.extra && s.gzhead.extra.length) {
  18796. put_byte(s, s.gzhead.extra.length & 0xff);
  18797. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  18798. }
  18799. if (s.gzhead.hcrc) {
  18800. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  18801. }
  18802. s.gzindex = 0;
  18803. s.status = EXTRA_STATE;
  18804. }
  18805. }
  18806. else // DEFLATE header
  18807. {
  18808. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  18809. var level_flags = -1;
  18810. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  18811. level_flags = 0;
  18812. } else if (s.level < 6) {
  18813. level_flags = 1;
  18814. } else if (s.level === 6) {
  18815. level_flags = 2;
  18816. } else {
  18817. level_flags = 3;
  18818. }
  18819. header |= (level_flags << 6);
  18820. if (s.strstart !== 0) { header |= PRESET_DICT; }
  18821. header += 31 - (header % 31);
  18822. s.status = BUSY_STATE;
  18823. putShortMSB(s, header);
  18824. /* Save the adler32 of the preset dictionary: */
  18825. if (s.strstart !== 0) {
  18826. putShortMSB(s, strm.adler >>> 16);
  18827. putShortMSB(s, strm.adler & 0xffff);
  18828. }
  18829. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  18830. }
  18831. }
  18832. //#ifdef GZIP
  18833. if (s.status === EXTRA_STATE) {
  18834. if (s.gzhead.extra/* != Z_NULL*/) {
  18835. beg = s.pending; /* start of bytes to update crc */
  18836. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  18837. if (s.pending === s.pending_buf_size) {
  18838. if (s.gzhead.hcrc && s.pending > beg) {
  18839. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18840. }
  18841. flush_pending(strm);
  18842. beg = s.pending;
  18843. if (s.pending === s.pending_buf_size) {
  18844. break;
  18845. }
  18846. }
  18847. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  18848. s.gzindex++;
  18849. }
  18850. if (s.gzhead.hcrc && s.pending > beg) {
  18851. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18852. }
  18853. if (s.gzindex === s.gzhead.extra.length) {
  18854. s.gzindex = 0;
  18855. s.status = NAME_STATE;
  18856. }
  18857. }
  18858. else {
  18859. s.status = NAME_STATE;
  18860. }
  18861. }
  18862. if (s.status === NAME_STATE) {
  18863. if (s.gzhead.name/* != Z_NULL*/) {
  18864. beg = s.pending; /* start of bytes to update crc */
  18865. //int val;
  18866. do {
  18867. if (s.pending === s.pending_buf_size) {
  18868. if (s.gzhead.hcrc && s.pending > beg) {
  18869. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18870. }
  18871. flush_pending(strm);
  18872. beg = s.pending;
  18873. if (s.pending === s.pending_buf_size) {
  18874. val = 1;
  18875. break;
  18876. }
  18877. }
  18878. // JS specific: little magic to add zero terminator to end of string
  18879. if (s.gzindex < s.gzhead.name.length) {
  18880. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  18881. } else {
  18882. val = 0;
  18883. }
  18884. put_byte(s, val);
  18885. } while (val !== 0);
  18886. if (s.gzhead.hcrc && s.pending > beg){
  18887. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18888. }
  18889. if (val === 0) {
  18890. s.gzindex = 0;
  18891. s.status = COMMENT_STATE;
  18892. }
  18893. }
  18894. else {
  18895. s.status = COMMENT_STATE;
  18896. }
  18897. }
  18898. if (s.status === COMMENT_STATE) {
  18899. if (s.gzhead.comment/* != Z_NULL*/) {
  18900. beg = s.pending; /* start of bytes to update crc */
  18901. //int val;
  18902. do {
  18903. if (s.pending === s.pending_buf_size) {
  18904. if (s.gzhead.hcrc && s.pending > beg) {
  18905. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18906. }
  18907. flush_pending(strm);
  18908. beg = s.pending;
  18909. if (s.pending === s.pending_buf_size) {
  18910. val = 1;
  18911. break;
  18912. }
  18913. }
  18914. // JS specific: little magic to add zero terminator to end of string
  18915. if (s.gzindex < s.gzhead.comment.length) {
  18916. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  18917. } else {
  18918. val = 0;
  18919. }
  18920. put_byte(s, val);
  18921. } while (val !== 0);
  18922. if (s.gzhead.hcrc && s.pending > beg) {
  18923. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  18924. }
  18925. if (val === 0) {
  18926. s.status = HCRC_STATE;
  18927. }
  18928. }
  18929. else {
  18930. s.status = HCRC_STATE;
  18931. }
  18932. }
  18933. if (s.status === HCRC_STATE) {
  18934. if (s.gzhead.hcrc) {
  18935. if (s.pending + 2 > s.pending_buf_size) {
  18936. flush_pending(strm);
  18937. }
  18938. if (s.pending + 2 <= s.pending_buf_size) {
  18939. put_byte(s, strm.adler & 0xff);
  18940. put_byte(s, (strm.adler >> 8) & 0xff);
  18941. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  18942. s.status = BUSY_STATE;
  18943. }
  18944. }
  18945. else {
  18946. s.status = BUSY_STATE;
  18947. }
  18948. }
  18949. //#endif
  18950. /* Flush as much pending output as possible */
  18951. if (s.pending !== 0) {
  18952. flush_pending(strm);
  18953. if (strm.avail_out === 0) {
  18954. /* Since avail_out is 0, deflate will be called again with
  18955. * more output space, but possibly with both pending and
  18956. * avail_in equal to zero. There won't be anything to do,
  18957. * but this is not an error situation so make sure we
  18958. * return OK instead of BUF_ERROR at next call of deflate:
  18959. */
  18960. s.last_flush = -1;
  18961. return Z_OK;
  18962. }
  18963. /* Make sure there is something to do and avoid duplicate consecutive
  18964. * flushes. For repeated and useless calls with Z_FINISH, we keep
  18965. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  18966. */
  18967. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  18968. flush !== Z_FINISH) {
  18969. return err(strm, Z_BUF_ERROR);
  18970. }
  18971. /* User must not provide more input after the first FINISH: */
  18972. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  18973. return err(strm, Z_BUF_ERROR);
  18974. }
  18975. /* Start a new block or continue the current one.
  18976. */
  18977. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  18978. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  18979. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  18980. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  18981. configuration_table[s.level].func(s, flush));
  18982. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  18983. s.status = FINISH_STATE;
  18984. }
  18985. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  18986. if (strm.avail_out === 0) {
  18987. s.last_flush = -1;
  18988. /* avoid BUF_ERROR next call, see above */
  18989. }
  18990. return Z_OK;
  18991. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  18992. * of deflate should use the same flush parameter to make sure
  18993. * that the flush is complete. So we don't have to output an
  18994. * empty block here, this will be done at next call. This also
  18995. * ensures that for a very small output buffer, we emit at most
  18996. * one empty block.
  18997. */
  18998. }
  18999. if (bstate === BS_BLOCK_DONE) {
  19000. if (flush === Z_PARTIAL_FLUSH) {
  19001. trees._tr_align(s);
  19002. }
  19003. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  19004. trees._tr_stored_block(s, 0, 0, false);
  19005. /* For a full flush, this empty block will be recognized
  19006. * as a special marker by inflate_sync().
  19007. */
  19008. if (flush === Z_FULL_FLUSH) {
  19009. /*** CLEAR_HASH(s); ***/ /* forget history */
  19010. zero(s.head); // Fill with NIL (= 0);
  19011. if (s.lookahead === 0) {
  19012. s.strstart = 0;
  19013. s.block_start = 0;
  19014. s.insert = 0;
  19015. }
  19016. }
  19017. }
  19018. flush_pending(strm);
  19019. if (strm.avail_out === 0) {
  19020. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  19021. return Z_OK;
  19022. }
  19023. }
  19024. }
  19025. //Assert(strm->avail_out > 0, "bug2");
  19026. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  19027. if (flush !== Z_FINISH) { return Z_OK; }
  19028. if (s.wrap <= 0) { return Z_STREAM_END; }
  19029. /* Write the trailer */
  19030. if (s.wrap === 2) {
  19031. put_byte(s, strm.adler & 0xff);
  19032. put_byte(s, (strm.adler >> 8) & 0xff);
  19033. put_byte(s, (strm.adler >> 16) & 0xff);
  19034. put_byte(s, (strm.adler >> 24) & 0xff);
  19035. put_byte(s, strm.total_in & 0xff);
  19036. put_byte(s, (strm.total_in >> 8) & 0xff);
  19037. put_byte(s, (strm.total_in >> 16) & 0xff);
  19038. put_byte(s, (strm.total_in >> 24) & 0xff);
  19039. }
  19040. else
  19041. {
  19042. putShortMSB(s, strm.adler >>> 16);
  19043. putShortMSB(s, strm.adler & 0xffff);
  19044. }
  19045. flush_pending(strm);
  19046. /* If avail_out is zero, the application will call deflate again
  19047. * to flush the rest.
  19048. */
  19049. if (s.wrap > 0) { s.wrap = -s.wrap; }
  19050. /* write the trailer only once! */
  19051. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  19052. }
  19053. function deflateEnd(strm) {
  19054. var status;
  19055. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  19056. return Z_STREAM_ERROR;
  19057. }
  19058. status = strm.state.status;
  19059. if (status !== INIT_STATE &&
  19060. status !== EXTRA_STATE &&
  19061. status !== NAME_STATE &&
  19062. status !== COMMENT_STATE &&
  19063. status !== HCRC_STATE &&
  19064. status !== BUSY_STATE &&
  19065. status !== FINISH_STATE
  19066. ) {
  19067. return err(strm, Z_STREAM_ERROR);
  19068. }
  19069. strm.state = null;
  19070. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  19071. }
  19072. /* =========================================================================
  19073. * Copy the source state to the destination state
  19074. */
  19075. //function deflateCopy(dest, source) {
  19076. //
  19077. //}
  19078. exports.deflateInit = deflateInit;
  19079. exports.deflateInit2 = deflateInit2;
  19080. exports.deflateReset = deflateReset;
  19081. exports.deflateResetKeep = deflateResetKeep;
  19082. exports.deflateSetHeader = deflateSetHeader;
  19083. exports.deflate = deflate;
  19084. exports.deflateEnd = deflateEnd;
  19085. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  19086. /* Not implemented
  19087. exports.deflateBound = deflateBound;
  19088. exports.deflateCopy = deflateCopy;
  19089. exports.deflateSetDictionary = deflateSetDictionary;
  19090. exports.deflateParams = deflateParams;
  19091. exports.deflatePending = deflatePending;
  19092. exports.deflatePrime = deflatePrime;
  19093. exports.deflateTune = deflateTune;
  19094. */
  19095. },{"../utils/common":65,"./adler32":67,"./crc32":69,"./messages":75,"./trees":76}],71:[function(require,module,exports){
  19096. 'use strict';
  19097. function GZheader() {
  19098. /* true if compressed data believed to be text */
  19099. this.text = 0;
  19100. /* modification time */
  19101. this.time = 0;
  19102. /* extra flags (not used when writing a gzip file) */
  19103. this.xflags = 0;
  19104. /* operating system */
  19105. this.os = 0;
  19106. /* pointer to extra field or Z_NULL if none */
  19107. this.extra = null;
  19108. /* extra field length (valid if extra != Z_NULL) */
  19109. this.extra_len = 0; // Actually, we don't need it in JS,
  19110. // but leave for few code modifications
  19111. //
  19112. // Setup limits is not necessary because in js we should not preallocate memory
  19113. // for inflate use constant limit in 65536 bytes
  19114. //
  19115. /* space at extra (only when reading header) */
  19116. // this.extra_max = 0;
  19117. /* pointer to zero-terminated file name or Z_NULL */
  19118. this.name = '';
  19119. /* space at name (only when reading header) */
  19120. // this.name_max = 0;
  19121. /* pointer to zero-terminated comment or Z_NULL */
  19122. this.comment = '';
  19123. /* space at comment (only when reading header) */
  19124. // this.comm_max = 0;
  19125. /* true if there was or will be a header crc */
  19126. this.hcrc = 0;
  19127. /* true when done reading gzip header (not used when writing a gzip file) */
  19128. this.done = false;
  19129. }
  19130. module.exports = GZheader;
  19131. },{}],72:[function(require,module,exports){
  19132. 'use strict';
  19133. // See state defs from inflate.js
  19134. var BAD = 30; /* got a data error -- remain here until reset */
  19135. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19136. /*
  19137. Decode literal, length, and distance codes and write out the resulting
  19138. literal and match bytes until either not enough input or output is
  19139. available, an end-of-block is encountered, or a data error is encountered.
  19140. When large enough input and output buffers are supplied to inflate(), for
  19141. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  19142. inflate execution time is spent in this routine.
  19143. Entry assumptions:
  19144. state.mode === LEN
  19145. strm.avail_in >= 6
  19146. strm.avail_out >= 258
  19147. start >= strm.avail_out
  19148. state.bits < 8
  19149. On return, state.mode is one of:
  19150. LEN -- ran out of enough output space or enough available input
  19151. TYPE -- reached end of block code, inflate() to interpret next block
  19152. BAD -- error in block data
  19153. Notes:
  19154. - The maximum input bits used by a length/distance pair is 15 bits for the
  19155. length code, 5 bits for the length extra, 15 bits for the distance code,
  19156. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  19157. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  19158. checking for available input while decoding.
  19159. - The maximum bytes that a single length/distance pair can output is 258
  19160. bytes, which is the maximum length that can be coded. inflate_fast()
  19161. requires strm.avail_out >= 258 for each loop to avoid checking for
  19162. output space.
  19163. */
  19164. module.exports = function inflate_fast(strm, start) {
  19165. var state;
  19166. var _in; /* local strm.input */
  19167. var last; /* have enough input while in < last */
  19168. var _out; /* local strm.output */
  19169. var beg; /* inflate()'s initial strm.output */
  19170. var end; /* while out < end, enough space available */
  19171. //#ifdef INFLATE_STRICT
  19172. var dmax; /* maximum distance from zlib header */
  19173. //#endif
  19174. var wsize; /* window size or zero if not using window */
  19175. var whave; /* valid bytes in the window */
  19176. var wnext; /* window write index */
  19177. var window; /* allocated sliding window, if wsize != 0 */
  19178. var hold; /* local strm.hold */
  19179. var bits; /* local strm.bits */
  19180. var lcode; /* local strm.lencode */
  19181. var dcode; /* local strm.distcode */
  19182. var lmask; /* mask for first level of length codes */
  19183. var dmask; /* mask for first level of distance codes */
  19184. var here; /* retrieved table entry */
  19185. var op; /* code bits, operation, extra bits, or */
  19186. /* window position, window bytes to copy */
  19187. var len; /* match length, unused bytes */
  19188. var dist; /* match distance */
  19189. var from; /* where to copy match from */
  19190. var from_source;
  19191. var input, output; // JS specific, because we have no pointers
  19192. /* copy state to local variables */
  19193. state = strm.state;
  19194. //here = state.here;
  19195. _in = strm.next_in;
  19196. input = strm.input;
  19197. last = _in + (strm.avail_in - 5);
  19198. _out = strm.next_out;
  19199. output = strm.output;
  19200. beg = _out - (start - strm.avail_out);
  19201. end = _out + (strm.avail_out - 257);
  19202. //#ifdef INFLATE_STRICT
  19203. dmax = state.dmax;
  19204. //#endif
  19205. wsize = state.wsize;
  19206. whave = state.whave;
  19207. wnext = state.wnext;
  19208. window = state.window;
  19209. hold = state.hold;
  19210. bits = state.bits;
  19211. lcode = state.lencode;
  19212. dcode = state.distcode;
  19213. lmask = (1 << state.lenbits) - 1;
  19214. dmask = (1 << state.distbits) - 1;
  19215. /* decode literals and length/distances until end-of-block or not enough
  19216. input data or output space */
  19217. top:
  19218. do {
  19219. if (bits < 15) {
  19220. hold += input[_in++] << bits;
  19221. bits += 8;
  19222. hold += input[_in++] << bits;
  19223. bits += 8;
  19224. }
  19225. here = lcode[hold & lmask];
  19226. dolen:
  19227. for (;;) { // Goto emulation
  19228. op = here >>> 24/*here.bits*/;
  19229. hold >>>= op;
  19230. bits -= op;
  19231. op = (here >>> 16) & 0xff/*here.op*/;
  19232. if (op === 0) { /* literal */
  19233. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  19234. // "inflate: literal '%c'\n" :
  19235. // "inflate: literal 0x%02x\n", here.val));
  19236. output[_out++] = here & 0xffff/*here.val*/;
  19237. }
  19238. else if (op & 16) { /* length base */
  19239. len = here & 0xffff/*here.val*/;
  19240. op &= 15; /* number of extra bits */
  19241. if (op) {
  19242. if (bits < op) {
  19243. hold += input[_in++] << bits;
  19244. bits += 8;
  19245. }
  19246. len += hold & ((1 << op) - 1);
  19247. hold >>>= op;
  19248. bits -= op;
  19249. }
  19250. //Tracevv((stderr, "inflate: length %u\n", len));
  19251. if (bits < 15) {
  19252. hold += input[_in++] << bits;
  19253. bits += 8;
  19254. hold += input[_in++] << bits;
  19255. bits += 8;
  19256. }
  19257. here = dcode[hold & dmask];
  19258. dodist:
  19259. for (;;) { // goto emulation
  19260. op = here >>> 24/*here.bits*/;
  19261. hold >>>= op;
  19262. bits -= op;
  19263. op = (here >>> 16) & 0xff/*here.op*/;
  19264. if (op & 16) { /* distance base */
  19265. dist = here & 0xffff/*here.val*/;
  19266. op &= 15; /* number of extra bits */
  19267. if (bits < op) {
  19268. hold += input[_in++] << bits;
  19269. bits += 8;
  19270. if (bits < op) {
  19271. hold += input[_in++] << bits;
  19272. bits += 8;
  19273. }
  19274. }
  19275. dist += hold & ((1 << op) - 1);
  19276. //#ifdef INFLATE_STRICT
  19277. if (dist > dmax) {
  19278. strm.msg = 'invalid distance too far back';
  19279. state.mode = BAD;
  19280. break top;
  19281. }
  19282. //#endif
  19283. hold >>>= op;
  19284. bits -= op;
  19285. //Tracevv((stderr, "inflate: distance %u\n", dist));
  19286. op = _out - beg; /* max distance in output */
  19287. if (dist > op) { /* see if copy from window */
  19288. op = dist - op; /* distance back in window */
  19289. if (op > whave) {
  19290. if (state.sane) {
  19291. strm.msg = 'invalid distance too far back';
  19292. state.mode = BAD;
  19293. break top;
  19294. }
  19295. // (!) This block is disabled in zlib defailts,
  19296. // don't enable it for binary compatibility
  19297. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  19298. // if (len <= op - whave) {
  19299. // do {
  19300. // output[_out++] = 0;
  19301. // } while (--len);
  19302. // continue top;
  19303. // }
  19304. // len -= op - whave;
  19305. // do {
  19306. // output[_out++] = 0;
  19307. // } while (--op > whave);
  19308. // if (op === 0) {
  19309. // from = _out - dist;
  19310. // do {
  19311. // output[_out++] = output[from++];
  19312. // } while (--len);
  19313. // continue top;
  19314. // }
  19315. //#endif
  19316. }
  19317. from = 0; // window index
  19318. from_source = window;
  19319. if (wnext === 0) { /* very common case */
  19320. from += wsize - op;
  19321. if (op < len) { /* some from window */
  19322. len -= op;
  19323. do {
  19324. output[_out++] = window[from++];
  19325. } while (--op);
  19326. from = _out - dist; /* rest from output */
  19327. from_source = output;
  19328. }
  19329. }
  19330. else if (wnext < op) { /* wrap around window */
  19331. from += wsize + wnext - op;
  19332. op -= wnext;
  19333. if (op < len) { /* some from end of window */
  19334. len -= op;
  19335. do {
  19336. output[_out++] = window[from++];
  19337. } while (--op);
  19338. from = 0;
  19339. if (wnext < len) { /* some from start of window */
  19340. op = wnext;
  19341. len -= op;
  19342. do {
  19343. output[_out++] = window[from++];
  19344. } while (--op);
  19345. from = _out - dist; /* rest from output */
  19346. from_source = output;
  19347. }
  19348. }
  19349. }
  19350. else { /* contiguous in window */
  19351. from += wnext - op;
  19352. if (op < len) { /* some from window */
  19353. len -= op;
  19354. do {
  19355. output[_out++] = window[from++];
  19356. } while (--op);
  19357. from = _out - dist; /* rest from output */
  19358. from_source = output;
  19359. }
  19360. }
  19361. while (len > 2) {
  19362. output[_out++] = from_source[from++];
  19363. output[_out++] = from_source[from++];
  19364. output[_out++] = from_source[from++];
  19365. len -= 3;
  19366. }
  19367. if (len) {
  19368. output[_out++] = from_source[from++];
  19369. if (len > 1) {
  19370. output[_out++] = from_source[from++];
  19371. }
  19372. }
  19373. }
  19374. else {
  19375. from = _out - dist; /* copy direct from output */
  19376. do { /* minimum length is three */
  19377. output[_out++] = output[from++];
  19378. output[_out++] = output[from++];
  19379. output[_out++] = output[from++];
  19380. len -= 3;
  19381. } while (len > 2);
  19382. if (len) {
  19383. output[_out++] = output[from++];
  19384. if (len > 1) {
  19385. output[_out++] = output[from++];
  19386. }
  19387. }
  19388. }
  19389. }
  19390. else if ((op & 64) === 0) { /* 2nd level distance code */
  19391. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19392. continue dodist;
  19393. }
  19394. else {
  19395. strm.msg = 'invalid distance code';
  19396. state.mode = BAD;
  19397. break top;
  19398. }
  19399. break; // need to emulate goto via "continue"
  19400. }
  19401. }
  19402. else if ((op & 64) === 0) { /* 2nd level length code */
  19403. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19404. continue dolen;
  19405. }
  19406. else if (op & 32) { /* end-of-block */
  19407. //Tracevv((stderr, "inflate: end of block\n"));
  19408. state.mode = TYPE;
  19409. break top;
  19410. }
  19411. else {
  19412. strm.msg = 'invalid literal/length code';
  19413. state.mode = BAD;
  19414. break top;
  19415. }
  19416. break; // need to emulate goto via "continue"
  19417. }
  19418. } while (_in < last && _out < end);
  19419. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  19420. len = bits >> 3;
  19421. _in -= len;
  19422. bits -= len << 3;
  19423. hold &= (1 << bits) - 1;
  19424. /* update state and return */
  19425. strm.next_in = _in;
  19426. strm.next_out = _out;
  19427. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  19428. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  19429. state.hold = hold;
  19430. state.bits = bits;
  19431. return;
  19432. };
  19433. },{}],73:[function(require,module,exports){
  19434. 'use strict';
  19435. var utils = require('../utils/common');
  19436. var adler32 = require('./adler32');
  19437. var crc32 = require('./crc32');
  19438. var inflate_fast = require('./inffast');
  19439. var inflate_table = require('./inftrees');
  19440. var CODES = 0;
  19441. var LENS = 1;
  19442. var DISTS = 2;
  19443. /* Public constants ==========================================================*/
  19444. /* ===========================================================================*/
  19445. /* Allowed flush values; see deflate() and inflate() below for details */
  19446. //var Z_NO_FLUSH = 0;
  19447. //var Z_PARTIAL_FLUSH = 1;
  19448. //var Z_SYNC_FLUSH = 2;
  19449. //var Z_FULL_FLUSH = 3;
  19450. var Z_FINISH = 4;
  19451. var Z_BLOCK = 5;
  19452. var Z_TREES = 6;
  19453. /* Return codes for the compression/decompression functions. Negative values
  19454. * are errors, positive values are used for special but normal events.
  19455. */
  19456. var Z_OK = 0;
  19457. var Z_STREAM_END = 1;
  19458. var Z_NEED_DICT = 2;
  19459. //var Z_ERRNO = -1;
  19460. var Z_STREAM_ERROR = -2;
  19461. var Z_DATA_ERROR = -3;
  19462. var Z_MEM_ERROR = -4;
  19463. var Z_BUF_ERROR = -5;
  19464. //var Z_VERSION_ERROR = -6;
  19465. /* The deflate compression method */
  19466. var Z_DEFLATED = 8;
  19467. /* STATES ====================================================================*/
  19468. /* ===========================================================================*/
  19469. var HEAD = 1; /* i: waiting for magic header */
  19470. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  19471. var TIME = 3; /* i: waiting for modification time (gzip) */
  19472. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  19473. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  19474. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  19475. var NAME = 7; /* i: waiting for end of file name (gzip) */
  19476. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  19477. var HCRC = 9; /* i: waiting for header crc (gzip) */
  19478. var DICTID = 10; /* i: waiting for dictionary check value */
  19479. var DICT = 11; /* waiting for inflateSetDictionary() call */
  19480. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19481. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  19482. var STORED = 14; /* i: waiting for stored size (length and complement) */
  19483. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  19484. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  19485. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  19486. var LENLENS = 18; /* i: waiting for code length code lengths */
  19487. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  19488. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  19489. var LEN = 21; /* i: waiting for length/lit/eob code */
  19490. var LENEXT = 22; /* i: waiting for length extra bits */
  19491. var DIST = 23; /* i: waiting for distance code */
  19492. var DISTEXT = 24; /* i: waiting for distance extra bits */
  19493. var MATCH = 25; /* o: waiting for output space to copy string */
  19494. var LIT = 26; /* o: waiting for output space to write literal */
  19495. var CHECK = 27; /* i: waiting for 32-bit check value */
  19496. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  19497. var DONE = 29; /* finished check, done -- remain here until reset */
  19498. var BAD = 30; /* got a data error -- remain here until reset */
  19499. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  19500. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  19501. /* ===========================================================================*/
  19502. var ENOUGH_LENS = 852;
  19503. var ENOUGH_DISTS = 592;
  19504. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  19505. var MAX_WBITS = 15;
  19506. /* 32K LZ77 window */
  19507. var DEF_WBITS = MAX_WBITS;
  19508. function ZSWAP32(q) {
  19509. return (((q >>> 24) & 0xff) +
  19510. ((q >>> 8) & 0xff00) +
  19511. ((q & 0xff00) << 8) +
  19512. ((q & 0xff) << 24));
  19513. }
  19514. function InflateState() {
  19515. this.mode = 0; /* current inflate mode */
  19516. this.last = false; /* true if processing last block */
  19517. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  19518. this.havedict = false; /* true if dictionary provided */
  19519. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  19520. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  19521. this.check = 0; /* protected copy of check value */
  19522. this.total = 0; /* protected copy of output count */
  19523. // TODO: may be {}
  19524. this.head = null; /* where to save gzip header information */
  19525. /* sliding window */
  19526. this.wbits = 0; /* log base 2 of requested window size */
  19527. this.wsize = 0; /* window size or zero if not using window */
  19528. this.whave = 0; /* valid bytes in the window */
  19529. this.wnext = 0; /* window write index */
  19530. this.window = null; /* allocated sliding window, if needed */
  19531. /* bit accumulator */
  19532. this.hold = 0; /* input bit accumulator */
  19533. this.bits = 0; /* number of bits in "in" */
  19534. /* for string and stored block copying */
  19535. this.length = 0; /* literal or length of data to copy */
  19536. this.offset = 0; /* distance back to copy string from */
  19537. /* for table and code decoding */
  19538. this.extra = 0; /* extra bits needed */
  19539. /* fixed and dynamic code tables */
  19540. this.lencode = null; /* starting table for length/literal codes */
  19541. this.distcode = null; /* starting table for distance codes */
  19542. this.lenbits = 0; /* index bits for lencode */
  19543. this.distbits = 0; /* index bits for distcode */
  19544. /* dynamic table building */
  19545. this.ncode = 0; /* number of code length code lengths */
  19546. this.nlen = 0; /* number of length code lengths */
  19547. this.ndist = 0; /* number of distance code lengths */
  19548. this.have = 0; /* number of code lengths in lens[] */
  19549. this.next = null; /* next available space in codes[] */
  19550. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  19551. this.work = new utils.Buf16(288); /* work area for code table building */
  19552. /*
  19553. because we don't have pointers in js, we use lencode and distcode directly
  19554. as buffers so we don't need codes
  19555. */
  19556. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  19557. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  19558. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  19559. this.sane = 0; /* if false, allow invalid distance too far */
  19560. this.back = 0; /* bits back of last unprocessed length/lit */
  19561. this.was = 0; /* initial length of match */
  19562. }
  19563. function inflateResetKeep(strm) {
  19564. var state;
  19565. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19566. state = strm.state;
  19567. strm.total_in = strm.total_out = state.total = 0;
  19568. strm.msg = ''; /*Z_NULL*/
  19569. if (state.wrap) { /* to support ill-conceived Java test suite */
  19570. strm.adler = state.wrap & 1;
  19571. }
  19572. state.mode = HEAD;
  19573. state.last = 0;
  19574. state.havedict = 0;
  19575. state.dmax = 32768;
  19576. state.head = null/*Z_NULL*/;
  19577. state.hold = 0;
  19578. state.bits = 0;
  19579. //state.lencode = state.distcode = state.next = state.codes;
  19580. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  19581. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  19582. state.sane = 1;
  19583. state.back = -1;
  19584. //Tracev((stderr, "inflate: reset\n"));
  19585. return Z_OK;
  19586. }
  19587. function inflateReset(strm) {
  19588. var state;
  19589. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19590. state = strm.state;
  19591. state.wsize = 0;
  19592. state.whave = 0;
  19593. state.wnext = 0;
  19594. return inflateResetKeep(strm);
  19595. }
  19596. function inflateReset2(strm, windowBits) {
  19597. var wrap;
  19598. var state;
  19599. /* get the state */
  19600. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19601. state = strm.state;
  19602. /* extract wrap request from windowBits parameter */
  19603. if (windowBits < 0) {
  19604. wrap = 0;
  19605. windowBits = -windowBits;
  19606. }
  19607. else {
  19608. wrap = (windowBits >> 4) + 1;
  19609. if (windowBits < 48) {
  19610. windowBits &= 15;
  19611. }
  19612. }
  19613. /* set number of window bits, free window if different */
  19614. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  19615. return Z_STREAM_ERROR;
  19616. }
  19617. if (state.window !== null && state.wbits !== windowBits) {
  19618. state.window = null;
  19619. }
  19620. /* update state and reset the rest of it */
  19621. state.wrap = wrap;
  19622. state.wbits = windowBits;
  19623. return inflateReset(strm);
  19624. }
  19625. function inflateInit2(strm, windowBits) {
  19626. var ret;
  19627. var state;
  19628. if (!strm) { return Z_STREAM_ERROR; }
  19629. //strm.msg = Z_NULL; /* in case we return an error */
  19630. state = new InflateState();
  19631. //if (state === Z_NULL) return Z_MEM_ERROR;
  19632. //Tracev((stderr, "inflate: allocated\n"));
  19633. strm.state = state;
  19634. state.window = null/*Z_NULL*/;
  19635. ret = inflateReset2(strm, windowBits);
  19636. if (ret !== Z_OK) {
  19637. strm.state = null/*Z_NULL*/;
  19638. }
  19639. return ret;
  19640. }
  19641. function inflateInit(strm) {
  19642. return inflateInit2(strm, DEF_WBITS);
  19643. }
  19644. /*
  19645. Return state with length and distance decoding tables and index sizes set to
  19646. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  19647. If BUILDFIXED is defined, then instead this routine builds the tables the
  19648. first time it's called, and returns those tables the first time and
  19649. thereafter. This reduces the size of the code by about 2K bytes, in
  19650. exchange for a little execution time. However, BUILDFIXED should not be
  19651. used for threaded applications, since the rewriting of the tables and virgin
  19652. may not be thread-safe.
  19653. */
  19654. var virgin = true;
  19655. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  19656. function fixedtables(state) {
  19657. /* build fixed huffman tables if first call (may not be thread safe) */
  19658. if (virgin) {
  19659. var sym;
  19660. lenfix = new utils.Buf32(512);
  19661. distfix = new utils.Buf32(32);
  19662. /* literal/length table */
  19663. sym = 0;
  19664. while (sym < 144) { state.lens[sym++] = 8; }
  19665. while (sym < 256) { state.lens[sym++] = 9; }
  19666. while (sym < 280) { state.lens[sym++] = 7; }
  19667. while (sym < 288) { state.lens[sym++] = 8; }
  19668. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  19669. /* distance table */
  19670. sym = 0;
  19671. while (sym < 32) { state.lens[sym++] = 5; }
  19672. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  19673. /* do this just once */
  19674. virgin = false;
  19675. }
  19676. state.lencode = lenfix;
  19677. state.lenbits = 9;
  19678. state.distcode = distfix;
  19679. state.distbits = 5;
  19680. }
  19681. /*
  19682. Update the window with the last wsize (normally 32K) bytes written before
  19683. returning. If window does not exist yet, create it. This is only called
  19684. when a window is already in use, or when output has been written during this
  19685. inflate call, but the end of the deflate stream has not been reached yet.
  19686. It is also called to create a window for dictionary data when a dictionary
  19687. is loaded.
  19688. Providing output buffers larger than 32K to inflate() should provide a speed
  19689. advantage, since only the last 32K of output is copied to the sliding window
  19690. upon return from inflate(), and since all distances after the first 32K of
  19691. output will fall in the output data, making match copies simpler and faster.
  19692. The advantage may be dependent on the size of the processor's data caches.
  19693. */
  19694. function updatewindow(strm, src, end, copy) {
  19695. var dist;
  19696. var state = strm.state;
  19697. /* if it hasn't been done already, allocate space for the window */
  19698. if (state.window === null) {
  19699. state.wsize = 1 << state.wbits;
  19700. state.wnext = 0;
  19701. state.whave = 0;
  19702. state.window = new utils.Buf8(state.wsize);
  19703. }
  19704. /* copy state->wsize or less output bytes into the circular window */
  19705. if (copy >= state.wsize) {
  19706. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  19707. state.wnext = 0;
  19708. state.whave = state.wsize;
  19709. }
  19710. else {
  19711. dist = state.wsize - state.wnext;
  19712. if (dist > copy) {
  19713. dist = copy;
  19714. }
  19715. //zmemcpy(state->window + state->wnext, end - copy, dist);
  19716. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  19717. copy -= dist;
  19718. if (copy) {
  19719. //zmemcpy(state->window, end - copy, copy);
  19720. utils.arraySet(state.window,src, end - copy, copy, 0);
  19721. state.wnext = copy;
  19722. state.whave = state.wsize;
  19723. }
  19724. else {
  19725. state.wnext += dist;
  19726. if (state.wnext === state.wsize) { state.wnext = 0; }
  19727. if (state.whave < state.wsize) { state.whave += dist; }
  19728. }
  19729. }
  19730. return 0;
  19731. }
  19732. function inflate(strm, flush) {
  19733. var state;
  19734. var input, output; // input/output buffers
  19735. var next; /* next input INDEX */
  19736. var put; /* next output INDEX */
  19737. var have, left; /* available input and output */
  19738. var hold; /* bit buffer */
  19739. var bits; /* bits in bit buffer */
  19740. var _in, _out; /* save starting available input and output */
  19741. var copy; /* number of stored or match bytes to copy */
  19742. var from; /* where to copy match bytes from */
  19743. var from_source;
  19744. var here = 0; /* current decoding table entry */
  19745. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  19746. //var last; /* parent table entry */
  19747. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  19748. var len; /* length to copy for repeats, bits to drop */
  19749. var ret; /* return code */
  19750. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  19751. var opts;
  19752. var n; // temporary var for NEED_BITS
  19753. var order = /* permutation of code lengths */
  19754. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  19755. if (!strm || !strm.state || !strm.output ||
  19756. (!strm.input && strm.avail_in !== 0)) {
  19757. return Z_STREAM_ERROR;
  19758. }
  19759. state = strm.state;
  19760. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  19761. //--- LOAD() ---
  19762. put = strm.next_out;
  19763. output = strm.output;
  19764. left = strm.avail_out;
  19765. next = strm.next_in;
  19766. input = strm.input;
  19767. have = strm.avail_in;
  19768. hold = state.hold;
  19769. bits = state.bits;
  19770. //---
  19771. _in = have;
  19772. _out = left;
  19773. ret = Z_OK;
  19774. inf_leave: // goto emulation
  19775. for (;;) {
  19776. switch (state.mode) {
  19777. case HEAD:
  19778. if (state.wrap === 0) {
  19779. state.mode = TYPEDO;
  19780. break;
  19781. }
  19782. //=== NEEDBITS(16);
  19783. while (bits < 16) {
  19784. if (have === 0) { break inf_leave; }
  19785. have--;
  19786. hold += input[next++] << bits;
  19787. bits += 8;
  19788. }
  19789. //===//
  19790. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  19791. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  19792. //=== CRC2(state.check, hold);
  19793. hbuf[0] = hold & 0xff;
  19794. hbuf[1] = (hold >>> 8) & 0xff;
  19795. state.check = crc32(state.check, hbuf, 2, 0);
  19796. //===//
  19797. //=== INITBITS();
  19798. hold = 0;
  19799. bits = 0;
  19800. //===//
  19801. state.mode = FLAGS;
  19802. break;
  19803. }
  19804. state.flags = 0; /* expect zlib header */
  19805. if (state.head) {
  19806. state.head.done = false;
  19807. }
  19808. if (!(state.wrap & 1) || /* check if zlib header allowed */
  19809. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  19810. strm.msg = 'incorrect header check';
  19811. state.mode = BAD;
  19812. break;
  19813. }
  19814. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  19815. strm.msg = 'unknown compression method';
  19816. state.mode = BAD;
  19817. break;
  19818. }
  19819. //--- DROPBITS(4) ---//
  19820. hold >>>= 4;
  19821. bits -= 4;
  19822. //---//
  19823. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  19824. if (state.wbits === 0) {
  19825. state.wbits = len;
  19826. }
  19827. else if (len > state.wbits) {
  19828. strm.msg = 'invalid window size';
  19829. state.mode = BAD;
  19830. break;
  19831. }
  19832. state.dmax = 1 << len;
  19833. //Tracev((stderr, "inflate: zlib header ok\n"));
  19834. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  19835. state.mode = hold & 0x200 ? DICTID : TYPE;
  19836. //=== INITBITS();
  19837. hold = 0;
  19838. bits = 0;
  19839. //===//
  19840. break;
  19841. case FLAGS:
  19842. //=== NEEDBITS(16); */
  19843. while (bits < 16) {
  19844. if (have === 0) { break inf_leave; }
  19845. have--;
  19846. hold += input[next++] << bits;
  19847. bits += 8;
  19848. }
  19849. //===//
  19850. state.flags = hold;
  19851. if ((state.flags & 0xff) !== Z_DEFLATED) {
  19852. strm.msg = 'unknown compression method';
  19853. state.mode = BAD;
  19854. break;
  19855. }
  19856. if (state.flags & 0xe000) {
  19857. strm.msg = 'unknown header flags set';
  19858. state.mode = BAD;
  19859. break;
  19860. }
  19861. if (state.head) {
  19862. state.head.text = ((hold >> 8) & 1);
  19863. }
  19864. if (state.flags & 0x0200) {
  19865. //=== CRC2(state.check, hold);
  19866. hbuf[0] = hold & 0xff;
  19867. hbuf[1] = (hold >>> 8) & 0xff;
  19868. state.check = crc32(state.check, hbuf, 2, 0);
  19869. //===//
  19870. }
  19871. //=== INITBITS();
  19872. hold = 0;
  19873. bits = 0;
  19874. //===//
  19875. state.mode = TIME;
  19876. /* falls through */
  19877. case TIME:
  19878. //=== NEEDBITS(32); */
  19879. while (bits < 32) {
  19880. if (have === 0) { break inf_leave; }
  19881. have--;
  19882. hold += input[next++] << bits;
  19883. bits += 8;
  19884. }
  19885. //===//
  19886. if (state.head) {
  19887. state.head.time = hold;
  19888. }
  19889. if (state.flags & 0x0200) {
  19890. //=== CRC4(state.check, hold)
  19891. hbuf[0] = hold & 0xff;
  19892. hbuf[1] = (hold >>> 8) & 0xff;
  19893. hbuf[2] = (hold >>> 16) & 0xff;
  19894. hbuf[3] = (hold >>> 24) & 0xff;
  19895. state.check = crc32(state.check, hbuf, 4, 0);
  19896. //===
  19897. }
  19898. //=== INITBITS();
  19899. hold = 0;
  19900. bits = 0;
  19901. //===//
  19902. state.mode = OS;
  19903. /* falls through */
  19904. case OS:
  19905. //=== NEEDBITS(16); */
  19906. while (bits < 16) {
  19907. if (have === 0) { break inf_leave; }
  19908. have--;
  19909. hold += input[next++] << bits;
  19910. bits += 8;
  19911. }
  19912. //===//
  19913. if (state.head) {
  19914. state.head.xflags = (hold & 0xff);
  19915. state.head.os = (hold >> 8);
  19916. }
  19917. if (state.flags & 0x0200) {
  19918. //=== CRC2(state.check, hold);
  19919. hbuf[0] = hold & 0xff;
  19920. hbuf[1] = (hold >>> 8) & 0xff;
  19921. state.check = crc32(state.check, hbuf, 2, 0);
  19922. //===//
  19923. }
  19924. //=== INITBITS();
  19925. hold = 0;
  19926. bits = 0;
  19927. //===//
  19928. state.mode = EXLEN;
  19929. /* falls through */
  19930. case EXLEN:
  19931. if (state.flags & 0x0400) {
  19932. //=== NEEDBITS(16); */
  19933. while (bits < 16) {
  19934. if (have === 0) { break inf_leave; }
  19935. have--;
  19936. hold += input[next++] << bits;
  19937. bits += 8;
  19938. }
  19939. //===//
  19940. state.length = hold;
  19941. if (state.head) {
  19942. state.head.extra_len = hold;
  19943. }
  19944. if (state.flags & 0x0200) {
  19945. //=== CRC2(state.check, hold);
  19946. hbuf[0] = hold & 0xff;
  19947. hbuf[1] = (hold >>> 8) & 0xff;
  19948. state.check = crc32(state.check, hbuf, 2, 0);
  19949. //===//
  19950. }
  19951. //=== INITBITS();
  19952. hold = 0;
  19953. bits = 0;
  19954. //===//
  19955. }
  19956. else if (state.head) {
  19957. state.head.extra = null/*Z_NULL*/;
  19958. }
  19959. state.mode = EXTRA;
  19960. /* falls through */
  19961. case EXTRA:
  19962. if (state.flags & 0x0400) {
  19963. copy = state.length;
  19964. if (copy > have) { copy = have; }
  19965. if (copy) {
  19966. if (state.head) {
  19967. len = state.head.extra_len - state.length;
  19968. if (!state.head.extra) {
  19969. // Use untyped array for more conveniend processing later
  19970. state.head.extra = new Array(state.head.extra_len);
  19971. }
  19972. utils.arraySet(
  19973. state.head.extra,
  19974. input,
  19975. next,
  19976. // extra field is limited to 65536 bytes
  19977. // - no need for additional size check
  19978. copy,
  19979. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  19980. len
  19981. );
  19982. //zmemcpy(state.head.extra + len, next,
  19983. // len + copy > state.head.extra_max ?
  19984. // state.head.extra_max - len : copy);
  19985. }
  19986. if (state.flags & 0x0200) {
  19987. state.check = crc32(state.check, input, copy, next);
  19988. }
  19989. have -= copy;
  19990. next += copy;
  19991. state.length -= copy;
  19992. }
  19993. if (state.length) { break inf_leave; }
  19994. }
  19995. state.length = 0;
  19996. state.mode = NAME;
  19997. /* falls through */
  19998. case NAME:
  19999. if (state.flags & 0x0800) {
  20000. if (have === 0) { break inf_leave; }
  20001. copy = 0;
  20002. do {
  20003. // TODO: 2 or 1 bytes?
  20004. len = input[next + copy++];
  20005. /* use constant limit because in js we should not preallocate memory */
  20006. if (state.head && len &&
  20007. (state.length < 65536 /*state.head.name_max*/)) {
  20008. state.head.name += String.fromCharCode(len);
  20009. }
  20010. } while (len && copy < have);
  20011. if (state.flags & 0x0200) {
  20012. state.check = crc32(state.check, input, copy, next);
  20013. }
  20014. have -= copy;
  20015. next += copy;
  20016. if (len) { break inf_leave; }
  20017. }
  20018. else if (state.head) {
  20019. state.head.name = null;
  20020. }
  20021. state.length = 0;
  20022. state.mode = COMMENT;
  20023. /* falls through */
  20024. case COMMENT:
  20025. if (state.flags & 0x1000) {
  20026. if (have === 0) { break inf_leave; }
  20027. copy = 0;
  20028. do {
  20029. len = input[next + copy++];
  20030. /* use constant limit because in js we should not preallocate memory */
  20031. if (state.head && len &&
  20032. (state.length < 65536 /*state.head.comm_max*/)) {
  20033. state.head.comment += String.fromCharCode(len);
  20034. }
  20035. } while (len && copy < have);
  20036. if (state.flags & 0x0200) {
  20037. state.check = crc32(state.check, input, copy, next);
  20038. }
  20039. have -= copy;
  20040. next += copy;
  20041. if (len) { break inf_leave; }
  20042. }
  20043. else if (state.head) {
  20044. state.head.comment = null;
  20045. }
  20046. state.mode = HCRC;
  20047. /* falls through */
  20048. case HCRC:
  20049. if (state.flags & 0x0200) {
  20050. //=== NEEDBITS(16); */
  20051. while (bits < 16) {
  20052. if (have === 0) { break inf_leave; }
  20053. have--;
  20054. hold += input[next++] << bits;
  20055. bits += 8;
  20056. }
  20057. //===//
  20058. if (hold !== (state.check & 0xffff)) {
  20059. strm.msg = 'header crc mismatch';
  20060. state.mode = BAD;
  20061. break;
  20062. }
  20063. //=== INITBITS();
  20064. hold = 0;
  20065. bits = 0;
  20066. //===//
  20067. }
  20068. if (state.head) {
  20069. state.head.hcrc = ((state.flags >> 9) & 1);
  20070. state.head.done = true;
  20071. }
  20072. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  20073. state.mode = TYPE;
  20074. break;
  20075. case DICTID:
  20076. //=== NEEDBITS(32); */
  20077. while (bits < 32) {
  20078. if (have === 0) { break inf_leave; }
  20079. have--;
  20080. hold += input[next++] << bits;
  20081. bits += 8;
  20082. }
  20083. //===//
  20084. strm.adler = state.check = ZSWAP32(hold);
  20085. //=== INITBITS();
  20086. hold = 0;
  20087. bits = 0;
  20088. //===//
  20089. state.mode = DICT;
  20090. /* falls through */
  20091. case DICT:
  20092. if (state.havedict === 0) {
  20093. //--- RESTORE() ---
  20094. strm.next_out = put;
  20095. strm.avail_out = left;
  20096. strm.next_in = next;
  20097. strm.avail_in = have;
  20098. state.hold = hold;
  20099. state.bits = bits;
  20100. //---
  20101. return Z_NEED_DICT;
  20102. }
  20103. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20104. state.mode = TYPE;
  20105. /* falls through */
  20106. case TYPE:
  20107. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  20108. /* falls through */
  20109. case TYPEDO:
  20110. if (state.last) {
  20111. //--- BYTEBITS() ---//
  20112. hold >>>= bits & 7;
  20113. bits -= bits & 7;
  20114. //---//
  20115. state.mode = CHECK;
  20116. break;
  20117. }
  20118. //=== NEEDBITS(3); */
  20119. while (bits < 3) {
  20120. if (have === 0) { break inf_leave; }
  20121. have--;
  20122. hold += input[next++] << bits;
  20123. bits += 8;
  20124. }
  20125. //===//
  20126. state.last = (hold & 0x01)/*BITS(1)*/;
  20127. //--- DROPBITS(1) ---//
  20128. hold >>>= 1;
  20129. bits -= 1;
  20130. //---//
  20131. switch ((hold & 0x03)/*BITS(2)*/) {
  20132. case 0: /* stored block */
  20133. //Tracev((stderr, "inflate: stored block%s\n",
  20134. // state.last ? " (last)" : ""));
  20135. state.mode = STORED;
  20136. break;
  20137. case 1: /* fixed block */
  20138. fixedtables(state);
  20139. //Tracev((stderr, "inflate: fixed codes block%s\n",
  20140. // state.last ? " (last)" : ""));
  20141. state.mode = LEN_; /* decode codes */
  20142. if (flush === Z_TREES) {
  20143. //--- DROPBITS(2) ---//
  20144. hold >>>= 2;
  20145. bits -= 2;
  20146. //---//
  20147. break inf_leave;
  20148. }
  20149. break;
  20150. case 2: /* dynamic block */
  20151. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  20152. // state.last ? " (last)" : ""));
  20153. state.mode = TABLE;
  20154. break;
  20155. case 3:
  20156. strm.msg = 'invalid block type';
  20157. state.mode = BAD;
  20158. }
  20159. //--- DROPBITS(2) ---//
  20160. hold >>>= 2;
  20161. bits -= 2;
  20162. //---//
  20163. break;
  20164. case STORED:
  20165. //--- BYTEBITS() ---// /* go to byte boundary */
  20166. hold >>>= bits & 7;
  20167. bits -= bits & 7;
  20168. //---//
  20169. //=== NEEDBITS(32); */
  20170. while (bits < 32) {
  20171. if (have === 0) { break inf_leave; }
  20172. have--;
  20173. hold += input[next++] << bits;
  20174. bits += 8;
  20175. }
  20176. //===//
  20177. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  20178. strm.msg = 'invalid stored block lengths';
  20179. state.mode = BAD;
  20180. break;
  20181. }
  20182. state.length = hold & 0xffff;
  20183. //Tracev((stderr, "inflate: stored length %u\n",
  20184. // state.length));
  20185. //=== INITBITS();
  20186. hold = 0;
  20187. bits = 0;
  20188. //===//
  20189. state.mode = COPY_;
  20190. if (flush === Z_TREES) { break inf_leave; }
  20191. /* falls through */
  20192. case COPY_:
  20193. state.mode = COPY;
  20194. /* falls through */
  20195. case COPY:
  20196. copy = state.length;
  20197. if (copy) {
  20198. if (copy > have) { copy = have; }
  20199. if (copy > left) { copy = left; }
  20200. if (copy === 0) { break inf_leave; }
  20201. //--- zmemcpy(put, next, copy); ---
  20202. utils.arraySet(output, input, next, copy, put);
  20203. //---//
  20204. have -= copy;
  20205. next += copy;
  20206. left -= copy;
  20207. put += copy;
  20208. state.length -= copy;
  20209. break;
  20210. }
  20211. //Tracev((stderr, "inflate: stored end\n"));
  20212. state.mode = TYPE;
  20213. break;
  20214. case TABLE:
  20215. //=== NEEDBITS(14); */
  20216. while (bits < 14) {
  20217. if (have === 0) { break inf_leave; }
  20218. have--;
  20219. hold += input[next++] << bits;
  20220. bits += 8;
  20221. }
  20222. //===//
  20223. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  20224. //--- DROPBITS(5) ---//
  20225. hold >>>= 5;
  20226. bits -= 5;
  20227. //---//
  20228. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  20229. //--- DROPBITS(5) ---//
  20230. hold >>>= 5;
  20231. bits -= 5;
  20232. //---//
  20233. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  20234. //--- DROPBITS(4) ---//
  20235. hold >>>= 4;
  20236. bits -= 4;
  20237. //---//
  20238. //#ifndef PKZIP_BUG_WORKAROUND
  20239. if (state.nlen > 286 || state.ndist > 30) {
  20240. strm.msg = 'too many length or distance symbols';
  20241. state.mode = BAD;
  20242. break;
  20243. }
  20244. //#endif
  20245. //Tracev((stderr, "inflate: table sizes ok\n"));
  20246. state.have = 0;
  20247. state.mode = LENLENS;
  20248. /* falls through */
  20249. case LENLENS:
  20250. while (state.have < state.ncode) {
  20251. //=== NEEDBITS(3);
  20252. while (bits < 3) {
  20253. if (have === 0) { break inf_leave; }
  20254. have--;
  20255. hold += input[next++] << bits;
  20256. bits += 8;
  20257. }
  20258. //===//
  20259. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  20260. //--- DROPBITS(3) ---//
  20261. hold >>>= 3;
  20262. bits -= 3;
  20263. //---//
  20264. }
  20265. while (state.have < 19) {
  20266. state.lens[order[state.have++]] = 0;
  20267. }
  20268. // We have separate tables & no pointers. 2 commented lines below not needed.
  20269. //state.next = state.codes;
  20270. //state.lencode = state.next;
  20271. // Switch to use dynamic table
  20272. state.lencode = state.lendyn;
  20273. state.lenbits = 7;
  20274. opts = {bits: state.lenbits};
  20275. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  20276. state.lenbits = opts.bits;
  20277. if (ret) {
  20278. strm.msg = 'invalid code lengths set';
  20279. state.mode = BAD;
  20280. break;
  20281. }
  20282. //Tracev((stderr, "inflate: code lengths ok\n"));
  20283. state.have = 0;
  20284. state.mode = CODELENS;
  20285. /* falls through */
  20286. case CODELENS:
  20287. while (state.have < state.nlen + state.ndist) {
  20288. for (;;) {
  20289. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  20290. here_bits = here >>> 24;
  20291. here_op = (here >>> 16) & 0xff;
  20292. here_val = here & 0xffff;
  20293. if ((here_bits) <= bits) { break; }
  20294. //--- PULLBYTE() ---//
  20295. if (have === 0) { break inf_leave; }
  20296. have--;
  20297. hold += input[next++] << bits;
  20298. bits += 8;
  20299. //---//
  20300. }
  20301. if (here_val < 16) {
  20302. //--- DROPBITS(here.bits) ---//
  20303. hold >>>= here_bits;
  20304. bits -= here_bits;
  20305. //---//
  20306. state.lens[state.have++] = here_val;
  20307. }
  20308. else {
  20309. if (here_val === 16) {
  20310. //=== NEEDBITS(here.bits + 2);
  20311. n = here_bits + 2;
  20312. while (bits < n) {
  20313. if (have === 0) { break inf_leave; }
  20314. have--;
  20315. hold += input[next++] << bits;
  20316. bits += 8;
  20317. }
  20318. //===//
  20319. //--- DROPBITS(here.bits) ---//
  20320. hold >>>= here_bits;
  20321. bits -= here_bits;
  20322. //---//
  20323. if (state.have === 0) {
  20324. strm.msg = 'invalid bit length repeat';
  20325. state.mode = BAD;
  20326. break;
  20327. }
  20328. len = state.lens[state.have - 1];
  20329. copy = 3 + (hold & 0x03);//BITS(2);
  20330. //--- DROPBITS(2) ---//
  20331. hold >>>= 2;
  20332. bits -= 2;
  20333. //---//
  20334. }
  20335. else if (here_val === 17) {
  20336. //=== NEEDBITS(here.bits + 3);
  20337. n = here_bits + 3;
  20338. while (bits < n) {
  20339. if (have === 0) { break inf_leave; }
  20340. have--;
  20341. hold += input[next++] << bits;
  20342. bits += 8;
  20343. }
  20344. //===//
  20345. //--- DROPBITS(here.bits) ---//
  20346. hold >>>= here_bits;
  20347. bits -= here_bits;
  20348. //---//
  20349. len = 0;
  20350. copy = 3 + (hold & 0x07);//BITS(3);
  20351. //--- DROPBITS(3) ---//
  20352. hold >>>= 3;
  20353. bits -= 3;
  20354. //---//
  20355. }
  20356. else {
  20357. //=== NEEDBITS(here.bits + 7);
  20358. n = here_bits + 7;
  20359. while (bits < n) {
  20360. if (have === 0) { break inf_leave; }
  20361. have--;
  20362. hold += input[next++] << bits;
  20363. bits += 8;
  20364. }
  20365. //===//
  20366. //--- DROPBITS(here.bits) ---//
  20367. hold >>>= here_bits;
  20368. bits -= here_bits;
  20369. //---//
  20370. len = 0;
  20371. copy = 11 + (hold & 0x7f);//BITS(7);
  20372. //--- DROPBITS(7) ---//
  20373. hold >>>= 7;
  20374. bits -= 7;
  20375. //---//
  20376. }
  20377. if (state.have + copy > state.nlen + state.ndist) {
  20378. strm.msg = 'invalid bit length repeat';
  20379. state.mode = BAD;
  20380. break;
  20381. }
  20382. while (copy--) {
  20383. state.lens[state.have++] = len;
  20384. }
  20385. }
  20386. }
  20387. /* handle error breaks in while */
  20388. if (state.mode === BAD) { break; }
  20389. /* check for end-of-block code (better have one) */
  20390. if (state.lens[256] === 0) {
  20391. strm.msg = 'invalid code -- missing end-of-block';
  20392. state.mode = BAD;
  20393. break;
  20394. }
  20395. /* build code tables -- note: do not change the lenbits or distbits
  20396. values here (9 and 6) without reading the comments in inftrees.h
  20397. concerning the ENOUGH constants, which depend on those values */
  20398. state.lenbits = 9;
  20399. opts = {bits: state.lenbits};
  20400. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  20401. // We have separate tables & no pointers. 2 commented lines below not needed.
  20402. // state.next_index = opts.table_index;
  20403. state.lenbits = opts.bits;
  20404. // state.lencode = state.next;
  20405. if (ret) {
  20406. strm.msg = 'invalid literal/lengths set';
  20407. state.mode = BAD;
  20408. break;
  20409. }
  20410. state.distbits = 6;
  20411. //state.distcode.copy(state.codes);
  20412. // Switch to use dynamic table
  20413. state.distcode = state.distdyn;
  20414. opts = {bits: state.distbits};
  20415. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  20416. // We have separate tables & no pointers. 2 commented lines below not needed.
  20417. // state.next_index = opts.table_index;
  20418. state.distbits = opts.bits;
  20419. // state.distcode = state.next;
  20420. if (ret) {
  20421. strm.msg = 'invalid distances set';
  20422. state.mode = BAD;
  20423. break;
  20424. }
  20425. //Tracev((stderr, 'inflate: codes ok\n'));
  20426. state.mode = LEN_;
  20427. if (flush === Z_TREES) { break inf_leave; }
  20428. /* falls through */
  20429. case LEN_:
  20430. state.mode = LEN;
  20431. /* falls through */
  20432. case LEN:
  20433. if (have >= 6 && left >= 258) {
  20434. //--- RESTORE() ---
  20435. strm.next_out = put;
  20436. strm.avail_out = left;
  20437. strm.next_in = next;
  20438. strm.avail_in = have;
  20439. state.hold = hold;
  20440. state.bits = bits;
  20441. //---
  20442. inflate_fast(strm, _out);
  20443. //--- LOAD() ---
  20444. put = strm.next_out;
  20445. output = strm.output;
  20446. left = strm.avail_out;
  20447. next = strm.next_in;
  20448. input = strm.input;
  20449. have = strm.avail_in;
  20450. hold = state.hold;
  20451. bits = state.bits;
  20452. //---
  20453. if (state.mode === TYPE) {
  20454. state.back = -1;
  20455. }
  20456. break;
  20457. }
  20458. state.back = 0;
  20459. for (;;) {
  20460. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  20461. here_bits = here >>> 24;
  20462. here_op = (here >>> 16) & 0xff;
  20463. here_val = here & 0xffff;
  20464. if (here_bits <= bits) { break; }
  20465. //--- PULLBYTE() ---//
  20466. if (have === 0) { break inf_leave; }
  20467. have--;
  20468. hold += input[next++] << bits;
  20469. bits += 8;
  20470. //---//
  20471. }
  20472. if (here_op && (here_op & 0xf0) === 0) {
  20473. last_bits = here_bits;
  20474. last_op = here_op;
  20475. last_val = here_val;
  20476. for (;;) {
  20477. here = state.lencode[last_val +
  20478. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20479. here_bits = here >>> 24;
  20480. here_op = (here >>> 16) & 0xff;
  20481. here_val = here & 0xffff;
  20482. if ((last_bits + here_bits) <= bits) { break; }
  20483. //--- PULLBYTE() ---//
  20484. if (have === 0) { break inf_leave; }
  20485. have--;
  20486. hold += input[next++] << bits;
  20487. bits += 8;
  20488. //---//
  20489. }
  20490. //--- DROPBITS(last.bits) ---//
  20491. hold >>>= last_bits;
  20492. bits -= last_bits;
  20493. //---//
  20494. state.back += last_bits;
  20495. }
  20496. //--- DROPBITS(here.bits) ---//
  20497. hold >>>= here_bits;
  20498. bits -= here_bits;
  20499. //---//
  20500. state.back += here_bits;
  20501. state.length = here_val;
  20502. if (here_op === 0) {
  20503. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  20504. // "inflate: literal '%c'\n" :
  20505. // "inflate: literal 0x%02x\n", here.val));
  20506. state.mode = LIT;
  20507. break;
  20508. }
  20509. if (here_op & 32) {
  20510. //Tracevv((stderr, "inflate: end of block\n"));
  20511. state.back = -1;
  20512. state.mode = TYPE;
  20513. break;
  20514. }
  20515. if (here_op & 64) {
  20516. strm.msg = 'invalid literal/length code';
  20517. state.mode = BAD;
  20518. break;
  20519. }
  20520. state.extra = here_op & 15;
  20521. state.mode = LENEXT;
  20522. /* falls through */
  20523. case LENEXT:
  20524. if (state.extra) {
  20525. //=== NEEDBITS(state.extra);
  20526. n = state.extra;
  20527. while (bits < n) {
  20528. if (have === 0) { break inf_leave; }
  20529. have--;
  20530. hold += input[next++] << bits;
  20531. bits += 8;
  20532. }
  20533. //===//
  20534. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20535. //--- DROPBITS(state.extra) ---//
  20536. hold >>>= state.extra;
  20537. bits -= state.extra;
  20538. //---//
  20539. state.back += state.extra;
  20540. }
  20541. //Tracevv((stderr, "inflate: length %u\n", state.length));
  20542. state.was = state.length;
  20543. state.mode = DIST;
  20544. /* falls through */
  20545. case DIST:
  20546. for (;;) {
  20547. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  20548. here_bits = here >>> 24;
  20549. here_op = (here >>> 16) & 0xff;
  20550. here_val = here & 0xffff;
  20551. if ((here_bits) <= bits) { break; }
  20552. //--- PULLBYTE() ---//
  20553. if (have === 0) { break inf_leave; }
  20554. have--;
  20555. hold += input[next++] << bits;
  20556. bits += 8;
  20557. //---//
  20558. }
  20559. if ((here_op & 0xf0) === 0) {
  20560. last_bits = here_bits;
  20561. last_op = here_op;
  20562. last_val = here_val;
  20563. for (;;) {
  20564. here = state.distcode[last_val +
  20565. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20566. here_bits = here >>> 24;
  20567. here_op = (here >>> 16) & 0xff;
  20568. here_val = here & 0xffff;
  20569. if ((last_bits + here_bits) <= bits) { break; }
  20570. //--- PULLBYTE() ---//
  20571. if (have === 0) { break inf_leave; }
  20572. have--;
  20573. hold += input[next++] << bits;
  20574. bits += 8;
  20575. //---//
  20576. }
  20577. //--- DROPBITS(last.bits) ---//
  20578. hold >>>= last_bits;
  20579. bits -= last_bits;
  20580. //---//
  20581. state.back += last_bits;
  20582. }
  20583. //--- DROPBITS(here.bits) ---//
  20584. hold >>>= here_bits;
  20585. bits -= here_bits;
  20586. //---//
  20587. state.back += here_bits;
  20588. if (here_op & 64) {
  20589. strm.msg = 'invalid distance code';
  20590. state.mode = BAD;
  20591. break;
  20592. }
  20593. state.offset = here_val;
  20594. state.extra = (here_op) & 15;
  20595. state.mode = DISTEXT;
  20596. /* falls through */
  20597. case DISTEXT:
  20598. if (state.extra) {
  20599. //=== NEEDBITS(state.extra);
  20600. n = state.extra;
  20601. while (bits < n) {
  20602. if (have === 0) { break inf_leave; }
  20603. have--;
  20604. hold += input[next++] << bits;
  20605. bits += 8;
  20606. }
  20607. //===//
  20608. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20609. //--- DROPBITS(state.extra) ---//
  20610. hold >>>= state.extra;
  20611. bits -= state.extra;
  20612. //---//
  20613. state.back += state.extra;
  20614. }
  20615. //#ifdef INFLATE_STRICT
  20616. if (state.offset > state.dmax) {
  20617. strm.msg = 'invalid distance too far back';
  20618. state.mode = BAD;
  20619. break;
  20620. }
  20621. //#endif
  20622. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  20623. state.mode = MATCH;
  20624. /* falls through */
  20625. case MATCH:
  20626. if (left === 0) { break inf_leave; }
  20627. copy = _out - left;
  20628. if (state.offset > copy) { /* copy from window */
  20629. copy = state.offset - copy;
  20630. if (copy > state.whave) {
  20631. if (state.sane) {
  20632. strm.msg = 'invalid distance too far back';
  20633. state.mode = BAD;
  20634. break;
  20635. }
  20636. // (!) This block is disabled in zlib defailts,
  20637. // don't enable it for binary compatibility
  20638. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  20639. // Trace((stderr, "inflate.c too far\n"));
  20640. // copy -= state.whave;
  20641. // if (copy > state.length) { copy = state.length; }
  20642. // if (copy > left) { copy = left; }
  20643. // left -= copy;
  20644. // state.length -= copy;
  20645. // do {
  20646. // output[put++] = 0;
  20647. // } while (--copy);
  20648. // if (state.length === 0) { state.mode = LEN; }
  20649. // break;
  20650. //#endif
  20651. }
  20652. if (copy > state.wnext) {
  20653. copy -= state.wnext;
  20654. from = state.wsize - copy;
  20655. }
  20656. else {
  20657. from = state.wnext - copy;
  20658. }
  20659. if (copy > state.length) { copy = state.length; }
  20660. from_source = state.window;
  20661. }
  20662. else { /* copy from output */
  20663. from_source = output;
  20664. from = put - state.offset;
  20665. copy = state.length;
  20666. }
  20667. if (copy > left) { copy = left; }
  20668. left -= copy;
  20669. state.length -= copy;
  20670. do {
  20671. output[put++] = from_source[from++];
  20672. } while (--copy);
  20673. if (state.length === 0) { state.mode = LEN; }
  20674. break;
  20675. case LIT:
  20676. if (left === 0) { break inf_leave; }
  20677. output[put++] = state.length;
  20678. left--;
  20679. state.mode = LEN;
  20680. break;
  20681. case CHECK:
  20682. if (state.wrap) {
  20683. //=== NEEDBITS(32);
  20684. while (bits < 32) {
  20685. if (have === 0) { break inf_leave; }
  20686. have--;
  20687. // Use '|' insdead of '+' to make sure that result is signed
  20688. hold |= input[next++] << bits;
  20689. bits += 8;
  20690. }
  20691. //===//
  20692. _out -= left;
  20693. strm.total_out += _out;
  20694. state.total += _out;
  20695. if (_out) {
  20696. strm.adler = state.check =
  20697. /*UPDATE(state.check, put - _out, _out);*/
  20698. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  20699. }
  20700. _out = left;
  20701. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  20702. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  20703. strm.msg = 'incorrect data check';
  20704. state.mode = BAD;
  20705. break;
  20706. }
  20707. //=== INITBITS();
  20708. hold = 0;
  20709. bits = 0;
  20710. //===//
  20711. //Tracev((stderr, "inflate: check matches trailer\n"));
  20712. }
  20713. state.mode = LENGTH;
  20714. /* falls through */
  20715. case LENGTH:
  20716. if (state.wrap && state.flags) {
  20717. //=== NEEDBITS(32);
  20718. while (bits < 32) {
  20719. if (have === 0) { break inf_leave; }
  20720. have--;
  20721. hold += input[next++] << bits;
  20722. bits += 8;
  20723. }
  20724. //===//
  20725. if (hold !== (state.total & 0xffffffff)) {
  20726. strm.msg = 'incorrect length check';
  20727. state.mode = BAD;
  20728. break;
  20729. }
  20730. //=== INITBITS();
  20731. hold = 0;
  20732. bits = 0;
  20733. //===//
  20734. //Tracev((stderr, "inflate: length matches trailer\n"));
  20735. }
  20736. state.mode = DONE;
  20737. /* falls through */
  20738. case DONE:
  20739. ret = Z_STREAM_END;
  20740. break inf_leave;
  20741. case BAD:
  20742. ret = Z_DATA_ERROR;
  20743. break inf_leave;
  20744. case MEM:
  20745. return Z_MEM_ERROR;
  20746. case SYNC:
  20747. /* falls through */
  20748. default:
  20749. return Z_STREAM_ERROR;
  20750. }
  20751. }
  20752. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  20753. /*
  20754. Return from inflate(), updating the total counts and the check value.
  20755. If there was no progress during the inflate() call, return a buffer
  20756. error. Call updatewindow() to create and/or update the window state.
  20757. Note: a memory error from inflate() is non-recoverable.
  20758. */
  20759. //--- RESTORE() ---
  20760. strm.next_out = put;
  20761. strm.avail_out = left;
  20762. strm.next_in = next;
  20763. strm.avail_in = have;
  20764. state.hold = hold;
  20765. state.bits = bits;
  20766. //---
  20767. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  20768. (state.mode < CHECK || flush !== Z_FINISH))) {
  20769. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  20770. state.mode = MEM;
  20771. return Z_MEM_ERROR;
  20772. }
  20773. }
  20774. _in -= strm.avail_in;
  20775. _out -= strm.avail_out;
  20776. strm.total_in += _in;
  20777. strm.total_out += _out;
  20778. state.total += _out;
  20779. if (state.wrap && _out) {
  20780. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  20781. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  20782. }
  20783. strm.data_type = state.bits + (state.last ? 64 : 0) +
  20784. (state.mode === TYPE ? 128 : 0) +
  20785. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  20786. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  20787. ret = Z_BUF_ERROR;
  20788. }
  20789. return ret;
  20790. }
  20791. function inflateEnd(strm) {
  20792. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  20793. return Z_STREAM_ERROR;
  20794. }
  20795. var state = strm.state;
  20796. if (state.window) {
  20797. state.window = null;
  20798. }
  20799. strm.state = null;
  20800. return Z_OK;
  20801. }
  20802. function inflateGetHeader(strm, head) {
  20803. var state;
  20804. /* check state */
  20805. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20806. state = strm.state;
  20807. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  20808. /* save header structure */
  20809. state.head = head;
  20810. head.done = false;
  20811. return Z_OK;
  20812. }
  20813. exports.inflateReset = inflateReset;
  20814. exports.inflateReset2 = inflateReset2;
  20815. exports.inflateResetKeep = inflateResetKeep;
  20816. exports.inflateInit = inflateInit;
  20817. exports.inflateInit2 = inflateInit2;
  20818. exports.inflate = inflate;
  20819. exports.inflateEnd = inflateEnd;
  20820. exports.inflateGetHeader = inflateGetHeader;
  20821. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  20822. /* Not implemented
  20823. exports.inflateCopy = inflateCopy;
  20824. exports.inflateGetDictionary = inflateGetDictionary;
  20825. exports.inflateMark = inflateMark;
  20826. exports.inflatePrime = inflatePrime;
  20827. exports.inflateSetDictionary = inflateSetDictionary;
  20828. exports.inflateSync = inflateSync;
  20829. exports.inflateSyncPoint = inflateSyncPoint;
  20830. exports.inflateUndermine = inflateUndermine;
  20831. */
  20832. },{"../utils/common":65,"./adler32":67,"./crc32":69,"./inffast":72,"./inftrees":74}],74:[function(require,module,exports){
  20833. 'use strict';
  20834. var utils = require('../utils/common');
  20835. var MAXBITS = 15;
  20836. var ENOUGH_LENS = 852;
  20837. var ENOUGH_DISTS = 592;
  20838. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  20839. var CODES = 0;
  20840. var LENS = 1;
  20841. var DISTS = 2;
  20842. var lbase = [ /* Length codes 257..285 base */
  20843. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  20844. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  20845. ];
  20846. var lext = [ /* Length codes 257..285 extra */
  20847. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  20848. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  20849. ];
  20850. var dbase = [ /* Distance codes 0..29 base */
  20851. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  20852. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  20853. 8193, 12289, 16385, 24577, 0, 0
  20854. ];
  20855. var dext = [ /* Distance codes 0..29 extra */
  20856. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  20857. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  20858. 28, 28, 29, 29, 64, 64
  20859. ];
  20860. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  20861. {
  20862. var bits = opts.bits;
  20863. //here = opts.here; /* table entry for duplication */
  20864. var len = 0; /* a code's length in bits */
  20865. var sym = 0; /* index of code symbols */
  20866. var min = 0, max = 0; /* minimum and maximum code lengths */
  20867. var root = 0; /* number of index bits for root table */
  20868. var curr = 0; /* number of index bits for current table */
  20869. var drop = 0; /* code bits to drop for sub-table */
  20870. var left = 0; /* number of prefix codes available */
  20871. var used = 0; /* code entries in table used */
  20872. var huff = 0; /* Huffman code */
  20873. var incr; /* for incrementing code, index */
  20874. var fill; /* index for replicating entries */
  20875. var low; /* low bits for current root entry */
  20876. var mask; /* mask for low root bits */
  20877. var next; /* next available space in table */
  20878. var base = null; /* base value table to use */
  20879. var base_index = 0;
  20880. // var shoextra; /* extra bits table to use */
  20881. var end; /* use base and extra for symbol > end */
  20882. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  20883. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  20884. var extra = null;
  20885. var extra_index = 0;
  20886. var here_bits, here_op, here_val;
  20887. /*
  20888. Process a set of code lengths to create a canonical Huffman code. The
  20889. code lengths are lens[0..codes-1]. Each length corresponds to the
  20890. symbols 0..codes-1. The Huffman code is generated by first sorting the
  20891. symbols by length from short to long, and retaining the symbol order
  20892. for codes with equal lengths. Then the code starts with all zero bits
  20893. for the first code of the shortest length, and the codes are integer
  20894. increments for the same length, and zeros are appended as the length
  20895. increases. For the deflate format, these bits are stored backwards
  20896. from their more natural integer increment ordering, and so when the
  20897. decoding tables are built in the large loop below, the integer codes
  20898. are incremented backwards.
  20899. This routine assumes, but does not check, that all of the entries in
  20900. lens[] are in the range 0..MAXBITS. The caller must assure this.
  20901. 1..MAXBITS is interpreted as that code length. zero means that that
  20902. symbol does not occur in this code.
  20903. The codes are sorted by computing a count of codes for each length,
  20904. creating from that a table of starting indices for each length in the
  20905. sorted table, and then entering the symbols in order in the sorted
  20906. table. The sorted table is work[], with that space being provided by
  20907. the caller.
  20908. The length counts are used for other purposes as well, i.e. finding
  20909. the minimum and maximum length codes, determining if there are any
  20910. codes at all, checking for a valid set of lengths, and looking ahead
  20911. at length counts to determine sub-table sizes when building the
  20912. decoding tables.
  20913. */
  20914. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  20915. for (len = 0; len <= MAXBITS; len++) {
  20916. count[len] = 0;
  20917. }
  20918. for (sym = 0; sym < codes; sym++) {
  20919. count[lens[lens_index + sym]]++;
  20920. }
  20921. /* bound code lengths, force root to be within code lengths */
  20922. root = bits;
  20923. for (max = MAXBITS; max >= 1; max--) {
  20924. if (count[max] !== 0) { break; }
  20925. }
  20926. if (root > max) {
  20927. root = max;
  20928. }
  20929. if (max === 0) { /* no symbols to code at all */
  20930. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  20931. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  20932. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  20933. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  20934. //table.op[opts.table_index] = 64;
  20935. //table.bits[opts.table_index] = 1;
  20936. //table.val[opts.table_index++] = 0;
  20937. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  20938. opts.bits = 1;
  20939. return 0; /* no symbols, but wait for decoding to report error */
  20940. }
  20941. for (min = 1; min < max; min++) {
  20942. if (count[min] !== 0) { break; }
  20943. }
  20944. if (root < min) {
  20945. root = min;
  20946. }
  20947. /* check for an over-subscribed or incomplete set of lengths */
  20948. left = 1;
  20949. for (len = 1; len <= MAXBITS; len++) {
  20950. left <<= 1;
  20951. left -= count[len];
  20952. if (left < 0) {
  20953. return -1;
  20954. } /* over-subscribed */
  20955. }
  20956. if (left > 0 && (type === CODES || max !== 1)) {
  20957. return -1; /* incomplete set */
  20958. }
  20959. /* generate offsets into symbol table for each length for sorting */
  20960. offs[1] = 0;
  20961. for (len = 1; len < MAXBITS; len++) {
  20962. offs[len + 1] = offs[len] + count[len];
  20963. }
  20964. /* sort symbols by length, by symbol order within each length */
  20965. for (sym = 0; sym < codes; sym++) {
  20966. if (lens[lens_index + sym] !== 0) {
  20967. work[offs[lens[lens_index + sym]]++] = sym;
  20968. }
  20969. }
  20970. /*
  20971. Create and fill in decoding tables. In this loop, the table being
  20972. filled is at next and has curr index bits. The code being used is huff
  20973. with length len. That code is converted to an index by dropping drop
  20974. bits off of the bottom. For codes where len is less than drop + curr,
  20975. those top drop + curr - len bits are incremented through all values to
  20976. fill the table with replicated entries.
  20977. root is the number of index bits for the root table. When len exceeds
  20978. root, sub-tables are created pointed to by the root entry with an index
  20979. of the low root bits of huff. This is saved in low to check for when a
  20980. new sub-table should be started. drop is zero when the root table is
  20981. being filled, and drop is root when sub-tables are being filled.
  20982. When a new sub-table is needed, it is necessary to look ahead in the
  20983. code lengths to determine what size sub-table is needed. The length
  20984. counts are used for this, and so count[] is decremented as codes are
  20985. entered in the tables.
  20986. used keeps track of how many table entries have been allocated from the
  20987. provided *table space. It is checked for LENS and DIST tables against
  20988. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  20989. the initial root table size constants. See the comments in inftrees.h
  20990. for more information.
  20991. sym increments through all symbols, and the loop terminates when
  20992. all codes of length max, i.e. all codes, have been processed. This
  20993. routine permits incomplete codes, so another loop after this one fills
  20994. in the rest of the decoding tables with invalid code markers.
  20995. */
  20996. /* set up for code type */
  20997. // poor man optimization - use if-else instead of switch,
  20998. // to avoid deopts in old v8
  20999. if (type === CODES) {
  21000. base = extra = work; /* dummy value--not used */
  21001. end = 19;
  21002. } else if (type === LENS) {
  21003. base = lbase;
  21004. base_index -= 257;
  21005. extra = lext;
  21006. extra_index -= 257;
  21007. end = 256;
  21008. } else { /* DISTS */
  21009. base = dbase;
  21010. extra = dext;
  21011. end = -1;
  21012. }
  21013. /* initialize opts for loop */
  21014. huff = 0; /* starting code */
  21015. sym = 0; /* starting code symbol */
  21016. len = min; /* starting code length */
  21017. next = table_index; /* current table to fill in */
  21018. curr = root; /* current table index bits */
  21019. drop = 0; /* current bits to drop from code for index */
  21020. low = -1; /* trigger new sub-table when len > root */
  21021. used = 1 << root; /* use root table entries */
  21022. mask = used - 1; /* mask for comparing low */
  21023. /* check available table space */
  21024. if ((type === LENS && used > ENOUGH_LENS) ||
  21025. (type === DISTS && used > ENOUGH_DISTS)) {
  21026. return 1;
  21027. }
  21028. var i=0;
  21029. /* process all codes and make table entries */
  21030. for (;;) {
  21031. i++;
  21032. /* create table entry */
  21033. here_bits = len - drop;
  21034. if (work[sym] < end) {
  21035. here_op = 0;
  21036. here_val = work[sym];
  21037. }
  21038. else if (work[sym] > end) {
  21039. here_op = extra[extra_index + work[sym]];
  21040. here_val = base[base_index + work[sym]];
  21041. }
  21042. else {
  21043. here_op = 32 + 64; /* end of block */
  21044. here_val = 0;
  21045. }
  21046. /* replicate for those indices with low len bits equal to huff */
  21047. incr = 1 << (len - drop);
  21048. fill = 1 << curr;
  21049. min = fill; /* save offset to next table */
  21050. do {
  21051. fill -= incr;
  21052. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  21053. } while (fill !== 0);
  21054. /* backwards increment the len-bit code huff */
  21055. incr = 1 << (len - 1);
  21056. while (huff & incr) {
  21057. incr >>= 1;
  21058. }
  21059. if (incr !== 0) {
  21060. huff &= incr - 1;
  21061. huff += incr;
  21062. } else {
  21063. huff = 0;
  21064. }
  21065. /* go to next symbol, update count, len */
  21066. sym++;
  21067. if (--count[len] === 0) {
  21068. if (len === max) { break; }
  21069. len = lens[lens_index + work[sym]];
  21070. }
  21071. /* create new sub-table if needed */
  21072. if (len > root && (huff & mask) !== low) {
  21073. /* if first time, transition to sub-tables */
  21074. if (drop === 0) {
  21075. drop = root;
  21076. }
  21077. /* increment past last table */
  21078. next += min; /* here min is 1 << curr */
  21079. /* determine length of next table */
  21080. curr = len - drop;
  21081. left = 1 << curr;
  21082. while (curr + drop < max) {
  21083. left -= count[curr + drop];
  21084. if (left <= 0) { break; }
  21085. curr++;
  21086. left <<= 1;
  21087. }
  21088. /* check for enough space */
  21089. used += 1 << curr;
  21090. if ((type === LENS && used > ENOUGH_LENS) ||
  21091. (type === DISTS && used > ENOUGH_DISTS)) {
  21092. return 1;
  21093. }
  21094. /* point entry in root table to sub-table */
  21095. low = huff & mask;
  21096. /*table.op[low] = curr;
  21097. table.bits[low] = root;
  21098. table.val[low] = next - opts.table_index;*/
  21099. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  21100. }
  21101. }
  21102. /* fill in remaining table entry if code is incomplete (guaranteed to have
  21103. at most one remaining entry, since if the code is incomplete, the
  21104. maximum code length that was allowed to get this far is one bit) */
  21105. if (huff !== 0) {
  21106. //table.op[next + huff] = 64; /* invalid code marker */
  21107. //table.bits[next + huff] = len - drop;
  21108. //table.val[next + huff] = 0;
  21109. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  21110. }
  21111. /* set return parameters */
  21112. //opts.table_index += used;
  21113. opts.bits = root;
  21114. return 0;
  21115. };
  21116. },{"../utils/common":65}],75:[function(require,module,exports){
  21117. 'use strict';
  21118. module.exports = {
  21119. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  21120. '1': 'stream end', /* Z_STREAM_END 1 */
  21121. '0': '', /* Z_OK 0 */
  21122. '-1': 'file error', /* Z_ERRNO (-1) */
  21123. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  21124. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  21125. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  21126. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  21127. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  21128. };
  21129. },{}],76:[function(require,module,exports){
  21130. 'use strict';
  21131. var utils = require('../utils/common');
  21132. /* Public constants ==========================================================*/
  21133. /* ===========================================================================*/
  21134. //var Z_FILTERED = 1;
  21135. //var Z_HUFFMAN_ONLY = 2;
  21136. //var Z_RLE = 3;
  21137. var Z_FIXED = 4;
  21138. //var Z_DEFAULT_STRATEGY = 0;
  21139. /* Possible values of the data_type field (though see inflate()) */
  21140. var Z_BINARY = 0;
  21141. var Z_TEXT = 1;
  21142. //var Z_ASCII = 1; // = Z_TEXT
  21143. var Z_UNKNOWN = 2;
  21144. /*============================================================================*/
  21145. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  21146. // From zutil.h
  21147. var STORED_BLOCK = 0;
  21148. var STATIC_TREES = 1;
  21149. var DYN_TREES = 2;
  21150. /* The three kinds of block type */
  21151. var MIN_MATCH = 3;
  21152. var MAX_MATCH = 258;
  21153. /* The minimum and maximum match lengths */
  21154. // From deflate.h
  21155. /* ===========================================================================
  21156. * Internal compression state.
  21157. */
  21158. var LENGTH_CODES = 29;
  21159. /* number of length codes, not counting the special END_BLOCK code */
  21160. var LITERALS = 256;
  21161. /* number of literal bytes 0..255 */
  21162. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  21163. /* number of Literal or Length codes, including the END_BLOCK code */
  21164. var D_CODES = 30;
  21165. /* number of distance codes */
  21166. var BL_CODES = 19;
  21167. /* number of codes used to transfer the bit lengths */
  21168. var HEAP_SIZE = 2*L_CODES + 1;
  21169. /* maximum heap size */
  21170. var MAX_BITS = 15;
  21171. /* All codes must not exceed MAX_BITS bits */
  21172. var Buf_size = 16;
  21173. /* size of bit buffer in bi_buf */
  21174. /* ===========================================================================
  21175. * Constants
  21176. */
  21177. var MAX_BL_BITS = 7;
  21178. /* Bit length codes must not exceed MAX_BL_BITS bits */
  21179. var END_BLOCK = 256;
  21180. /* end of block literal code */
  21181. var REP_3_6 = 16;
  21182. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  21183. var REPZ_3_10 = 17;
  21184. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  21185. var REPZ_11_138 = 18;
  21186. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  21187. var extra_lbits = /* extra bits for each length code */
  21188. [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];
  21189. var extra_dbits = /* extra bits for each distance code */
  21190. [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];
  21191. var extra_blbits = /* extra bits for each bit length code */
  21192. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  21193. var bl_order =
  21194. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  21195. /* The lengths of the bit length codes are sent in order of decreasing
  21196. * probability, to avoid transmitting the lengths for unused bit length codes.
  21197. */
  21198. /* ===========================================================================
  21199. * Local data. These are initialized only once.
  21200. */
  21201. // We pre-fill arrays with 0 to avoid uninitialized gaps
  21202. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  21203. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  21204. var static_ltree = new Array((L_CODES+2) * 2);
  21205. zero(static_ltree);
  21206. /* The static literal tree. Since the bit lengths are imposed, there is no
  21207. * need for the L_CODES extra codes used during heap construction. However
  21208. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  21209. * below).
  21210. */
  21211. var static_dtree = new Array(D_CODES * 2);
  21212. zero(static_dtree);
  21213. /* The static distance tree. (Actually a trivial tree since all codes use
  21214. * 5 bits.)
  21215. */
  21216. var _dist_code = new Array(DIST_CODE_LEN);
  21217. zero(_dist_code);
  21218. /* Distance codes. The first 256 values correspond to the distances
  21219. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  21220. * the 15 bit distances.
  21221. */
  21222. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  21223. zero(_length_code);
  21224. /* length code for each normalized match length (0 == MIN_MATCH) */
  21225. var base_length = new Array(LENGTH_CODES);
  21226. zero(base_length);
  21227. /* First normalized length for each code (0 = MIN_MATCH) */
  21228. var base_dist = new Array(D_CODES);
  21229. zero(base_dist);
  21230. /* First normalized distance for each code (0 = distance of 1) */
  21231. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  21232. this.static_tree = static_tree; /* static tree or NULL */
  21233. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  21234. this.extra_base = extra_base; /* base index for extra_bits */
  21235. this.elems = elems; /* max number of elements in the tree */
  21236. this.max_length = max_length; /* max bit length for the codes */
  21237. // show if `static_tree` has data or dummy - needed for monomorphic objects
  21238. this.has_stree = static_tree && static_tree.length;
  21239. };
  21240. var static_l_desc;
  21241. var static_d_desc;
  21242. var static_bl_desc;
  21243. var TreeDesc = function(dyn_tree, stat_desc) {
  21244. this.dyn_tree = dyn_tree; /* the dynamic tree */
  21245. this.max_code = 0; /* largest code with non zero frequency */
  21246. this.stat_desc = stat_desc; /* the corresponding static tree */
  21247. };
  21248. function d_code(dist) {
  21249. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  21250. }
  21251. /* ===========================================================================
  21252. * Output a short LSB first on the stream.
  21253. * IN assertion: there is enough room in pendingBuf.
  21254. */
  21255. function put_short (s, w) {
  21256. // put_byte(s, (uch)((w) & 0xff));
  21257. // put_byte(s, (uch)((ush)(w) >> 8));
  21258. s.pending_buf[s.pending++] = (w) & 0xff;
  21259. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  21260. }
  21261. /* ===========================================================================
  21262. * Send a value on a given number of bits.
  21263. * IN assertion: length <= 16 and value fits in length bits.
  21264. */
  21265. function send_bits(s, value, length) {
  21266. if (s.bi_valid > (Buf_size - length)) {
  21267. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21268. put_short(s, s.bi_buf);
  21269. s.bi_buf = value >> (Buf_size - s.bi_valid);
  21270. s.bi_valid += length - Buf_size;
  21271. } else {
  21272. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21273. s.bi_valid += length;
  21274. }
  21275. }
  21276. function send_code(s, c, tree) {
  21277. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  21278. }
  21279. /* ===========================================================================
  21280. * Reverse the first len bits of a code, using straightforward code (a faster
  21281. * method would use a table)
  21282. * IN assertion: 1 <= len <= 15
  21283. */
  21284. function bi_reverse(code, len) {
  21285. var res = 0;
  21286. do {
  21287. res |= code & 1;
  21288. code >>>= 1;
  21289. res <<= 1;
  21290. } while (--len > 0);
  21291. return res >>> 1;
  21292. }
  21293. /* ===========================================================================
  21294. * Flush the bit buffer, keeping at most 7 bits in it.
  21295. */
  21296. function bi_flush(s) {
  21297. if (s.bi_valid === 16) {
  21298. put_short(s, s.bi_buf);
  21299. s.bi_buf = 0;
  21300. s.bi_valid = 0;
  21301. } else if (s.bi_valid >= 8) {
  21302. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  21303. s.bi_buf >>= 8;
  21304. s.bi_valid -= 8;
  21305. }
  21306. }
  21307. /* ===========================================================================
  21308. * Compute the optimal bit lengths for a tree and update the total bit length
  21309. * for the current block.
  21310. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  21311. * above are the tree nodes sorted by increasing frequency.
  21312. * OUT assertions: the field len is set to the optimal bit length, the
  21313. * array bl_count contains the frequencies for each bit length.
  21314. * The length opt_len is updated; static_len is also updated if stree is
  21315. * not null.
  21316. */
  21317. function gen_bitlen(s, desc)
  21318. // deflate_state *s;
  21319. // tree_desc *desc; /* the tree descriptor */
  21320. {
  21321. var tree = desc.dyn_tree;
  21322. var max_code = desc.max_code;
  21323. var stree = desc.stat_desc.static_tree;
  21324. var has_stree = desc.stat_desc.has_stree;
  21325. var extra = desc.stat_desc.extra_bits;
  21326. var base = desc.stat_desc.extra_base;
  21327. var max_length = desc.stat_desc.max_length;
  21328. var h; /* heap index */
  21329. var n, m; /* iterate over the tree elements */
  21330. var bits; /* bit length */
  21331. var xbits; /* extra bits */
  21332. var f; /* frequency */
  21333. var overflow = 0; /* number of elements with bit length too large */
  21334. for (bits = 0; bits <= MAX_BITS; bits++) {
  21335. s.bl_count[bits] = 0;
  21336. }
  21337. /* In a first pass, compute the optimal bit lengths (which may
  21338. * overflow in the case of the bit length tree).
  21339. */
  21340. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  21341. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  21342. n = s.heap[h];
  21343. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  21344. if (bits > max_length) {
  21345. bits = max_length;
  21346. overflow++;
  21347. }
  21348. tree[n*2 + 1]/*.Len*/ = bits;
  21349. /* We overwrite tree[n].Dad which is no longer needed */
  21350. if (n > max_code) { continue; } /* not a leaf node */
  21351. s.bl_count[bits]++;
  21352. xbits = 0;
  21353. if (n >= base) {
  21354. xbits = extra[n-base];
  21355. }
  21356. f = tree[n * 2]/*.Freq*/;
  21357. s.opt_len += f * (bits + xbits);
  21358. if (has_stree) {
  21359. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  21360. }
  21361. }
  21362. if (overflow === 0) { return; }
  21363. // Trace((stderr,"\nbit length overflow\n"));
  21364. /* This happens for example on obj2 and pic of the Calgary corpus */
  21365. /* Find the first bit length which could increase: */
  21366. do {
  21367. bits = max_length-1;
  21368. while (s.bl_count[bits] === 0) { bits--; }
  21369. s.bl_count[bits]--; /* move one leaf down the tree */
  21370. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  21371. s.bl_count[max_length]--;
  21372. /* The brother of the overflow item also moves one step up,
  21373. * but this does not affect bl_count[max_length]
  21374. */
  21375. overflow -= 2;
  21376. } while (overflow > 0);
  21377. /* Now recompute all bit lengths, scanning in increasing frequency.
  21378. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  21379. * lengths instead of fixing only the wrong ones. This idea is taken
  21380. * from 'ar' written by Haruhiko Okumura.)
  21381. */
  21382. for (bits = max_length; bits !== 0; bits--) {
  21383. n = s.bl_count[bits];
  21384. while (n !== 0) {
  21385. m = s.heap[--h];
  21386. if (m > max_code) { continue; }
  21387. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  21388. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  21389. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  21390. tree[m*2 + 1]/*.Len*/ = bits;
  21391. }
  21392. n--;
  21393. }
  21394. }
  21395. }
  21396. /* ===========================================================================
  21397. * Generate the codes for a given tree and bit counts (which need not be
  21398. * optimal).
  21399. * IN assertion: the array bl_count contains the bit length statistics for
  21400. * the given tree and the field len is set for all tree elements.
  21401. * OUT assertion: the field code is set for all tree elements of non
  21402. * zero code length.
  21403. */
  21404. function gen_codes(tree, max_code, bl_count)
  21405. // ct_data *tree; /* the tree to decorate */
  21406. // int max_code; /* largest code with non zero frequency */
  21407. // ushf *bl_count; /* number of codes at each bit length */
  21408. {
  21409. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  21410. var code = 0; /* running code value */
  21411. var bits; /* bit index */
  21412. var n; /* code index */
  21413. /* The distribution counts are first used to generate the code values
  21414. * without bit reversal.
  21415. */
  21416. for (bits = 1; bits <= MAX_BITS; bits++) {
  21417. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  21418. }
  21419. /* Check that the bit counts in bl_count are consistent. The last code
  21420. * must be all ones.
  21421. */
  21422. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  21423. // "inconsistent bit counts");
  21424. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  21425. for (n = 0; n <= max_code; n++) {
  21426. var len = tree[n*2 + 1]/*.Len*/;
  21427. if (len === 0) { continue; }
  21428. /* Now reverse the bits */
  21429. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  21430. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  21431. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  21432. }
  21433. }
  21434. /* ===========================================================================
  21435. * Initialize the various 'constant' tables.
  21436. */
  21437. function tr_static_init() {
  21438. var n; /* iterates over tree elements */
  21439. var bits; /* bit counter */
  21440. var length; /* length value */
  21441. var code; /* code value */
  21442. var dist; /* distance index */
  21443. var bl_count = new Array(MAX_BITS+1);
  21444. /* number of codes at each bit length for an optimal tree */
  21445. // do check in _tr_init()
  21446. //if (static_init_done) return;
  21447. /* For some embedded targets, global variables are not initialized: */
  21448. /*#ifdef NO_INIT_GLOBAL_POINTERS
  21449. static_l_desc.static_tree = static_ltree;
  21450. static_l_desc.extra_bits = extra_lbits;
  21451. static_d_desc.static_tree = static_dtree;
  21452. static_d_desc.extra_bits = extra_dbits;
  21453. static_bl_desc.extra_bits = extra_blbits;
  21454. #endif*/
  21455. /* Initialize the mapping length (0..255) -> length code (0..28) */
  21456. length = 0;
  21457. for (code = 0; code < LENGTH_CODES-1; code++) {
  21458. base_length[code] = length;
  21459. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  21460. _length_code[length++] = code;
  21461. }
  21462. }
  21463. //Assert (length == 256, "tr_static_init: length != 256");
  21464. /* Note that the length 255 (match length 258) can be represented
  21465. * in two different ways: code 284 + 5 bits or code 285, so we
  21466. * overwrite length_code[255] to use the best encoding:
  21467. */
  21468. _length_code[length-1] = code;
  21469. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  21470. dist = 0;
  21471. for (code = 0 ; code < 16; code++) {
  21472. base_dist[code] = dist;
  21473. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  21474. _dist_code[dist++] = code;
  21475. }
  21476. }
  21477. //Assert (dist == 256, "tr_static_init: dist != 256");
  21478. dist >>= 7; /* from now on, all distances are divided by 128 */
  21479. for ( ; code < D_CODES; code++) {
  21480. base_dist[code] = dist << 7;
  21481. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  21482. _dist_code[256 + dist++] = code;
  21483. }
  21484. }
  21485. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  21486. /* Construct the codes of the static literal tree */
  21487. for (bits = 0; bits <= MAX_BITS; bits++) {
  21488. bl_count[bits] = 0;
  21489. }
  21490. n = 0;
  21491. while (n <= 143) {
  21492. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21493. n++;
  21494. bl_count[8]++;
  21495. }
  21496. while (n <= 255) {
  21497. static_ltree[n*2 + 1]/*.Len*/ = 9;
  21498. n++;
  21499. bl_count[9]++;
  21500. }
  21501. while (n <= 279) {
  21502. static_ltree[n*2 + 1]/*.Len*/ = 7;
  21503. n++;
  21504. bl_count[7]++;
  21505. }
  21506. while (n <= 287) {
  21507. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21508. n++;
  21509. bl_count[8]++;
  21510. }
  21511. /* Codes 286 and 287 do not exist, but we must include them in the
  21512. * tree construction to get a canonical Huffman tree (longest code
  21513. * all ones)
  21514. */
  21515. gen_codes(static_ltree, L_CODES+1, bl_count);
  21516. /* The static distance tree is trivial: */
  21517. for (n = 0; n < D_CODES; n++) {
  21518. static_dtree[n*2 + 1]/*.Len*/ = 5;
  21519. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  21520. }
  21521. // Now data ready and we can init static trees
  21522. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  21523. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  21524. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  21525. //static_init_done = true;
  21526. }
  21527. /* ===========================================================================
  21528. * Initialize a new block.
  21529. */
  21530. function init_block(s) {
  21531. var n; /* iterates over tree elements */
  21532. /* Initialize the trees. */
  21533. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  21534. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  21535. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  21536. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  21537. s.opt_len = s.static_len = 0;
  21538. s.last_lit = s.matches = 0;
  21539. }
  21540. /* ===========================================================================
  21541. * Flush the bit buffer and align the output on a byte boundary
  21542. */
  21543. function bi_windup(s)
  21544. {
  21545. if (s.bi_valid > 8) {
  21546. put_short(s, s.bi_buf);
  21547. } else if (s.bi_valid > 0) {
  21548. //put_byte(s, (Byte)s->bi_buf);
  21549. s.pending_buf[s.pending++] = s.bi_buf;
  21550. }
  21551. s.bi_buf = 0;
  21552. s.bi_valid = 0;
  21553. }
  21554. /* ===========================================================================
  21555. * Copy a stored block, storing first the length and its
  21556. * one's complement if requested.
  21557. */
  21558. function copy_block(s, buf, len, header)
  21559. //DeflateState *s;
  21560. //charf *buf; /* the input data */
  21561. //unsigned len; /* its length */
  21562. //int header; /* true if block header must be written */
  21563. {
  21564. bi_windup(s); /* align on byte boundary */
  21565. if (header) {
  21566. put_short(s, len);
  21567. put_short(s, ~len);
  21568. }
  21569. // while (len--) {
  21570. // put_byte(s, *buf++);
  21571. // }
  21572. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  21573. s.pending += len;
  21574. }
  21575. /* ===========================================================================
  21576. * Compares to subtrees, using the tree depth as tie breaker when
  21577. * the subtrees have equal frequency. This minimizes the worst case length.
  21578. */
  21579. function smaller(tree, n, m, depth) {
  21580. var _n2 = n*2;
  21581. var _m2 = m*2;
  21582. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  21583. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  21584. }
  21585. /* ===========================================================================
  21586. * Restore the heap property by moving down the tree starting at node k,
  21587. * exchanging a node with the smallest of its two sons if necessary, stopping
  21588. * when the heap property is re-established (each father smaller than its
  21589. * two sons).
  21590. */
  21591. function pqdownheap(s, tree, k)
  21592. // deflate_state *s;
  21593. // ct_data *tree; /* the tree to restore */
  21594. // int k; /* node to move down */
  21595. {
  21596. var v = s.heap[k];
  21597. var j = k << 1; /* left son of k */
  21598. while (j <= s.heap_len) {
  21599. /* Set j to the smallest of the two sons: */
  21600. if (j < s.heap_len &&
  21601. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  21602. j++;
  21603. }
  21604. /* Exit if v is smaller than both sons */
  21605. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  21606. /* Exchange v with the smallest son */
  21607. s.heap[k] = s.heap[j];
  21608. k = j;
  21609. /* And continue down the tree, setting j to the left son of k */
  21610. j <<= 1;
  21611. }
  21612. s.heap[k] = v;
  21613. }
  21614. // inlined manually
  21615. // var SMALLEST = 1;
  21616. /* ===========================================================================
  21617. * Send the block data compressed using the given Huffman trees
  21618. */
  21619. function compress_block(s, ltree, dtree)
  21620. // deflate_state *s;
  21621. // const ct_data *ltree; /* literal tree */
  21622. // const ct_data *dtree; /* distance tree */
  21623. {
  21624. var dist; /* distance of matched string */
  21625. var lc; /* match length or unmatched char (if dist == 0) */
  21626. var lx = 0; /* running index in l_buf */
  21627. var code; /* the code to send */
  21628. var extra; /* number of extra bits to send */
  21629. if (s.last_lit !== 0) {
  21630. do {
  21631. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  21632. lc = s.pending_buf[s.l_buf + lx];
  21633. lx++;
  21634. if (dist === 0) {
  21635. send_code(s, lc, ltree); /* send a literal byte */
  21636. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  21637. } else {
  21638. /* Here, lc is the match length - MIN_MATCH */
  21639. code = _length_code[lc];
  21640. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  21641. extra = extra_lbits[code];
  21642. if (extra !== 0) {
  21643. lc -= base_length[code];
  21644. send_bits(s, lc, extra); /* send the extra length bits */
  21645. }
  21646. dist--; /* dist is now the match distance - 1 */
  21647. code = d_code(dist);
  21648. //Assert (code < D_CODES, "bad d_code");
  21649. send_code(s, code, dtree); /* send the distance code */
  21650. extra = extra_dbits[code];
  21651. if (extra !== 0) {
  21652. dist -= base_dist[code];
  21653. send_bits(s, dist, extra); /* send the extra distance bits */
  21654. }
  21655. } /* literal or match pair ? */
  21656. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  21657. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  21658. // "pendingBuf overflow");
  21659. } while (lx < s.last_lit);
  21660. }
  21661. send_code(s, END_BLOCK, ltree);
  21662. }
  21663. /* ===========================================================================
  21664. * Construct one Huffman tree and assigns the code bit strings and lengths.
  21665. * Update the total bit length for the current block.
  21666. * IN assertion: the field freq is set for all tree elements.
  21667. * OUT assertions: the fields len and code are set to the optimal bit length
  21668. * and corresponding code. The length opt_len is updated; static_len is
  21669. * also updated if stree is not null. The field max_code is set.
  21670. */
  21671. function build_tree(s, desc)
  21672. // deflate_state *s;
  21673. // tree_desc *desc; /* the tree descriptor */
  21674. {
  21675. var tree = desc.dyn_tree;
  21676. var stree = desc.stat_desc.static_tree;
  21677. var has_stree = desc.stat_desc.has_stree;
  21678. var elems = desc.stat_desc.elems;
  21679. var n, m; /* iterate over heap elements */
  21680. var max_code = -1; /* largest code with non zero frequency */
  21681. var node; /* new node being created */
  21682. /* Construct the initial heap, with least frequent element in
  21683. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  21684. * heap[0] is not used.
  21685. */
  21686. s.heap_len = 0;
  21687. s.heap_max = HEAP_SIZE;
  21688. for (n = 0; n < elems; n++) {
  21689. if (tree[n * 2]/*.Freq*/ !== 0) {
  21690. s.heap[++s.heap_len] = max_code = n;
  21691. s.depth[n] = 0;
  21692. } else {
  21693. tree[n*2 + 1]/*.Len*/ = 0;
  21694. }
  21695. }
  21696. /* The pkzip format requires that at least one distance code exists,
  21697. * and that at least one bit should be sent even if there is only one
  21698. * possible code. So to avoid special checks later on we force at least
  21699. * two codes of non zero frequency.
  21700. */
  21701. while (s.heap_len < 2) {
  21702. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  21703. tree[node * 2]/*.Freq*/ = 1;
  21704. s.depth[node] = 0;
  21705. s.opt_len--;
  21706. if (has_stree) {
  21707. s.static_len -= stree[node*2 + 1]/*.Len*/;
  21708. }
  21709. /* node is 0 or 1 so it does not have extra bits */
  21710. }
  21711. desc.max_code = max_code;
  21712. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  21713. * establish sub-heaps of increasing lengths:
  21714. */
  21715. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  21716. /* Construct the Huffman tree by repeatedly combining the least two
  21717. * frequent nodes.
  21718. */
  21719. node = elems; /* next internal node of the tree */
  21720. do {
  21721. //pqremove(s, tree, n); /* n = node of least frequency */
  21722. /*** pqremove ***/
  21723. n = s.heap[1/*SMALLEST*/];
  21724. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  21725. pqdownheap(s, tree, 1/*SMALLEST*/);
  21726. /***/
  21727. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  21728. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  21729. s.heap[--s.heap_max] = m;
  21730. /* Create a new node father of n and m */
  21731. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  21732. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  21733. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  21734. /* and insert the new node in the heap */
  21735. s.heap[1/*SMALLEST*/] = node++;
  21736. pqdownheap(s, tree, 1/*SMALLEST*/);
  21737. } while (s.heap_len >= 2);
  21738. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  21739. /* At this point, the fields freq and dad are set. We can now
  21740. * generate the bit lengths.
  21741. */
  21742. gen_bitlen(s, desc);
  21743. /* The field len is now set, we can generate the bit codes */
  21744. gen_codes(tree, max_code, s.bl_count);
  21745. }
  21746. /* ===========================================================================
  21747. * Scan a literal or distance tree to determine the frequencies of the codes
  21748. * in the bit length tree.
  21749. */
  21750. function scan_tree(s, tree, max_code)
  21751. // deflate_state *s;
  21752. // ct_data *tree; /* the tree to be scanned */
  21753. // int max_code; /* and its largest code of non zero frequency */
  21754. {
  21755. var n; /* iterates over all tree elements */
  21756. var prevlen = -1; /* last emitted length */
  21757. var curlen; /* length of current code */
  21758. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  21759. var count = 0; /* repeat count of the current code */
  21760. var max_count = 7; /* max repeat count */
  21761. var min_count = 4; /* min repeat count */
  21762. if (nextlen === 0) {
  21763. max_count = 138;
  21764. min_count = 3;
  21765. }
  21766. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  21767. for (n = 0; n <= max_code; n++) {
  21768. curlen = nextlen;
  21769. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  21770. if (++count < max_count && curlen === nextlen) {
  21771. continue;
  21772. } else if (count < min_count) {
  21773. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  21774. } else if (curlen !== 0) {
  21775. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  21776. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  21777. } else if (count <= 10) {
  21778. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  21779. } else {
  21780. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  21781. }
  21782. count = 0;
  21783. prevlen = curlen;
  21784. if (nextlen === 0) {
  21785. max_count = 138;
  21786. min_count = 3;
  21787. } else if (curlen === nextlen) {
  21788. max_count = 6;
  21789. min_count = 3;
  21790. } else {
  21791. max_count = 7;
  21792. min_count = 4;
  21793. }
  21794. }
  21795. }
  21796. /* ===========================================================================
  21797. * Send a literal or distance tree in compressed form, using the codes in
  21798. * bl_tree.
  21799. */
  21800. function send_tree(s, tree, max_code)
  21801. // deflate_state *s;
  21802. // ct_data *tree; /* the tree to be scanned */
  21803. // int max_code; /* and its largest code of non zero frequency */
  21804. {
  21805. var n; /* iterates over all tree elements */
  21806. var prevlen = -1; /* last emitted length */
  21807. var curlen; /* length of current code */
  21808. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  21809. var count = 0; /* repeat count of the current code */
  21810. var max_count = 7; /* max repeat count */
  21811. var min_count = 4; /* min repeat count */
  21812. /* tree[max_code+1].Len = -1; */ /* guard already set */
  21813. if (nextlen === 0) {
  21814. max_count = 138;
  21815. min_count = 3;
  21816. }
  21817. for (n = 0; n <= max_code; n++) {
  21818. curlen = nextlen;
  21819. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  21820. if (++count < max_count && curlen === nextlen) {
  21821. continue;
  21822. } else if (count < min_count) {
  21823. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  21824. } else if (curlen !== 0) {
  21825. if (curlen !== prevlen) {
  21826. send_code(s, curlen, s.bl_tree);
  21827. count--;
  21828. }
  21829. //Assert(count >= 3 && count <= 6, " 3_6?");
  21830. send_code(s, REP_3_6, s.bl_tree);
  21831. send_bits(s, count-3, 2);
  21832. } else if (count <= 10) {
  21833. send_code(s, REPZ_3_10, s.bl_tree);
  21834. send_bits(s, count-3, 3);
  21835. } else {
  21836. send_code(s, REPZ_11_138, s.bl_tree);
  21837. send_bits(s, count-11, 7);
  21838. }
  21839. count = 0;
  21840. prevlen = curlen;
  21841. if (nextlen === 0) {
  21842. max_count = 138;
  21843. min_count = 3;
  21844. } else if (curlen === nextlen) {
  21845. max_count = 6;
  21846. min_count = 3;
  21847. } else {
  21848. max_count = 7;
  21849. min_count = 4;
  21850. }
  21851. }
  21852. }
  21853. /* ===========================================================================
  21854. * Construct the Huffman tree for the bit lengths and return the index in
  21855. * bl_order of the last bit length code to send.
  21856. */
  21857. function build_bl_tree(s) {
  21858. var max_blindex; /* index of last bit length code of non zero freq */
  21859. /* Determine the bit length frequencies for literal and distance trees */
  21860. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  21861. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  21862. /* Build the bit length tree: */
  21863. build_tree(s, s.bl_desc);
  21864. /* opt_len now includes the length of the tree representations, except
  21865. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  21866. */
  21867. /* Determine the number of bit length codes to send. The pkzip format
  21868. * requires that at least 4 bit length codes be sent. (appnote.txt says
  21869. * 3 but the actual value used is 4.)
  21870. */
  21871. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  21872. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  21873. break;
  21874. }
  21875. }
  21876. /* Update opt_len to include the bit length tree and counts */
  21877. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  21878. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  21879. // s->opt_len, s->static_len));
  21880. return max_blindex;
  21881. }
  21882. /* ===========================================================================
  21883. * Send the header for a block using dynamic Huffman trees: the counts, the
  21884. * lengths of the bit length codes, the literal tree and the distance tree.
  21885. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  21886. */
  21887. function send_all_trees(s, lcodes, dcodes, blcodes)
  21888. // deflate_state *s;
  21889. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  21890. {
  21891. var rank; /* index in bl_order */
  21892. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  21893. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  21894. // "too many codes");
  21895. //Tracev((stderr, "\nbl counts: "));
  21896. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  21897. send_bits(s, dcodes-1, 5);
  21898. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  21899. for (rank = 0; rank < blcodes; rank++) {
  21900. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  21901. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  21902. }
  21903. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  21904. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  21905. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  21906. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  21907. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  21908. }
  21909. /* ===========================================================================
  21910. * Check if the data type is TEXT or BINARY, using the following algorithm:
  21911. * - TEXT if the two conditions below are satisfied:
  21912. * a) There are no non-portable control characters belonging to the
  21913. * "black list" (0..6, 14..25, 28..31).
  21914. * b) There is at least one printable character belonging to the
  21915. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  21916. * - BINARY otherwise.
  21917. * - The following partially-portable control characters form a
  21918. * "gray list" that is ignored in this detection algorithm:
  21919. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  21920. * IN assertion: the fields Freq of dyn_ltree are set.
  21921. */
  21922. function detect_data_type(s) {
  21923. /* black_mask is the bit mask of black-listed bytes
  21924. * set bits 0..6, 14..25, and 28..31
  21925. * 0xf3ffc07f = binary 11110011111111111100000001111111
  21926. */
  21927. var black_mask = 0xf3ffc07f;
  21928. var n;
  21929. /* Check for non-textual ("black-listed") bytes. */
  21930. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  21931. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  21932. return Z_BINARY;
  21933. }
  21934. }
  21935. /* Check for textual ("white-listed") bytes. */
  21936. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  21937. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  21938. return Z_TEXT;
  21939. }
  21940. for (n = 32; n < LITERALS; n++) {
  21941. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  21942. return Z_TEXT;
  21943. }
  21944. }
  21945. /* There are no "black-listed" or "white-listed" bytes:
  21946. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  21947. */
  21948. return Z_BINARY;
  21949. }
  21950. var static_init_done = false;
  21951. /* ===========================================================================
  21952. * Initialize the tree data structures for a new zlib stream.
  21953. */
  21954. function _tr_init(s)
  21955. {
  21956. if (!static_init_done) {
  21957. tr_static_init();
  21958. static_init_done = true;
  21959. }
  21960. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  21961. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  21962. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  21963. s.bi_buf = 0;
  21964. s.bi_valid = 0;
  21965. /* Initialize the first block of the first file: */
  21966. init_block(s);
  21967. }
  21968. /* ===========================================================================
  21969. * Send a stored block
  21970. */
  21971. function _tr_stored_block(s, buf, stored_len, last)
  21972. //DeflateState *s;
  21973. //charf *buf; /* input block */
  21974. //ulg stored_len; /* length of input block */
  21975. //int last; /* one if this is the last block for a file */
  21976. {
  21977. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  21978. copy_block(s, buf, stored_len, true); /* with header */
  21979. }
  21980. /* ===========================================================================
  21981. * Send one empty static block to give enough lookahead for inflate.
  21982. * This takes 10 bits, of which 7 may remain in the bit buffer.
  21983. */
  21984. function _tr_align(s) {
  21985. send_bits(s, STATIC_TREES<<1, 3);
  21986. send_code(s, END_BLOCK, static_ltree);
  21987. bi_flush(s);
  21988. }
  21989. /* ===========================================================================
  21990. * Determine the best encoding for the current block: dynamic trees, static
  21991. * trees or store, and output the encoded block to the zip file.
  21992. */
  21993. function _tr_flush_block(s, buf, stored_len, last)
  21994. //DeflateState *s;
  21995. //charf *buf; /* input block, or NULL if too old */
  21996. //ulg stored_len; /* length of input block */
  21997. //int last; /* one if this is the last block for a file */
  21998. {
  21999. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  22000. var max_blindex = 0; /* index of last bit length code of non zero freq */
  22001. /* Build the Huffman trees unless a stored block is forced */
  22002. if (s.level > 0) {
  22003. /* Check if the file is binary or text */
  22004. if (s.strm.data_type === Z_UNKNOWN) {
  22005. s.strm.data_type = detect_data_type(s);
  22006. }
  22007. /* Construct the literal and distance trees */
  22008. build_tree(s, s.l_desc);
  22009. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  22010. // s->static_len));
  22011. build_tree(s, s.d_desc);
  22012. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  22013. // s->static_len));
  22014. /* At this point, opt_len and static_len are the total bit lengths of
  22015. * the compressed block data, excluding the tree representations.
  22016. */
  22017. /* Build the bit length tree for the above two trees, and get the index
  22018. * in bl_order of the last bit length code to send.
  22019. */
  22020. max_blindex = build_bl_tree(s);
  22021. /* Determine the best encoding. Compute the block lengths in bytes. */
  22022. opt_lenb = (s.opt_len+3+7) >>> 3;
  22023. static_lenb = (s.static_len+3+7) >>> 3;
  22024. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  22025. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  22026. // s->last_lit));
  22027. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  22028. } else {
  22029. // Assert(buf != (char*)0, "lost buf");
  22030. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  22031. }
  22032. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  22033. /* 4: two words for the lengths */
  22034. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  22035. * Otherwise we can't have processed more than WSIZE input bytes since
  22036. * the last block flush, because compression would have been
  22037. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  22038. * transform a block into a stored block.
  22039. */
  22040. _tr_stored_block(s, buf, stored_len, last);
  22041. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  22042. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  22043. compress_block(s, static_ltree, static_dtree);
  22044. } else {
  22045. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  22046. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  22047. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  22048. }
  22049. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  22050. /* The above check is made mod 2^32, for files larger than 512 MB
  22051. * and uLong implemented on 32 bits.
  22052. */
  22053. init_block(s);
  22054. if (last) {
  22055. bi_windup(s);
  22056. }
  22057. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  22058. // s->compressed_len-7*last));
  22059. }
  22060. /* ===========================================================================
  22061. * Save the match info and tally the frequency counts. Return true if
  22062. * the current block must be flushed.
  22063. */
  22064. function _tr_tally(s, dist, lc)
  22065. // deflate_state *s;
  22066. // unsigned dist; /* distance of matched string */
  22067. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  22068. {
  22069. //var out_length, in_length, dcode;
  22070. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  22071. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  22072. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  22073. s.last_lit++;
  22074. if (dist === 0) {
  22075. /* lc is the unmatched char */
  22076. s.dyn_ltree[lc*2]/*.Freq*/++;
  22077. } else {
  22078. s.matches++;
  22079. /* Here, lc is the match length - MIN_MATCH */
  22080. dist--; /* dist = match distance - 1 */
  22081. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  22082. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  22083. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  22084. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  22085. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  22086. }
  22087. // (!) This block is disabled in zlib defailts,
  22088. // don't enable it for binary compatibility
  22089. //#ifdef TRUNCATE_BLOCK
  22090. // /* Try to guess if it is profitable to stop the current block here */
  22091. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  22092. // /* Compute an upper bound for the compressed length */
  22093. // out_length = s.last_lit*8;
  22094. // in_length = s.strstart - s.block_start;
  22095. //
  22096. // for (dcode = 0; dcode < D_CODES; dcode++) {
  22097. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  22098. // }
  22099. // out_length >>>= 3;
  22100. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  22101. // // s->last_lit, in_length, out_length,
  22102. // // 100L - out_length*100L/in_length));
  22103. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  22104. // return true;
  22105. // }
  22106. // }
  22107. //#endif
  22108. return (s.last_lit === s.lit_bufsize-1);
  22109. /* We avoid equality with lit_bufsize because of wraparound at 64K
  22110. * on 16 bit machines and because stored blocks are restricted to
  22111. * 64K-1 bytes.
  22112. */
  22113. }
  22114. exports._tr_init = _tr_init;
  22115. exports._tr_stored_block = _tr_stored_block;
  22116. exports._tr_flush_block = _tr_flush_block;
  22117. exports._tr_tally = _tr_tally;
  22118. exports._tr_align = _tr_align;
  22119. },{"../utils/common":65}],77:[function(require,module,exports){
  22120. 'use strict';
  22121. function ZStream() {
  22122. /* next input byte */
  22123. this.input = null; // JS specific, because we have no pointers
  22124. this.next_in = 0;
  22125. /* number of bytes available at input */
  22126. this.avail_in = 0;
  22127. /* total number of input bytes read so far */
  22128. this.total_in = 0;
  22129. /* next output byte should be put there */
  22130. this.output = null; // JS specific, because we have no pointers
  22131. this.next_out = 0;
  22132. /* remaining free space at output */
  22133. this.avail_out = 0;
  22134. /* total number of bytes output so far */
  22135. this.total_out = 0;
  22136. /* last error message, NULL if no error */
  22137. this.msg = ''/*Z_NULL*/;
  22138. /* not visible by applications */
  22139. this.state = null;
  22140. /* best guess about the data type: binary or text */
  22141. this.data_type = 2/*Z_UNKNOWN*/;
  22142. /* adler32 value of the uncompressed data */
  22143. this.adler = 0;
  22144. }
  22145. module.exports = ZStream;
  22146. },{}],78:[function(require,module,exports){
  22147. var MediaStreamType = {
  22148. VIDEO_TYPE: "Video",
  22149. AUDIO_TYPE: "Audio"
  22150. };
  22151. module.exports = MediaStreamType;
  22152. },{}],79:[function(require,module,exports){
  22153. var RTCBrowserType = {
  22154. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  22155. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  22156. };
  22157. module.exports = RTCBrowserType;
  22158. },{}],80:[function(require,module,exports){
  22159. var RTCEvents = {
  22160. LASTN_CHANGED: "rtc.lastn_changed",
  22161. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  22162. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  22163. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  22164. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  22165. SIMULCAST_START: "rtc.simlcast_start",
  22166. SIMULCAST_STOP: "rtc.simlcast_stop"
  22167. };
  22168. module.exports = RTCEvents;
  22169. },{}],81:[function(require,module,exports){
  22170. var Resolutions = {
  22171. "1080": {
  22172. width: 1920,
  22173. height: 1080,
  22174. order: 7
  22175. },
  22176. "fullhd": {
  22177. width: 1920,
  22178. height: 1080,
  22179. order: 7
  22180. },
  22181. "720": {
  22182. width: 1280,
  22183. height: 720,
  22184. order: 6
  22185. },
  22186. "hd": {
  22187. width: 1280,
  22188. height: 720,
  22189. order: 6
  22190. },
  22191. "960": {
  22192. width: 960,
  22193. height: 720,
  22194. order: 5
  22195. },
  22196. "640": {
  22197. width: 640,
  22198. height: 480,
  22199. order: 4
  22200. },
  22201. "vga": {
  22202. width: 640,
  22203. height: 480,
  22204. order: 4
  22205. },
  22206. "360": {
  22207. width: 640,
  22208. height: 360,
  22209. order: 3
  22210. },
  22211. "320": {
  22212. width: 320,
  22213. height: 240,
  22214. order: 2
  22215. },
  22216. "180": {
  22217. width: 320,
  22218. height: 180,
  22219. order: 1
  22220. }
  22221. };
  22222. module.exports = Resolutions;
  22223. },{}],82:[function(require,module,exports){
  22224. var StreamEventTypes = {
  22225. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  22226. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  22227. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  22228. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  22229. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  22230. };
  22231. module.exports = StreamEventTypes;
  22232. },{}],83:[function(require,module,exports){
  22233. var UIEvents = {
  22234. NICKNAME_CHANGED: "UI.nickname_changed",
  22235. SELECTED_ENDPOINT: "UI.selected_endpoint",
  22236. PINNED_ENDPOINT: "UI.pinned_endpoint"
  22237. };
  22238. module.exports = UIEvents;
  22239. },{}],84:[function(require,module,exports){
  22240. var AuthenticationEvents = {
  22241. /**
  22242. * Event callback arguments:
  22243. * function(authenticationEnabled, userIdentity)
  22244. * authenticationEnabled - indicates whether authentication has been enabled
  22245. * in this session
  22246. * userIdentity - if user has been logged in then it contains user name. If
  22247. * contains 'null' or 'undefined' then user is not logged in.
  22248. */
  22249. IDENTITY_UPDATED: "authentication.identity_updated"
  22250. };
  22251. module.exports = AuthenticationEvents;
  22252. },{}],85:[function(require,module,exports){
  22253. var CQEvents = {
  22254. LOCALSTATS_UPDATED: "cq.localstats_updated",
  22255. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  22256. STOP: "cq.stop"
  22257. };
  22258. module.exports = CQEvents;
  22259. },{}],86:[function(require,module,exports){
  22260. var DesktopSharingEventTypes = {
  22261. INIT: "ds.init",
  22262. SWITCHING_DONE: "ds.switching_done",
  22263. NEW_STREAM_CREATED: "ds.new_stream_created"
  22264. };
  22265. module.exports = DesktopSharingEventTypes;
  22266. },{}],87:[function(require,module,exports){
  22267. module.exports = {
  22268. getLanguages : function () {
  22269. var languages = [];
  22270. for(var lang in this)
  22271. {
  22272. if(typeof this[lang] === "string")
  22273. languages.push(this[lang]);
  22274. }
  22275. return languages;
  22276. },
  22277. EN: "en",
  22278. BG: "bg",
  22279. DE: "de"
  22280. }
  22281. },{}],88:[function(require,module,exports){
  22282. var XMPPEvents = {
  22283. CONFERENCE_CERATED: "xmpp.conferenceCreated.jingle",
  22284. CALL_TERMINATED: "xmpp.callterminated.jingle",
  22285. CALL_INCOMING: "xmpp.callincoming.jingle",
  22286. DISPOSE_CONFERENCE: "xmpp.dispoce_confernce",
  22287. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  22288. KICKED: "xmpp.kicked",
  22289. BRIDGE_DOWN: "xmpp.bridge_down",
  22290. USER_ID_CHANGED: "xmpp.user_id_changed",
  22291. CHANGED_STREAMS: "xmpp.changed_streams",
  22292. MUC_JOINED: "xmpp.muc_joined",
  22293. MUC_ENTER: "xmpp.muc_enter",
  22294. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  22295. MUC_LEFT: "xmpp.muc_left",
  22296. MUC_DESTROYED: "xmpp.muc_destroyed",
  22297. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  22298. REMOTE_STATS: "xmpp.remote_stats",
  22299. LOCALROLE_CHANGED: "xmpp.localrole_changed",
  22300. PRESENCE_STATUS: "xmpp.presence_status",
  22301. RESERVATION_ERROR: "xmpp.room_reservation_error",
  22302. SUBJECT_CHANGED: "xmpp.subject_changed",
  22303. MESSAGE_RECEIVED: "xmpp.message_received",
  22304. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  22305. PASSWORD_REQUIRED: "xmpp.password_required",
  22306. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  22307. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  22308. ETHERPAD: "xmpp.etherpad"
  22309. };
  22310. module.exports = XMPPEvents;
  22311. },{}],89:[function(require,module,exports){
  22312. // Copyright Joyent, Inc. and other Node contributors.
  22313. //
  22314. // Permission is hereby granted, free of charge, to any person obtaining a
  22315. // copy of this software and associated documentation files (the
  22316. // "Software"), to deal in the Software without restriction, including
  22317. // without limitation the rights to use, copy, modify, merge, publish,
  22318. // distribute, sublicense, and/or sell copies of the Software, and to permit
  22319. // persons to whom the Software is furnished to do so, subject to the
  22320. // following conditions:
  22321. //
  22322. // The above copyright notice and this permission notice shall be included
  22323. // in all copies or substantial portions of the Software.
  22324. //
  22325. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  22326. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22327. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  22328. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  22329. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22330. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  22331. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22332. function EventEmitter() {
  22333. this._events = this._events || {};
  22334. this._maxListeners = this._maxListeners || undefined;
  22335. }
  22336. module.exports = EventEmitter;
  22337. // Backwards-compat with node 0.10.x
  22338. EventEmitter.EventEmitter = EventEmitter;
  22339. EventEmitter.prototype._events = undefined;
  22340. EventEmitter.prototype._maxListeners = undefined;
  22341. // By default EventEmitters will print a warning if more than 10 listeners are
  22342. // added to it. This is a useful default which helps finding memory leaks.
  22343. EventEmitter.defaultMaxListeners = 10;
  22344. // Obviously not all Emitters should be limited to 10. This function allows
  22345. // that to be increased. Set to zero for unlimited.
  22346. EventEmitter.prototype.setMaxListeners = function(n) {
  22347. if (!isNumber(n) || n < 0 || isNaN(n))
  22348. throw TypeError('n must be a positive number');
  22349. this._maxListeners = n;
  22350. return this;
  22351. };
  22352. EventEmitter.prototype.emit = function(type) {
  22353. var er, handler, len, args, i, listeners;
  22354. if (!this._events)
  22355. this._events = {};
  22356. // If there is no 'error' event listener then throw.
  22357. if (type === 'error') {
  22358. if (!this._events.error ||
  22359. (isObject(this._events.error) && !this._events.error.length)) {
  22360. er = arguments[1];
  22361. if (er instanceof Error) {
  22362. throw er; // Unhandled 'error' event
  22363. }
  22364. throw TypeError('Uncaught, unspecified "error" event.');
  22365. }
  22366. }
  22367. handler = this._events[type];
  22368. if (isUndefined(handler))
  22369. return false;
  22370. if (isFunction(handler)) {
  22371. switch (arguments.length) {
  22372. // fast cases
  22373. case 1:
  22374. handler.call(this);
  22375. break;
  22376. case 2:
  22377. handler.call(this, arguments[1]);
  22378. break;
  22379. case 3:
  22380. handler.call(this, arguments[1], arguments[2]);
  22381. break;
  22382. // slower
  22383. default:
  22384. len = arguments.length;
  22385. args = new Array(len - 1);
  22386. for (i = 1; i < len; i++)
  22387. args[i - 1] = arguments[i];
  22388. handler.apply(this, args);
  22389. }
  22390. } else if (isObject(handler)) {
  22391. len = arguments.length;
  22392. args = new Array(len - 1);
  22393. for (i = 1; i < len; i++)
  22394. args[i - 1] = arguments[i];
  22395. listeners = handler.slice();
  22396. len = listeners.length;
  22397. for (i = 0; i < len; i++)
  22398. listeners[i].apply(this, args);
  22399. }
  22400. return true;
  22401. };
  22402. EventEmitter.prototype.addListener = function(type, listener) {
  22403. var m;
  22404. if (!isFunction(listener))
  22405. throw TypeError('listener must be a function');
  22406. if (!this._events)
  22407. this._events = {};
  22408. // To avoid recursion in the case that type === "newListener"! Before
  22409. // adding it to the listeners, first emit "newListener".
  22410. if (this._events.newListener)
  22411. this.emit('newListener', type,
  22412. isFunction(listener.listener) ?
  22413. listener.listener : listener);
  22414. if (!this._events[type])
  22415. // Optimize the case of one listener. Don't need the extra array object.
  22416. this._events[type] = listener;
  22417. else if (isObject(this._events[type]))
  22418. // If we've already got an array, just append.
  22419. this._events[type].push(listener);
  22420. else
  22421. // Adding the second element, need to change to array.
  22422. this._events[type] = [this._events[type], listener];
  22423. // Check for listener leak
  22424. if (isObject(this._events[type]) && !this._events[type].warned) {
  22425. var m;
  22426. if (!isUndefined(this._maxListeners)) {
  22427. m = this._maxListeners;
  22428. } else {
  22429. m = EventEmitter.defaultMaxListeners;
  22430. }
  22431. if (m && m > 0 && this._events[type].length > m) {
  22432. this._events[type].warned = true;
  22433. console.error('(node) warning: possible EventEmitter memory ' +
  22434. 'leak detected. %d listeners added. ' +
  22435. 'Use emitter.setMaxListeners() to increase limit.',
  22436. this._events[type].length);
  22437. if (typeof console.trace === 'function') {
  22438. // not supported in IE 10
  22439. console.trace();
  22440. }
  22441. }
  22442. }
  22443. return this;
  22444. };
  22445. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  22446. EventEmitter.prototype.once = function(type, listener) {
  22447. if (!isFunction(listener))
  22448. throw TypeError('listener must be a function');
  22449. var fired = false;
  22450. function g() {
  22451. this.removeListener(type, g);
  22452. if (!fired) {
  22453. fired = true;
  22454. listener.apply(this, arguments);
  22455. }
  22456. }
  22457. g.listener = listener;
  22458. this.on(type, g);
  22459. return this;
  22460. };
  22461. // emits a 'removeListener' event iff the listener was removed
  22462. EventEmitter.prototype.removeListener = function(type, listener) {
  22463. var list, position, length, i;
  22464. if (!isFunction(listener))
  22465. throw TypeError('listener must be a function');
  22466. if (!this._events || !this._events[type])
  22467. return this;
  22468. list = this._events[type];
  22469. length = list.length;
  22470. position = -1;
  22471. if (list === listener ||
  22472. (isFunction(list.listener) && list.listener === listener)) {
  22473. delete this._events[type];
  22474. if (this._events.removeListener)
  22475. this.emit('removeListener', type, listener);
  22476. } else if (isObject(list)) {
  22477. for (i = length; i-- > 0;) {
  22478. if (list[i] === listener ||
  22479. (list[i].listener && list[i].listener === listener)) {
  22480. position = i;
  22481. break;
  22482. }
  22483. }
  22484. if (position < 0)
  22485. return this;
  22486. if (list.length === 1) {
  22487. list.length = 0;
  22488. delete this._events[type];
  22489. } else {
  22490. list.splice(position, 1);
  22491. }
  22492. if (this._events.removeListener)
  22493. this.emit('removeListener', type, listener);
  22494. }
  22495. return this;
  22496. };
  22497. EventEmitter.prototype.removeAllListeners = function(type) {
  22498. var key, listeners;
  22499. if (!this._events)
  22500. return this;
  22501. // not listening for removeListener, no need to emit
  22502. if (!this._events.removeListener) {
  22503. if (arguments.length === 0)
  22504. this._events = {};
  22505. else if (this._events[type])
  22506. delete this._events[type];
  22507. return this;
  22508. }
  22509. // emit removeListener for all listeners on all events
  22510. if (arguments.length === 0) {
  22511. for (key in this._events) {
  22512. if (key === 'removeListener') continue;
  22513. this.removeAllListeners(key);
  22514. }
  22515. this.removeAllListeners('removeListener');
  22516. this._events = {};
  22517. return this;
  22518. }
  22519. listeners = this._events[type];
  22520. if (isFunction(listeners)) {
  22521. this.removeListener(type, listeners);
  22522. } else {
  22523. // LIFO order
  22524. while (listeners.length)
  22525. this.removeListener(type, listeners[listeners.length - 1]);
  22526. }
  22527. delete this._events[type];
  22528. return this;
  22529. };
  22530. EventEmitter.prototype.listeners = function(type) {
  22531. var ret;
  22532. if (!this._events || !this._events[type])
  22533. ret = [];
  22534. else if (isFunction(this._events[type]))
  22535. ret = [this._events[type]];
  22536. else
  22537. ret = this._events[type].slice();
  22538. return ret;
  22539. };
  22540. EventEmitter.listenerCount = function(emitter, type) {
  22541. var ret;
  22542. if (!emitter._events || !emitter._events[type])
  22543. ret = 0;
  22544. else if (isFunction(emitter._events[type]))
  22545. ret = 1;
  22546. else
  22547. ret = emitter._events[type].length;
  22548. return ret;
  22549. };
  22550. function isFunction(arg) {
  22551. return typeof arg === 'function';
  22552. }
  22553. function isNumber(arg) {
  22554. return typeof arg === 'number';
  22555. }
  22556. function isObject(arg) {
  22557. return typeof arg === 'object' && arg !== null;
  22558. }
  22559. function isUndefined(arg) {
  22560. return arg === void 0;
  22561. }
  22562. },{}]},{},[1])(1)
  22563. });