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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226
  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. this.settings = require("./modules/settings/Settings");
  18. }
  19. };
  20. function init() {
  21. APP.RTC.start();
  22. APP.xmpp.start();
  23. APP.statistics.start();
  24. APP.connectionquality.init();
  25. // Set default desktop sharing method
  26. APP.desktopsharing.init();
  27. APP.keyboardshortcut.init();
  28. }
  29. $(document).ready(function () {
  30. APP.init();
  31. APP.translation.init();
  32. if(APP.API.isEnabled())
  33. APP.API.init();
  34. APP.UI.start(init);
  35. });
  36. $(window).bind('beforeunload', function () {
  37. if(APP.API.isEnabled())
  38. APP.API.dispose();
  39. });
  40. module.exports = APP;
  41. },{"./modules/API/API":2,"./modules/RTC/RTC":6,"./modules/UI/UI":8,"./modules/connectionquality/connectionquality":35,"./modules/desktopsharing/desktopsharing":36,"./modules/keyboardshortcut/keyboardshortcut":37,"./modules/settings/Settings":38,"./modules/simulcast/simulcast":43,"./modules/statistics/statistics":46,"./modules/translation/translation":47,"./modules/xmpp/xmpp":61}],2:[function(require,module,exports){
  42. /**
  43. * Implements API class that communicates with external api class
  44. * and provides interface to access Jitsi Meet features by external
  45. * applications that embed Jitsi Meet
  46. */
  47. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  48. /**
  49. * List of the available commands.
  50. * @type {{
  51. * displayName: inputDisplayNameHandler,
  52. * muteAudio: toggleAudio,
  53. * muteVideo: toggleVideo,
  54. * filmStrip: toggleFilmStrip
  55. * }}
  56. */
  57. var commands =
  58. {
  59. displayName: APP.UI.inputDisplayNameHandler,
  60. muteAudio: APP.UI.toggleAudio,
  61. muteVideo: APP.UI.toggleVideo,
  62. toggleFilmStrip: APP.UI.toggleFilmStrip,
  63. toggleChat: APP.UI.toggleChat,
  64. toggleContactList: APP.UI.toggleContactList
  65. };
  66. /**
  67. * Maps the supported events and their status
  68. * (true it the event is enabled and false if it is disabled)
  69. * @type {{
  70. * incomingMessage: boolean,
  71. * outgoingMessage: boolean,
  72. * displayNameChange: boolean,
  73. * participantJoined: boolean,
  74. * participantLeft: boolean
  75. * }}
  76. */
  77. var events =
  78. {
  79. incomingMessage: false,
  80. outgoingMessage:false,
  81. displayNameChange: false,
  82. participantJoined: false,
  83. participantLeft: false
  84. };
  85. var displayName = {};
  86. /**
  87. * Processes commands from external applicaiton.
  88. * @param message the object with the command
  89. */
  90. function processCommand(message)
  91. {
  92. if(message.action != "execute")
  93. {
  94. console.error("Unknown action of the message");
  95. return;
  96. }
  97. for(var key in message)
  98. {
  99. if(commands[key])
  100. commands[key].apply(null, message[key]);
  101. }
  102. }
  103. /**
  104. * Processes events objects from external applications
  105. * @param event the event
  106. */
  107. function processEvent(event) {
  108. if(!event.action)
  109. {
  110. console.error("Event with no action is received.");
  111. return;
  112. }
  113. var i = 0;
  114. switch(event.action)
  115. {
  116. case "add":
  117. for(; i < event.events.length; i++)
  118. {
  119. events[event.events[i]] = true;
  120. }
  121. break;
  122. case "remove":
  123. for(; i < event.events.length; i++)
  124. {
  125. events[event.events[i]] = false;
  126. }
  127. break;
  128. default:
  129. console.error("Unknown action for event.");
  130. }
  131. }
  132. /**
  133. * Sends message to the external application.
  134. * @param object
  135. */
  136. function sendMessage(object) {
  137. window.parent.postMessage(JSON.stringify(object), "*");
  138. }
  139. /**
  140. * Processes a message event from the external application
  141. * @param event the message event
  142. */
  143. function processMessage(event)
  144. {
  145. var message;
  146. try {
  147. message = JSON.parse(event.data);
  148. } catch (e) {}
  149. if(!message.type)
  150. return;
  151. switch (message.type)
  152. {
  153. case "command":
  154. processCommand(message);
  155. break;
  156. case "event":
  157. processEvent(message);
  158. break;
  159. default:
  160. console.error("Unknown type of the message");
  161. return;
  162. }
  163. }
  164. function setupListeners() {
  165. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, function (from) {
  166. API.triggerEvent("participantJoined", {jid: from});
  167. });
  168. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid) {
  169. if (from != myjid)
  170. API.triggerEvent("incomingMessage",
  171. {"from": from, "nick": nick, "message": txt});
  172. });
  173. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, function (jid) {
  174. API.triggerEvent("participantLeft", {jid: jid});
  175. });
  176. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  177. name = displayName[jid];
  178. if(!name || name != newDisplayName) {
  179. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  180. displayName[jid] = newDisplayName;
  181. }
  182. });
  183. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  184. APP.API.triggerEvent("outgoingMessage", {"message": body});
  185. });
  186. }
  187. var API = {
  188. /**
  189. * Check whether the API should be enabled or not.
  190. * @returns {boolean}
  191. */
  192. isEnabled: function () {
  193. var hash = location.hash;
  194. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  195. return true;
  196. return false;
  197. },
  198. /**
  199. * Initializes the APIConnector. Setups message event listeners that will
  200. * receive information from external applications that embed Jitsi Meet.
  201. * It also sends a message to the external application that APIConnector
  202. * is initialized.
  203. */
  204. init: function () {
  205. if (window.addEventListener)
  206. {
  207. window.addEventListener('message',
  208. processMessage, false);
  209. }
  210. else
  211. {
  212. window.attachEvent('onmessage', processMessage);
  213. }
  214. sendMessage({type: "system", loaded: true});
  215. setupListeners();
  216. },
  217. /**
  218. * Checks whether the event is enabled ot not.
  219. * @param name the name of the event.
  220. * @returns {*}
  221. */
  222. isEventEnabled: function (name) {
  223. return events[name];
  224. },
  225. /**
  226. * Sends event object to the external application that has been subscribed
  227. * for that event.
  228. * @param name the name event
  229. * @param object data associated with the event
  230. */
  231. triggerEvent: function (name, object) {
  232. if(this.isEnabled() && this.isEventEnabled(name))
  233. sendMessage({
  234. type: "event", action: "result", event: name, result: object});
  235. },
  236. /**
  237. * Removes the listeners.
  238. */
  239. dispose: function () {
  240. if(window.removeEventListener)
  241. {
  242. window.removeEventListener("message",
  243. processMessage, false);
  244. }
  245. else
  246. {
  247. window.detachEvent('onmessage', processMessage);
  248. }
  249. }
  250. };
  251. module.exports = API;
  252. },{"../../service/xmpp/XMPPEvents":97}],3:[function(require,module,exports){
  253. /* global Strophe, focusedVideoSrc*/
  254. // cache datachannels to avoid garbage collection
  255. // https://code.google.com/p/chromium/issues/detail?id=405545
  256. var RTCEvents = require("../../service/RTC/RTCEvents");
  257. var _dataChannels = [];
  258. var eventEmitter = null;
  259. var DataChannels =
  260. {
  261. /**
  262. * Callback triggered by PeerConnection when new data channel is opened
  263. * on the bridge.
  264. * @param event the event info object.
  265. */
  266. onDataChannel: function (event)
  267. {
  268. var dataChannel = event.channel;
  269. dataChannel.onopen = function () {
  270. console.info("Data channel opened by the Videobridge!", dataChannel);
  271. // Code sample for sending string and/or binary data
  272. // Sends String message to the bridge
  273. //dataChannel.send("Hello bridge!");
  274. // Sends 12 bytes binary message to the bridge
  275. //dataChannel.send(new ArrayBuffer(12));
  276. // when the data channel becomes available, tell the bridge about video
  277. // selections so that it can do adaptive simulcast,
  278. // we want the notification to trigger even if userJid is undefined,
  279. // or null.
  280. var userJid = APP.UI.getLargeVideoState().userResourceJid;
  281. // we want the notification to trigger even if userJid is undefined,
  282. // or null.
  283. onSelectedEndpointChanged(userJid);
  284. };
  285. dataChannel.onerror = function (error) {
  286. console.error("Data Channel Error:", error, dataChannel);
  287. };
  288. dataChannel.onmessage = function (event) {
  289. var data = event.data;
  290. // JSON
  291. var obj;
  292. try {
  293. obj = JSON.parse(data);
  294. }
  295. catch (e) {
  296. console.error(
  297. "Failed to parse data channel message as JSON: ",
  298. data,
  299. dataChannel);
  300. }
  301. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  302. var colibriClass = obj.colibriClass;
  303. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  304. // Endpoint ID from the Videobridge.
  305. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  306. console.info(
  307. "Data channel new dominant speaker event: ",
  308. dominantSpeakerEndpoint);
  309. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  310. }
  311. else if ("InLastNChangeEvent" === colibriClass)
  312. {
  313. var oldValue = obj.oldValue;
  314. var newValue = obj.newValue;
  315. // Make sure that oldValue and newValue are of type boolean.
  316. var type;
  317. if ((type = typeof oldValue) !== 'boolean') {
  318. if (type === 'string') {
  319. oldValue = (oldValue == "true");
  320. } else {
  321. oldValue = new Boolean(oldValue).valueOf();
  322. }
  323. }
  324. if ((type = typeof newValue) !== 'boolean') {
  325. if (type === 'string') {
  326. newValue = (newValue == "true");
  327. } else {
  328. newValue = new Boolean(newValue).valueOf();
  329. }
  330. }
  331. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  332. }
  333. else if ("LastNEndpointsChangeEvent" === colibriClass)
  334. {
  335. // The new/latest list of last-n endpoint IDs.
  336. var lastNEndpoints = obj.lastNEndpoints;
  337. // The list of endpoint IDs which are entering the list of
  338. // last-n at this time i.e. were not in the old list of last-n
  339. // endpoint IDs.
  340. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  341. var stream = obj.stream;
  342. console.log(
  343. "Data channel new last-n event: ",
  344. lastNEndpoints, endpointsEnteringLastN, obj);
  345. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  346. lastNEndpoints, endpointsEnteringLastN, obj);
  347. }
  348. else if ("SimulcastLayersChangedEvent" === colibriClass)
  349. {
  350. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGED,
  351. obj.endpointSimulcastLayers);
  352. }
  353. else if ("SimulcastLayersChangingEvent" === colibriClass)
  354. {
  355. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGING,
  356. obj.endpointSimulcastLayers);
  357. }
  358. else if ("StartSimulcastLayerEvent" === colibriClass)
  359. {
  360. eventEmitter.emit(RTCEvents.SIMULCAST_START, obj.simulcastLayer);
  361. }
  362. else if ("StopSimulcastLayerEvent" === colibriClass)
  363. {
  364. eventEmitter.emit(RTCEvents.SIMULCAST_STOP, obj.simulcastLayer);
  365. }
  366. else
  367. {
  368. console.debug("Data channel JSON-formatted message: ", obj);
  369. }
  370. }
  371. };
  372. dataChannel.onclose = function ()
  373. {
  374. console.info("The Data Channel closed", dataChannel);
  375. var idx = _dataChannels.indexOf(dataChannel);
  376. if (idx > -1)
  377. _dataChannels = _dataChannels.splice(idx, 1);
  378. };
  379. _dataChannels.push(dataChannel);
  380. },
  381. /**
  382. * Binds "ondatachannel" event listener to given PeerConnection instance.
  383. * @param peerConnection WebRTC peer connection instance.
  384. */
  385. init: function (peerConnection, emitter) {
  386. if(!config.openSctp)
  387. return;
  388. peerConnection.ondatachannel = this.onDataChannel;
  389. eventEmitter = emitter;
  390. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  391. // Although it's not a requirement to open separate channels from both bridge
  392. // and peer as single channel can be used for sending and receiving data.
  393. // So either channel opened by the bridge or the one opened here is enough
  394. // for communication with the bridge.
  395. /*var dataChannelOptions =
  396. {
  397. reliable: true
  398. };
  399. var dataChannel
  400. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  401. // Can be used only when is in open state
  402. dataChannel.onopen = function ()
  403. {
  404. dataChannel.send("My channel !!!");
  405. };
  406. dataChannel.onmessage = function (event)
  407. {
  408. var msgData = event.data;
  409. console.info("Got My Data Channel Message:", msgData, dataChannel);
  410. };*/
  411. },
  412. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  413. handlePinnedEndpointEvent: onPinnedEndpointChanged
  414. };
  415. function onSelectedEndpointChanged(userResource)
  416. {
  417. console.log('selected endpoint changed: ', userResource);
  418. if (_dataChannels && _dataChannels.length != 0)
  419. {
  420. _dataChannels.some(function (dataChannel) {
  421. if (dataChannel.readyState == 'open')
  422. {
  423. console.log('sending selected endpoint changed '
  424. + 'notification to the bridge: ', userResource);
  425. dataChannel.send(JSON.stringify({
  426. 'colibriClass': 'SelectedEndpointChangedEvent',
  427. 'selectedEndpoint':
  428. (!userResource || userResource === null)?
  429. null : userResource
  430. }));
  431. return true;
  432. }
  433. });
  434. }
  435. }
  436. function onPinnedEndpointChanged(userResource)
  437. {
  438. console.log('pinned endpoint changed: ', userResource);
  439. if (_dataChannels && _dataChannels.length != 0)
  440. {
  441. _dataChannels.some(function (dataChannel) {
  442. if (dataChannel.readyState == 'open')
  443. {
  444. dataChannel.send(JSON.stringify({
  445. 'colibriClass': 'PinnedEndpointChangedEvent',
  446. 'pinnedEndpoint':
  447. (!userResource || userResource == null)?
  448. null : userResource
  449. }));
  450. return true;
  451. }
  452. });
  453. }
  454. }
  455. module.exports = DataChannels;
  456. },{"../../service/RTC/RTCEvents":89}],4:[function(require,module,exports){
  457. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  458. function LocalStream(stream, type, eventEmitter, videoType)
  459. {
  460. this.stream = stream;
  461. this.eventEmitter = eventEmitter;
  462. this.type = type;
  463. this.videoType = videoType;
  464. var self = this;
  465. if(type == "audio")
  466. {
  467. this.getTracks = function () {
  468. return self.stream.getAudioTracks();
  469. };
  470. }
  471. else
  472. {
  473. this.getTracks = function () {
  474. return self.stream.getVideoTracks();
  475. };
  476. }
  477. this.stream.onended = function()
  478. {
  479. self.streamEnded();
  480. };
  481. }
  482. LocalStream.prototype.streamEnded = function () {
  483. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  484. }
  485. LocalStream.prototype.getOriginalStream = function()
  486. {
  487. return this.stream;
  488. }
  489. LocalStream.prototype.isAudioStream = function () {
  490. return (this.stream.getAudioTracks() && this.stream.getAudioTracks().length > 0);
  491. };
  492. LocalStream.prototype.mute = function()
  493. {
  494. var ismuted = false;
  495. var tracks = this.getTracks();
  496. for (var idx = 0; idx < tracks.length; idx++) {
  497. ismuted = !tracks[idx].enabled;
  498. tracks[idx].enabled = ismuted;
  499. }
  500. return ismuted;
  501. };
  502. LocalStream.prototype.setMute = function(mute)
  503. {
  504. var tracks = this.getTracks();
  505. for (var idx = 0; idx < tracks.length; idx++) {
  506. tracks[idx].enabled = mute;
  507. }
  508. };
  509. LocalStream.prototype.isMuted = function () {
  510. var tracks = [];
  511. if(this.type == "audio")
  512. {
  513. tracks = this.stream.getAudioTracks();
  514. }
  515. else
  516. {
  517. tracks = this.stream.getVideoTracks();
  518. }
  519. for (var idx = 0; idx < tracks.length; idx++) {
  520. if(tracks[idx].enabled)
  521. return false;
  522. }
  523. return true;
  524. }
  525. LocalStream.prototype.getId = function () {
  526. return this.stream.getTracks()[0].id;
  527. }
  528. module.exports = LocalStream;
  529. },{"../../service/RTC/StreamEventTypes.js":91}],5:[function(require,module,exports){
  530. ////These lines should be uncommented when require works in app.js
  531. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  532. var StreamEventType = require("../../service/RTC/StreamEventTypes");
  533. /**
  534. * Creates a MediaStream object for the given data, session id and ssrc.
  535. * It is a wrapper class for the MediaStream.
  536. *
  537. * @param data the data object from which we obtain the stream,
  538. * the peerjid, etc.
  539. * @param sid the session id
  540. * @param ssrc the ssrc corresponding to this MediaStream
  541. *
  542. * @constructor
  543. */
  544. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  545. // XXX(gp) to minimize headaches in the future, we should build our
  546. // abstractions around tracks and not streams. ORTC is track based API.
  547. // Mozilla expects m-lines to represent media tracks.
  548. //
  549. // Practically, what I'm saying is that we should have a MediaTrack class
  550. // and not a MediaStream class.
  551. //
  552. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  553. // a track might have an associated RTX and FEC sources.
  554. this.sid = sid;
  555. this.stream = data.stream;
  556. this.peerjid = data.peerjid;
  557. this.ssrc = ssrc;
  558. this.type = (this.stream.getVideoTracks().length > 0)?
  559. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  560. this.videoType = null;
  561. this.muted = false;
  562. this.eventEmitter = eventEmitter;
  563. }
  564. MediaStream.prototype.getOriginalStream = function()
  565. {
  566. return this.stream;
  567. };
  568. MediaStream.prototype.setMute = function (value)
  569. {
  570. this.stream.muted = value;
  571. this.muted = value;
  572. };
  573. MediaStream.prototype.setVideoType = function (value) {
  574. if(this.videoType === value)
  575. return;
  576. this.videoType = value;
  577. this.eventEmitter.emit(StreamEventType.EVENT_TYPE_REMOTE_CHANGED,
  578. this.peerjid);
  579. };
  580. module.exports = MediaStream;
  581. },{"../../service/RTC/MediaStreamTypes":87,"../../service/RTC/StreamEventTypes":91}],6:[function(require,module,exports){
  582. var EventEmitter = require("events");
  583. var RTCUtils = require("./RTCUtils.js");
  584. var LocalStream = require("./LocalStream.js");
  585. var DataChannels = require("./DataChannels");
  586. var MediaStream = require("./MediaStream.js");
  587. var DesktopSharingEventTypes
  588. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  589. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  590. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  591. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  592. var UIEvents = require("../../service/UI/UIEvents");
  593. var eventEmitter = new EventEmitter();
  594. var RTC = {
  595. rtcUtils: null,
  596. localStreams: [],
  597. remoteStreams: {},
  598. localAudio: null,
  599. localVideo: null,
  600. addStreamListener: function (listener, eventType) {
  601. eventEmitter.on(eventType, listener);
  602. },
  603. addListener: function (type, listener) {
  604. eventEmitter.on(type, listener);
  605. },
  606. removeStreamListener: function (listener, eventType) {
  607. if(!(eventType instanceof StreamEventTypes))
  608. throw "Illegal argument";
  609. eventEmitter.removeListener(eventType, listener);
  610. },
  611. createLocalStream: function (stream, type, change) {
  612. var localStream = new LocalStream(stream, type, eventEmitter);
  613. //in firefox we have only one stream object
  614. if(this.localStreams.length == 0 ||
  615. this.localStreams[0].getOriginalStream() != stream)
  616. this.localStreams.push(localStream);
  617. if(type == "audio")
  618. {
  619. this.localAudio = localStream;
  620. }
  621. else
  622. {
  623. this.localVideo = localStream;
  624. }
  625. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  626. if(change)
  627. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  628. eventEmitter.emit(eventType, localStream);
  629. return localStream;
  630. },
  631. removeLocalStream: function (stream) {
  632. for(var i = 0; i < this.localStreams.length; i++)
  633. {
  634. if(this.localStreams[i].getOriginalStream() === stream) {
  635. delete this.localStreams[i];
  636. return;
  637. }
  638. }
  639. },
  640. createRemoteStream: function (data, sid, thessrc) {
  641. var remoteStream = new MediaStream(data, sid, thessrc,
  642. this.getBrowserType(), eventEmitter);
  643. var jid = data.peerjid || APP.xmpp.myJid();
  644. if(!this.remoteStreams[jid]) {
  645. this.remoteStreams[jid] = {};
  646. }
  647. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  648. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  649. return remoteStream;
  650. },
  651. getBrowserType: function () {
  652. return this.rtcUtils.browser;
  653. },
  654. getPCConstraints: function () {
  655. return this.rtcUtils.pc_constraints;
  656. },
  657. getUserMediaWithConstraints:function(um, success_callback,
  658. failure_callback, resolution,
  659. bandwidth, fps, desktopStream)
  660. {
  661. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  662. failure_callback, resolution, bandwidth, fps, desktopStream);
  663. },
  664. attachMediaStream: function (element, stream) {
  665. this.rtcUtils.attachMediaStream(element, stream);
  666. },
  667. getStreamID: function (stream) {
  668. return this.rtcUtils.getStreamID(stream);
  669. },
  670. getVideoSrc: function (element) {
  671. return this.rtcUtils.getVideoSrc(element);
  672. },
  673. setVideoSrc: function (element, src) {
  674. this.rtcUtils.setVideoSrc(element, src);
  675. },
  676. dispose: function() {
  677. if (this.rtcUtils) {
  678. this.rtcUtils = null;
  679. }
  680. },
  681. stop: function () {
  682. this.dispose();
  683. },
  684. start: function () {
  685. var self = this;
  686. APP.desktopsharing.addListener(
  687. function (stream, isUsingScreenStream, callback) {
  688. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  689. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  690. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  691. for(var i = 0; i < changedStreams.length; i++) {
  692. var type = changedStreams[i].type;
  693. if (type != "audio") {
  694. var peerStreams = self.remoteStreams[jid];
  695. if(!peerStreams)
  696. continue;
  697. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  698. if(!videoStream)
  699. continue;
  700. videoStream.setVideoType(changedStreams[i].type);
  701. }
  702. }
  703. });
  704. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  705. DataChannels.init(event.peerconnection, eventEmitter);
  706. });
  707. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  708. DataChannels.handleSelectedEndpointEvent);
  709. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  710. DataChannels.handlePinnedEndpointEvent);
  711. this.rtcUtils = new RTCUtils(this);
  712. this.rtcUtils.obtainAudioAndVideoPermissions();
  713. },
  714. muteRemoteVideoStream: function (jid, value) {
  715. var stream;
  716. if(this.remoteStreams[jid] &&
  717. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  718. {
  719. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  720. }
  721. if(!stream)
  722. return false;
  723. if (value != stream.muted) {
  724. stream.setMute(value);
  725. return true;
  726. }
  727. return false;
  728. },
  729. switchVideoStreams: function (new_stream) {
  730. this.localVideo.stream = new_stream;
  731. this.localStreams = [];
  732. //in firefox we have only one stream object
  733. if (this.localAudio.getOriginalStream() != new_stream)
  734. this.localStreams.push(this.localAudio);
  735. this.localStreams.push(this.localVideo);
  736. },
  737. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  738. var oldStream = this.localVideo.getOriginalStream();
  739. var type = (isUsingScreenStream? "screen" : "video");
  740. this.localVideo = this.createLocalStream(stream, "video", true, type);
  741. // Stop the stream to trigger onended event for old stream
  742. oldStream.stop();
  743. APP.xmpp.switchStreams(stream, oldStream,callback);
  744. },
  745. /**
  746. * Checks if video identified by given src is desktop stream.
  747. * @param videoSrc eg.
  748. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  749. * @returns {boolean}
  750. */
  751. isVideoSrcDesktop: function (jid) {
  752. if(!jid)
  753. return false;
  754. var isDesktop = false;
  755. var stream = null;
  756. if (APP.xmpp.myJid() === 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":87,"../../service/RTC/StreamEventTypes.js":91,"../../service/UI/UIEvents":92,"../../service/desktopsharing/DesktopSharingEventTypes":95,"../../service/xmpp/XMPPEvents":97,"./DataChannels":3,"./LocalStream.js":4,"./MediaStream.js":5,"./RTCUtils.js":7,"events":98}],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 >= 39) {
  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. // srcObject is being standardized and FF will eventually
  898. // support that unprefixed. FF also supports the
  899. // "element.src = URL.createObjectURL(...)" combo, but that
  900. // will be deprecated in favour of srcObject.
  901. //
  902. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  903. // https://github.com/webrtc/samples/issues/302
  904. element[0].mozSrcObject = stream;
  905. element[0].play();
  906. };
  907. this.getStreamID = function (stream) {
  908. var tracks = stream.getVideoTracks();
  909. if(!tracks || tracks.length == 0)
  910. {
  911. tracks = stream.getAudioTracks();
  912. }
  913. return tracks[0].id.replace(/[\{,\}]/g,"");
  914. };
  915. this.getVideoSrc = function (element) {
  916. return element.mozSrcObject;
  917. };
  918. this.setVideoSrc = function (element, src) {
  919. element.mozSrcObject = src;
  920. };
  921. RTCSessionDescription = mozRTCSessionDescription;
  922. RTCIceCandidate = mozRTCIceCandidate;
  923. } else {
  924. window.location.href = 'unsupported_browser.html';
  925. return;
  926. }
  927. } else if (navigator.webkitGetUserMedia) {
  928. console.log('This appears to be Chrome');
  929. this.peerconnection = webkitRTCPeerConnection;
  930. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  931. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  932. this.attachMediaStream = function (element, stream) {
  933. element.attr('src', webkitURL.createObjectURL(stream));
  934. };
  935. this.getStreamID = function (stream) {
  936. // streams from FF endpoints have the characters '{' and '}'
  937. // that make jQuery choke.
  938. return stream.id.replace(/[\{,\}]/g,"");
  939. };
  940. this.getVideoSrc = function (element) {
  941. return element.getAttribute("src");
  942. };
  943. this.setVideoSrc = function (element, src) {
  944. element.setAttribute("src", src);
  945. };
  946. // DTLS should now be enabled by default but..
  947. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  948. if (navigator.userAgent.indexOf('Android') != -1) {
  949. this.pc_constraints = {}; // disable DTLS on Android
  950. }
  951. if (!webkitMediaStream.prototype.getVideoTracks) {
  952. webkitMediaStream.prototype.getVideoTracks = function () {
  953. return this.videoTracks;
  954. };
  955. }
  956. if (!webkitMediaStream.prototype.getAudioTracks) {
  957. webkitMediaStream.prototype.getAudioTracks = function () {
  958. return this.audioTracks;
  959. };
  960. }
  961. }
  962. else
  963. {
  964. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  965. window.location.href = 'unsupported_browser.html';
  966. return;
  967. }
  968. }
  969. RTCUtils.prototype.getUserMediaWithConstraints = function(
  970. um, success_callback, failure_callback, resolution,bandwidth, fps,
  971. desktopStream)
  972. {
  973. currentResolution = resolution;
  974. // Check if we are running on Android device
  975. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  976. var constraints = getConstraints(
  977. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  978. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  979. try {
  980. if (config.enableSimulcast
  981. && constraints.video
  982. && constraints.video.chromeMediaSource !== 'screen'
  983. && constraints.video.chromeMediaSource !== 'desktop'
  984. && !isAndroid
  985. // We currently do not support FF, as it doesn't have multistream support.
  986. && !isFF) {
  987. APP.simulcast.getUserMedia(constraints, function (stream) {
  988. console.log('onUserMediaSuccess');
  989. success_callback(stream);
  990. },
  991. function (error) {
  992. console.warn('Failed to get access to local media. Error ', error);
  993. if (failure_callback) {
  994. failure_callback(error);
  995. }
  996. });
  997. } else {
  998. this.getUserMedia(constraints,
  999. function (stream) {
  1000. console.log('onUserMediaSuccess');
  1001. success_callback(stream);
  1002. },
  1003. function (error) {
  1004. console.warn('Failed to get access to local media. Error ',
  1005. error, constraints);
  1006. if (failure_callback) {
  1007. failure_callback(error);
  1008. }
  1009. });
  1010. }
  1011. } catch (e) {
  1012. console.error('GUM failed: ', e);
  1013. if(failure_callback) {
  1014. failure_callback(e);
  1015. }
  1016. }
  1017. };
  1018. /**
  1019. * We ask for audio and video combined stream in order to get permissions and
  1020. * not to ask twice.
  1021. */
  1022. RTCUtils.prototype.obtainAudioAndVideoPermissions = function() {
  1023. var self = this;
  1024. // Get AV
  1025. this.getUserMediaWithConstraints(
  1026. ['audio', 'video'],
  1027. function (stream) {
  1028. self.successCallback(stream);
  1029. },
  1030. function (error) {
  1031. self.errorCallback(error);
  1032. },
  1033. config.resolution || '360');
  1034. }
  1035. RTCUtils.prototype.successCallback = function (stream) {
  1036. console.log('got', stream, stream.getAudioTracks().length,
  1037. stream.getVideoTracks().length);
  1038. this.handleLocalStream(stream);
  1039. };
  1040. RTCUtils.prototype.errorCallback = function (error) {
  1041. var self = this;
  1042. console.error('failed to obtain audio/video stream - trying audio only', error);
  1043. var resolution = getPreviousResolution(currentResolution);
  1044. if(typeof error == "object" && error.constraintName && error.name
  1045. && (error.name == "ConstraintNotSatisfiedError" ||
  1046. error.name == "OverconstrainedError") &&
  1047. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1048. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1049. && resolution != null)
  1050. {
  1051. self.getUserMediaWithConstraints(['audio', 'video'],
  1052. function (stream) {
  1053. return self.successCallback(stream);
  1054. }, function (error) {
  1055. return self.errorCallback(error);
  1056. }, resolution);
  1057. }
  1058. else
  1059. {
  1060. self.getUserMediaWithConstraints(
  1061. ['audio'],
  1062. function (stream) {
  1063. return self.successCallback(stream);
  1064. },
  1065. function (error) {
  1066. console.error('failed to obtain audio/video stream - stop',
  1067. error);
  1068. APP.UI.messageHandler.showError("dialog.error",
  1069. "dialog.failedpermissions");
  1070. }
  1071. );
  1072. }
  1073. }
  1074. RTCUtils.prototype.handleLocalStream = function(stream)
  1075. {
  1076. if(window.webkitMediaStream)
  1077. {
  1078. var audioStream = new webkitMediaStream();
  1079. var videoStream = new webkitMediaStream();
  1080. var audioTracks = stream.getAudioTracks();
  1081. var videoTracks = stream.getVideoTracks();
  1082. for (var i = 0; i < audioTracks.length; i++) {
  1083. audioStream.addTrack(audioTracks[i]);
  1084. }
  1085. this.service.createLocalStream(audioStream, "audio");
  1086. for (i = 0; i < videoTracks.length; i++) {
  1087. videoStream.addTrack(videoTracks[i]);
  1088. }
  1089. this.service.createLocalStream(videoStream, "video");
  1090. }
  1091. else
  1092. {//firefox
  1093. this.service.createLocalStream(stream, "stream");
  1094. }
  1095. };
  1096. module.exports = RTCUtils;
  1097. },{"../../service/RTC/RTCBrowserType.js":88,"../../service/RTC/Resolutions":90}],8:[function(require,module,exports){
  1098. var UI = {};
  1099. var VideoLayout = require("./videolayout/VideoLayout.js");
  1100. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1101. var Prezi = require("./prezi/Prezi.js");
  1102. var Etherpad = require("./etherpad/Etherpad.js");
  1103. var Chat = require("./side_pannels/chat/Chat.js");
  1104. var Toolbar = require("./toolbars/Toolbar");
  1105. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1106. var BottomToolbar = require("./toolbars/BottomToolbar");
  1107. var ContactList = require("./side_pannels/contactlist/ContactList");
  1108. var Avatar = require("./avatar/Avatar");
  1109. var EventEmitter = require("events");
  1110. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1111. var Settings = require("./../settings/Settings");
  1112. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1113. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1114. UI.messageHandler = require("./util/MessageHandler");
  1115. var messageHandler = UI.messageHandler;
  1116. var Authentication = require("./authentication/Authentication");
  1117. var UIUtil = require("./util/UIUtil");
  1118. var NicknameHandler = require("./util/NicknameHandler");
  1119. var CQEvents = require("../../service/connectionquality/CQEvents");
  1120. var DesktopSharingEventTypes
  1121. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1122. var RTCEvents = require("../../service/RTC/RTCEvents");
  1123. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1124. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1125. var eventEmitter = new EventEmitter();
  1126. var roomName = null;
  1127. function setupPrezi()
  1128. {
  1129. $("#reloadPresentationLink").click(function()
  1130. {
  1131. Prezi.reloadPresentation();
  1132. });
  1133. }
  1134. function setupChat()
  1135. {
  1136. Chat.init();
  1137. $("#toggle_smileys").click(function() {
  1138. Chat.toggleSmileys();
  1139. });
  1140. }
  1141. function setupToolbars() {
  1142. Toolbar.init(UI);
  1143. Toolbar.setupButtonsFromConfig();
  1144. BottomToolbar.init();
  1145. }
  1146. function streamHandler(stream) {
  1147. switch (stream.type)
  1148. {
  1149. case "audio":
  1150. VideoLayout.changeLocalAudio(stream);
  1151. break;
  1152. case "video":
  1153. VideoLayout.changeLocalVideo(stream);
  1154. break;
  1155. case "stream":
  1156. VideoLayout.changeLocalStream(stream);
  1157. break;
  1158. }
  1159. }
  1160. function onDisposeConference(unload) {
  1161. Toolbar.showAuthenticateButton(false);
  1162. };
  1163. function onDisplayNameChanged(jid, displayName) {
  1164. ContactList.onDisplayNameChange(jid, displayName);
  1165. SettingsMenu.onDisplayNameChange(jid, displayName);
  1166. VideoLayout.onDisplayNameChanged(jid, displayName);
  1167. }
  1168. function registerListeners() {
  1169. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1170. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1171. APP.RTC.addStreamListener(function (stream) {
  1172. VideoLayout.onRemoteStreamAdded(stream);
  1173. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1174. APP.RTC.addStreamListener(function (jid) {
  1175. VideoLayout.onVideoTypeChanged(jid);
  1176. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  1177. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1178. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1179. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1180. });
  1181. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1182. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1183. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1184. endpointsEnteringLastN, stream);
  1185. });
  1186. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  1187. function (endpointSimulcastLayers) {
  1188. VideoLayout.onSimulcastLayersChanged(endpointSimulcastLayers);
  1189. });
  1190. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGING,
  1191. function (endpointSimulcastLayers) {
  1192. VideoLayout.onSimulcastLayersChanging(endpointSimulcastLayers);
  1193. });
  1194. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1195. {
  1196. var resourceJid;
  1197. if(jid === APP.statistics.LOCAL_JID)
  1198. {
  1199. resourceJid = AudioLevels.LOCAL_LEVEL;
  1200. if(APP.RTC.localAudio.isMuted())
  1201. {
  1202. audioLevel = 0;
  1203. }
  1204. }
  1205. else
  1206. {
  1207. resourceJid = Strophe.getResourceFromJid(jid);
  1208. }
  1209. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1210. UI.getLargeVideoState().userResourceJid);
  1211. });
  1212. APP.desktopsharing.addListener(function () {
  1213. ToolbarToggler.showDesktopSharingButton();
  1214. }, DesktopSharingEventTypes.INIT);
  1215. APP.desktopsharing.addListener(
  1216. Toolbar.changeDesktopSharingButtonState,
  1217. DesktopSharingEventTypes.SWITCHING_DONE);
  1218. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1219. VideoLayout.updateLocalConnectionStats);
  1220. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1221. VideoLayout.updateConnectionStats);
  1222. APP.connectionquality.addListener(CQEvents.STOP,
  1223. VideoLayout.onStatsStop);
  1224. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1225. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  1226. messageHandler.openMessageDialog(
  1227. 'dialog.serviceUnavailable',
  1228. 'dialog.gracefulShutdown'
  1229. );
  1230. });
  1231. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  1232. var title = APP.translation.generateTranslatonHTML(
  1233. "dialog.reservationError");
  1234. var message = APP.translation.generateTranslatonHTML(
  1235. "dialog.reservationErrorMsg", {code: code, msg: msg});
  1236. messageHandler.openDialog(
  1237. title,
  1238. message,
  1239. true, {},
  1240. function (event, value, message, formVals)
  1241. {
  1242. return false;
  1243. }
  1244. );
  1245. });
  1246. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1247. messageHandler.openMessageDialog("dialog.sessTerminated",
  1248. "dialog.kickMessage");
  1249. });
  1250. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1251. //FIXME: use Session Terminated from translation, but
  1252. // 'reason' text comes from XMPP packet and is not translated
  1253. var title = APP.translation.generateTranslatonHTML("dialog.sessTerminated");
  1254. messageHandler.openDialog(
  1255. title, reason, true, {},
  1256. function (event, value, message, formVals)
  1257. {
  1258. return false;
  1259. }
  1260. );
  1261. });
  1262. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1263. messageHandler.showError("dialog.error",
  1264. "dialog.bridgeUnavailable");
  1265. });
  1266. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1267. Avatar.setUserAvatar(from, id);
  1268. });
  1269. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  1270. for(stream in changedStreams)
  1271. {
  1272. // might need to update the direction if participant just went from sendrecv to recvonly
  1273. if (stream.type === 'video' || stream.type === 'screen') {
  1274. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1275. switch (stream.direction) {
  1276. case 'sendrecv':
  1277. el.show();
  1278. break;
  1279. case 'recvonly':
  1280. el.hide();
  1281. // FIXME: Check if we have to change large video
  1282. //VideoLayout.updateLargeVideo(el);
  1283. break;
  1284. }
  1285. }
  1286. }
  1287. });
  1288. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1289. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1290. APP.xmpp.addListener(XMPPEvents.LOCALROLE_CHANGED, onLocalRoleChange);
  1291. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, onMucEntered);
  1292. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1293. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1294. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1295. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1296. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1297. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordReqiured);
  1298. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1299. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1300. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, onAuthenticationRequired);
  1301. }
  1302. /**
  1303. * Mutes/unmutes the local video.
  1304. *
  1305. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1306. * @param options an object which specifies optional arguments such as the
  1307. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1308. * specifies whether the method was initiated in response to a user command (in
  1309. * contrast to an automatic decision taken by the application logic)
  1310. */
  1311. function setVideoMute(mute, options) {
  1312. APP.xmpp.setVideoMute(
  1313. mute,
  1314. function (mute) {
  1315. var video = $('#video');
  1316. var communicativeClass = "icon-camera";
  1317. var muteClass = "icon-camera icon-camera-disabled";
  1318. if (mute) {
  1319. video.removeClass(communicativeClass);
  1320. video.addClass(muteClass);
  1321. } else {
  1322. video.removeClass(muteClass);
  1323. video.addClass(communicativeClass);
  1324. }
  1325. },
  1326. options);
  1327. }
  1328. function bindEvents()
  1329. {
  1330. /**
  1331. * Resizes and repositions videos in full screen mode.
  1332. */
  1333. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1334. function () {
  1335. VideoLayout.resizeLargeVideoContainer();
  1336. VideoLayout.positionLarge();
  1337. }
  1338. );
  1339. $(window).resize(function () {
  1340. VideoLayout.resizeLargeVideoContainer();
  1341. VideoLayout.positionLarge();
  1342. });
  1343. }
  1344. UI.start = function (init) {
  1345. document.title = interfaceConfig.APP_NAME;
  1346. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1347. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1348. {
  1349. $("#videoconference_page").hide();
  1350. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1351. setupWelcomePage();
  1352. return;
  1353. }
  1354. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1355. var leftWatermarkDiv
  1356. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1357. leftWatermarkDiv.css({display: 'block'});
  1358. leftWatermarkDiv.parent().get(0).href
  1359. = interfaceConfig.JITSI_WATERMARK_LINK;
  1360. }
  1361. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1362. var rightWatermarkDiv
  1363. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1364. rightWatermarkDiv.css({display: 'block'});
  1365. rightWatermarkDiv.parent().get(0).href
  1366. = interfaceConfig.BRAND_WATERMARK_LINK;
  1367. rightWatermarkDiv.get(0).style.backgroundImage
  1368. = "url(images/rightwatermark.png)";
  1369. }
  1370. if (interfaceConfig.SHOW_POWERED_BY) {
  1371. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1372. }
  1373. $("#welcome_page").hide();
  1374. VideoLayout.resizeLargeVideoContainer();
  1375. $("#videospace").mousemove(function () {
  1376. return ToolbarToggler.showToolbar();
  1377. });
  1378. // Set the defaults for prompt dialogs.
  1379. jQuery.prompt.setDefaults({persistent: false});
  1380. VideoLayout.init(eventEmitter);
  1381. AudioLevels.init();
  1382. NicknameHandler.init(eventEmitter);
  1383. registerListeners();
  1384. bindEvents();
  1385. setupPrezi();
  1386. setupToolbars();
  1387. setupChat();
  1388. document.title = interfaceConfig.APP_NAME;
  1389. $("#downloadlog").click(function (event) {
  1390. dump(event.target);
  1391. });
  1392. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1393. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1394. {
  1395. $("#videoconference_page").hide();
  1396. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1397. setupWelcomePage();
  1398. return;
  1399. }
  1400. $("#welcome_page").hide();
  1401. // Display notice message at the top of the toolbar
  1402. if (config.noticeMessage) {
  1403. $('#noticeText').text(config.noticeMessage);
  1404. $('#notice').css({display: 'block'});
  1405. }
  1406. document.getElementById('largeVideo').volume = 0;
  1407. if (!$('#settings').is(':visible')) {
  1408. console.log('init');
  1409. init();
  1410. } else {
  1411. loginInfo.onsubmit = function (e) {
  1412. if (e.preventDefault) e.preventDefault();
  1413. $('#settings').hide();
  1414. init();
  1415. };
  1416. }
  1417. toastr.options = {
  1418. "closeButton": true,
  1419. "debug": false,
  1420. "positionClass": "notification-bottom-right",
  1421. "onclick": null,
  1422. "showDuration": "300",
  1423. "hideDuration": "1000",
  1424. "timeOut": "2000",
  1425. "extendedTimeOut": "1000",
  1426. "showEasing": "swing",
  1427. "hideEasing": "linear",
  1428. "showMethod": "fadeIn",
  1429. "hideMethod": "fadeOut",
  1430. "reposition": function() {
  1431. if(PanelToggler.isVisible()) {
  1432. $("#toast-container").addClass("notification-bottom-right-center");
  1433. } else {
  1434. $("#toast-container").removeClass("notification-bottom-right-center");
  1435. }
  1436. },
  1437. "newestOnTop": false
  1438. };
  1439. SettingsMenu.init();
  1440. };
  1441. function chatAddError(errorMessage, originalText)
  1442. {
  1443. return Chat.chatAddError(errorMessage, originalText);
  1444. };
  1445. function chatSetSubject(text)
  1446. {
  1447. return Chat.chatSetSubject(text);
  1448. };
  1449. function updateChatConversation(from, displayName, message) {
  1450. return Chat.updateChatConversation(from, displayName, message);
  1451. };
  1452. function onMucJoined(jid, info) {
  1453. Toolbar.updateRoomUrl(window.location.href);
  1454. var meHTML = APP.translation.generateTranslatonHTML("me");
  1455. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  1456. var settings = Settings.getSettings();
  1457. // Add myself to the contact list.
  1458. ContactList.addContact(jid, settings.email || settings.uid);
  1459. // Once we've joined the muc show the toolbar
  1460. ToolbarToggler.showToolbar();
  1461. var displayName = !config.displayJids
  1462. ? info.displayName : Strophe.getResourceFromJid(jid);
  1463. if (displayName)
  1464. onDisplayNameChanged('localVideoContainer', displayName);
  1465. }
  1466. function initEtherpad(name) {
  1467. Etherpad.init(name);
  1468. };
  1469. function onMucLeft(jid) {
  1470. console.log('left.muc', jid);
  1471. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1472. '>.displayname').html();
  1473. messageHandler.notify(displayName,'notify.somebody',
  1474. 'disconnected',
  1475. 'notify.disconnected');
  1476. // Need to call this with a slight delay, otherwise the element couldn't be
  1477. // found for some reason.
  1478. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1479. window.setTimeout(function () {
  1480. var container = document.getElementById(
  1481. 'participant_' + Strophe.getResourceFromJid(jid));
  1482. if (container) {
  1483. ContactList.removeContact(jid);
  1484. VideoLayout.removeConnectionIndicator(jid);
  1485. // hide here, wait for video to close before removing
  1486. $(container).hide();
  1487. VideoLayout.resizeThumbnails();
  1488. }
  1489. }, 10);
  1490. VideoLayout.participantLeft(jid);
  1491. };
  1492. function onLocalRoleChange(jid, info, pres, isModerator)
  1493. {
  1494. console.info("My role changed, new role: " + info.role);
  1495. onModeratorStatusChanged(isModerator);
  1496. VideoLayout.showModeratorIndicator();
  1497. if (isModerator) {
  1498. Authentication.closeAuthenticationWindow();
  1499. messageHandler.notify(null, "notify.me",
  1500. 'connected', "notify.moderator");
  1501. }
  1502. }
  1503. function onModeratorStatusChanged(isModerator) {
  1504. Toolbar.showSipCallButton(isModerator);
  1505. Toolbar.showRecordingButton(
  1506. isModerator); //&&
  1507. // FIXME:
  1508. // Recording visible if
  1509. // there are at least 2(+ 1 focus) participants
  1510. //Object.keys(connection.emuc.members).length >= 3);
  1511. if (isModerator && config.etherpad_base) {
  1512. Etherpad.init();
  1513. }
  1514. };
  1515. function onPasswordReqiured(callback) {
  1516. // password is required
  1517. Toolbar.lockLockButton();
  1518. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1519. message += APP.translation.translateString(
  1520. "dialog.passwordRequired");
  1521. message += '</h2>' +
  1522. '<input name="lockKey" type="text" data-i18n=' +
  1523. '"[placeholder]dialog.password" placeholder="' +
  1524. APP.translation.translateString("dialog.password") +
  1525. '" autofocus>';
  1526. messageHandler.openTwoButtonDialog(null, null, null, message,
  1527. true,
  1528. "dialog.Ok",
  1529. function (e, v, m, f) {},
  1530. null,
  1531. function (e, v, m, f) {
  1532. if (v) {
  1533. var lockKey = f.lockKey;
  1534. if (lockKey) {
  1535. Toolbar.setSharedKey(lockKey);
  1536. callback(lockKey);
  1537. }
  1538. }
  1539. },
  1540. ':input:first'
  1541. );
  1542. }
  1543. function onMucEntered(jid, id, displayName) {
  1544. messageHandler.notify(displayName,'notify.somebody',
  1545. 'connected',
  1546. 'notify.connected');
  1547. // Add Peer's container
  1548. VideoLayout.ensurePeerContainerExists(jid,id);
  1549. }
  1550. function onMucPresenceStatus( jid, info) {
  1551. VideoLayout.setPresenceStatus(
  1552. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1553. }
  1554. function onMucRoleChanged(role, displayName) {
  1555. VideoLayout.showModeratorIndicator();
  1556. if (role === 'moderator') {
  1557. var messageKey, messageOptions = {};
  1558. if (!displayName) {
  1559. messageKey = "notify.grantedToUnknown";
  1560. }
  1561. else
  1562. {
  1563. messageKey = "notify.grantedTo";
  1564. messageOptions = {to: displayName};
  1565. }
  1566. messageHandler.notify(
  1567. displayName,'notify.somebody',
  1568. 'connected', messageKey,
  1569. messageOptions);
  1570. }
  1571. }
  1572. function onAuthenticationRequired(intervalCallback) {
  1573. Authentication.openAuthenticationDialog(
  1574. roomName, intervalCallback, function () {
  1575. Toolbar.authenticateClicked();
  1576. });
  1577. };
  1578. function onLastNChanged(oldValue, newValue) {
  1579. if (config.muteLocalVideoIfNotInLastN) {
  1580. setVideoMute(!newValue, { 'byUser': false });
  1581. }
  1582. }
  1583. UI.toggleSmileys = function () {
  1584. Chat.toggleSmileys();
  1585. };
  1586. UI.getSettings = function () {
  1587. return Settings.getSettings();
  1588. };
  1589. UI.toggleFilmStrip = function () {
  1590. return BottomToolbar.toggleFilmStrip();
  1591. };
  1592. UI.toggleChat = function () {
  1593. return BottomToolbar.toggleChat();
  1594. };
  1595. UI.toggleContactList = function () {
  1596. return BottomToolbar.toggleContactList();
  1597. };
  1598. UI.inputDisplayNameHandler = function (value) {
  1599. VideoLayout.inputDisplayNameHandler(value);
  1600. };
  1601. UI.getLargeVideoState = function()
  1602. {
  1603. return VideoLayout.getLargeVideoState();
  1604. };
  1605. UI.generateRoomName = function() {
  1606. if(roomName)
  1607. return roomName;
  1608. var roomnode = null;
  1609. var path = window.location.pathname;
  1610. // determinde the room node from the url
  1611. // TODO: just the roomnode or the whole bare jid?
  1612. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1613. // custom function might be responsible for doing the pushstate
  1614. roomnode = config.getroomnode(path);
  1615. } else {
  1616. /* fall back to default strategy
  1617. * this is making assumptions about how the URL->room mapping happens.
  1618. * It currently assumes deployment at root, with a rewrite like the
  1619. * following one (for nginx):
  1620. location ~ ^/([a-zA-Z0-9]+)$ {
  1621. rewrite ^/(.*)$ / break;
  1622. }
  1623. */
  1624. if (path.length > 1) {
  1625. roomnode = path.substr(1).toLowerCase();
  1626. } else {
  1627. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1628. roomnode = word.toLowerCase();
  1629. window.history.pushState('VideoChat',
  1630. 'Room: ' + word, window.location.pathname + word);
  1631. }
  1632. }
  1633. roomName = roomnode + '@' + config.hosts.muc;
  1634. return roomName;
  1635. };
  1636. UI.connectionIndicatorShowMore = function(id)
  1637. {
  1638. return VideoLayout.connectionIndicators[id].showMore();
  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 name="username" type="text" ' +
  1648. 'placeholder="user@domain.net" autofocus>' +
  1649. '<input name="password" ' +
  1650. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  1651. ' placeholder="user password">';
  1652. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  1653. true,
  1654. "dialog.Ok",
  1655. function (e, v, m, f) {
  1656. if (v) {
  1657. if (f.username !== null && f.password != null) {
  1658. callback(f.username, f.password);
  1659. }
  1660. }
  1661. },
  1662. null, null, ':input:first'
  1663. );
  1664. }
  1665. UI.checkForNicknameAndJoin = function () {
  1666. Authentication.closeAuthenticationDialog();
  1667. Authentication.stopInterval();
  1668. var nick = null;
  1669. if (config.useNicks) {
  1670. nick = window.prompt('Your nickname (optional)');
  1671. }
  1672. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1673. };
  1674. function dump(elem, filename) {
  1675. elem = elem.parentNode;
  1676. elem.download = filename || 'meetlog.json';
  1677. elem.href = 'data:application/json;charset=utf-8,\n';
  1678. var data = APP.xmpp.populateData();
  1679. var metadata = {};
  1680. metadata.time = new Date();
  1681. metadata.url = window.location.href;
  1682. metadata.ua = navigator.userAgent;
  1683. var log = APP.xmpp.getLogger();
  1684. if (log) {
  1685. metadata.xmpp = log;
  1686. }
  1687. data.metadata = metadata;
  1688. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1689. return false;
  1690. }
  1691. UI.getRoomName = function () {
  1692. return roomName;
  1693. };
  1694. /**
  1695. * Mutes/unmutes the local video.
  1696. */
  1697. UI.toggleVideo = function () {
  1698. UIUtil.buttonClick("#video", "icon-camera icon-camera-disabled");
  1699. setVideoMute(!APP.RTC.localVideo.isMuted());
  1700. };
  1701. /**
  1702. * Mutes / unmutes audio for the local participant.
  1703. */
  1704. UI.toggleAudio = function() {
  1705. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  1706. };
  1707. /**
  1708. * Sets muted audio state for the local participant.
  1709. */
  1710. UI.setAudioMuted = function (mute) {
  1711. if(!APP.xmpp.setAudioMute(mute, function () {
  1712. VideoLayout.showLocalAudioIndicator(mute);
  1713. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1714. }))
  1715. {
  1716. // We still click the button.
  1717. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1718. return;
  1719. }
  1720. }
  1721. UI.addListener = function (type, listener) {
  1722. eventEmitter.on(type, listener);
  1723. }
  1724. UI.clickOnVideo = function (videoNumber) {
  1725. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  1726. if (remoteVideos.length > videoNumber) {
  1727. remoteVideos[videoNumber].click();
  1728. }
  1729. }
  1730. //Used by torture
  1731. UI.showToolbar = function () {
  1732. return ToolbarToggler.showToolbar();
  1733. }
  1734. //Used by torture
  1735. UI.dockToolbar = function (isDock) {
  1736. return ToolbarToggler.dockToolbar(isDock);
  1737. }
  1738. module.exports = UI;
  1739. },{"../../service/RTC/RTCEvents":89,"../../service/RTC/StreamEventTypes":91,"../../service/connectionquality/CQEvents":94,"../../service/desktopsharing/DesktopSharingEventTypes":95,"../../service/xmpp/XMPPEvents":97,"./../settings/Settings":38,"./audio_levels/AudioLevels.js":9,"./authentication/Authentication":11,"./avatar/Avatar":13,"./etherpad/Etherpad.js":14,"./prezi/Prezi.js":15,"./side_pannels/SidePanelToggler":17,"./side_pannels/chat/Chat.js":18,"./side_pannels/contactlist/ContactList":22,"./side_pannels/settings/SettingsMenu":23,"./toolbars/BottomToolbar":24,"./toolbars/Toolbar":25,"./toolbars/ToolbarToggler":26,"./util/MessageHandler":28,"./util/NicknameHandler":29,"./util/UIUtil":30,"./videolayout/VideoLayout.js":32,"./welcome_page/RoomnameGenerator":33,"./welcome_page/WelcomePage":34,"events":98}],9:[function(require,module,exports){
  1740. var CanvasUtil = require("./CanvasUtils");
  1741. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  1742. function initActiveSpeakerAudioLevels() {
  1743. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  1744. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  1745. // Draw a circle.
  1746. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  1747. // Add a shadow around the circle
  1748. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  1749. ASDrawContext.shadowOffsetX = 0;
  1750. ASDrawContext.shadowOffsetY = 0;
  1751. }
  1752. /**
  1753. * The audio Levels plugin.
  1754. */
  1755. var AudioLevels = (function(my) {
  1756. var audioLevelCanvasCache = {};
  1757. my.LOCAL_LEVEL = 'local';
  1758. my.init = function () {
  1759. initActiveSpeakerAudioLevels();
  1760. }
  1761. /**
  1762. * Updates the audio level canvas for the given peerJid. If the canvas
  1763. * didn't exist we create it.
  1764. */
  1765. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  1766. var resourceJid = null;
  1767. var videoSpanId = null;
  1768. if (!peerJid)
  1769. videoSpanId = 'localVideoContainer';
  1770. else {
  1771. resourceJid = Strophe.getResourceFromJid(peerJid);
  1772. videoSpanId = 'participant_' + resourceJid;
  1773. }
  1774. var videoSpan = document.getElementById(videoSpanId);
  1775. if (!videoSpan) {
  1776. if (resourceJid)
  1777. console.error("No video element for jid", resourceJid);
  1778. else
  1779. console.error("No video element for local video.");
  1780. return;
  1781. }
  1782. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  1783. var videoSpaceWidth = $('#remoteVideos').width();
  1784. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  1785. var thumbnailWidth = thumbnailSize[0];
  1786. var thumbnailHeight = thumbnailSize[1];
  1787. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  1788. audioLevelCanvas = document.createElement('canvas');
  1789. audioLevelCanvas.className = "audiolevel";
  1790. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1791. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1792. resizeAudioLevelCanvas( audioLevelCanvas,
  1793. thumbnailWidth,
  1794. thumbnailHeight);
  1795. videoSpan.appendChild(audioLevelCanvas);
  1796. } else {
  1797. audioLevelCanvas = audioLevelCanvas.get(0);
  1798. resizeAudioLevelCanvas( audioLevelCanvas,
  1799. thumbnailWidth,
  1800. thumbnailHeight);
  1801. }
  1802. };
  1803. /**
  1804. * Updates the audio level UI for the given resourceJid.
  1805. *
  1806. * @param resourceJid the resource jid indicating the video element for
  1807. * which we draw the audio level
  1808. * @param audioLevel the newAudio level to render
  1809. */
  1810. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  1811. drawAudioLevelCanvas(resourceJid, audioLevel);
  1812. var videoSpanId = getVideoSpanId(resourceJid);
  1813. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  1814. if (!audioLevelCanvas)
  1815. return;
  1816. var drawContext = audioLevelCanvas.getContext('2d');
  1817. var canvasCache = audioLevelCanvasCache[resourceJid];
  1818. drawContext.clearRect (0, 0,
  1819. audioLevelCanvas.width, audioLevelCanvas.height);
  1820. drawContext.drawImage(canvasCache, 0, 0);
  1821. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  1822. if(!APP.xmpp.myJid()) {
  1823. return;
  1824. }
  1825. resourceJid = APP.xmpp.myResource();
  1826. }
  1827. if(resourceJid === largeVideoResourceJid) {
  1828. window.requestAnimationFrame(function () {
  1829. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  1830. });
  1831. }
  1832. };
  1833. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  1834. if($("#activeSpeaker").css("visibility") == "hidden")
  1835. return;
  1836. ASDrawContext.clearRect(0, 0, 300, 300);
  1837. if(audioLevel == 0)
  1838. return;
  1839. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  1840. // Fill the shape.
  1841. ASDrawContext.fill();
  1842. };
  1843. /**
  1844. * Resizes the given audio level canvas to match the given thumbnail size.
  1845. */
  1846. function resizeAudioLevelCanvas(audioLevelCanvas,
  1847. thumbnailWidth,
  1848. thumbnailHeight) {
  1849. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  1850. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  1851. }
  1852. /**
  1853. * Draws the audio level canvas into the cached canvas object.
  1854. *
  1855. * @param resourceJid the resource jid indicating the video element for
  1856. * which we draw the audio level
  1857. * @param audioLevel the newAudio level to render
  1858. */
  1859. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  1860. if (!audioLevelCanvasCache[resourceJid]) {
  1861. var videoSpanId = getVideoSpanId(resourceJid);
  1862. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  1863. /*
  1864. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  1865. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  1866. * error. Since audio levels are frequently updated, the errors have
  1867. * been observed to pile into the console, strain the CPU.
  1868. */
  1869. if (audioLevelCanvasOrig)
  1870. {
  1871. audioLevelCanvasCache[resourceJid]
  1872. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  1873. }
  1874. }
  1875. var canvas = audioLevelCanvasCache[resourceJid];
  1876. if (!canvas)
  1877. return;
  1878. var drawContext = canvas.getContext('2d');
  1879. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  1880. var shadowLevel = getShadowLevel(audioLevel);
  1881. if (shadowLevel > 0)
  1882. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  1883. CanvasUtil.drawRoundRectGlow( drawContext,
  1884. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  1885. canvas.width - interfaceConfig.CANVAS_EXTRA,
  1886. canvas.height - interfaceConfig.CANVAS_EXTRA,
  1887. interfaceConfig.CANVAS_RADIUS,
  1888. interfaceConfig.SHADOW_COLOR,
  1889. shadowLevel);
  1890. }
  1891. /**
  1892. * Returns the shadow/glow level for the given audio level.
  1893. *
  1894. * @param audioLevel the audio level from which we determine the shadow
  1895. * level
  1896. */
  1897. function getShadowLevel (audioLevel) {
  1898. var shadowLevel = 0;
  1899. if (audioLevel <= 0.3) {
  1900. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  1901. }
  1902. else if (audioLevel <= 0.6) {
  1903. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  1904. }
  1905. else {
  1906. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  1907. }
  1908. return shadowLevel;
  1909. }
  1910. /**
  1911. * Returns the video span id corresponding to the given resourceJid or local
  1912. * user.
  1913. */
  1914. function getVideoSpanId(resourceJid) {
  1915. var videoSpanId = null;
  1916. if (resourceJid === AudioLevels.LOCAL_LEVEL
  1917. || (APP.xmpp.myResource() && resourceJid
  1918. === APP.xmpp.myResource()))
  1919. videoSpanId = 'localVideoContainer';
  1920. else
  1921. videoSpanId = 'participant_' + resourceJid;
  1922. return videoSpanId;
  1923. }
  1924. /**
  1925. * Indicates that the remote video has been resized.
  1926. */
  1927. $(document).bind('remotevideo.resized', function (event, width, height) {
  1928. var resized = false;
  1929. $('#remoteVideos>span>canvas').each(function() {
  1930. var canvas = $(this).get(0);
  1931. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  1932. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  1933. resized = true;
  1934. }
  1935. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  1936. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  1937. resized = true;
  1938. }
  1939. });
  1940. if (resized)
  1941. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  1942. audioLevelCanvasCache[resourceJid].width
  1943. = width + interfaceConfig.CANVAS_EXTRA;
  1944. audioLevelCanvasCache[resourceJid].height
  1945. = height + interfaceConfig.CANVAS_EXTRA;
  1946. });
  1947. });
  1948. return my;
  1949. })(AudioLevels || {});
  1950. module.exports = AudioLevels;
  1951. },{"./CanvasUtils":10}],10:[function(require,module,exports){
  1952. /**
  1953. * Utility class for drawing canvas shapes.
  1954. */
  1955. var CanvasUtil = (function(my) {
  1956. /**
  1957. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  1958. * of the glow.
  1959. *
  1960. * @param drawContext the context of the canvas to draw to
  1961. * @param x the x coordinate of the round rectangle
  1962. * @param y the y coordinate of the round rectangle
  1963. * @param w the width of the round rectangle
  1964. * @param h the height of the round rectangle
  1965. * @param glowColor the color of the glow
  1966. * @param glowWidth the width of the glow
  1967. */
  1968. my.drawRoundRectGlow
  1969. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  1970. // Save the previous state of the context.
  1971. drawContext.save();
  1972. if (w < 2 * r) r = w / 2;
  1973. if (h < 2 * r) r = h / 2;
  1974. // Draw a round rectangle.
  1975. drawContext.beginPath();
  1976. drawContext.moveTo(x+r, y);
  1977. drawContext.arcTo(x+w, y, x+w, y+h, r);
  1978. drawContext.arcTo(x+w, y+h, x, y+h, r);
  1979. drawContext.arcTo(x, y+h, x, y, r);
  1980. drawContext.arcTo(x, y, x+w, y, r);
  1981. drawContext.closePath();
  1982. // Add a shadow around the rectangle
  1983. drawContext.shadowColor = glowColor;
  1984. drawContext.shadowBlur = glowWidth;
  1985. drawContext.shadowOffsetX = 0;
  1986. drawContext.shadowOffsetY = 0;
  1987. // Fill the shape.
  1988. drawContext.fill();
  1989. drawContext.save();
  1990. drawContext.restore();
  1991. // 1) Uncomment this line to use Composite Operation, which is doing the
  1992. // same as the clip function below and is also antialiasing the round
  1993. // border, but is said to be less fast performance wise.
  1994. // drawContext.globalCompositeOperation='destination-out';
  1995. drawContext.beginPath();
  1996. drawContext.moveTo(x+r, y);
  1997. drawContext.arcTo(x+w, y, x+w, y+h, r);
  1998. drawContext.arcTo(x+w, y+h, x, y+h, r);
  1999. drawContext.arcTo(x, y+h, x, y, r);
  2000. drawContext.arcTo(x, y, x+w, y, r);
  2001. drawContext.closePath();
  2002. // 2) Uncomment this line to use Composite Operation, which is doing the
  2003. // same as the clip function below and is also antialiasing the round
  2004. // border, but is said to be less fast performance wise.
  2005. // drawContext.fill();
  2006. // Comment these two lines if choosing to do the same with composite
  2007. // operation above 1 and 2.
  2008. drawContext.clip();
  2009. drawContext.clearRect(0, 0, 277, 200);
  2010. // Restore the previous context state.
  2011. drawContext.restore();
  2012. };
  2013. /**
  2014. * Clones the given canvas.
  2015. *
  2016. * @return the new cloned canvas.
  2017. */
  2018. my.cloneCanvas = function (oldCanvas) {
  2019. /*
  2020. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2021. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2022. * levels are frequently updated, the errors have been observed to pile
  2023. * into the console, strain the CPU.
  2024. */
  2025. if (!oldCanvas)
  2026. return oldCanvas;
  2027. //create a new canvas
  2028. var newCanvas = document.createElement('canvas');
  2029. var context = newCanvas.getContext('2d');
  2030. //set dimensions
  2031. newCanvas.width = oldCanvas.width;
  2032. newCanvas.height = oldCanvas.height;
  2033. //apply the old canvas to the new one
  2034. context.drawImage(oldCanvas, 0, 0);
  2035. //return the new canvas
  2036. return newCanvas;
  2037. };
  2038. return my;
  2039. })(CanvasUtil || {});
  2040. module.exports = CanvasUtil;
  2041. },{}],11:[function(require,module,exports){
  2042. /* global $, APP*/
  2043. var LoginDialog = require('./LoginDialog');
  2044. var Moderator = require('../../xmpp/moderator');
  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 buttonTxt
  2065. = APP.translation.generateTranslatonHTML("dialog.Authenticate");
  2066. var buttons = [];
  2067. buttons.push({title: buttonTxt, 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. xmppAuthenticate: function () {
  2090. var loginDialog = LoginDialog.show(
  2091. function (connection, state) {
  2092. if (!state) {
  2093. // User cancelled
  2094. loginDialog.close();
  2095. return;
  2096. } else if (state == APP.xmpp.Status.CONNECTED) {
  2097. loginDialog.close();
  2098. Authentication.stopInterval();
  2099. Authentication.closeAuthenticationDialog();
  2100. // Close the connection as anonymous one will be used
  2101. // to create the conference. Session-id will authorize
  2102. // the request.
  2103. connection.disconnect();
  2104. var roomName = APP.UI.generateRoomName();
  2105. Moderator.allocateConferenceFocus(roomName, function () {
  2106. // If it's not "on the fly" authentication now join
  2107. // the conference room
  2108. if (!APP.xmpp.getMUCJoined()) {
  2109. APP.UI.checkForNicknameAndJoin();
  2110. }
  2111. });
  2112. }
  2113. }, true);
  2114. },
  2115. focusAuthenticationWindow: function () {
  2116. // If auth window exists just bring it to the front
  2117. if (authenticationWindow) {
  2118. authenticationWindow.focus();
  2119. return;
  2120. }
  2121. },
  2122. closeAuthenticationDialog: function () {
  2123. // Close authentication dialog if opened
  2124. if (authDialog) {
  2125. authDialog.close();
  2126. authDialog = null;
  2127. }
  2128. },
  2129. createAuthenticationWindow: function (callback, url) {
  2130. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2131. url, 910, 660,
  2132. // On closed
  2133. function () {
  2134. // Close authentication dialog if opened
  2135. Authentication.closeAuthenticationDialog();
  2136. callback();
  2137. authenticationWindow = null;
  2138. });
  2139. return authenticationWindow;
  2140. },
  2141. stopInterval: function () {
  2142. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2143. if (authRetryId) {
  2144. window.clearTimeout(authRetryId);
  2145. authRetryId = null;
  2146. }
  2147. }
  2148. };
  2149. module.exports = Authentication;
  2150. },{"../../xmpp/moderator":53,"./LoginDialog":12}],12:[function(require,module,exports){
  2151. /* global $, APP, config*/
  2152. var XMPP = require('../../xmpp/xmpp');
  2153. var Moderator = require('../../xmpp/moderator');
  2154. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  2155. // anonymous domain is not enabled
  2156. /**
  2157. * Creates new <tt>Dialog</tt> instance.
  2158. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  2159. * when we either fail to connect or succeed(check Strophe.Status).
  2160. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  2161. * in order to create session-id after the connection is established.
  2162. * @constructor
  2163. */
  2164. function Dialog(callback, obtainSession) {
  2165. var self = this;
  2166. var stop = false;
  2167. var connection = APP.xmpp.createConnection();
  2168. var message = '<h2 data-i18n="dialog.passwordRequired">';
  2169. message += APP.translation.translateString("dialog.passwordRequired");
  2170. message += '</h2>' +
  2171. '<input name="username" type="text" ' +
  2172. 'placeholder="user@domain.net" autofocus>' +
  2173. '<input name="password" ' +
  2174. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  2175. ' placeholder="user password">';
  2176. var okButton = APP.translation.generateTranslatonHTML("dialog.Ok");
  2177. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel");
  2178. var states = {
  2179. login: {
  2180. html: message,
  2181. buttons: [
  2182. { title: okButton, value: true},
  2183. { title: cancelButton, value: false}
  2184. ],
  2185. focus: ':input:first',
  2186. submit: function (e, v, m, f) {
  2187. e.preventDefault();
  2188. if (v) {
  2189. var jid = f.username;
  2190. var password = f.password;
  2191. if (jid && password) {
  2192. stop = false;
  2193. connection.reset();
  2194. connDialog.goToState('connecting');
  2195. connection.connect(jid, password, stateHandler);
  2196. }
  2197. } else {
  2198. // User cancelled
  2199. stop = true;
  2200. callback();
  2201. }
  2202. }
  2203. },
  2204. connecting: {
  2205. title: APP.translation.translateString('dialog.connecting'),
  2206. html: '<div id="connectionStatus"></div>',
  2207. buttons: [],
  2208. defaultButton: 0
  2209. },
  2210. finished: {
  2211. title: APP.translation.translateString('dialog.error'),
  2212. html: '<div id="errorMessage"></div>',
  2213. buttons: [
  2214. {
  2215. title: APP.translation.translateString('dialog.retry'),
  2216. value: 'retry'
  2217. },
  2218. {
  2219. title: APP.translation.translateString('dialog.Cancel'),
  2220. value: 'cancel'
  2221. },
  2222. ],
  2223. defaultButton: 0,
  2224. submit: function (e, v, m, f) {
  2225. e.preventDefault();
  2226. if (v === 'retry')
  2227. connDialog.goToState('login');
  2228. else
  2229. callback();
  2230. }
  2231. }
  2232. };
  2233. var connDialog
  2234. = APP.UI.messageHandler.openDialogWithStates(states,
  2235. { persistent: true, closeText: '' }, null);
  2236. var stateHandler = function (status, message) {
  2237. if (stop) {
  2238. return;
  2239. }
  2240. var translateKey = "connection." + XMPP.getStatusString(status);
  2241. var statusStr = APP.translation.translateString(translateKey);
  2242. // Display current state
  2243. var connectionStatus =
  2244. connDialog.getState('connecting').find('#connectionStatus');
  2245. connectionStatus.text(statusStr);
  2246. switch (status) {
  2247. case XMPP.Status.CONNECTED:
  2248. stop = true;
  2249. if (!obtainSession) {
  2250. callback(connection, status);
  2251. return;
  2252. }
  2253. // Obtaining session-id status
  2254. connectionStatus.text(
  2255. APP.translation.translateString(
  2256. 'connection.FETCH_SESSION_ID'));
  2257. // Authenticate with Jicofo and obtain session-id
  2258. var roomName = APP.UI.generateRoomName();
  2259. // Jicofo will return new session-id when connected
  2260. // from authenticated domain
  2261. connection.sendIQ(
  2262. Moderator.createConferenceIq(roomName),
  2263. function (result) {
  2264. connectionStatus.text(
  2265. APP.translation.translateString(
  2266. 'connection.GOT_SESSION_ID'));
  2267. stop = true;
  2268. // Parse session-id
  2269. Moderator.parseSessionId(result);
  2270. callback(connection, status);
  2271. },
  2272. function (error) {
  2273. console.error("Auth on the fly failed", error);
  2274. stop = true;
  2275. var errorMsg =
  2276. APP.translation.translateString(
  2277. 'connection.GET_SESSION_ID_ERROR') +
  2278. $(error).find('>error').attr('code');
  2279. self.displayError(errorMsg);
  2280. connection.disconnect();
  2281. });
  2282. break;
  2283. case XMPP.Status.AUTHFAIL:
  2284. case XMPP.Status.CONNFAIL:
  2285. case XMPP.Status.DISCONNECTED:
  2286. stop = true;
  2287. callback(connection, status);
  2288. var errorMessage = statusStr;
  2289. if (message)
  2290. {
  2291. errorMessage += ': ' + message;
  2292. }
  2293. self.displayError(errorMessage);
  2294. break;
  2295. default:
  2296. break;
  2297. }
  2298. };
  2299. /**
  2300. * Displays error message in 'finished' state which allows either to cancel
  2301. * or retry.
  2302. * @param message the final message to be displayed.
  2303. */
  2304. this.displayError = function (message) {
  2305. var finishedState = connDialog.getState('finished');
  2306. var errorMessageElem = finishedState.find('#errorMessage');
  2307. errorMessageElem.text(message);
  2308. connDialog.goToState('finished');
  2309. };
  2310. /**
  2311. * Closes LoginDialog.
  2312. */
  2313. this.close = function () {
  2314. stop = true;
  2315. connDialog.close();
  2316. };
  2317. }
  2318. var LoginDialog = {
  2319. /**
  2320. * Displays login prompt used to establish new XMPP connection. Given
  2321. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  2322. * called when we connect successfully(status === CONNECTED) or when we fail
  2323. * to do so. On connection failure program can call Dialog.close() method in
  2324. * order to cancel or do nothing to let the user retry.
  2325. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  2326. * called when we either fail to connect or succeed(check
  2327. * Strophe.Status).
  2328. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  2329. * Jicofo in order to create session-id after the connection is
  2330. * established.
  2331. * @returns {Dialog}
  2332. */
  2333. show: function (callback, obtainSession) {
  2334. return new Dialog(callback, obtainSession);
  2335. }
  2336. };
  2337. module.exports = LoginDialog;
  2338. },{"../../xmpp/moderator":53,"../../xmpp/xmpp":61}],13:[function(require,module,exports){
  2339. var Settings = require("../../settings/Settings");
  2340. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2341. var users = {};
  2342. var activeSpeakerJid;
  2343. function setVisibility(selector, show) {
  2344. if (selector && selector.length > 0) {
  2345. selector.css("visibility", show ? "visible" : "hidden");
  2346. }
  2347. }
  2348. function isUserMuted(jid) {
  2349. // XXX(gp) we may want to rename this method to something like
  2350. // isUserStreaming, for example.
  2351. if (jid && jid != APP.xmpp.myJid()) {
  2352. var resource = Strophe.getResourceFromJid(jid);
  2353. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2354. return true;
  2355. }
  2356. }
  2357. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2358. return null;
  2359. }
  2360. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2361. }
  2362. function getGravatarUrl(id, size) {
  2363. if(id === APP.xmpp.myJid() || !id) {
  2364. id = Settings.getSettings().uid;
  2365. }
  2366. return 'https://www.gravatar.com/avatar/' +
  2367. MD5.hexdigest(id.trim().toLowerCase()) +
  2368. "?d=wavatar&size=" + (size || "30");
  2369. }
  2370. var Avatar = {
  2371. /**
  2372. * Sets the user's avatar in the settings menu(if local user), contact list
  2373. * and thumbnail
  2374. * @param jid jid of the user
  2375. * @param id email or userID to be used as a hash
  2376. */
  2377. setUserAvatar: function (jid, id) {
  2378. if (id) {
  2379. if (users[jid] === id) {
  2380. return;
  2381. }
  2382. users[jid] = id;
  2383. }
  2384. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2385. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2386. var resourceJid = Strophe.getResourceFromJid(jid);
  2387. var thumbnail = $('#participant_' + resourceJid);
  2388. var avatar = $('#avatar_' + resourceJid);
  2389. // set the avatar in the settings menu if it is local user and get the
  2390. // local video container
  2391. if (jid === APP.xmpp.myJid()) {
  2392. $('#avatar').get(0).src = thumbUrl;
  2393. thumbnail = $('#localVideoContainer');
  2394. }
  2395. // set the avatar in the contact list
  2396. var contact = $('#' + resourceJid + '>img');
  2397. if (contact && contact.length > 0) {
  2398. contact.get(0).src = contactListUrl;
  2399. }
  2400. // set the avatar in the thumbnail
  2401. if (avatar && avatar.length > 0) {
  2402. avatar[0].src = thumbUrl;
  2403. } else {
  2404. if (thumbnail && thumbnail.length > 0) {
  2405. avatar = document.createElement('img');
  2406. avatar.id = 'avatar_' + resourceJid;
  2407. avatar.className = 'userAvatar';
  2408. avatar.src = thumbUrl;
  2409. thumbnail.append(avatar);
  2410. }
  2411. }
  2412. //if the user is the current active speaker - update the active speaker
  2413. // avatar
  2414. if (jid === activeSpeakerJid) {
  2415. this.updateActiveSpeakerAvatarSrc(jid);
  2416. }
  2417. },
  2418. /**
  2419. * Hides or shows the user's avatar
  2420. * @param jid jid of the user
  2421. * @param show whether we should show the avatar or not
  2422. * video because there is no dominant speaker and no focused speaker
  2423. */
  2424. showUserAvatar: function (jid, show) {
  2425. if (users[jid]) {
  2426. var resourceJid = Strophe.getResourceFromJid(jid);
  2427. var video = $('#participant_' + resourceJid + '>video');
  2428. var avatar = $('#avatar_' + resourceJid);
  2429. if (jid === APP.xmpp.myJid()) {
  2430. video = $('#localVideoWrapper>video');
  2431. }
  2432. if (show === undefined || show === null) {
  2433. show = isUserMuted(jid);
  2434. }
  2435. //if the user is the currently focused, the dominant speaker or if
  2436. //there is no focused and no dominant speaker and the large video is
  2437. //currently shown
  2438. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2439. setVisibility($("#largeVideo"), !show);
  2440. setVisibility($('#activeSpeaker'), show);
  2441. setVisibility(avatar, false);
  2442. setVisibility(video, false);
  2443. } else {
  2444. if (video && video.length > 0) {
  2445. setVisibility(video, !show);
  2446. setVisibility(avatar, show);
  2447. }
  2448. }
  2449. }
  2450. },
  2451. /**
  2452. * Updates the src of the active speaker avatar
  2453. * @param jid of the current active speaker
  2454. */
  2455. updateActiveSpeakerAvatarSrc: function (jid) {
  2456. if (!jid) {
  2457. jid = APP.xmpp.findJidFromResource(
  2458. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2459. }
  2460. var avatar = $("#activeSpeakerAvatar")[0];
  2461. var url = getGravatarUrl(users[jid],
  2462. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2463. if (jid === activeSpeakerJid && avatar.src === url) {
  2464. return;
  2465. }
  2466. activeSpeakerJid = jid;
  2467. var isMuted = isUserMuted(jid);
  2468. if (jid && isMuted !== null) {
  2469. avatar.src = url;
  2470. setVisibility($("#largeVideo"), !isMuted);
  2471. Avatar.showUserAvatar(jid, isMuted);
  2472. }
  2473. }
  2474. };
  2475. module.exports = Avatar;
  2476. },{"../../../service/RTC/MediaStreamTypes":87,"../../settings/Settings":38,"../videolayout/VideoLayout":32}],14:[function(require,module,exports){
  2477. /* global $, config,
  2478. setLargeVideoVisible, Util */
  2479. var VideoLayout = require("../videolayout/VideoLayout");
  2480. var Prezi = require("../prezi/Prezi");
  2481. var UIUtil = require("../util/UIUtil");
  2482. var etherpadName = null;
  2483. var etherpadIFrame = null;
  2484. var domain = null;
  2485. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2486. /**
  2487. * Resizes the etherpad.
  2488. */
  2489. function resize() {
  2490. if ($('#etherpad>iframe').length) {
  2491. var remoteVideos = $('#remoteVideos');
  2492. var availableHeight
  2493. = window.innerHeight - remoteVideos.outerHeight();
  2494. var availableWidth = UIUtil.getAvailableVideoWidth();
  2495. $('#etherpad>iframe').width(availableWidth);
  2496. $('#etherpad>iframe').height(availableHeight);
  2497. }
  2498. }
  2499. /**
  2500. * Shares the Etherpad name with other participants.
  2501. */
  2502. function shareEtherpad() {
  2503. APP.xmpp.addToPresence("etherpad", etherpadName);
  2504. }
  2505. /**
  2506. * Creates the Etherpad button and adds it to the toolbar.
  2507. */
  2508. function enableEtherpadButton() {
  2509. if (!$('#etherpadButton').is(":visible"))
  2510. $('#etherpadButton').css({display: 'inline-block'});
  2511. }
  2512. /**
  2513. * Creates the IFrame for the etherpad.
  2514. */
  2515. function createIFrame() {
  2516. etherpadIFrame = document.createElement('iframe');
  2517. etherpadIFrame.src = domain + etherpadName + options;
  2518. etherpadIFrame.frameBorder = 0;
  2519. etherpadIFrame.scrolling = "no";
  2520. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2521. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2522. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2523. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2524. etherpadIFrame.onload = function() {
  2525. document.domain = document.domain;
  2526. bubbleIframeMouseMove(etherpadIFrame);
  2527. setTimeout(function() {
  2528. // the iframes inside of the etherpad are
  2529. // not yet loaded when the etherpad iframe is loaded
  2530. var outer = etherpadIFrame.
  2531. contentDocument.getElementsByName("ace_outer")[0];
  2532. bubbleIframeMouseMove(outer);
  2533. var inner = outer.
  2534. contentDocument.getElementsByName("ace_inner")[0];
  2535. bubbleIframeMouseMove(inner);
  2536. }, 2000);
  2537. };
  2538. }
  2539. function bubbleIframeMouseMove(iframe){
  2540. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2541. iframe.contentWindow.onmousemove = function(e){
  2542. if(existingOnMouseMove) existingOnMouseMove(e);
  2543. var evt = document.createEvent("MouseEvents");
  2544. var boundingClientRect = iframe.getBoundingClientRect();
  2545. evt.initMouseEvent(
  2546. "mousemove",
  2547. true, // bubbles
  2548. false, // not cancelable
  2549. window,
  2550. e.detail,
  2551. e.screenX,
  2552. e.screenY,
  2553. e.clientX + boundingClientRect.left,
  2554. e.clientY + boundingClientRect.top,
  2555. e.ctrlKey,
  2556. e.altKey,
  2557. e.shiftKey,
  2558. e.metaKey,
  2559. e.button,
  2560. null // no related element
  2561. );
  2562. iframe.dispatchEvent(evt);
  2563. };
  2564. }
  2565. /**
  2566. * On video selected event.
  2567. */
  2568. $(document).bind('video.selected', function (event, isPresentation) {
  2569. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2570. Etherpad.toggleEtherpad(isPresentation);
  2571. });
  2572. var Etherpad = {
  2573. /**
  2574. * Initializes the etherpad.
  2575. */
  2576. init: function (name) {
  2577. if (config.etherpad_base && !etherpadName) {
  2578. domain = config.etherpad_base;
  2579. if (!name) {
  2580. // In case we're the focus we generate the name.
  2581. etherpadName = Math.random().toString(36).substring(7) +
  2582. '_' + (new Date().getTime()).toString();
  2583. shareEtherpad();
  2584. }
  2585. else
  2586. etherpadName = name;
  2587. enableEtherpadButton();
  2588. /**
  2589. * Resizes the etherpad, when the window is resized.
  2590. */
  2591. $(window).resize(function () {
  2592. resize();
  2593. });
  2594. }
  2595. },
  2596. /**
  2597. * Opens/hides the Etherpad.
  2598. */
  2599. toggleEtherpad: function (isPresentation) {
  2600. if (!etherpadIFrame)
  2601. createIFrame();
  2602. var largeVideo = null;
  2603. if (Prezi.isPresentationVisible())
  2604. largeVideo = $('#presentation>iframe');
  2605. else
  2606. largeVideo = $('#largeVideo');
  2607. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2608. $('#activeSpeaker').css('visibility', 'hidden');
  2609. largeVideo.fadeOut(300, function () {
  2610. if (Prezi.isPresentationVisible()) {
  2611. largeVideo.css({opacity: '0'});
  2612. } else {
  2613. VideoLayout.setLargeVideoVisible(false);
  2614. }
  2615. });
  2616. $('#etherpad>iframe').fadeIn(300, function () {
  2617. document.body.style.background = '#eeeeee';
  2618. $('#etherpad>iframe').css({visibility: 'visible'});
  2619. $('#etherpad').css({zIndex: 2});
  2620. });
  2621. }
  2622. else if ($('#etherpad>iframe')) {
  2623. $('#etherpad>iframe').fadeOut(300, function () {
  2624. $('#etherpad>iframe').css({visibility: 'hidden'});
  2625. $('#etherpad').css({zIndex: 0});
  2626. document.body.style.background = 'black';
  2627. });
  2628. if (!isPresentation) {
  2629. $('#largeVideo').fadeIn(300, function () {
  2630. VideoLayout.setLargeVideoVisible(true);
  2631. });
  2632. }
  2633. }
  2634. resize();
  2635. },
  2636. isVisible: function() {
  2637. var etherpadIframe = $('#etherpad>iframe');
  2638. return etherpadIframe && etherpadIframe.is(':visible');
  2639. }
  2640. };
  2641. module.exports = Etherpad;
  2642. },{"../prezi/Prezi":15,"../util/UIUtil":30,"../videolayout/VideoLayout":32}],15:[function(require,module,exports){
  2643. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2644. var UIUtil = require("../util/UIUtil");
  2645. var VideoLayout = require("../videolayout/VideoLayout");
  2646. var messageHandler = require("../util/MessageHandler");
  2647. var PreziPlayer = require("./PreziPlayer");
  2648. var preziPlayer = null;
  2649. var Prezi = {
  2650. /**
  2651. * Reloads the current presentation.
  2652. */
  2653. reloadPresentation: function() {
  2654. var iframe = document.getElementById(preziPlayer.options.preziId);
  2655. iframe.src = iframe.src;
  2656. },
  2657. /**
  2658. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2659. * otherwise.
  2660. */
  2661. isPresentationVisible: function () {
  2662. return ($('#presentation>iframe') != null
  2663. && $('#presentation>iframe').css('opacity') == 1);
  2664. },
  2665. /**
  2666. * Opens the Prezi dialog, from which the user could choose a presentation
  2667. * to load.
  2668. */
  2669. openPreziDialog: function() {
  2670. var myprezi = APP.xmpp.getPrezi();
  2671. if (myprezi) {
  2672. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  2673. null,
  2674. "dialog.removePreziMsg",
  2675. null,
  2676. false,
  2677. "dialog.Remove",
  2678. function(e,v,m,f) {
  2679. if(v) {
  2680. APP.xmpp.removePreziFromPresence();
  2681. }
  2682. }
  2683. );
  2684. }
  2685. else if (preziPlayer != null) {
  2686. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  2687. null, "dialog.sharePreziMsg",
  2688. null,
  2689. false,
  2690. "dialog.Ok",
  2691. function(e,v,m,f) {
  2692. $.prompt.close();
  2693. }
  2694. );
  2695. }
  2696. else {
  2697. var html = APP.translation.generateTranslatonHTML(
  2698. "dialog.sharePreziTitle");
  2699. var cancelButton = APP.translation.generateTranslatonHTML(
  2700. "dialog.Cancel");
  2701. var shareButton = APP.translation.generateTranslatonHTML(
  2702. "dialog.Share");
  2703. var backButton = APP.translation.generateTranslatonHTML(
  2704. "dialog.Back");
  2705. var buttons = [];
  2706. var buttons1 = [];
  2707. // Cancel button to both states
  2708. buttons.push({title: cancelButton, value: false});
  2709. buttons1.push({title: cancelButton, value: false});
  2710. // Share button
  2711. buttons.push({title: shareButton, value: true});
  2712. // Back button
  2713. buttons1.push({title: backButton, value: true});
  2714. var linkError = APP.translation.generateTranslatonHTML(
  2715. "dialog.preziLinkError");
  2716. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  2717. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  2718. var openPreziState = {
  2719. state0: {
  2720. html: '<h2>' + html + '</h2>' +
  2721. '<input name="preziUrl" type="text" ' +
  2722. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  2723. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  2724. '\' placeholder="' + defaultUrl + '" autofocus>',
  2725. persistent: false,
  2726. buttons: buttons,
  2727. focus: ':input:first',
  2728. defaultButton: 0,
  2729. submit: function (e, v, m, f) {
  2730. e.preventDefault();
  2731. if(v)
  2732. {
  2733. var preziUrl = f.preziUrl;
  2734. if (preziUrl)
  2735. {
  2736. var urlValue
  2737. = encodeURI(UIUtil.escapeHtml(preziUrl));
  2738. if (urlValue.indexOf('http://prezi.com/') != 0
  2739. && urlValue.indexOf('https://prezi.com/') != 0)
  2740. {
  2741. $.prompt.goToState('state1');
  2742. return false;
  2743. }
  2744. else {
  2745. var presIdTmp = urlValue.substring(
  2746. urlValue.indexOf("prezi.com/") + 10);
  2747. if (!isAlphanumeric(presIdTmp)
  2748. || presIdTmp.indexOf('/') < 2) {
  2749. $.prompt.goToState('state1');
  2750. return false;
  2751. }
  2752. else {
  2753. APP.xmpp.addToPresence("prezi", urlValue);
  2754. $.prompt.close();
  2755. }
  2756. }
  2757. }
  2758. }
  2759. else
  2760. $.prompt.close();
  2761. }
  2762. },
  2763. state1: {
  2764. html: '<h2>' + html + '</h2>' +
  2765. linkError,
  2766. persistent: false,
  2767. buttons: buttons1,
  2768. focus: ':input:first',
  2769. defaultButton: 1,
  2770. submit: function (e, v, m, f) {
  2771. e.preventDefault();
  2772. if (v === 0)
  2773. $.prompt.close();
  2774. else
  2775. $.prompt.goToState('state0');
  2776. }
  2777. }
  2778. };
  2779. messageHandler.openDialogWithStates(openPreziState);
  2780. }
  2781. }
  2782. };
  2783. /**
  2784. * A new presentation has been added.
  2785. *
  2786. * @param event the event indicating the add of a presentation
  2787. * @param jid the jid from which the presentation was added
  2788. * @param presUrl url of the presentation
  2789. * @param currentSlide the current slide to which we should move
  2790. */
  2791. function presentationAdded(event, jid, presUrl, currentSlide) {
  2792. console.log("presentation added", presUrl);
  2793. var presId = getPresentationId(presUrl);
  2794. var elementId = 'participant_'
  2795. + Strophe.getResourceFromJid(jid)
  2796. + '_' + presId;
  2797. // We explicitly don't specify the peer jid here, because we don't want
  2798. // this video to be dealt with as a peer related one (for example we
  2799. // don't want to show a mute/kick menu for this one, etc.).
  2800. VideoLayout.addRemoteVideoContainer(null, elementId);
  2801. VideoLayout.resizeThumbnails();
  2802. var controlsEnabled = false;
  2803. if (jid === APP.xmpp.myJid())
  2804. controlsEnabled = true;
  2805. setPresentationVisible(true);
  2806. $('#largeVideoContainer').hover(
  2807. function (event) {
  2808. if (Prezi.isPresentationVisible()) {
  2809. var reloadButtonRight = window.innerWidth
  2810. - $('#presentation>iframe').offset().left
  2811. - $('#presentation>iframe').width();
  2812. $('#reloadPresentation').css({ right: reloadButtonRight,
  2813. display:'inline-block'});
  2814. }
  2815. },
  2816. function (event) {
  2817. if (!Prezi.isPresentationVisible())
  2818. $('#reloadPresentation').css({display:'none'});
  2819. else {
  2820. var e = event.toElement || event.relatedTarget;
  2821. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  2822. $('#reloadPresentation').css({display:'none'});
  2823. }
  2824. });
  2825. preziPlayer = new PreziPlayer(
  2826. 'presentation',
  2827. {preziId: presId,
  2828. width: getPresentationWidth(),
  2829. height: getPresentationHeihgt(),
  2830. controls: controlsEnabled,
  2831. debug: true
  2832. });
  2833. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  2834. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  2835. console.log("prezi status", event.value);
  2836. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  2837. if (jid != APP.xmpp.myJid())
  2838. preziPlayer.flyToStep(currentSlide);
  2839. }
  2840. });
  2841. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  2842. console.log("event value", event.value);
  2843. APP.xmpp.addToPresence("preziSlide", event.value);
  2844. });
  2845. $("#" + elementId).css( 'background-image',
  2846. 'url(../images/avatarprezi.png)');
  2847. $("#" + elementId).click(
  2848. function () {
  2849. setPresentationVisible(true);
  2850. }
  2851. );
  2852. };
  2853. /**
  2854. * A presentation has been removed.
  2855. *
  2856. * @param event the event indicating the remove of a presentation
  2857. * @param jid the jid for which the presentation was removed
  2858. * @param the url of the presentation
  2859. */
  2860. function presentationRemoved(event, jid, presUrl) {
  2861. console.log('presentation removed', presUrl);
  2862. var presId = getPresentationId(presUrl);
  2863. setPresentationVisible(false);
  2864. $('#participant_'
  2865. + Strophe.getResourceFromJid(jid)
  2866. + '_' + presId).remove();
  2867. $('#presentation>iframe').remove();
  2868. if (preziPlayer != null) {
  2869. preziPlayer.destroy();
  2870. preziPlayer = null;
  2871. }
  2872. };
  2873. /**
  2874. * Indicates if the given string is an alphanumeric string.
  2875. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  2876. * purpose of checking URIs.
  2877. */
  2878. function isAlphanumeric(unsafeText) {
  2879. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  2880. return regex.test(unsafeText);
  2881. }
  2882. /**
  2883. * Returns the presentation id from the given url.
  2884. */
  2885. function getPresentationId (presUrl) {
  2886. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  2887. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  2888. }
  2889. /**
  2890. * Returns the presentation width.
  2891. */
  2892. function getPresentationWidth() {
  2893. var availableWidth = UIUtil.getAvailableVideoWidth();
  2894. var availableHeight = getPresentationHeihgt();
  2895. var aspectRatio = 16.0 / 9.0;
  2896. if (availableHeight < availableWidth / aspectRatio) {
  2897. availableWidth = Math.floor(availableHeight * aspectRatio);
  2898. }
  2899. return availableWidth;
  2900. }
  2901. /**
  2902. * Returns the presentation height.
  2903. */
  2904. function getPresentationHeihgt() {
  2905. var remoteVideos = $('#remoteVideos');
  2906. return window.innerHeight - remoteVideos.outerHeight();
  2907. }
  2908. /**
  2909. * Resizes the presentation iframe.
  2910. */
  2911. function resize() {
  2912. if ($('#presentation>iframe')) {
  2913. $('#presentation>iframe').width(getPresentationWidth());
  2914. $('#presentation>iframe').height(getPresentationHeihgt());
  2915. }
  2916. }
  2917. /**
  2918. * Shows/hides a presentation.
  2919. */
  2920. function setPresentationVisible(visible) {
  2921. var prezi = $('#presentation>iframe');
  2922. if (visible) {
  2923. // Trigger the video.selected event to indicate a change in the
  2924. // large video.
  2925. $(document).trigger("video.selected", [true]);
  2926. $('#largeVideo').fadeOut(300);
  2927. prezi.fadeIn(300, function() {
  2928. prezi.css({opacity:'1'});
  2929. ToolbarToggler.dockToolbar(true);
  2930. VideoLayout.setLargeVideoVisible(false);
  2931. });
  2932. $('#activeSpeaker').css('visibility', 'hidden');
  2933. }
  2934. else {
  2935. if (prezi.css('opacity') == '1') {
  2936. prezi.fadeOut(300, function () {
  2937. prezi.css({opacity:'0'});
  2938. $('#reloadPresentation').css({display:'none'});
  2939. $('#largeVideo').fadeIn(300, function() {
  2940. VideoLayout.setLargeVideoVisible(true);
  2941. ToolbarToggler.dockToolbar(false);
  2942. });
  2943. });
  2944. }
  2945. }
  2946. }
  2947. /**
  2948. * Presentation has been removed.
  2949. */
  2950. $(document).bind('presentationremoved.muc', presentationRemoved);
  2951. /**
  2952. * Presentation has been added.
  2953. */
  2954. $(document).bind('presentationadded.muc', presentationAdded);
  2955. /*
  2956. * Indicates presentation slide change.
  2957. */
  2958. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  2959. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  2960. preziPlayer.flyToStep(current);
  2961. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  2962. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  2963. preziPlayer.flyToStep(current, i);
  2964. }
  2965. }
  2966. });
  2967. /**
  2968. * On video selected event.
  2969. */
  2970. $(document).bind('video.selected', function (event, isPresentation) {
  2971. if (!isPresentation && $('#presentation>iframe')) {
  2972. setPresentationVisible(false);
  2973. }
  2974. });
  2975. $(window).resize(function () {
  2976. resize();
  2977. });
  2978. module.exports = Prezi;
  2979. },{"../toolbars/ToolbarToggler":26,"../util/MessageHandler":28,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./PreziPlayer":16}],16:[function(require,module,exports){
  2980. (function() {
  2981. "use strict";
  2982. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  2983. window.PreziPlayer = (function() {
  2984. PreziPlayer.API_VERSION = 1;
  2985. PreziPlayer.CURRENT_STEP = 'currentStep';
  2986. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  2987. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  2988. PreziPlayer.STATUS_LOADING = 'loading';
  2989. PreziPlayer.STATUS_READY = 'ready';
  2990. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  2991. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  2992. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  2993. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  2994. PreziPlayer.EVENT_STATUS = "statusChange";
  2995. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  2996. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  2997. PreziPlayer.domain = "https://prezi.com";
  2998. PreziPlayer.path = "/player/";
  2999. PreziPlayer.players = {};
  3000. PreziPlayer.binded_methods = ['changesHandler'];
  3001. PreziPlayer.createMultiplePlayers = function(optionArray){
  3002. for(var i=0; i<optionArray.length; i++) {
  3003. var optionSet = optionArray[i];
  3004. new PreziPlayer(optionSet.id, optionSet);
  3005. };
  3006. };
  3007. PreziPlayer.messageReceived = function(event){
  3008. var message, item, player;
  3009. try {
  3010. message = JSON.parse(event.data);
  3011. if (message.id && (player = PreziPlayer.players[message.id])) {
  3012. if (player.options.debug === true) {
  3013. if (console && console.log)
  3014. console.log('received', message);
  3015. }
  3016. if (message.type === "changes") {
  3017. player.changesHandler(message);
  3018. }
  3019. for (var i = 0; i < player.callbacks.length; i++) {
  3020. item = player.callbacks[i];
  3021. if (item && message.type === item.event) {
  3022. item.callback(message);
  3023. }
  3024. }
  3025. }
  3026. } catch (e) { }
  3027. };
  3028. function PreziPlayer(id, options) {
  3029. var params, paramString = "", _this = this;
  3030. if (PreziPlayer.players[id]){
  3031. PreziPlayer.players[id].destroy();
  3032. }
  3033. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  3034. var method_name = PreziPlayer.binded_methods[i];
  3035. _this[method_name] = __bind(_this[method_name], _this);
  3036. };
  3037. options = options || {};
  3038. this.options = options;
  3039. this.values = {'status': PreziPlayer.STATUS_LOADING};
  3040. this.values[PreziPlayer.CURRENT_STEP] = 0;
  3041. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  3042. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  3043. this.callbacks = [];
  3044. this.id = id;
  3045. this.embedTo = document.getElementById(id);
  3046. if (!this.embedTo) {
  3047. throw "The element id is not available.";
  3048. }
  3049. this.iframe = document.createElement('iframe');
  3050. params = [
  3051. { name: 'oid', value: options.preziId },
  3052. { name: 'explorable', value: options.explorable ? 1 : 0 },
  3053. { name: 'controls', value: options.controls ? 1 : 0 }
  3054. ];
  3055. for(var i=0; i<params.length; i++) {
  3056. var param = params[i];
  3057. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  3058. };
  3059. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  3060. this.iframe.frameBorder = 0;
  3061. this.iframe.scrolling = "no";
  3062. this.iframe.width = options.width || 640;
  3063. this.iframe.height = options.height || 480;
  3064. this.embedTo.innerHTML = '';
  3065. // JITSI: IN CASE SOMETHING GOES WRONG.
  3066. try {
  3067. this.embedTo.appendChild(this.iframe);
  3068. }
  3069. catch (err) {
  3070. console.log("CATCH ERROR");
  3071. }
  3072. // JITSI: Increase interval from 200 to 500, which fixes prezi
  3073. // crashes for us.
  3074. this.initPollInterval = setInterval(function(){
  3075. _this.sendMessage({'action': 'init'});
  3076. }, 500);
  3077. PreziPlayer.players[id] = this;
  3078. }
  3079. PreziPlayer.prototype.changesHandler = function(message) {
  3080. var key, value, j, item;
  3081. if (this.initPollInterval) {
  3082. clearInterval(this.initPollInterval);
  3083. this.initPollInterval = false;
  3084. }
  3085. for (key in message.data) {
  3086. if (message.data.hasOwnProperty(key)){
  3087. value = message.data[key];
  3088. this.values[key] = value;
  3089. for (j=0; j<this.callbacks.length; j++) {
  3090. item = this.callbacks[j];
  3091. if (item && item.event === key + "Change"){
  3092. item.callback({type: item.event, value: value});
  3093. }
  3094. }
  3095. }
  3096. }
  3097. };
  3098. PreziPlayer.prototype.destroy = function() {
  3099. if (this.initPollInterval) {
  3100. clearInterval(this.initPollInterval);
  3101. this.initPollInterval = false;
  3102. }
  3103. this.embedTo.innerHTML = '';
  3104. };
  3105. PreziPlayer.prototype.sendMessage = function(message) {
  3106. if (this.options.debug === true) {
  3107. if (console && console.log) console.log('sent', message);
  3108. }
  3109. message.version = PreziPlayer.API_VERSION;
  3110. message.id = this.id;
  3111. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  3112. };
  3113. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  3114. PreziPlayer.prototype.flyToNextStep = function() {
  3115. return this.sendMessage({
  3116. 'action': 'present',
  3117. 'data': ['moveToNextStep']
  3118. });
  3119. };
  3120. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  3121. PreziPlayer.prototype.flyToPreviousStep = function() {
  3122. return this.sendMessage({
  3123. 'action': 'present',
  3124. 'data': ['moveToPrevStep']
  3125. });
  3126. };
  3127. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  3128. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  3129. var obj = this;
  3130. // check animation_step
  3131. if (animation_step > 0 &&
  3132. obj.values.animationCountOnSteps &&
  3133. obj.values.animationCountOnSteps[step] <= animation_step) {
  3134. animation_step = obj.values.animationCountOnSteps[step];
  3135. }
  3136. // jump to animation steps by calling flyToNextStep()
  3137. function doAnimationSteps() {
  3138. if (obj.values.isMoving == true) {
  3139. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  3140. return;
  3141. }
  3142. while (animation_step-- > 0) {
  3143. obj.flyToNextStep(); // do the animation steps
  3144. }
  3145. }
  3146. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  3147. // jump to the step
  3148. return this.sendMessage({
  3149. 'action': 'present',
  3150. 'data': ['moveToStep', step]
  3151. });
  3152. };
  3153. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  3154. PreziPlayer.prototype.flyToObject = function(objectId) {
  3155. return this.sendMessage({
  3156. 'action': 'present',
  3157. 'data': ['moveToObject', objectId]
  3158. });
  3159. };
  3160. PreziPlayer.prototype.play = function(defaultDelay) {
  3161. return this.sendMessage({
  3162. 'action': 'present',
  3163. 'data': ['startAutoPlay', defaultDelay]
  3164. });
  3165. };
  3166. PreziPlayer.prototype.stop = function() {
  3167. return this.sendMessage({
  3168. 'action': 'present',
  3169. 'data': ['stopAutoPlay']
  3170. });
  3171. };
  3172. PreziPlayer.prototype.pause = function(defaultDelay) {
  3173. return this.sendMessage({
  3174. 'action': 'present',
  3175. 'data': ['pauseAutoPlay', defaultDelay]
  3176. });
  3177. };
  3178. PreziPlayer.prototype.getCurrentStep = function() {
  3179. return this.values.currentStep;
  3180. };
  3181. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  3182. return this.values.currentAnimationStep;
  3183. };
  3184. PreziPlayer.prototype.getCurrentObject = function() {
  3185. return this.values.currentObject;
  3186. };
  3187. PreziPlayer.prototype.getStatus = function() {
  3188. return this.values.status;
  3189. };
  3190. PreziPlayer.prototype.isPlaying = function() {
  3191. return this.values.isAutoPlaying;
  3192. };
  3193. PreziPlayer.prototype.getStepCount = function() {
  3194. return this.values.stepCount;
  3195. };
  3196. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  3197. return this.values.animationCountOnSteps;
  3198. };
  3199. PreziPlayer.prototype.getTitle = function() {
  3200. return this.values.title;
  3201. };
  3202. PreziPlayer.prototype.setDimensions = function(dims) {
  3203. for (var parameter in dims) {
  3204. this.iframe[parameter] = dims[parameter];
  3205. }
  3206. }
  3207. PreziPlayer.prototype.getDimensions = function() {
  3208. return {
  3209. width: parseInt(this.iframe.width, 10),
  3210. height: parseInt(this.iframe.height, 10)
  3211. }
  3212. }
  3213. PreziPlayer.prototype.on = function(event, callback) {
  3214. this.callbacks.push({
  3215. event: event,
  3216. callback: callback
  3217. });
  3218. };
  3219. PreziPlayer.prototype.off = function(event, callback) {
  3220. var j, item;
  3221. if (event === undefined) {
  3222. this.callbacks = [];
  3223. }
  3224. j = this.callbacks.length;
  3225. while (j--) {
  3226. item = this.callbacks[j];
  3227. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3228. this.callbacks.splice(j, 1);
  3229. }
  3230. }
  3231. };
  3232. if (window.addEventListener) {
  3233. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3234. } else {
  3235. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3236. }
  3237. return PreziPlayer;
  3238. })();
  3239. })();
  3240. module.exports = PreziPlayer;
  3241. },{}],17:[function(require,module,exports){
  3242. var Chat = require("./chat/Chat");
  3243. var ContactList = require("./contactlist/ContactList");
  3244. var Settings = require("./../../settings/Settings");
  3245. var SettingsMenu = require("./settings/SettingsMenu");
  3246. var VideoLayout = require("../videolayout/VideoLayout");
  3247. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3248. var UIUtil = require("../util/UIUtil");
  3249. /**
  3250. * Toggler for the chat, contact list, settings menu, etc..
  3251. */
  3252. var PanelToggler = (function(my) {
  3253. var currentlyOpen = null;
  3254. var buttons = {
  3255. '#chatspace': '#chatBottomButton',
  3256. '#contactlist': '#contactListButton',
  3257. '#settingsmenu': '#settingsButton'
  3258. };
  3259. /**
  3260. * Resizes the video area
  3261. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3262. * @param completeFunction a function to be called when the video space is resized
  3263. */
  3264. var resizeVideoArea = function(isClosing, completeFunction) {
  3265. var videospace = $('#videospace');
  3266. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3267. var videospaceWidth = window.innerWidth - panelSize[0];
  3268. var videospaceHeight = window.innerHeight;
  3269. var videoSize
  3270. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3271. var videoWidth = videoSize[0];
  3272. var videoHeight = videoSize[1];
  3273. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3274. videoHeight,
  3275. videospaceWidth,
  3276. videospaceHeight);
  3277. var horizontalIndent = videoPosition[0];
  3278. var verticalIndent = videoPosition[1];
  3279. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3280. var thumbnailsWidth = thumbnailSize[0];
  3281. var thumbnailsHeight = thumbnailSize[1];
  3282. //for chat
  3283. videospace.animate({
  3284. right: panelSize[0],
  3285. width: videospaceWidth,
  3286. height: videospaceHeight
  3287. },
  3288. {
  3289. queue: false,
  3290. duration: 500,
  3291. complete: completeFunction
  3292. });
  3293. $('#remoteVideos').animate({
  3294. height: thumbnailsHeight
  3295. },
  3296. {
  3297. queue: false,
  3298. duration: 500
  3299. });
  3300. $('#remoteVideos>span').animate({
  3301. height: thumbnailsHeight,
  3302. width: thumbnailsWidth
  3303. },
  3304. {
  3305. queue: false,
  3306. duration: 500,
  3307. complete: function () {
  3308. $(document).trigger(
  3309. "remotevideo.resized",
  3310. [thumbnailsWidth,
  3311. thumbnailsHeight]);
  3312. }
  3313. });
  3314. $('#largeVideoContainer').animate({
  3315. width: videospaceWidth,
  3316. height: videospaceHeight
  3317. },
  3318. {
  3319. queue: false,
  3320. duration: 500
  3321. });
  3322. $('#largeVideo').animate({
  3323. width: videoWidth,
  3324. height: videoHeight,
  3325. top: verticalIndent,
  3326. bottom: verticalIndent,
  3327. left: horizontalIndent,
  3328. right: horizontalIndent
  3329. },
  3330. {
  3331. queue: false,
  3332. duration: 500
  3333. });
  3334. };
  3335. /**
  3336. * Toggles the windows in the side panel
  3337. * @param object the window that should be shown
  3338. * @param selector the selector for the element containing the panel
  3339. * @param onOpenComplete function to be called when the panel is opened
  3340. * @param onOpen function to be called if the window is going to be opened
  3341. * @param onClose function to be called if the window is going to be closed
  3342. */
  3343. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3344. UIUtil.buttonClick(buttons[selector], "active");
  3345. if (object.isVisible()) {
  3346. $("#toast-container").animate({
  3347. right: '5px'
  3348. },
  3349. {
  3350. queue: false,
  3351. duration: 500
  3352. });
  3353. $(selector).hide("slide", {
  3354. direction: "right",
  3355. queue: false,
  3356. duration: 500
  3357. });
  3358. if(typeof onClose === "function") {
  3359. onClose();
  3360. }
  3361. currentlyOpen = null;
  3362. }
  3363. else {
  3364. // Undock the toolbar when the chat is shown and if we're in a
  3365. // video mode.
  3366. if (VideoLayout.isLargeVideoVisible()) {
  3367. ToolbarToggler.dockToolbar(false);
  3368. }
  3369. if(currentlyOpen) {
  3370. var current = $(currentlyOpen);
  3371. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3372. current.css('z-index', 4);
  3373. setTimeout(function () {
  3374. current.css('display', 'none');
  3375. current.css('z-index', 5);
  3376. }, 500);
  3377. }
  3378. $("#toast-container").animate({
  3379. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3380. },
  3381. {
  3382. queue: false,
  3383. duration: 500
  3384. });
  3385. $(selector).show("slide", {
  3386. direction: "right",
  3387. queue: false,
  3388. duration: 500,
  3389. complete: onOpenComplete
  3390. });
  3391. if(typeof onOpen === "function") {
  3392. onOpen();
  3393. }
  3394. currentlyOpen = selector;
  3395. }
  3396. };
  3397. /**
  3398. * Opens / closes the chat area.
  3399. */
  3400. my.toggleChat = function() {
  3401. var chatCompleteFunction = Chat.isVisible() ?
  3402. function() {} : function () {
  3403. Chat.scrollChatToBottom();
  3404. $('#chatspace').trigger('shown');
  3405. };
  3406. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3407. toggle(Chat,
  3408. '#chatspace',
  3409. function () {
  3410. // Request the focus in the nickname field or the chat input field.
  3411. if ($('#nickname').css('visibility') === 'visible') {
  3412. $('#nickinput').focus();
  3413. } else {
  3414. $('#usermsg').focus();
  3415. }
  3416. },
  3417. null,
  3418. Chat.resizeChat,
  3419. null);
  3420. };
  3421. /**
  3422. * Opens / closes the contact list area.
  3423. */
  3424. my.toggleContactList = function () {
  3425. var completeFunction = ContactList.isVisible() ?
  3426. function() {} : function () { $('#contactlist').trigger('shown');};
  3427. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3428. toggle(ContactList,
  3429. '#contactlist',
  3430. null,
  3431. function() {
  3432. ContactList.setVisualNotification(false);
  3433. },
  3434. null);
  3435. };
  3436. /**
  3437. * Opens / closes the settings menu
  3438. */
  3439. my.toggleSettingsMenu = function() {
  3440. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3441. toggle(SettingsMenu,
  3442. '#settingsmenu',
  3443. null,
  3444. function() {
  3445. var settings = Settings.getSettings();
  3446. $('#setDisplayName').get(0).value = settings.displayName;
  3447. $('#setEmail').get(0).value = settings.email;
  3448. },
  3449. null);
  3450. };
  3451. /**
  3452. * Returns the size of the side panel.
  3453. */
  3454. my.getPanelSize = function () {
  3455. var availableHeight = window.innerHeight;
  3456. var availableWidth = window.innerWidth;
  3457. var panelWidth = 200;
  3458. if (availableWidth * 0.2 < 200) {
  3459. panelWidth = availableWidth * 0.2;
  3460. }
  3461. return [panelWidth, availableHeight];
  3462. };
  3463. my.isVisible = function() {
  3464. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3465. };
  3466. return my;
  3467. }(PanelToggler || {}));
  3468. module.exports = PanelToggler;
  3469. },{"../toolbars/ToolbarToggler":26,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./../../settings/Settings":38,"./chat/Chat":18,"./contactlist/ContactList":22,"./settings/SettingsMenu":23}],18:[function(require,module,exports){
  3470. /* global $, Util, nickname:true */
  3471. var Replacement = require("./Replacement");
  3472. var CommandsProcessor = require("./Commands");
  3473. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3474. var smileys = require("./smileys.json").smileys;
  3475. var NicknameHandler = require("../../util/NicknameHandler");
  3476. var UIUtil = require("../../util/UIUtil");
  3477. var UIEvents = require("../../../../service/UI/UIEvents");
  3478. var notificationInterval = false;
  3479. var unreadMessages = 0;
  3480. /**
  3481. * Shows/hides a visual notification, indicating that a message has arrived.
  3482. */
  3483. function setVisualNotification(show) {
  3484. var unreadMsgElement = document.getElementById('unreadMessages');
  3485. var unreadMsgBottomElement
  3486. = document.getElementById('bottomUnreadMessages');
  3487. var glower = $('#chatButton');
  3488. var bottomGlower = $('#chatBottomButton');
  3489. if (unreadMessages) {
  3490. unreadMsgElement.innerHTML = unreadMessages.toString();
  3491. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3492. ToolbarToggler.dockToolbar(true);
  3493. var chatButtonElement
  3494. = document.getElementById('chatButton').parentNode;
  3495. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3496. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3497. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3498. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3499. unreadMsgElement.setAttribute(
  3500. 'style',
  3501. 'top:' + topIndent +
  3502. '; left:' + leftIndent + ';');
  3503. var chatBottomButtonElement
  3504. = document.getElementById('chatBottomButton').parentNode;
  3505. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3506. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3507. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3508. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3509. unreadMsgBottomElement.setAttribute(
  3510. 'style',
  3511. 'top:' + bottomTopIndent +
  3512. '; left:' + bottomLeftIndent + ';');
  3513. if (!glower.hasClass('icon-chat-simple')) {
  3514. glower.removeClass('icon-chat');
  3515. glower.addClass('icon-chat-simple');
  3516. }
  3517. }
  3518. else {
  3519. unreadMsgElement.innerHTML = '';
  3520. unreadMsgBottomElement.innerHTML = '';
  3521. glower.removeClass('icon-chat-simple');
  3522. glower.addClass('icon-chat');
  3523. }
  3524. if (show && !notificationInterval) {
  3525. notificationInterval = window.setInterval(function () {
  3526. glower.toggleClass('active');
  3527. bottomGlower.toggleClass('active glowing');
  3528. }, 800);
  3529. }
  3530. else if (!show && notificationInterval) {
  3531. window.clearInterval(notificationInterval);
  3532. notificationInterval = false;
  3533. glower.removeClass('active');
  3534. bottomGlower.removeClass('glowing');
  3535. bottomGlower.addClass('active');
  3536. }
  3537. }
  3538. /**
  3539. * Returns the current time in the format it is shown to the user
  3540. * @returns {string}
  3541. */
  3542. function getCurrentTime() {
  3543. var now = new Date();
  3544. var hour = now.getHours();
  3545. var minute = now.getMinutes();
  3546. var second = now.getSeconds();
  3547. if(hour.toString().length === 1) {
  3548. hour = '0'+hour;
  3549. }
  3550. if(minute.toString().length === 1) {
  3551. minute = '0'+minute;
  3552. }
  3553. if(second.toString().length === 1) {
  3554. second = '0'+second;
  3555. }
  3556. return hour+':'+minute+':'+second;
  3557. }
  3558. function toggleSmileys()
  3559. {
  3560. var smileys = $('#smileysContainer');
  3561. if(!smileys.is(':visible')) {
  3562. smileys.show("slide", { direction: "down", duration: 300});
  3563. } else {
  3564. smileys.hide("slide", { direction: "down", duration: 300});
  3565. }
  3566. $('#usermsg').focus();
  3567. }
  3568. function addClickFunction(smiley, number) {
  3569. smiley.onclick = function addSmileyToMessage() {
  3570. var usermsg = $('#usermsg');
  3571. var message = usermsg.val();
  3572. message += smileys['smiley' + number];
  3573. usermsg.val(message);
  3574. usermsg.get(0).setSelectionRange(message.length, message.length);
  3575. toggleSmileys();
  3576. usermsg.focus();
  3577. };
  3578. }
  3579. /**
  3580. * Adds the smileys container to the chat
  3581. */
  3582. function addSmileys() {
  3583. var smileysContainer = document.createElement('div');
  3584. smileysContainer.id = 'smileysContainer';
  3585. for(var i = 1; i <= 21; i++) {
  3586. var smileyContainer = document.createElement('div');
  3587. smileyContainer.id = 'smiley' + i;
  3588. smileyContainer.className = 'smileyContainer';
  3589. var smiley = document.createElement('img');
  3590. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3591. smiley.className = 'smiley';
  3592. addClickFunction(smiley, i);
  3593. smileyContainer.appendChild(smiley);
  3594. smileysContainer.appendChild(smileyContainer);
  3595. }
  3596. $("#chatspace").append(smileysContainer);
  3597. }
  3598. /**
  3599. * Resizes the chat conversation.
  3600. */
  3601. function resizeChatConversation() {
  3602. var msgareaHeight = $('#usermsg').outerHeight();
  3603. var chatspace = $('#chatspace');
  3604. var width = chatspace.width();
  3605. var chat = $('#chatconversation');
  3606. var smileys = $('#smileysarea');
  3607. smileys.height(msgareaHeight);
  3608. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3609. $('#smileysContainer').css('bottom', msgareaHeight);
  3610. chat.width(width - 10);
  3611. chat.height(window.innerHeight - 15 - msgareaHeight);
  3612. }
  3613. /**
  3614. * Chat related user interface.
  3615. */
  3616. var Chat = (function (my) {
  3617. /**
  3618. * Initializes chat related interface.
  3619. */
  3620. my.init = function () {
  3621. if(NicknameHandler.getNickname())
  3622. Chat.setChatConversationMode(true);
  3623. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3624. function (nickname) {
  3625. Chat.setChatConversationMode(true);
  3626. });
  3627. $('#nickinput').keydown(function (event) {
  3628. if (event.keyCode === 13) {
  3629. event.preventDefault();
  3630. var val = UIUtil.escapeHtml(this.value);
  3631. this.value = '';
  3632. if (!NicknameHandler.getNickname()) {
  3633. NicknameHandler.setNickname(val);
  3634. return;
  3635. }
  3636. }
  3637. });
  3638. $('#usermsg').keydown(function (event) {
  3639. if (event.keyCode === 13) {
  3640. event.preventDefault();
  3641. var value = this.value;
  3642. $('#usermsg').val('').trigger('autosize.resize');
  3643. this.focus();
  3644. var command = new CommandsProcessor(value);
  3645. if(command.isCommand())
  3646. {
  3647. command.processCommand();
  3648. }
  3649. else
  3650. {
  3651. var message = UIUtil.escapeHtml(value);
  3652. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3653. }
  3654. }
  3655. });
  3656. var onTextAreaResize = function () {
  3657. resizeChatConversation();
  3658. Chat.scrollChatToBottom();
  3659. };
  3660. $('#usermsg').autosize({callback: onTextAreaResize});
  3661. $("#chatspace").bind("shown",
  3662. function () {
  3663. unreadMessages = 0;
  3664. setVisualNotification(false);
  3665. });
  3666. addSmileys();
  3667. };
  3668. /**
  3669. * Appends the given message to the chat conversation.
  3670. */
  3671. my.updateChatConversation = function (from, displayName, message) {
  3672. var divClassName = '';
  3673. if (APP.xmpp.myJid() === from) {
  3674. divClassName = "localuser";
  3675. }
  3676. else {
  3677. divClassName = "remoteuser";
  3678. if (!Chat.isVisible()) {
  3679. unreadMessages++;
  3680. UIUtil.playSoundNotification('chatNotification');
  3681. setVisualNotification(true);
  3682. }
  3683. }
  3684. // replace links and smileys
  3685. // Strophe already escapes special symbols on sending,
  3686. // so we escape here only tags to avoid double &amp;
  3687. var escMessage = message.replace(/</g, '&lt;').
  3688. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  3689. var escDisplayName = UIUtil.escapeHtml(displayName);
  3690. message = Replacement.processReplacements(escMessage);
  3691. var messageContainer =
  3692. '<div class="chatmessage">'+
  3693. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  3694. '<div class="username ' + divClassName +'">' + escDisplayName +
  3695. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  3696. '</div>' + '<div class="usermessage">' + message + '</div>' +
  3697. '</div>';
  3698. $('#chatconversation').append(messageContainer);
  3699. $('#chatconversation').animate(
  3700. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3701. };
  3702. /**
  3703. * Appends error message to the conversation
  3704. * @param errorMessage the received error message.
  3705. * @param originalText the original message.
  3706. */
  3707. my.chatAddError = function(errorMessage, originalText)
  3708. {
  3709. errorMessage = UIUtil.escapeHtml(errorMessage);
  3710. originalText = UIUtil.escapeHtml(originalText);
  3711. $('#chatconversation').append(
  3712. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  3713. (originalText? (' \"'+ originalText + '\"') : "") +
  3714. ' was not sent.' +
  3715. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  3716. $('#chatconversation').animate(
  3717. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3718. };
  3719. /**
  3720. * Sets the subject to the UI
  3721. * @param subject the subject
  3722. */
  3723. my.chatSetSubject = function(subject)
  3724. {
  3725. if(subject)
  3726. subject = subject.trim();
  3727. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  3728. if(subject === "")
  3729. {
  3730. $("#subject").css({display: "none"});
  3731. }
  3732. else
  3733. {
  3734. $("#subject").css({display: "block"});
  3735. }
  3736. };
  3737. /**
  3738. * Sets the chat conversation mode.
  3739. */
  3740. my.setChatConversationMode = function (isConversationMode) {
  3741. if (isConversationMode) {
  3742. $('#nickname').css({visibility: 'hidden'});
  3743. $('#chatconversation').css({visibility: 'visible'});
  3744. $('#usermsg').css({visibility: 'visible'});
  3745. $('#smileysarea').css({visibility: 'visible'});
  3746. $('#usermsg').focus();
  3747. }
  3748. };
  3749. /**
  3750. * Resizes the chat area.
  3751. */
  3752. my.resizeChat = function () {
  3753. var chatSize = require("../SidePanelToggler").getPanelSize();
  3754. $('#chatspace').width(chatSize[0]);
  3755. $('#chatspace').height(chatSize[1]);
  3756. resizeChatConversation();
  3757. };
  3758. /**
  3759. * Indicates if the chat is currently visible.
  3760. */
  3761. my.isVisible = function () {
  3762. return $('#chatspace').is(":visible");
  3763. };
  3764. /**
  3765. * Shows and hides the window with the smileys
  3766. */
  3767. my.toggleSmileys = toggleSmileys;
  3768. /**
  3769. * Scrolls chat to the bottom.
  3770. */
  3771. my.scrollChatToBottom = function() {
  3772. setTimeout(function () {
  3773. $('#chatconversation').scrollTop(
  3774. $('#chatconversation')[0].scrollHeight);
  3775. }, 5);
  3776. };
  3777. return my;
  3778. }(Chat || {}));
  3779. module.exports = Chat;
  3780. },{"../../../../service/UI/UIEvents":92,"../../toolbars/ToolbarToggler":26,"../../util/NicknameHandler":29,"../../util/UIUtil":30,"../SidePanelToggler":17,"./Commands":19,"./Replacement":20,"./smileys.json":21}],19:[function(require,module,exports){
  3781. var UIUtil = require("../../util/UIUtil");
  3782. /**
  3783. * List with supported commands. The keys are the names of the commands and
  3784. * the value is the function that processes the message.
  3785. * @type {{String: function}}
  3786. */
  3787. var commands = {
  3788. "topic" : processTopic
  3789. };
  3790. /**
  3791. * Extracts the command from the message.
  3792. * @param message the received message
  3793. * @returns {string} the command
  3794. */
  3795. function getCommand(message)
  3796. {
  3797. if(message)
  3798. {
  3799. for(var command in commands)
  3800. {
  3801. if(message.indexOf("/" + command) == 0)
  3802. return command;
  3803. }
  3804. }
  3805. return "";
  3806. };
  3807. /**
  3808. * Processes the data for topic command.
  3809. * @param commandArguments the arguments of the topic command.
  3810. */
  3811. function processTopic(commandArguments)
  3812. {
  3813. var topic = UIUtil.escapeHtml(commandArguments);
  3814. APP.xmpp.setSubject(topic);
  3815. }
  3816. /**
  3817. * Constructs new CommandProccessor instance from a message that
  3818. * handles commands received via chat messages.
  3819. * @param message the message
  3820. * @constructor
  3821. */
  3822. function CommandsProcessor(message)
  3823. {
  3824. var command = getCommand(message);
  3825. /**
  3826. * Returns the name of the command.
  3827. * @returns {String} the command
  3828. */
  3829. this.getCommand = function()
  3830. {
  3831. return command;
  3832. };
  3833. var messageArgument = message.substr(command.length + 2);
  3834. /**
  3835. * Returns the arguments of the command.
  3836. * @returns {string}
  3837. */
  3838. this.getArgument = function()
  3839. {
  3840. return messageArgument;
  3841. };
  3842. }
  3843. /**
  3844. * Checks whether this instance is valid command or not.
  3845. * @returns {boolean}
  3846. */
  3847. CommandsProcessor.prototype.isCommand = function()
  3848. {
  3849. if(this.getCommand())
  3850. return true;
  3851. return false;
  3852. };
  3853. /**
  3854. * Processes the command.
  3855. */
  3856. CommandsProcessor.prototype.processCommand = function()
  3857. {
  3858. if(!this.isCommand())
  3859. return;
  3860. commands[this.getCommand()](this.getArgument());
  3861. };
  3862. module.exports = CommandsProcessor;
  3863. },{"../../util/UIUtil":30}],20:[function(require,module,exports){
  3864. var Smileys = require("./smileys.json");
  3865. /**
  3866. * Processes links and smileys in "body"
  3867. */
  3868. function processReplacements(body)
  3869. {
  3870. //make links clickable
  3871. body = linkify(body);
  3872. //add smileys
  3873. body = smilify(body);
  3874. return body;
  3875. }
  3876. /**
  3877. * Finds and replaces all links in the links in "body"
  3878. * with their <a href=""></a>
  3879. */
  3880. function linkify(inputText)
  3881. {
  3882. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  3883. //URLs starting with http://, https://, or ftp://
  3884. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  3885. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  3886. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  3887. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  3888. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  3889. //Change email addresses to mailto:: links.
  3890. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  3891. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  3892. return replacedText;
  3893. }
  3894. /**
  3895. * Replaces common smiley strings with images
  3896. */
  3897. function smilify(body)
  3898. {
  3899. if(!body) {
  3900. return body;
  3901. }
  3902. var regexs = Smileys["regexs"];
  3903. for(var smiley in regexs) {
  3904. if(regexs.hasOwnProperty(smiley)) {
  3905. body = body.replace(regexs[smiley],
  3906. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  3907. }
  3908. }
  3909. return body;
  3910. }
  3911. module.exports = {
  3912. processReplacements: processReplacements,
  3913. linkify: linkify
  3914. };
  3915. },{"./smileys.json":21}],21:[function(require,module,exports){
  3916. module.exports={
  3917. "smileys": {
  3918. "smiley1": ":)",
  3919. "smiley2": ":(",
  3920. "smiley3": ":D",
  3921. "smiley4": "(y)",
  3922. "smiley5": " :P",
  3923. "smiley6": "(wave)",
  3924. "smiley7": "(blush)",
  3925. "smiley8": "(chuckle)",
  3926. "smiley9": "(shocked)",
  3927. "smiley10": ":*",
  3928. "smiley11": "(n)",
  3929. "smiley12": "(search)",
  3930. "smiley13": " <3",
  3931. "smiley14": "(oops)",
  3932. "smiley15": "(angry)",
  3933. "smiley16": "(angel)",
  3934. "smiley17": "(sick)",
  3935. "smiley18": ";(",
  3936. "smiley19": "(bomb)",
  3937. "smiley20": "(clap)",
  3938. "smiley21": " ;)"
  3939. },
  3940. "regexs": {
  3941. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  3942. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  3943. "smiley1": /(:-\)|:\))/gi,
  3944. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  3945. "smiley5": /(:-P|:P|:-p|:p)/gi,
  3946. "smiley6": /(\(wave\))/gi,
  3947. "smiley7": /(\(blush\))/gi,
  3948. "smiley8": /(\(chuckle\))/gi,
  3949. "smiley9": /(:-0|\(shocked\))/gi,
  3950. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  3951. "smiley11": /(\(n\))/gi,
  3952. "smiley12": /(\(search\))/g,
  3953. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  3954. "smiley14": /(\(oops\))/gi,
  3955. "smiley15": /(\(angry\))/gi,
  3956. "smiley16": /(\(angel\))/gi,
  3957. "smiley17": /(\(sick\))/gi,
  3958. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  3959. "smiley19": /(\(bomb\))/gi,
  3960. "smiley20": /(\(clap\))/gi,
  3961. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  3962. }
  3963. }
  3964. },{}],22:[function(require,module,exports){
  3965. var numberOfContacts = 0;
  3966. var notificationInterval;
  3967. /**
  3968. * Updates the number of participants in the contact list button and sets
  3969. * the glow
  3970. * @param delta indicates whether a new user has joined (1) or someone has
  3971. * left(-1)
  3972. */
  3973. function updateNumberOfParticipants(delta) {
  3974. //when the user is alone we don't show the number of participants
  3975. if(numberOfContacts === 0) {
  3976. $("#numberOfParticipants").text('');
  3977. numberOfContacts += delta;
  3978. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  3979. ContactList.setVisualNotification(true);
  3980. numberOfContacts += delta;
  3981. $("#numberOfParticipants").text(numberOfContacts);
  3982. }
  3983. }
  3984. /**
  3985. * Creates the avatar element.
  3986. *
  3987. * @return the newly created avatar element
  3988. */
  3989. function createAvatar(id) {
  3990. var avatar = document.createElement('img');
  3991. avatar.className = "icon-avatar avatar";
  3992. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  3993. return avatar;
  3994. }
  3995. /**
  3996. * Creates the display name paragraph.
  3997. *
  3998. * @param displayName the display name to set
  3999. */
  4000. function createDisplayNameParagraph(key, displayName) {
  4001. var p = document.createElement('p');
  4002. if(displayName)
  4003. p.innerText = displayName;
  4004. else if(key)
  4005. {
  4006. p.setAttribute("data-i18n",key);
  4007. p.innerText = APP.translation.translateString(key);
  4008. }
  4009. return p;
  4010. }
  4011. function stopGlowing(glower) {
  4012. window.clearInterval(notificationInterval);
  4013. notificationInterval = false;
  4014. glower.removeClass('glowing');
  4015. if (!ContactList.isVisible()) {
  4016. glower.removeClass('active');
  4017. }
  4018. }
  4019. /**
  4020. * Contact list.
  4021. */
  4022. var ContactList = {
  4023. /**
  4024. * Indicates if the chat is currently visible.
  4025. *
  4026. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  4027. * otherwise
  4028. */
  4029. isVisible: function () {
  4030. return $('#contactlist').is(":visible");
  4031. },
  4032. /**
  4033. * Adds a contact for the given peerJid if such doesn't yet exist.
  4034. *
  4035. * @param peerJid the peerJid corresponding to the contact
  4036. * @param id the user's email or userId used to get the user's avatar
  4037. */
  4038. ensureAddContact: function (peerJid, id) {
  4039. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4040. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4041. if (!contact || contact.length <= 0)
  4042. ContactList.addContact(peerJid, id);
  4043. },
  4044. /**
  4045. * Adds a contact for the given peer jid.
  4046. *
  4047. * @param peerJid the jid of the contact to add
  4048. * @param id the email or userId of the user
  4049. */
  4050. addContact: function (peerJid, id) {
  4051. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4052. var contactlist = $('#contactlist>ul');
  4053. var newContact = document.createElement('li');
  4054. newContact.id = resourceJid;
  4055. newContact.className = "clickable";
  4056. newContact.onclick = function (event) {
  4057. if (event.currentTarget.className === "clickable") {
  4058. $(ContactList).trigger('contactclicked', [peerJid]);
  4059. }
  4060. };
  4061. newContact.appendChild(createAvatar(id));
  4062. newContact.appendChild(createDisplayNameParagraph("participant"));
  4063. var clElement = contactlist.get(0);
  4064. if (resourceJid === APP.xmpp.myResource()
  4065. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  4066. clElement.insertBefore(newContact,
  4067. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  4068. }
  4069. else {
  4070. clElement.appendChild(newContact);
  4071. }
  4072. updateNumberOfParticipants(1);
  4073. },
  4074. /**
  4075. * Removes a contact for the given peer jid.
  4076. *
  4077. * @param peerJid the peerJid corresponding to the contact to remove
  4078. */
  4079. removeContact: function (peerJid) {
  4080. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4081. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4082. if (contact && contact.length > 0) {
  4083. var contactlist = $('#contactlist>ul');
  4084. contactlist.get(0).removeChild(contact.get(0));
  4085. updateNumberOfParticipants(-1);
  4086. }
  4087. },
  4088. setVisualNotification: function (show, stopGlowingIn) {
  4089. var glower = $('#contactListButton');
  4090. if (show && !notificationInterval) {
  4091. notificationInterval = window.setInterval(function () {
  4092. glower.toggleClass('active glowing');
  4093. }, 800);
  4094. }
  4095. else if (!show && notificationInterval) {
  4096. stopGlowing(glower);
  4097. }
  4098. if (stopGlowingIn) {
  4099. setTimeout(function () {
  4100. stopGlowing(glower);
  4101. }, stopGlowingIn);
  4102. }
  4103. },
  4104. setClickable: function (resourceJid, isClickable) {
  4105. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4106. if (isClickable) {
  4107. contact.addClass('clickable');
  4108. } else {
  4109. contact.removeClass('clickable');
  4110. }
  4111. },
  4112. onDisplayNameChange: function (peerJid, displayName) {
  4113. if (peerJid === 'localVideoContainer')
  4114. peerJid = APP.xmpp.myJid();
  4115. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4116. var contactName = $('#contactlist #' + resourceJid + '>p');
  4117. if (contactName && displayName && displayName.length > 0)
  4118. contactName.html(displayName);
  4119. }
  4120. };
  4121. module.exports = ContactList;
  4122. },{}],23:[function(require,module,exports){
  4123. var Avatar = require("../../avatar/Avatar");
  4124. var Settings = require("./../../../settings/Settings");
  4125. var UIUtil = require("../../util/UIUtil");
  4126. var languages = require("../../../../service/translation/languages");
  4127. function generateLanguagesSelectBox()
  4128. {
  4129. var currentLang = APP.translation.getCurrentLanguage();
  4130. var html = "<select id=\"languages_selectbox\">";
  4131. var langArray = languages.getLanguages();
  4132. for(var i = 0; i < langArray.length; i++)
  4133. {
  4134. var lang = langArray[i];
  4135. html += "<option ";
  4136. if(lang === currentLang)
  4137. html += "selected ";
  4138. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  4139. html += "</option>";
  4140. }
  4141. return html + "</select>";
  4142. }
  4143. var SettingsMenu = {
  4144. init: function () {
  4145. $("#updateSettings").before(generateLanguagesSelectBox());
  4146. APP.translation.translateElement($("#languages_selectbox"));
  4147. $('#settingsmenu>input').keyup(function(event){
  4148. if(event.keyCode === 13) {//enter
  4149. SettingsMenu.update();
  4150. }
  4151. });
  4152. $("#updateSettings").click(function () {
  4153. SettingsMenu.update();
  4154. });
  4155. },
  4156. update: function() {
  4157. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  4158. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  4159. if(newDisplayName) {
  4160. var displayName = Settings.setDisplayName(newDisplayName);
  4161. APP.xmpp.addToPresence("displayName", displayName, true);
  4162. }
  4163. var language = $("#languages_selectbox").val();
  4164. APP.translation.setLanguage(language);
  4165. Settings.setLanguage(language);
  4166. APP.xmpp.addToPresence("email", newEmail);
  4167. var email = Settings.setEmail(newEmail);
  4168. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  4169. },
  4170. isVisible: function() {
  4171. return $('#settingsmenu').is(':visible');
  4172. },
  4173. setDisplayName: function(newDisplayName) {
  4174. var displayName = Settings.setDisplayName(newDisplayName);
  4175. $('#setDisplayName').get(0).value = displayName;
  4176. },
  4177. onDisplayNameChange: function(peerJid, newDisplayName) {
  4178. if(peerJid === 'localVideoContainer' ||
  4179. peerJid === APP.xmpp.myJid()) {
  4180. this.setDisplayName(newDisplayName);
  4181. }
  4182. }
  4183. };
  4184. module.exports = SettingsMenu;
  4185. },{"../../../../service/translation/languages":96,"../../avatar/Avatar":13,"../../util/UIUtil":30,"./../../../settings/Settings":38}],24:[function(require,module,exports){
  4186. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4187. var buttonHandlers = {
  4188. "bottom_toolbar_contact_list": function () {
  4189. BottomToolbar.toggleContactList();
  4190. },
  4191. "bottom_toolbar_film_strip": function () {
  4192. BottomToolbar.toggleFilmStrip();
  4193. },
  4194. "bottom_toolbar_chat": function () {
  4195. BottomToolbar.toggleChat();
  4196. }
  4197. };
  4198. var BottomToolbar = (function (my) {
  4199. my.init = function () {
  4200. for(var k in buttonHandlers)
  4201. $("#" + k).click(buttonHandlers[k]);
  4202. };
  4203. my.toggleChat = function() {
  4204. PanelToggler.toggleChat();
  4205. };
  4206. my.toggleContactList = function() {
  4207. PanelToggler.toggleContactList();
  4208. };
  4209. my.toggleFilmStrip = function() {
  4210. var filmstrip = $("#remoteVideos");
  4211. filmstrip.toggleClass("hidden");
  4212. };
  4213. $(document).bind("remotevideo.resized", function (event, width, height) {
  4214. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  4215. $('#bottomToolbar').css({bottom: bottom + 'px'});
  4216. });
  4217. return my;
  4218. }(BottomToolbar || {}));
  4219. module.exports = BottomToolbar;
  4220. },{"../side_pannels/SidePanelToggler":17}],25:[function(require,module,exports){
  4221. /* global APP,$, buttonClick, config, lockRoom,
  4222. setSharedKey, Util */
  4223. var messageHandler = require("../util/MessageHandler");
  4224. var BottomToolbar = require("./BottomToolbar");
  4225. var Prezi = require("../prezi/Prezi");
  4226. var Etherpad = require("../etherpad/Etherpad");
  4227. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4228. var Authentication = require("../authentication/Authentication");
  4229. var UIUtil = require("../util/UIUtil");
  4230. var AuthenticationEvents
  4231. = require("../../../service/authentication/AuthenticationEvents");
  4232. var roomUrl = null;
  4233. var sharedKey = '';
  4234. var UI = null;
  4235. var buttonHandlers =
  4236. {
  4237. "toolbar_button_mute": function () {
  4238. return APP.UI.toggleAudio();
  4239. },
  4240. "toolbar_button_camera": function () {
  4241. return APP.UI.toggleVideo();
  4242. },
  4243. /*"toolbar_button_authentication": function () {
  4244. return Toolbar.authenticateClicked();
  4245. },*/
  4246. "toolbar_button_record": function () {
  4247. return toggleRecording();
  4248. },
  4249. "toolbar_button_security": function () {
  4250. return Toolbar.openLockDialog();
  4251. },
  4252. "toolbar_button_link": function () {
  4253. return Toolbar.openLinkDialog();
  4254. },
  4255. "toolbar_button_chat": function () {
  4256. return BottomToolbar.toggleChat();
  4257. },
  4258. "toolbar_button_prezi": function () {
  4259. return Prezi.openPreziDialog();
  4260. },
  4261. "toolbar_button_etherpad": function () {
  4262. return Etherpad.toggleEtherpad(0);
  4263. },
  4264. "toolbar_button_desktopsharing": function () {
  4265. return APP.desktopsharing.toggleScreenSharing();
  4266. },
  4267. "toolbar_button_fullScreen": function()
  4268. {
  4269. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4270. return Toolbar.toggleFullScreen();
  4271. },
  4272. "toolbar_button_sip": function () {
  4273. return callSipButtonClicked();
  4274. },
  4275. "toolbar_button_settings": function () {
  4276. PanelToggler.toggleSettingsMenu();
  4277. },
  4278. "toolbar_button_hangup": function () {
  4279. return hangup();
  4280. },
  4281. "toolbar_button_login": function () {
  4282. Toolbar.authenticateClicked();
  4283. },
  4284. "toolbar_button_logout": function () {
  4285. // Ask for confirmation
  4286. messageHandler.openTwoButtonDialog(
  4287. "dialog.logoutTitle",
  4288. null,
  4289. "dialog.logoutQuestion",
  4290. null,
  4291. false,
  4292. "dialog.Yes",
  4293. function (evt, yes) {
  4294. if (yes) {
  4295. APP.xmpp.logout(function (url) {
  4296. if (url) {
  4297. window.location.href = url;
  4298. } else {
  4299. hangup();
  4300. }
  4301. });
  4302. }
  4303. });
  4304. }
  4305. };
  4306. function hangup() {
  4307. APP.xmpp.disposeConference();
  4308. if(config.enableWelcomePage)
  4309. {
  4310. setTimeout(function()
  4311. {
  4312. window.localStorage.welcomePageDisabled = false;
  4313. window.location.pathname = "/";
  4314. }, 10000);
  4315. }
  4316. var title = APP.translation.generateTranslatonHTML(
  4317. "dialog.sessTerminated");
  4318. var msg = APP.translation.generateTranslatonHTML(
  4319. "dialog.hungUp");
  4320. var button = APP.translation.generateTranslatonHTML(
  4321. "dialog.joinAgain");
  4322. var buttons = [];
  4323. buttons.push({title: button, value: true});
  4324. UI.messageHandler.openDialog(
  4325. title,
  4326. msg,
  4327. true,
  4328. buttons,
  4329. function(event, value, message, formVals)
  4330. {
  4331. window.location.reload();
  4332. return false;
  4333. }
  4334. );
  4335. }
  4336. /**
  4337. * Starts or stops the recording for the conference.
  4338. */
  4339. function toggleRecording() {
  4340. APP.xmpp.toggleRecording(function (callback) {
  4341. var msg = APP.translation.generateTranslatonHTML(
  4342. "dialog.recordingToken");
  4343. var token = APP.translation.translateString("dialog.token");
  4344. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  4345. '<h2>' + msg + '</h2>' +
  4346. '<input name="recordingToken" type="text" ' +
  4347. ' data-i18n="[placeholder]dialog.token" ' +
  4348. 'placeholder="' + token + '" autofocus>',
  4349. false,
  4350. "dialog.Save",
  4351. function (e, v, m, f) {
  4352. if (v) {
  4353. var token = f.recordingToken;
  4354. if (token) {
  4355. callback(UIUtil.escapeHtml(token));
  4356. }
  4357. }
  4358. },
  4359. null,
  4360. function () { },
  4361. ':input:first'
  4362. );
  4363. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4364. }
  4365. /**
  4366. * Locks / unlocks the room.
  4367. */
  4368. function lockRoom(lock) {
  4369. var currentSharedKey = '';
  4370. if (lock)
  4371. currentSharedKey = sharedKey;
  4372. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4373. // password is required
  4374. if (sharedKey)
  4375. {
  4376. console.log('set room password');
  4377. Toolbar.lockLockButton();
  4378. }
  4379. else
  4380. {
  4381. console.log('removed room password');
  4382. Toolbar.unlockLockButton();
  4383. }
  4384. }, function (err) {
  4385. console.warn('setting password failed', err);
  4386. messageHandler.showError("dialog.lockTitle",
  4387. "dialog.lockMessage");
  4388. Toolbar.setSharedKey('');
  4389. }, function () {
  4390. console.warn('room passwords not supported');
  4391. messageHandler.showError("dialog.warning",
  4392. "dialog.passwordNotSupported");
  4393. Toolbar.setSharedKey('');
  4394. });
  4395. };
  4396. /**
  4397. * Invite participants to conference.
  4398. */
  4399. function inviteParticipants() {
  4400. if (roomUrl === null)
  4401. return;
  4402. var sharedKeyText = "";
  4403. if (sharedKey && sharedKey.length > 0) {
  4404. sharedKeyText =
  4405. APP.translation.translateString("email.sharedKey",
  4406. {sharedKey: sharedKey});
  4407. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  4408. }
  4409. var supportedBrowsers = "Chromium, Google Chrome " +
  4410. APP.translation.translateString("email.and") + " Opera";
  4411. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4412. var subject = APP.translation.translateString("email.subject",
  4413. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  4414. var body = APP.translation.translateString("email.body",
  4415. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  4416. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  4417. body = body.replace(/\n/g, "%0D%0A");
  4418. if (window.localStorage.displayname) {
  4419. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4420. }
  4421. if (interfaceConfig.INVITATION_POWERED_BY) {
  4422. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4423. }
  4424. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4425. }
  4426. function callSipButtonClicked()
  4427. {
  4428. var defaultNumber
  4429. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4430. var sipMsg = APP.translation.generateTranslatonHTML(
  4431. "dialog.sipMsg");
  4432. messageHandler.openTwoButtonDialog(null, null, null,
  4433. '<h2>' + sipMsg + '</h2>' +
  4434. '<input name="sipNumber" type="text"' +
  4435. ' value="' + defaultNumber + '" autofocus>',
  4436. false,
  4437. "dialog.Dial",
  4438. function (e, v, m, f) {
  4439. if (v) {
  4440. var numberInput = f.sipNumber;
  4441. if (numberInput) {
  4442. APP.xmpp.dial(
  4443. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  4444. }
  4445. }
  4446. },
  4447. null,
  4448. ':input:first'
  4449. );
  4450. }
  4451. var Toolbar = (function (my) {
  4452. my.init = function (ui) {
  4453. for(var k in buttonHandlers)
  4454. $("#" + k).click(buttonHandlers[k]);
  4455. UI = ui;
  4456. // Update login info
  4457. APP.xmpp.addListener(
  4458. AuthenticationEvents.IDENTITY_UPDATED,
  4459. function (authenticationEnabled, userIdentity) {
  4460. var loggedIn = false;
  4461. if (userIdentity) {
  4462. loggedIn = true;
  4463. }
  4464. Toolbar.showAuthenticateButton(authenticationEnabled);
  4465. if (authenticationEnabled) {
  4466. Toolbar.setAuthenticatedIdentity(userIdentity);
  4467. Toolbar.showLoginButton(!loggedIn);
  4468. Toolbar.showLogoutButton(loggedIn);
  4469. }
  4470. }
  4471. );
  4472. },
  4473. /**
  4474. * Sets shared key
  4475. * @param sKey the shared key
  4476. */
  4477. my.setSharedKey = function (sKey) {
  4478. sharedKey = sKey;
  4479. };
  4480. my.authenticateClicked = function () {
  4481. Authentication.focusAuthenticationWindow();
  4482. if (!APP.xmpp.isExternalAuthEnabled()) {
  4483. Authentication.xmppAuthenticate();
  4484. return;
  4485. }
  4486. // Get authentication URL
  4487. if (!APP.xmpp.getMUCJoined()) {
  4488. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4489. // If conference has not been started yet - redirect to login page
  4490. window.location.href = url;
  4491. });
  4492. } else {
  4493. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4494. // Otherwise - open popup with authentication URL
  4495. var authenticationWindow = Authentication.createAuthenticationWindow(
  4496. function () {
  4497. // On popup closed - retry room allocation
  4498. APP.xmpp.allocateConferenceFocus(
  4499. APP.UI.getRoomName(),
  4500. function () { console.info("AUTH DONE"); }
  4501. );
  4502. }, url);
  4503. if (!authenticationWindow) {
  4504. messageHandler.openMessageDialog(
  4505. null, "dialog.popupError");
  4506. }
  4507. });
  4508. }
  4509. };
  4510. /**
  4511. * Updates the room invite url.
  4512. */
  4513. my.updateRoomUrl = function (newRoomUrl) {
  4514. roomUrl = newRoomUrl;
  4515. // If the invite dialog has been already opened we update the information.
  4516. var inviteLink = document.getElementById('inviteLinkRef');
  4517. if (inviteLink) {
  4518. inviteLink.value = roomUrl;
  4519. inviteLink.select();
  4520. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  4521. }
  4522. };
  4523. /**
  4524. * Disables and enables some of the buttons.
  4525. */
  4526. my.setupButtonsFromConfig = function () {
  4527. if (config.disablePrezi)
  4528. {
  4529. $("#prezi_button").css({display: "none"});
  4530. }
  4531. };
  4532. /**
  4533. * Opens the lock room dialog.
  4534. */
  4535. my.openLockDialog = function () {
  4536. // Only the focus is able to set a shared key.
  4537. if (!APP.xmpp.isModerator()) {
  4538. if (sharedKey) {
  4539. messageHandler.openMessageDialog(null,
  4540. "dialog.passwordError");
  4541. } else {
  4542. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  4543. }
  4544. } else {
  4545. if (sharedKey) {
  4546. messageHandler.openTwoButtonDialog(null, null,
  4547. "dialog.passwordCheck",
  4548. null,
  4549. false,
  4550. "dialog.Remove",
  4551. function (e, v) {
  4552. if (v) {
  4553. Toolbar.setSharedKey('');
  4554. lockRoom(false);
  4555. }
  4556. });
  4557. } else {
  4558. var msg = APP.translation.generateTranslatonHTML(
  4559. "dialog.passwordMsg");
  4560. var yourPassword = APP.translation.translateString(
  4561. "dialog.yourPassword");
  4562. messageHandler.openTwoButtonDialog(null, null, null,
  4563. '<h2>' + msg + '</h2>' +
  4564. '<input name="lockKey" type="text"' +
  4565. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  4566. 'placeholder="' + yourPassword + '" autofocus>',
  4567. false,
  4568. "dialog.Save",
  4569. function (e, v, m, f) {
  4570. if (v) {
  4571. var lockKey = f.lockKey;
  4572. if (lockKey) {
  4573. Toolbar.setSharedKey(
  4574. UIUtil.escapeHtml(lockKey));
  4575. lockRoom(true);
  4576. }
  4577. }
  4578. },
  4579. null, null, 'input:first'
  4580. );
  4581. }
  4582. }
  4583. };
  4584. /**
  4585. * Opens the invite link dialog.
  4586. */
  4587. my.openLinkDialog = function () {
  4588. var inviteAttreibutes;
  4589. if (roomUrl === null) {
  4590. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  4591. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  4592. } else {
  4593. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  4594. }
  4595. messageHandler.openTwoButtonDialog("dialog.shareLink",
  4596. null, null,
  4597. '<input id="inviteLinkRef" type="text" ' +
  4598. inviteAttreibutes + ' onclick="this.select();" readonly>',
  4599. false,
  4600. "dialog.Invite",
  4601. function (e, v) {
  4602. if (v) {
  4603. if (roomUrl) {
  4604. inviteParticipants();
  4605. }
  4606. }
  4607. },
  4608. function () {
  4609. if (roomUrl) {
  4610. document.getElementById('inviteLinkRef').select();
  4611. } else {
  4612. document.getElementById('jqi_state0_buttonInvite')
  4613. .disabled = true;
  4614. }
  4615. }
  4616. );
  4617. };
  4618. /**
  4619. * Opens the settings dialog.
  4620. * FIXME: not used ?
  4621. */
  4622. my.openSettingsDialog = function () {
  4623. var settings1 = APP.translation.generateTranslatonHTML(
  4624. "dialog.settings1");
  4625. var settings2 = APP.translation.generateTranslatonHTML(
  4626. "dialog.settings2");
  4627. var settings3 = APP.translation.generateTranslatonHTML(
  4628. "dialog.settings3");
  4629. var yourPassword = APP.translation.translateString(
  4630. "dialog.yourPassword");
  4631. messageHandler.openTwoButtonDialog(null,
  4632. '<h2>' + settings1 + '</h2>' +
  4633. '<input type="checkbox" id="initMuted">' +
  4634. settings2 + '<br/>' +
  4635. '<input type="checkbox" id="requireNicknames">' +
  4636. settings3 +
  4637. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  4638. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  4639. null,
  4640. null,
  4641. false,
  4642. "dialog.Save",
  4643. function () {
  4644. document.getElementById('lockKey').focus();
  4645. },
  4646. function (e, v) {
  4647. if (v) {
  4648. if ($('#initMuted').is(":checked")) {
  4649. // it is checked
  4650. }
  4651. if ($('#requireNicknames').is(":checked")) {
  4652. // it is checked
  4653. }
  4654. /*
  4655. var lockKey = document.getElementById('lockKey');
  4656. if (lockKey.value) {
  4657. setSharedKey(lockKey.value);
  4658. lockRoom(true);
  4659. }
  4660. */
  4661. }
  4662. }
  4663. );
  4664. };
  4665. /**
  4666. * Toggles the application in and out of full screen mode
  4667. * (a.k.a. presentation mode in Chrome).
  4668. */
  4669. my.toggleFullScreen = function () {
  4670. var fsElement = document.documentElement;
  4671. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  4672. //Enter Full Screen
  4673. if (fsElement.mozRequestFullScreen) {
  4674. fsElement.mozRequestFullScreen();
  4675. }
  4676. else {
  4677. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  4678. }
  4679. } else {
  4680. //Exit Full Screen
  4681. if (document.mozCancelFullScreen) {
  4682. document.mozCancelFullScreen();
  4683. } else {
  4684. document.webkitCancelFullScreen();
  4685. }
  4686. }
  4687. };
  4688. /**
  4689. * Unlocks the lock button state.
  4690. */
  4691. my.unlockLockButton = function () {
  4692. if ($("#lockIcon").hasClass("icon-security-locked"))
  4693. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4694. };
  4695. /**
  4696. * Updates the lock button state to locked.
  4697. */
  4698. my.lockLockButton = function () {
  4699. if ($("#lockIcon").hasClass("icon-security"))
  4700. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4701. };
  4702. /**
  4703. * Shows or hides authentication button
  4704. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  4705. */
  4706. my.showAuthenticateButton = function (show) {
  4707. if (show) {
  4708. $('#authentication').css({display: "inline"});
  4709. }
  4710. else {
  4711. $('#authentication').css({display: "none"});
  4712. }
  4713. };
  4714. // Shows or hides the 'recording' button.
  4715. my.showRecordingButton = function (show) {
  4716. if (!config.enableRecording) {
  4717. return;
  4718. }
  4719. if (show) {
  4720. $('#recording').css({display: "inline"});
  4721. }
  4722. else {
  4723. $('#recording').css({display: "none"});
  4724. }
  4725. };
  4726. // Sets the state of the recording button
  4727. my.setRecordingButtonState = function (isRecording) {
  4728. if (isRecording) {
  4729. $('#recordButton').removeClass("icon-recEnable");
  4730. $('#recordButton').addClass("icon-recEnable active");
  4731. } else {
  4732. $('#recordButton').removeClass("icon-recEnable active");
  4733. $('#recordButton').addClass("icon-recEnable");
  4734. }
  4735. };
  4736. // Shows or hides SIP calls button
  4737. my.showSipCallButton = function (show) {
  4738. if (APP.xmpp.isSipGatewayEnabled() && show) {
  4739. $('#sipCallButton').css({display: "inline-block"});
  4740. } else {
  4741. $('#sipCallButton').css({display: "none"});
  4742. }
  4743. };
  4744. /**
  4745. * Displays user authenticated identity name(login).
  4746. * @param authIdentity identity name to be displayed.
  4747. */
  4748. my.setAuthenticatedIdentity = function (authIdentity) {
  4749. if (authIdentity) {
  4750. $('#toolbar_auth_identity').css({display: "list-item"});
  4751. $('#toolbar_auth_identity').text(authIdentity);
  4752. } else {
  4753. $('#toolbar_auth_identity').css({display: "none"});
  4754. }
  4755. };
  4756. /**
  4757. * Shows/hides login button.
  4758. * @param show <tt>true</tt> to show
  4759. */
  4760. my.showLoginButton = function (show) {
  4761. if (show) {
  4762. $('#toolbar_button_login').css({display: "list-item"});
  4763. } else {
  4764. $('#toolbar_button_login').css({display: "none"});
  4765. }
  4766. };
  4767. /**
  4768. * Shows/hides logout button.
  4769. * @param show <tt>true</tt> to show
  4770. */
  4771. my.showLogoutButton = function (show) {
  4772. if (show) {
  4773. $('#toolbar_button_logout').css({display: "list-item"});
  4774. } else {
  4775. $('#toolbar_button_logout').css({display: "none"});
  4776. }
  4777. };
  4778. /**
  4779. * Sets the state of the button. The button has blue glow if desktop
  4780. * streaming is active.
  4781. * @param active the state of the desktop streaming.
  4782. */
  4783. my.changeDesktopSharingButtonState = function (active) {
  4784. var button = $("#desktopsharing > a");
  4785. if (active)
  4786. {
  4787. button.addClass("glow");
  4788. }
  4789. else
  4790. {
  4791. button.removeClass("glow");
  4792. }
  4793. };
  4794. return my;
  4795. }(Toolbar || {}));
  4796. module.exports = Toolbar;
  4797. },{"../../../service/authentication/AuthenticationEvents":93,"../authentication/Authentication":11,"../etherpad/Etherpad":14,"../prezi/Prezi":15,"../side_pannels/SidePanelToggler":17,"../util/MessageHandler":28,"../util/UIUtil":30,"./BottomToolbar":24}],26:[function(require,module,exports){
  4798. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  4799. var toolbarTimeoutObject,
  4800. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  4801. function showDesktopSharingButton() {
  4802. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  4803. $('#desktopsharing').css({display: "inline"});
  4804. } else {
  4805. $('#desktopsharing').css({display: "none"});
  4806. }
  4807. }
  4808. /**
  4809. * Hides the toolbar.
  4810. */
  4811. function hideToolbar() {
  4812. var header = $("#header"),
  4813. bottomToolbar = $("#bottomToolbar");
  4814. var isToolbarHover = false;
  4815. header.find('*').each(function () {
  4816. var id = $(this).attr('id');
  4817. if ($("#" + id + ":hover").length > 0) {
  4818. isToolbarHover = true;
  4819. }
  4820. });
  4821. if ($("#bottomToolbar:hover").length > 0) {
  4822. isToolbarHover = true;
  4823. }
  4824. clearTimeout(toolbarTimeoutObject);
  4825. toolbarTimeoutObject = null;
  4826. if (!isToolbarHover) {
  4827. header.hide("slide", { direction: "up", duration: 300});
  4828. $('#subject').animate({top: "-=40"}, 300);
  4829. if ($("#remoteVideos").hasClass("hidden")) {
  4830. bottomToolbar.hide(
  4831. "slide", {direction: "right", duration: 300});
  4832. }
  4833. }
  4834. else {
  4835. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4836. }
  4837. }
  4838. var ToolbarToggler = {
  4839. /**
  4840. * Shows the main toolbar.
  4841. */
  4842. showToolbar: function () {
  4843. var header = $("#header"),
  4844. bottomToolbar = $("#bottomToolbar");
  4845. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  4846. header.show("slide", { direction: "up", duration: 300});
  4847. $('#subject').animate({top: "+=40"}, 300);
  4848. if (!bottomToolbar.is(":visible")) {
  4849. bottomToolbar.show(
  4850. "slide", {direction: "right", duration: 300});
  4851. }
  4852. if (toolbarTimeoutObject) {
  4853. clearTimeout(toolbarTimeoutObject);
  4854. toolbarTimeoutObject = null;
  4855. }
  4856. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4857. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  4858. }
  4859. if (APP.xmpp.isModerator())
  4860. {
  4861. // TODO: Enable settings functionality.
  4862. // Need to uncomment the settings button in index.html.
  4863. // $('#settingsButton').css({visibility:"visible"});
  4864. }
  4865. // Show/hide desktop sharing button
  4866. showDesktopSharingButton();
  4867. },
  4868. /**
  4869. * Docks/undocks the toolbar.
  4870. *
  4871. * @param isDock indicates what operation to perform
  4872. */
  4873. dockToolbar: function (isDock) {
  4874. if (isDock) {
  4875. // First make sure the toolbar is shown.
  4876. if (!$('#header').is(':visible')) {
  4877. this.showToolbar();
  4878. }
  4879. // Then clear the time out, to dock the toolbar.
  4880. if (toolbarTimeoutObject) {
  4881. clearTimeout(toolbarTimeoutObject);
  4882. toolbarTimeoutObject = null;
  4883. }
  4884. }
  4885. else {
  4886. if (!$('#header').is(':visible')) {
  4887. this.showToolbar();
  4888. }
  4889. else {
  4890. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4891. }
  4892. }
  4893. },
  4894. showDesktopSharingButton: showDesktopSharingButton
  4895. };
  4896. module.exports = ToolbarToggler;
  4897. },{}],27:[function(require,module,exports){
  4898. var JitsiPopover = (function () {
  4899. /**
  4900. * Constructs new JitsiPopover and attaches it to the element
  4901. * @param element jquery selector
  4902. * @param options the options for the popover.
  4903. * @constructor
  4904. */
  4905. function JitsiPopover(element, options)
  4906. {
  4907. this.options = {
  4908. skin: "white",
  4909. content: ""
  4910. };
  4911. if(options)
  4912. {
  4913. if(options.skin)
  4914. this.options.skin = options.skin;
  4915. if(options.content)
  4916. this.options.content = options.content;
  4917. }
  4918. this.elementIsHovered = false;
  4919. this.popoverIsHovered = false;
  4920. this.popoverShown = false;
  4921. element.data("jitsi_popover", this);
  4922. this.element = element;
  4923. this.template = ' <div class="jitsipopover ' + this.options.skin +
  4924. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  4925. '<div class="jitsiPopupmenuPadding"></div></div>';
  4926. var self = this;
  4927. this.element.on("mouseenter", function () {
  4928. self.elementIsHovered = true;
  4929. self.show();
  4930. }).on("mouseleave", function () {
  4931. self.elementIsHovered = false;
  4932. setTimeout(function () {
  4933. self.hide();
  4934. }, 10);
  4935. });
  4936. }
  4937. /**
  4938. * Shows the popover
  4939. */
  4940. JitsiPopover.prototype.show = function () {
  4941. this.createPopover();
  4942. this.popoverShown = true;
  4943. };
  4944. /**
  4945. * Hides the popover
  4946. */
  4947. JitsiPopover.prototype.hide = function () {
  4948. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  4949. {
  4950. this.forceHide();
  4951. }
  4952. };
  4953. /**
  4954. * Hides the popover
  4955. */
  4956. JitsiPopover.prototype.forceHide = function () {
  4957. $(".jitsipopover").remove();
  4958. this.popoverShown = false;
  4959. };
  4960. /**
  4961. * Creates the popover html
  4962. */
  4963. JitsiPopover.prototype.createPopover = function () {
  4964. $("body").append(this.template);
  4965. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  4966. var self = this;
  4967. $(".jitsipopover").on("mouseenter", function () {
  4968. self.popoverIsHovered = true;
  4969. }).on("mouseleave", function () {
  4970. self.popoverIsHovered = false;
  4971. self.hide();
  4972. });
  4973. this.refreshPosition();
  4974. };
  4975. /**
  4976. * Refreshes the position of the popover
  4977. */
  4978. JitsiPopover.prototype.refreshPosition = function () {
  4979. $(".jitsipopover").position({
  4980. my: "bottom",
  4981. at: "top",
  4982. collision: "fit",
  4983. of: this.element,
  4984. using: function (position, elements) {
  4985. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  4986. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  4987. $(".jitsipopover > .arrow").css({left: calcLeft});
  4988. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  4989. }
  4990. });
  4991. };
  4992. /**
  4993. * Updates the content of popover.
  4994. * @param content new content
  4995. */
  4996. JitsiPopover.prototype.updateContent = function (content) {
  4997. this.options.content = content;
  4998. if(!this.popoverShown)
  4999. return;
  5000. $(".jitsipopover").remove();
  5001. this.createPopover();
  5002. };
  5003. return JitsiPopover;
  5004. })();
  5005. module.exports = JitsiPopover;
  5006. },{}],28:[function(require,module,exports){
  5007. /* global $, APP, jQuery, toastr */
  5008. var messageHandler = (function(my) {
  5009. /**
  5010. * Shows a message to the user.
  5011. *
  5012. * @param titleString the title of the message
  5013. * @param messageString the text of the message
  5014. */
  5015. my.openMessageDialog = function(titleKey, messageKey) {
  5016. var title = null;
  5017. if(titleKey)
  5018. {
  5019. title = APP.translation.generateTranslatonHTML(titleKey);
  5020. }
  5021. var message = APP.translation.generateTranslatonHTML(messageKey);
  5022. $.prompt(message,
  5023. {
  5024. title: title,
  5025. persistent: false
  5026. }
  5027. );
  5028. };
  5029. /**
  5030. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5031. *
  5032. * @param titleString the title of the message
  5033. * @param msgString the text of the message
  5034. * @param persistent boolean value which determines whether the message is persistent or not
  5035. * @param leftButton the fist button's text
  5036. * @param submitFunction function to be called on submit
  5037. * @param loadedFunction function to be called after the prompt is fully loaded
  5038. * @param closeFunction function to be called after the prompt is closed
  5039. * @param focus optional focus selector or button index to be focused after
  5040. * the dialog is opened
  5041. * @param defaultButton index of default button which will be activated when
  5042. * the user press 'enter'. Indexed from 0.
  5043. */
  5044. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  5045. persistent, leftButtonKey, submitFunction, loadedFunction,
  5046. closeFunction, focus, defaultButton)
  5047. {
  5048. var buttons = [];
  5049. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  5050. buttons.push({ title: leftButton, value: true});
  5051. var cancelButton
  5052. = APP.translation.generateTranslatonHTML("dialog.Cancel");
  5053. buttons.push({title: cancelButton, value: false});
  5054. var message = msgString, title = titleString;
  5055. if (titleKey)
  5056. {
  5057. title = APP.translation.generateTranslatonHTML(titleKey);
  5058. }
  5059. if (msgKey) {
  5060. message = APP.translation.generateTranslatonHTML(msgKey);
  5061. }
  5062. $.prompt(message, {
  5063. title: title,
  5064. persistent: false,
  5065. buttons: buttons,
  5066. defaultButton: defaultButton,
  5067. focus: focus,
  5068. loaded: loadedFunction,
  5069. submit: submitFunction,
  5070. close: closeFunction
  5071. });
  5072. };
  5073. /**
  5074. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5075. *
  5076. * @param titleString the title of the message
  5077. * @param msgString the text of the message
  5078. * @param persistent boolean value which determines whether the message is persistent or not
  5079. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  5080. * that will be passed to submitFunction
  5081. * @param submitFunction function to be called on submit
  5082. * @param loadedFunction function to be called after the prompt is fully loaded
  5083. */
  5084. my.openDialog = function (titleString, msgString, persistent, buttons,
  5085. submitFunction, loadedFunction) {
  5086. var args = {
  5087. title: titleString,
  5088. persistent: persistent,
  5089. buttons: buttons,
  5090. defaultButton: 1,
  5091. loaded: loadedFunction,
  5092. submit: submitFunction
  5093. };
  5094. if (persistent) {
  5095. args.closeText = '';
  5096. }
  5097. return new Impromptu(msgString, args);
  5098. };
  5099. /**
  5100. * Closes currently opened dialog.
  5101. */
  5102. my.closeDialog = function () {
  5103. $.prompt.close();
  5104. };
  5105. /**
  5106. * Shows a dialog with different states to the user.
  5107. *
  5108. * @param statesObject object containing all the states of the dialog
  5109. */
  5110. my.openDialogWithStates = function (statesObject, options) {
  5111. return new Impromptu(statesObject, options);
  5112. };
  5113. /**
  5114. * Opens new popup window for given <tt>url</tt> centered over current
  5115. * window.
  5116. *
  5117. * @param url the URL to be displayed in the popup window
  5118. * @param w the width of the popup window
  5119. * @param h the height of the popup window
  5120. * @param onPopupClosed optional callback function called when popup window
  5121. * has been closed.
  5122. *
  5123. * @returns popup window object if opened successfully or undefined
  5124. * in case we failed to open it(popup blocked)
  5125. */
  5126. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  5127. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  5128. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  5129. var popup = window.open(
  5130. url, '_blank',
  5131. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  5132. if (popup && onPopupClosed) {
  5133. var pollTimer = window.setInterval(function () {
  5134. if (popup.closed !== false) {
  5135. window.clearInterval(pollTimer);
  5136. onPopupClosed();
  5137. }
  5138. }, 200);
  5139. }
  5140. return popup;
  5141. };
  5142. /**
  5143. * Shows a dialog prompting the user to send an error report.
  5144. *
  5145. * @param titleString the title of the message
  5146. * @param msgString the text of the message
  5147. * @param error the error that is being reported
  5148. */
  5149. my.openReportDialog = function(titleKey, msgKey, error) {
  5150. my.openMessageDialog(titleKey, msgKey);
  5151. console.log(error);
  5152. //FIXME send the error to the server
  5153. };
  5154. /**
  5155. * Shows an error dialog to the user.
  5156. * @param title the title of the message
  5157. * @param message the text of the messafe
  5158. */
  5159. my.showError = function(titleKey, msgKey) {
  5160. if(!titleKey) {
  5161. titleKey = "dialog.oops";
  5162. }
  5163. if(!msgKey)
  5164. {
  5165. msgKey = "dialog.defaultError";
  5166. }
  5167. messageHandler.openMessageDialog(titleKey, msgKey);
  5168. };
  5169. my.notify = function(displayName, displayNameKey,
  5170. cls, messageKey, messageArguments) {
  5171. var displayNameSpan = '<span class="nickname" ';
  5172. if(displayName)
  5173. {
  5174. displayNameSpan += ">" + displayName;
  5175. }
  5176. else
  5177. {
  5178. displayNameSpan += "data-i18n='" + displayNameKey +
  5179. "'>" + APP.translation.translateString(displayNameKey);
  5180. }
  5181. displayNameSpan += "</span>";
  5182. toastr.info(
  5183. displayNameSpan + '<br>' +
  5184. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  5185. (messageArguments?
  5186. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  5187. : "") + ">" +
  5188. APP.translation.translateString(messageKey,
  5189. messageArguments) +
  5190. '</span>');
  5191. };
  5192. return my;
  5193. }(messageHandler || {}));
  5194. module.exports = messageHandler;
  5195. },{}],29:[function(require,module,exports){
  5196. var UIEvents = require("../../../service/UI/UIEvents");
  5197. var nickname = null;
  5198. var eventEmitter = null;
  5199. var NickanameHandler = {
  5200. init: function (emitter) {
  5201. eventEmitter = emitter;
  5202. var storedDisplayName = window.localStorage.displayname;
  5203. if (storedDisplayName) {
  5204. nickname = storedDisplayName;
  5205. }
  5206. },
  5207. setNickname: function (newNickname) {
  5208. if (!newNickname || nickname === newNickname)
  5209. return;
  5210. nickname = newNickname;
  5211. window.localStorage.displayname = nickname;
  5212. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  5213. },
  5214. getNickname: function () {
  5215. return nickname;
  5216. },
  5217. addListener: function (type, listener) {
  5218. eventEmitter.on(type, listener);
  5219. }
  5220. };
  5221. module.exports = NickanameHandler;
  5222. },{"../../../service/UI/UIEvents":92}],30:[function(require,module,exports){
  5223. /**
  5224. * Created by hristo on 12/22/14.
  5225. */
  5226. module.exports = {
  5227. /**
  5228. * Returns the available video width.
  5229. */
  5230. getAvailableVideoWidth: function () {
  5231. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5232. var rightPanelWidth
  5233. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5234. return window.innerWidth - rightPanelWidth;
  5235. },
  5236. /**
  5237. * Changes the style class of the element given by id.
  5238. */
  5239. buttonClick: function(id, classname) {
  5240. $(id).toggleClass(classname); // add the class to the clicked element
  5241. },
  5242. /**
  5243. * Returns the text width for the given element.
  5244. *
  5245. * @param el the element
  5246. */
  5247. getTextWidth: function (el) {
  5248. return (el.clientWidth + 1);
  5249. },
  5250. /**
  5251. * Returns the text height for the given element.
  5252. *
  5253. * @param el the element
  5254. */
  5255. getTextHeight: function (el) {
  5256. return (el.clientHeight + 1);
  5257. },
  5258. /**
  5259. * Plays the sound given by id.
  5260. *
  5261. * @param id the identifier of the audio element.
  5262. */
  5263. playSoundNotification: function (id) {
  5264. document.getElementById(id).play();
  5265. },
  5266. /**
  5267. * Escapes the given text.
  5268. */
  5269. escapeHtml: function (unsafeText) {
  5270. return $('<div/>').text(unsafeText).html();
  5271. },
  5272. imageToGrayScale: function (canvas) {
  5273. var context = canvas.getContext('2d');
  5274. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5275. var pixels = imgData.data;
  5276. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5277. var grayscale
  5278. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5279. pixels[i ] = grayscale; // red
  5280. pixels[i+1] = grayscale; // green
  5281. pixels[i+2] = grayscale; // blue
  5282. // pixels[i+3] is alpha
  5283. }
  5284. // redraw the image in black & white
  5285. context.putImageData(imgData, 0, 0);
  5286. },
  5287. setTooltip: function (element, key, position) {
  5288. element.setAttribute("data-i18n", "[data-content]" + key);
  5289. element.setAttribute("data-toggle", "popover");
  5290. element.setAttribute("data-placement", position);
  5291. element.setAttribute("data-html", true);
  5292. element.setAttribute("data-container", "body");
  5293. }
  5294. };
  5295. },{"../side_pannels/SidePanelToggler":17}],31:[function(require,module,exports){
  5296. var JitsiPopover = require("../util/JitsiPopover");
  5297. /**
  5298. * Constructs new connection indicator.
  5299. * @param videoContainer the video container associated with the indicator.
  5300. * @constructor
  5301. */
  5302. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5303. {
  5304. this.videoContainer = videoContainer;
  5305. this.bandwidth = null;
  5306. this.packetLoss = null;
  5307. this.bitrate = null;
  5308. this.showMoreValue = false;
  5309. this.resolution = null;
  5310. this.transport = [];
  5311. this.popover = null;
  5312. this.jid = jid;
  5313. this.create();
  5314. this.videoLayout = VideoLayout;
  5315. }
  5316. /**
  5317. * Values for the connection quality
  5318. * @type {{98: string,
  5319. * 81: string,
  5320. * 64: string,
  5321. * 47: string,
  5322. * 30: string,
  5323. * 0: string}}
  5324. */
  5325. ConnectionIndicator.connectionQualityValues = {
  5326. 98: "18px", //full
  5327. 81: "15px",//4 bars
  5328. 64: "11px",//3 bars
  5329. 47: "7px",//2 bars
  5330. 30: "3px",//1 bar
  5331. 0: "0px"//empty
  5332. };
  5333. ConnectionIndicator.getIP = function(value)
  5334. {
  5335. return value.substring(0, value.lastIndexOf(":"));
  5336. };
  5337. ConnectionIndicator.getPort = function(value)
  5338. {
  5339. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5340. };
  5341. ConnectionIndicator.getStringFromArray = function (array) {
  5342. var res = "";
  5343. for(var i = 0; i < array.length; i++)
  5344. {
  5345. res += (i === 0? "" : ", ") + array[i];
  5346. }
  5347. return res;
  5348. };
  5349. /**
  5350. * Generates the html content.
  5351. * @returns {string} the html content.
  5352. */
  5353. ConnectionIndicator.prototype.generateText = function () {
  5354. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5355. var translate = APP.translation.translateString;
  5356. if(this.bitrate === null)
  5357. {
  5358. downloadBitrate = "N/A";
  5359. uploadBitrate = "N/A";
  5360. }
  5361. else
  5362. {
  5363. downloadBitrate =
  5364. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5365. uploadBitrate =
  5366. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5367. }
  5368. if(this.packetLoss === null)
  5369. {
  5370. packetLoss = "N/A";
  5371. }
  5372. else
  5373. {
  5374. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5375. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5376. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5377. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5378. }
  5379. var resolutionValue = null;
  5380. if(this.resolution && this.jid != null)
  5381. {
  5382. var keys = Object.keys(this.resolution);
  5383. if(keys.length == 1)
  5384. {
  5385. for(var ssrc in this.resolution)
  5386. {
  5387. resolutionValue = this.resolution[ssrc];
  5388. }
  5389. }
  5390. else if(keys.length > 1)
  5391. {
  5392. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  5393. resolutionValue = this.resolution[displayedSsrc];
  5394. }
  5395. }
  5396. if(this.jid === null)
  5397. {
  5398. resolution = "";
  5399. if(this.resolution === null || !Object.keys(this.resolution) ||
  5400. Object.keys(this.resolution).length === 0)
  5401. {
  5402. resolution = "N/A";
  5403. }
  5404. else
  5405. for(i in this.resolution)
  5406. {
  5407. resolutionValue = this.resolution[i];
  5408. if(resolutionValue)
  5409. {
  5410. if(resolutionValue.height &&
  5411. resolutionValue.width)
  5412. {
  5413. resolution += (resolution === ""? "" : ", ") +
  5414. resolutionValue.width + "x" +
  5415. resolutionValue.height;
  5416. }
  5417. }
  5418. }
  5419. }
  5420. else if(!resolutionValue ||
  5421. !resolutionValue.height ||
  5422. !resolutionValue.width)
  5423. {
  5424. resolution = "N/A";
  5425. }
  5426. else
  5427. {
  5428. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5429. }
  5430. var result = "<table style='width:100%'>" +
  5431. "<tr>" +
  5432. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5433. translate("connectionindicator.bitrate") + "</span></td>" +
  5434. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5435. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5436. uploadBitrate + "</td>" +
  5437. "</tr><tr>" +
  5438. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5439. translate("connectionindicator.packetloss") + "</span></td>" +
  5440. "<td>" + packetLoss + "</td>" +
  5441. "</tr><tr>" +
  5442. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5443. translate("connectionindicator.resolution") + "</span></td>" +
  5444. "<td>" + resolution + "</td></tr></table>";
  5445. if(this.videoContainer.id == "localVideoContainer") {
  5446. result += "<div class=\"jitsipopover_showmore\" " +
  5447. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5448. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5449. (this.showMoreValue ? "less" : "more") + "'>" +
  5450. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5451. "</div><br />";
  5452. }
  5453. if(this.showMoreValue)
  5454. {
  5455. var downloadBandwidth, uploadBandwidth, transport;
  5456. if(this.bandwidth === null)
  5457. {
  5458. downloadBandwidth = "N/A";
  5459. uploadBandwidth = "N/A";
  5460. }
  5461. else
  5462. {
  5463. downloadBandwidth = this.bandwidth.download?
  5464. this.bandwidth.download + " Kbps" :
  5465. "N/A";
  5466. uploadBandwidth = this.bandwidth.upload?
  5467. this.bandwidth.upload + " Kbps" :
  5468. "N/A";
  5469. }
  5470. if(!this.transport || this.transport.length === 0)
  5471. {
  5472. transport = "<tr>" +
  5473. "<td><span class='jitsipopover_blue' " +
  5474. "data-i18n='connectionindicator.address'>" +
  5475. translate("connectionindicator.address") + "</span></td>" +
  5476. "<td> N/A</td></tr>";
  5477. }
  5478. else
  5479. {
  5480. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5481. for(i = 0; i < this.transport.length; i++)
  5482. {
  5483. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5484. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5485. var localIP =
  5486. ConnectionIndicator.getIP(this.transport[i].localip);
  5487. var localPort =
  5488. ConnectionIndicator.getPort(this.transport[i].localip);
  5489. if(data.remoteIP.indexOf(ip) == -1)
  5490. {
  5491. data.remoteIP.push(ip);
  5492. }
  5493. if(data.remotePort.indexOf(port) == -1)
  5494. {
  5495. data.remotePort.push(port);
  5496. }
  5497. if(data.localIP.indexOf(localIP) == -1)
  5498. {
  5499. data.localIP.push(localIP);
  5500. }
  5501. if(data.localPort.indexOf(localPort) == -1)
  5502. {
  5503. data.localPort.push(localPort);
  5504. }
  5505. }
  5506. var local_address_key = "connectionindicator.localaddress";
  5507. var remote_address_key = "connectionindicator.remoteaddress";
  5508. var localTransport =
  5509. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5510. local_address_key +"' data-i18n-options='" +
  5511. JSON.stringify({count: data.localIP.length}) + "'>" +
  5512. translate(local_address_key, {count: data.localIP.length}) +
  5513. "</span></td><td> " +
  5514. ConnectionIndicator.getStringFromArray(data.localIP) +
  5515. "</td></tr>";
  5516. transport =
  5517. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5518. remote_address_key + "' data-i18n-options='" +
  5519. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  5520. translate(remote_address_key,
  5521. {count: data.remoteIP.length}) +
  5522. "</span></td><td> " +
  5523. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5524. "</td></tr>";
  5525. var key_remote = "connectionindicator.remoteport",
  5526. key_local = "connectionindicator.localport";
  5527. transport += "<tr>" +
  5528. "<td>" +
  5529. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5530. "' data-i18n-options='" +
  5531. JSON.stringify({count: this.transport.length}) + "'>" +
  5532. translate(key_remote, {count: this.transport.length}) +
  5533. "</span></td><td>";
  5534. localTransport += "<tr>" +
  5535. "<td>" +
  5536. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5537. "' data-i18n-options='" +
  5538. JSON.stringify({count: this.transport.length}) + "'>" +
  5539. translate(key_local, {count: this.transport.length}) +
  5540. "</span></td><td>";
  5541. transport +=
  5542. ConnectionIndicator.getStringFromArray(data.remotePort);
  5543. localTransport +=
  5544. ConnectionIndicator.getStringFromArray(data.localPort);
  5545. transport += "</td></tr>";
  5546. transport += localTransport + "</td></tr>";
  5547. transport +="<tr>" +
  5548. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5549. translate("connectionindicator.transport") + "</span></td>" +
  5550. "<td>" + this.transport[0].type + "</td></tr>";
  5551. }
  5552. result += "<table style='width:100%'>" +
  5553. "<tr>" +
  5554. "<td>" +
  5555. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5556. translate("connectionindicator.bandwidth") + "</span>" +
  5557. "</td><td>" +
  5558. "<span class='jitsipopover_green'>&darr;</span>" +
  5559. downloadBandwidth +
  5560. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5561. uploadBandwidth + "</td></tr>";
  5562. result += transport + "</table>";
  5563. }
  5564. return result;
  5565. };
  5566. /**
  5567. * Shows or hide the additional information.
  5568. */
  5569. ConnectionIndicator.prototype.showMore = function () {
  5570. this.showMoreValue = !this.showMoreValue;
  5571. this.updatePopoverData();
  5572. };
  5573. function createIcon(classes)
  5574. {
  5575. var icon = document.createElement("span");
  5576. for(var i in classes)
  5577. {
  5578. icon.classList.add(classes[i]);
  5579. }
  5580. icon.appendChild(
  5581. document.createElement("i")).classList.add("icon-connection");
  5582. return icon;
  5583. }
  5584. /**
  5585. * Creates the indicator
  5586. */
  5587. ConnectionIndicator.prototype.create = function () {
  5588. this.connectionIndicatorContainer = document.createElement("div");
  5589. this.connectionIndicatorContainer.className = "connectionindicator";
  5590. this.connectionIndicatorContainer.style.display = "none";
  5591. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5592. this.popover = new JitsiPopover(
  5593. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5594. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5595. APP.translation.translateString("connectionindicator.na") + "</div>",
  5596. skin: "black"});
  5597. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5598. createIcon(["connection", "connection_empty"]));
  5599. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5600. createIcon(["connection", "connection_full"]));
  5601. };
  5602. /**
  5603. * Removes the indicator
  5604. */
  5605. ConnectionIndicator.prototype.remove = function()
  5606. {
  5607. this.connectionIndicatorContainer.remove();
  5608. this.popover.forceHide();
  5609. };
  5610. /**
  5611. * Updates the data of the indicator
  5612. * @param percent the percent of connection quality
  5613. * @param object the statistics data.
  5614. */
  5615. ConnectionIndicator.prototype.updateConnectionQuality =
  5616. function (percent, object) {
  5617. if(percent === null)
  5618. {
  5619. this.connectionIndicatorContainer.style.display = "none";
  5620. this.popover.forceHide();
  5621. return;
  5622. }
  5623. else
  5624. {
  5625. if(this.connectionIndicatorContainer.style.display == "none") {
  5626. this.connectionIndicatorContainer.style.display = "block";
  5627. this.videoLayout.updateMutePosition(this.videoContainer.id);
  5628. }
  5629. }
  5630. this.bandwidth = object.bandwidth;
  5631. this.bitrate = object.bitrate;
  5632. this.packetLoss = object.packetLoss;
  5633. this.transport = object.transport;
  5634. if(object.resolution)
  5635. {
  5636. this.resolution = object.resolution;
  5637. }
  5638. for(var quality in ConnectionIndicator.connectionQualityValues)
  5639. {
  5640. if(percent >= quality)
  5641. {
  5642. this.fullIcon.style.width =
  5643. ConnectionIndicator.connectionQualityValues[quality];
  5644. }
  5645. }
  5646. this.updatePopoverData();
  5647. };
  5648. /**
  5649. * Updates the resolution
  5650. * @param resolution the new resolution
  5651. */
  5652. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  5653. this.resolution = resolution;
  5654. this.updatePopoverData();
  5655. };
  5656. /**
  5657. * Updates the content of the popover
  5658. */
  5659. ConnectionIndicator.prototype.updatePopoverData = function () {
  5660. this.popover.updateContent(
  5661. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  5662. APP.translation.translateElement($(".connection_info"));
  5663. };
  5664. /**
  5665. * Hides the popover
  5666. */
  5667. ConnectionIndicator.prototype.hide = function () {
  5668. this.popover.forceHide();
  5669. };
  5670. /**
  5671. * Hides the indicator
  5672. */
  5673. ConnectionIndicator.prototype.hideIndicator = function () {
  5674. this.connectionIndicatorContainer.style.display = "none";
  5675. if(this.popover)
  5676. this.popover.forceHide();
  5677. };
  5678. module.exports = ConnectionIndicator;
  5679. },{"../util/JitsiPopover":27}],32:[function(require,module,exports){
  5680. var AudioLevels = require("../audio_levels/AudioLevels");
  5681. var Avatar = require("../avatar/Avatar");
  5682. var Chat = require("../side_pannels/chat/Chat");
  5683. var ContactList = require("../side_pannels/contactlist/ContactList");
  5684. var UIUtil = require("../util/UIUtil");
  5685. var ConnectionIndicator = require("./ConnectionIndicator");
  5686. var NicknameHandler = require("../util/NicknameHandler");
  5687. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  5688. var UIEvents = require("../../../service/UI/UIEvents");
  5689. var currentDominantSpeaker = null;
  5690. var lastNCount = config.channelLastN;
  5691. var localLastNCount = config.channelLastN;
  5692. var localLastNSet = [];
  5693. var lastNEndpointsCache = [];
  5694. var lastNPickupJid = null;
  5695. var largeVideoState = {
  5696. updateInProgress: false,
  5697. newSrc: ''
  5698. };
  5699. var eventEmitter = null;
  5700. /**
  5701. * Currently focused video "src"(displayed in large video).
  5702. * @type {String}
  5703. */
  5704. var focusedVideoInfo = null;
  5705. /**
  5706. * Indicates if we have muted our audio before the conference has started.
  5707. * @type {boolean}
  5708. */
  5709. var preMuted = false;
  5710. var mutedAudios = {};
  5711. var flipXLocalVideo = true;
  5712. var currentVideoWidth = null;
  5713. var currentVideoHeight = null;
  5714. var localVideoSrc = null;
  5715. function videoactive( videoelem) {
  5716. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  5717. // ignore mixedmslabela0 and v0
  5718. videoelem.show();
  5719. VideoLayout.resizeThumbnails();
  5720. var videoParent = videoelem.parent();
  5721. var parentResourceJid = null;
  5722. if (videoParent)
  5723. parentResourceJid
  5724. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  5725. // Update the large video to the last added video only if there's no
  5726. // current dominant, focused speaker or prezi playing or update it to
  5727. // the current dominant speaker.
  5728. if ((!focusedVideoInfo &&
  5729. !VideoLayout.getDominantSpeakerResourceJid() &&
  5730. !require("../prezi/Prezi").isPresentationVisible()) ||
  5731. (parentResourceJid &&
  5732. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  5733. VideoLayout.updateLargeVideo(
  5734. APP.RTC.getVideoSrc(videoelem[0]),
  5735. 1,
  5736. parentResourceJid);
  5737. }
  5738. VideoLayout.showModeratorIndicator();
  5739. }
  5740. }
  5741. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  5742. // XXX(gp) so, every call to this function is *always* preceded by a call
  5743. // to the RTC.attachMediaStream() function but that call is *not* followed
  5744. // by an update to the videoSrcToSsrc map!
  5745. //
  5746. // The above way of doing things results in video SRCs that don't correspond
  5747. // to any SSRC for a short period of time (to be more precise, for as long
  5748. // the waitForRemoteVideo takes to complete). This causes problems (see
  5749. // bellow).
  5750. //
  5751. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  5752. // a second time in here and only then update the videoSrcToSsrc map? Why
  5753. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  5754. // is called the first time? I actually do that in the lastN changed event
  5755. // handler because the "orphan" video SRC is causing troubles there. The
  5756. // purpose of this method would then be to fire the "videoactive.jingle".
  5757. //
  5758. // Food for though I guess :-)
  5759. if (selector.removed || !selector.parent().is(":visible")) {
  5760. console.warn("Media removed before had started", selector);
  5761. return;
  5762. }
  5763. if (stream.id === 'mixedmslabel') return;
  5764. if (selector[0].currentTime > 0) {
  5765. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  5766. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  5767. videoactive(selector);
  5768. } else {
  5769. setTimeout(function () {
  5770. waitForRemoteVideo(selector, ssrc, stream, jid);
  5771. }, 250);
  5772. }
  5773. }
  5774. /**
  5775. * Returns an array of the video horizontal and vertical indents,
  5776. * so that if fits its parent.
  5777. *
  5778. * @return an array with 2 elements, the horizontal indent and the vertical
  5779. * indent
  5780. */
  5781. function getCameraVideoPosition(videoWidth,
  5782. videoHeight,
  5783. videoSpaceWidth,
  5784. videoSpaceHeight) {
  5785. // Parent height isn't completely calculated when we position the video in
  5786. // full screen mode and this is why we use the screen height in this case.
  5787. // Need to think it further at some point and implement it properly.
  5788. var isFullScreen = document.fullScreen ||
  5789. document.mozFullScreen ||
  5790. document.webkitIsFullScreen;
  5791. if (isFullScreen)
  5792. videoSpaceHeight = window.innerHeight;
  5793. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5794. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  5795. return [horizontalIndent, verticalIndent];
  5796. }
  5797. /**
  5798. * Returns an array of the video horizontal and vertical indents.
  5799. * Centers horizontally and top aligns vertically.
  5800. *
  5801. * @return an array with 2 elements, the horizontal indent and the vertical
  5802. * indent
  5803. */
  5804. function getDesktopVideoPosition(videoWidth,
  5805. videoHeight,
  5806. videoSpaceWidth,
  5807. videoSpaceHeight) {
  5808. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5809. var verticalIndent = 0;// Top aligned
  5810. return [horizontalIndent, verticalIndent];
  5811. }
  5812. /**
  5813. * Returns an array of the video dimensions, so that it covers the screen.
  5814. * It leaves no empty areas, but some parts of the video might not be visible.
  5815. *
  5816. * @return an array with 2 elements, the video width and the video height
  5817. */
  5818. function getCameraVideoSize(videoWidth,
  5819. videoHeight,
  5820. videoSpaceWidth,
  5821. videoSpaceHeight) {
  5822. if (!videoWidth)
  5823. videoWidth = currentVideoWidth;
  5824. if (!videoHeight)
  5825. videoHeight = currentVideoHeight;
  5826. var aspectRatio = videoWidth / videoHeight;
  5827. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5828. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5829. if (availableWidth / aspectRatio < videoSpaceHeight) {
  5830. availableHeight = videoSpaceHeight;
  5831. availableWidth = availableHeight * aspectRatio;
  5832. }
  5833. if (availableHeight * aspectRatio < videoSpaceWidth) {
  5834. availableWidth = videoSpaceWidth;
  5835. availableHeight = availableWidth / aspectRatio;
  5836. }
  5837. return [availableWidth, availableHeight];
  5838. }
  5839. /**
  5840. * Sets the display name for the given video span id.
  5841. */
  5842. function setDisplayName(videoSpanId, displayName, key) {
  5843. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  5844. var defaultLocalDisplayName = APP.translation.generateTranslatonHTML(
  5845. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  5846. // If we already have a display name for this video.
  5847. if (nameSpan.length > 0) {
  5848. var nameSpanElement = nameSpan.get(0);
  5849. if (nameSpanElement.id === 'localDisplayName' &&
  5850. $('#localDisplayName').text() !== displayName) {
  5851. if (displayName && displayName.length > 0)
  5852. {
  5853. var meHTML = APP.translation.generateTranslatonHTML("me");
  5854. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  5855. }
  5856. else
  5857. $('#localDisplayName').html(defaultLocalDisplayName);
  5858. } else {
  5859. if (displayName && displayName.length > 0)
  5860. {
  5861. $('#' + videoSpanId + '_name').html(displayName);
  5862. }
  5863. else if (key && key.length > 0)
  5864. {
  5865. var nameHtml = APP.translation.generateTranslatonHTML(key);
  5866. $('#' + videoSpanId + '_name').html(nameHtml);
  5867. }
  5868. else
  5869. $('#' + videoSpanId + '_name').text(
  5870. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  5871. }
  5872. } else {
  5873. var editButton = null;
  5874. nameSpan = document.createElement('span');
  5875. nameSpan.className = 'displayname';
  5876. $('#' + videoSpanId)[0].appendChild(nameSpan);
  5877. if (videoSpanId === 'localVideoContainer') {
  5878. editButton = createEditDisplayNameButton();
  5879. if (displayName && displayName.length > 0) {
  5880. var meHTML = APP.translation.generateTranslatonHTML("me");
  5881. nameSpan.innerHTML = displayName + meHTML;
  5882. }
  5883. else
  5884. nameSpan.innerHTML = defaultLocalDisplayName;
  5885. }
  5886. else {
  5887. if (displayName && displayName.length > 0) {
  5888. nameSpan.innerText = displayName;
  5889. }
  5890. else
  5891. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  5892. }
  5893. if (!editButton) {
  5894. nameSpan.id = videoSpanId + '_name';
  5895. } else {
  5896. nameSpan.id = 'localDisplayName';
  5897. $('#' + videoSpanId)[0].appendChild(editButton);
  5898. //translates popover of edit button
  5899. APP.translation.translateElement($("a.displayname"));
  5900. var editableText = document.createElement('input');
  5901. editableText.className = 'displayname';
  5902. editableText.type = 'text';
  5903. editableText.id = 'editDisplayName';
  5904. if (displayName && displayName.length) {
  5905. editableText.value
  5906. = displayName;
  5907. }
  5908. var defaultNickname = APP.translation.translateString(
  5909. "defaultNickname", {name: "Jane Pink"});
  5910. editableText.setAttribute('style', 'display:none;');
  5911. editableText.setAttribute('data-18n',
  5912. '[placeholder]defaultNickname');
  5913. editableText.setAttribute("data-i18n-options",
  5914. JSON.stringify({name: "Jane Pink"}));
  5915. editableText.setAttribute("placeholder", defaultNickname);
  5916. $('#' + videoSpanId)[0].appendChild(editableText);
  5917. $('#localVideoContainer .displayname')
  5918. .bind("click", function (e) {
  5919. e.preventDefault();
  5920. e.stopPropagation();
  5921. $('#localDisplayName').hide();
  5922. $('#editDisplayName').show();
  5923. $('#editDisplayName').focus();
  5924. $('#editDisplayName').select();
  5925. $('#editDisplayName').one("focusout", function (e) {
  5926. VideoLayout.inputDisplayNameHandler(this.value);
  5927. });
  5928. $('#editDisplayName').on('keydown', function (e) {
  5929. if (e.keyCode === 13) {
  5930. e.preventDefault();
  5931. VideoLayout.inputDisplayNameHandler(this.value);
  5932. }
  5933. });
  5934. });
  5935. }
  5936. }
  5937. }
  5938. /**
  5939. * Gets the selector of video thumbnail container for the user identified by
  5940. * given <tt>userJid</tt>
  5941. * @param resourceJid user's Jid for whom we want to get the video container.
  5942. */
  5943. function getParticipantContainer(resourceJid)
  5944. {
  5945. if (!resourceJid)
  5946. return null;
  5947. if (resourceJid === APP.xmpp.myResource())
  5948. return $("#localVideoContainer");
  5949. else
  5950. return $("#participant_" + resourceJid);
  5951. }
  5952. /**
  5953. * Sets the size and position of the given video element.
  5954. *
  5955. * @param video the video element to position
  5956. * @param width the desired video width
  5957. * @param height the desired video height
  5958. * @param horizontalIndent the left and right indent
  5959. * @param verticalIndent the top and bottom indent
  5960. */
  5961. function positionVideo(video,
  5962. width,
  5963. height,
  5964. horizontalIndent,
  5965. verticalIndent) {
  5966. video.width(width);
  5967. video.height(height);
  5968. video.css({ top: verticalIndent + 'px',
  5969. bottom: verticalIndent + 'px',
  5970. left: horizontalIndent + 'px',
  5971. right: horizontalIndent + 'px'});
  5972. }
  5973. /**
  5974. * Adds the remote video menu element for the given <tt>jid</tt> in the
  5975. * given <tt>parentElement</tt>.
  5976. *
  5977. * @param jid the jid indicating the video for which we're adding a menu.
  5978. * @param parentElement the parent element where this menu will be added
  5979. */
  5980. function addRemoteVideoMenu(jid, parentElement) {
  5981. var spanElement = document.createElement('span');
  5982. spanElement.className = 'remotevideomenu';
  5983. parentElement.appendChild(spanElement);
  5984. var menuElement = document.createElement('i');
  5985. menuElement.className = 'fa fa-angle-down';
  5986. menuElement.title = 'Remote user controls';
  5987. spanElement.appendChild(menuElement);
  5988. // <ul class="popupmenu">
  5989. // <li><a href="#">Mute</a></li>
  5990. // <li><a href="#">Eject</a></li>
  5991. // </ul>
  5992. var popupmenuElement = document.createElement('ul');
  5993. popupmenuElement.className = 'popupmenu';
  5994. popupmenuElement.id
  5995. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  5996. spanElement.appendChild(popupmenuElement);
  5997. var muteMenuItem = document.createElement('li');
  5998. var muteLinkItem = document.createElement('a');
  5999. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  6000. if (!mutedAudios[jid]) {
  6001. muteLinkItem.innerHTML = mutedIndicator +
  6002. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6003. muteLinkItem.className = 'mutelink';
  6004. }
  6005. else {
  6006. muteLinkItem.innerHTML = mutedIndicator +
  6007. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6008. muteLinkItem.className = 'mutelink disabled';
  6009. }
  6010. muteLinkItem.onclick = function(){
  6011. if ($(this).attr('disabled') != undefined) {
  6012. event.preventDefault();
  6013. }
  6014. var isMute = mutedAudios[jid] == true;
  6015. APP.xmpp.setMute(jid, !isMute);
  6016. popupmenuElement.setAttribute('style', 'display:none;');
  6017. if (isMute) {
  6018. this.innerHTML = mutedIndicator +
  6019. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6020. this.className = 'mutelink disabled';
  6021. }
  6022. else {
  6023. this.innerHTML = mutedIndicator +
  6024. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6025. this.className = 'mutelink';
  6026. }
  6027. };
  6028. muteMenuItem.appendChild(muteLinkItem);
  6029. popupmenuElement.appendChild(muteMenuItem);
  6030. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  6031. var ejectMenuItem = document.createElement('li');
  6032. var ejectLinkItem = document.createElement('a');
  6033. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  6034. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  6035. ejectLinkItem.onclick = function(){
  6036. APP.xmpp.eject(jid);
  6037. popupmenuElement.setAttribute('style', 'display:none;');
  6038. };
  6039. ejectMenuItem.appendChild(ejectLinkItem);
  6040. popupmenuElement.appendChild(ejectMenuItem);
  6041. var paddingSpan = document.createElement('span');
  6042. paddingSpan.className = 'popupmenuPadding';
  6043. popupmenuElement.appendChild(paddingSpan);
  6044. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  6045. }
  6046. /**
  6047. * Removes remote video menu element from video element identified by
  6048. * given <tt>videoElementId</tt>.
  6049. *
  6050. * @param videoElementId the id of local or remote video element.
  6051. */
  6052. function removeRemoteVideoMenu(videoElementId) {
  6053. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  6054. if (menuSpan.length) {
  6055. menuSpan.remove();
  6056. }
  6057. }
  6058. /**
  6059. * Updates the data for the indicator
  6060. * @param id the id of the indicator
  6061. * @param percent the percent for connection quality
  6062. * @param object the data
  6063. */
  6064. function updateStatsIndicator(id, percent, object) {
  6065. if(VideoLayout.connectionIndicators[id])
  6066. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  6067. }
  6068. /**
  6069. * Returns an array of the video dimensions, so that it keeps it's aspect
  6070. * ratio and fits available area with it's larger dimension. This method
  6071. * ensures that whole video will be visible and can leave empty areas.
  6072. *
  6073. * @return an array with 2 elements, the video width and the video height
  6074. */
  6075. function getDesktopVideoSize(videoWidth,
  6076. videoHeight,
  6077. videoSpaceWidth,
  6078. videoSpaceHeight) {
  6079. if (!videoWidth)
  6080. videoWidth = currentVideoWidth;
  6081. if (!videoHeight)
  6082. videoHeight = currentVideoHeight;
  6083. var aspectRatio = videoWidth / videoHeight;
  6084. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6085. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6086. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  6087. if (availableWidth / aspectRatio >= videoSpaceHeight)
  6088. {
  6089. availableHeight = videoSpaceHeight;
  6090. availableWidth = availableHeight * aspectRatio;
  6091. }
  6092. if (availableHeight * aspectRatio >= videoSpaceWidth)
  6093. {
  6094. availableWidth = videoSpaceWidth;
  6095. availableHeight = availableWidth / aspectRatio;
  6096. }
  6097. return [availableWidth, availableHeight];
  6098. }
  6099. /**
  6100. * Creates the edit display name button.
  6101. *
  6102. * @returns the edit button
  6103. */
  6104. function createEditDisplayNameButton() {
  6105. var editButton = document.createElement('a');
  6106. editButton.className = 'displayname';
  6107. UIUtil.setTooltip(editButton,
  6108. "videothumbnail.editnickname",
  6109. "top");
  6110. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  6111. return editButton;
  6112. }
  6113. /**
  6114. * Creates the element indicating the moderator(owner) of the conference.
  6115. *
  6116. * @param parentElement the parent element where the owner indicator will
  6117. * be added
  6118. */
  6119. function createModeratorIndicatorElement(parentElement) {
  6120. var moderatorIndicator = document.createElement('i');
  6121. moderatorIndicator.className = 'fa fa-star';
  6122. parentElement.appendChild(moderatorIndicator);
  6123. UIUtil.setTooltip(parentElement,
  6124. "videothumbnail.moderator",
  6125. "top");
  6126. }
  6127. var VideoLayout = (function (my) {
  6128. my.connectionIndicators = {};
  6129. // By default we use camera
  6130. my.getVideoSize = getCameraVideoSize;
  6131. my.getVideoPosition = getCameraVideoPosition;
  6132. my.init = function (emitter) {
  6133. // Listen for large video size updates
  6134. document.getElementById('largeVideo')
  6135. .addEventListener('loadedmetadata', function (e) {
  6136. currentVideoWidth = this.videoWidth;
  6137. currentVideoHeight = this.videoHeight;
  6138. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6139. });
  6140. eventEmitter = emitter;
  6141. };
  6142. my.isInLastN = function(resource) {
  6143. return lastNCount < 0 // lastN is disabled, return true
  6144. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  6145. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  6146. };
  6147. my.changeLocalStream = function (stream) {
  6148. VideoLayout.changeLocalVideo(stream);
  6149. };
  6150. my.changeLocalAudio = function(stream) {
  6151. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  6152. document.getElementById('localAudio').autoplay = true;
  6153. document.getElementById('localAudio').volume = 0;
  6154. if (preMuted) {
  6155. if(!APP.UI.setAudioMuted(true))
  6156. {
  6157. preMuted = mute;
  6158. }
  6159. preMuted = false;
  6160. }
  6161. };
  6162. my.changeLocalVideo = function(stream) {
  6163. var flipX = true;
  6164. if(stream.videoType == "screen")
  6165. flipX = false;
  6166. var localVideo = document.createElement('video');
  6167. localVideo.id = 'localVideo_' +
  6168. APP.RTC.getStreamID(stream.getOriginalStream());
  6169. localVideo.autoplay = true;
  6170. localVideo.volume = 0; // is it required if audio is separated ?
  6171. localVideo.oncontextmenu = function () { return false; };
  6172. var localVideoContainer = document.getElementById('localVideoWrapper');
  6173. localVideoContainer.appendChild(localVideo);
  6174. // Set default display name.
  6175. setDisplayName('localVideoContainer');
  6176. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  6177. VideoLayout.connectionIndicators["localVideoContainer"]
  6178. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  6179. }
  6180. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  6181. var localVideoSelector = $('#' + localVideo.id);
  6182. function localVideoClick(event) {
  6183. event.stopPropagation();
  6184. VideoLayout.handleVideoThumbClicked(
  6185. APP.RTC.getVideoSrc(localVideo),
  6186. false,
  6187. APP.xmpp.myResource());
  6188. }
  6189. // Add click handler to both video and video wrapper elements in case
  6190. // there's no video.
  6191. localVideoSelector.click(localVideoClick);
  6192. $('#localVideoContainer').click(localVideoClick);
  6193. // Add hover handler
  6194. $('#localVideoContainer').hover(
  6195. function() {
  6196. VideoLayout.showDisplayName('localVideoContainer', true);
  6197. },
  6198. function() {
  6199. if (!VideoLayout.isLargeVideoVisible()
  6200. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6201. VideoLayout.showDisplayName('localVideoContainer', false);
  6202. }
  6203. );
  6204. // Add stream ended handler
  6205. stream.getOriginalStream().onended = function () {
  6206. localVideoContainer.removeChild(localVideo);
  6207. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  6208. };
  6209. // Flip video x axis if needed
  6210. flipXLocalVideo = flipX;
  6211. if (flipX) {
  6212. localVideoSelector.addClass("flipVideoX");
  6213. }
  6214. // Attach WebRTC stream
  6215. var videoStream = APP.simulcast.getLocalVideoStream();
  6216. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  6217. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  6218. var myResourceJid = APP.xmpp.myResource();
  6219. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  6220. myResourceJid);
  6221. };
  6222. /**
  6223. * Checks if removed video is currently displayed and tries to display
  6224. * another one instead.
  6225. * @param removedVideoSrc src stream identifier of the video.
  6226. */
  6227. my.updateRemovedVideo = function(removedVideoSrc) {
  6228. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  6229. // this is currently displayed as large
  6230. // pick the last visible video in the row
  6231. // if nobody else is left, this picks the local video
  6232. var pick
  6233. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  6234. .get(0);
  6235. if (!pick) {
  6236. console.info("Last visible video no longer exists");
  6237. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  6238. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  6239. // Try local video
  6240. console.info("Fallback to local video...");
  6241. pick = $('#remoteVideos>span>span>video').get(0);
  6242. }
  6243. }
  6244. // mute if localvideo
  6245. if (pick) {
  6246. var container = pick.parentNode;
  6247. var jid = null;
  6248. if(container)
  6249. {
  6250. if(container.id == "localVideoWrapper")
  6251. {
  6252. jid = APP.xmpp.myResource();
  6253. }
  6254. else
  6255. {
  6256. jid = VideoLayout.getPeerContainerResourceJid(container);
  6257. }
  6258. }
  6259. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(pick), pick.volume, jid);
  6260. } else {
  6261. console.warn("Failed to elect large video");
  6262. }
  6263. }
  6264. };
  6265. my.onRemoteStreamAdded = function (stream) {
  6266. var container;
  6267. var remotes = document.getElementById('remoteVideos');
  6268. if (stream.peerjid) {
  6269. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6270. container = document.getElementById(
  6271. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6272. } else {
  6273. var id = stream.getOriginalStream().id;
  6274. if (id !== 'mixedmslabel'
  6275. // FIXME: default stream is added always with new focus
  6276. // (to be investigated)
  6277. && id !== 'default') {
  6278. console.error('can not associate stream',
  6279. id,
  6280. 'with a participant');
  6281. // We don't want to add it here since it will cause troubles
  6282. return;
  6283. }
  6284. // FIXME: for the mixed ms we dont need a video -- currently
  6285. container = document.createElement('span');
  6286. container.id = 'mixedstream';
  6287. container.className = 'videocontainer';
  6288. remotes.appendChild(container);
  6289. UIUtil.playSoundNotification('userJoined');
  6290. }
  6291. if (container) {
  6292. VideoLayout.addRemoteStreamElement( container,
  6293. stream.sid,
  6294. stream.getOriginalStream(),
  6295. stream.peerjid,
  6296. stream.ssrc);
  6297. }
  6298. }
  6299. my.getLargeVideoState = function () {
  6300. return largeVideoState;
  6301. };
  6302. /**
  6303. * Updates the large video with the given new video source.
  6304. */
  6305. my.updateLargeVideo = function(newSrc, vol, resourceJid) {
  6306. console.log('hover in', newSrc);
  6307. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc) {
  6308. $('#activeSpeaker').css('visibility', 'hidden');
  6309. // Due to the simulcast the localVideoSrc may have changed when the
  6310. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6311. // isVideoSrcDesktop methods will not function correctly.
  6312. //
  6313. // Also, again due to the simulcast, the updateLargeVideo method can
  6314. // be called multiple times almost simultaneously. Therefore, we
  6315. // store the state here and update only once.
  6316. largeVideoState.newSrc = newSrc;
  6317. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6318. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(
  6319. APP.xmpp.findJidFromResource(resourceJid));
  6320. if(largeVideoState.userResourceJid) {
  6321. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6322. } else {
  6323. largeVideoState.oldResourceJid = null;
  6324. }
  6325. largeVideoState.userResourceJid = resourceJid;
  6326. // Screen stream is already rotated
  6327. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6328. var userChanged = false;
  6329. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6330. userChanged = true;
  6331. // we want the notification to trigger even if userJid is undefined,
  6332. // or null.
  6333. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6334. largeVideoState.userResourceJid);
  6335. }
  6336. if (!largeVideoState.updateInProgress) {
  6337. largeVideoState.updateInProgress = true;
  6338. var doUpdate = function () {
  6339. Avatar.updateActiveSpeakerAvatarSrc(
  6340. APP.xmpp.findJidFromResource(
  6341. largeVideoState.userResourceJid));
  6342. if (!userChanged && largeVideoState.preload &&
  6343. largeVideoState.preload !== null &&
  6344. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  6345. {
  6346. console.info('Switching to preloaded video');
  6347. var attributes = $('#largeVideo').prop("attributes");
  6348. // loop through largeVideo attributes and apply them on
  6349. // preload.
  6350. $.each(attributes, function () {
  6351. if (this.name !== 'id' && this.name !== 'src') {
  6352. largeVideoState.preload.attr(this.name, this.value);
  6353. }
  6354. });
  6355. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  6356. $('#largeVideo').attr('id', 'previousLargeVideo');
  6357. largeVideoState.preload.attr('id', 'largeVideo');
  6358. $('#previousLargeVideo').remove();
  6359. largeVideoState.preload.on('loadedmetadata', function (e) {
  6360. currentVideoWidth = this.videoWidth;
  6361. currentVideoHeight = this.videoHeight;
  6362. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6363. });
  6364. largeVideoState.preload = null;
  6365. largeVideoState.preload_ssrc = 0;
  6366. } else {
  6367. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6368. }
  6369. var videoTransform = document.getElementById('largeVideo')
  6370. .style.webkitTransform;
  6371. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6372. document.getElementById('largeVideo').style.webkitTransform
  6373. = "scaleX(-1)";
  6374. }
  6375. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6376. document.getElementById('largeVideo').style.webkitTransform
  6377. = "none";
  6378. }
  6379. // Change the way we'll be measuring and positioning large video
  6380. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6381. ? getDesktopVideoSize
  6382. : getCameraVideoSize;
  6383. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6384. ? getDesktopVideoPosition
  6385. : getCameraVideoPosition;
  6386. // Only if the large video is currently visible.
  6387. // Disable previous dominant speaker video.
  6388. if (largeVideoState.oldResourceJid) {
  6389. VideoLayout.enableDominantSpeaker(
  6390. largeVideoState.oldResourceJid,
  6391. false);
  6392. }
  6393. // Enable new dominant speaker in the remote videos section.
  6394. if (largeVideoState.userResourceJid) {
  6395. VideoLayout.enableDominantSpeaker(
  6396. largeVideoState.userResourceJid,
  6397. true);
  6398. }
  6399. if (userChanged && largeVideoState.isVisible) {
  6400. // using "this" should be ok because we're called
  6401. // from within the fadeOut event.
  6402. $(this).fadeIn(300);
  6403. }
  6404. if(userChanged) {
  6405. Avatar.showUserAvatar(
  6406. APP.xmpp.findJidFromResource(
  6407. largeVideoState.oldResourceJid));
  6408. }
  6409. largeVideoState.updateInProgress = false;
  6410. };
  6411. if (userChanged) {
  6412. $('#largeVideo').fadeOut(300, doUpdate);
  6413. } else {
  6414. doUpdate();
  6415. }
  6416. }
  6417. } else {
  6418. Avatar.showUserAvatar(
  6419. APP.xmpp.findJidFromResource(
  6420. largeVideoState.userResourceJid));
  6421. }
  6422. };
  6423. my.handleVideoThumbClicked = function(videoSrc,
  6424. noPinnedEndpointChangedEvent,
  6425. resourceJid) {
  6426. // Restore style for previously focused video
  6427. var oldContainer = null;
  6428. if(focusedVideoInfo) {
  6429. var focusResourceJid = focusedVideoInfo.resourceJid;
  6430. oldContainer = getParticipantContainer(focusResourceJid);
  6431. }
  6432. if (oldContainer) {
  6433. oldContainer.removeClass("videoContainerFocused");
  6434. }
  6435. // Unlock current focused.
  6436. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6437. {
  6438. focusedVideoInfo = null;
  6439. var dominantSpeakerVideo = null;
  6440. // Enable the currently set dominant speaker.
  6441. if (currentDominantSpeaker) {
  6442. dominantSpeakerVideo
  6443. = $('#participant_' + currentDominantSpeaker + '>video')
  6444. .get(0);
  6445. if (dominantSpeakerVideo) {
  6446. VideoLayout.updateLargeVideo(
  6447. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6448. 1,
  6449. currentDominantSpeaker);
  6450. }
  6451. }
  6452. if (!noPinnedEndpointChangedEvent) {
  6453. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6454. }
  6455. return;
  6456. }
  6457. // Lock new video
  6458. focusedVideoInfo = {
  6459. src: videoSrc,
  6460. resourceJid: resourceJid
  6461. };
  6462. // Update focused/pinned interface.
  6463. if (resourceJid)
  6464. {
  6465. var container = getParticipantContainer(resourceJid);
  6466. container.addClass("videoContainerFocused");
  6467. if (!noPinnedEndpointChangedEvent) {
  6468. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6469. }
  6470. }
  6471. if ($('#largeVideo').attr('src') === videoSrc &&
  6472. VideoLayout.isLargeVideoOnTop()) {
  6473. return;
  6474. }
  6475. // Triggers a "video.selected" event. The "false" parameter indicates
  6476. // this isn't a prezi.
  6477. $(document).trigger("video.selected", [false]);
  6478. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6479. $('audio').each(function (idx, el) {
  6480. if (el.id.indexOf('mixedmslabel') !== -1) {
  6481. el.volume = 0;
  6482. el.volume = 1;
  6483. }
  6484. });
  6485. };
  6486. /**
  6487. * Positions the large video.
  6488. *
  6489. * @param videoWidth the stream video width
  6490. * @param videoHeight the stream video height
  6491. */
  6492. my.positionLarge = function (videoWidth, videoHeight) {
  6493. var videoSpaceWidth = $('#videospace').width();
  6494. var videoSpaceHeight = window.innerHeight;
  6495. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6496. videoHeight,
  6497. videoSpaceWidth,
  6498. videoSpaceHeight);
  6499. var largeVideoWidth = videoSize[0];
  6500. var largeVideoHeight = videoSize[1];
  6501. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6502. largeVideoHeight,
  6503. videoSpaceWidth,
  6504. videoSpaceHeight);
  6505. var horizontalIndent = videoPosition[0];
  6506. var verticalIndent = videoPosition[1];
  6507. positionVideo($('#largeVideo'),
  6508. largeVideoWidth,
  6509. largeVideoHeight,
  6510. horizontalIndent, verticalIndent);
  6511. };
  6512. /**
  6513. * Shows/hides the large video.
  6514. */
  6515. my.setLargeVideoVisible = function(isVisible) {
  6516. var resourceJid = largeVideoState.userResourceJid;
  6517. if (isVisible) {
  6518. $('#largeVideo').css({visibility: 'visible'});
  6519. $('.watermark').css({visibility: 'visible'});
  6520. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6521. }
  6522. else {
  6523. $('#largeVideo').css({visibility: 'hidden'});
  6524. $('#activeSpeaker').css('visibility', 'hidden');
  6525. $('.watermark').css({visibility: 'hidden'});
  6526. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6527. if(focusedVideoInfo) {
  6528. var focusResourceJid = focusedVideoInfo.resourceJid;
  6529. var oldContainer = getParticipantContainer(focusResourceJid);
  6530. if (oldContainer && oldContainer.length > 0) {
  6531. oldContainer.removeClass("videoContainerFocused");
  6532. }
  6533. focusedVideoInfo = null;
  6534. if(focusResourceJid) {
  6535. Avatar.showUserAvatar(
  6536. APP.xmpp.findJidFromResource(focusResourceJid));
  6537. }
  6538. }
  6539. }
  6540. };
  6541. /**
  6542. * Indicates if the large video is currently visible.
  6543. *
  6544. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6545. */
  6546. my.isLargeVideoVisible = function() {
  6547. return $('#largeVideo').is(':visible');
  6548. };
  6549. my.isLargeVideoOnTop = function () {
  6550. var Etherpad = require("../etherpad/Etherpad");
  6551. var Prezi = require("../prezi/Prezi");
  6552. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6553. };
  6554. /**
  6555. * Checks if container for participant identified by given peerJid exists
  6556. * in the document and creates it eventually.
  6557. *
  6558. * @param peerJid peer Jid to check.
  6559. * @param userId user email or id for setting the avatar
  6560. *
  6561. * @return Returns <tt>true</tt> if the peer container exists,
  6562. * <tt>false</tt> - otherwise
  6563. */
  6564. my.ensurePeerContainerExists = function(peerJid, userId) {
  6565. ContactList.ensureAddContact(peerJid, userId);
  6566. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6567. var videoSpanId = 'participant_' + resourceJid;
  6568. if (!$('#' + videoSpanId).length) {
  6569. var container =
  6570. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6571. Avatar.setUserAvatar(peerJid, userId);
  6572. // Set default display name.
  6573. setDisplayName(videoSpanId);
  6574. VideoLayout.connectionIndicators[videoSpanId] =
  6575. new ConnectionIndicator(container, peerJid, VideoLayout);
  6576. var nickfield = document.createElement('span');
  6577. nickfield.className = "nick";
  6578. nickfield.appendChild(document.createTextNode(resourceJid));
  6579. container.appendChild(nickfield);
  6580. // In case this is not currently in the last n we don't show it.
  6581. if (localLastNCount
  6582. && localLastNCount > 0
  6583. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  6584. showPeerContainer(resourceJid, 'hide');
  6585. }
  6586. else
  6587. VideoLayout.resizeThumbnails();
  6588. }
  6589. };
  6590. my.addRemoteVideoContainer = function(peerJid, spanId) {
  6591. var container = document.createElement('span');
  6592. container.id = spanId;
  6593. container.className = 'videocontainer';
  6594. var remotes = document.getElementById('remoteVideos');
  6595. remotes.appendChild(container);
  6596. // If the peerJid is null then this video span couldn't be directly
  6597. // associated with a participant (this could happen in the case of prezi).
  6598. if (APP.xmpp.isModerator() && peerJid !== null)
  6599. addRemoteVideoMenu(peerJid, container);
  6600. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  6601. return container;
  6602. };
  6603. /**
  6604. * Creates an audio or video stream element.
  6605. */
  6606. my.createStreamElement = function (sid, stream) {
  6607. var isVideo = stream.getVideoTracks().length > 0;
  6608. var element = isVideo
  6609. ? document.createElement('video')
  6610. : document.createElement('audio');
  6611. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  6612. + sid + '_' + APP.RTC.getStreamID(stream);
  6613. element.id = id;
  6614. element.autoplay = true;
  6615. element.oncontextmenu = function () { return false; };
  6616. return element;
  6617. };
  6618. my.addRemoteStreamElement
  6619. = function (container, sid, stream, peerJid, thessrc) {
  6620. var newElementId = null;
  6621. var isVideo = stream.getVideoTracks().length > 0;
  6622. if (container) {
  6623. var streamElement = VideoLayout.createStreamElement(sid, stream);
  6624. newElementId = streamElement.id;
  6625. container.appendChild(streamElement);
  6626. var sel = $('#' + newElementId);
  6627. sel.hide();
  6628. // If the container is currently visible we attach the stream.
  6629. if (!isVideo
  6630. || (container.offsetParent !== null && isVideo)) {
  6631. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6632. APP.RTC.attachMediaStream(sel, videoStream);
  6633. if (isVideo)
  6634. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  6635. }
  6636. stream.onended = function () {
  6637. console.log('stream ended', this);
  6638. VideoLayout.removeRemoteStreamElement(
  6639. stream, isVideo, container);
  6640. // NOTE(gp) it seems that under certain circumstances, the
  6641. // onended event is not fired and thus the contact list is not
  6642. // updated.
  6643. //
  6644. // The onended event of a stream should be fired when the SSRCs
  6645. // corresponding to that stream are removed from the SDP; but
  6646. // this doesn't seem to always be the case, resulting in ghost
  6647. // contacts.
  6648. //
  6649. // In an attempt to fix the ghost contacts problem, I'm moving
  6650. // the removeContact() method call in app.js, inside the
  6651. // 'muc.left' event handler.
  6652. //if (peerJid)
  6653. // ContactList.removeContact(peerJid);
  6654. };
  6655. // Add click handler.
  6656. container.onclick = function (event) {
  6657. /*
  6658. * FIXME It turns out that videoThumb may not exist (if there is
  6659. * no actual video).
  6660. */
  6661. var videoThumb = $('#' + container.id + '>video').get(0);
  6662. if (videoThumb) {
  6663. VideoLayout.handleVideoThumbClicked(
  6664. APP.RTC.getVideoSrc(videoThumb),
  6665. false,
  6666. Strophe.getResourceFromJid(peerJid));
  6667. }
  6668. event.stopPropagation();
  6669. event.preventDefault();
  6670. return false;
  6671. };
  6672. // Add hover handler
  6673. $(container).hover(
  6674. function() {
  6675. VideoLayout.showDisplayName(container.id, true);
  6676. },
  6677. function() {
  6678. var videoSrc = null;
  6679. if ($('#' + container.id + '>video')
  6680. && $('#' + container.id + '>video').length > 0) {
  6681. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  6682. }
  6683. // If the video has been "pinned" by the user we want to
  6684. // keep the display name on place.
  6685. if (!VideoLayout.isLargeVideoVisible()
  6686. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6687. VideoLayout.showDisplayName(container.id, false);
  6688. }
  6689. );
  6690. }
  6691. return newElementId;
  6692. };
  6693. /**
  6694. * Removes the remote stream element corresponding to the given stream and
  6695. * parent container.
  6696. *
  6697. * @param stream the stream
  6698. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  6699. * @param container
  6700. */
  6701. my.removeRemoteStreamElement = function (stream, isVideo, container) {
  6702. if (!container)
  6703. return;
  6704. var select = null;
  6705. var removedVideoSrc = null;
  6706. if (isVideo) {
  6707. select = $('#' + container.id + '>video');
  6708. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  6709. }
  6710. else
  6711. select = $('#' + container.id + '>audio');
  6712. // Mark video as removed to cancel waiting loop(if video is removed
  6713. // before has started)
  6714. select.removed = true;
  6715. select.remove();
  6716. var audioCount = $('#' + container.id + '>audio').length;
  6717. var videoCount = $('#' + container.id + '>video').length;
  6718. if (!audioCount && !videoCount) {
  6719. console.log("Remove whole user", container.id);
  6720. if(VideoLayout.connectionIndicators[container.id])
  6721. VideoLayout.connectionIndicators[container.id].remove();
  6722. // Remove whole container
  6723. container.remove();
  6724. UIUtil.playSoundNotification('userLeft');
  6725. VideoLayout.resizeThumbnails();
  6726. }
  6727. if (removedVideoSrc)
  6728. VideoLayout.updateRemovedVideo(removedVideoSrc);
  6729. };
  6730. /**
  6731. * Show/hide peer container for the given resourceJid.
  6732. */
  6733. function showPeerContainer(resourceJid, state) {
  6734. var peerContainer = $('#participant_' + resourceJid);
  6735. if (!peerContainer)
  6736. return;
  6737. var isHide = state === 'hide';
  6738. var resizeThumbnails = false;
  6739. if (!isHide) {
  6740. if (!peerContainer.is(':visible')) {
  6741. resizeThumbnails = true;
  6742. peerContainer.show();
  6743. }
  6744. var jid = APP.xmpp.findJidFromResource(resourceJid);
  6745. if (state == 'show')
  6746. {
  6747. // peerContainer.css('-webkit-filter', '');
  6748. Avatar.showUserAvatar(jid, false);
  6749. }
  6750. else // if (state == 'avatar')
  6751. {
  6752. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  6753. Avatar.showUserAvatar(jid, true);
  6754. }
  6755. }
  6756. else if (peerContainer.is(':visible') && isHide)
  6757. {
  6758. resizeThumbnails = true;
  6759. peerContainer.hide();
  6760. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  6761. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  6762. }
  6763. if (resizeThumbnails) {
  6764. VideoLayout.resizeThumbnails();
  6765. }
  6766. // We want to be able to pin a participant from the contact list, even
  6767. // if he's not in the lastN set!
  6768. // ContactList.setClickable(resourceJid, !isHide);
  6769. };
  6770. my.inputDisplayNameHandler = function (name) {
  6771. NicknameHandler.setNickname(name);
  6772. if (!$('#localDisplayName').is(":visible")) {
  6773. if (NicknameHandler.getNickname())
  6774. {
  6775. var meHTML = APP.translation.generateTranslatonHTML("me");
  6776. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  6777. }
  6778. else
  6779. {
  6780. var defaultHTML = APP.translation.generateTranslatonHTML(
  6781. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6782. $('#localDisplayName')
  6783. .html(defaultHTML);
  6784. }
  6785. $('#localDisplayName').show();
  6786. }
  6787. $('#editDisplayName').hide();
  6788. };
  6789. /**
  6790. * Shows/hides the display name on the remote video.
  6791. * @param videoSpanId the identifier of the video span element
  6792. * @param isShow indicates if the display name should be shown or hidden
  6793. */
  6794. my.showDisplayName = function(videoSpanId, isShow) {
  6795. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  6796. if (isShow) {
  6797. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  6798. nameSpan.setAttribute("style", "display:inline-block;");
  6799. }
  6800. else {
  6801. if (nameSpan)
  6802. nameSpan.setAttribute("style", "display:none;");
  6803. }
  6804. };
  6805. /**
  6806. * Shows the presence status message for the given video.
  6807. */
  6808. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  6809. if (!$('#' + videoSpanId).length) {
  6810. // No container
  6811. return;
  6812. }
  6813. var statusSpan = $('#' + videoSpanId + '>span.status');
  6814. if (!statusSpan.length) {
  6815. //Add status span
  6816. statusSpan = document.createElement('span');
  6817. statusSpan.className = 'status';
  6818. statusSpan.id = videoSpanId + '_status';
  6819. $('#' + videoSpanId)[0].appendChild(statusSpan);
  6820. statusSpan = $('#' + videoSpanId + '>span.status');
  6821. }
  6822. // Display status
  6823. if (statusMsg && statusMsg.length) {
  6824. $('#' + videoSpanId + '_status').text(statusMsg);
  6825. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  6826. }
  6827. else {
  6828. // Hide
  6829. statusSpan.get(0).setAttribute("style", "display:none;");
  6830. }
  6831. };
  6832. /**
  6833. * Shows a visual indicator for the moderator of the conference.
  6834. */
  6835. my.showModeratorIndicator = function () {
  6836. var isModerator = APP.xmpp.isModerator();
  6837. if (isModerator) {
  6838. var indicatorSpan = $('#localVideoContainer .focusindicator');
  6839. if (indicatorSpan.children().length === 0)
  6840. {
  6841. createModeratorIndicatorElement(indicatorSpan[0]);
  6842. //translates text in focus indicator
  6843. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  6844. }
  6845. }
  6846. var members = APP.xmpp.getMembers();
  6847. Object.keys(members).forEach(function (jid) {
  6848. if (Strophe.getResourceFromJid(jid) === 'focus') {
  6849. // Skip server side focus
  6850. return;
  6851. }
  6852. var resourceJid = Strophe.getResourceFromJid(jid);
  6853. var videoSpanId = 'participant_' + resourceJid;
  6854. var videoContainer = document.getElementById(videoSpanId);
  6855. if (!videoContainer) {
  6856. console.error("No video container for " + jid);
  6857. return;
  6858. }
  6859. var member = members[jid];
  6860. if (member.role === 'moderator') {
  6861. // Remove menu if peer is moderator
  6862. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  6863. if (menuSpan.length) {
  6864. removeRemoteVideoMenu(videoSpanId);
  6865. }
  6866. // Show moderator indicator
  6867. var indicatorSpan
  6868. = $('#' + videoSpanId + ' .focusindicator');
  6869. if (!indicatorSpan || indicatorSpan.length === 0) {
  6870. indicatorSpan = document.createElement('span');
  6871. indicatorSpan.className = 'focusindicator';
  6872. videoContainer.appendChild(indicatorSpan);
  6873. createModeratorIndicatorElement(indicatorSpan);
  6874. //translates text in focus indicators
  6875. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  6876. }
  6877. } else if (isModerator) {
  6878. // We are moderator, but user is not - add menu
  6879. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  6880. addRemoteVideoMenu(
  6881. jid,
  6882. document.getElementById('participant_' + resourceJid));
  6883. }
  6884. }
  6885. });
  6886. };
  6887. /**
  6888. * Shows video muted indicator over small videos.
  6889. */
  6890. my.showVideoIndicator = function(videoSpanId, isMuted) {
  6891. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6892. if (isMuted === 'false') {
  6893. if (videoMutedSpan.length > 0) {
  6894. videoMutedSpan.remove();
  6895. }
  6896. }
  6897. else {
  6898. if(videoMutedSpan.length == 0) {
  6899. videoMutedSpan = document.createElement('span');
  6900. videoMutedSpan.className = 'videoMuted';
  6901. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  6902. var mutedIndicator = document.createElement('i');
  6903. mutedIndicator.className = 'icon-camera-disabled';
  6904. UIUtil.setTooltip(mutedIndicator,
  6905. "videothumbnail.videomute",
  6906. "top");
  6907. videoMutedSpan.appendChild(mutedIndicator);
  6908. //translate texts for muted indicator
  6909. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  6910. }
  6911. VideoLayout.updateMutePosition(videoSpanId);
  6912. }
  6913. };
  6914. my.updateMutePosition = function (videoSpanId) {
  6915. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6916. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  6917. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6918. if(connectionIndicator.length > 0
  6919. && connectionIndicator[0].style.display != "none") {
  6920. audioMutedSpan.css({right: "23px"});
  6921. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  6922. }
  6923. else
  6924. {
  6925. audioMutedSpan.css({right: "0px"});
  6926. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  6927. }
  6928. }
  6929. /**
  6930. * Shows audio muted indicator over small videos.
  6931. * @param {string} isMuted
  6932. */
  6933. my.showAudioIndicator = function(videoSpanId, isMuted) {
  6934. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6935. if (isMuted === 'false') {
  6936. if (audioMutedSpan.length > 0) {
  6937. audioMutedSpan.popover('hide');
  6938. audioMutedSpan.remove();
  6939. }
  6940. }
  6941. else {
  6942. if(audioMutedSpan.length == 0 ) {
  6943. audioMutedSpan = document.createElement('span');
  6944. audioMutedSpan.className = 'audioMuted';
  6945. UIUtil.setTooltip(audioMutedSpan,
  6946. "videothumbnail.mute",
  6947. "top");
  6948. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  6949. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  6950. var mutedIndicator = document.createElement('i');
  6951. mutedIndicator.className = 'icon-mic-disabled';
  6952. audioMutedSpan.appendChild(mutedIndicator);
  6953. }
  6954. VideoLayout.updateMutePosition(videoSpanId);
  6955. }
  6956. };
  6957. /*
  6958. * Shows or hides the audio muted indicator over the local thumbnail video.
  6959. * @param {boolean} isMuted
  6960. */
  6961. my.showLocalAudioIndicator = function(isMuted) {
  6962. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  6963. };
  6964. /**
  6965. * Resizes the large video container.
  6966. */
  6967. my.resizeLargeVideoContainer = function () {
  6968. Chat.resizeChat();
  6969. var availableHeight = window.innerHeight;
  6970. var availableWidth = UIUtil.getAvailableVideoWidth();
  6971. if (availableWidth < 0 || availableHeight < 0) return;
  6972. $('#videospace').width(availableWidth);
  6973. $('#videospace').height(availableHeight);
  6974. $('#largeVideoContainer').width(availableWidth);
  6975. $('#largeVideoContainer').height(availableHeight);
  6976. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  6977. var top = availableHeight / 2 - avatarSize / 4 * 3;
  6978. $('#activeSpeaker').css('top', top);
  6979. VideoLayout.resizeThumbnails();
  6980. };
  6981. /**
  6982. * Resizes thumbnails.
  6983. */
  6984. my.resizeThumbnails = function() {
  6985. var videoSpaceWidth = $('#remoteVideos').width();
  6986. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  6987. var width = thumbnailSize[0];
  6988. var height = thumbnailSize[1];
  6989. // size videos so that while keeping AR and max height, we have a
  6990. // nice fit
  6991. $('#remoteVideos').height(height);
  6992. $('#remoteVideos>span').width(width);
  6993. $('#remoteVideos>span').height(height);
  6994. $('.userAvatar').css('left', (width - height) / 2);
  6995. $(document).trigger("remotevideo.resized", [width, height]);
  6996. };
  6997. /**
  6998. * Enables the dominant speaker UI.
  6999. *
  7000. * @param resourceJid the jid indicating the video element to
  7001. * activate/deactivate
  7002. * @param isEnable indicates if the dominant speaker should be enabled or
  7003. * disabled
  7004. */
  7005. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  7006. var videoSpanId = null;
  7007. var videoContainerId = null;
  7008. if (resourceJid
  7009. === APP.xmpp.myResource()) {
  7010. videoSpanId = 'localVideoWrapper';
  7011. videoContainerId = 'localVideoContainer';
  7012. }
  7013. else {
  7014. videoSpanId = 'participant_' + resourceJid;
  7015. videoContainerId = videoSpanId;
  7016. }
  7017. var displayName = resourceJid;
  7018. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  7019. if (nameSpan.length > 0)
  7020. displayName = nameSpan.html();
  7021. console.log("UI enable dominant speaker",
  7022. displayName,
  7023. resourceJid,
  7024. isEnable);
  7025. videoSpan = document.getElementById(videoContainerId);
  7026. if (!videoSpan) {
  7027. return;
  7028. }
  7029. var video = $('#' + videoSpanId + '>video');
  7030. if (video && video.length > 0) {
  7031. if (isEnable) {
  7032. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  7033. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  7034. if (!videoSpan.classList.contains("dominantspeaker"))
  7035. videoSpan.classList.add("dominantspeaker");
  7036. }
  7037. else {
  7038. VideoLayout.showDisplayName(videoContainerId, false);
  7039. if (videoSpan.classList.contains("dominantspeaker"))
  7040. videoSpan.classList.remove("dominantspeaker");
  7041. }
  7042. Avatar.showUserAvatar(
  7043. APP.xmpp.findJidFromResource(resourceJid));
  7044. }
  7045. };
  7046. /**
  7047. * Calculates the thumbnail size.
  7048. *
  7049. * @param videoSpaceWidth the width of the video space
  7050. */
  7051. my.calculateThumbnailSize = function (videoSpaceWidth) {
  7052. // Calculate the available height, which is the inner window height minus
  7053. // 39px for the header minus 2px for the delimiter lines on the top and
  7054. // bottom of the large video, minus the 36px space inside the remoteVideos
  7055. // container used for highlighting shadow.
  7056. var availableHeight = 100;
  7057. var numvids = $('#remoteVideos>span:visible').length;
  7058. if (localLastNCount && localLastNCount > 0) {
  7059. numvids = Math.min(localLastNCount + 1, numvids);
  7060. }
  7061. // Remove the 3px borders arround videos and border around the remote
  7062. // videos area and the 4 pixels between the local video and the others
  7063. //TODO: Find out where the 4 pixels come from and remove them
  7064. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  7065. var availableWidth = availableWinWidth / numvids;
  7066. var aspectRatio = 16.0 / 9.0;
  7067. var maxHeight = Math.min(160, availableHeight);
  7068. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  7069. if (availableHeight < availableWidth / aspectRatio) {
  7070. availableWidth = Math.floor(availableHeight * aspectRatio);
  7071. }
  7072. return [availableWidth, availableHeight];
  7073. };
  7074. /**
  7075. * Updates the remote video menu.
  7076. *
  7077. * @param jid the jid indicating the video for which we're adding a menu.
  7078. * @param isMuted indicates the current mute state
  7079. */
  7080. my.updateRemoteVideoMenu = function(jid, isMuted) {
  7081. var muteMenuItem
  7082. = $('#remote_popupmenu_'
  7083. + Strophe.getResourceFromJid(jid)
  7084. + '>li>a.mutelink');
  7085. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  7086. if (muteMenuItem.length) {
  7087. var muteLink = muteMenuItem.get(0);
  7088. if (isMuted === 'true') {
  7089. muteLink.innerHTML = mutedIndicator + ' Muted';
  7090. muteLink.className = 'mutelink disabled';
  7091. }
  7092. else {
  7093. muteLink.innerHTML = mutedIndicator + ' Mute';
  7094. muteLink.className = 'mutelink';
  7095. }
  7096. }
  7097. };
  7098. /**
  7099. * Returns the current dominant speaker resource jid.
  7100. */
  7101. my.getDominantSpeakerResourceJid = function () {
  7102. return currentDominantSpeaker;
  7103. };
  7104. /**
  7105. * Returns the corresponding resource jid to the given peer container
  7106. * DOM element.
  7107. *
  7108. * @return the corresponding resource jid to the given peer container
  7109. * DOM element
  7110. */
  7111. my.getPeerContainerResourceJid = function (containerElement) {
  7112. var i = containerElement.id.indexOf('participant_');
  7113. if (i >= 0)
  7114. return containerElement.id.substring(i + 12);
  7115. };
  7116. /**
  7117. * On contact list item clicked.
  7118. */
  7119. $(ContactList).bind('contactclicked', function(event, jid) {
  7120. if (!jid) {
  7121. return;
  7122. }
  7123. var resource = Strophe.getResourceFromJid(jid);
  7124. var videoContainer = $("#participant_" + resource);
  7125. if (videoContainer.length > 0) {
  7126. var videoThumb = $('video', videoContainer).get(0);
  7127. // It is not always the case that a videoThumb exists (if there is
  7128. // no actual video).
  7129. if (videoThumb) {
  7130. if (videoThumb.src && videoThumb.src != '') {
  7131. // We have a video src, great! Let's update the large video
  7132. // now.
  7133. VideoLayout.handleVideoThumbClicked(
  7134. videoThumb.src,
  7135. false,
  7136. Strophe.getResourceFromJid(jid));
  7137. } else {
  7138. // If we don't have a video src for jid, there's absolutely
  7139. // no point in calling handleVideoThumbClicked; Quite
  7140. // simply, it won't work because it needs an src to attach
  7141. // to the large video.
  7142. //
  7143. // Instead, we trigger the pinned endpoint changed event to
  7144. // let the bridge adjust its lastN set for myjid and store
  7145. // the pinned user in the lastNPickupJid variable to be
  7146. // picked up later by the lastN changed event handler.
  7147. lastNPickupJid = jid;
  7148. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  7149. Strophe.getResourceFromJid(jid));
  7150. }
  7151. } else if (jid == APP.xmpp.myJid()) {
  7152. $("#localVideoContainer").click();
  7153. }
  7154. }
  7155. });
  7156. /**
  7157. * On audio muted event.
  7158. */
  7159. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  7160. /*
  7161. // FIXME: but focus can not mute in this case ? - check
  7162. if (jid === xmpp.myJid()) {
  7163. // The local mute indicator is controlled locally
  7164. return;
  7165. }*/
  7166. var videoSpanId = null;
  7167. if (jid === APP.xmpp.myJid()) {
  7168. videoSpanId = 'localVideoContainer';
  7169. } else {
  7170. VideoLayout.ensurePeerContainerExists(jid);
  7171. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7172. }
  7173. mutedAudios[jid] = isMuted;
  7174. if (APP.xmpp.isModerator()) {
  7175. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  7176. }
  7177. if (videoSpanId)
  7178. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  7179. });
  7180. /**
  7181. * On video muted event.
  7182. */
  7183. $(document).bind('videomuted.muc', function (event, jid, value) {
  7184. var isMuted = (value === "true");
  7185. if(!APP.RTC.muteRemoteVideoStream(jid, isMuted))
  7186. return;
  7187. Avatar.showUserAvatar(jid, isMuted);
  7188. var videoSpanId = null;
  7189. if (jid === APP.xmpp.myJid()) {
  7190. videoSpanId = 'localVideoContainer';
  7191. } else {
  7192. VideoLayout.ensurePeerContainerExists(jid);
  7193. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7194. }
  7195. if (videoSpanId)
  7196. VideoLayout.showVideoIndicator(videoSpanId, value);
  7197. });
  7198. /**
  7199. * Display name changed.
  7200. */
  7201. my.onDisplayNameChanged =
  7202. function (jid, displayName, status) {
  7203. if (jid === 'localVideoContainer'
  7204. || jid === APP.xmpp.myJid()) {
  7205. setDisplayName('localVideoContainer',
  7206. displayName);
  7207. } else {
  7208. VideoLayout.ensurePeerContainerExists(jid);
  7209. setDisplayName(
  7210. 'participant_' + Strophe.getResourceFromJid(jid),
  7211. displayName,
  7212. status);
  7213. }
  7214. };
  7215. /**
  7216. * On dominant speaker changed event.
  7217. */
  7218. my.onDominantSpeakerChanged = function (resourceJid) {
  7219. // We ignore local user events.
  7220. if (resourceJid
  7221. === APP.xmpp.myResource())
  7222. return;
  7223. var members = APP.xmpp.getMembers();
  7224. // Update the current dominant speaker.
  7225. if (resourceJid !== currentDominantSpeaker) {
  7226. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  7227. newSpeakerVideoSpanId = "participant_" + resourceJid;
  7228. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  7229. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  7230. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  7231. !members[currentJID].displayName)) {
  7232. setDisplayName(oldSpeakerVideoSpanId, null);
  7233. }
  7234. if(resourceJid && (!members || !members[newJID] ||
  7235. !members[newJID].displayName)) {
  7236. setDisplayName(newSpeakerVideoSpanId, null,
  7237. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  7238. }
  7239. currentDominantSpeaker = resourceJid;
  7240. } else {
  7241. return;
  7242. }
  7243. // Obtain container for new dominant speaker.
  7244. var container = document.getElementById(
  7245. 'participant_' + resourceJid);
  7246. // Local video will not have container found, but that's ok
  7247. // since we don't want to switch to local video.
  7248. if (container && !focusedVideoInfo)
  7249. {
  7250. var video = container.getElementsByTagName("video");
  7251. // Update the large video if the video source is already available,
  7252. // otherwise wait for the "videoactive.jingle" event.
  7253. if (video.length && video[0].currentTime > 0)
  7254. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  7255. }
  7256. };
  7257. /**
  7258. * On last N change event.
  7259. *
  7260. * @param lastNEndpoints the list of last N endpoints
  7261. * @param endpointsEnteringLastN the list currently entering last N
  7262. * endpoints
  7263. */
  7264. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7265. endpointsEnteringLastN,
  7266. stream) {
  7267. if (lastNCount !== lastNEndpoints.length)
  7268. lastNCount = lastNEndpoints.length;
  7269. lastNEndpointsCache = lastNEndpoints;
  7270. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7271. //
  7272. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7273. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7274. // so E sees them. C is only in E's local LastN set.
  7275. //
  7276. // If F starts talking and LastN = 3, then E should see thumbnails for
  7277. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7278. // enters E's local LastN ejecting C.
  7279. // Increase the local LastN set size, if necessary.
  7280. if (lastNCount > localLastNCount) {
  7281. localLastNCount = lastNCount;
  7282. }
  7283. // Update the local LastN set preserving the order in which the
  7284. // endpoints appeared in the LastN/local LastN set.
  7285. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7286. for (var i = 0; i < localLastNSet.length; i++) {
  7287. if (nextLocalLastNSet.length >= localLastNCount) {
  7288. break;
  7289. }
  7290. var resourceJid = localLastNSet[i];
  7291. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7292. nextLocalLastNSet.push(resourceJid);
  7293. }
  7294. }
  7295. localLastNSet = nextLocalLastNSet;
  7296. var updateLargeVideo = false;
  7297. // Handle LastN/local LastN changes.
  7298. $('#remoteVideos>span').each(function( index, element ) {
  7299. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7300. var isReceived = true;
  7301. if (resourceJid
  7302. && lastNEndpoints.indexOf(resourceJid) < 0
  7303. && localLastNSet.indexOf(resourceJid) < 0) {
  7304. console.log("Remove from last N", resourceJid);
  7305. showPeerContainer(resourceJid, 'hide');
  7306. isReceived = false;
  7307. } else if (resourceJid
  7308. && $('#participant_' + resourceJid).is(':visible')
  7309. && lastNEndpoints.indexOf(resourceJid) < 0
  7310. && localLastNSet.indexOf(resourceJid) >= 0) {
  7311. showPeerContainer(resourceJid, 'avatar');
  7312. isReceived = false;
  7313. }
  7314. if (!isReceived) {
  7315. // resourceJid has dropped out of the server side lastN set, so
  7316. // it is no longer being received. If resourceJid was being
  7317. // displayed in the large video we have to switch to another
  7318. // user.
  7319. var largeVideoResource = largeVideoState.userResourceJid;
  7320. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7321. updateLargeVideo = true;
  7322. }
  7323. }
  7324. });
  7325. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7326. endpointsEnteringLastN = lastNEndpoints;
  7327. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7328. endpointsEnteringLastN.forEach(function (resourceJid) {
  7329. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7330. showPeerContainer(resourceJid, 'show');
  7331. if (!isVisible) {
  7332. console.log("Add to last N", resourceJid);
  7333. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7334. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7335. var sel = $('#participant_' + resourceJid + '>video');
  7336. var videoStream = APP.simulcast.getReceivingVideoStream(
  7337. mediaStream.stream);
  7338. APP.RTC.attachMediaStream(sel, videoStream);
  7339. if (lastNPickupJid == mediaStream.peerjid) {
  7340. // Clean up the lastN pickup jid.
  7341. lastNPickupJid = null;
  7342. // Don't fire the events again, they've already
  7343. // been fired in the contact list click handler.
  7344. VideoLayout.handleVideoThumbClicked(
  7345. $(sel).attr('src'),
  7346. false,
  7347. Strophe.getResourceFromJid(mediaStream.peerjid));
  7348. updateLargeVideo = false;
  7349. }
  7350. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7351. }
  7352. })
  7353. }
  7354. // The endpoint that was being shown in the large video has dropped out
  7355. // of the lastN set and there was no lastN pickup jid. We need to update
  7356. // the large video now.
  7357. if (updateLargeVideo) {
  7358. var resource, container, src;
  7359. var myResource
  7360. = APP.xmpp.myResource();
  7361. // Find out which endpoint to show in the large video.
  7362. for (var i = 0; i < lastNEndpoints.length; i++) {
  7363. resource = lastNEndpoints[i];
  7364. if (!resource || resource === myResource)
  7365. continue;
  7366. container = $("#participant_" + resource);
  7367. if (container.length == 0)
  7368. continue;
  7369. src = $('video', container).attr('src');
  7370. if (!src)
  7371. continue;
  7372. // videoSrcToSsrc needs to be update for this call to succeed.
  7373. VideoLayout.updateLargeVideo(src);
  7374. break;
  7375. }
  7376. }
  7377. };
  7378. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  7379. endpointSimulcastLayers.forEach(function (esl) {
  7380. var resource = esl.endpoint;
  7381. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7382. // then ignore the event (= do not preload anything).
  7383. //
  7384. // The bridge could probably stop sending this message if it's for
  7385. // an endpoint that's not in lastN.
  7386. if (lastNCount != -1
  7387. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7388. return;
  7389. }
  7390. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7391. // Get session and stream from primary ssrc.
  7392. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7393. var sid = res.sid;
  7394. var electedStream = res.stream;
  7395. if (sid && electedStream) {
  7396. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7397. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7398. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  7399. if (preload) {
  7400. if (largeVideoState.preload)
  7401. {
  7402. $(largeVideoState.preload).remove();
  7403. }
  7404. console.info('Preloading remote video');
  7405. largeVideoState.preload = $('<video autoplay></video>');
  7406. // ssrcs are unique in an rtp session
  7407. largeVideoState.preload_ssrc = primarySSRC;
  7408. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  7409. }
  7410. } else {
  7411. console.error('Could not find a stream or a session.', sid, electedStream);
  7412. }
  7413. });
  7414. };
  7415. /**
  7416. * On simulcast layers changed event.
  7417. */
  7418. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  7419. endpointSimulcastLayers.forEach(function (esl) {
  7420. var resource = esl.endpoint;
  7421. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7422. // then ignore the event (= do not change large video/thumbnail
  7423. // SRCs).
  7424. //
  7425. // Note that even if we ignore the "changed" event in this event
  7426. // handler, the bridge must continue sending these events because
  7427. // the simulcast code in simulcast.js uses it to know what's going
  7428. // to be streamed by the bridge when/if the endpoint gets back into
  7429. // the lastN set.
  7430. if (lastNCount != -1
  7431. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7432. return;
  7433. }
  7434. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7435. // Get session and stream from primary ssrc.
  7436. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7437. var sid = res.sid;
  7438. var electedStream = res.stream;
  7439. if (sid && electedStream) {
  7440. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7441. console.info('Switching simulcast substream.');
  7442. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7443. var msidParts = msid.split(' ');
  7444. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  7445. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  7446. == largeVideoState.userResourceJid);
  7447. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  7448. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  7449. var electedStreamUrl;
  7450. if (largeVideoState.preload_ssrc == primarySSRC)
  7451. {
  7452. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  7453. }
  7454. else
  7455. {
  7456. if (largeVideoState.preload
  7457. && largeVideoState.preload != null) {
  7458. $(largeVideoState.preload).remove();
  7459. }
  7460. largeVideoState.preload_ssrc = 0;
  7461. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  7462. }
  7463. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  7464. if (updateLargeVideo) {
  7465. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  7466. Strophe.getResourceFromJid(jid));
  7467. }
  7468. if (updateFocusedVideoSrc) {
  7469. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  7470. }
  7471. var videoId;
  7472. if(resource == APP.xmpp.myResource())
  7473. {
  7474. videoId = "localVideoContainer";
  7475. }
  7476. else
  7477. {
  7478. videoId = "participant_" + resource;
  7479. }
  7480. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  7481. if(connectionIndicator)
  7482. connectionIndicator.updatePopoverData();
  7483. } else {
  7484. console.error('Could not find a stream or a sid.', sid, electedStream);
  7485. }
  7486. });
  7487. };
  7488. /**
  7489. * Updates local stats
  7490. * @param percent
  7491. * @param object
  7492. */
  7493. my.updateLocalConnectionStats = function (percent, object) {
  7494. var resolution = null;
  7495. if(object.resolution !== null)
  7496. {
  7497. resolution = object.resolution;
  7498. object.resolution = resolution[APP.xmpp.myJid()];
  7499. delete resolution[APP.xmpp.myJid()];
  7500. }
  7501. updateStatsIndicator("localVideoContainer", percent, object);
  7502. for(var jid in resolution)
  7503. {
  7504. if(resolution[jid] === null)
  7505. continue;
  7506. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7507. if(VideoLayout.connectionIndicators[id])
  7508. {
  7509. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7510. }
  7511. }
  7512. };
  7513. /**
  7514. * Updates remote stats.
  7515. * @param jid the jid associated with the stats
  7516. * @param percent the connection quality percent
  7517. * @param object the stats data
  7518. */
  7519. my.updateConnectionStats = function (jid, percent, object) {
  7520. var resourceJid = Strophe.getResourceFromJid(jid);
  7521. var videoSpanId = 'participant_' + resourceJid;
  7522. updateStatsIndicator(videoSpanId, percent, object);
  7523. };
  7524. /**
  7525. * Removes the connection
  7526. * @param jid
  7527. */
  7528. my.removeConnectionIndicator = function (jid) {
  7529. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7530. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7531. };
  7532. /**
  7533. * Hides the connection indicator
  7534. * @param jid
  7535. */
  7536. my.hideConnectionIndicator = function (jid) {
  7537. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7538. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7539. };
  7540. /**
  7541. * Hides all the indicators
  7542. */
  7543. my.onStatsStop = function () {
  7544. for(var indicator in VideoLayout.connectionIndicators)
  7545. {
  7546. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7547. }
  7548. };
  7549. my.participantLeft = function (jid) {
  7550. // Unlock large video
  7551. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7552. {
  7553. console.info("Focused video owner has left the conference");
  7554. focusedVideoInfo = null;
  7555. }
  7556. }
  7557. my.onVideoTypeChanged = function (jid) {
  7558. if(jid &&
  7559. Strophe.getResourceFromJid(jid) === largeVideoState.userResourceJid)
  7560. {
  7561. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  7562. VideoLayout.getVideoSize = largeVideoState.isDesktop
  7563. ? getDesktopVideoSize
  7564. : getCameraVideoSize;
  7565. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  7566. ? getDesktopVideoPosition
  7567. : getCameraVideoPosition;
  7568. VideoLayout.positionLarge(null, null);
  7569. }
  7570. }
  7571. return my;
  7572. }(VideoLayout || {}));
  7573. module.exports = VideoLayout;
  7574. },{"../../../service/RTC/MediaStreamTypes":87,"../../../service/UI/UIEvents":92,"../audio_levels/AudioLevels":9,"../avatar/Avatar":13,"../etherpad/Etherpad":14,"../prezi/Prezi":15,"../side_pannels/chat/Chat":18,"../side_pannels/contactlist/ContactList":22,"../util/NicknameHandler":29,"../util/UIUtil":30,"./ConnectionIndicator":31}],33:[function(require,module,exports){
  7575. //var nouns = [
  7576. //];
  7577. var pluralNouns = [
  7578. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7579. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  7580. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  7581. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  7582. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  7583. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  7584. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  7585. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  7586. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  7587. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  7588. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  7589. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  7590. ];
  7591. //var places = [
  7592. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  7593. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  7594. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  7595. // "Bridge"
  7596. //];
  7597. var verbs = [
  7598. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  7599. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  7600. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  7601. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  7602. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  7603. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  7604. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  7605. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  7606. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  7607. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  7608. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  7609. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  7610. ];
  7611. var adverbs = [
  7612. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  7613. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  7614. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  7615. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  7616. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  7617. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  7618. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  7619. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  7620. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  7621. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  7622. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  7623. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  7624. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  7625. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  7626. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  7627. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  7628. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  7629. ];
  7630. var adjectives = [
  7631. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  7632. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  7633. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  7634. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  7635. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  7636. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  7637. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  7638. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  7639. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  7640. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  7641. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  7642. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  7643. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  7644. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  7645. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  7646. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  7647. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  7648. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  7649. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  7650. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  7651. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  7652. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  7653. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  7654. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  7655. "Zealous"
  7656. ];
  7657. //var pronouns = [
  7658. //];
  7659. //var conjunctions = [
  7660. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  7661. //];
  7662. /*
  7663. * Maps a string (category name) to the array of words from that category.
  7664. */
  7665. var CATEGORIES =
  7666. {
  7667. //"_NOUN_": nouns,
  7668. "_PLURALNOUN_": pluralNouns,
  7669. //"_PLACE_": places,
  7670. "_VERB_": verbs,
  7671. "_ADVERB_": adverbs,
  7672. "_ADJECTIVE_": adjectives
  7673. //"_PRONOUN_": pronouns,
  7674. //"_CONJUNCTION_": conjunctions,
  7675. };
  7676. var PATTERNS = [
  7677. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  7678. // BeautifulFungiOrSpaghetti
  7679. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  7680. // AmazinglyScaryToy
  7681. //"_ADVERB__ADJECTIVE__NOUN_",
  7682. // NeitherTrashNorRifle
  7683. //"Neither_NOUN_Nor_NOUN_",
  7684. //"Either_NOUN_Or_NOUN_",
  7685. // EitherCopulateOrInvestigate
  7686. //"Either_VERB_Or_VERB_",
  7687. //"Neither_VERB_Nor_VERB_",
  7688. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  7689. //"The_ADVERB__ADJECTIVE__NOUN_",
  7690. //"The_ADVERB__ADJECTIVE__NOUN_s",
  7691. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  7692. // WolvesComputeBadly
  7693. //"_PLURALNOUN__VERB__ADVERB_",
  7694. // UniteFacilitateAndMerge
  7695. //"_VERB__VERB_And_VERB_",
  7696. //NastyWitchesAtThePub
  7697. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  7698. ];
  7699. /*
  7700. * Returns a random element from the array 'arr'
  7701. */
  7702. function randomElement(arr)
  7703. {
  7704. return arr[Math.floor(Math.random() * arr.length)];
  7705. }
  7706. /*
  7707. * Returns true if the string 's' contains one of the
  7708. * template strings.
  7709. */
  7710. function hasTemplate(s)
  7711. {
  7712. for (var template in CATEGORIES){
  7713. if (s.indexOf(template) >= 0){
  7714. return true;
  7715. }
  7716. }
  7717. }
  7718. /**
  7719. * Generates new room name.
  7720. */
  7721. var RoomNameGenerator = {
  7722. generateRoomWithoutSeparator: function()
  7723. {
  7724. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  7725. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  7726. var name = randomElement(PATTERNS);
  7727. var word;
  7728. while (hasTemplate(name)){
  7729. for (var template in CATEGORIES){
  7730. word = randomElement(CATEGORIES[template]);
  7731. name = name.replace(template, word);
  7732. }
  7733. }
  7734. return name;
  7735. }
  7736. }
  7737. module.exports = RoomNameGenerator;
  7738. },{}],34:[function(require,module,exports){
  7739. var animateTimeout, updateTimeout;
  7740. var RoomNameGenerator = require("./RoomnameGenerator");
  7741. function enter_room()
  7742. {
  7743. var val = $("#enter_room_field").val();
  7744. if(!val) {
  7745. val = $("#enter_room_field").attr("room_name");
  7746. }
  7747. if (val) {
  7748. window.location.pathname = "/" + val;
  7749. }
  7750. }
  7751. function animate(word) {
  7752. var currentVal = $("#enter_room_field").attr("placeholder");
  7753. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  7754. animateTimeout = setTimeout(function() {
  7755. animate(word.substring(1, word.length))
  7756. }, 70);
  7757. }
  7758. function update_roomname()
  7759. {
  7760. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  7761. $("#enter_room_field").attr("room_name", word);
  7762. $("#enter_room_field").attr("placeholder", "");
  7763. clearTimeout(animateTimeout);
  7764. animate(word);
  7765. updateTimeout = setTimeout(update_roomname, 10000);
  7766. }
  7767. function setupWelcomePage()
  7768. {
  7769. $("#videoconference_page").hide();
  7770. $("#domain_name").text(
  7771. window.location.protocol + "//" + window.location.host + "/");
  7772. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7773. var leftWatermarkDiv
  7774. = $("#welcome_page_header div[class='watermark leftwatermark']");
  7775. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  7776. {
  7777. leftWatermarkDiv.css({display: 'block'});
  7778. leftWatermarkDiv.parent().get(0).href
  7779. = interfaceConfig.JITSI_WATERMARK_LINK;
  7780. }
  7781. }
  7782. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7783. var rightWatermarkDiv
  7784. = $("#welcome_page_header div[class='watermark rightwatermark']");
  7785. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  7786. rightWatermarkDiv.css({display: 'block'});
  7787. rightWatermarkDiv.parent().get(0).href
  7788. = interfaceConfig.BRAND_WATERMARK_LINK;
  7789. rightWatermarkDiv.get(0).style.backgroundImage
  7790. = "url(images/rightwatermark.png)";
  7791. }
  7792. }
  7793. if (interfaceConfig.SHOW_POWERED_BY) {
  7794. $("#welcome_page_header>a[class='poweredby']")
  7795. .css({display: 'block'});
  7796. }
  7797. $("#enter_room_button").click(function()
  7798. {
  7799. enter_room();
  7800. });
  7801. $("#enter_room_field").keydown(function (event) {
  7802. if (event.keyCode === 13 /* enter */) {
  7803. enter_room();
  7804. }
  7805. });
  7806. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  7807. var updateTimeout;
  7808. var animateTimeout;
  7809. $("#reload_roomname").click(function () {
  7810. clearTimeout(updateTimeout);
  7811. clearTimeout(animateTimeout);
  7812. update_roomname();
  7813. });
  7814. $("#reload_roomname").show();
  7815. update_roomname();
  7816. }
  7817. $("#disable_welcome").click(function () {
  7818. window.localStorage.welcomePageDisabled
  7819. = $("#disable_welcome").is(":checked");
  7820. });
  7821. }
  7822. module.exports = setupWelcomePage;
  7823. },{"./RoomnameGenerator":33}],35:[function(require,module,exports){
  7824. var EventEmitter = require("events");
  7825. var eventEmitter = new EventEmitter();
  7826. var CQEvents = require("../../service/connectionquality/CQEvents");
  7827. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7828. /**
  7829. * local stats
  7830. * @type {{}}
  7831. */
  7832. var stats = {};
  7833. /**
  7834. * remote stats
  7835. * @type {{}}
  7836. */
  7837. var remoteStats = {};
  7838. /**
  7839. * Interval for sending statistics to other participants
  7840. * @type {null}
  7841. */
  7842. var sendIntervalId = null;
  7843. /**
  7844. * Start statistics sending.
  7845. */
  7846. function startSendingStats() {
  7847. sendStats();
  7848. sendIntervalId = setInterval(sendStats, 10000);
  7849. }
  7850. /**
  7851. * Sends statistics to other participants
  7852. */
  7853. function sendStats() {
  7854. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  7855. }
  7856. /**
  7857. * Converts statistics to format for sending through XMPP
  7858. * @param stats the statistics
  7859. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  7860. */
  7861. function convertToMUCStats(stats) {
  7862. return {
  7863. "bitrate_download": stats.bitrate.download,
  7864. "bitrate_upload": stats.bitrate.upload,
  7865. "packetLoss_total": stats.packetLoss.total,
  7866. "packetLoss_download": stats.packetLoss.download,
  7867. "packetLoss_upload": stats.packetLoss.upload
  7868. };
  7869. }
  7870. /**
  7871. * Converts statitistics to format used by VideoLayout
  7872. * @param stats
  7873. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  7874. */
  7875. function parseMUCStats(stats) {
  7876. return {
  7877. bitrate: {
  7878. download: stats.bitrate_download,
  7879. upload: stats.bitrate_upload
  7880. },
  7881. packetLoss: {
  7882. total: stats.packetLoss_total,
  7883. download: stats.packetLoss_download,
  7884. upload: stats.packetLoss_upload
  7885. }
  7886. };
  7887. }
  7888. var ConnectionQuality = {
  7889. init: function () {
  7890. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  7891. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  7892. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  7893. },
  7894. /**
  7895. * Updates the local statistics
  7896. * @param data new statistics
  7897. */
  7898. updateLocalStats: function (data) {
  7899. stats = data;
  7900. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  7901. if (sendIntervalId == null) {
  7902. startSendingStats();
  7903. }
  7904. },
  7905. /**
  7906. * Updates remote statistics
  7907. * @param jid the jid associated with the statistics
  7908. * @param data the statistics
  7909. */
  7910. updateRemoteStats: function (jid, data) {
  7911. if (data == null || data.packetLoss_total == null) {
  7912. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  7913. return;
  7914. }
  7915. remoteStats[jid] = parseMUCStats(data);
  7916. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  7917. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  7918. },
  7919. /**
  7920. * Stops statistics sending.
  7921. */
  7922. stopSendingStats: function () {
  7923. clearInterval(sendIntervalId);
  7924. sendIntervalId = null;
  7925. //notify UI about stopping statistics gathering
  7926. eventEmitter.emit(CQEvents.STOP);
  7927. },
  7928. /**
  7929. * Returns the local statistics.
  7930. */
  7931. getStats: function () {
  7932. return stats;
  7933. },
  7934. addListener: function (type, listener) {
  7935. eventEmitter.on(type, listener);
  7936. }
  7937. };
  7938. module.exports = ConnectionQuality;
  7939. },{"../../service/connectionquality/CQEvents":94,"../../service/xmpp/XMPPEvents":97,"events":98}],36:[function(require,module,exports){
  7940. /* global $, alert, changeLocalVideo, chrome, config, getConferenceHandler, getUserMediaWithConstraints */
  7941. /**
  7942. * Indicates that desktop stream is currently in use(for toggle purpose).
  7943. * @type {boolean}
  7944. */
  7945. var isUsingScreenStream = false;
  7946. /**
  7947. * Indicates that switch stream operation is in progress and prevent from triggering new events.
  7948. * @type {boolean}
  7949. */
  7950. var switchInProgress = false;
  7951. /**
  7952. * Method used to get screen sharing stream.
  7953. *
  7954. * @type {function (stream_callback, failure_callback}
  7955. */
  7956. var obtainDesktopStream = null;
  7957. /**
  7958. * Flag used to cache desktop sharing enabled state. Do not use directly as it can be <tt>null</tt>.
  7959. * @type {null|boolean}
  7960. */
  7961. var _desktopSharingEnabled = null;
  7962. var EventEmitter = require("events");
  7963. var eventEmitter = new EventEmitter();
  7964. var DesktopSharingEventTypes = require("../../service/desktopsharing/DesktopSharingEventTypes");
  7965. /**
  7966. * Method obtains desktop stream from WebRTC 'screen' source.
  7967. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  7968. */
  7969. function obtainWebRTCScreen(streamCallback, failCallback) {
  7970. APP.RTC.getUserMediaWithConstraints(
  7971. ['screen'],
  7972. streamCallback,
  7973. failCallback
  7974. );
  7975. }
  7976. /**
  7977. * Constructs inline install URL for Chrome desktop streaming extension.
  7978. * The 'chromeExtensionId' must be defined in config.js.
  7979. * @returns {string}
  7980. */
  7981. function getWebStoreInstallUrl()
  7982. {
  7983. return "https://chrome.google.com/webstore/detail/" + config.chromeExtensionId;
  7984. }
  7985. /**
  7986. * Checks whether extension update is required.
  7987. * @param minVersion minimal required version
  7988. * @param extVersion current extension version
  7989. * @returns {boolean}
  7990. */
  7991. function isUpdateRequired(minVersion, extVersion)
  7992. {
  7993. try
  7994. {
  7995. var s1 = minVersion.split('.');
  7996. var s2 = extVersion.split('.');
  7997. var len = Math.max(s1.length, s2.length);
  7998. for (var i = 0; i < len; i++)
  7999. {
  8000. var n1 = 0,
  8001. n2 = 0;
  8002. if (i < s1.length)
  8003. n1 = parseInt(s1[i]);
  8004. if (i < s2.length)
  8005. n2 = parseInt(s2[i]);
  8006. if (isNaN(n1) || isNaN(n2))
  8007. {
  8008. return true;
  8009. }
  8010. else if (n1 !== n2)
  8011. {
  8012. return n1 > n2;
  8013. }
  8014. }
  8015. // will happen if boths version has identical numbers in
  8016. // their components (even if one of them is longer, has more components)
  8017. return false;
  8018. }
  8019. catch (e)
  8020. {
  8021. console.error("Failed to parse extension version", e);
  8022. APP.UI.messageHandler.showError("dialog.error",
  8023. "dialog.detectext");
  8024. return true;
  8025. }
  8026. }
  8027. function checkExtInstalled(isInstalledCallback) {
  8028. if (!chrome.runtime) {
  8029. // No API, so no extension for sure
  8030. isInstalledCallback(false);
  8031. return;
  8032. }
  8033. chrome.runtime.sendMessage(
  8034. config.chromeExtensionId,
  8035. { getVersion: true },
  8036. function (response) {
  8037. if (!response || !response.version) {
  8038. // Communication failure - assume that no endpoint exists
  8039. console.warn("Extension not installed?: " + chrome.runtime.lastError);
  8040. isInstalledCallback(false);
  8041. } else {
  8042. // Check installed extension version
  8043. var extVersion = response.version;
  8044. console.log('Extension version is: ' + extVersion);
  8045. var updateRequired = isUpdateRequired(config.minChromeExtVersion, extVersion);
  8046. if (updateRequired) {
  8047. alert(
  8048. 'Jitsi Desktop Streamer requires update. ' +
  8049. 'Changes will take effect after next Chrome restart.');
  8050. }
  8051. isInstalledCallback(!updateRequired);
  8052. }
  8053. }
  8054. );
  8055. }
  8056. function doGetStreamFromExtension(streamCallback, failCallback) {
  8057. // Sends 'getStream' msg to the extension. Extension id must be defined in the config.
  8058. chrome.runtime.sendMessage(
  8059. config.chromeExtensionId,
  8060. { getStream: true, sources: config.desktopSharingSources },
  8061. function (response) {
  8062. if (!response) {
  8063. failCallback(chrome.runtime.lastError);
  8064. return;
  8065. }
  8066. console.log("Response from extension: " + response);
  8067. if (response.streamId) {
  8068. APP.RTC.getUserMediaWithConstraints(
  8069. ['desktop'],
  8070. function (stream) {
  8071. streamCallback(stream);
  8072. },
  8073. failCallback,
  8074. null, null, null,
  8075. response.streamId);
  8076. } else {
  8077. failCallback("Extension failed to get the stream");
  8078. }
  8079. }
  8080. );
  8081. }
  8082. /**
  8083. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop' stream for returned stream token.
  8084. */
  8085. function obtainScreenFromExtension(streamCallback, failCallback) {
  8086. checkExtInstalled(
  8087. function (isInstalled) {
  8088. if (isInstalled) {
  8089. doGetStreamFromExtension(streamCallback, failCallback);
  8090. } else {
  8091. chrome.webstore.install(
  8092. getWebStoreInstallUrl(),
  8093. function (arg) {
  8094. console.log("Extension installed successfully", arg);
  8095. // We need to reload the page in order to get the access to chrome.runtime
  8096. window.location.reload(false);
  8097. },
  8098. function (arg) {
  8099. console.log("Failed to install the extension", arg);
  8100. failCallback(arg);
  8101. APP.UI.messageHandler.showError("dialog.error",
  8102. "dialog.failtoinstall");
  8103. }
  8104. );
  8105. }
  8106. }
  8107. );
  8108. }
  8109. /**
  8110. * Call this method to toggle desktop sharing feature.
  8111. * @param method pass "ext" to use chrome extension for desktop capture(chrome extension required),
  8112. * pass "webrtc" to use WebRTC "screen" desktop source('chrome://flags/#enable-usermedia-screen-capture'
  8113. * must be enabled), pass any other string or nothing in order to disable this feature completely.
  8114. */
  8115. function setDesktopSharing(method) {
  8116. // Check if we are running chrome
  8117. if (!navigator.webkitGetUserMedia) {
  8118. obtainDesktopStream = null;
  8119. console.info("Desktop sharing disabled");
  8120. } else if (method == "ext") {
  8121. obtainDesktopStream = obtainScreenFromExtension;
  8122. console.info("Using Chrome extension for desktop sharing");
  8123. } else if (method == "webrtc") {
  8124. obtainDesktopStream = obtainWebRTCScreen;
  8125. console.info("Using Chrome WebRTC for desktop sharing");
  8126. }
  8127. // Reset enabled cache
  8128. _desktopSharingEnabled = null;
  8129. }
  8130. /**
  8131. * Initializes <link rel=chrome-webstore-item /> with extension id set in config.js to support inline installs.
  8132. * Host site must be selected as main website of published extension.
  8133. */
  8134. function initInlineInstalls()
  8135. {
  8136. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  8137. }
  8138. function getSwitchStreamFailed(error) {
  8139. console.error("Failed to obtain the stream to switch to", error);
  8140. switchInProgress = false;
  8141. }
  8142. function streamSwitchDone() {
  8143. switchInProgress = false;
  8144. eventEmitter.emit(
  8145. DesktopSharingEventTypes.SWITCHING_DONE,
  8146. isUsingScreenStream);
  8147. }
  8148. function newStreamCreated(stream)
  8149. {
  8150. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  8151. stream, isUsingScreenStream, streamSwitchDone);
  8152. }
  8153. module.exports = {
  8154. isUsingScreenStream: function () {
  8155. return isUsingScreenStream;
  8156. },
  8157. /**
  8158. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available and enabled.
  8159. */
  8160. isDesktopSharingEnabled: function () {
  8161. if (_desktopSharingEnabled === null) {
  8162. if (obtainDesktopStream === obtainScreenFromExtension) {
  8163. // Parse chrome version
  8164. var userAgent = navigator.userAgent.toLowerCase();
  8165. // We can assume that user agent is chrome, because it's enforced when 'ext' streaming method is set
  8166. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  8167. console.log("Chrome version" + userAgent, ver);
  8168. _desktopSharingEnabled = ver >= 34;
  8169. } else {
  8170. _desktopSharingEnabled = obtainDesktopStream === obtainWebRTCScreen;
  8171. }
  8172. }
  8173. return _desktopSharingEnabled;
  8174. },
  8175. init: function () {
  8176. setDesktopSharing(config.desktopSharing);
  8177. // Initialize Chrome extension inline installs
  8178. if (config.chromeExtensionId) {
  8179. initInlineInstalls();
  8180. }
  8181. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  8182. },
  8183. addListener: function(listener, type)
  8184. {
  8185. eventEmitter.on(type, listener);
  8186. },
  8187. removeListener: function (listener,type) {
  8188. eventEmitter.removeListener(type, listener);
  8189. },
  8190. /*
  8191. * Toggles screen sharing.
  8192. */
  8193. toggleScreenSharing: function () {
  8194. if (switchInProgress || !obtainDesktopStream) {
  8195. console.warn("Switch in progress or no method defined");
  8196. return;
  8197. }
  8198. switchInProgress = true;
  8199. if (!isUsingScreenStream)
  8200. {
  8201. // Switch to desktop stream
  8202. obtainDesktopStream(
  8203. function (stream) {
  8204. // We now use screen stream
  8205. isUsingScreenStream = true;
  8206. // Hook 'ended' event to restore camera when screen stream stops
  8207. stream.addEventListener('ended',
  8208. function (e) {
  8209. if (!switchInProgress && isUsingScreenStream) {
  8210. toggleScreenSharing();
  8211. }
  8212. }
  8213. );
  8214. newStreamCreated(stream);
  8215. },
  8216. getSwitchStreamFailed);
  8217. } else {
  8218. // Disable screen stream
  8219. APP.RTC.getUserMediaWithConstraints(
  8220. ['video'],
  8221. function (stream) {
  8222. // We are now using camera stream
  8223. isUsingScreenStream = false;
  8224. newStreamCreated(stream);
  8225. },
  8226. getSwitchStreamFailed, config.resolution || '360'
  8227. );
  8228. }
  8229. }
  8230. };
  8231. },{"../../service/desktopsharing/DesktopSharingEventTypes":95,"events":98}],37:[function(require,module,exports){
  8232. //maps keycode to character, id of popover for given function and function
  8233. var shortcuts = {
  8234. 67: {
  8235. character: "C",
  8236. id: "toggleChatPopover",
  8237. function: APP.UI.toggleChat
  8238. },
  8239. 70: {
  8240. character: "F",
  8241. id: "filmstripPopover",
  8242. function: APP.UI.toggleFilmStrip
  8243. },
  8244. 77: {
  8245. character: "M",
  8246. id: "mutePopover",
  8247. function: APP.UI.toggleAudio
  8248. },
  8249. 84: {
  8250. character: "T",
  8251. function: function() {
  8252. if(!APP.RTC.localAudio.isMuted()) {
  8253. APP.UI.toggleAudio();
  8254. }
  8255. }
  8256. },
  8257. 86: {
  8258. character: "V",
  8259. id: "toggleVideoPopover",
  8260. function: APP.UI.toggleVideo
  8261. }
  8262. };
  8263. var KeyboardShortcut = {
  8264. init: function () {
  8265. window.onkeyup = function(e) {
  8266. var keycode = e.which;
  8267. if(!($(":focus").is("input[type=text]") ||
  8268. $(":focus").is("input[type=password]") ||
  8269. $(":focus").is("textarea"))) {
  8270. if (typeof shortcuts[keycode] === "object") {
  8271. shortcuts[keycode].function();
  8272. }
  8273. else if (keycode >= "0".charCodeAt(0) &&
  8274. keycode <= "9".charCodeAt(0)) {
  8275. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8276. }
  8277. //esc while the smileys are visible hides them
  8278. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8279. APP.UI.toggleSmileys();
  8280. }
  8281. };
  8282. window.onkeydown = function(e) {
  8283. if(!($(":focus").is("input[type=text]") ||
  8284. $(":focus").is("input[type=password]") ||
  8285. $(":focus").is("textarea"))) {
  8286. if(e.which === "T".charCodeAt(0)) {
  8287. if(APP.RTC.localAudio.isMuted()) {
  8288. APP.UI.toggleAudio();
  8289. }
  8290. }
  8291. }
  8292. };
  8293. var self = this;
  8294. $('body').popover({ selector: '[data-toggle=popover]',
  8295. trigger: 'click hover',
  8296. content: function() {
  8297. return this.getAttribute("content") +
  8298. self.getShortcut(this.getAttribute("shortcut"));
  8299. }
  8300. });
  8301. },
  8302. /**
  8303. *
  8304. * @param id indicates the popover associated with the shortcut
  8305. * @returns {string} the keyboard shortcut used for the id given
  8306. */
  8307. getShortcut: function (id) {
  8308. for (var keycode in shortcuts) {
  8309. if (shortcuts.hasOwnProperty(keycode)) {
  8310. if (shortcuts[keycode].id === id) {
  8311. return " (" + shortcuts[keycode].character + ")";
  8312. }
  8313. }
  8314. }
  8315. return "";
  8316. }
  8317. };
  8318. module.exports = KeyboardShortcut;
  8319. },{}],38:[function(require,module,exports){
  8320. var email = '';
  8321. var displayName = '';
  8322. var userId;
  8323. var language = null;
  8324. function supportsLocalStorage() {
  8325. try {
  8326. return 'localStorage' in window && window.localStorage !== null;
  8327. } catch (e) {
  8328. console.log("localstorage is not supported");
  8329. return false;
  8330. }
  8331. }
  8332. function generateUniqueId() {
  8333. function _p8() {
  8334. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8335. }
  8336. return _p8() + _p8() + _p8() + _p8();
  8337. }
  8338. if (supportsLocalStorage()) {
  8339. if (!window.localStorage.jitsiMeetId) {
  8340. window.localStorage.jitsiMeetId = generateUniqueId();
  8341. console.log("generated id", window.localStorage.jitsiMeetId);
  8342. }
  8343. userId = window.localStorage.jitsiMeetId || '';
  8344. email = window.localStorage.email || '';
  8345. displayName = window.localStorage.displayname || '';
  8346. language = window.localStorage.language;
  8347. } else {
  8348. console.log("local storage is not supported");
  8349. userId = generateUniqueId();
  8350. }
  8351. var Settings =
  8352. {
  8353. setDisplayName: function (newDisplayName) {
  8354. displayName = newDisplayName;
  8355. window.localStorage.displayname = displayName;
  8356. return displayName;
  8357. },
  8358. setEmail: function (newEmail)
  8359. {
  8360. email = newEmail;
  8361. window.localStorage.email = newEmail;
  8362. return email;
  8363. },
  8364. getSettings: function () {
  8365. return {
  8366. email: email,
  8367. displayName: displayName,
  8368. uid: userId,
  8369. language: language
  8370. };
  8371. },
  8372. setLanguage: function (lang) {
  8373. language = lang;
  8374. window.localStorage.language = lang;
  8375. }
  8376. };
  8377. module.exports = Settings;
  8378. },{}],39:[function(require,module,exports){
  8379. /**
  8380. *
  8381. * @constructor
  8382. */
  8383. function SimulcastLogger(name, lvl) {
  8384. this.name = name;
  8385. this.lvl = lvl;
  8386. }
  8387. SimulcastLogger.prototype.log = function (text) {
  8388. if (this.lvl) {
  8389. console.log(text);
  8390. }
  8391. };
  8392. SimulcastLogger.prototype.info = function (text) {
  8393. if (this.lvl > 1) {
  8394. console.info(text);
  8395. }
  8396. };
  8397. SimulcastLogger.prototype.fine = function (text) {
  8398. if (this.lvl > 2) {
  8399. console.log(text);
  8400. }
  8401. };
  8402. SimulcastLogger.prototype.error = function (text) {
  8403. console.error(text);
  8404. };
  8405. module.exports = SimulcastLogger;
  8406. },{}],40:[function(require,module,exports){
  8407. var SimulcastLogger = require("./SimulcastLogger");
  8408. var SimulcastUtils = require("./SimulcastUtils");
  8409. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  8410. function SimulcastReceiver() {
  8411. this.simulcastUtils = new SimulcastUtils();
  8412. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  8413. }
  8414. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  8415. SimulcastReceiver.prototype._remoteMaps = {
  8416. msid2Quality: {},
  8417. ssrc2Msid: {},
  8418. msid2ssrc: {},
  8419. receivingVideoStreams: {}
  8420. };
  8421. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  8422. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8423. };
  8424. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  8425. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  8426. };
  8427. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  8428. var sb;
  8429. this.logger.info('Ensuring x-google-conference flag...')
  8430. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8431. // TODO(gp) do that for the audio as well as suggested by fippo.
  8432. // Add the google conference flag
  8433. sb = this.simulcastUtils._getVideoSources(lines);
  8434. sb = ['a=x-google-flag:conference'].concat(sb);
  8435. this.simulcastUtils._replaceVideoSources(lines, sb);
  8436. }
  8437. };
  8438. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  8439. this._restoreRemoteVideoSources(sb);
  8440. };
  8441. /**
  8442. * Restores the simulcast groups of the remote description. In
  8443. * transformRemoteDescription we remove those in order for the set remote
  8444. * description to succeed. The focus needs the signal the groups to new
  8445. * participants.
  8446. *
  8447. * @param desc
  8448. * @returns {*}
  8449. */
  8450. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  8451. var sb;
  8452. if (!this.simulcastUtils.isValidDescription(desc)) {
  8453. return desc;
  8454. }
  8455. if (config.enableSimulcast) {
  8456. sb = desc.sdp.split('\r\n');
  8457. this._restoreSimulcastGroups(sb);
  8458. desc = new RTCSessionDescription({
  8459. type: desc.type,
  8460. sdp: sb.join('\r\n')
  8461. });
  8462. }
  8463. return desc;
  8464. };
  8465. SimulcastUtils.prototype._ensureOrder = function (lines) {
  8466. var videoSources, sb;
  8467. videoSources = this.parseMedia(lines, ['video'])[0];
  8468. sb = this._compileVideoSources(videoSources);
  8469. this._replaceVideoSources(lines, sb);
  8470. };
  8471. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  8472. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  8473. videoSource, quality;
  8474. // (re) initialize the remote maps.
  8475. this._remoteMaps.msid2Quality = {};
  8476. this._remoteMaps.ssrc2Msid = {};
  8477. this._remoteMaps.msid2ssrc = {};
  8478. var self = this;
  8479. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  8480. remoteVideoSources.groups.forEach(function (group) {
  8481. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  8482. quality = 0;
  8483. group.ssrcs.forEach(function (ssrc) {
  8484. videoSource = remoteVideoSources.sources[ssrc];
  8485. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  8486. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  8487. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  8488. });
  8489. }
  8490. });
  8491. }
  8492. };
  8493. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  8494. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  8495. };
  8496. /**
  8497. * Returns a stream with single video track, the one currently being
  8498. * received by this endpoint.
  8499. *
  8500. * @param stream the remote simulcast stream.
  8501. * @returns {webkitMediaStream}
  8502. */
  8503. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  8504. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  8505. var self = this;
  8506. if (config.enableSimulcast) {
  8507. stream.getVideoTracks().some(function (track) {
  8508. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  8509. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  8510. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  8511. if (msid == [stream.id, track.id].join(' ')) {
  8512. electedTrack = track;
  8513. return true;
  8514. }
  8515. });
  8516. });
  8517. if (!electedTrack) {
  8518. // we don't have an elected track, choose by initial quality.
  8519. tracks = stream.getVideoTracks();
  8520. for (i = 0; i < tracks.length; i++) {
  8521. msid = [stream.id, tracks[i].id].join(' ');
  8522. if (this._remoteMaps.msid2Quality[msid] === quality) {
  8523. electedTrack = tracks[i];
  8524. break;
  8525. }
  8526. }
  8527. // TODO(gp) if the initialQuality could not be satisfied, lower
  8528. // the requirement and try again.
  8529. }
  8530. }
  8531. return (electedTrack)
  8532. ? new webkitMediaStream([electedTrack])
  8533. : stream;
  8534. };
  8535. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  8536. var resource = Strophe.getResourceFromJid(jid);
  8537. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  8538. // If we haven't receiving a "changed" event yet, then we must be receiving
  8539. // low quality (that the sender always streams).
  8540. if(!ssrc)
  8541. {
  8542. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8543. var remoteStream = remoteStreamObject.getOriginalStream();
  8544. var tracks = remoteStream.getVideoTracks();
  8545. if (tracks) {
  8546. for (var k = 0; k < tracks.length; k++) {
  8547. var track = tracks[k];
  8548. var msid = [remoteStream.id, track.id].join(' ');
  8549. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  8550. var quality = this._remoteMaps.msid2Quality[msid];
  8551. if (quality == 0) {
  8552. ssrc = _ssrc;
  8553. }
  8554. }
  8555. }
  8556. }
  8557. return ssrc;
  8558. };
  8559. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  8560. {
  8561. var sid, electedStream;
  8562. var i, j, k;
  8563. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  8564. if(jid && APP.RTC.remoteStreams[jid])
  8565. {
  8566. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8567. var remoteStream = remoteStreamObject.getOriginalStream();
  8568. var tracks = remoteStream.getVideoTracks();
  8569. if (tracks) {
  8570. for (k = 0; k < tracks.length; k++) {
  8571. var track = tracks[k];
  8572. var msid = [remoteStream.id, track.id].join(' ');
  8573. var tmp = this._remoteMaps.msid2ssrc[msid];
  8574. if (tmp == ssrc) {
  8575. electedStream = new webkitMediaStream([track]);
  8576. sid = remoteStreamObject.sid;
  8577. // stream found, stop.
  8578. break;
  8579. }
  8580. }
  8581. }
  8582. }
  8583. else
  8584. {
  8585. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  8586. }
  8587. return {
  8588. sid: sid,
  8589. stream: electedStream
  8590. };
  8591. };
  8592. /**
  8593. * Gets the fully qualified msid (stream.id + track.id) associated to the
  8594. * SSRC.
  8595. *
  8596. * @param ssrc
  8597. * @returns {*}
  8598. */
  8599. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  8600. return this._remoteMaps.ssrc2Msid[ssrc];
  8601. };
  8602. /**
  8603. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  8604. * either gets confused and thinks this is an FID group or, if an FID group
  8605. * is already present, it fails to set the remote description.
  8606. *
  8607. * @param desc
  8608. * @returns {*}
  8609. */
  8610. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  8611. if (desc && desc.sdp) {
  8612. var sb = desc.sdp.split('\r\n');
  8613. this._updateRemoteMaps(sb);
  8614. this._cacheRemoteVideoSources(sb);
  8615. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  8616. // need the simulcast group in the _updateRemoteMaps() method.
  8617. this.simulcastUtils._removeSimulcastGroup(sb);
  8618. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  8619. // We don't need the goog conference flag if we're not doing
  8620. // simulcast.
  8621. this._ensureGoogConference(sb);
  8622. }
  8623. desc = new RTCSessionDescription({
  8624. type: desc.type,
  8625. sdp: sb.join('\r\n')
  8626. });
  8627. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  8628. }
  8629. return desc;
  8630. };
  8631. module.exports = SimulcastReceiver;
  8632. },{"../../service/RTC/MediaStreamTypes":87,"./SimulcastLogger":39,"./SimulcastUtils":42}],41:[function(require,module,exports){
  8633. var SimulcastLogger = require("./SimulcastLogger");
  8634. var SimulcastUtils = require("./SimulcastUtils");
  8635. function SimulcastSender() {
  8636. this.simulcastUtils = new SimulcastUtils();
  8637. this.logger = new SimulcastLogger('SimulcastSender', 1);
  8638. }
  8639. SimulcastSender.prototype.displayedLocalVideoStream = null;
  8640. SimulcastSender.prototype._generateGuid = (function () {
  8641. function s4() {
  8642. return Math.floor((1 + Math.random()) * 0x10000)
  8643. .toString(16)
  8644. .substring(1);
  8645. }
  8646. return function () {
  8647. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  8648. s4() + '-' + s4() + s4() + s4();
  8649. };
  8650. }());
  8651. // Returns a random integer between min (included) and max (excluded)
  8652. // Using Math.round() gives a non-uniform distribution!
  8653. SimulcastSender.prototype._generateRandomSSRC = function () {
  8654. var min = 0, max = 0xffffffff;
  8655. return Math.floor(Math.random() * (max - min)) + min;
  8656. };
  8657. SimulcastSender.prototype.getLocalVideoStream = function () {
  8658. return (this.displayedLocalVideoStream != null)
  8659. ? this.displayedLocalVideoStream
  8660. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  8661. : APP.RTC.localVideo.getOriginalStream();
  8662. };
  8663. function NativeSimulcastSender() {
  8664. SimulcastSender.call(this); // call the super constructor.
  8665. }
  8666. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8667. NativeSimulcastSender.prototype._localExplosionMap = {};
  8668. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  8669. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  8670. NativeSimulcastSender.prototype.reset = function () {
  8671. this._localExplosionMap = {};
  8672. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  8673. };
  8674. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  8675. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8676. };
  8677. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  8678. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  8679. };
  8680. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  8681. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  8682. this.logger.info('Appending simulcast group...');
  8683. // Get the primary SSRC information.
  8684. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8685. // Start building the SIM SSRC group.
  8686. ssrcGroup = ['a=ssrc-group:SIM'];
  8687. // The video source buffer.
  8688. sb = [];
  8689. // Create the simulcast sub-streams.
  8690. for (i = 0; i < numOfSubs; i++) {
  8691. // TODO(gp) prevent SSRC collision.
  8692. simSSRC = this._generateRandomSSRC();
  8693. ssrcGroup.push(simSSRC);
  8694. if (videoSources.base) {
  8695. sb.splice.apply(sb, [sb.length, 0].concat(
  8696. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  8697. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  8698. ));
  8699. }
  8700. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  8701. }
  8702. // Add the group sim layers.
  8703. sb.splice(0, 0, ssrcGroup.join(' '))
  8704. this.simulcastUtils._replaceVideoSources(lines, sb);
  8705. };
  8706. // Does the actual patching.
  8707. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  8708. this.logger.info('Ensuring simulcast group...');
  8709. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8710. this._appendSimulcastGroup(lines);
  8711. this._cacheLocalVideoSources(lines);
  8712. } else {
  8713. // verify that the ssrcs participating in the SIM group are present
  8714. // in the SDP (needed for presence).
  8715. this._restoreLocalVideoSources(lines);
  8716. }
  8717. };
  8718. /**
  8719. * Produces a single stream with multiple tracks for local video sources.
  8720. *
  8721. * @param lines
  8722. * @private
  8723. */
  8724. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  8725. var sb, msid, sid, tid, videoSources, self;
  8726. this.logger.info('Exploding local video sources...');
  8727. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8728. self = this;
  8729. if (videoSources.groups && videoSources.groups.length !== 0) {
  8730. videoSources.groups.forEach(function (group) {
  8731. if (group.semantics === 'SIM') {
  8732. group.ssrcs.forEach(function (ssrc) {
  8733. // Get the msid for this ssrc..
  8734. if (self._localExplosionMap[ssrc]) {
  8735. // .. either from the explosion map..
  8736. msid = self._localExplosionMap[ssrc];
  8737. } else {
  8738. // .. or generate a new one (msid).
  8739. sid = videoSources.sources[ssrc].msid
  8740. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  8741. tid = self._generateGuid();
  8742. msid = [sid, tid].join(' ');
  8743. self._localExplosionMap[ssrc] = msid;
  8744. }
  8745. // Assign it to the source object.
  8746. videoSources.sources[ssrc].msid = msid;
  8747. // TODO(gp) Change the msid of associated sources.
  8748. });
  8749. }
  8750. });
  8751. }
  8752. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8753. this.simulcastUtils._replaceVideoSources(lines, sb);
  8754. };
  8755. /**
  8756. * GUM for simulcast.
  8757. *
  8758. * @param constraints
  8759. * @param success
  8760. * @param err
  8761. */
  8762. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8763. // There's nothing special to do for native simulcast, so just do a normal GUM.
  8764. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8765. success(hqStream);
  8766. }, err);
  8767. };
  8768. /**
  8769. * Prepares the local description for public usage (i.e. to be signaled
  8770. * through Jingle to the focus).
  8771. *
  8772. * @param desc
  8773. * @returns {RTCSessionDescription}
  8774. */
  8775. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8776. var sb;
  8777. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8778. return desc;
  8779. }
  8780. sb = desc.sdp.split('\r\n');
  8781. this._explodeSimulcastSenderSources(sb);
  8782. desc = new RTCSessionDescription({
  8783. type: desc.type,
  8784. sdp: sb.join('\r\n')
  8785. });
  8786. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  8787. return desc;
  8788. };
  8789. /**
  8790. * Ensures that the simulcast group is present in the answer, _if_ native
  8791. * simulcast is enabled,
  8792. *
  8793. * @param desc
  8794. * @returns {*}
  8795. */
  8796. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  8797. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8798. return desc;
  8799. }
  8800. var sb = desc.sdp.split('\r\n');
  8801. // Even if we have enabled native simulcasting previously
  8802. // (with a call to SLD with an appropriate SDP, for example),
  8803. // createAnswer seems to consistently generate incomplete SDP
  8804. // with missing SSRCS.
  8805. //
  8806. // So, subsequent calls to SLD will have missing SSRCS and presence
  8807. // won't have the complete list of SRCs.
  8808. this._ensureSimulcastGroup(sb);
  8809. desc = new RTCSessionDescription({
  8810. type: desc.type,
  8811. sdp: sb.join('\r\n')
  8812. });
  8813. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  8814. return desc;
  8815. };
  8816. /**
  8817. *
  8818. *
  8819. * @param desc
  8820. * @returns {*}
  8821. */
  8822. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8823. return desc;
  8824. };
  8825. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8826. // Nothing to do here, native simulcast does that auto-magically.
  8827. };
  8828. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  8829. function SimpleSimulcastSender() {
  8830. SimulcastSender.call(this);
  8831. }
  8832. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8833. SimpleSimulcastSender.prototype.localStream = null;
  8834. SimpleSimulcastSender.prototype._localMaps = {
  8835. msids: [],
  8836. msid2ssrc: {}
  8837. };
  8838. /**
  8839. * Groups local video sources together in the ssrc-group:SIM group.
  8840. *
  8841. * @param lines
  8842. * @private
  8843. */
  8844. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  8845. var sb, videoSources, ssrcs = [], ssrc;
  8846. this.logger.info('Grouping local video sources...');
  8847. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8848. for (ssrc in videoSources.sources) {
  8849. // jitsi-meet destroys/creates streams at various places causing
  8850. // the original local stream ids to change. The only thing that
  8851. // remains unchanged is the trackid.
  8852. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  8853. }
  8854. var self = this;
  8855. // TODO(gp) add only "free" sources.
  8856. this._localMaps.msids.forEach(function (msid) {
  8857. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  8858. });
  8859. if (!videoSources.groups) {
  8860. videoSources.groups = [];
  8861. }
  8862. videoSources.groups.push({
  8863. 'semantics': 'SIM',
  8864. 'ssrcs': ssrcs
  8865. });
  8866. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8867. this.simulcastUtils._replaceVideoSources(lines, sb);
  8868. };
  8869. /**
  8870. * GUM for simulcast.
  8871. *
  8872. * @param constraints
  8873. * @param success
  8874. * @param err
  8875. */
  8876. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8877. // TODO(gp) what if we request a resolution not supported by the hardware?
  8878. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  8879. var lqConstraints = {
  8880. audio: false,
  8881. video: {
  8882. mandatory: {
  8883. maxWidth: 320,
  8884. maxHeight: 180,
  8885. maxFrameRate: 15
  8886. }
  8887. }
  8888. };
  8889. this.logger.info('HQ constraints: ', constraints);
  8890. this.logger.info('LQ constraints: ', lqConstraints);
  8891. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  8892. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  8893. // reason appears to be that Chrome only acquires the cam once and
  8894. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  8895. var self = this;
  8896. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8897. self.localStream = hqStream;
  8898. // reset local maps.
  8899. self._localMaps.msids = [];
  8900. self._localMaps.msid2ssrc = {};
  8901. // add hq trackid to local map
  8902. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  8903. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  8904. self.displayedLocalVideoStream = lqStream;
  8905. // NOTE(gp) The specification says Array.forEach() will visit
  8906. // the array elements in numeric order, and that it doesn't
  8907. // visit elements that don't exist.
  8908. // add lq trackid to local map
  8909. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  8910. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  8911. success(self.localStream);
  8912. }, err);
  8913. }, err);
  8914. };
  8915. /**
  8916. * Prepares the local description for public usage (i.e. to be signaled
  8917. * through Jingle to the focus).
  8918. *
  8919. * @param desc
  8920. * @returns {RTCSessionDescription}
  8921. */
  8922. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8923. var sb;
  8924. if (!this.simulcastUtils.isValidDescription(desc)) {
  8925. return desc;
  8926. }
  8927. sb = desc.sdp.split('\r\n');
  8928. this._groupLocalVideoSources(sb);
  8929. desc = new RTCSessionDescription({
  8930. type: desc.type,
  8931. sdp: sb.join('\r\n')
  8932. });
  8933. this.logger.fine('Grouped local video sources');
  8934. this.logger.fine(desc.sdp);
  8935. return desc;
  8936. };
  8937. /**
  8938. * Ensures that the simulcast group is present in the answer, _if_ native
  8939. * simulcast is enabled,
  8940. *
  8941. * @param desc
  8942. * @returns {*}
  8943. */
  8944. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  8945. return desc;
  8946. };
  8947. /**
  8948. *
  8949. *
  8950. * @param desc
  8951. * @returns {*}
  8952. */
  8953. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8954. var sb = desc.sdp.split('\r\n');
  8955. this.simulcastUtils._removeSimulcastGroup(sb);
  8956. desc = new RTCSessionDescription({
  8957. type: desc.type,
  8958. sdp: sb.join('\r\n')
  8959. });
  8960. this.logger.fine('Transformed local description');
  8961. this.logger.fine(desc.sdp);
  8962. return desc;
  8963. };
  8964. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8965. var trackid;
  8966. var self = this;
  8967. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  8968. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  8969. // Search for the track id that corresponds to the ssrc
  8970. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  8971. trackid = tid;
  8972. return true;
  8973. }
  8974. }) && self.localStream.getVideoTracks().some(function (track) {
  8975. // Start/stop the track that corresponds to the track id
  8976. if (track.id === trackid) {
  8977. track.enabled = enabled;
  8978. return true;
  8979. }
  8980. })) {
  8981. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  8982. $(document).trigger(enabled
  8983. ? 'simulcastlayerstarted'
  8984. : 'simulcastlayerstopped');
  8985. } else {
  8986. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  8987. }
  8988. };
  8989. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  8990. function NoSimulcastSender() {
  8991. SimulcastSender.call(this);
  8992. }
  8993. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8994. /**
  8995. * GUM for simulcast.
  8996. *
  8997. * @param constraints
  8998. * @param success
  8999. * @param err
  9000. */
  9001. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9002. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9003. success(hqStream);
  9004. }, err);
  9005. };
  9006. /**
  9007. * Prepares the local description for public usage (i.e. to be signaled
  9008. * through Jingle to the focus).
  9009. *
  9010. * @param desc
  9011. * @returns {RTCSessionDescription}
  9012. */
  9013. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9014. return desc;
  9015. };
  9016. /**
  9017. * Ensures that the simulcast group is present in the answer, _if_ native
  9018. * simulcast is enabled,
  9019. *
  9020. * @param desc
  9021. * @returns {*}
  9022. */
  9023. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  9024. return desc;
  9025. };
  9026. /**
  9027. *
  9028. *
  9029. * @param desc
  9030. * @returns {*}
  9031. */
  9032. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9033. return desc;
  9034. };
  9035. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9036. };
  9037. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  9038. module.exports = {
  9039. "native": NativeSimulcastSender,
  9040. "no": NoSimulcastSender
  9041. }
  9042. },{"./SimulcastLogger":39,"./SimulcastUtils":42}],42:[function(require,module,exports){
  9043. var SimulcastLogger = require("./SimulcastLogger");
  9044. /**
  9045. *
  9046. * @constructor
  9047. */
  9048. function SimulcastUtils() {
  9049. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  9050. }
  9051. /**
  9052. *
  9053. * @type {{}}
  9054. * @private
  9055. */
  9056. SimulcastUtils.prototype._emptyCompoundIndex = {};
  9057. /**
  9058. *
  9059. * @param lines
  9060. * @param videoSources
  9061. * @private
  9062. */
  9063. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  9064. var i, inVideo = false, index = -1, howMany = 0;
  9065. this.logger.info('Replacing video sources...');
  9066. for (i = 0; i < lines.length; i++) {
  9067. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9068. // Out of video.
  9069. break;
  9070. }
  9071. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9072. // In video.
  9073. inVideo = true;
  9074. }
  9075. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  9076. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  9077. if (index === -1) {
  9078. index = i;
  9079. }
  9080. howMany++;
  9081. }
  9082. }
  9083. // efficiency baby ;)
  9084. lines.splice.apply(lines,
  9085. [index, howMany].concat(videoSources));
  9086. };
  9087. SimulcastUtils.prototype.isValidDescription = function (desc)
  9088. {
  9089. return desc && desc != null
  9090. && desc.type && desc.type != ''
  9091. && desc.sdp && desc.sdp != '';
  9092. };
  9093. SimulcastUtils.prototype._getVideoSources = function (lines) {
  9094. var i, inVideo = false, sb = [];
  9095. this.logger.info('Getting video sources...');
  9096. for (i = 0; i < lines.length; i++) {
  9097. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9098. // Out of video.
  9099. break;
  9100. }
  9101. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9102. // In video.
  9103. inVideo = true;
  9104. }
  9105. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9106. // In SSRC.
  9107. sb.push(lines[i]);
  9108. }
  9109. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9110. sb.push(lines[i]);
  9111. }
  9112. }
  9113. return sb;
  9114. };
  9115. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  9116. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  9117. ssrc_attribute, group, semantics, skip = true;
  9118. this.logger.info('Parsing media sources...');
  9119. for (i = 0; i < lines.length; i++) {
  9120. if (lines[i].substring(0, 'm='.length) === 'm=') {
  9121. type = lines[i]
  9122. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  9123. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  9124. if (!skip) {
  9125. cur_media = {
  9126. 'type': type,
  9127. 'sources': {},
  9128. 'groups': []
  9129. };
  9130. res.push(cur_media);
  9131. }
  9132. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9133. idx = lines[i].indexOf(' ');
  9134. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  9135. if (cur_media.sources[ssrc] === undefined) {
  9136. cur_ssrc = {'ssrc': ssrc};
  9137. cur_media.sources[ssrc] = cur_ssrc;
  9138. }
  9139. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  9140. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  9141. if (cur_media.base === undefined) {
  9142. cur_media.base = cur_ssrc;
  9143. }
  9144. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9145. idx = lines[i].indexOf(' ');
  9146. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  9147. ssrcs = lines[i].substr(idx).trim().split(' ');
  9148. group = {
  9149. 'semantics': semantics,
  9150. 'ssrcs': ssrcs
  9151. };
  9152. cur_media.groups.push(group);
  9153. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  9154. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  9155. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  9156. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  9157. cur_media.direction = lines[i].substring('a='.length);
  9158. }
  9159. }
  9160. return res;
  9161. };
  9162. /**
  9163. * The _indexOfArray() method returns the first a CompoundIndex at which a
  9164. * given element can be found in the array, or _emptyCompoundIndex if it is
  9165. * not present.
  9166. *
  9167. * Example:
  9168. *
  9169. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  9170. *
  9171. * returns {row: 2, column: 14}
  9172. *
  9173. * @param needle
  9174. * @param haystack
  9175. * @param start
  9176. * @returns {}
  9177. * @private
  9178. */
  9179. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  9180. var length = haystack.length, idx, i;
  9181. if (!start) {
  9182. start = 0;
  9183. }
  9184. for (i = start; i < length; i++) {
  9185. idx = haystack[i].indexOf(needle);
  9186. if (idx !== -1) {
  9187. return {row: i, column: idx};
  9188. }
  9189. }
  9190. return this._emptyCompoundIndex;
  9191. };
  9192. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  9193. var i;
  9194. for (i = lines.length - 1; i >= 0; i--) {
  9195. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  9196. lines.splice(i, 1);
  9197. }
  9198. }
  9199. };
  9200. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  9201. var sb = [], ssrc, addedSSRCs = [];
  9202. this.logger.info('Compiling video sources...');
  9203. // Add the groups
  9204. if (videoSources.groups && videoSources.groups.length !== 0) {
  9205. videoSources.groups.forEach(function (group) {
  9206. if (group.ssrcs && group.ssrcs.length !== 0) {
  9207. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  9208. // if (group.semantics !== 'SIM') {
  9209. group.ssrcs.forEach(function (ssrc) {
  9210. addedSSRCs.push(ssrc);
  9211. sb.splice.apply(sb, [sb.length, 0].concat([
  9212. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9213. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9214. });
  9215. //}
  9216. }
  9217. });
  9218. }
  9219. // Then add any free sources.
  9220. if (videoSources.sources) {
  9221. for (ssrc in videoSources.sources) {
  9222. if (addedSSRCs.indexOf(ssrc) === -1) {
  9223. sb.splice.apply(sb, [sb.length, 0].concat([
  9224. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9225. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9226. }
  9227. }
  9228. }
  9229. return sb;
  9230. };
  9231. module.exports = SimulcastUtils;
  9232. },{"./SimulcastLogger":39}],43:[function(require,module,exports){
  9233. /*jslint plusplus: true */
  9234. /*jslint nomen: true*/
  9235. var SimulcastSender = require("./SimulcastSender");
  9236. var NoSimulcastSender = SimulcastSender["no"];
  9237. var NativeSimulcastSender = SimulcastSender["native"];
  9238. var SimulcastReceiver = require("./SimulcastReceiver");
  9239. var SimulcastUtils = require("./SimulcastUtils");
  9240. var RTCEvents = require("../../service/RTC/RTCEvents");
  9241. /**
  9242. *
  9243. * @constructor
  9244. */
  9245. function SimulcastManager() {
  9246. // Create the simulcast utilities.
  9247. this.simulcastUtils = new SimulcastUtils();
  9248. // Create remote simulcast.
  9249. this.simulcastReceiver = new SimulcastReceiver();
  9250. // Initialize local simulcast.
  9251. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  9252. // account constraints.
  9253. if (!config.enableSimulcast) {
  9254. this.simulcastSender = new NoSimulcastSender();
  9255. } else {
  9256. var isChromium = window.chrome,
  9257. vendorName = window.navigator.vendor;
  9258. if(isChromium !== null && isChromium !== undefined
  9259. /* skip opera */
  9260. && vendorName === "Google Inc."
  9261. /* skip Chromium as suggested by fippo */
  9262. && !window.navigator.appVersion.match(/Chromium\//) ) {
  9263. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  9264. if (ver > 37) {
  9265. this.simulcastSender = new NativeSimulcastSender();
  9266. } else {
  9267. this.simulcastSender = new NoSimulcastSender();
  9268. }
  9269. } else {
  9270. this.simulcastSender = new NoSimulcastSender();
  9271. }
  9272. }
  9273. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  9274. function (endpointSimulcastLayers) {
  9275. endpointSimulcastLayers.forEach(function (esl) {
  9276. var ssrc = esl.simulcastLayer.primarySSRC;
  9277. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  9278. });
  9279. });
  9280. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  9281. var ssrc = simulcastLayer.primarySSRC;
  9282. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  9283. });
  9284. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  9285. var ssrc = simulcastLayer.primarySSRC;
  9286. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  9287. });
  9288. }
  9289. /**
  9290. * Restores the simulcast groups of the remote description. In
  9291. * transformRemoteDescription we remove those in order for the set remote
  9292. * description to succeed. The focus needs the signal the groups to new
  9293. * participants.
  9294. *
  9295. * @param desc
  9296. * @returns {*}
  9297. */
  9298. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  9299. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  9300. };
  9301. /**
  9302. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9303. * either gets confused and thinks this is an FID group or, if an FID group
  9304. * is already present, it fails to set the remote description.
  9305. *
  9306. * @param desc
  9307. * @returns {*}
  9308. */
  9309. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  9310. return this.simulcastReceiver.transformRemoteDescription(desc);
  9311. };
  9312. /**
  9313. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9314. * SSRC.
  9315. *
  9316. * @param ssrc
  9317. * @returns {*}
  9318. */
  9319. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9320. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  9321. };
  9322. /**
  9323. * Returns a stream with single video track, the one currently being
  9324. * received by this endpoint.
  9325. *
  9326. * @param stream the remote simulcast stream.
  9327. * @returns {webkitMediaStream}
  9328. */
  9329. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  9330. return this.simulcastReceiver.getReceivingVideoStream(stream);
  9331. };
  9332. /**
  9333. *
  9334. *
  9335. * @param desc
  9336. * @returns {*}
  9337. */
  9338. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  9339. return this.simulcastSender.transformLocalDescription(desc);
  9340. };
  9341. /**
  9342. *
  9343. * @returns {*}
  9344. */
  9345. SimulcastManager.prototype.getLocalVideoStream = function() {
  9346. return this.simulcastSender.getLocalVideoStream();
  9347. };
  9348. /**
  9349. * GUM for simulcast.
  9350. *
  9351. * @param constraints
  9352. * @param success
  9353. * @param err
  9354. */
  9355. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  9356. this.simulcastSender.getUserMedia(constraints, success, err);
  9357. };
  9358. /**
  9359. * Prepares the local description for public usage (i.e. to be signaled
  9360. * through Jingle to the focus).
  9361. *
  9362. * @param desc
  9363. * @returns {RTCSessionDescription}
  9364. */
  9365. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  9366. return this.simulcastSender.reverseTransformLocalDescription(desc);
  9367. };
  9368. /**
  9369. * Ensures that the simulcast group is present in the answer, _if_ native
  9370. * simulcast is enabled,
  9371. *
  9372. * @param desc
  9373. * @returns {*}
  9374. */
  9375. SimulcastManager.prototype.transformAnswer = function (desc) {
  9376. return this.simulcastSender.transformAnswer(desc);
  9377. };
  9378. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  9379. return this.simulcastReceiver.getReceivingSSRC(jid);
  9380. };
  9381. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  9382. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  9383. };
  9384. /**
  9385. *
  9386. * @param lines
  9387. * @param mediatypes
  9388. * @returns {*}
  9389. */
  9390. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  9391. var sb = lines.sdp.split('\r\n');
  9392. return this.simulcastUtils.parseMedia(sb, mediatypes);
  9393. };
  9394. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  9395. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  9396. };
  9397. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  9398. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  9399. };
  9400. SimulcastManager.prototype.resetSender = function() {
  9401. if (typeof this.simulcastSender.reset === 'function'){
  9402. this.simulcastSender.reset();
  9403. }
  9404. };
  9405. var simulcast = new SimulcastManager();
  9406. module.exports = simulcast;
  9407. },{"../../service/RTC/RTCEvents":89,"./SimulcastReceiver":40,"./SimulcastSender":41,"./SimulcastUtils":42}],44:[function(require,module,exports){
  9408. /**
  9409. * Provides statistics for the local stream.
  9410. */
  9411. /**
  9412. * Size of the webaudio analizer buffer.
  9413. * @type {number}
  9414. */
  9415. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  9416. /**
  9417. * Value of the webaudio analizer smoothing time parameter.
  9418. * @type {number}
  9419. */
  9420. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  9421. /**
  9422. * Converts time domain data array to audio level.
  9423. * @param array the time domain data array.
  9424. * @returns {number} the audio level
  9425. */
  9426. function timeDomainDataToAudioLevel(samples) {
  9427. var maxVolume = 0;
  9428. var length = samples.length;
  9429. for (var i = 0; i < length; i++) {
  9430. if (maxVolume < samples[i])
  9431. maxVolume = samples[i];
  9432. }
  9433. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  9434. };
  9435. /**
  9436. * Animates audio level change
  9437. * @param newLevel the new audio level
  9438. * @param lastLevel the last audio level
  9439. * @returns {Number} the audio level to be set
  9440. */
  9441. function animateLevel(newLevel, lastLevel)
  9442. {
  9443. var value = 0;
  9444. var diff = lastLevel - newLevel;
  9445. if(diff > 0.2)
  9446. {
  9447. value = lastLevel - 0.2;
  9448. }
  9449. else if(diff < -0.4)
  9450. {
  9451. value = lastLevel + 0.4;
  9452. }
  9453. else
  9454. {
  9455. value = newLevel;
  9456. }
  9457. return parseFloat(value.toFixed(3));
  9458. }
  9459. /**
  9460. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  9461. *
  9462. * @param stream the local stream
  9463. * @param interval stats refresh interval given in ms.
  9464. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  9465. * update.
  9466. * @constructor
  9467. */
  9468. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  9469. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  9470. this.stream = stream;
  9471. this.intervalId = null;
  9472. this.intervalMilis = interval;
  9473. this.eventEmitter = eventEmitter;
  9474. this.audioLevel = 0;
  9475. this.statisticsService = statisticsService;
  9476. }
  9477. /**
  9478. * Starts the collecting the statistics.
  9479. */
  9480. LocalStatsCollector.prototype.start = function () {
  9481. if (config.disableAudioLevels || !window.AudioContext)
  9482. return;
  9483. var context = new AudioContext();
  9484. var analyser = context.createAnalyser();
  9485. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  9486. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  9487. var source = context.createMediaStreamSource(this.stream);
  9488. source.connect(analyser);
  9489. var self = this;
  9490. this.intervalId = setInterval(
  9491. function () {
  9492. var array = new Uint8Array(analyser.frequencyBinCount);
  9493. analyser.getByteTimeDomainData(array);
  9494. var audioLevel = timeDomainDataToAudioLevel(array);
  9495. if(audioLevel != self.audioLevel) {
  9496. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  9497. self.eventEmitter.emit(
  9498. "statistics.audioLevel",
  9499. self.statisticsService.LOCAL_JID,
  9500. self.audioLevel);
  9501. }
  9502. },
  9503. this.intervalMilis
  9504. );
  9505. };
  9506. /**
  9507. * Stops collecting the statistics.
  9508. */
  9509. LocalStatsCollector.prototype.stop = function () {
  9510. if (this.intervalId) {
  9511. clearInterval(this.intervalId);
  9512. this.intervalId = null;
  9513. }
  9514. };
  9515. module.exports = LocalStatsCollector;
  9516. },{}],45:[function(require,module,exports){
  9517. /* global ssrc2jid */
  9518. /* jshint -W117 */
  9519. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9520. /**
  9521. * Calculates packet lost percent using the number of lost packets and the
  9522. * number of all packet.
  9523. * @param lostPackets the number of lost packets
  9524. * @param totalPackets the number of all packets.
  9525. * @returns {number} packet loss percent
  9526. */
  9527. function calculatePacketLoss(lostPackets, totalPackets) {
  9528. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  9529. return 0;
  9530. return Math.round((lostPackets/totalPackets)*100);
  9531. }
  9532. function getStatValue(item, name) {
  9533. if(!keyMap[APP.RTC.getBrowserType()][name])
  9534. throw "The property isn't supported!";
  9535. var key = keyMap[APP.RTC.getBrowserType()][name];
  9536. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  9537. }
  9538. /**
  9539. * Peer statistics data holder.
  9540. * @constructor
  9541. */
  9542. function PeerStats()
  9543. {
  9544. this.ssrc2Loss = {};
  9545. this.ssrc2AudioLevel = {};
  9546. this.ssrc2bitrate = {};
  9547. this.ssrc2resolution = {};
  9548. }
  9549. /**
  9550. * The bandwidth
  9551. * @type {{}}
  9552. */
  9553. PeerStats.bandwidth = {};
  9554. /**
  9555. * The bit rate
  9556. * @type {{}}
  9557. */
  9558. PeerStats.bitrate = {};
  9559. /**
  9560. * The packet loss rate
  9561. * @type {{}}
  9562. */
  9563. PeerStats.packetLoss = null;
  9564. /**
  9565. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  9566. * represented by this instance.
  9567. * @param ssrc audio or video RTP stream SSRC.
  9568. * @param lossRate new packet loss rate value to be set.
  9569. */
  9570. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  9571. {
  9572. this.ssrc2Loss[ssrc] = lossRate;
  9573. };
  9574. /**
  9575. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  9576. * represented by this instance.
  9577. * @param ssrc audio or video RTP stream SSRC.
  9578. * @param resolution new resolution value to be set.
  9579. */
  9580. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  9581. {
  9582. if(resolution === null && this.ssrc2resolution[ssrc])
  9583. {
  9584. delete this.ssrc2resolution[ssrc];
  9585. }
  9586. else if(resolution !== null)
  9587. this.ssrc2resolution[ssrc] = resolution;
  9588. };
  9589. /**
  9590. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  9591. * represented by this instance.
  9592. * @param ssrc audio or video RTP stream SSRC.
  9593. * @param bitrate new bitrate value to be set.
  9594. */
  9595. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  9596. {
  9597. if(this.ssrc2bitrate[ssrc])
  9598. {
  9599. this.ssrc2bitrate[ssrc].download += bitrate.download;
  9600. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  9601. }
  9602. else {
  9603. this.ssrc2bitrate[ssrc] = bitrate;
  9604. }
  9605. };
  9606. /**
  9607. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  9608. * the stream which belongs to the peer represented by this instance.
  9609. * @param ssrc RTP stream SSRC for which current audio level value will be
  9610. * updated.
  9611. * @param audioLevel the new audio level value to be set. Value is truncated to
  9612. * fit the range from 0 to 1.
  9613. */
  9614. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  9615. {
  9616. // Range limit 0 - 1
  9617. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  9618. };
  9619. function formatAudioLevel(audioLevel) {
  9620. return Math.min(Math.max(audioLevel, 0), 1);
  9621. }
  9622. /**
  9623. * Array with the transport information.
  9624. * @type {Array}
  9625. */
  9626. PeerStats.transport = [];
  9627. /**
  9628. * <tt>StatsCollector</tt> registers for stats updates of given
  9629. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  9630. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  9631. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9632. * instance as an event source.
  9633. *
  9634. * @param peerconnection webRTC peer connection object.
  9635. * @param interval stats refresh interval given in ms.
  9636. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  9637. * called on stats update.
  9638. * @constructor
  9639. */
  9640. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  9641. {
  9642. this.peerconnection = peerconnection;
  9643. this.baselineAudioLevelsReport = null;
  9644. this.currentAudioLevelsReport = null;
  9645. this.currentStatsReport = null;
  9646. this.baselineStatsReport = null;
  9647. this.audioLevelsIntervalId = null;
  9648. this.eventEmitter = eventEmitter;
  9649. /**
  9650. * Gather PeerConnection stats once every this many milliseconds.
  9651. */
  9652. this.GATHER_INTERVAL = 15000;
  9653. /**
  9654. * Log stats via the focus once every this many milliseconds.
  9655. */
  9656. this.LOG_INTERVAL = 60000;
  9657. /**
  9658. * Gather stats and store them in this.statsToBeLogged.
  9659. */
  9660. this.gatherStatsIntervalId = null;
  9661. /**
  9662. * Send the stats already saved in this.statsToBeLogged to be logged via
  9663. * the focus.
  9664. */
  9665. this.logStatsIntervalId = null;
  9666. /**
  9667. * Stores the statistics which will be send to the focus to be logged.
  9668. */
  9669. this.statsToBeLogged =
  9670. {
  9671. timestamps: [],
  9672. stats: {}
  9673. };
  9674. // Updates stats interval
  9675. this.audioLevelsIntervalMilis = audioLevelsInterval;
  9676. this.statsIntervalId = null;
  9677. this.statsIntervalMilis = statsInterval;
  9678. // Map of jids to PeerStats
  9679. this.jid2stats = {};
  9680. }
  9681. module.exports = StatsCollector;
  9682. /**
  9683. * Stops stats updates.
  9684. */
  9685. StatsCollector.prototype.stop = function () {
  9686. if (this.audioLevelsIntervalId) {
  9687. clearInterval(this.audioLevelsIntervalId);
  9688. this.audioLevelsIntervalId = null;
  9689. }
  9690. if (this.statsIntervalId)
  9691. {
  9692. clearInterval(this.statsIntervalId);
  9693. this.statsIntervalId = null;
  9694. }
  9695. if(this.logStatsIntervalId)
  9696. {
  9697. clearInterval(this.logStatsIntervalId);
  9698. this.logStatsIntervalId = null;
  9699. }
  9700. if(this.gatherStatsIntervalId)
  9701. {
  9702. clearInterval(this.gatherStatsIntervalId);
  9703. this.gatherStatsIntervalId = null;
  9704. }
  9705. };
  9706. /**
  9707. * Callback passed to <tt>getStats</tt> method.
  9708. * @param error an error that occurred on <tt>getStats</tt> call.
  9709. */
  9710. StatsCollector.prototype.errorCallback = function (error)
  9711. {
  9712. console.error("Get stats error", error);
  9713. this.stop();
  9714. };
  9715. /**
  9716. * Starts stats updates.
  9717. */
  9718. StatsCollector.prototype.start = function ()
  9719. {
  9720. var self = this;
  9721. if(!config.disableAudioLevels) {
  9722. this.audioLevelsIntervalId = setInterval(
  9723. function () {
  9724. // Interval updates
  9725. self.peerconnection.getStats(
  9726. function (report) {
  9727. var results = null;
  9728. if (!report || !report.result ||
  9729. typeof report.result != 'function') {
  9730. results = report;
  9731. }
  9732. else {
  9733. results = report.result();
  9734. }
  9735. //console.error("Got interval report", results);
  9736. self.currentAudioLevelsReport = results;
  9737. self.processAudioLevelReport();
  9738. self.baselineAudioLevelsReport =
  9739. self.currentAudioLevelsReport;
  9740. },
  9741. self.errorCallback
  9742. );
  9743. },
  9744. self.audioLevelsIntervalMilis
  9745. );
  9746. }
  9747. if(!config.disableStats) {
  9748. this.statsIntervalId = setInterval(
  9749. function () {
  9750. // Interval updates
  9751. self.peerconnection.getStats(
  9752. function (report) {
  9753. var results = null;
  9754. if (!report || !report.result ||
  9755. typeof report.result != 'function') {
  9756. //firefox
  9757. results = report;
  9758. }
  9759. else {
  9760. //chrome
  9761. results = report.result();
  9762. }
  9763. //console.error("Got interval report", results);
  9764. self.currentStatsReport = results;
  9765. try {
  9766. self.processStatsReport();
  9767. }
  9768. catch (e) {
  9769. console.error("Unsupported key:" + e, e);
  9770. }
  9771. self.baselineStatsReport = self.currentStatsReport;
  9772. },
  9773. self.errorCallback
  9774. );
  9775. },
  9776. self.statsIntervalMilis
  9777. );
  9778. }
  9779. if (config.logStats) {
  9780. this.gatherStatsIntervalId = setInterval(
  9781. function () {
  9782. self.peerconnection.getStats(
  9783. function (report) {
  9784. self.addStatsToBeLogged(report.result());
  9785. },
  9786. function () {
  9787. }
  9788. );
  9789. },
  9790. this.GATHER_INTERVAL
  9791. );
  9792. this.logStatsIntervalId = setInterval(
  9793. function() { self.logStats(); },
  9794. this.LOG_INTERVAL);
  9795. }
  9796. };
  9797. /**
  9798. * Checks whether a certain record should be included in the logged statistics.
  9799. */
  9800. function acceptStat(reportId, reportType, statName) {
  9801. if (reportType == "googCandidatePair" && statName == "googChannelId")
  9802. return false;
  9803. if (reportType == "ssrc") {
  9804. if (statName == "googTrackId" ||
  9805. statName == "transportId" ||
  9806. statName == "ssrc")
  9807. return false;
  9808. }
  9809. return true;
  9810. }
  9811. /**
  9812. * Checks whether a certain record should be included in the logged statistics.
  9813. */
  9814. function acceptReport(id, type) {
  9815. if (id.substring(0, 15) == "googCertificate" ||
  9816. id.substring(0, 9) == "googTrack" ||
  9817. id.substring(0, 20) == "googLibjingleSession")
  9818. return false;
  9819. if (type == "googComponent")
  9820. return false;
  9821. return true;
  9822. }
  9823. /**
  9824. * Converts the stats to the format used for logging, and saves the data in
  9825. * this.statsToBeLogged.
  9826. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  9827. */
  9828. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  9829. var self = this;
  9830. var num_records = this.statsToBeLogged.timestamps.length;
  9831. this.statsToBeLogged.timestamps.push(new Date().getTime());
  9832. reports.map(function (report) {
  9833. if (!acceptReport(report.id, report.type))
  9834. return;
  9835. var stat = self.statsToBeLogged.stats[report.id];
  9836. if (!stat) {
  9837. stat = self.statsToBeLogged.stats[report.id] = {};
  9838. }
  9839. stat.type = report.type;
  9840. report.names().map(function (name) {
  9841. if (!acceptStat(report.id, report.type, name))
  9842. return;
  9843. var values = stat[name];
  9844. if (!values) {
  9845. values = stat[name] = [];
  9846. }
  9847. while (values.length < num_records) {
  9848. values.push(null);
  9849. }
  9850. values.push(report.stat(name));
  9851. });
  9852. });
  9853. };
  9854. StatsCollector.prototype.logStats = function () {
  9855. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  9856. return;
  9857. // Reset the stats
  9858. this.statsToBeLogged.stats = {};
  9859. this.statsToBeLogged.timestamps = [];
  9860. };
  9861. var keyMap = {};
  9862. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  9863. "ssrc": "ssrc",
  9864. "packetsReceived": "packetsReceived",
  9865. "packetsLost": "packetsLost",
  9866. "packetsSent": "packetsSent",
  9867. "bytesReceived": "bytesReceived",
  9868. "bytesSent": "bytesSent"
  9869. };
  9870. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  9871. "receiveBandwidth": "googAvailableReceiveBandwidth",
  9872. "sendBandwidth": "googAvailableSendBandwidth",
  9873. "remoteAddress": "googRemoteAddress",
  9874. "transportType": "googTransportType",
  9875. "localAddress": "googLocalAddress",
  9876. "activeConnection": "googActiveConnection",
  9877. "ssrc": "ssrc",
  9878. "packetsReceived": "packetsReceived",
  9879. "packetsSent": "packetsSent",
  9880. "packetsLost": "packetsLost",
  9881. "bytesReceived": "bytesReceived",
  9882. "bytesSent": "bytesSent",
  9883. "googFrameHeightReceived": "googFrameHeightReceived",
  9884. "googFrameWidthReceived": "googFrameWidthReceived",
  9885. "googFrameHeightSent": "googFrameHeightSent",
  9886. "googFrameWidthSent": "googFrameWidthSent",
  9887. "audioInputLevel": "audioInputLevel",
  9888. "audioOutputLevel": "audioOutputLevel"
  9889. };
  9890. /**
  9891. * Stats processing logic.
  9892. */
  9893. StatsCollector.prototype.processStatsReport = function () {
  9894. if (!this.baselineStatsReport) {
  9895. return;
  9896. }
  9897. for (var idx in this.currentStatsReport) {
  9898. var now = this.currentStatsReport[idx];
  9899. try {
  9900. if (getStatValue(now, 'receiveBandwidth') ||
  9901. getStatValue(now, 'sendBandwidth')) {
  9902. PeerStats.bandwidth = {
  9903. "download": Math.round(
  9904. (getStatValue(now, 'receiveBandwidth')) / 1000),
  9905. "upload": Math.round(
  9906. (getStatValue(now, 'sendBandwidth')) / 1000)
  9907. };
  9908. }
  9909. }
  9910. catch(e){/*not supported*/}
  9911. if(now.type == 'googCandidatePair')
  9912. {
  9913. var ip, type, localIP, active;
  9914. try {
  9915. ip = getStatValue(now, 'remoteAddress');
  9916. type = getStatValue(now, "transportType");
  9917. localIP = getStatValue(now, "localAddress");
  9918. active = getStatValue(now, "activeConnection");
  9919. }
  9920. catch(e){/*not supported*/}
  9921. if(!ip || !type || !localIP || active != "true")
  9922. continue;
  9923. var addressSaved = false;
  9924. for(var i = 0; i < PeerStats.transport.length; i++)
  9925. {
  9926. if(PeerStats.transport[i].ip == ip &&
  9927. PeerStats.transport[i].type == type &&
  9928. PeerStats.transport[i].localip == localIP)
  9929. {
  9930. addressSaved = true;
  9931. }
  9932. }
  9933. if(addressSaved)
  9934. continue;
  9935. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  9936. continue;
  9937. }
  9938. if(now.type == "candidatepair")
  9939. {
  9940. if(now.state == "succeeded")
  9941. continue;
  9942. var local = this.currentStatsReport[now.localCandidateId];
  9943. var remote = this.currentStatsReport[now.remoteCandidateId];
  9944. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  9945. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  9946. }
  9947. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  9948. now.type != "inboundrtp") {
  9949. continue;
  9950. }
  9951. var before = this.baselineStatsReport[idx];
  9952. if (!before) {
  9953. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9954. continue;
  9955. }
  9956. var ssrc = getStatValue(now, 'ssrc');
  9957. if(!ssrc)
  9958. continue;
  9959. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9960. if (!jid && (Date.now() - now.timestamp) < 3000) {
  9961. console.warn("No jid for ssrc: " + ssrc);
  9962. continue;
  9963. }
  9964. var jidStats = this.jid2stats[jid];
  9965. if (!jidStats) {
  9966. jidStats = new PeerStats();
  9967. this.jid2stats[jid] = jidStats;
  9968. }
  9969. var isDownloadStream = true;
  9970. var key = 'packetsReceived';
  9971. if (!getStatValue(now, key))
  9972. {
  9973. isDownloadStream = false;
  9974. key = 'packetsSent';
  9975. if (!getStatValue(now, key))
  9976. {
  9977. console.warn("No packetsReceived nor packetSent stat found");
  9978. continue;
  9979. }
  9980. }
  9981. var packetsNow = getStatValue(now, key);
  9982. if(!packetsNow || packetsNow < 0)
  9983. packetsNow = 0;
  9984. var packetsBefore = getStatValue(before, key);
  9985. if(!packetsBefore || packetsBefore < 0)
  9986. packetsBefore = 0;
  9987. var packetRate = packetsNow - packetsBefore;
  9988. if(!packetRate || packetRate < 0)
  9989. packetRate = 0;
  9990. var currentLoss = getStatValue(now, 'packetsLost');
  9991. if(!currentLoss || currentLoss < 0)
  9992. currentLoss = 0;
  9993. var previousLoss = getStatValue(before, 'packetsLost');
  9994. if(!previousLoss || previousLoss < 0)
  9995. previousLoss = 0;
  9996. var lossRate = currentLoss - previousLoss;
  9997. if(!lossRate || lossRate < 0)
  9998. lossRate = 0;
  9999. var packetsTotal = (packetRate + lossRate);
  10000. jidStats.setSsrcLoss(ssrc,
  10001. {"packetsTotal": packetsTotal,
  10002. "packetsLost": lossRate,
  10003. "isDownloadStream": isDownloadStream});
  10004. var bytesReceived = 0, bytesSent = 0;
  10005. if(getStatValue(now, "bytesReceived"))
  10006. {
  10007. bytesReceived = getStatValue(now, "bytesReceived") -
  10008. getStatValue(before, "bytesReceived");
  10009. }
  10010. if(getStatValue(now, "bytesSent"))
  10011. {
  10012. bytesSent = getStatValue(now, "bytesSent") -
  10013. getStatValue(before, "bytesSent");
  10014. }
  10015. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  10016. if(bytesReceived <= 0 || time <= 0)
  10017. {
  10018. bytesReceived = 0;
  10019. }
  10020. else
  10021. {
  10022. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  10023. }
  10024. if(bytesSent <= 0 || time <= 0)
  10025. {
  10026. bytesSent = 0;
  10027. }
  10028. else
  10029. {
  10030. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  10031. }
  10032. jidStats.setSsrcBitrate(ssrc, {
  10033. "download": bytesReceived,
  10034. "upload": bytesSent});
  10035. var resolution = {height: null, width: null};
  10036. try {
  10037. if (getStatValue(now, "googFrameHeightReceived") &&
  10038. getStatValue(now, "googFrameWidthReceived")) {
  10039. resolution.height = getStatValue(now, "googFrameHeightReceived");
  10040. resolution.width = getStatValue(now, "googFrameWidthReceived");
  10041. }
  10042. else if (getStatValue(now, "googFrameHeightSent") &&
  10043. getStatValue(now, "googFrameWidthSent")) {
  10044. resolution.height = getStatValue(now, "googFrameHeightSent");
  10045. resolution.width = getStatValue(now, "googFrameWidthSent");
  10046. }
  10047. }
  10048. catch(e){/*not supported*/}
  10049. if(resolution.height && resolution.width)
  10050. {
  10051. jidStats.setSsrcResolution(ssrc, resolution);
  10052. }
  10053. else
  10054. {
  10055. jidStats.setSsrcResolution(ssrc, null);
  10056. }
  10057. }
  10058. var self = this;
  10059. // Jid stats
  10060. var totalPackets = {download: 0, upload: 0};
  10061. var lostPackets = {download: 0, upload: 0};
  10062. var bitrateDownload = 0;
  10063. var bitrateUpload = 0;
  10064. var resolutions = {};
  10065. Object.keys(this.jid2stats).forEach(
  10066. function (jid)
  10067. {
  10068. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  10069. function (ssrc)
  10070. {
  10071. var type = "upload";
  10072. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  10073. type = "download";
  10074. totalPackets[type] +=
  10075. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  10076. lostPackets[type] +=
  10077. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  10078. }
  10079. );
  10080. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  10081. function (ssrc) {
  10082. bitrateDownload +=
  10083. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  10084. bitrateUpload +=
  10085. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  10086. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  10087. }
  10088. );
  10089. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  10090. }
  10091. );
  10092. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  10093. PeerStats.packetLoss = {
  10094. total:
  10095. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  10096. totalPackets.download + totalPackets.upload),
  10097. download:
  10098. calculatePacketLoss(lostPackets.download, totalPackets.download),
  10099. upload:
  10100. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  10101. };
  10102. this.eventEmitter.emit("statistics.connectionstats",
  10103. {
  10104. "bitrate": PeerStats.bitrate,
  10105. "packetLoss": PeerStats.packetLoss,
  10106. "bandwidth": PeerStats.bandwidth,
  10107. "resolution": resolutions,
  10108. "transport": PeerStats.transport
  10109. });
  10110. PeerStats.transport = [];
  10111. };
  10112. /**
  10113. * Stats processing logic.
  10114. */
  10115. StatsCollector.prototype.processAudioLevelReport = function ()
  10116. {
  10117. if (!this.baselineAudioLevelsReport)
  10118. {
  10119. return;
  10120. }
  10121. for (var idx in this.currentAudioLevelsReport)
  10122. {
  10123. var now = this.currentAudioLevelsReport[idx];
  10124. if (now.type != 'ssrc')
  10125. {
  10126. continue;
  10127. }
  10128. var before = this.baselineAudioLevelsReport[idx];
  10129. if (!before)
  10130. {
  10131. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10132. continue;
  10133. }
  10134. var ssrc = getStatValue(now, 'ssrc');
  10135. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10136. if (!jid && (Date.now() - now.timestamp) < 3000)
  10137. {
  10138. console.warn("No jid for ssrc: " + ssrc);
  10139. continue;
  10140. }
  10141. var jidStats = this.jid2stats[jid];
  10142. if (!jidStats)
  10143. {
  10144. jidStats = new PeerStats();
  10145. this.jid2stats[jid] = jidStats;
  10146. }
  10147. // Audio level
  10148. var audioLevel = null;
  10149. try {
  10150. audioLevel = getStatValue(now, 'audioInputLevel');
  10151. if (!audioLevel)
  10152. audioLevel = getStatValue(now, 'audioOutputLevel');
  10153. }
  10154. catch(e) {/*not supported*/
  10155. console.warn("Audio Levels are not available in the statistics.");
  10156. clearInterval(this.audioLevelsIntervalId);
  10157. return;
  10158. }
  10159. if (audioLevel)
  10160. {
  10161. // TODO: can't find specs about what this value really is,
  10162. // but it seems to vary between 0 and around 32k.
  10163. audioLevel = audioLevel / 32767;
  10164. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  10165. if(jid != APP.xmpp.myJid())
  10166. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  10167. }
  10168. }
  10169. };
  10170. },{"../../service/RTC/RTCBrowserType":88}],46:[function(require,module,exports){
  10171. /**
  10172. * Created by hristo on 8/4/14.
  10173. */
  10174. var LocalStats = require("./LocalStatsCollector.js");
  10175. var RTPStats = require("./RTPStatsCollector.js");
  10176. var EventEmitter = require("events");
  10177. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  10178. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10179. var eventEmitter = new EventEmitter();
  10180. var localStats = null;
  10181. var rtpStats = null;
  10182. function stopLocal()
  10183. {
  10184. if(localStats)
  10185. {
  10186. localStats.stop();
  10187. localStats = null;
  10188. }
  10189. }
  10190. function stopRemote()
  10191. {
  10192. if(rtpStats)
  10193. {
  10194. rtpStats.stop();
  10195. eventEmitter.emit("statistics.stop");
  10196. rtpStats = null;
  10197. }
  10198. }
  10199. function startRemoteStats (peerconnection) {
  10200. if(rtpStats)
  10201. {
  10202. rtpStats.stop();
  10203. rtpStats = null;
  10204. }
  10205. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  10206. rtpStats.start();
  10207. }
  10208. function onStreamCreated(stream)
  10209. {
  10210. if(stream.getOriginalStream().getAudioTracks().length === 0)
  10211. return;
  10212. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  10213. eventEmitter);
  10214. localStats.start();
  10215. }
  10216. function onDisposeConference(onUnload) {
  10217. stopRemote();
  10218. if(onUnload) {
  10219. stopLocal();
  10220. eventEmitter.removeAllListeners();
  10221. }
  10222. }
  10223. var statistics =
  10224. {
  10225. /**
  10226. * Indicates that this audio level is for local jid.
  10227. * @type {string}
  10228. */
  10229. LOCAL_JID: 'local',
  10230. addAudioLevelListener: function(listener)
  10231. {
  10232. eventEmitter.on("statistics.audioLevel", listener);
  10233. },
  10234. removeAudioLevelListener: function(listener)
  10235. {
  10236. eventEmitter.removeListener("statistics.audioLevel", listener);
  10237. },
  10238. addConnectionStatsListener: function(listener)
  10239. {
  10240. eventEmitter.on("statistics.connectionstats", listener);
  10241. },
  10242. removeConnectionStatsListener: function(listener)
  10243. {
  10244. eventEmitter.removeListener("statistics.connectionstats", listener);
  10245. },
  10246. addRemoteStatsStopListener: function(listener)
  10247. {
  10248. eventEmitter.on("statistics.stop", listener);
  10249. },
  10250. removeRemoteStatsStopListener: function(listener)
  10251. {
  10252. eventEmitter.removeListener("statistics.stop", listener);
  10253. },
  10254. stop: function () {
  10255. stopLocal();
  10256. stopRemote();
  10257. if(eventEmitter)
  10258. {
  10259. eventEmitter.removeAllListeners();
  10260. }
  10261. },
  10262. stopRemoteStatistics: function()
  10263. {
  10264. stopRemote();
  10265. },
  10266. start: function () {
  10267. APP.RTC.addStreamListener(onStreamCreated,
  10268. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10269. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10270. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10271. startRemoteStats(event.peerconnection);
  10272. });
  10273. }
  10274. };
  10275. module.exports = statistics;
  10276. },{"../../service/RTC/StreamEventTypes.js":91,"../../service/xmpp/XMPPEvents":97,"./LocalStatsCollector.js":44,"./RTPStatsCollector.js":45,"events":98}],47:[function(require,module,exports){
  10277. var i18n = require("i18next-client");
  10278. var languages = require("../../service/translation/languages");
  10279. var Settings = require("../settings/Settings");
  10280. var DEFAULT_LANG = languages.EN;
  10281. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10282. return value.replace("__app__", interfaceConfig.APP_NAME);
  10283. });
  10284. var defaultOptions = {
  10285. detectLngQS: "lang",
  10286. useCookie: false,
  10287. fallbackLng: DEFAULT_LANG,
  10288. load: "unspecific",
  10289. resGetPath: 'lang/__ns__-__lng__.json',
  10290. ns: {
  10291. namespaces: ['main', 'languages'],
  10292. defaultNs: 'main'
  10293. },
  10294. lngWhitelist : languages.getLanguages(),
  10295. fallbackOnNull: true,
  10296. fallbackOnEmpty: true,
  10297. useDataAttrOptions: true,
  10298. defaultValueFromContent: false,
  10299. app: interfaceConfig.APP_NAME,
  10300. getAsync: false,
  10301. defaultValueFromContent: false,
  10302. customLoad: function(lng, ns, options, done) {
  10303. var resPath = "lang/__ns__-__lng__.json";
  10304. if(lng === languages.EN)
  10305. resPath = "lang/__ns__.json";
  10306. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10307. i18n.functions.ajax({
  10308. url: url,
  10309. success: function(data, status, xhr) {
  10310. i18n.functions.log('loaded: ' + url);
  10311. done(null, data);
  10312. },
  10313. error : function(xhr, status, error) {
  10314. if ((status && status == 200) ||
  10315. (xhr && xhr.status && xhr.status == 200)) {
  10316. // file loaded but invalid json, stop waste time !
  10317. i18n.functions.error('There is a typo in: ' + url);
  10318. } else if ((status && status == 404) ||
  10319. (xhr && xhr.status && xhr.status == 404)) {
  10320. i18n.functions.log('Does not exist: ' + url);
  10321. } else {
  10322. var theStatus = status ? status :
  10323. ((xhr && xhr.status) ? xhr.status : null);
  10324. i18n.functions.log(theStatus + ' when loading ' + url);
  10325. }
  10326. done(error, {});
  10327. },
  10328. dataType: "json",
  10329. async : options.getAsync
  10330. });
  10331. }
  10332. // options for caching
  10333. // useLocalStorage: true,
  10334. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10335. };
  10336. function initCompleted(t)
  10337. {
  10338. $("[data-i18n]").i18n();
  10339. }
  10340. function checkForParameter() {
  10341. var query = window.location.search.substring(1);
  10342. var vars = query.split("&");
  10343. for (var i=0;i<vars.length;i++) {
  10344. var pair = vars[i].split("=");
  10345. if(pair[0] == "lang")
  10346. {
  10347. return pair[1];
  10348. }
  10349. }
  10350. return null;
  10351. }
  10352. module.exports = {
  10353. init: function (lang) {
  10354. var options = defaultOptions;
  10355. if(!lang)
  10356. {
  10357. lang = checkForParameter();
  10358. if(!lang)
  10359. {
  10360. var settings = Settings.getSettings();
  10361. if(settings)
  10362. lang = settings.language;
  10363. }
  10364. }
  10365. if(lang) {
  10366. options.lng = lang;
  10367. }
  10368. i18n.init(options, initCompleted);
  10369. },
  10370. translateString: function (key, options) {
  10371. return i18n.t(key, options);
  10372. },
  10373. setLanguage: function (lang) {
  10374. if(!lang)
  10375. lang = DEFAULT_LANG;
  10376. i18n.setLng(lang, defaultOptions, initCompleted);
  10377. },
  10378. getCurrentLanguage: function () {
  10379. return i18n.lng();
  10380. },
  10381. translateElement: function (selector) {
  10382. selector.i18n();
  10383. },
  10384. generateTranslatonHTML: function (key, options) {
  10385. var str = "<span data-i18n=\"" + key + "\"";
  10386. if(options)
  10387. {
  10388. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10389. }
  10390. str += ">";
  10391. str += this.translateString(key, options);
  10392. str += "</span>";
  10393. return str;
  10394. }
  10395. };
  10396. },{"../../service/translation/languages":96,"../settings/Settings":38,"i18next-client":62}],48:[function(require,module,exports){
  10397. /* jshint -W117 */
  10398. var TraceablePeerConnection = require("./TraceablePeerConnection");
  10399. var SDPDiffer = require("./SDPDiffer");
  10400. var SDPUtil = require("./SDPUtil");
  10401. var SDP = require("./SDP");
  10402. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10403. // Jingle stuff
  10404. function JingleSession(me, sid, connection, service) {
  10405. this.me = me;
  10406. this.sid = sid;
  10407. this.connection = connection;
  10408. this.initiator = null;
  10409. this.responder = null;
  10410. this.isInitiator = null;
  10411. this.peerjid = null;
  10412. this.state = null;
  10413. this.localSDP = null;
  10414. this.remoteSDP = null;
  10415. this.relayedStreams = [];
  10416. this.startTime = null;
  10417. this.stopTime = null;
  10418. this.media_constraints = null;
  10419. this.pc_constraints = null;
  10420. this.ice_config = {};
  10421. this.drip_container = [];
  10422. this.service = service;
  10423. this.usetrickle = true;
  10424. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  10425. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  10426. this.hadstuncandidate = false;
  10427. this.hadturncandidate = false;
  10428. this.lasticecandidate = false;
  10429. this.statsinterval = null;
  10430. this.reason = null;
  10431. this.addssrc = [];
  10432. this.removessrc = [];
  10433. this.pendingop = null;
  10434. this.switchstreams = false;
  10435. this.wait = true;
  10436. this.localStreamsSSRC = null;
  10437. /**
  10438. * The indicator which determines whether the (local) video has been muted
  10439. * in response to a user command in contrast to an automatic decision made
  10440. * by the application logic.
  10441. */
  10442. this.videoMuteByUser = false;
  10443. }
  10444. //TODO: this array must be removed when firefox implement multistream support
  10445. JingleSession.notReceivedSSRCs = [];
  10446. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  10447. var self = this;
  10448. if (this.state !== null) {
  10449. console.error('attempt to initiate on session ' + this.sid +
  10450. 'in state ' + this.state);
  10451. return;
  10452. }
  10453. this.isInitiator = isInitiator;
  10454. this.state = 'pending';
  10455. this.initiator = isInitiator ? this.me : peerjid;
  10456. this.responder = !isInitiator ? this.me : peerjid;
  10457. this.peerjid = peerjid;
  10458. this.hadstuncandidate = false;
  10459. this.hadturncandidate = false;
  10460. this.lasticecandidate = false;
  10461. this.peerconnection
  10462. = new TraceablePeerConnection(
  10463. this.connection.jingle.ice_config,
  10464. this.connection.jingle.pc_constraints );
  10465. this.peerconnection.onicecandidate = function (event) {
  10466. self.sendIceCandidate(event.candidate);
  10467. };
  10468. this.peerconnection.onaddstream = function (event) {
  10469. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  10470. self.remoteStreamAdded(event);
  10471. };
  10472. this.peerconnection.onremovestream = function (event) {
  10473. // Remove the stream from remoteStreams
  10474. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  10475. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  10476. };
  10477. this.peerconnection.onsignalingstatechange = function (event) {
  10478. if (!(self && self.peerconnection)) return;
  10479. };
  10480. this.peerconnection.oniceconnectionstatechange = function (event) {
  10481. if (!(self && self.peerconnection)) return;
  10482. switch (self.peerconnection.iceConnectionState) {
  10483. case 'connected':
  10484. this.startTime = new Date();
  10485. break;
  10486. case 'disconnected':
  10487. this.stopTime = new Date();
  10488. break;
  10489. }
  10490. onIceConnectionStateChange(self.sid, self);
  10491. };
  10492. // add any local and relayed stream
  10493. APP.RTC.localStreams.forEach(function(stream) {
  10494. self.peerconnection.addStream(stream.getOriginalStream());
  10495. });
  10496. this.relayedStreams.forEach(function(stream) {
  10497. self.peerconnection.addStream(stream);
  10498. });
  10499. };
  10500. function onIceConnectionStateChange(sid, session) {
  10501. switch (session.peerconnection.iceConnectionState) {
  10502. case 'checking':
  10503. session.timeChecking = (new Date()).getTime();
  10504. session.firstconnect = true;
  10505. break;
  10506. case 'completed': // on caller side
  10507. case 'connected':
  10508. if (session.firstconnect) {
  10509. session.firstconnect = false;
  10510. var metadata = {};
  10511. metadata.setupTime
  10512. = (new Date()).getTime() - session.timeChecking;
  10513. session.peerconnection.getStats(function (res) {
  10514. if(res && res.result) {
  10515. res.result().forEach(function (report) {
  10516. if (report.type == 'googCandidatePair' &&
  10517. report.stat('googActiveConnection') == 'true') {
  10518. metadata.localCandidateType
  10519. = report.stat('googLocalCandidateType');
  10520. metadata.remoteCandidateType
  10521. = report.stat('googRemoteCandidateType');
  10522. // log pair as well so we can get nice pie
  10523. // charts
  10524. metadata.candidatePair
  10525. = report.stat('googLocalCandidateType') +
  10526. ';' +
  10527. report.stat('googRemoteCandidateType');
  10528. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  10529. {
  10530. metadata.ipv6 = true;
  10531. }
  10532. }
  10533. });
  10534. }
  10535. });
  10536. }
  10537. break;
  10538. }
  10539. }
  10540. JingleSession.prototype.accept = function () {
  10541. var self = this;
  10542. this.state = 'active';
  10543. var pranswer = this.peerconnection.localDescription;
  10544. if (!pranswer || pranswer.type != 'pranswer') {
  10545. return;
  10546. }
  10547. console.log('going from pranswer to answer');
  10548. if (this.usetrickle) {
  10549. // remove candidates already sent from session-accept
  10550. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  10551. for (var i = 0; i < lines.length; i++) {
  10552. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  10553. }
  10554. }
  10555. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  10556. // FIXME: change any inactive to sendrecv or whatever they were originally
  10557. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  10558. }
  10559. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  10560. var prsdp = new SDP(pranswer.sdp);
  10561. var accept = $iq({to: this.peerjid,
  10562. type: 'set'})
  10563. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10564. action: 'session-accept',
  10565. initiator: this.initiator,
  10566. responder: this.responder,
  10567. sid: this.sid });
  10568. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10569. var sdp = this.peerconnection.localDescription.sdp;
  10570. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  10571. // FIXME: change any inactive to sendrecv or whatever they were originally
  10572. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  10573. }
  10574. var self = this;
  10575. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  10576. function () {
  10577. //console.log('setLocalDescription success');
  10578. self.setLocalDescription();
  10579. self.connection.sendIQ(accept,
  10580. function () {
  10581. var ack = {};
  10582. ack.source = 'answer';
  10583. $(document).trigger('ack.jingle', [self.sid, ack]);
  10584. },
  10585. function (stanza) {
  10586. var error = ($(stanza).find('error').length) ? {
  10587. code: $(stanza).find('error').attr('code'),
  10588. reason: $(stanza).find('error :first')[0].tagName
  10589. }:{};
  10590. error.source = 'answer';
  10591. JingleSession.onJingleError(self.sid, error);
  10592. },
  10593. 10000);
  10594. },
  10595. function (e) {
  10596. console.error('setLocalDescription failed', e);
  10597. }
  10598. );
  10599. };
  10600. JingleSession.prototype.terminate = function (reason) {
  10601. this.state = 'ended';
  10602. this.reason = reason;
  10603. this.peerconnection.close();
  10604. if (this.statsinterval !== null) {
  10605. window.clearInterval(this.statsinterval);
  10606. this.statsinterval = null;
  10607. }
  10608. };
  10609. JingleSession.prototype.active = function () {
  10610. return this.state == 'active';
  10611. };
  10612. JingleSession.prototype.sendIceCandidate = function (candidate) {
  10613. var self = this;
  10614. if (candidate && !this.lasticecandidate) {
  10615. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  10616. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  10617. if (!(ice && jcand)) {
  10618. console.error('failed to get ice && jcand');
  10619. return;
  10620. }
  10621. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10622. if (jcand.type === 'srflx') {
  10623. this.hadstuncandidate = true;
  10624. } else if (jcand.type === 'relay') {
  10625. this.hadturncandidate = true;
  10626. }
  10627. if (this.usetrickle) {
  10628. if (this.usedrip) {
  10629. if (this.drip_container.length === 0) {
  10630. // start 20ms callout
  10631. window.setTimeout(function () {
  10632. if (self.drip_container.length === 0) return;
  10633. self.sendIceCandidates(self.drip_container);
  10634. self.drip_container = [];
  10635. }, 20);
  10636. }
  10637. this.drip_container.push(candidate);
  10638. return;
  10639. } else {
  10640. self.sendIceCandidate([candidate]);
  10641. }
  10642. }
  10643. } else {
  10644. //console.log('sendIceCandidate: last candidate.');
  10645. if (!this.usetrickle) {
  10646. //console.log('should send full offer now...');
  10647. var init = $iq({to: this.peerjid,
  10648. type: 'set'})
  10649. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10650. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  10651. initiator: this.initiator,
  10652. sid: this.sid});
  10653. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  10654. var self = this;
  10655. var sendJingle = function (ssrc) {
  10656. if(!ssrc)
  10657. ssrc = {};
  10658. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  10659. self.connection.sendIQ(init,
  10660. function () {
  10661. //console.log('session initiate ack');
  10662. var ack = {};
  10663. ack.source = 'offer';
  10664. $(document).trigger('ack.jingle', [self.sid, ack]);
  10665. },
  10666. function (stanza) {
  10667. self.state = 'error';
  10668. self.peerconnection.close();
  10669. var error = ($(stanza).find('error').length) ? {
  10670. code: $(stanza).find('error').attr('code'),
  10671. reason: $(stanza).find('error :first')[0].tagName,
  10672. }:{};
  10673. error.source = 'offer';
  10674. JingleSession.onJingleError(self.sid, error);
  10675. },
  10676. 10000);
  10677. }
  10678. sendJingle();
  10679. }
  10680. this.lasticecandidate = true;
  10681. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  10682. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  10683. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  10684. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  10685. }
  10686. }
  10687. };
  10688. JingleSession.prototype.sendIceCandidates = function (candidates) {
  10689. console.log('sendIceCandidates', candidates);
  10690. var cand = $iq({to: this.peerjid, type: 'set'})
  10691. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10692. action: 'transport-info',
  10693. initiator: this.initiator,
  10694. sid: this.sid});
  10695. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  10696. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  10697. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  10698. if (cands.length > 0) {
  10699. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  10700. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10701. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  10702. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  10703. }).c('transport', ice);
  10704. for (var i = 0; i < cands.length; i++) {
  10705. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  10706. }
  10707. // add fingerprint
  10708. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  10709. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  10710. tmp.required = true;
  10711. cand.c(
  10712. 'fingerprint',
  10713. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  10714. .t(tmp.fingerprint);
  10715. delete tmp.fingerprint;
  10716. cand.attrs(tmp);
  10717. cand.up();
  10718. }
  10719. cand.up(); // transport
  10720. cand.up(); // content
  10721. }
  10722. }
  10723. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  10724. //console.log('was this the last candidate', this.lasticecandidate);
  10725. this.connection.sendIQ(cand,
  10726. function () {
  10727. var ack = {};
  10728. ack.source = 'transportinfo';
  10729. $(document).trigger('ack.jingle', [this.sid, ack]);
  10730. },
  10731. function (stanza) {
  10732. var error = ($(stanza).find('error').length) ? {
  10733. code: $(stanza).find('error').attr('code'),
  10734. reason: $(stanza).find('error :first')[0].tagName,
  10735. }:{};
  10736. error.source = 'transportinfo';
  10737. JingleSession.onJingleError(this.sid, error);
  10738. },
  10739. 10000);
  10740. };
  10741. JingleSession.prototype.sendOffer = function () {
  10742. //console.log('sendOffer...');
  10743. var self = this;
  10744. this.peerconnection.createOffer(function (sdp) {
  10745. self.createdOffer(sdp);
  10746. },
  10747. function (e) {
  10748. console.error('createOffer failed', e);
  10749. },
  10750. this.media_constraints
  10751. );
  10752. };
  10753. JingleSession.prototype.createdOffer = function (sdp) {
  10754. //console.log('createdOffer', sdp);
  10755. var self = this;
  10756. this.localSDP = new SDP(sdp.sdp);
  10757. //this.localSDP.mangle();
  10758. var sendJingle = function () {
  10759. var init = $iq({to: this.peerjid,
  10760. type: 'set'})
  10761. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10762. action: 'session-initiate',
  10763. initiator: this.initiator,
  10764. sid: this.sid});
  10765. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10766. self.connection.sendIQ(init,
  10767. function () {
  10768. var ack = {};
  10769. ack.source = 'offer';
  10770. $(document).trigger('ack.jingle', [self.sid, ack]);
  10771. },
  10772. function (stanza) {
  10773. self.state = 'error';
  10774. self.peerconnection.close();
  10775. var error = ($(stanza).find('error').length) ? {
  10776. code: $(stanza).find('error').attr('code'),
  10777. reason: $(stanza).find('error :first')[0].tagName,
  10778. }:{};
  10779. error.source = 'offer';
  10780. JingleSession.onJingleError(self.sid, error);
  10781. },
  10782. 10000);
  10783. }
  10784. sdp.sdp = this.localSDP.raw;
  10785. this.peerconnection.setLocalDescription(sdp,
  10786. function () {
  10787. if(self.usetrickle)
  10788. {
  10789. sendJingle();
  10790. }
  10791. self.setLocalDescription();
  10792. //console.log('setLocalDescription success');
  10793. },
  10794. function (e) {
  10795. console.error('setLocalDescription failed', e);
  10796. }
  10797. );
  10798. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10799. for (var i = 0; i < cands.length; i++) {
  10800. var cand = SDPUtil.parse_icecandidate(cands[i]);
  10801. if (cand.type == 'srflx') {
  10802. this.hadstuncandidate = true;
  10803. } else if (cand.type == 'relay') {
  10804. this.hadturncandidate = true;
  10805. }
  10806. }
  10807. };
  10808. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  10809. //console.log('setting remote description... ', desctype);
  10810. this.remoteSDP = new SDP('');
  10811. this.remoteSDP.fromJingle(elem);
  10812. if (this.peerconnection.remoteDescription !== null) {
  10813. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  10814. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  10815. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  10816. for (var i = 0; i < pranswer.media.length; i++) {
  10817. // make sure we have ice ufrag and pwd
  10818. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  10819. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  10820. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  10821. } else {
  10822. console.warn('no ice ufrag?');
  10823. }
  10824. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  10825. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  10826. } else {
  10827. console.warn('no ice pwd?');
  10828. }
  10829. }
  10830. // copy over candidates
  10831. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  10832. for (var j = 0; j < lines.length; j++) {
  10833. this.remoteSDP.media[i] += lines[j] + '\r\n';
  10834. }
  10835. }
  10836. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10837. }
  10838. }
  10839. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  10840. this.peerconnection.setRemoteDescription(remotedesc,
  10841. function () {
  10842. //console.log('setRemoteDescription success');
  10843. },
  10844. function (e) {
  10845. console.error('setRemoteDescription error', e);
  10846. JingleSession.onJingleFatalError(self, e);
  10847. }
  10848. );
  10849. };
  10850. JingleSession.prototype.addIceCandidate = function (elem) {
  10851. var self = this;
  10852. if (this.peerconnection.signalingState == 'closed') {
  10853. return;
  10854. }
  10855. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  10856. console.log('trickle ice candidate arriving before session accept...');
  10857. // create a PRANSWER for setRemoteDescription
  10858. if (!this.remoteSDP) {
  10859. var cobbled = 'v=0\r\n' +
  10860. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  10861. 's=-\r\n' +
  10862. 't=0 0\r\n';
  10863. // first, take some things from the local description
  10864. for (var i = 0; i < this.localSDP.media.length; i++) {
  10865. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  10866. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  10867. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  10868. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  10869. }
  10870. cobbled += 'a=inactive\r\n';
  10871. }
  10872. this.remoteSDP = new SDP(cobbled);
  10873. }
  10874. // then add things like ice and dtls from remote candidate
  10875. elem.each(function () {
  10876. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  10877. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10878. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10879. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  10880. var tmp = $(this).find('transport');
  10881. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  10882. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  10883. tmp = $(this).find('transport>fingerprint');
  10884. if (tmp.length) {
  10885. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  10886. } else {
  10887. console.log('no dtls fingerprint (webrtc issue #1718?)');
  10888. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  10889. }
  10890. break;
  10891. }
  10892. }
  10893. }
  10894. });
  10895. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10896. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  10897. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  10898. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  10899. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  10900. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  10901. }).length == this.remoteSDP.media.length;
  10902. if (iscomplete) {
  10903. console.log('setting pranswer');
  10904. try {
  10905. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  10906. function() {
  10907. },
  10908. function(e) {
  10909. console.log('setRemoteDescription pranswer failed', e.toString());
  10910. });
  10911. } catch (e) {
  10912. console.error('setting pranswer failed', e);
  10913. }
  10914. } else {
  10915. //console.log('not yet setting pranswer');
  10916. }
  10917. }
  10918. // operate on each content element
  10919. elem.each(function () {
  10920. // would love to deactivate this, but firefox still requires it
  10921. var idx = -1;
  10922. var i;
  10923. for (i = 0; i < self.remoteSDP.media.length; i++) {
  10924. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10925. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10926. idx = i;
  10927. break;
  10928. }
  10929. }
  10930. if (idx == -1) { // fall back to localdescription
  10931. for (i = 0; i < self.localSDP.media.length; i++) {
  10932. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10933. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10934. idx = i;
  10935. break;
  10936. }
  10937. }
  10938. }
  10939. var name = $(this).attr('name');
  10940. // TODO: check ice-pwd and ice-ufrag?
  10941. $(this).find('transport>candidate').each(function () {
  10942. var line, candidate;
  10943. line = SDPUtil.candidateFromJingle(this);
  10944. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  10945. sdpMid: name,
  10946. candidate: line});
  10947. try {
  10948. self.peerconnection.addIceCandidate(candidate);
  10949. } catch (e) {
  10950. console.error('addIceCandidate failed', e.toString(), line);
  10951. }
  10952. });
  10953. });
  10954. };
  10955. JingleSession.prototype.sendAnswer = function (provisional) {
  10956. //console.log('createAnswer', provisional);
  10957. var self = this;
  10958. this.peerconnection.createAnswer(
  10959. function (sdp) {
  10960. self.createdAnswer(sdp, provisional);
  10961. },
  10962. function (e) {
  10963. console.error('createAnswer failed', e);
  10964. },
  10965. this.media_constraints
  10966. );
  10967. };
  10968. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  10969. //console.log('createAnswer callback');
  10970. var self = this;
  10971. this.localSDP = new SDP(sdp.sdp);
  10972. //this.localSDP.mangle();
  10973. this.usepranswer = provisional === true;
  10974. if (this.usetrickle) {
  10975. if (this.usepranswer) {
  10976. sdp.type = 'pranswer';
  10977. for (var i = 0; i < this.localSDP.media.length; i++) {
  10978. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  10979. }
  10980. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  10981. }
  10982. }
  10983. var self = this;
  10984. var sendJingle = function (ssrcs) {
  10985. var accept = $iq({to: self.peerjid,
  10986. type: 'set'})
  10987. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10988. action: 'session-accept',
  10989. initiator: self.initiator,
  10990. responder: self.responder,
  10991. sid: self.sid });
  10992. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  10993. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  10994. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  10995. self.connection.sendIQ(accept,
  10996. function () {
  10997. var ack = {};
  10998. ack.source = 'answer';
  10999. $(document).trigger('ack.jingle', [self.sid, ack]);
  11000. },
  11001. function (stanza) {
  11002. var error = ($(stanza).find('error').length) ? {
  11003. code: $(stanza).find('error').attr('code'),
  11004. reason: $(stanza).find('error :first')[0].tagName,
  11005. }:{};
  11006. error.source = 'answer';
  11007. JingleSession.onJingleError(self.sid, error);
  11008. },
  11009. 10000);
  11010. }
  11011. sdp.sdp = this.localSDP.raw;
  11012. this.peerconnection.setLocalDescription(sdp,
  11013. function () {
  11014. //console.log('setLocalDescription success');
  11015. if (self.usetrickle && !self.usepranswer) {
  11016. sendJingle();
  11017. }
  11018. self.setLocalDescription();
  11019. },
  11020. function (e) {
  11021. console.error('setLocalDescription failed', e);
  11022. }
  11023. );
  11024. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11025. for (var j = 0; j < cands.length; j++) {
  11026. var cand = SDPUtil.parse_icecandidate(cands[j]);
  11027. if (cand.type == 'srflx') {
  11028. this.hadstuncandidate = true;
  11029. } else if (cand.type == 'relay') {
  11030. this.hadturncandidate = true;
  11031. }
  11032. }
  11033. };
  11034. JingleSession.prototype.sendTerminate = function (reason, text) {
  11035. var self = this,
  11036. term = $iq({to: this.peerjid,
  11037. type: 'set'})
  11038. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11039. action: 'session-terminate',
  11040. initiator: this.initiator,
  11041. sid: this.sid})
  11042. .c('reason')
  11043. .c(reason || 'success');
  11044. if (text) {
  11045. term.up().c('text').t(text);
  11046. }
  11047. this.connection.sendIQ(term,
  11048. function () {
  11049. self.peerconnection.close();
  11050. self.peerconnection = null;
  11051. self.terminate();
  11052. var ack = {};
  11053. ack.source = 'terminate';
  11054. $(document).trigger('ack.jingle', [self.sid, ack]);
  11055. },
  11056. function (stanza) {
  11057. var error = ($(stanza).find('error').length) ? {
  11058. code: $(stanza).find('error').attr('code'),
  11059. reason: $(stanza).find('error :first')[0].tagName,
  11060. }:{};
  11061. $(document).trigger('ack.jingle', [self.sid, error]);
  11062. },
  11063. 10000);
  11064. if (this.statsinterval !== null) {
  11065. window.clearInterval(this.statsinterval);
  11066. this.statsinterval = null;
  11067. }
  11068. };
  11069. JingleSession.prototype.addSource = function (elem, fromJid) {
  11070. var self = this;
  11071. // FIXME: dirty waiting
  11072. if (!this.peerconnection.localDescription)
  11073. {
  11074. console.warn("addSource - localDescription not ready yet")
  11075. setTimeout(function()
  11076. {
  11077. self.addSource(elem, fromJid);
  11078. },
  11079. 200
  11080. );
  11081. return;
  11082. }
  11083. console.log('addssrc', new Date().getTime());
  11084. console.log('ice', this.peerconnection.iceConnectionState);
  11085. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11086. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11087. $(elem).each(function (idx, content) {
  11088. var name = $(content).attr('name');
  11089. var lines = '';
  11090. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11091. var semantics = this.getAttribute('semantics');
  11092. var ssrcs = $(this).find('>source').map(function () {
  11093. return this.getAttribute('ssrc');
  11094. }).get();
  11095. if (ssrcs.length != 0) {
  11096. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11097. }
  11098. });
  11099. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11100. tmp.each(function () {
  11101. var ssrc = $(this).attr('ssrc');
  11102. if(mySdp.containsSSRC(ssrc)){
  11103. /**
  11104. * This happens when multiple participants change their streams at the same time and
  11105. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  11106. * addssrc are scheduled for update IQ. See
  11107. */
  11108. console.warn("Got add stream request for my own ssrc: "+ssrc);
  11109. return;
  11110. }
  11111. $(this).find('>parameter').each(function () {
  11112. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11113. if ($(this).attr('value') && $(this).attr('value').length)
  11114. lines += ':' + $(this).attr('value');
  11115. lines += '\r\n';
  11116. });
  11117. });
  11118. sdp.media.forEach(function(media, idx) {
  11119. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11120. return;
  11121. sdp.media[idx] += lines;
  11122. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  11123. self.addssrc[idx] += lines;
  11124. });
  11125. sdp.raw = sdp.session + sdp.media.join('');
  11126. });
  11127. this.modifySources();
  11128. };
  11129. JingleSession.prototype.removeSource = function (elem, fromJid) {
  11130. var self = this;
  11131. // FIXME: dirty waiting
  11132. if (!this.peerconnection.localDescription)
  11133. {
  11134. console.warn("removeSource - localDescription not ready yet")
  11135. setTimeout(function()
  11136. {
  11137. self.removeSource(elem, fromJid);
  11138. },
  11139. 200
  11140. );
  11141. return;
  11142. }
  11143. console.log('removessrc', new Date().getTime());
  11144. console.log('ice', this.peerconnection.iceConnectionState);
  11145. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11146. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11147. $(elem).each(function (idx, content) {
  11148. var name = $(content).attr('name');
  11149. var lines = '';
  11150. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11151. var semantics = this.getAttribute('semantics');
  11152. var ssrcs = $(this).find('>source').map(function () {
  11153. return this.getAttribute('ssrc');
  11154. }).get();
  11155. if (ssrcs.length != 0) {
  11156. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11157. }
  11158. });
  11159. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11160. tmp.each(function () {
  11161. var ssrc = $(this).attr('ssrc');
  11162. // This should never happen, but can be useful for bug detection
  11163. if(mySdp.containsSSRC(ssrc)){
  11164. console.error("Got remove stream request for my own ssrc: "+ssrc);
  11165. return;
  11166. }
  11167. $(this).find('>parameter').each(function () {
  11168. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11169. if ($(this).attr('value') && $(this).attr('value').length)
  11170. lines += ':' + $(this).attr('value');
  11171. lines += '\r\n';
  11172. });
  11173. });
  11174. sdp.media.forEach(function(media, idx) {
  11175. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11176. return;
  11177. sdp.media[idx] += lines;
  11178. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  11179. self.removessrc[idx] += lines;
  11180. });
  11181. sdp.raw = sdp.session + sdp.media.join('');
  11182. });
  11183. this.modifySources();
  11184. };
  11185. JingleSession.prototype.modifySources = function (successCallback) {
  11186. var self = this;
  11187. if (this.peerconnection.signalingState == 'closed') return;
  11188. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  11189. // There is nothing to do since scheduled job might have been executed by another succeeding call
  11190. this.setLocalDescription();
  11191. if(successCallback){
  11192. successCallback();
  11193. }
  11194. return;
  11195. }
  11196. // FIXME: this is a big hack
  11197. // https://code.google.com/p/webrtc/issues/detail?id=2688
  11198. // ^ has been fixed.
  11199. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
  11200. console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
  11201. this.wait = true;
  11202. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  11203. return;
  11204. }
  11205. if (this.wait) {
  11206. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  11207. this.wait = false;
  11208. return;
  11209. }
  11210. // Reset switch streams flag
  11211. this.switchstreams = false;
  11212. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11213. // add sources
  11214. this.addssrc.forEach(function(lines, idx) {
  11215. sdp.media[idx] += lines;
  11216. });
  11217. this.addssrc = [];
  11218. // remove sources
  11219. this.removessrc.forEach(function(lines, idx) {
  11220. lines = lines.split('\r\n');
  11221. lines.pop(); // remove empty last element;
  11222. lines.forEach(function(line) {
  11223. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  11224. });
  11225. });
  11226. this.removessrc = [];
  11227. // FIXME:
  11228. // this was a hack for the situation when only one peer exists
  11229. // in the conference.
  11230. // check if still required and remove
  11231. if (sdp.media[0])
  11232. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  11233. if (sdp.media[1])
  11234. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11235. sdp.raw = sdp.session + sdp.media.join('');
  11236. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  11237. function() {
  11238. if(self.signalingState == 'closed') {
  11239. console.error("createAnswer attempt on closed state");
  11240. return;
  11241. }
  11242. self.peerconnection.createAnswer(
  11243. function(modifiedAnswer) {
  11244. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  11245. if (self.pendingop !== null) {
  11246. var sdp = new SDP(modifiedAnswer.sdp);
  11247. if (sdp.media.length > 1) {
  11248. switch(self.pendingop) {
  11249. case 'mute':
  11250. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  11251. break;
  11252. case 'unmute':
  11253. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11254. break;
  11255. }
  11256. sdp.raw = sdp.session + sdp.media.join('');
  11257. modifiedAnswer.sdp = sdp.raw;
  11258. }
  11259. self.pendingop = null;
  11260. }
  11261. // FIXME: pushing down an answer while ice connection state
  11262. // is still checking is bad...
  11263. //console.log(self.peerconnection.iceConnectionState);
  11264. // trying to work around another chrome bug
  11265. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11266. self.peerconnection.setLocalDescription(modifiedAnswer,
  11267. function() {
  11268. //console.log('modified setLocalDescription ok');
  11269. self.setLocalDescription();
  11270. if(successCallback){
  11271. successCallback();
  11272. }
  11273. },
  11274. function(error) {
  11275. console.error('modified setLocalDescription failed', error);
  11276. }
  11277. );
  11278. },
  11279. function(error) {
  11280. console.error('modified answer failed', error);
  11281. }
  11282. );
  11283. },
  11284. function(error) {
  11285. console.error('modify failed', error);
  11286. }
  11287. );
  11288. };
  11289. /**
  11290. * Switches video streams.
  11291. * @param new_stream new stream that will be used as video of this session.
  11292. * @param oldStream old video stream of this session.
  11293. * @param success_callback callback executed after successful stream switch.
  11294. */
  11295. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback) {
  11296. var self = this;
  11297. // Remember SDP to figure out added/removed SSRCs
  11298. var oldSdp = null;
  11299. if(self.peerconnection) {
  11300. if(self.peerconnection.localDescription) {
  11301. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11302. }
  11303. self.peerconnection.removeStream(oldStream, true);
  11304. self.peerconnection.addStream(new_stream);
  11305. }
  11306. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11307. // Conference is not active
  11308. if(!oldSdp || !self.peerconnection) {
  11309. success_callback();
  11310. return;
  11311. }
  11312. self.switchstreams = true;
  11313. self.modifySources(function() {
  11314. console.log('modify sources done');
  11315. success_callback();
  11316. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11317. console.log("SDPs", oldSdp, newSdp);
  11318. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11319. });
  11320. };
  11321. /**
  11322. * Figures out added/removed ssrcs and send update IQs.
  11323. * @param old_sdp SDP object for old description.
  11324. * @param new_sdp SDP object for new description.
  11325. */
  11326. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11327. if (!(this.peerconnection.signalingState == 'stable' &&
  11328. this.peerconnection.iceConnectionState == 'connected')){
  11329. console.log("Too early to send updates");
  11330. return;
  11331. }
  11332. // send source-remove IQ.
  11333. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11334. var remove = $iq({to: this.peerjid, type: 'set'})
  11335. .c('jingle', {
  11336. xmlns: 'urn:xmpp:jingle:1',
  11337. action: 'source-remove',
  11338. initiator: this.initiator,
  11339. sid: this.sid
  11340. }
  11341. );
  11342. var removed = sdpDiffer.toJingle(remove);
  11343. if (removed) {
  11344. this.connection.sendIQ(remove,
  11345. function (res) {
  11346. console.info('got remove result', res);
  11347. },
  11348. function (err) {
  11349. console.error('got remove error', err);
  11350. }
  11351. );
  11352. } else {
  11353. console.log('removal not necessary');
  11354. }
  11355. // send source-add IQ.
  11356. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11357. var add = $iq({to: this.peerjid, type: 'set'})
  11358. .c('jingle', {
  11359. xmlns: 'urn:xmpp:jingle:1',
  11360. action: 'source-add',
  11361. initiator: this.initiator,
  11362. sid: this.sid
  11363. }
  11364. );
  11365. var added = sdpDiffer.toJingle(add);
  11366. if (added) {
  11367. this.connection.sendIQ(add,
  11368. function (res) {
  11369. console.info('got add result', res);
  11370. },
  11371. function (err) {
  11372. console.error('got add error', err);
  11373. }
  11374. );
  11375. } else {
  11376. console.log('addition not necessary');
  11377. }
  11378. };
  11379. /**
  11380. * Determines whether the (local) video is mute i.e. all video tracks are
  11381. * disabled.
  11382. *
  11383. * @return <tt>true</tt> if the (local) video is mute i.e. all video tracks are
  11384. * disabled; otherwise, <tt>false</tt>
  11385. */
  11386. JingleSession.prototype.isVideoMute = function () {
  11387. var tracks = APP.RTC.localVideo.getVideoTracks();
  11388. var mute = true;
  11389. for (var i = 0; i < tracks.length; ++i) {
  11390. if (tracks[i].enabled) {
  11391. mute = false;
  11392. break;
  11393. }
  11394. }
  11395. return mute;
  11396. };
  11397. /**
  11398. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  11399. *
  11400. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  11401. * tracks; otherwise, <tt>false</tt>
  11402. * @param callback a function to be invoked with <tt>mute</tt> after all video
  11403. * tracks have been enabled/disabled. The function may, optionally, return
  11404. * another function which is to be invoked after the whole mute/unmute operation
  11405. * has completed successfully.
  11406. * @param options an object which specifies optional arguments such as the
  11407. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  11408. * specifies whether the method was initiated in response to a user command (in
  11409. * contrast to an automatic decision made by the application logic)
  11410. */
  11411. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  11412. var byUser;
  11413. if (options) {
  11414. byUser = options.byUser;
  11415. if (typeof byUser === 'undefined') {
  11416. byUser = true;
  11417. }
  11418. } else {
  11419. byUser = true;
  11420. }
  11421. // The user's command to mute the (local) video takes precedence over any
  11422. // automatic decision made by the application logic.
  11423. if (byUser) {
  11424. this.videoMuteByUser = mute;
  11425. } else if (this.videoMuteByUser) {
  11426. return;
  11427. }
  11428. var self = this;
  11429. var localCallback = function (mute) {
  11430. self.connection.emuc.addVideoInfoToPresence(mute);
  11431. self.connection.emuc.sendPresence();
  11432. return callback(mute)
  11433. };
  11434. if (mute == APP.RTC.localVideo.isMuted())
  11435. {
  11436. // Even if no change occurs, the specified callback is to be executed.
  11437. // The specified callback may, optionally, return a successCallback
  11438. // which is to be executed as well.
  11439. var successCallback = localCallback(mute);
  11440. if (successCallback) {
  11441. successCallback();
  11442. }
  11443. } else {
  11444. APP.RTC.localVideo.setMute(!mute);
  11445. this.hardMuteVideo(mute);
  11446. this.modifySources(localCallback(mute));
  11447. }
  11448. };
  11449. // SDP-based mute by going recvonly/sendrecv
  11450. // FIXME: should probably black out the screen as well
  11451. JingleSession.prototype.toggleVideoMute = function (callback) {
  11452. this.service.setVideoMute(APP.RTC.localVideo.isMuted(), callback);
  11453. };
  11454. JingleSession.prototype.hardMuteVideo = function (muted) {
  11455. this.pendingop = muted ? 'mute' : 'unmute';
  11456. };
  11457. JingleSession.prototype.sendMute = function (muted, content) {
  11458. var info = $iq({to: this.peerjid,
  11459. type: 'set'})
  11460. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11461. action: 'session-info',
  11462. initiator: this.initiator,
  11463. sid: this.sid });
  11464. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11465. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  11466. if (content) {
  11467. info.attrs({'name': content});
  11468. }
  11469. this.connection.send(info);
  11470. };
  11471. JingleSession.prototype.sendRinging = function () {
  11472. var info = $iq({to: this.peerjid,
  11473. type: 'set'})
  11474. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11475. action: 'session-info',
  11476. initiator: this.initiator,
  11477. sid: this.sid });
  11478. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11479. this.connection.send(info);
  11480. };
  11481. JingleSession.prototype.getStats = function (interval) {
  11482. var self = this;
  11483. var recv = {audio: 0, video: 0};
  11484. var lost = {audio: 0, video: 0};
  11485. var lastrecv = {audio: 0, video: 0};
  11486. var lastlost = {audio: 0, video: 0};
  11487. var loss = {audio: 0, video: 0};
  11488. var delta = {audio: 0, video: 0};
  11489. this.statsinterval = window.setInterval(function () {
  11490. if (self && self.peerconnection && self.peerconnection.getStats) {
  11491. self.peerconnection.getStats(function (stats) {
  11492. var results = stats.result();
  11493. // TODO: there are so much statistics you can get from this..
  11494. for (var i = 0; i < results.length; ++i) {
  11495. if (results[i].type == 'ssrc') {
  11496. var packetsrecv = results[i].stat('packetsReceived');
  11497. var packetslost = results[i].stat('packetsLost');
  11498. if (packetsrecv && packetslost) {
  11499. packetsrecv = parseInt(packetsrecv, 10);
  11500. packetslost = parseInt(packetslost, 10);
  11501. if (results[i].stat('googFrameRateReceived')) {
  11502. lastlost.video = lost.video;
  11503. lastrecv.video = recv.video;
  11504. recv.video = packetsrecv;
  11505. lost.video = packetslost;
  11506. } else {
  11507. lastlost.audio = lost.audio;
  11508. lastrecv.audio = recv.audio;
  11509. recv.audio = packetsrecv;
  11510. lost.audio = packetslost;
  11511. }
  11512. }
  11513. }
  11514. }
  11515. delta.audio = recv.audio - lastrecv.audio;
  11516. delta.video = recv.video - lastrecv.video;
  11517. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  11518. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  11519. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  11520. });
  11521. }
  11522. }, interval || 3000);
  11523. return this.statsinterval;
  11524. };
  11525. JingleSession.onJingleError = function (session, error)
  11526. {
  11527. console.error("Jingle error", error);
  11528. }
  11529. JingleSession.onJingleFatalError = function (session, error)
  11530. {
  11531. this.service.sessionTerminated = true;
  11532. this.connection.emuc.doLeave();
  11533. APP.UI.messageHandler.showError("dialog.sorry",
  11534. "dialog.internalError");
  11535. }
  11536. JingleSession.prototype.setLocalDescription = function () {
  11537. // put our ssrcs into presence so other clients can identify our stream
  11538. var newssrcs = [];
  11539. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  11540. media.forEach(function (media) {
  11541. if(Object.keys(media.sources).length > 0) {
  11542. // TODO(gp) maybe exclude FID streams?
  11543. Object.keys(media.sources).forEach(function (ssrc) {
  11544. newssrcs.push({
  11545. 'ssrc': ssrc,
  11546. 'type': media.type,
  11547. 'direction': media.direction
  11548. });
  11549. });
  11550. }
  11551. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  11552. {
  11553. newssrcs.push({
  11554. 'ssrc': this.localStreamsSSRC[media.type],
  11555. 'type': media.type,
  11556. 'direction': media.direction
  11557. });
  11558. }
  11559. });
  11560. console.log('new ssrcs', newssrcs);
  11561. // Have to clear presence map to get rid of removed streams
  11562. this.connection.emuc.clearPresenceMedia();
  11563. if (newssrcs.length > 0) {
  11564. for (var i = 1; i <= newssrcs.length; i ++) {
  11565. // Change video type to screen
  11566. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  11567. newssrcs[i-1].type = 'screen';
  11568. }
  11569. this.connection.emuc.addMediaToPresence(i,
  11570. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  11571. }
  11572. this.connection.emuc.sendPresence();
  11573. }
  11574. }
  11575. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11576. function sendKeyframe(pc) {
  11577. console.log('sendkeyframe', pc.iceConnectionState);
  11578. if (pc.iceConnectionState !== 'connected') return; // safe...
  11579. pc.setRemoteDescription(
  11580. pc.remoteDescription,
  11581. function () {
  11582. pc.createAnswer(
  11583. function (modifiedAnswer) {
  11584. pc.setLocalDescription(
  11585. modifiedAnswer,
  11586. function () {
  11587. // noop
  11588. },
  11589. function (error) {
  11590. console.log('triggerKeyframe setLocalDescription failed', error);
  11591. APP.UI.messageHandler.showError();
  11592. }
  11593. );
  11594. },
  11595. function (error) {
  11596. console.log('triggerKeyframe createAnswer failed', error);
  11597. APP.UI.messageHandler.showError();
  11598. }
  11599. );
  11600. },
  11601. function (error) {
  11602. console.log('triggerKeyframe setRemoteDescription failed', error);
  11603. APP.UI.messageHandler.showError();
  11604. }
  11605. );
  11606. }
  11607. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  11608. var self = this;
  11609. var thessrc;
  11610. var ssrc2jid = this.connection.emuc.ssrc2jid;
  11611. // look up an associated JID for a stream id
  11612. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  11613. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  11614. var ssrclines
  11615. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  11616. ssrclines = ssrclines.filter(function (line) {
  11617. // NOTE(gp) previously we filtered on the mslabel, but that property
  11618. // is not always present.
  11619. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  11620. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  11621. });
  11622. if (ssrclines.length) {
  11623. thessrc = ssrclines[0].substring(7).split(' ')[0];
  11624. // We signal our streams (through Jingle to the focus) before we set
  11625. // our presence (through which peers associate remote streams to
  11626. // jids). So, it might arrive that a remote stream is added but
  11627. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  11628. // successfully set. Here we wait for up to a second for the
  11629. // presence to arrive.
  11630. if (!ssrc2jid[thessrc]) {
  11631. if (typeof times === 'undefined')
  11632. {
  11633. times = 0;
  11634. }
  11635. if (times > 10)
  11636. {
  11637. console.warning('Waiting for jid timed out', thessrc);
  11638. }
  11639. else
  11640. {
  11641. setTimeout(function(d) {
  11642. return function() {
  11643. self.remoteStreamAdded(d, times++);
  11644. }
  11645. }(data), 250);
  11646. }
  11647. return;
  11648. }
  11649. // ok to overwrite the one from focus? might save work in colibri.js
  11650. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  11651. if (ssrc2jid[thessrc]) {
  11652. data.peerjid = ssrc2jid[thessrc];
  11653. }
  11654. }
  11655. }
  11656. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  11657. var isVideo = data.stream.getVideoTracks().length > 0;
  11658. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11659. if (isVideo &&
  11660. data.peerjid && this.peerjid === data.peerjid &&
  11661. data.stream.getVideoTracks().length === 0 &&
  11662. APP.RTC.localVideo.getTracks().length > 0) {
  11663. window.setTimeout(function () {
  11664. sendKeyframe(self.peerconnection);
  11665. }, 3000);
  11666. }
  11667. }
  11668. module.exports = JingleSession;
  11669. },{"../../service/RTC/RTCBrowserType":88,"./SDP":49,"./SDPDiffer":50,"./SDPUtil":51,"./TraceablePeerConnection":52}],49:[function(require,module,exports){
  11670. /* jshint -W117 */
  11671. var SDPUtil = require("./SDPUtil");
  11672. // SDP STUFF
  11673. function SDP(sdp) {
  11674. this.media = sdp.split('\r\nm=');
  11675. for (var i = 1; i < this.media.length; i++) {
  11676. this.media[i] = 'm=' + this.media[i];
  11677. if (i != this.media.length - 1) {
  11678. this.media[i] += '\r\n';
  11679. }
  11680. }
  11681. this.session = this.media.shift() + '\r\n';
  11682. this.raw = this.session + this.media.join('');
  11683. }
  11684. /**
  11685. * Returns map of MediaChannel mapped per channel idx.
  11686. */
  11687. SDP.prototype.getMediaSsrcMap = function() {
  11688. var self = this;
  11689. var media_ssrcs = {};
  11690. var tmp;
  11691. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  11692. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  11693. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  11694. var media = {
  11695. mediaindex: mediaindex,
  11696. mid: mid,
  11697. ssrcs: {},
  11698. ssrcGroups: []
  11699. };
  11700. media_ssrcs[mediaindex] = media;
  11701. tmp.forEach(function (line) {
  11702. var linessrc = line.substring(7).split(' ')[0];
  11703. // allocate new ChannelSsrc
  11704. if(!media.ssrcs[linessrc]) {
  11705. media.ssrcs[linessrc] = {
  11706. ssrc: linessrc,
  11707. lines: []
  11708. };
  11709. }
  11710. media.ssrcs[linessrc].lines.push(line);
  11711. });
  11712. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  11713. tmp.forEach(function(line){
  11714. var semantics = line.substr(0, idx).substr(13);
  11715. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11716. if (ssrcs.length != 0) {
  11717. media.ssrcGroups.push({
  11718. semantics: semantics,
  11719. ssrcs: ssrcs
  11720. });
  11721. }
  11722. });
  11723. }
  11724. return media_ssrcs;
  11725. };
  11726. /**
  11727. * Returns <tt>true</tt> if this SDP contains given SSRC.
  11728. * @param ssrc the ssrc to check.
  11729. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  11730. */
  11731. SDP.prototype.containsSSRC = function(ssrc) {
  11732. var medias = this.getMediaSsrcMap();
  11733. var contains = false;
  11734. Object.keys(medias).forEach(function(mediaindex){
  11735. var media = medias[mediaindex];
  11736. //console.log("Check", channel, ssrc);
  11737. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  11738. contains = true;
  11739. }
  11740. });
  11741. return contains;
  11742. };
  11743. // remove iSAC and CN from SDP
  11744. SDP.prototype.mangle = function () {
  11745. var i, j, mline, lines, rtpmap, newdesc;
  11746. for (i = 0; i < this.media.length; i++) {
  11747. lines = this.media[i].split('\r\n');
  11748. lines.pop(); // remove empty last element
  11749. mline = SDPUtil.parse_mline(lines.shift());
  11750. if (mline.media != 'audio')
  11751. continue;
  11752. newdesc = '';
  11753. mline.fmt.length = 0;
  11754. for (j = 0; j < lines.length; j++) {
  11755. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  11756. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  11757. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  11758. continue;
  11759. mline.fmt.push(rtpmap.id);
  11760. newdesc += lines[j] + '\r\n';
  11761. } else {
  11762. newdesc += lines[j] + '\r\n';
  11763. }
  11764. }
  11765. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  11766. this.media[i] += newdesc;
  11767. }
  11768. this.raw = this.session + this.media.join('');
  11769. };
  11770. // remove lines matching prefix from session section
  11771. SDP.prototype.removeSessionLines = function(prefix) {
  11772. var self = this;
  11773. var lines = SDPUtil.find_lines(this.session, prefix);
  11774. lines.forEach(function(line) {
  11775. self.session = self.session.replace(line + '\r\n', '');
  11776. });
  11777. this.raw = this.session + this.media.join('');
  11778. return lines;
  11779. }
  11780. // remove lines matching prefix from a media section specified by mediaindex
  11781. // TODO: non-numeric mediaindex could match mid
  11782. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  11783. var self = this;
  11784. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  11785. lines.forEach(function(line) {
  11786. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  11787. });
  11788. this.raw = this.session + this.media.join('');
  11789. return lines;
  11790. }
  11791. // add content's to a jingle element
  11792. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  11793. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  11794. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  11795. var self = this;
  11796. // new bundle plan
  11797. if (SDPUtil.find_line(this.session, 'a=group:')) {
  11798. lines = SDPUtil.find_lines(this.session, 'a=group:');
  11799. for (i = 0; i < lines.length; i++) {
  11800. tmp = lines[i].split(' ');
  11801. var semantics = tmp.shift().substr(8);
  11802. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  11803. for (j = 0; j < tmp.length; j++) {
  11804. elem.c('content', {name: tmp[j]}).up();
  11805. }
  11806. elem.up();
  11807. }
  11808. }
  11809. for (i = 0; i < this.media.length; i++) {
  11810. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  11811. if (!(mline.media === 'audio' ||
  11812. mline.media === 'video' ||
  11813. mline.media === 'application'))
  11814. {
  11815. continue;
  11816. }
  11817. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  11818. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  11819. } else {
  11820. if(ssrcs && ssrcs[mline.media])
  11821. {
  11822. ssrc = ssrcs[mline.media];
  11823. }
  11824. else
  11825. ssrc = false;
  11826. }
  11827. elem.c('content', {creator: thecreator, name: mline.media});
  11828. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  11829. // prefer identifier from a=mid if present
  11830. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  11831. elem.attrs({ name: mid });
  11832. }
  11833. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  11834. {
  11835. elem.c('description',
  11836. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  11837. media: mline.media });
  11838. if (ssrc) {
  11839. elem.attrs({ssrc: ssrc});
  11840. }
  11841. for (j = 0; j < mline.fmt.length; j++) {
  11842. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  11843. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  11844. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  11845. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  11846. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  11847. for (k = 0; k < tmp.length; k++) {
  11848. elem.c('parameter', tmp[k]).up();
  11849. }
  11850. }
  11851. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  11852. elem.up();
  11853. }
  11854. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  11855. elem.c('encryption', {required: 1});
  11856. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  11857. crypto.forEach(function(line) {
  11858. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  11859. });
  11860. elem.up(); // end of encryption
  11861. }
  11862. if (ssrc) {
  11863. // new style mapping
  11864. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11865. // FIXME: group by ssrc and support multiple different ssrcs
  11866. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  11867. if(ssrclines.length > 0) {
  11868. ssrclines.forEach(function (line) {
  11869. idx = line.indexOf(' ');
  11870. var linessrc = line.substr(0, idx).substr(7);
  11871. if (linessrc != ssrc) {
  11872. elem.up();
  11873. ssrc = linessrc;
  11874. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11875. }
  11876. var kv = line.substr(idx + 1);
  11877. elem.c('parameter');
  11878. if (kv.indexOf(':') == -1) {
  11879. elem.attrs({ name: kv });
  11880. } else {
  11881. elem.attrs({ name: kv.split(':', 2)[0] });
  11882. elem.attrs({ value: kv.split(':', 2)[1] });
  11883. }
  11884. elem.up();
  11885. });
  11886. elem.up();
  11887. }
  11888. else
  11889. {
  11890. elem.up();
  11891. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11892. elem.c('parameter');
  11893. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  11894. elem.up();
  11895. var msid = null;
  11896. if(mline.media == "audio")
  11897. {
  11898. msid = APP.RTC.localAudio.getId();
  11899. }
  11900. else
  11901. {
  11902. msid = APP.RTC.localVideo.getId();
  11903. }
  11904. if(msid != null)
  11905. {
  11906. msid = msid.replace(/[\{,\}]/g,"");
  11907. elem.c('parameter');
  11908. elem.attrs({name: "msid", value:msid});
  11909. elem.up();
  11910. elem.c('parameter');
  11911. elem.attrs({name: "mslabel", value:msid});
  11912. elem.up();
  11913. elem.c('parameter');
  11914. elem.attrs({name: "label", value:msid});
  11915. elem.up();
  11916. elem.up();
  11917. }
  11918. }
  11919. // XEP-0339 handle ssrc-group attributes
  11920. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  11921. ssrc_group_lines.forEach(function(line) {
  11922. idx = line.indexOf(' ');
  11923. var semantics = line.substr(0, idx).substr(13);
  11924. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11925. if (ssrcs.length != 0) {
  11926. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11927. ssrcs.forEach(function(ssrc) {
  11928. elem.c('source', { ssrc: ssrc })
  11929. .up();
  11930. });
  11931. elem.up();
  11932. }
  11933. });
  11934. }
  11935. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  11936. elem.c('rtcp-mux').up();
  11937. }
  11938. // XEP-0293 -- map a=rtcp-fb:*
  11939. this.RtcpFbToJingle(i, elem, '*');
  11940. // XEP-0294
  11941. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  11942. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  11943. for (j = 0; j < lines.length; j++) {
  11944. tmp = SDPUtil.parse_extmap(lines[j]);
  11945. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  11946. uri: tmp.uri,
  11947. id: tmp.value });
  11948. if (tmp.hasOwnProperty('direction')) {
  11949. switch (tmp.direction) {
  11950. case 'sendonly':
  11951. elem.attrs({senders: 'responder'});
  11952. break;
  11953. case 'recvonly':
  11954. elem.attrs({senders: 'initiator'});
  11955. break;
  11956. case 'sendrecv':
  11957. elem.attrs({senders: 'both'});
  11958. break;
  11959. case 'inactive':
  11960. elem.attrs({senders: 'none'});
  11961. break;
  11962. }
  11963. }
  11964. // TODO: handle params
  11965. elem.up();
  11966. }
  11967. }
  11968. elem.up(); // end of description
  11969. }
  11970. // map ice-ufrag/pwd, dtls fingerprint, candidates
  11971. this.TransportToJingle(i, elem);
  11972. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  11973. elem.attrs({senders: 'both'});
  11974. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  11975. elem.attrs({senders: 'initiator'});
  11976. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  11977. elem.attrs({senders: 'responder'});
  11978. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  11979. elem.attrs({senders: 'none'});
  11980. }
  11981. if (mline.port == '0') {
  11982. // estos hack to reject an m-line
  11983. elem.attrs({senders: 'rejected'});
  11984. }
  11985. elem.up(); // end of content
  11986. }
  11987. elem.up();
  11988. return elem;
  11989. };
  11990. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  11991. var i = mediaindex;
  11992. var tmp;
  11993. var self = this;
  11994. elem.c('transport');
  11995. // XEP-0343 DTLS/SCTP
  11996. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  11997. {
  11998. var sctpmap = SDPUtil.find_line(
  11999. this.media[i], 'a=sctpmap:', self.session);
  12000. if (sctpmap)
  12001. {
  12002. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  12003. elem.c('sctpmap',
  12004. {
  12005. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  12006. number: sctpAttrs[0], /* SCTP port */
  12007. protocol: sctpAttrs[1], /* protocol */
  12008. });
  12009. // Optional stream count attribute
  12010. if (sctpAttrs.length > 2)
  12011. elem.attrs({ streams: sctpAttrs[2]});
  12012. elem.up();
  12013. }
  12014. }
  12015. // XEP-0320
  12016. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  12017. fingerprints.forEach(function(line) {
  12018. tmp = SDPUtil.parse_fingerprint(line);
  12019. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  12020. elem.c('fingerprint').t(tmp.fingerprint);
  12021. delete tmp.fingerprint;
  12022. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  12023. if (line) {
  12024. tmp.setup = line.substr(8);
  12025. }
  12026. elem.attrs(tmp);
  12027. elem.up(); // end of fingerprint
  12028. });
  12029. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  12030. if (tmp) {
  12031. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12032. elem.attrs(tmp);
  12033. // XEP-0176
  12034. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  12035. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  12036. lines.forEach(function (line) {
  12037. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  12038. });
  12039. }
  12040. }
  12041. elem.up(); // end of transport
  12042. }
  12043. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  12044. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  12045. lines.forEach(function (line) {
  12046. var tmp = SDPUtil.parse_rtcpfb(line);
  12047. if (tmp.type == 'trr-int') {
  12048. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  12049. elem.up();
  12050. } else {
  12051. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  12052. if (tmp.params.length > 0) {
  12053. elem.attrs({'subtype': tmp.params[0]});
  12054. }
  12055. elem.up();
  12056. }
  12057. });
  12058. };
  12059. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  12060. var media = '';
  12061. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12062. if (tmp.length) {
  12063. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  12064. if (tmp.attr('value')) {
  12065. media += tmp.attr('value');
  12066. } else {
  12067. media += '0';
  12068. }
  12069. media += '\r\n';
  12070. }
  12071. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12072. tmp.each(function () {
  12073. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  12074. if ($(this).attr('subtype')) {
  12075. media += ' ' + $(this).attr('subtype');
  12076. }
  12077. media += '\r\n';
  12078. });
  12079. return media;
  12080. };
  12081. // construct an SDP from a jingle stanza
  12082. SDP.prototype.fromJingle = function (jingle) {
  12083. var self = this;
  12084. this.raw = 'v=0\r\n' +
  12085. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12086. 's=-\r\n' +
  12087. 't=0 0\r\n';
  12088. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  12089. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  12090. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  12091. var contents = $(group).find('>content').map(function (idx, content) {
  12092. return content.getAttribute('name');
  12093. }).get();
  12094. if (contents.length > 0) {
  12095. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  12096. }
  12097. });
  12098. }
  12099. this.session = this.raw;
  12100. jingle.find('>content').each(function () {
  12101. var m = self.jingle2media($(this));
  12102. self.media.push(m);
  12103. });
  12104. // reconstruct msid-semantic -- apparently not necessary
  12105. /*
  12106. var msid = SDPUtil.parse_ssrc(this.raw);
  12107. if (msid.hasOwnProperty('mslabel')) {
  12108. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  12109. }
  12110. */
  12111. this.raw = this.session + this.media.join('');
  12112. };
  12113. // translate a jingle content element into an an SDP media part
  12114. SDP.prototype.jingle2media = function (content) {
  12115. var media = '',
  12116. desc = content.find('description'),
  12117. ssrc = desc.attr('ssrc'),
  12118. self = this,
  12119. tmp;
  12120. var sctp = content.find(
  12121. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  12122. tmp = { media: desc.attr('media') };
  12123. tmp.port = '1';
  12124. if (content.attr('senders') == 'rejected') {
  12125. // estos hack to reject an m-line.
  12126. tmp.port = '0';
  12127. }
  12128. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  12129. if (sctp.length)
  12130. tmp.proto = 'DTLS/SCTP';
  12131. else
  12132. tmp.proto = 'RTP/SAVPF';
  12133. } else {
  12134. tmp.proto = 'RTP/AVPF';
  12135. }
  12136. if (!sctp.length)
  12137. {
  12138. tmp.fmt = desc.find('payload-type').map(
  12139. function () { return this.getAttribute('id'); }).get();
  12140. media += SDPUtil.build_mline(tmp) + '\r\n';
  12141. }
  12142. else
  12143. {
  12144. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  12145. media += 'a=sctpmap:' + sctp.attr('number') +
  12146. ' ' + sctp.attr('protocol');
  12147. var streamCount = sctp.attr('streams');
  12148. if (streamCount)
  12149. media += ' ' + streamCount + '\r\n';
  12150. else
  12151. media += '\r\n';
  12152. }
  12153. media += 'c=IN IP4 0.0.0.0\r\n';
  12154. if (!sctp.length)
  12155. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  12156. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  12157. if (tmp.length) {
  12158. if (tmp.attr('ufrag')) {
  12159. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  12160. }
  12161. if (tmp.attr('pwd')) {
  12162. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  12163. }
  12164. tmp.find('>fingerprint').each(function () {
  12165. // FIXME: check namespace at some point
  12166. media += 'a=fingerprint:' + this.getAttribute('hash');
  12167. media += ' ' + $(this).text();
  12168. media += '\r\n';
  12169. if (this.getAttribute('setup')) {
  12170. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  12171. }
  12172. });
  12173. }
  12174. switch (content.attr('senders')) {
  12175. case 'initiator':
  12176. media += 'a=sendonly\r\n';
  12177. break;
  12178. case 'responder':
  12179. media += 'a=recvonly\r\n';
  12180. break;
  12181. case 'none':
  12182. media += 'a=inactive\r\n';
  12183. break;
  12184. case 'both':
  12185. media += 'a=sendrecv\r\n';
  12186. break;
  12187. }
  12188. media += 'a=mid:' + content.attr('name') + '\r\n';
  12189. // <description><rtcp-mux/></description>
  12190. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  12191. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  12192. if (desc.find('rtcp-mux').length) {
  12193. media += 'a=rtcp-mux\r\n';
  12194. }
  12195. if (desc.find('encryption').length) {
  12196. desc.find('encryption>crypto').each(function () {
  12197. media += 'a=crypto:' + this.getAttribute('tag');
  12198. media += ' ' + this.getAttribute('crypto-suite');
  12199. media += ' ' + this.getAttribute('key-params');
  12200. if (this.getAttribute('session-params')) {
  12201. media += ' ' + this.getAttribute('session-params');
  12202. }
  12203. media += '\r\n';
  12204. });
  12205. }
  12206. desc.find('payload-type').each(function () {
  12207. media += SDPUtil.build_rtpmap(this) + '\r\n';
  12208. if ($(this).find('>parameter').length) {
  12209. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  12210. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  12211. media += '\r\n';
  12212. }
  12213. // xep-0293
  12214. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  12215. });
  12216. // xep-0293
  12217. media += self.RtcpFbFromJingle(desc, '*');
  12218. // xep-0294
  12219. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  12220. tmp.each(function () {
  12221. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  12222. });
  12223. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  12224. media += SDPUtil.candidateFromJingle(this);
  12225. });
  12226. // XEP-0339 handle ssrc-group attributes
  12227. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12228. var semantics = this.getAttribute('semantics');
  12229. var ssrcs = $(this).find('>source').map(function() {
  12230. return this.getAttribute('ssrc');
  12231. }).get();
  12232. if (ssrcs.length != 0) {
  12233. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12234. }
  12235. });
  12236. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12237. tmp.each(function () {
  12238. var ssrc = this.getAttribute('ssrc');
  12239. $(this).find('>parameter').each(function () {
  12240. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  12241. if (this.getAttribute('value') && this.getAttribute('value').length)
  12242. media += ':' + this.getAttribute('value');
  12243. media += '\r\n';
  12244. });
  12245. });
  12246. return media;
  12247. };
  12248. module.exports = SDP;
  12249. },{"./SDPUtil":51}],50:[function(require,module,exports){
  12250. function SDPDiffer(mySDP, otherSDP) {
  12251. this.mySDP = mySDP;
  12252. this.otherSDP = otherSDP;
  12253. }
  12254. /**
  12255. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  12256. * @param otherSdp the other SDP to check ssrc with.
  12257. */
  12258. SDPDiffer.prototype.getNewMedia = function() {
  12259. // this could be useful in Array.prototype.
  12260. function arrayEquals(array) {
  12261. // if the other array is a falsy value, return
  12262. if (!array)
  12263. return false;
  12264. // compare lengths - can save a lot of time
  12265. if (this.length != array.length)
  12266. return false;
  12267. for (var i = 0, l=this.length; i < l; i++) {
  12268. // Check if we have nested arrays
  12269. if (this[i] instanceof Array && array[i] instanceof Array) {
  12270. // recurse into the nested arrays
  12271. if (!this[i].equals(array[i]))
  12272. return false;
  12273. }
  12274. else if (this[i] != array[i]) {
  12275. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12276. return false;
  12277. }
  12278. }
  12279. return true;
  12280. }
  12281. var myMedias = this.mySDP.getMediaSsrcMap();
  12282. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12283. var newMedia = {};
  12284. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12285. var myMedia = myMedias[othersMediaIdx];
  12286. var othersMedia = othersMedias[othersMediaIdx];
  12287. if(!myMedia && othersMedia) {
  12288. // Add whole channel
  12289. newMedia[othersMediaIdx] = othersMedia;
  12290. return;
  12291. }
  12292. // Look for new ssrcs accross the channel
  12293. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12294. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12295. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12296. if(!newMedia[othersMediaIdx]){
  12297. newMedia[othersMediaIdx] = {
  12298. mediaindex: othersMedia.mediaindex,
  12299. mid: othersMedia.mid,
  12300. ssrcs: {},
  12301. ssrcGroups: []
  12302. };
  12303. }
  12304. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12305. }
  12306. });
  12307. // Look for new ssrc groups across the channels
  12308. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12309. // try to match the other ssrc-group with an ssrc-group of ours
  12310. var matched = false;
  12311. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12312. var mySsrcGroup = myMedia.ssrcGroups[i];
  12313. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12314. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12315. matched = true;
  12316. break;
  12317. }
  12318. }
  12319. if (!matched) {
  12320. // Allocate channel if we've found an ssrc-group that doesn't
  12321. // exist in our channel
  12322. if(!newMedia[othersMediaIdx]){
  12323. newMedia[othersMediaIdx] = {
  12324. mediaindex: othersMedia.mediaindex,
  12325. mid: othersMedia.mid,
  12326. ssrcs: {},
  12327. ssrcGroups: []
  12328. };
  12329. }
  12330. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12331. }
  12332. });
  12333. });
  12334. return newMedia;
  12335. };
  12336. /**
  12337. * Sends SSRC update IQ.
  12338. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12339. * @param sid session identifier that will be put into the IQ.
  12340. * @param initiator initiator identifier.
  12341. * @param toJid destination Jid
  12342. * @param isAdd indicates if this is remove or add operation.
  12343. */
  12344. SDPDiffer.prototype.toJingle = function(modify) {
  12345. var sdpMediaSsrcs = this.getNewMedia();
  12346. var self = this;
  12347. // FIXME: only announce video ssrcs since we mix audio and dont need
  12348. // the audio ssrcs therefore
  12349. var modified = false;
  12350. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12351. modified = true;
  12352. var media = sdpMediaSsrcs[mediaindex];
  12353. modify.c('content', {name: media.mid});
  12354. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12355. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12356. // generate sources from lines
  12357. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12358. var mediaSsrc = media.ssrcs[ssrcNum];
  12359. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12360. modify.attrs({ssrc: mediaSsrc.ssrc});
  12361. // iterate over ssrc lines
  12362. mediaSsrc.lines.forEach(function (line) {
  12363. var idx = line.indexOf(' ');
  12364. var kv = line.substr(idx + 1);
  12365. modify.c('parameter');
  12366. if (kv.indexOf(':') == -1) {
  12367. modify.attrs({ name: kv });
  12368. } else {
  12369. modify.attrs({ name: kv.split(':', 2)[0] });
  12370. modify.attrs({ value: kv.split(':', 2)[1] });
  12371. }
  12372. modify.up(); // end of parameter
  12373. });
  12374. modify.up(); // end of source
  12375. });
  12376. // generate source groups from lines
  12377. media.ssrcGroups.forEach(function(ssrcGroup) {
  12378. if (ssrcGroup.ssrcs.length != 0) {
  12379. modify.c('ssrc-group', {
  12380. semantics: ssrcGroup.semantics,
  12381. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12382. });
  12383. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12384. modify.c('source', { ssrc: ssrc })
  12385. .up(); // end of source
  12386. });
  12387. modify.up(); // end of ssrc-group
  12388. }
  12389. });
  12390. modify.up(); // end of description
  12391. modify.up(); // end of content
  12392. });
  12393. return modified;
  12394. };
  12395. module.exports = SDPDiffer;
  12396. },{}],51:[function(require,module,exports){
  12397. SDPUtil = {
  12398. iceparams: function (mediadesc, sessiondesc) {
  12399. var data = null;
  12400. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  12401. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  12402. data = {
  12403. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  12404. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  12405. };
  12406. }
  12407. return data;
  12408. },
  12409. parse_iceufrag: function (line) {
  12410. return line.substring(12);
  12411. },
  12412. build_iceufrag: function (frag) {
  12413. return 'a=ice-ufrag:' + frag;
  12414. },
  12415. parse_icepwd: function (line) {
  12416. return line.substring(10);
  12417. },
  12418. build_icepwd: function (pwd) {
  12419. return 'a=ice-pwd:' + pwd;
  12420. },
  12421. parse_mid: function (line) {
  12422. return line.substring(6);
  12423. },
  12424. parse_mline: function (line) {
  12425. var parts = line.substring(2).split(' '),
  12426. data = {};
  12427. data.media = parts.shift();
  12428. data.port = parts.shift();
  12429. data.proto = parts.shift();
  12430. if (parts[parts.length - 1] === '') { // trailing whitespace
  12431. parts.pop();
  12432. }
  12433. data.fmt = parts;
  12434. return data;
  12435. },
  12436. build_mline: function (mline) {
  12437. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  12438. },
  12439. parse_rtpmap: function (line) {
  12440. var parts = line.substring(9).split(' '),
  12441. data = {};
  12442. data.id = parts.shift();
  12443. parts = parts[0].split('/');
  12444. data.name = parts.shift();
  12445. data.clockrate = parts.shift();
  12446. data.channels = parts.length ? parts.shift() : '1';
  12447. return data;
  12448. },
  12449. /**
  12450. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  12451. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  12452. * @returns [SCTP port number, protocol, streams]
  12453. */
  12454. parse_sctpmap: function (line)
  12455. {
  12456. var parts = line.substring(10).split(' ');
  12457. var sctpPort = parts[0];
  12458. var protocol = parts[1];
  12459. // Stream count is optional
  12460. var streamCount = parts.length > 2 ? parts[2] : null;
  12461. return [sctpPort, protocol, streamCount];// SCTP port
  12462. },
  12463. build_rtpmap: function (el) {
  12464. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  12465. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  12466. line += '/' + el.getAttribute('channels');
  12467. }
  12468. return line;
  12469. },
  12470. parse_crypto: function (line) {
  12471. var parts = line.substring(9).split(' '),
  12472. data = {};
  12473. data.tag = parts.shift();
  12474. data['crypto-suite'] = parts.shift();
  12475. data['key-params'] = parts.shift();
  12476. if (parts.length) {
  12477. data['session-params'] = parts.join(' ');
  12478. }
  12479. return data;
  12480. },
  12481. parse_fingerprint: function (line) { // RFC 4572
  12482. var parts = line.substring(14).split(' '),
  12483. data = {};
  12484. data.hash = parts.shift();
  12485. data.fingerprint = parts.shift();
  12486. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  12487. return data;
  12488. },
  12489. parse_fmtp: function (line) {
  12490. var parts = line.split(' '),
  12491. i, key, value,
  12492. data = [];
  12493. parts.shift();
  12494. parts = parts.join(' ').split(';');
  12495. for (i = 0; i < parts.length; i++) {
  12496. key = parts[i].split('=')[0];
  12497. while (key.length && key[0] == ' ') {
  12498. key = key.substring(1);
  12499. }
  12500. value = parts[i].split('=')[1];
  12501. if (key && value) {
  12502. data.push({name: key, value: value});
  12503. } else if (key) {
  12504. // rfc 4733 (DTMF) style stuff
  12505. data.push({name: '', value: key});
  12506. }
  12507. }
  12508. return data;
  12509. },
  12510. parse_icecandidate: function (line) {
  12511. var candidate = {},
  12512. elems = line.split(' ');
  12513. candidate.foundation = elems[0].substring(12);
  12514. candidate.component = elems[1];
  12515. candidate.protocol = elems[2].toLowerCase();
  12516. candidate.priority = elems[3];
  12517. candidate.ip = elems[4];
  12518. candidate.port = elems[5];
  12519. // elems[6] => "typ"
  12520. candidate.type = elems[7];
  12521. candidate.generation = 0; // default value, may be overwritten below
  12522. for (var i = 8; i < elems.length; i += 2) {
  12523. switch (elems[i]) {
  12524. case 'raddr':
  12525. candidate['rel-addr'] = elems[i + 1];
  12526. break;
  12527. case 'rport':
  12528. candidate['rel-port'] = elems[i + 1];
  12529. break;
  12530. case 'generation':
  12531. candidate.generation = elems[i + 1];
  12532. break;
  12533. case 'tcptype':
  12534. candidate.tcptype = elems[i + 1];
  12535. break;
  12536. default: // TODO
  12537. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12538. }
  12539. }
  12540. candidate.network = '1';
  12541. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12542. return candidate;
  12543. },
  12544. build_icecandidate: function (cand) {
  12545. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  12546. line += ' ';
  12547. switch (cand.type) {
  12548. case 'srflx':
  12549. case 'prflx':
  12550. case 'relay':
  12551. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  12552. line += 'raddr';
  12553. line += ' ';
  12554. line += cand['rel-addr'];
  12555. line += ' ';
  12556. line += 'rport';
  12557. line += ' ';
  12558. line += cand['rel-port'];
  12559. line += ' ';
  12560. }
  12561. break;
  12562. }
  12563. if (cand.hasOwnAttribute('tcptype')) {
  12564. line += 'tcptype';
  12565. line += ' ';
  12566. line += cand.tcptype;
  12567. line += ' ';
  12568. }
  12569. line += 'generation';
  12570. line += ' ';
  12571. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  12572. return line;
  12573. },
  12574. parse_ssrc: function (desc) {
  12575. // proprietary mapping of a=ssrc lines
  12576. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  12577. // and parse according to that
  12578. var lines = desc.split('\r\n'),
  12579. data = {};
  12580. for (var i = 0; i < lines.length; i++) {
  12581. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  12582. var idx = lines[i].indexOf(' ');
  12583. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  12584. }
  12585. }
  12586. return data;
  12587. },
  12588. parse_rtcpfb: function (line) {
  12589. var parts = line.substr(10).split(' ');
  12590. var data = {};
  12591. data.pt = parts.shift();
  12592. data.type = parts.shift();
  12593. data.params = parts;
  12594. return data;
  12595. },
  12596. parse_extmap: function (line) {
  12597. var parts = line.substr(9).split(' ');
  12598. var data = {};
  12599. data.value = parts.shift();
  12600. if (data.value.indexOf('/') != -1) {
  12601. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  12602. data.value = data.value.substr(0, data.value.indexOf('/'));
  12603. } else {
  12604. data.direction = 'both';
  12605. }
  12606. data.uri = parts.shift();
  12607. data.params = parts;
  12608. return data;
  12609. },
  12610. find_line: function (haystack, needle, sessionpart) {
  12611. var lines = haystack.split('\r\n');
  12612. for (var i = 0; i < lines.length; i++) {
  12613. if (lines[i].substring(0, needle.length) == needle) {
  12614. return lines[i];
  12615. }
  12616. }
  12617. if (!sessionpart) {
  12618. return false;
  12619. }
  12620. // search session part
  12621. lines = sessionpart.split('\r\n');
  12622. for (var j = 0; j < lines.length; j++) {
  12623. if (lines[j].substring(0, needle.length) == needle) {
  12624. return lines[j];
  12625. }
  12626. }
  12627. return false;
  12628. },
  12629. find_lines: function (haystack, needle, sessionpart) {
  12630. var lines = haystack.split('\r\n'),
  12631. needles = [];
  12632. for (var i = 0; i < lines.length; i++) {
  12633. if (lines[i].substring(0, needle.length) == needle)
  12634. needles.push(lines[i]);
  12635. }
  12636. if (needles.length || !sessionpart) {
  12637. return needles;
  12638. }
  12639. // search session part
  12640. lines = sessionpart.split('\r\n');
  12641. for (var j = 0; j < lines.length; j++) {
  12642. if (lines[j].substring(0, needle.length) == needle) {
  12643. needles.push(lines[j]);
  12644. }
  12645. }
  12646. return needles;
  12647. },
  12648. candidateToJingle: function (line) {
  12649. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  12650. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  12651. if (line.indexOf('candidate:') === 0) {
  12652. line = 'a=' + line;
  12653. } else if (line.substring(0, 12) != 'a=candidate:') {
  12654. console.log('parseCandidate called with a line that is not a candidate line');
  12655. console.log(line);
  12656. return null;
  12657. }
  12658. if (line.substring(line.length - 2) == '\r\n') // chomp it
  12659. line = line.substring(0, line.length - 2);
  12660. var candidate = {},
  12661. elems = line.split(' '),
  12662. i;
  12663. if (elems[6] != 'typ') {
  12664. console.log('did not find typ in the right place');
  12665. console.log(line);
  12666. return null;
  12667. }
  12668. candidate.foundation = elems[0].substring(12);
  12669. candidate.component = elems[1];
  12670. candidate.protocol = elems[2].toLowerCase();
  12671. candidate.priority = elems[3];
  12672. candidate.ip = elems[4];
  12673. candidate.port = elems[5];
  12674. // elems[6] => "typ"
  12675. candidate.type = elems[7];
  12676. candidate.generation = '0'; // default, may be overwritten below
  12677. for (i = 8; i < elems.length; i += 2) {
  12678. switch (elems[i]) {
  12679. case 'raddr':
  12680. candidate['rel-addr'] = elems[i + 1];
  12681. break;
  12682. case 'rport':
  12683. candidate['rel-port'] = elems[i + 1];
  12684. break;
  12685. case 'generation':
  12686. candidate.generation = elems[i + 1];
  12687. break;
  12688. case 'tcptype':
  12689. candidate.tcptype = elems[i + 1];
  12690. break;
  12691. default: // TODO
  12692. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12693. }
  12694. }
  12695. candidate.network = '1';
  12696. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12697. return candidate;
  12698. },
  12699. candidateFromJingle: function (cand) {
  12700. var line = 'a=candidate:';
  12701. line += cand.getAttribute('foundation');
  12702. line += ' ';
  12703. line += cand.getAttribute('component');
  12704. line += ' ';
  12705. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  12706. line += ' ';
  12707. line += cand.getAttribute('priority');
  12708. line += ' ';
  12709. line += cand.getAttribute('ip');
  12710. line += ' ';
  12711. line += cand.getAttribute('port');
  12712. line += ' ';
  12713. line += 'typ';
  12714. line += ' ' + cand.getAttribute('type');
  12715. line += ' ';
  12716. switch (cand.getAttribute('type')) {
  12717. case 'srflx':
  12718. case 'prflx':
  12719. case 'relay':
  12720. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  12721. line += 'raddr';
  12722. line += ' ';
  12723. line += cand.getAttribute('rel-addr');
  12724. line += ' ';
  12725. line += 'rport';
  12726. line += ' ';
  12727. line += cand.getAttribute('rel-port');
  12728. line += ' ';
  12729. }
  12730. break;
  12731. }
  12732. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  12733. line += 'tcptype';
  12734. line += ' ';
  12735. line += cand.getAttribute('tcptype');
  12736. line += ' ';
  12737. }
  12738. line += 'generation';
  12739. line += ' ';
  12740. line += cand.getAttribute('generation') || '0';
  12741. return line + '\r\n';
  12742. }
  12743. };
  12744. module.exports = SDPUtil;
  12745. },{}],52:[function(require,module,exports){
  12746. function TraceablePeerConnection(ice_config, constraints) {
  12747. var self = this;
  12748. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  12749. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  12750. this.updateLog = [];
  12751. this.stats = {};
  12752. this.statsinterval = null;
  12753. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  12754. var Interop = require('sdp-interop').Interop;
  12755. this.interop = new Interop();
  12756. // override as desired
  12757. this.trace = function (what, info) {
  12758. //console.warn('WTRACE', what, info);
  12759. self.updateLog.push({
  12760. time: new Date(),
  12761. type: what,
  12762. value: info || ""
  12763. });
  12764. };
  12765. this.onicecandidate = null;
  12766. this.peerconnection.onicecandidate = function (event) {
  12767. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  12768. if (self.onicecandidate !== null) {
  12769. self.onicecandidate(event);
  12770. }
  12771. };
  12772. this.onaddstream = null;
  12773. this.peerconnection.onaddstream = function (event) {
  12774. self.trace('onaddstream', event.stream.id);
  12775. if (self.onaddstream !== null) {
  12776. self.onaddstream(event);
  12777. }
  12778. };
  12779. this.onremovestream = null;
  12780. this.peerconnection.onremovestream = function (event) {
  12781. self.trace('onremovestream', event.stream.id);
  12782. if (self.onremovestream !== null) {
  12783. self.onremovestream(event);
  12784. }
  12785. };
  12786. this.onsignalingstatechange = null;
  12787. this.peerconnection.onsignalingstatechange = function (event) {
  12788. self.trace('onsignalingstatechange', self.signalingState);
  12789. if (self.onsignalingstatechange !== null) {
  12790. self.onsignalingstatechange(event);
  12791. }
  12792. };
  12793. this.oniceconnectionstatechange = null;
  12794. this.peerconnection.oniceconnectionstatechange = function (event) {
  12795. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12796. if (self.oniceconnectionstatechange !== null) {
  12797. self.oniceconnectionstatechange(event);
  12798. }
  12799. };
  12800. this.onnegotiationneeded = null;
  12801. this.peerconnection.onnegotiationneeded = function (event) {
  12802. self.trace('onnegotiationneeded');
  12803. if (self.onnegotiationneeded !== null) {
  12804. self.onnegotiationneeded(event);
  12805. }
  12806. };
  12807. self.ondatachannel = null;
  12808. this.peerconnection.ondatachannel = function (event) {
  12809. self.trace('ondatachannel', event);
  12810. if (self.ondatachannel !== null) {
  12811. self.ondatachannel(event);
  12812. }
  12813. };
  12814. if (!navigator.mozGetUserMedia && this.maxstats) {
  12815. this.statsinterval = window.setInterval(function() {
  12816. self.peerconnection.getStats(function(stats) {
  12817. var results = stats.result();
  12818. for (var i = 0; i < results.length; ++i) {
  12819. //console.log(results[i].type, results[i].id, results[i].names())
  12820. var now = new Date();
  12821. results[i].names().forEach(function (name) {
  12822. var id = results[i].id + '-' + name;
  12823. if (!self.stats[id]) {
  12824. self.stats[id] = {
  12825. startTime: now,
  12826. endTime: now,
  12827. values: [],
  12828. times: []
  12829. };
  12830. }
  12831. self.stats[id].values.push(results[i].stat(name));
  12832. self.stats[id].times.push(now.getTime());
  12833. if (self.stats[id].values.length > self.maxstats) {
  12834. self.stats[id].values.shift();
  12835. self.stats[id].times.shift();
  12836. }
  12837. self.stats[id].endTime = now;
  12838. });
  12839. }
  12840. });
  12841. }, 1000);
  12842. }
  12843. };
  12844. dumpSDP = function(description) {
  12845. if (typeof description === 'undefined' || description == null) {
  12846. return '';
  12847. }
  12848. return 'type: ' + description.type + '\r\n' + description.sdp;
  12849. };
  12850. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  12851. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  12852. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  12853. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  12854. this.trace('getLocalDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.localDescription));
  12855. // if we're running on FF, transform to Plan B first.
  12856. var desc = this.peerconnection.localDescription;
  12857. if (navigator.mozGetUserMedia) {
  12858. desc = this.interop.toPlanB(desc);
  12859. } else {
  12860. desc = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  12861. }
  12862. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  12863. return desc;
  12864. });
  12865. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  12866. this.trace('getRemoteDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.remoteDescription));
  12867. // if we're running on FF, transform to Plan B first.
  12868. var desc = this.peerconnection.remoteDescription;
  12869. if (navigator.mozGetUserMedia) {
  12870. desc = this.interop.toPlanB(desc);
  12871. } else {
  12872. desc = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  12873. }
  12874. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  12875. return desc;
  12876. });
  12877. }
  12878. TraceablePeerConnection.prototype.addStream = function (stream) {
  12879. this.trace('addStream', stream.id);
  12880. APP.simulcast.resetSender();
  12881. try
  12882. {
  12883. this.peerconnection.addStream(stream);
  12884. }
  12885. catch (e)
  12886. {
  12887. console.error(e);
  12888. return;
  12889. }
  12890. };
  12891. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  12892. this.trace('removeStream', stream.id);
  12893. APP.simulcast.resetSender();
  12894. if(stopStreams) {
  12895. stream.getAudioTracks().forEach(function (track) {
  12896. track.stop();
  12897. });
  12898. stream.getVideoTracks().forEach(function (track) {
  12899. track.stop();
  12900. });
  12901. }
  12902. try {
  12903. // FF doesn't support this yet.
  12904. this.peerconnection.removeStream(stream);
  12905. } catch (e) {
  12906. console.error(e);
  12907. }
  12908. };
  12909. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  12910. this.trace('createDataChannel', label, opts);
  12911. return this.peerconnection.createDataChannel(label, opts);
  12912. };
  12913. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  12914. this.trace('setLocalDescription::preTransform (Plan B)', dumpSDP(description));
  12915. // if we're running on FF, transform to Plan A first.
  12916. if (navigator.mozGetUserMedia) {
  12917. description = this.interop.toPlanA(description);
  12918. } else {
  12919. description = APP.simulcast.transformLocalDescription(description);
  12920. }
  12921. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  12922. var self = this;
  12923. this.peerconnection.setLocalDescription(description,
  12924. function () {
  12925. self.trace('setLocalDescriptionOnSuccess');
  12926. successCallback();
  12927. },
  12928. function (err) {
  12929. self.trace('setLocalDescriptionOnFailure', err);
  12930. failureCallback(err);
  12931. }
  12932. );
  12933. /*
  12934. if (this.statsinterval === null && this.maxstats > 0) {
  12935. // start gathering stats
  12936. }
  12937. */
  12938. };
  12939. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  12940. this.trace('setRemoteDescription::preTransform (Plan B)', dumpSDP(description));
  12941. // if we're running on FF, transform to Plan A first.
  12942. if (navigator.mozGetUserMedia) {
  12943. description = this.interop.toPlanA(description);
  12944. }
  12945. else {
  12946. description = APP.simulcast.transformRemoteDescription(description);
  12947. }
  12948. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  12949. var self = this;
  12950. this.peerconnection.setRemoteDescription(description,
  12951. function () {
  12952. self.trace('setRemoteDescriptionOnSuccess');
  12953. successCallback();
  12954. },
  12955. function (err) {
  12956. self.trace('setRemoteDescriptionOnFailure', err);
  12957. failureCallback(err);
  12958. }
  12959. );
  12960. /*
  12961. if (this.statsinterval === null && this.maxstats > 0) {
  12962. // start gathering stats
  12963. }
  12964. */
  12965. };
  12966. TraceablePeerConnection.prototype.close = function () {
  12967. this.trace('stop');
  12968. if (this.statsinterval !== null) {
  12969. window.clearInterval(this.statsinterval);
  12970. this.statsinterval = null;
  12971. }
  12972. this.peerconnection.close();
  12973. };
  12974. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  12975. var self = this;
  12976. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  12977. this.peerconnection.createOffer(
  12978. function (offer) {
  12979. self.trace('createOfferOnSuccess::preTransform (Plan A)', dumpSDP(offer));
  12980. // if we're running on FF, transform to Plan B first.
  12981. if (navigator.mozGetUserMedia) {
  12982. offer = self.interop.toPlanB(offer);
  12983. }
  12984. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  12985. successCallback(offer);
  12986. },
  12987. function(err) {
  12988. self.trace('createOfferOnFailure', err);
  12989. failureCallback(err);
  12990. },
  12991. constraints
  12992. );
  12993. };
  12994. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  12995. var self = this;
  12996. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  12997. this.peerconnection.createAnswer(
  12998. function (answer) {
  12999. self.trace('createAnswerOnSuccess::preTransfom (Plan A)', dumpSDP(answer));
  13000. // if we're running on FF, transform to Plan A first.
  13001. if (navigator.mozGetUserMedia) {
  13002. answer = self.interop.toPlanB(answer);
  13003. } else {
  13004. answer = APP.simulcast.transformAnswer(answer);
  13005. }
  13006. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  13007. successCallback(answer);
  13008. },
  13009. function(err) {
  13010. self.trace('createAnswerOnFailure', err);
  13011. failureCallback(err);
  13012. },
  13013. constraints
  13014. );
  13015. };
  13016. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  13017. var self = this;
  13018. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  13019. this.peerconnection.addIceCandidate(candidate);
  13020. /* maybe later
  13021. this.peerconnection.addIceCandidate(candidate,
  13022. function () {
  13023. self.trace('addIceCandidateOnSuccess');
  13024. successCallback();
  13025. },
  13026. function (err) {
  13027. self.trace('addIceCandidateOnFailure', err);
  13028. failureCallback(err);
  13029. }
  13030. );
  13031. */
  13032. };
  13033. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  13034. if (navigator.mozGetUserMedia) {
  13035. // ignore for now...
  13036. if(!errback)
  13037. errback = function () {
  13038. }
  13039. this.peerconnection.getStats(null,callback,errback);
  13040. } else {
  13041. this.peerconnection.getStats(callback);
  13042. }
  13043. };
  13044. module.exports = TraceablePeerConnection;
  13045. },{"sdp-interop":80}],53:[function(require,module,exports){
  13046. /* global $, $iq, APP, config, connection, UI, messageHandler,
  13047. roomName, sessionTerminated, Strophe, Util */
  13048. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13049. var Settings = require("../settings/Settings");
  13050. var AuthenticationEvents
  13051. = require("../../service/authentication/AuthenticationEvents");
  13052. /**
  13053. * Contains logic responsible for enabling/disabling functionality available
  13054. * only to moderator users.
  13055. */
  13056. var connection = null;
  13057. var focusUserJid;
  13058. function createExpBackoffTimer(step) {
  13059. var count = 1;
  13060. return function (reset) {
  13061. // Reset call
  13062. if (reset) {
  13063. count = 1;
  13064. return;
  13065. }
  13066. // Calculate next timeout
  13067. var timeout = Math.pow(2, count - 1);
  13068. count += 1;
  13069. return timeout * step;
  13070. };
  13071. }
  13072. var getNextTimeout = createExpBackoffTimer(1000);
  13073. var getNextErrorTimeout = createExpBackoffTimer(1000);
  13074. // External authentication stuff
  13075. var externalAuthEnabled = false;
  13076. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  13077. // it will be enabled automatically if focus detects the component through
  13078. // service discovery.
  13079. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  13080. var eventEmitter = null;
  13081. var Moderator = {
  13082. isModerator: function () {
  13083. return connection && connection.emuc.isModerator();
  13084. },
  13085. isPeerModerator: function (peerJid) {
  13086. return connection &&
  13087. connection.emuc.getMemberRole(peerJid) === 'moderator';
  13088. },
  13089. isExternalAuthEnabled: function () {
  13090. return externalAuthEnabled;
  13091. },
  13092. isSipGatewayEnabled: function () {
  13093. return sipGatewayEnabled;
  13094. },
  13095. setConnection: function (con) {
  13096. connection = con;
  13097. },
  13098. init: function (xmpp, emitter) {
  13099. this.xmppService = xmpp;
  13100. eventEmitter = emitter;
  13101. // Message listener that talks to POPUP window
  13102. function listener(event) {
  13103. if (event.data && event.data.sessionId) {
  13104. if (event.origin !== window.location.origin) {
  13105. console.warn(
  13106. "Ignoring sessionId from different origin: " + event.origin);
  13107. return;
  13108. }
  13109. localStorage.setItem('sessionId', event.data.sessionId);
  13110. // After popup is closed we will authenticate
  13111. }
  13112. }
  13113. // Register
  13114. if (window.addEventListener) {
  13115. window.addEventListener("message", listener, false);
  13116. } else {
  13117. window.attachEvent("onmessage", listener);
  13118. }
  13119. },
  13120. onMucLeft: function (jid) {
  13121. console.info("Someone left is it focus ? " + jid);
  13122. var resource = Strophe.getResourceFromJid(jid);
  13123. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  13124. console.info(
  13125. "Focus has left the room - leaving conference");
  13126. //hangUp();
  13127. // We'd rather reload to have everything re-initialized
  13128. // FIXME: show some message before reload
  13129. location.reload();
  13130. }
  13131. },
  13132. setFocusUserJid: function (focusJid) {
  13133. if (!focusUserJid) {
  13134. focusUserJid = focusJid;
  13135. console.info("Focus jid set to: " + focusUserJid);
  13136. }
  13137. },
  13138. getFocusUserJid: function () {
  13139. return focusUserJid;
  13140. },
  13141. getFocusComponent: function () {
  13142. // Get focus component address
  13143. var focusComponent = config.hosts.focus;
  13144. // If not specified use default: 'focus.domain'
  13145. if (!focusComponent) {
  13146. focusComponent = 'focus.' + config.hosts.domain;
  13147. }
  13148. return focusComponent;
  13149. },
  13150. createConferenceIq: function (roomName) {
  13151. // Generate create conference IQ
  13152. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13153. // Session Id used for authentication
  13154. var sessionId = localStorage.getItem('sessionId');
  13155. var machineUID = Settings.getSettings().uid;
  13156. console.info(
  13157. "Session ID: " + sessionId + " machine UID: " + machineUID);
  13158. elem.c('conference', {
  13159. xmlns: 'http://jitsi.org/protocol/focus',
  13160. room: roomName,
  13161. 'machine-uid': machineUID
  13162. });
  13163. if (sessionId) {
  13164. elem.attrs({ 'session-id': sessionId});
  13165. }
  13166. if (config.hosts.bridge !== undefined) {
  13167. elem.c(
  13168. 'property',
  13169. { name: 'bridge', value: config.hosts.bridge})
  13170. .up();
  13171. }
  13172. // Tell the focus we have Jigasi configured
  13173. if (config.hosts.call_control !== undefined) {
  13174. elem.c(
  13175. 'property',
  13176. { name: 'call_control', value: config.hosts.call_control})
  13177. .up();
  13178. }
  13179. if (config.channelLastN !== undefined) {
  13180. elem.c(
  13181. 'property',
  13182. { name: 'channelLastN', value: config.channelLastN})
  13183. .up();
  13184. }
  13185. if (config.adaptiveLastN !== undefined) {
  13186. elem.c(
  13187. 'property',
  13188. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  13189. .up();
  13190. }
  13191. if (config.adaptiveSimulcast !== undefined) {
  13192. elem.c(
  13193. 'property',
  13194. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  13195. .up();
  13196. }
  13197. if (config.openSctp !== undefined) {
  13198. elem.c(
  13199. 'property',
  13200. { name: 'openSctp', value: config.openSctp})
  13201. .up();
  13202. }
  13203. if (config.enableFirefoxSupport !== undefined) {
  13204. elem.c(
  13205. 'property',
  13206. { name: 'enableFirefoxHacks',
  13207. value: config.enableFirefoxSupport})
  13208. .up();
  13209. }
  13210. elem.up();
  13211. return elem;
  13212. },
  13213. parseSessionId: function (resultIq) {
  13214. var sessionId = $(resultIq).find('conference').attr('session-id');
  13215. if (sessionId) {
  13216. console.info('Received sessionId: ' + sessionId);
  13217. localStorage.setItem('sessionId', sessionId);
  13218. }
  13219. },
  13220. parseConfigOptions: function (resultIq) {
  13221. Moderator.setFocusUserJid(
  13222. $(resultIq).find('conference').attr('focusjid'));
  13223. var authenticationEnabled
  13224. = $(resultIq).find(
  13225. '>conference>property' +
  13226. '[name=\'authentication\'][value=\'true\']').length > 0;
  13227. console.info("Authentication enabled: " + authenticationEnabled);
  13228. externalAuthEnabled
  13229. = $(resultIq).find(
  13230. '>conference>property' +
  13231. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  13232. console.info('External authentication enabled: ' + externalAuthEnabled);
  13233. if (!externalAuthEnabled) {
  13234. // We expect to receive sessionId in 'internal' authentication mode
  13235. Moderator.parseSessionId(resultIq);
  13236. }
  13237. var authIdentity = $(resultIq).find('>conference').attr('identity');
  13238. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  13239. authenticationEnabled, authIdentity);
  13240. // Check if focus has auto-detected Jigasi component(this will be also
  13241. // included if we have passed our host from the config)
  13242. if ($(resultIq).find(
  13243. '>conference>property' +
  13244. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  13245. sipGatewayEnabled = true;
  13246. }
  13247. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  13248. },
  13249. // FIXME: we need to show the fact that we're waiting for the focus
  13250. // to the user(or that focus is not available)
  13251. allocateConferenceFocus: function (roomName, callback) {
  13252. // Try to use focus user JID from the config
  13253. Moderator.setFocusUserJid(config.focusUserJid);
  13254. // Send create conference IQ
  13255. var iq = Moderator.createConferenceIq(roomName);
  13256. var self = this;
  13257. connection.sendIQ(
  13258. iq,
  13259. function (result) {
  13260. // Setup config options
  13261. Moderator.parseConfigOptions(result);
  13262. if ('true' === $(result).find('conference').attr('ready')) {
  13263. // Reset both timers
  13264. getNextTimeout(true);
  13265. getNextErrorTimeout(true);
  13266. // Exec callback
  13267. callback();
  13268. } else {
  13269. var waitMs = getNextTimeout();
  13270. console.info("Waiting for the focus... " + waitMs);
  13271. // Reset error timeout
  13272. getNextErrorTimeout(true);
  13273. window.setTimeout(
  13274. function () {
  13275. Moderator.allocateConferenceFocus(
  13276. roomName, callback);
  13277. }, waitMs);
  13278. }
  13279. },
  13280. function (error) {
  13281. // Invalid session ? remove and try again
  13282. // without session ID to get a new one
  13283. var invalidSession
  13284. = $(error).find('>error>session-invalid').length;
  13285. if (invalidSession) {
  13286. console.info("Session expired! - removing");
  13287. localStorage.removeItem("sessionId");
  13288. }
  13289. if ($(error).find('>error>graceful-shutdown').length) {
  13290. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  13291. return;
  13292. }
  13293. // Check for error returned by the reservation system
  13294. var reservationErr = $(error).find('>error>reservation-error');
  13295. if (reservationErr.length) {
  13296. // Trigger error event
  13297. var errorCode = reservationErr.attr('error-code');
  13298. var errorMsg;
  13299. if ($(error).find('>error>text')) {
  13300. errorMsg = $(error).find('>error>text').text();
  13301. }
  13302. eventEmitter.emit(
  13303. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  13304. return;
  13305. }
  13306. // Not authorized to create new room
  13307. if ($(error).find('>error>not-authorized').length) {
  13308. console.warn("Unauthorized to start the conference", error);
  13309. var toDomain
  13310. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13311. if (toDomain !== config.hosts.anonymousdomain) {
  13312. // FIXME: "is external" should come either from
  13313. // the focus or config.js
  13314. externalAuthEnabled = true;
  13315. }
  13316. eventEmitter.emit(
  13317. XMPPEvents.AUTHENTICATION_REQUIRED,
  13318. function () {
  13319. Moderator.allocateConferenceFocus(
  13320. roomName, callback);
  13321. });
  13322. return;
  13323. }
  13324. var waitMs = getNextErrorTimeout();
  13325. console.error("Focus error, retry after " + waitMs, error);
  13326. // Show message
  13327. var focusComponent = Moderator.getFocusComponent();
  13328. var retrySec = waitMs / 1000;
  13329. // FIXME: message is duplicated ?
  13330. // Do not show in case of session invalid
  13331. // which means just a retry
  13332. if (!invalidSession) {
  13333. APP.UI.messageHandler.notify(
  13334. null, "notify.focus",
  13335. 'disconnected', "notify.focusFail",
  13336. {component: focusComponent, ms: retrySec});
  13337. }
  13338. // Reset response timeout
  13339. getNextTimeout(true);
  13340. window.setTimeout(
  13341. function () {
  13342. Moderator.allocateConferenceFocus(roomName, callback);
  13343. }, waitMs);
  13344. }
  13345. );
  13346. },
  13347. getLoginUrl: function (roomName, urlCallback) {
  13348. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13349. iq.c('login-url', {
  13350. xmlns: 'http://jitsi.org/protocol/focus',
  13351. room: roomName,
  13352. 'machine-uid': Settings.getSettings().uid
  13353. });
  13354. connection.sendIQ(
  13355. iq,
  13356. function (result) {
  13357. var url = $(result).find('login-url').attr('url');
  13358. url = url = decodeURIComponent(url);
  13359. if (url) {
  13360. console.info("Got auth url: " + url);
  13361. urlCallback(url);
  13362. } else {
  13363. console.error(
  13364. "Failed to get auth url from the focus", result);
  13365. }
  13366. },
  13367. function (error) {
  13368. console.error("Get auth url error", error);
  13369. }
  13370. );
  13371. },
  13372. getPopupLoginUrl: function (roomName, urlCallback) {
  13373. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13374. iq.c('login-url', {
  13375. xmlns: 'http://jitsi.org/protocol/focus',
  13376. room: roomName,
  13377. 'machine-uid': Settings.getSettings().uid,
  13378. popup: true
  13379. });
  13380. connection.sendIQ(
  13381. iq,
  13382. function (result) {
  13383. var url = $(result).find('login-url').attr('url');
  13384. url = url = decodeURIComponent(url);
  13385. if (url) {
  13386. console.info("Got POPUP auth url: " + url);
  13387. urlCallback(url);
  13388. } else {
  13389. console.error(
  13390. "Failed to get POPUP auth url from the focus", result);
  13391. }
  13392. },
  13393. function (error) {
  13394. console.error('Get POPUP auth url error', error);
  13395. }
  13396. );
  13397. },
  13398. logout: function (callback) {
  13399. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13400. var sessionId = localStorage.getItem('sessionId');
  13401. if (!sessionId) {
  13402. callback();
  13403. return;
  13404. }
  13405. iq.c('logout', {
  13406. xmlns: 'http://jitsi.org/protocol/focus',
  13407. 'session-id': sessionId
  13408. });
  13409. connection.sendIQ(
  13410. iq,
  13411. function (result) {
  13412. var logoutUrl = $(result).find('logout').attr('logout-url');
  13413. if (logoutUrl) {
  13414. logoutUrl = decodeURIComponent(logoutUrl);
  13415. }
  13416. console.info("Log out OK, url: " + logoutUrl, result);
  13417. localStorage.removeItem('sessionId');
  13418. callback(logoutUrl);
  13419. },
  13420. function (error) {
  13421. console.error("Logout error", error);
  13422. }
  13423. );
  13424. }
  13425. };
  13426. module.exports = Moderator;
  13427. },{"../../service/authentication/AuthenticationEvents":93,"../../service/xmpp/XMPPEvents":97,"../settings/Settings":38}],54:[function(require,module,exports){
  13428. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  13429. Toolbar, Util */
  13430. var Moderator = require("./moderator");
  13431. var recordingToken = null;
  13432. var recordingEnabled;
  13433. /**
  13434. * Whether to use a jirecon component for recording, or use the videobridge
  13435. * through COLIBRI.
  13436. */
  13437. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  13438. /**
  13439. * The ID of the jirecon recording session. Jirecon generates it when we
  13440. * initially start recording, and it needs to be used in subsequent requests
  13441. * to jirecon.
  13442. */
  13443. var jireconRid = null;
  13444. function setRecordingToken(token) {
  13445. recordingToken = token;
  13446. }
  13447. function setRecording(state, token, callback, connection) {
  13448. if (useJirecon){
  13449. setRecordingJirecon(state, token, callback, connection);
  13450. } else {
  13451. setRecordingColibri(state, token, callback, connection);
  13452. }
  13453. }
  13454. function setRecordingJirecon(state, token, callback, connection) {
  13455. if (state == recordingEnabled){
  13456. return;
  13457. }
  13458. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  13459. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  13460. action: state ? 'start' : 'stop',
  13461. mucjid: connection.emuc.roomjid});
  13462. if (!state){
  13463. iq.attrs({rid: jireconRid});
  13464. }
  13465. console.log('Start recording');
  13466. connection.sendIQ(
  13467. iq,
  13468. function (result) {
  13469. // TODO wait for an IQ with the real status, since this is
  13470. // provisional?
  13471. jireconRid = $(result).find('recording').attr('rid');
  13472. console.log('Recording ' + (state ? 'started' : 'stopped') +
  13473. '(jirecon)' + result);
  13474. recordingEnabled = state;
  13475. if (!state){
  13476. jireconRid = null;
  13477. }
  13478. callback(state);
  13479. },
  13480. function (error) {
  13481. console.log('Failed to start recording, error: ', error);
  13482. callback(recordingEnabled);
  13483. });
  13484. }
  13485. // Sends a COLIBRI message which enables or disables (according to 'state')
  13486. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  13487. // with the new recording state, according to the IQ.
  13488. function setRecordingColibri(state, token, callback, connection) {
  13489. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  13490. elem.c('conference', {
  13491. xmlns: 'http://jitsi.org/protocol/colibri'
  13492. });
  13493. elem.c('recording', {state: state, token: token});
  13494. connection.sendIQ(elem,
  13495. function (result) {
  13496. console.log('Set recording "', state, '". Result:', result);
  13497. var recordingElem = $(result).find('>conference>recording');
  13498. var newState = ('true' === recordingElem.attr('state'));
  13499. recordingEnabled = newState;
  13500. callback(newState);
  13501. },
  13502. function (error) {
  13503. console.warn(error);
  13504. callback(recordingEnabled);
  13505. }
  13506. );
  13507. }
  13508. var Recording = {
  13509. toggleRecording: function (tokenEmptyCallback,
  13510. startingCallback, startedCallback, connection) {
  13511. if (!Moderator.isModerator()) {
  13512. console.log(
  13513. 'non-focus, or conference not yet organized:' +
  13514. ' not enabling recording');
  13515. return;
  13516. }
  13517. var self = this;
  13518. // Jirecon does not (currently) support a token.
  13519. if (!recordingToken && !useJirecon) {
  13520. tokenEmptyCallback(function (value) {
  13521. setRecordingToken(value);
  13522. self.toggleRecording(tokenEmptyCallback,
  13523. startingCallback, startedCallback, connection);
  13524. });
  13525. return;
  13526. }
  13527. var oldState = recordingEnabled;
  13528. startingCallback(!oldState);
  13529. setRecording(!oldState,
  13530. recordingToken,
  13531. function (state) {
  13532. console.log("New recording state: ", state);
  13533. if (state === oldState) {
  13534. // FIXME: new focus:
  13535. // this will not work when moderator changes
  13536. // during active session. Then it will assume that
  13537. // recording status has changed to true, but it might have
  13538. // been already true(and we only received actual status from
  13539. // the focus).
  13540. //
  13541. // SO we start with status null, so that it is initialized
  13542. // here and will fail only after second click, so if invalid
  13543. // token was used we have to press the button twice before
  13544. // current status will be fetched and token will be reset.
  13545. //
  13546. // Reliable way would be to return authentication error.
  13547. // Or status update when moderator connects.
  13548. // Or we have to stop recording session when current
  13549. // moderator leaves the room.
  13550. // Failed to change, reset the token because it might
  13551. // have been wrong
  13552. setRecordingToken(null);
  13553. }
  13554. startedCallback(state);
  13555. },
  13556. connection
  13557. );
  13558. }
  13559. }
  13560. module.exports = Recording;
  13561. },{"./moderator":53}],55:[function(require,module,exports){
  13562. /* jshint -W117 */
  13563. /* a simple MUC connection plugin
  13564. * can only handle a single MUC room
  13565. */
  13566. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13567. var Moderator = require("./moderator");
  13568. var JingleSession = require("./JingleSession");
  13569. var bridgeIsDown = false;
  13570. module.exports = function(XMPP, eventEmitter) {
  13571. Strophe.addConnectionPlugin('emuc', {
  13572. connection: null,
  13573. roomjid: null,
  13574. myroomjid: null,
  13575. members: {},
  13576. list_members: [], // so we can elect a new focus
  13577. presMap: {},
  13578. preziMap: {},
  13579. joined: false,
  13580. isOwner: false,
  13581. role: null,
  13582. focusMucJid: null,
  13583. ssrc2jid: {},
  13584. init: function (conn) {
  13585. this.connection = conn;
  13586. },
  13587. initPresenceMap: function (myroomjid) {
  13588. this.presMap['to'] = myroomjid;
  13589. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  13590. },
  13591. doJoin: function (jid, password) {
  13592. this.myroomjid = jid;
  13593. console.info("Joined MUC as " + this.myroomjid);
  13594. this.initPresenceMap(this.myroomjid);
  13595. if (!this.roomjid) {
  13596. this.roomjid = Strophe.getBareJidFromJid(jid);
  13597. // add handlers (just once)
  13598. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  13599. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  13600. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  13601. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  13602. }
  13603. if (password !== undefined) {
  13604. this.presMap['password'] = password;
  13605. }
  13606. this.sendPresence();
  13607. },
  13608. doLeave: function () {
  13609. console.log("do leave", this.myroomjid);
  13610. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  13611. this.presMap.length = 0;
  13612. this.connection.send(pres);
  13613. },
  13614. createNonAnonymousRoom: function () {
  13615. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  13616. var getForm = $iq({type: 'get', to: this.roomjid})
  13617. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  13618. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13619. var self = this;
  13620. this.connection.sendIQ(getForm, function (form) {
  13621. if (!$(form).find(
  13622. '>query>x[xmlns="jabber:x:data"]' +
  13623. '>field[var="muc#roomconfig_whois"]').length) {
  13624. console.error('non-anonymous rooms not supported');
  13625. return;
  13626. }
  13627. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  13628. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13629. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13630. formSubmit.c('field', {'var': 'FORM_TYPE'})
  13631. .c('value')
  13632. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13633. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  13634. .c('value').t('anyone').up().up();
  13635. self.connection.sendIQ(formSubmit);
  13636. }, function (error) {
  13637. console.error("Error getting room configuration form");
  13638. });
  13639. },
  13640. onPresence: function (pres) {
  13641. var from = pres.getAttribute('from');
  13642. // What is this for? A workaround for something?
  13643. if (pres.getAttribute('type')) {
  13644. return true;
  13645. }
  13646. // Parse etherpad tag.
  13647. var etherpad = $(pres).find('>etherpad');
  13648. if (etherpad.length) {
  13649. if (config.etherpad_base && !Moderator.isModerator()) {
  13650. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  13651. }
  13652. }
  13653. // Parse prezi tag.
  13654. var presentation = $(pres).find('>prezi');
  13655. if (presentation.length) {
  13656. var url = presentation.attr('url');
  13657. var current = presentation.find('>current').text();
  13658. console.log('presentation info received from', from, url);
  13659. if (this.preziMap[from] == null) {
  13660. this.preziMap[from] = url;
  13661. $(document).trigger('presentationadded.muc', [from, url, current]);
  13662. }
  13663. else {
  13664. $(document).trigger('gotoslide.muc', [from, url, current]);
  13665. }
  13666. }
  13667. else if (this.preziMap[from] != null) {
  13668. var url = this.preziMap[from];
  13669. delete this.preziMap[from];
  13670. $(document).trigger('presentationremoved.muc', [from, url]);
  13671. }
  13672. // Parse audio info tag.
  13673. var audioMuted = $(pres).find('>audiomuted');
  13674. if (audioMuted.length) {
  13675. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  13676. }
  13677. // Parse video info tag.
  13678. var videoMuted = $(pres).find('>videomuted');
  13679. if (videoMuted.length) {
  13680. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  13681. }
  13682. var stats = $(pres).find('>stats');
  13683. if (stats.length) {
  13684. var statsObj = {};
  13685. Strophe.forEachChild(stats[0], "stat", function (el) {
  13686. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  13687. });
  13688. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  13689. }
  13690. // Parse status.
  13691. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  13692. this.isOwner = true;
  13693. this.createNonAnonymousRoom();
  13694. }
  13695. // Parse roles.
  13696. var member = {};
  13697. member.show = $(pres).find('>show').text();
  13698. member.status = $(pres).find('>status').text();
  13699. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  13700. member.affiliation = tmp.attr('affiliation');
  13701. member.role = tmp.attr('role');
  13702. // Focus recognition
  13703. member.jid = tmp.attr('jid');
  13704. member.isFocus = false;
  13705. if (member.jid
  13706. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  13707. member.isFocus = true;
  13708. }
  13709. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  13710. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  13711. if (from == this.myroomjid) {
  13712. if (member.affiliation == 'owner') this.isOwner = true;
  13713. if (this.role !== member.role) {
  13714. this.role = member.role;
  13715. eventEmitter.emit(XMPPEvents.LOCALROLE_CHANGED,
  13716. from, member, pres, Moderator.isModerator());
  13717. }
  13718. if (!this.joined) {
  13719. this.joined = true;
  13720. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  13721. this.list_members.push(from);
  13722. }
  13723. } else if (this.members[from] === undefined) {
  13724. // new participant
  13725. this.members[from] = member;
  13726. this.list_members.push(from);
  13727. console.log('entered', from, member);
  13728. if (member.isFocus) {
  13729. this.focusMucJid = from;
  13730. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  13731. }
  13732. else {
  13733. var id = $(pres).find('>userID').text();
  13734. var email = $(pres).find('>email');
  13735. if (email.length > 0) {
  13736. id = email.text();
  13737. }
  13738. eventEmitter.emit(XMPPEvents.MUC_ENTER, from, id, member.displayName);
  13739. }
  13740. } else {
  13741. // Presence update for existing participant
  13742. // Watch role change:
  13743. if (this.members[from].role != member.role) {
  13744. this.members[from].role = member.role;
  13745. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  13746. member.role, member.displayName);
  13747. }
  13748. }
  13749. // Always trigger presence to update bindings
  13750. this.parsePresence(from, member, pres);
  13751. // Trigger status message update
  13752. if (member.status) {
  13753. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  13754. }
  13755. return true;
  13756. },
  13757. onPresenceUnavailable: function (pres) {
  13758. var from = pres.getAttribute('from');
  13759. // room destroyed ?
  13760. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13761. '>destroy').length) {
  13762. var reason;
  13763. var reasonSelect = $(pres).find(
  13764. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13765. '>destroy>reason');
  13766. if (reasonSelect.length) {
  13767. reason = reasonSelect.text();
  13768. }
  13769. XMPP.disposeConference(false);
  13770. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  13771. return true;
  13772. }
  13773. // Status code 110 indicates that this notification is "self-presence".
  13774. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  13775. delete this.members[from];
  13776. this.list_members.splice(this.list_members.indexOf(from), 1);
  13777. this.onParticipantLeft(from);
  13778. }
  13779. // If the status code is 110 this means we're leaving and we would like
  13780. // to remove everyone else from our view, so we trigger the event.
  13781. else if (this.list_members.length > 1) {
  13782. for (var i = 0; i < this.list_members.length; i++) {
  13783. var member = this.list_members[i];
  13784. delete this.members[i];
  13785. this.list_members.splice(i, 1);
  13786. this.onParticipantLeft(member);
  13787. }
  13788. }
  13789. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  13790. $(document).trigger('kicked.muc', [from]);
  13791. if (this.myroomjid === from) {
  13792. XMPP.disposeConference(false);
  13793. eventEmitter.emit(XMPPEvents.KICKED);
  13794. }
  13795. }
  13796. return true;
  13797. },
  13798. onPresenceError: function (pres) {
  13799. var from = pres.getAttribute('from');
  13800. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13801. console.log('on password required', from);
  13802. var self = this;
  13803. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  13804. self.doJoin(from, value);
  13805. });
  13806. } else if ($(pres).find(
  13807. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13808. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  13809. if (toDomain === config.hosts.anonymousdomain) {
  13810. // enter the room by replying with 'not-authorized'. This would
  13811. // result in reconnection from authorized domain.
  13812. // We're either missing Jicofo/Prosody config for anonymous
  13813. // domains or something is wrong.
  13814. // XMPP.promptLogin();
  13815. APP.UI.messageHandler.openReportDialog(null,
  13816. "dialog.joinError", pres);
  13817. } else {
  13818. console.warn('onPresError ', pres);
  13819. APP.UI.messageHandler.openReportDialog(null,
  13820. "dialog.connectError",
  13821. pres);
  13822. }
  13823. } else {
  13824. console.warn('onPresError ', pres);
  13825. APP.UI.messageHandler.openReportDialog(null,
  13826. "dialog.connectError",
  13827. pres);
  13828. }
  13829. return true;
  13830. },
  13831. sendMessage: function (body, nickname) {
  13832. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13833. msg.c('body', body).up();
  13834. if (nickname) {
  13835. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  13836. }
  13837. this.connection.send(msg);
  13838. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  13839. },
  13840. setSubject: function (subject) {
  13841. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13842. msg.c('subject', subject);
  13843. this.connection.send(msg);
  13844. console.log("topic changed to " + subject);
  13845. },
  13846. onMessage: function (msg) {
  13847. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  13848. var from = msg.getAttribute('from');
  13849. var nick =
  13850. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  13851. .text() ||
  13852. Strophe.getResourceFromJid(from);
  13853. var txt = $(msg).find('>body').text();
  13854. var type = msg.getAttribute("type");
  13855. if (type == "error") {
  13856. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  13857. $(msg).find('>text').text(), txt);
  13858. return true;
  13859. }
  13860. var subject = $(msg).find('>subject');
  13861. if (subject.length) {
  13862. var subjectText = subject.text();
  13863. if (subjectText || subjectText == "") {
  13864. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  13865. console.log("Subject is changed to " + subjectText);
  13866. }
  13867. }
  13868. if (txt) {
  13869. console.log('chat', nick, txt);
  13870. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  13871. from, nick, txt, this.myroomjid);
  13872. }
  13873. return true;
  13874. },
  13875. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  13876. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  13877. var ob = this;
  13878. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  13879. function (res) {
  13880. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  13881. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13882. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13883. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13884. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  13885. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  13886. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  13887. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  13888. ob.connection.sendIQ(formsubmit,
  13889. onSuccess,
  13890. onError);
  13891. } else {
  13892. onNotSupported();
  13893. }
  13894. }, onError);
  13895. },
  13896. kick: function (jid) {
  13897. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  13898. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  13899. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  13900. .c('reason').t('You have been kicked.').up().up().up();
  13901. this.connection.sendIQ(
  13902. kickIQ,
  13903. function (result) {
  13904. console.log('Kick participant with jid: ', jid, result);
  13905. },
  13906. function (error) {
  13907. console.log('Kick participant error: ', error);
  13908. });
  13909. },
  13910. sendPresence: function () {
  13911. var pres = $pres({to: this.presMap['to'] });
  13912. pres.c('x', {xmlns: this.presMap['xns']});
  13913. if (this.presMap['password']) {
  13914. pres.c('password').t(this.presMap['password']).up();
  13915. }
  13916. pres.up();
  13917. // Send XEP-0115 'c' stanza that contains our capabilities info
  13918. if (this.connection.caps) {
  13919. this.connection.caps.node = config.clientNode;
  13920. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  13921. }
  13922. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  13923. .t(navigator.userAgent).up();
  13924. if (this.presMap['bridgeIsDown']) {
  13925. pres.c('bridgeIsDown').up();
  13926. }
  13927. if (this.presMap['email']) {
  13928. pres.c('email').t(this.presMap['email']).up();
  13929. }
  13930. if (this.presMap['userId']) {
  13931. pres.c('userId').t(this.presMap['userId']).up();
  13932. }
  13933. if (this.presMap['displayName']) {
  13934. // XEP-0172
  13935. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  13936. .t(this.presMap['displayName']).up();
  13937. }
  13938. if (this.presMap['audions']) {
  13939. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  13940. .t(this.presMap['audiomuted']).up();
  13941. }
  13942. if (this.presMap['videons']) {
  13943. pres.c('videomuted', {xmlns: this.presMap['videons']})
  13944. .t(this.presMap['videomuted']).up();
  13945. }
  13946. if (this.presMap['statsns']) {
  13947. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  13948. for (var stat in this.presMap["stats"])
  13949. if (this.presMap["stats"][stat] != null)
  13950. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  13951. pres.up();
  13952. }
  13953. if (this.presMap['prezins']) {
  13954. pres.c('prezi',
  13955. {xmlns: this.presMap['prezins'],
  13956. 'url': this.presMap['preziurl']})
  13957. .c('current').t(this.presMap['prezicurrent']).up().up();
  13958. }
  13959. if (this.presMap['etherpadns']) {
  13960. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  13961. .t(this.presMap['etherpadname']).up();
  13962. }
  13963. if (this.presMap['medians']) {
  13964. pres.c('media', {xmlns: this.presMap['medians']});
  13965. var sourceNumber = 0;
  13966. Object.keys(this.presMap).forEach(function (key) {
  13967. if (key.indexOf('source') >= 0) {
  13968. sourceNumber++;
  13969. }
  13970. });
  13971. if (sourceNumber > 0)
  13972. for (var i = 1; i <= sourceNumber / 3; i++) {
  13973. pres.c('source',
  13974. {type: this.presMap['source' + i + '_type'],
  13975. ssrc: this.presMap['source' + i + '_ssrc'],
  13976. direction: this.presMap['source' + i + '_direction']
  13977. || 'sendrecv' }
  13978. ).up();
  13979. }
  13980. }
  13981. pres.up();
  13982. this.connection.send(pres);
  13983. },
  13984. addDisplayNameToPresence: function (displayName) {
  13985. this.presMap['displayName'] = displayName;
  13986. },
  13987. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  13988. if (!this.presMap['medians'])
  13989. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  13990. this.presMap['source' + sourceNumber + '_type'] = mtype;
  13991. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  13992. this.presMap['source' + sourceNumber + '_direction'] = direction;
  13993. },
  13994. clearPresenceMedia: function () {
  13995. var self = this;
  13996. Object.keys(this.presMap).forEach(function (key) {
  13997. if (key.indexOf('source') != -1) {
  13998. delete self.presMap[key];
  13999. }
  14000. });
  14001. },
  14002. addPreziToPresence: function (url, currentSlide) {
  14003. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  14004. this.presMap['preziurl'] = url;
  14005. this.presMap['prezicurrent'] = currentSlide;
  14006. },
  14007. removePreziFromPresence: function () {
  14008. delete this.presMap['prezins'];
  14009. delete this.presMap['preziurl'];
  14010. delete this.presMap['prezicurrent'];
  14011. },
  14012. addCurrentSlideToPresence: function (currentSlide) {
  14013. this.presMap['prezicurrent'] = currentSlide;
  14014. },
  14015. getPrezi: function (roomjid) {
  14016. return this.preziMap[roomjid];
  14017. },
  14018. addEtherpadToPresence: function (etherpadName) {
  14019. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  14020. this.presMap['etherpadname'] = etherpadName;
  14021. },
  14022. addAudioInfoToPresence: function (isMuted) {
  14023. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  14024. this.presMap['audiomuted'] = isMuted.toString();
  14025. },
  14026. addVideoInfoToPresence: function (isMuted) {
  14027. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  14028. this.presMap['videomuted'] = isMuted.toString();
  14029. },
  14030. addConnectionInfoToPresence: function (stats) {
  14031. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  14032. this.presMap['stats'] = stats;
  14033. },
  14034. findJidFromResource: function (resourceJid) {
  14035. if (resourceJid &&
  14036. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  14037. return this.myroomjid;
  14038. }
  14039. var peerJid = null;
  14040. Object.keys(this.members).some(function (jid) {
  14041. peerJid = jid;
  14042. return Strophe.getResourceFromJid(jid) === resourceJid;
  14043. });
  14044. return peerJid;
  14045. },
  14046. addBridgeIsDownToPresence: function () {
  14047. this.presMap['bridgeIsDown'] = true;
  14048. },
  14049. addEmailToPresence: function (email) {
  14050. this.presMap['email'] = email;
  14051. },
  14052. addUserIdToPresence: function (userId) {
  14053. this.presMap['userId'] = userId;
  14054. },
  14055. isModerator: function () {
  14056. return this.role === 'moderator';
  14057. },
  14058. getMemberRole: function (peerJid) {
  14059. if (this.members[peerJid]) {
  14060. return this.members[peerJid].role;
  14061. }
  14062. return null;
  14063. },
  14064. onParticipantLeft: function (jid) {
  14065. eventEmitter.emit(XMPPEvents.MUC_LEFT, jid);
  14066. this.connection.jingle.terminateByJid(jid);
  14067. if (this.getPrezi(jid)) {
  14068. $(document).trigger('presentationremoved.muc',
  14069. [jid, this.getPrezi(jid)]);
  14070. }
  14071. Moderator.onMucLeft(jid);
  14072. },
  14073. parsePresence: function (from, memeber, pres) {
  14074. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  14075. bridgeIsDown = true;
  14076. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  14077. }
  14078. if(memeber.isFocus)
  14079. return;
  14080. var self = this;
  14081. // Remove old ssrcs coming from the jid
  14082. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  14083. if (self.ssrc2jid[ssrc] == from) {
  14084. delete self.ssrc2jid[ssrc];
  14085. }
  14086. });
  14087. var changedStreams = [];
  14088. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  14089. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  14090. var ssrcV = ssrc.getAttribute('ssrc');
  14091. self.ssrc2jid[ssrcV] = from;
  14092. JingleSession.notReceivedSSRCs.push(ssrcV);
  14093. var type = ssrc.getAttribute('type');
  14094. var direction = ssrc.getAttribute('direction');
  14095. changedStreams.push({type: type, direction: direction});
  14096. });
  14097. eventEmitter.emit(XMPPEvents.CHANGED_STREAMS, from, changedStreams);
  14098. var displayName = !config.displayJids
  14099. ? memeber.displayName : Strophe.getResourceFromJid(from);
  14100. if (displayName && displayName.length > 0)
  14101. {
  14102. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  14103. }
  14104. var id = $(pres).find('>userID').text();
  14105. var email = $(pres).find('>email');
  14106. if(email.length > 0) {
  14107. id = email.text();
  14108. }
  14109. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  14110. }
  14111. });
  14112. };
  14113. },{"../../service/xmpp/XMPPEvents":97,"./JingleSession":48,"./moderator":53}],56:[function(require,module,exports){
  14114. /* jshint -W117 */
  14115. var JingleSession = require("./JingleSession");
  14116. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14117. module.exports = function(XMPP, eventEmitter)
  14118. {
  14119. function CallIncomingJingle(sid, connection) {
  14120. var sess = connection.jingle.sessions[sid];
  14121. // TODO: do we check activecall == null?
  14122. connection.jingle.activecall = sess;
  14123. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  14124. // TODO: check affiliation and/or role
  14125. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  14126. sess.usedrip = true; // not-so-naive trickle ice
  14127. sess.sendAnswer();
  14128. sess.accept();
  14129. };
  14130. Strophe.addConnectionPlugin('jingle', {
  14131. connection: null,
  14132. sessions: {},
  14133. jid2session: {},
  14134. ice_config: {iceServers: []},
  14135. pc_constraints: {},
  14136. activecall: null,
  14137. media_constraints: {
  14138. mandatory: {
  14139. 'OfferToReceiveAudio': true,
  14140. 'OfferToReceiveVideo': true
  14141. }
  14142. // MozDontOfferDataChannel: true when this is firefox
  14143. },
  14144. init: function (conn) {
  14145. this.connection = conn;
  14146. if (this.connection.disco) {
  14147. // http://xmpp.org/extensions/xep-0167.html#support
  14148. // http://xmpp.org/extensions/xep-0176.html#support
  14149. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  14150. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  14151. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  14152. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  14153. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  14154. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  14155. // this is dealt with by SDP O/A so we don't need to annouce this
  14156. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  14157. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  14158. if (config.useRtcpMux) {
  14159. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  14160. }
  14161. if (config.useBundle) {
  14162. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  14163. }
  14164. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  14165. }
  14166. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  14167. },
  14168. onJingle: function (iq) {
  14169. var sid = $(iq).find('jingle').attr('sid');
  14170. var action = $(iq).find('jingle').attr('action');
  14171. var fromJid = iq.getAttribute('from');
  14172. // send ack first
  14173. var ack = $iq({type: 'result',
  14174. to: fromJid,
  14175. id: iq.getAttribute('id')
  14176. });
  14177. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  14178. var sess = this.sessions[sid];
  14179. if ('session-initiate' != action) {
  14180. if (sess === null) {
  14181. ack.type = 'error';
  14182. ack.c('error', {type: 'cancel'})
  14183. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14184. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14185. this.connection.send(ack);
  14186. return true;
  14187. }
  14188. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  14189. // local jid is not checked
  14190. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  14191. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  14192. ack.type = 'error';
  14193. ack.c('error', {type: 'cancel'})
  14194. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14195. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14196. this.connection.send(ack);
  14197. return true;
  14198. }
  14199. } else if (sess !== undefined) {
  14200. // existing session with same session id
  14201. // this might be out-of-order if the sess.peerjid is the same as from
  14202. ack.type = 'error';
  14203. ack.c('error', {type: 'cancel'})
  14204. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  14205. console.warn('duplicate session id', sid);
  14206. this.connection.send(ack);
  14207. return true;
  14208. }
  14209. // FIXME: check for a defined action
  14210. this.connection.send(ack);
  14211. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  14212. switch (action) {
  14213. case 'session-initiate':
  14214. sess = new JingleSession(
  14215. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  14216. this.connection, XMPP);
  14217. // configure session
  14218. sess.media_constraints = this.media_constraints;
  14219. sess.pc_constraints = this.pc_constraints;
  14220. sess.ice_config = this.ice_config;
  14221. sess.initiate(fromJid, false);
  14222. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  14223. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  14224. this.sessions[sess.sid] = sess;
  14225. this.jid2session[sess.peerjid] = sess;
  14226. // the callback should either
  14227. // .sendAnswer and .accept
  14228. // or .sendTerminate -- not necessarily synchronus
  14229. CallIncomingJingle(sess.sid, this.connection);
  14230. break;
  14231. case 'session-accept':
  14232. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  14233. sess.accept();
  14234. $(document).trigger('callaccepted.jingle', [sess.sid]);
  14235. break;
  14236. case 'session-terminate':
  14237. // If this is not the focus sending the terminate, we have
  14238. // nothing more to do here.
  14239. if (Object.keys(this.sessions).length < 1
  14240. || !(this.sessions[Object.keys(this.sessions)[0]]
  14241. instanceof JingleSession))
  14242. {
  14243. break;
  14244. }
  14245. console.log('terminating...', sess.sid);
  14246. sess.terminate();
  14247. this.terminate(sess.sid);
  14248. if ($(iq).find('>jingle>reason').length) {
  14249. $(document).trigger('callterminated.jingle', [
  14250. sess.sid,
  14251. sess.peerjid,
  14252. $(iq).find('>jingle>reason>:first')[0].tagName,
  14253. $(iq).find('>jingle>reason>text').text()
  14254. ]);
  14255. } else {
  14256. $(document).trigger('callterminated.jingle',
  14257. [sess.sid, sess.peerjid]);
  14258. }
  14259. break;
  14260. case 'transport-info':
  14261. sess.addIceCandidate($(iq).find('>jingle>content'));
  14262. break;
  14263. case 'session-info':
  14264. var affected;
  14265. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14266. $(document).trigger('ringing.jingle', [sess.sid]);
  14267. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14268. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14269. $(document).trigger('mute.jingle', [sess.sid, affected]);
  14270. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14271. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14272. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  14273. }
  14274. break;
  14275. case 'addsource': // FIXME: proprietary, un-jingleish
  14276. case 'source-add': // FIXME: proprietary
  14277. sess.addSource($(iq).find('>jingle>content'), fromJid);
  14278. break;
  14279. case 'removesource': // FIXME: proprietary, un-jingleish
  14280. case 'source-remove': // FIXME: proprietary
  14281. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  14282. break;
  14283. default:
  14284. console.warn('jingle action not implemented', action);
  14285. break;
  14286. }
  14287. return true;
  14288. },
  14289. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  14290. var sess = new JingleSession(myjid || this.connection.jid,
  14291. Math.random().toString(36).substr(2, 12), // random string
  14292. this.connection, XMPP);
  14293. // configure session
  14294. sess.media_constraints = this.media_constraints;
  14295. sess.pc_constraints = this.pc_constraints;
  14296. sess.ice_config = this.ice_config;
  14297. sess.initiate(peerjid, true);
  14298. this.sessions[sess.sid] = sess;
  14299. this.jid2session[sess.peerjid] = sess;
  14300. sess.sendOffer();
  14301. return sess;
  14302. },
  14303. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  14304. if (sid === null || sid === undefined) {
  14305. for (sid in this.sessions) {
  14306. if (this.sessions[sid].state != 'ended') {
  14307. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14308. this.sessions[sid].terminate();
  14309. }
  14310. delete this.jid2session[this.sessions[sid].peerjid];
  14311. delete this.sessions[sid];
  14312. }
  14313. } else if (this.sessions.hasOwnProperty(sid)) {
  14314. if (this.sessions[sid].state != 'ended') {
  14315. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14316. this.sessions[sid].terminate();
  14317. }
  14318. delete this.jid2session[this.sessions[sid].peerjid];
  14319. delete this.sessions[sid];
  14320. }
  14321. },
  14322. // Used to terminate a session when an unavailable presence is received.
  14323. terminateByJid: function (jid) {
  14324. if (this.jid2session.hasOwnProperty(jid)) {
  14325. var sess = this.jid2session[jid];
  14326. if (sess) {
  14327. sess.terminate();
  14328. console.log('peer went away silently', jid);
  14329. delete this.sessions[sess.sid];
  14330. delete this.jid2session[jid];
  14331. $(document).trigger('callterminated.jingle',
  14332. [sess.sid, jid], 'gone');
  14333. }
  14334. }
  14335. },
  14336. terminateRemoteByJid: function (jid, reason) {
  14337. if (this.jid2session.hasOwnProperty(jid)) {
  14338. var sess = this.jid2session[jid];
  14339. if (sess) {
  14340. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  14341. sess.terminate();
  14342. console.log('terminate peer with jid', sess.sid, jid);
  14343. delete this.sessions[sess.sid];
  14344. delete this.jid2session[jid];
  14345. $(document).trigger('callterminated.jingle',
  14346. [sess.sid, jid, 'kicked']);
  14347. }
  14348. }
  14349. },
  14350. getStunAndTurnCredentials: function () {
  14351. // get stun and turn configuration from server via xep-0215
  14352. // uses time-limited credentials as described in
  14353. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  14354. //
  14355. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  14356. // for a prosody module which implements this
  14357. //
  14358. // currently, this doesn't work with updateIce and therefore credentials with a long
  14359. // validity have to be fetched before creating the peerconnection
  14360. // TODO: implement refresh via updateIce as described in
  14361. // https://code.google.com/p/webrtc/issues/detail?id=1650
  14362. var self = this;
  14363. this.connection.sendIQ(
  14364. $iq({type: 'get', to: this.connection.domain})
  14365. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  14366. function (res) {
  14367. var iceservers = [];
  14368. $(res).find('>services>service').each(function (idx, el) {
  14369. el = $(el);
  14370. var dict = {};
  14371. var type = el.attr('type');
  14372. switch (type) {
  14373. case 'stun':
  14374. dict.url = 'stun:' + el.attr('host');
  14375. if (el.attr('port')) {
  14376. dict.url += ':' + el.attr('port');
  14377. }
  14378. iceservers.push(dict);
  14379. break;
  14380. case 'turn':
  14381. case 'turns':
  14382. dict.url = type + ':';
  14383. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  14384. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  14385. dict.url += el.attr('username') + '@';
  14386. } else {
  14387. dict.username = el.attr('username'); // only works in M28
  14388. }
  14389. }
  14390. dict.url += el.attr('host');
  14391. if (el.attr('port') && el.attr('port') != '3478') {
  14392. dict.url += ':' + el.attr('port');
  14393. }
  14394. if (el.attr('transport') && el.attr('transport') != 'udp') {
  14395. dict.url += '?transport=' + el.attr('transport');
  14396. }
  14397. if (el.attr('password')) {
  14398. dict.credential = el.attr('password');
  14399. }
  14400. iceservers.push(dict);
  14401. break;
  14402. }
  14403. });
  14404. self.ice_config.iceServers = iceservers;
  14405. },
  14406. function (err) {
  14407. console.warn('getting turn credentials failed', err);
  14408. console.warn('is mod_turncredentials or similar installed?');
  14409. }
  14410. );
  14411. // implement push?
  14412. },
  14413. /**
  14414. * Populates the log data
  14415. */
  14416. populateData: function () {
  14417. var data = {};
  14418. Object.keys(this.sessions).forEach(function (sid) {
  14419. var session = this.sessions[sid];
  14420. if (session.peerconnection && session.peerconnection.updateLog) {
  14421. // FIXME: should probably be a .dump call
  14422. data["jingle_" + session.sid] = {
  14423. updateLog: session.peerconnection.updateLog,
  14424. stats: session.peerconnection.stats,
  14425. url: window.location.href
  14426. };
  14427. }
  14428. });
  14429. return data;
  14430. }
  14431. });
  14432. };
  14433. },{"../../service/xmpp/XMPPEvents":97,"./JingleSession":48}],57:[function(require,module,exports){
  14434. /* global Strophe */
  14435. module.exports = function () {
  14436. Strophe.addConnectionPlugin('logger', {
  14437. // logs raw stanzas and makes them available for download as JSON
  14438. connection: null,
  14439. log: [],
  14440. init: function (conn) {
  14441. this.connection = conn;
  14442. this.connection.rawInput = this.log_incoming.bind(this);
  14443. this.connection.rawOutput = this.log_outgoing.bind(this);
  14444. },
  14445. log_incoming: function (stanza) {
  14446. this.log.push([new Date().getTime(), 'incoming', stanza]);
  14447. },
  14448. log_outgoing: function (stanza) {
  14449. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  14450. }
  14451. });
  14452. };
  14453. },{}],58:[function(require,module,exports){
  14454. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  14455. setAudioMuted, Strophe */
  14456. /**
  14457. * Moderate connection plugin.
  14458. */
  14459. module.exports = function (XMPP) {
  14460. Strophe.addConnectionPlugin('moderate', {
  14461. connection: null,
  14462. init: function (conn) {
  14463. this.connection = conn;
  14464. this.connection.addHandler(this.onMute.bind(this),
  14465. 'http://jitsi.org/jitmeet/audio',
  14466. 'iq',
  14467. 'set',
  14468. null,
  14469. null);
  14470. },
  14471. setMute: function (jid, mute) {
  14472. console.info("set mute", mute);
  14473. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  14474. .c('mute', {
  14475. xmlns: 'http://jitsi.org/jitmeet/audio',
  14476. jid: jid
  14477. })
  14478. .t(mute.toString())
  14479. .up();
  14480. this.connection.sendIQ(
  14481. iqToFocus,
  14482. function (result) {
  14483. console.log('set mute', result);
  14484. },
  14485. function (error) {
  14486. console.log('set mute error', error);
  14487. });
  14488. },
  14489. onMute: function (iq) {
  14490. var from = iq.getAttribute('from');
  14491. if (from !== this.connection.emuc.focusMucJid) {
  14492. console.warn("Ignored mute from non focus peer");
  14493. return false;
  14494. }
  14495. var mute = $(iq).find('mute');
  14496. if (mute.length) {
  14497. var doMuteAudio = mute.text() === "true";
  14498. APP.UI.setAudioMuted(doMuteAudio);
  14499. XMPP.forceMuted = doMuteAudio;
  14500. }
  14501. return true;
  14502. },
  14503. eject: function (jid) {
  14504. // We're not the focus, so can't terminate
  14505. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  14506. this.connection.emuc.kick(jid);
  14507. }
  14508. });
  14509. }
  14510. },{}],59:[function(require,module,exports){
  14511. /* jshint -W117 */
  14512. module.exports = function() {
  14513. Strophe.addConnectionPlugin('rayo',
  14514. {
  14515. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  14516. connection: null,
  14517. init: function (conn) {
  14518. this.connection = conn;
  14519. if (this.connection.disco) {
  14520. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  14521. }
  14522. this.connection.addHandler(
  14523. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  14524. },
  14525. onRayo: function (iq) {
  14526. console.info("Rayo IQ", iq);
  14527. },
  14528. dial: function (to, from, roomName, roomPass) {
  14529. var self = this;
  14530. var req = $iq(
  14531. {
  14532. type: 'set',
  14533. to: this.connection.emuc.focusMucJid
  14534. }
  14535. );
  14536. req.c('dial',
  14537. {
  14538. xmlns: this.RAYO_XMLNS,
  14539. to: to,
  14540. from: from
  14541. });
  14542. req.c('header',
  14543. {
  14544. name: 'JvbRoomName',
  14545. value: roomName
  14546. }).up();
  14547. if (roomPass !== null && roomPass.length) {
  14548. req.c('header',
  14549. {
  14550. name: 'JvbRoomPassword',
  14551. value: roomPass
  14552. }).up();
  14553. }
  14554. this.connection.sendIQ(
  14555. req,
  14556. function (result) {
  14557. console.info('Dial result ', result);
  14558. var resource = $(result).find('ref').attr('uri');
  14559. this.call_resource = resource.substr('xmpp:'.length);
  14560. console.info(
  14561. "Received call resource: " + this.call_resource);
  14562. },
  14563. function (error) {
  14564. console.info('Dial error ', error);
  14565. }
  14566. );
  14567. },
  14568. hang_up: function () {
  14569. if (!this.call_resource) {
  14570. console.warn("No call in progress");
  14571. return;
  14572. }
  14573. var self = this;
  14574. var req = $iq(
  14575. {
  14576. type: 'set',
  14577. to: this.call_resource
  14578. }
  14579. );
  14580. req.c('hangup',
  14581. {
  14582. xmlns: this.RAYO_XMLNS
  14583. });
  14584. this.connection.sendIQ(
  14585. req,
  14586. function (result) {
  14587. console.info('Hangup result ', result);
  14588. self.call_resource = null;
  14589. },
  14590. function (error) {
  14591. console.info('Hangup error ', error);
  14592. self.call_resource = null;
  14593. }
  14594. );
  14595. }
  14596. }
  14597. );
  14598. };
  14599. },{}],60:[function(require,module,exports){
  14600. /**
  14601. * Strophe logger implementation. Logs from level WARN and above.
  14602. */
  14603. module.exports = function () {
  14604. Strophe.log = function (level, msg) {
  14605. switch (level) {
  14606. case Strophe.LogLevel.WARN:
  14607. console.warn("Strophe: " + msg);
  14608. break;
  14609. case Strophe.LogLevel.ERROR:
  14610. case Strophe.LogLevel.FATAL:
  14611. console.error("Strophe: " + msg);
  14612. break;
  14613. }
  14614. };
  14615. Strophe.getStatusString = function (status) {
  14616. switch (status) {
  14617. case Strophe.Status.ERROR:
  14618. return "ERROR";
  14619. case Strophe.Status.CONNECTING:
  14620. return "CONNECTING";
  14621. case Strophe.Status.CONNFAIL:
  14622. return "CONNFAIL";
  14623. case Strophe.Status.AUTHENTICATING:
  14624. return "AUTHENTICATING";
  14625. case Strophe.Status.AUTHFAIL:
  14626. return "AUTHFAIL";
  14627. case Strophe.Status.CONNECTED:
  14628. return "CONNECTED";
  14629. case Strophe.Status.DISCONNECTED:
  14630. return "DISCONNECTED";
  14631. case Strophe.Status.DISCONNECTING:
  14632. return "DISCONNECTING";
  14633. case Strophe.Status.ATTACHED:
  14634. return "ATTACHED";
  14635. default:
  14636. return "unknown";
  14637. }
  14638. };
  14639. };
  14640. },{}],61:[function(require,module,exports){
  14641. /* global $, APP, config, Strophe*/
  14642. var Moderator = require("./moderator");
  14643. var EventEmitter = require("events");
  14644. var Recording = require("./recording");
  14645. var SDP = require("./SDP");
  14646. var Pako = require("pako");
  14647. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  14648. var UIEvents = require("../../service/UI/UIEvents");
  14649. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14650. var eventEmitter = new EventEmitter();
  14651. var connection = null;
  14652. var authenticatedUser = false;
  14653. function connect(jid, password) {
  14654. connection = XMPP.createConnection();
  14655. Moderator.setConnection(connection);
  14656. if (connection.disco) {
  14657. // for chrome, add multistream cap
  14658. }
  14659. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  14660. if (config.useIPv6) {
  14661. // https://code.google.com/p/webrtc/issues/detail?id=2828
  14662. if (!connection.jingle.pc_constraints.optional)
  14663. connection.jingle.pc_constraints.optional = [];
  14664. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  14665. }
  14666. var anonymousConnectionFailed = false;
  14667. connection.connect(jid, password, function (status, msg) {
  14668. console.log('Strophe status changed to',
  14669. Strophe.getStatusString(status));
  14670. if (status === Strophe.Status.CONNECTED) {
  14671. if (config.useStunTurn) {
  14672. connection.jingle.getStunAndTurnCredentials();
  14673. }
  14674. console.info("My Jabber ID: " + connection.jid);
  14675. if(password)
  14676. authenticatedUser = true;
  14677. maybeDoJoin();
  14678. } else if (status === Strophe.Status.CONNFAIL) {
  14679. if(msg === 'x-strophe-bad-non-anon-jid') {
  14680. anonymousConnectionFailed = true;
  14681. }
  14682. } else if (status === Strophe.Status.DISCONNECTED) {
  14683. if(anonymousConnectionFailed) {
  14684. // prompt user for username and password
  14685. XMPP.promptLogin();
  14686. }
  14687. } else if (status === Strophe.Status.AUTHFAIL) {
  14688. // wrong password or username, prompt user
  14689. XMPP.promptLogin();
  14690. }
  14691. });
  14692. }
  14693. function maybeDoJoin() {
  14694. if (connection && connection.connected &&
  14695. Strophe.getResourceFromJid(connection.jid)
  14696. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  14697. // .connected is true while connecting?
  14698. doJoin();
  14699. }
  14700. }
  14701. function doJoin() {
  14702. var roomName = APP.UI.generateRoomName();
  14703. Moderator.allocateConferenceFocus(
  14704. roomName, APP.UI.checkForNicknameAndJoin);
  14705. }
  14706. function initStrophePlugins()
  14707. {
  14708. require("./strophe.emuc")(XMPP, eventEmitter);
  14709. require("./strophe.jingle")(XMPP, eventEmitter);
  14710. require("./strophe.moderate")(XMPP);
  14711. require("./strophe.util")();
  14712. require("./strophe.rayo")();
  14713. require("./strophe.logger")();
  14714. }
  14715. function registerListeners() {
  14716. APP.RTC.addStreamListener(maybeDoJoin,
  14717. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  14718. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  14719. XMPP.addToPresence("displayName", nickname);
  14720. });
  14721. }
  14722. function setupEvents() {
  14723. $(window).bind('beforeunload', function () {
  14724. if (connection && connection.connected) {
  14725. // ensure signout
  14726. $.ajax({
  14727. type: 'POST',
  14728. url: config.bosh,
  14729. async: false,
  14730. cache: false,
  14731. contentType: 'application/xml',
  14732. data: "<body rid='" + (connection.rid || connection._proto.rid)
  14733. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  14734. + (connection.sid || connection._proto.sid)
  14735. + "' type='terminate'>" +
  14736. "<presence xmlns='jabber:client' type='unavailable'/>" +
  14737. "</body>",
  14738. success: function (data) {
  14739. console.log('signed out');
  14740. console.log(data);
  14741. },
  14742. error: function (XMLHttpRequest, textStatus, errorThrown) {
  14743. console.log('signout error',
  14744. textStatus + ' (' + errorThrown + ')');
  14745. }
  14746. });
  14747. }
  14748. XMPP.disposeConference(true);
  14749. });
  14750. }
  14751. var XMPP = {
  14752. sessionTerminated: false,
  14753. /**
  14754. * XMPP connection status
  14755. */
  14756. Status: Strophe.Status,
  14757. /**
  14758. * Remembers if we were muted by the focus.
  14759. * @type {boolean}
  14760. */
  14761. forceMuted: false,
  14762. start: function () {
  14763. setupEvents();
  14764. initStrophePlugins();
  14765. registerListeners();
  14766. Moderator.init(this, eventEmitter);
  14767. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  14768. // Force authenticated domain if room is appended with '?login=true'
  14769. if (config.hosts.anonymousdomain &&
  14770. window.location.search.indexOf("login=true") !== -1) {
  14771. configDomain = config.hosts.domain;
  14772. }
  14773. var jid = configDomain || window.location.hostname;
  14774. connect(jid, null);
  14775. },
  14776. createConnection: function () {
  14777. var bosh = config.bosh || '/http-bind';
  14778. return new Strophe.Connection(bosh);
  14779. },
  14780. getStatusString: function (status) {
  14781. return Strophe.getStatusString(status);
  14782. },
  14783. promptLogin: function () {
  14784. // FIXME: re-use LoginDialog which supports retries
  14785. APP.UI.showLoginPopup(connect);
  14786. },
  14787. joinRoom: function(roomName, useNicks, nick)
  14788. {
  14789. var roomjid;
  14790. roomjid = roomName;
  14791. if (useNicks) {
  14792. if (nick) {
  14793. roomjid += '/' + nick;
  14794. } else {
  14795. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  14796. }
  14797. } else {
  14798. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  14799. if(!authenticatedUser)
  14800. tmpJid = tmpJid.substr(0, 8);
  14801. roomjid += '/' + tmpJid;
  14802. }
  14803. connection.emuc.doJoin(roomjid);
  14804. },
  14805. myJid: function () {
  14806. if(!connection)
  14807. return null;
  14808. return connection.emuc.myroomjid;
  14809. },
  14810. myResource: function () {
  14811. if(!connection || ! connection.emuc.myroomjid)
  14812. return null;
  14813. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  14814. },
  14815. disposeConference: function (onUnload) {
  14816. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  14817. var handler = connection.jingle.activecall;
  14818. if (handler && handler.peerconnection) {
  14819. // FIXME: probably removing streams is not required and close() should
  14820. // be enough
  14821. if (APP.RTC.localAudio) {
  14822. handler.peerconnection.removeStream(APP.RTC.localAudio.getOriginalStream(), onUnload);
  14823. }
  14824. if (APP.RTC.localVideo) {
  14825. handler.peerconnection.removeStream(APP.RTC.localVideo.getOriginalStream(), onUnload);
  14826. }
  14827. handler.peerconnection.close();
  14828. }
  14829. connection.jingle.activecall = null;
  14830. if(!onUnload)
  14831. {
  14832. this.sessionTerminated = true;
  14833. connection.emuc.doLeave();
  14834. }
  14835. },
  14836. addListener: function(type, listener)
  14837. {
  14838. eventEmitter.on(type, listener);
  14839. },
  14840. removeListener: function (type, listener) {
  14841. eventEmitter.removeListener(type, listener);
  14842. },
  14843. allocateConferenceFocus: function(roomName, callback) {
  14844. Moderator.allocateConferenceFocus(roomName, callback);
  14845. },
  14846. getLoginUrl: function (roomName, callback) {
  14847. Moderator.getLoginUrl(roomName, callback);
  14848. },
  14849. getPopupLoginUrl: function (roomName, callback) {
  14850. Moderator.getPopupLoginUrl(roomName, callback);
  14851. },
  14852. isModerator: function () {
  14853. return Moderator.isModerator();
  14854. },
  14855. isSipGatewayEnabled: function () {
  14856. return Moderator.isSipGatewayEnabled();
  14857. },
  14858. isExternalAuthEnabled: function () {
  14859. return Moderator.isExternalAuthEnabled();
  14860. },
  14861. switchStreams: function (stream, oldStream, callback) {
  14862. if (connection && connection.jingle.activecall) {
  14863. // FIXME: will block switchInProgress on true value in case of exception
  14864. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  14865. } else {
  14866. // We are done immediately
  14867. console.warn("No conference handler or conference not started yet");
  14868. callback();
  14869. }
  14870. },
  14871. setVideoMute: function (mute, callback, options) {
  14872. if(connection && APP.RTC.localVideo && connection.jingle.activecall)
  14873. {
  14874. connection.jingle.activecall.setVideoMute(mute, callback, options);
  14875. }
  14876. },
  14877. setAudioMute: function (mute, callback) {
  14878. if (!(connection && APP.RTC.localAudio)) {
  14879. return false;
  14880. }
  14881. if (this.forceMuted && !mute) {
  14882. console.info("Asking focus for unmute");
  14883. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  14884. // FIXME: wait for result before resetting muted status
  14885. this.forceMuted = false;
  14886. }
  14887. if (mute == APP.RTC.localAudio.isMuted()) {
  14888. // Nothing to do
  14889. return true;
  14890. }
  14891. // It is not clear what is the right way to handle multiple tracks.
  14892. // So at least make sure that they are all muted or all unmuted and
  14893. // that we send presence just once.
  14894. APP.RTC.localAudio.mute();
  14895. // isMuted is the opposite of audioEnabled
  14896. connection.emuc.addAudioInfoToPresence(mute);
  14897. connection.emuc.sendPresence();
  14898. callback();
  14899. return true;
  14900. },
  14901. // Really mute video, i.e. dont even send black frames
  14902. muteVideo: function (pc, unmute) {
  14903. // FIXME: this probably needs another of those lovely state safeguards...
  14904. // which checks for iceconn == connected and sigstate == stable
  14905. pc.setRemoteDescription(pc.remoteDescription,
  14906. function () {
  14907. pc.createAnswer(
  14908. function (answer) {
  14909. var sdp = new SDP(answer.sdp);
  14910. if (sdp.media.length > 1) {
  14911. if (unmute)
  14912. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  14913. else
  14914. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  14915. sdp.raw = sdp.session + sdp.media.join('');
  14916. answer.sdp = sdp.raw;
  14917. }
  14918. pc.setLocalDescription(answer,
  14919. function () {
  14920. console.log('mute SLD ok');
  14921. },
  14922. function (error) {
  14923. console.log('mute SLD error');
  14924. APP.UI.messageHandler.showError("dialog.error",
  14925. "dialog.SLDFailure");
  14926. }
  14927. );
  14928. },
  14929. function (error) {
  14930. console.log(error);
  14931. APP.UI.messageHandler.showError();
  14932. }
  14933. );
  14934. },
  14935. function (error) {
  14936. console.log('muteVideo SRD error');
  14937. APP.UI.messageHandler.showError("dialog.error",
  14938. "dialog.SRDFailure");
  14939. }
  14940. );
  14941. },
  14942. toggleRecording: function (tokenEmptyCallback,
  14943. startingCallback, startedCallback) {
  14944. Recording.toggleRecording(tokenEmptyCallback,
  14945. startingCallback, startedCallback, connection);
  14946. },
  14947. addToPresence: function (name, value, dontSend) {
  14948. switch (name)
  14949. {
  14950. case "displayName":
  14951. connection.emuc.addDisplayNameToPresence(value);
  14952. break;
  14953. case "etherpad":
  14954. connection.emuc.addEtherpadToPresence(value);
  14955. break;
  14956. case "prezi":
  14957. connection.emuc.addPreziToPresence(value, 0);
  14958. break;
  14959. case "preziSlide":
  14960. connection.emuc.addCurrentSlideToPresence(value);
  14961. break;
  14962. case "connectionQuality":
  14963. connection.emuc.addConnectionInfoToPresence(value);
  14964. break;
  14965. case "email":
  14966. connection.emuc.addEmailToPresence(value);
  14967. default :
  14968. console.log("Unknown tag for presence.");
  14969. return;
  14970. }
  14971. if(!dontSend)
  14972. connection.emuc.sendPresence();
  14973. },
  14974. /**
  14975. * Sends 'data' as a log message to the focus. Returns true iff a message
  14976. * was sent.
  14977. * @param data
  14978. * @returns {boolean} true iff a message was sent.
  14979. */
  14980. sendLogs: function (data) {
  14981. if(!connection.emuc.focusMucJid)
  14982. return false;
  14983. var deflate = true;
  14984. var content = JSON.stringify(data);
  14985. if (deflate) {
  14986. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  14987. }
  14988. content = Base64.encode(content);
  14989. // XEP-0337-ish
  14990. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  14991. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  14992. id: 'PeerConnectionStats'});
  14993. message.c('message').t(content).up();
  14994. if (deflate) {
  14995. message.c('tag', {name: "deflated", value: "true"}).up();
  14996. }
  14997. message.up();
  14998. connection.send(message);
  14999. return true;
  15000. },
  15001. populateData: function () {
  15002. var data = {};
  15003. if (connection.jingle) {
  15004. data = connection.jingle.populateData();
  15005. }
  15006. return data;
  15007. },
  15008. getLogger: function () {
  15009. if(connection.logger)
  15010. return connection.logger.log;
  15011. return null;
  15012. },
  15013. getPrezi: function () {
  15014. return connection.emuc.getPrezi(this.myJid());
  15015. },
  15016. removePreziFromPresence: function () {
  15017. connection.emuc.removePreziFromPresence();
  15018. connection.emuc.sendPresence();
  15019. },
  15020. sendChatMessage: function (message, nickname) {
  15021. connection.emuc.sendMessage(message, nickname);
  15022. },
  15023. setSubject: function (topic) {
  15024. connection.emuc.setSubject(topic);
  15025. },
  15026. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15027. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  15028. },
  15029. dial: function (to, from, roomName,roomPass) {
  15030. connection.rayo.dial(to, from, roomName,roomPass);
  15031. },
  15032. setMute: function (jid, mute) {
  15033. connection.moderate.setMute(jid, mute);
  15034. },
  15035. eject: function (jid) {
  15036. connection.moderate.eject(jid);
  15037. },
  15038. logout: function (callback) {
  15039. Moderator.logout(callback);
  15040. },
  15041. findJidFromResource: function (resource) {
  15042. return connection.emuc.findJidFromResource(resource);
  15043. },
  15044. getMembers: function () {
  15045. return connection.emuc.members;
  15046. },
  15047. getJidFromSSRC: function (ssrc) {
  15048. if(!connection)
  15049. return null;
  15050. return connection.emuc.ssrc2jid[ssrc];
  15051. },
  15052. getMUCJoined: function () {
  15053. return connection.emuc.joined;
  15054. },
  15055. getSessions: function () {
  15056. return connection.jingle.sessions;
  15057. }
  15058. };
  15059. module.exports = XMPP;
  15060. },{"../../service/RTC/StreamEventTypes":91,"../../service/UI/UIEvents":92,"../../service/xmpp/XMPPEvents":97,"./SDP":49,"./moderator":53,"./recording":54,"./strophe.emuc":55,"./strophe.jingle":56,"./strophe.logger":57,"./strophe.moderate":58,"./strophe.rayo":59,"./strophe.util":60,"events":98,"pako":63}],62:[function(require,module,exports){
  15061. // i18next, v1.7.7
  15062. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  15063. // Distributed under MIT license
  15064. // http://i18next.com
  15065. (function() {
  15066. // add indexOf to non ECMA-262 standard compliant browsers
  15067. if (!Array.prototype.indexOf) {
  15068. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  15069. "use strict";
  15070. if (this == null) {
  15071. throw new TypeError();
  15072. }
  15073. var t = Object(this);
  15074. var len = t.length >>> 0;
  15075. if (len === 0) {
  15076. return -1;
  15077. }
  15078. var n = 0;
  15079. if (arguments.length > 0) {
  15080. n = Number(arguments[1]);
  15081. if (n != n) { // shortcut for verifying if it's NaN
  15082. n = 0;
  15083. } else if (n != 0 && n != Infinity && n != -Infinity) {
  15084. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  15085. }
  15086. }
  15087. if (n >= len) {
  15088. return -1;
  15089. }
  15090. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  15091. for (; k < len; k++) {
  15092. if (k in t && t[k] === searchElement) {
  15093. return k;
  15094. }
  15095. }
  15096. return -1;
  15097. }
  15098. }
  15099. // add lastIndexOf to non ECMA-262 standard compliant browsers
  15100. if (!Array.prototype.lastIndexOf) {
  15101. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  15102. "use strict";
  15103. if (this == null) {
  15104. throw new TypeError();
  15105. }
  15106. var t = Object(this);
  15107. var len = t.length >>> 0;
  15108. if (len === 0) {
  15109. return -1;
  15110. }
  15111. var n = len;
  15112. if (arguments.length > 1) {
  15113. n = Number(arguments[1]);
  15114. if (n != n) {
  15115. n = 0;
  15116. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  15117. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  15118. }
  15119. }
  15120. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  15121. for (; k >= 0; k--) {
  15122. if (k in t && t[k] === searchElement) {
  15123. return k;
  15124. }
  15125. }
  15126. return -1;
  15127. };
  15128. }
  15129. // Add string trim for IE8.
  15130. if (typeof String.prototype.trim !== 'function') {
  15131. String.prototype.trim = function() {
  15132. return this.replace(/^\s+|\s+$/g, '');
  15133. }
  15134. }
  15135. var root = this
  15136. , $ = root.jQuery || root.Zepto
  15137. , i18n = {}
  15138. , resStore = {}
  15139. , currentLng
  15140. , replacementCounter = 0
  15141. , languages = []
  15142. , initialized = false
  15143. , sync = {};
  15144. // Export the i18next object for **CommonJS**.
  15145. // If we're not in CommonJS, add `i18n` to the
  15146. // global object or to jquery.
  15147. if (typeof module !== 'undefined' && module.exports) {
  15148. if (!$) {
  15149. try {
  15150. $ = require('jquery');
  15151. } catch(e) {
  15152. // just ignore
  15153. }
  15154. }
  15155. if ($) {
  15156. $.i18n = $.i18n || i18n;
  15157. }
  15158. module.exports = i18n;
  15159. } else {
  15160. if ($) {
  15161. $.i18n = $.i18n || i18n;
  15162. }
  15163. root.i18n = root.i18n || i18n;
  15164. }
  15165. sync = {
  15166. load: function(lngs, options, cb) {
  15167. if (options.useLocalStorage) {
  15168. sync._loadLocal(lngs, options, function(err, store) {
  15169. var missingLngs = [];
  15170. for (var i = 0, len = lngs.length; i < len; i++) {
  15171. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  15172. }
  15173. if (missingLngs.length > 0) {
  15174. sync._fetch(missingLngs, options, function(err, fetched) {
  15175. f.extend(store, fetched);
  15176. sync._storeLocal(fetched);
  15177. cb(null, store);
  15178. });
  15179. } else {
  15180. cb(null, store);
  15181. }
  15182. });
  15183. } else {
  15184. sync._fetch(lngs, options, function(err, store){
  15185. cb(null, store);
  15186. });
  15187. }
  15188. },
  15189. _loadLocal: function(lngs, options, cb) {
  15190. var store = {}
  15191. , nowMS = new Date().getTime();
  15192. if(window.localStorage) {
  15193. var todo = lngs.length;
  15194. f.each(lngs, function(key, lng) {
  15195. var local = window.localStorage.getItem('res_' + lng);
  15196. if (local) {
  15197. local = JSON.parse(local);
  15198. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  15199. store[lng] = local;
  15200. }
  15201. }
  15202. todo--; // wait for all done befor callback
  15203. if (todo === 0) cb(null, store);
  15204. });
  15205. }
  15206. },
  15207. _storeLocal: function(store) {
  15208. if(window.localStorage) {
  15209. for (var m in store) {
  15210. store[m].i18nStamp = new Date().getTime();
  15211. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  15212. }
  15213. }
  15214. return;
  15215. },
  15216. _fetch: function(lngs, options, cb) {
  15217. var ns = options.ns
  15218. , store = {};
  15219. if (!options.dynamicLoad) {
  15220. var todo = ns.namespaces.length * lngs.length
  15221. , errors;
  15222. // load each file individual
  15223. f.each(ns.namespaces, function(nsIndex, nsValue) {
  15224. f.each(lngs, function(lngIndex, lngValue) {
  15225. // Call this once our translation has returned.
  15226. var loadComplete = function(err, data) {
  15227. if (err) {
  15228. errors = errors || [];
  15229. errors.push(err);
  15230. }
  15231. store[lngValue] = store[lngValue] || {};
  15232. store[lngValue][nsValue] = data;
  15233. todo--; // wait for all done befor callback
  15234. if (todo === 0) cb(errors, store);
  15235. };
  15236. if(typeof options.customLoad == 'function'){
  15237. // Use the specified custom callback.
  15238. options.customLoad(lngValue, nsValue, options, loadComplete);
  15239. } else {
  15240. //~ // Use our inbuilt sync.
  15241. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  15242. }
  15243. });
  15244. });
  15245. } else {
  15246. // Call this once our translation has returned.
  15247. var loadComplete = function(err, data) {
  15248. cb(null, data);
  15249. };
  15250. if(typeof options.customLoad == 'function'){
  15251. // Use the specified custom callback.
  15252. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  15253. } else {
  15254. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  15255. // load all needed stuff once
  15256. f.ajax({
  15257. url: url,
  15258. success: function(data, status, xhr) {
  15259. f.log('loaded: ' + url);
  15260. loadComplete(null, data);
  15261. },
  15262. error : function(xhr, status, error) {
  15263. f.log('failed loading: ' + url);
  15264. loadComplete('failed loading resource.json error: ' + error);
  15265. },
  15266. dataType: "json",
  15267. async : options.getAsync
  15268. });
  15269. }
  15270. }
  15271. },
  15272. _fetchOne: function(lng, ns, options, done) {
  15273. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  15274. f.ajax({
  15275. url: url,
  15276. success: function(data, status, xhr) {
  15277. f.log('loaded: ' + url);
  15278. done(null, data);
  15279. },
  15280. error : function(xhr, status, error) {
  15281. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  15282. // file loaded but invalid json, stop waste time !
  15283. f.error('There is a typo in: ' + url);
  15284. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  15285. f.log('Does not exist: ' + url);
  15286. } else {
  15287. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  15288. f.log(theStatus + ' when loading ' + url);
  15289. }
  15290. done(error, {});
  15291. },
  15292. dataType: "json",
  15293. async : options.getAsync
  15294. });
  15295. },
  15296. postMissing: function(lng, ns, key, defaultValue, lngs) {
  15297. var payload = {};
  15298. payload[key] = defaultValue;
  15299. var urls = [];
  15300. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  15301. for (var i = 0; i < o.fallbackLng.length; i++) {
  15302. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  15303. }
  15304. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  15305. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  15306. } else if (o.sendMissingTo === 'all') {
  15307. for (var i = 0, l = lngs.length; i < l; i++) {
  15308. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  15309. }
  15310. }
  15311. for (var y = 0, len = urls.length; y < len; y++) {
  15312. var item = urls[y];
  15313. f.ajax({
  15314. url: item.url,
  15315. type: o.sendType,
  15316. data: payload,
  15317. success: function(data, status, xhr) {
  15318. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  15319. // add key to resStore
  15320. var keys = key.split('.');
  15321. var x = 0;
  15322. var value = resStore[item.lng][ns];
  15323. while (keys[x]) {
  15324. if (x === keys.length - 1) {
  15325. value = value[keys[x]] = defaultValue;
  15326. } else {
  15327. value = value[keys[x]] = value[keys[x]] || {};
  15328. }
  15329. x++;
  15330. }
  15331. },
  15332. error : function(xhr, status, error) {
  15333. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  15334. },
  15335. dataType: "json",
  15336. async : o.postAsync
  15337. });
  15338. }
  15339. },
  15340. reload: reload
  15341. };
  15342. // defaults
  15343. var o = {
  15344. lng: undefined,
  15345. load: 'all',
  15346. preload: [],
  15347. lowerCaseLng: false,
  15348. returnObjectTrees: false,
  15349. fallbackLng: ['dev'],
  15350. fallbackNS: [],
  15351. detectLngQS: 'setLng',
  15352. detectLngFromLocalStorage: false,
  15353. ns: 'translation',
  15354. fallbackOnNull: true,
  15355. fallbackOnEmpty: false,
  15356. fallbackToDefaultNS: false,
  15357. nsseparator: ':',
  15358. keyseparator: '.',
  15359. selectorAttr: 'data-i18n',
  15360. debug: false,
  15361. resGetPath: 'locales/__lng__/__ns__.json',
  15362. resPostPath: 'locales/add/__lng__/__ns__',
  15363. getAsync: true,
  15364. postAsync: true,
  15365. resStore: undefined,
  15366. useLocalStorage: false,
  15367. localStorageExpirationTime: 7*24*60*60*1000,
  15368. dynamicLoad: false,
  15369. sendMissing: false,
  15370. sendMissingTo: 'fallback', // current | all
  15371. sendType: 'POST',
  15372. interpolationPrefix: '__',
  15373. interpolationSuffix: '__',
  15374. defaultVariables: false,
  15375. reusePrefix: '$t(',
  15376. reuseSuffix: ')',
  15377. pluralSuffix: '_plural',
  15378. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  15379. contextNotFound: ['context_not_found', Math.random()].join(''),
  15380. escapeInterpolation: false,
  15381. indefiniteSuffix: '_indefinite',
  15382. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  15383. setJqueryExt: true,
  15384. defaultValueFromContent: true,
  15385. useDataAttrOptions: false,
  15386. cookieExpirationTime: undefined,
  15387. useCookie: true,
  15388. cookieName: 'i18next',
  15389. cookieDomain: undefined,
  15390. objectTreeKeyHandler: undefined,
  15391. postProcess: undefined,
  15392. parseMissingKey: undefined,
  15393. missingKeyHandler: sync.postMissing,
  15394. shortcutFunction: 'sprintf' // or: defaultValue
  15395. };
  15396. function _extend(target, source) {
  15397. if (!source || typeof source === 'function') {
  15398. return target;
  15399. }
  15400. for (var attr in source) { target[attr] = source[attr]; }
  15401. return target;
  15402. }
  15403. function _deepExtend(target, source) {
  15404. for (var prop in source)
  15405. if (prop in target)
  15406. _deepExtend(target[prop], source[prop]);
  15407. else
  15408. target[prop] = source[prop];
  15409. return target;
  15410. }
  15411. function _each(object, callback, args) {
  15412. var name, i = 0,
  15413. length = object.length,
  15414. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  15415. if (args) {
  15416. if (isObj) {
  15417. for (name in object) {
  15418. if (callback.apply(object[name], args) === false) {
  15419. break;
  15420. }
  15421. }
  15422. } else {
  15423. for ( ; i < length; ) {
  15424. if (callback.apply(object[i++], args) === false) {
  15425. break;
  15426. }
  15427. }
  15428. }
  15429. // A special, fast, case for the most common use of each
  15430. } else {
  15431. if (isObj) {
  15432. for (name in object) {
  15433. if (callback.call(object[name], name, object[name]) === false) {
  15434. break;
  15435. }
  15436. }
  15437. } else {
  15438. for ( ; i < length; ) {
  15439. if (callback.call(object[i], i, object[i++]) === false) {
  15440. break;
  15441. }
  15442. }
  15443. }
  15444. }
  15445. return object;
  15446. }
  15447. var _entityMap = {
  15448. "&": "&amp;",
  15449. "<": "&lt;",
  15450. ">": "&gt;",
  15451. '"': '&quot;',
  15452. "'": '&#39;',
  15453. "/": '&#x2F;'
  15454. };
  15455. function _escape(data) {
  15456. if (typeof data === 'string') {
  15457. return data.replace(/[&<>"'\/]/g, function (s) {
  15458. return _entityMap[s];
  15459. });
  15460. }else{
  15461. return data;
  15462. }
  15463. }
  15464. function _ajax(options) {
  15465. // v0.5.0 of https://github.com/goloroden/http.js
  15466. var getXhr = function (callback) {
  15467. // Use the native XHR object if the browser supports it.
  15468. if (window.XMLHttpRequest) {
  15469. return callback(null, new XMLHttpRequest());
  15470. } else if (window.ActiveXObject) {
  15471. // In Internet Explorer check for ActiveX versions of the XHR object.
  15472. try {
  15473. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  15474. } catch (e) {
  15475. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  15476. }
  15477. }
  15478. // If no XHR support was found, throw an error.
  15479. return callback(new Error());
  15480. };
  15481. var encodeUsingUrlEncoding = function (data) {
  15482. if(typeof data === 'string') {
  15483. return data;
  15484. }
  15485. var result = [];
  15486. for(var dataItem in data) {
  15487. if(data.hasOwnProperty(dataItem)) {
  15488. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  15489. }
  15490. }
  15491. return result.join('&');
  15492. };
  15493. var utf8 = function (text) {
  15494. text = text.replace(/\r\n/g, '\n');
  15495. var result = '';
  15496. for(var i = 0; i < text.length; i++) {
  15497. var c = text.charCodeAt(i);
  15498. if(c < 128) {
  15499. result += String.fromCharCode(c);
  15500. } else if((c > 127) && (c < 2048)) {
  15501. result += String.fromCharCode((c >> 6) | 192);
  15502. result += String.fromCharCode((c & 63) | 128);
  15503. } else {
  15504. result += String.fromCharCode((c >> 12) | 224);
  15505. result += String.fromCharCode(((c >> 6) & 63) | 128);
  15506. result += String.fromCharCode((c & 63) | 128);
  15507. }
  15508. }
  15509. return result;
  15510. };
  15511. var base64 = function (text) {
  15512. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15513. text = utf8(text);
  15514. var result = '',
  15515. chr1, chr2, chr3,
  15516. enc1, enc2, enc3, enc4,
  15517. i = 0;
  15518. do {
  15519. chr1 = text.charCodeAt(i++);
  15520. chr2 = text.charCodeAt(i++);
  15521. chr3 = text.charCodeAt(i++);
  15522. enc1 = chr1 >> 2;
  15523. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  15524. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  15525. enc4 = chr3 & 63;
  15526. if(isNaN(chr2)) {
  15527. enc3 = enc4 = 64;
  15528. } else if(isNaN(chr3)) {
  15529. enc4 = 64;
  15530. }
  15531. result +=
  15532. keyStr.charAt(enc1) +
  15533. keyStr.charAt(enc2) +
  15534. keyStr.charAt(enc3) +
  15535. keyStr.charAt(enc4);
  15536. chr1 = chr2 = chr3 = '';
  15537. enc1 = enc2 = enc3 = enc4 = '';
  15538. } while(i < text.length);
  15539. return result;
  15540. };
  15541. var mergeHeaders = function () {
  15542. // Use the first header object as base.
  15543. var result = arguments[0];
  15544. // Iterate through the remaining header objects and add them.
  15545. for(var i = 1; i < arguments.length; i++) {
  15546. var currentHeaders = arguments[i];
  15547. for(var header in currentHeaders) {
  15548. if(currentHeaders.hasOwnProperty(header)) {
  15549. result[header] = currentHeaders[header];
  15550. }
  15551. }
  15552. }
  15553. // Return the merged headers.
  15554. return result;
  15555. };
  15556. var ajax = function (method, url, options, callback) {
  15557. // Adjust parameters.
  15558. if(typeof options === 'function') {
  15559. callback = options;
  15560. options = {};
  15561. }
  15562. // Set default parameter values.
  15563. options.cache = options.cache || false;
  15564. options.data = options.data || {};
  15565. options.headers = options.headers || {};
  15566. options.jsonp = options.jsonp || false;
  15567. options.async = options.async === undefined ? true : options.async;
  15568. // Merge the various header objects.
  15569. var headers = mergeHeaders({
  15570. 'accept': '*/*',
  15571. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  15572. }, ajax.headers, options.headers);
  15573. // Encode the data according to the content-type.
  15574. var payload;
  15575. if (headers['content-type'] === 'application/json') {
  15576. payload = JSON.stringify(options.data);
  15577. } else {
  15578. payload = encodeUsingUrlEncoding(options.data);
  15579. }
  15580. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  15581. // if neccessary.
  15582. if(method === 'GET') {
  15583. // Setup the query string.
  15584. var queryString = [];
  15585. if(payload) {
  15586. queryString.push(payload);
  15587. payload = null;
  15588. }
  15589. // Handle caching.
  15590. if(!options.cache) {
  15591. queryString.push('_=' + (new Date()).getTime());
  15592. }
  15593. // If neccessary prepare the query string for a JSONP call.
  15594. if(options.jsonp) {
  15595. queryString.push('callback=' + options.jsonp);
  15596. queryString.push('jsonp=' + options.jsonp);
  15597. }
  15598. // Merge the query string and attach it to the url.
  15599. queryString = queryString.join('&');
  15600. if (queryString.length > 1) {
  15601. if (url.indexOf('?') > -1) {
  15602. url += '&' + queryString;
  15603. } else {
  15604. url += '?' + queryString;
  15605. }
  15606. }
  15607. // Make a JSONP call if neccessary.
  15608. if(options.jsonp) {
  15609. var head = document.getElementsByTagName('head')[0];
  15610. var script = document.createElement('script');
  15611. script.type = 'text/javascript';
  15612. script.src = url;
  15613. head.appendChild(script);
  15614. return;
  15615. }
  15616. }
  15617. // Since we got here, it is no JSONP request, so make a normal XHR request.
  15618. getXhr(function (err, xhr) {
  15619. if(err) return callback(err);
  15620. // Open the request.
  15621. xhr.open(method, url, options.async);
  15622. // Set the request headers.
  15623. for(var header in headers) {
  15624. if(headers.hasOwnProperty(header)) {
  15625. xhr.setRequestHeader(header, headers[header]);
  15626. }
  15627. }
  15628. // Handle the request events.
  15629. xhr.onreadystatechange = function () {
  15630. if(xhr.readyState === 4) {
  15631. var data = xhr.responseText || '';
  15632. // If no callback is given, return.
  15633. if(!callback) {
  15634. return;
  15635. }
  15636. // Return an object that provides access to the data as text and JSON.
  15637. callback(xhr.status, {
  15638. text: function () {
  15639. return data;
  15640. },
  15641. json: function () {
  15642. try {
  15643. return JSON.parse(data)
  15644. } catch (e) {
  15645. f.error('Can not parse JSON. URL: ' + url);
  15646. return {};
  15647. }
  15648. }
  15649. });
  15650. }
  15651. };
  15652. // Actually send the XHR request.
  15653. xhr.send(payload);
  15654. });
  15655. };
  15656. // Define the external interface.
  15657. var http = {
  15658. authBasic: function (username, password) {
  15659. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  15660. },
  15661. connect: function (url, options, callback) {
  15662. return ajax('CONNECT', url, options, callback);
  15663. },
  15664. del: function (url, options, callback) {
  15665. return ajax('DELETE', url, options, callback);
  15666. },
  15667. get: function (url, options, callback) {
  15668. return ajax('GET', url, options, callback);
  15669. },
  15670. head: function (url, options, callback) {
  15671. return ajax('HEAD', url, options, callback);
  15672. },
  15673. headers: function (headers) {
  15674. ajax.headers = headers || {};
  15675. },
  15676. isAllowed: function (url, verb, callback) {
  15677. this.options(url, function (status, data) {
  15678. callback(data.text().indexOf(verb) !== -1);
  15679. });
  15680. },
  15681. options: function (url, options, callback) {
  15682. return ajax('OPTIONS', url, options, callback);
  15683. },
  15684. patch: function (url, options, callback) {
  15685. return ajax('PATCH', url, options, callback);
  15686. },
  15687. post: function (url, options, callback) {
  15688. return ajax('POST', url, options, callback);
  15689. },
  15690. put: function (url, options, callback) {
  15691. return ajax('PUT', url, options, callback);
  15692. },
  15693. trace: function (url, options, callback) {
  15694. return ajax('TRACE', url, options, callback);
  15695. }
  15696. };
  15697. var methode = options.type ? options.type.toLowerCase() : 'get';
  15698. http[methode](options.url, options, function (status, data) {
  15699. // file: protocol always gives status code 0, so check for data
  15700. if (status === 200 || (status === 0 && data.text())) {
  15701. options.success(data.json(), status, null);
  15702. } else {
  15703. options.error(data.text(), status, null);
  15704. }
  15705. });
  15706. }
  15707. var _cookie = {
  15708. create: function(name,value,minutes,domain) {
  15709. var expires;
  15710. if (minutes) {
  15711. var date = new Date();
  15712. date.setTime(date.getTime()+(minutes*60*1000));
  15713. expires = "; expires="+date.toGMTString();
  15714. }
  15715. else expires = "";
  15716. domain = (domain)? "domain="+domain+";" : "";
  15717. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  15718. },
  15719. read: function(name) {
  15720. var nameEQ = name + "=";
  15721. var ca = document.cookie.split(';');
  15722. for(var i=0;i < ca.length;i++) {
  15723. var c = ca[i];
  15724. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  15725. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  15726. }
  15727. return null;
  15728. },
  15729. remove: function(name) {
  15730. this.create(name,"",-1);
  15731. }
  15732. };
  15733. var cookie_noop = {
  15734. create: function(name,value,minutes,domain) {},
  15735. read: function(name) { return null; },
  15736. remove: function(name) {}
  15737. };
  15738. // move dependent functions to a container so that
  15739. // they can be overriden easier in no jquery environment (node.js)
  15740. var f = {
  15741. extend: $ ? $.extend : _extend,
  15742. deepExtend: _deepExtend,
  15743. each: $ ? $.each : _each,
  15744. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  15745. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  15746. detectLanguage: detectLanguage,
  15747. escape: _escape,
  15748. log: function(str) {
  15749. if (o.debug && typeof console !== "undefined") console.log(str);
  15750. },
  15751. error: function(str) {
  15752. if (typeof console !== "undefined") console.error(str);
  15753. },
  15754. getCountyIndexOfLng: function(lng) {
  15755. var lng_index = 0;
  15756. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  15757. return lng_index;
  15758. },
  15759. toLanguages: function(lng) {
  15760. var log = this.log;
  15761. function applyCase(l) {
  15762. var ret = l;
  15763. if (typeof l === 'string' && l.indexOf('-') > -1) {
  15764. var parts = l.split('-');
  15765. ret = o.lowerCaseLng ?
  15766. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  15767. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  15768. } else {
  15769. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  15770. }
  15771. return ret;
  15772. }
  15773. var languages = [];
  15774. var whitelist = o.lngWhitelist || false;
  15775. var addLanguage = function(language){
  15776. //reject langs not whitelisted
  15777. if(!whitelist || whitelist.indexOf(language) > -1){
  15778. languages.push(language);
  15779. }else{
  15780. log('rejecting non-whitelisted language: ' + language);
  15781. }
  15782. };
  15783. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  15784. var parts = lng.split('-');
  15785. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  15786. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  15787. } else {
  15788. addLanguage(applyCase(lng));
  15789. }
  15790. for (var i = 0; i < o.fallbackLng.length; i++) {
  15791. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  15792. }
  15793. return languages;
  15794. },
  15795. regexEscape: function(str) {
  15796. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  15797. },
  15798. regexReplacementEscape: function(strOrFn) {
  15799. if (typeof strOrFn === 'string') {
  15800. return strOrFn.replace(/\$/g, "$$$$");
  15801. } else {
  15802. return strOrFn;
  15803. }
  15804. },
  15805. localStorage: {
  15806. setItem: function(key, value) {
  15807. if (window.localStorage) {
  15808. try {
  15809. window.localStorage.setItem(key, value);
  15810. } catch (e) {
  15811. f.log('failed to set value for key "' + key + '" to localStorage.');
  15812. }
  15813. }
  15814. }
  15815. }
  15816. };
  15817. function init(options, cb) {
  15818. if (typeof options === 'function') {
  15819. cb = options;
  15820. options = {};
  15821. }
  15822. options = options || {};
  15823. // override defaults with passed in options
  15824. f.extend(o, options);
  15825. delete o.fixLng; /* passed in each time */
  15826. // override functions: .log(), .detectLanguage(), etc
  15827. if (o.functions) {
  15828. delete o.functions;
  15829. f.extend(f, options.functions);
  15830. }
  15831. // create namespace object if namespace is passed in as string
  15832. if (typeof o.ns == 'string') {
  15833. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  15834. }
  15835. // fallback namespaces
  15836. if (typeof o.fallbackNS == 'string') {
  15837. o.fallbackNS = [o.fallbackNS];
  15838. }
  15839. // fallback languages
  15840. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  15841. o.fallbackLng = [o.fallbackLng];
  15842. }
  15843. // escape prefix/suffix
  15844. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  15845. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  15846. if (!o.lng) o.lng = f.detectLanguage();
  15847. languages = f.toLanguages(o.lng);
  15848. currentLng = languages[0];
  15849. f.log('currentLng set to: ' + currentLng);
  15850. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  15851. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  15852. }
  15853. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  15854. f.localStorage.setItem('i18next_lng', currentLng);
  15855. }
  15856. var lngTranslate = translate;
  15857. if (options.fixLng) {
  15858. lngTranslate = function(key, options) {
  15859. options = options || {};
  15860. options.lng = options.lng || lngTranslate.lng;
  15861. return translate(key, options);
  15862. };
  15863. lngTranslate.lng = currentLng;
  15864. }
  15865. pluralExtensions.setCurrentLng(currentLng);
  15866. // add JQuery extensions
  15867. if ($ && o.setJqueryExt) addJqueryFunct();
  15868. // jQuery deferred
  15869. var deferred;
  15870. if ($ && $.Deferred) {
  15871. deferred = $.Deferred();
  15872. }
  15873. // return immidiatly if res are passed in
  15874. if (o.resStore) {
  15875. resStore = o.resStore;
  15876. initialized = true;
  15877. if (cb) cb(lngTranslate);
  15878. if (deferred) deferred.resolve(lngTranslate);
  15879. if (deferred) return deferred.promise();
  15880. return;
  15881. }
  15882. // languages to load
  15883. var lngsToLoad = f.toLanguages(o.lng);
  15884. if (typeof o.preload === 'string') o.preload = [o.preload];
  15885. for (var i = 0, l = o.preload.length; i < l; i++) {
  15886. var pres = f.toLanguages(o.preload[i]);
  15887. for (var y = 0, len = pres.length; y < len; y++) {
  15888. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15889. lngsToLoad.push(pres[y]);
  15890. }
  15891. }
  15892. }
  15893. // else load them
  15894. i18n.sync.load(lngsToLoad, o, function(err, store) {
  15895. resStore = store;
  15896. initialized = true;
  15897. if (cb) cb(lngTranslate);
  15898. if (deferred) deferred.resolve(lngTranslate);
  15899. });
  15900. if (deferred) return deferred.promise();
  15901. }
  15902. function preload(lngs, cb) {
  15903. if (typeof lngs === 'string') lngs = [lngs];
  15904. for (var i = 0, l = lngs.length; i < l; i++) {
  15905. if (o.preload.indexOf(lngs[i]) < 0) {
  15906. o.preload.push(lngs[i]);
  15907. }
  15908. }
  15909. return init(cb);
  15910. }
  15911. function addResourceBundle(lng, ns, resources, deep) {
  15912. if (typeof ns !== 'string') {
  15913. resources = ns;
  15914. ns = o.ns.defaultNs;
  15915. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15916. o.ns.namespaces.push(ns);
  15917. }
  15918. resStore[lng] = resStore[lng] || {};
  15919. resStore[lng][ns] = resStore[lng][ns] || {};
  15920. if (deep) {
  15921. f.deepExtend(resStore[lng][ns], resources);
  15922. } else {
  15923. f.extend(resStore[lng][ns], resources);
  15924. }
  15925. }
  15926. function hasResourceBundle(lng, ns) {
  15927. if (typeof ns !== 'string') {
  15928. ns = o.ns.defaultNs;
  15929. }
  15930. resStore[lng] = resStore[lng] || {};
  15931. var res = resStore[lng][ns] || {};
  15932. var hasValues = false;
  15933. for(var prop in res) {
  15934. if (res.hasOwnProperty(prop)) {
  15935. hasValues = true;
  15936. }
  15937. }
  15938. return hasValues;
  15939. }
  15940. function removeResourceBundle(lng, ns) {
  15941. if (typeof ns !== 'string') {
  15942. ns = o.ns.defaultNs;
  15943. }
  15944. resStore[lng] = resStore[lng] || {};
  15945. resStore[lng][ns] = {};
  15946. }
  15947. function addResource(lng, ns, key, value) {
  15948. if (typeof ns !== 'string') {
  15949. resource = ns;
  15950. ns = o.ns.defaultNs;
  15951. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15952. o.ns.namespaces.push(ns);
  15953. }
  15954. resStore[lng] = resStore[lng] || {};
  15955. resStore[lng][ns] = resStore[lng][ns] || {};
  15956. var keys = key.split(o.keyseparator);
  15957. var x = 0;
  15958. var node = resStore[lng][ns];
  15959. var origRef = node;
  15960. while (keys[x]) {
  15961. if (x == keys.length - 1)
  15962. node[keys[x]] = value;
  15963. else {
  15964. if (node[keys[x]] == null)
  15965. node[keys[x]] = {};
  15966. node = node[keys[x]];
  15967. }
  15968. x++;
  15969. }
  15970. }
  15971. function addResources(lng, ns, resources) {
  15972. if (typeof ns !== 'string') {
  15973. resource = ns;
  15974. ns = o.ns.defaultNs;
  15975. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15976. o.ns.namespaces.push(ns);
  15977. }
  15978. for (var m in resources) {
  15979. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  15980. }
  15981. }
  15982. function setDefaultNamespace(ns) {
  15983. o.ns.defaultNs = ns;
  15984. }
  15985. function loadNamespace(namespace, cb) {
  15986. loadNamespaces([namespace], cb);
  15987. }
  15988. function loadNamespaces(namespaces, cb) {
  15989. var opts = {
  15990. dynamicLoad: o.dynamicLoad,
  15991. resGetPath: o.resGetPath,
  15992. getAsync: o.getAsync,
  15993. customLoad: o.customLoad,
  15994. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  15995. };
  15996. // languages to load
  15997. var lngsToLoad = f.toLanguages(o.lng);
  15998. if (typeof o.preload === 'string') o.preload = [o.preload];
  15999. for (var i = 0, l = o.preload.length; i < l; i++) {
  16000. var pres = f.toLanguages(o.preload[i]);
  16001. for (var y = 0, len = pres.length; y < len; y++) {
  16002. if (lngsToLoad.indexOf(pres[y]) < 0) {
  16003. lngsToLoad.push(pres[y]);
  16004. }
  16005. }
  16006. }
  16007. // check if we have to load
  16008. var lngNeedLoad = [];
  16009. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  16010. var needLoad = false;
  16011. var resSet = resStore[lngsToLoad[a]];
  16012. if (resSet) {
  16013. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  16014. if (!resSet[namespaces[b]]) needLoad = true;
  16015. }
  16016. } else {
  16017. needLoad = true;
  16018. }
  16019. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  16020. }
  16021. if (lngNeedLoad.length) {
  16022. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  16023. var todo = namespaces.length * lngNeedLoad.length;
  16024. // load each file individual
  16025. f.each(namespaces, function(nsIndex, nsValue) {
  16026. // append namespace to namespace array
  16027. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  16028. o.ns.namespaces.push(nsValue);
  16029. }
  16030. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  16031. resStore[lngValue] = resStore[lngValue] || {};
  16032. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  16033. todo--; // wait for all done befor callback
  16034. if (todo === 0 && cb) {
  16035. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  16036. cb();
  16037. }
  16038. });
  16039. });
  16040. });
  16041. } else {
  16042. if (cb) cb();
  16043. }
  16044. }
  16045. function setLng(lng, options, cb) {
  16046. if (typeof options === 'function') {
  16047. cb = options;
  16048. options = {};
  16049. } else if (!options) {
  16050. options = {};
  16051. }
  16052. options.lng = lng;
  16053. return init(options, cb);
  16054. }
  16055. function lng() {
  16056. return currentLng;
  16057. }
  16058. function reload(cb) {
  16059. resStore = {};
  16060. setLng(currentLng, cb);
  16061. }
  16062. function addJqueryFunct() {
  16063. // $.t shortcut
  16064. $.t = $.t || translate;
  16065. function parse(ele, key, options) {
  16066. if (key.length === 0) return;
  16067. var attr = 'text';
  16068. if (key.indexOf('[') === 0) {
  16069. var parts = key.split(']');
  16070. key = parts[1];
  16071. attr = parts[0].substr(1, parts[0].length-1);
  16072. }
  16073. if (key.indexOf(';') === key.length-1) {
  16074. key = key.substr(0, key.length-2);
  16075. }
  16076. var optionsToUse;
  16077. if (attr === 'html') {
  16078. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16079. ele.html($.t(key, optionsToUse));
  16080. } else if (attr === 'text') {
  16081. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  16082. ele.text($.t(key, optionsToUse));
  16083. } else if (attr === 'prepend') {
  16084. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16085. ele.prepend($.t(key, optionsToUse));
  16086. } else if (attr === 'append') {
  16087. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16088. ele.append($.t(key, optionsToUse));
  16089. } else if (attr.indexOf("data-") === 0) {
  16090. var dataAttr = attr.substr(("data-").length);
  16091. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  16092. var translated = $.t(key, optionsToUse);
  16093. //we change into the data cache
  16094. ele.data(dataAttr, translated);
  16095. //we change into the dom
  16096. ele.attr(attr, translated);
  16097. } else {
  16098. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  16099. ele.attr(attr, $.t(key, optionsToUse));
  16100. }
  16101. }
  16102. function localize(ele, options) {
  16103. var key = ele.attr(o.selectorAttr);
  16104. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  16105. if (!key) return;
  16106. var target = ele
  16107. , targetSelector = ele.data("i18n-target");
  16108. if (targetSelector) {
  16109. target = ele.find(targetSelector) || ele;
  16110. }
  16111. if (!options && o.useDataAttrOptions === true) {
  16112. options = ele.data("i18n-options");
  16113. }
  16114. options = options || {};
  16115. if (key.indexOf(';') >= 0) {
  16116. var keys = key.split(';');
  16117. $.each(keys, function(m, k) {
  16118. if (k !== '') parse(target, k, options);
  16119. });
  16120. } else {
  16121. parse(target, key, options);
  16122. }
  16123. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  16124. }
  16125. // fn
  16126. $.fn.i18n = function (options) {
  16127. return this.each(function() {
  16128. // localize element itself
  16129. localize($(this), options);
  16130. // localize childs
  16131. var elements = $(this).find('[' + o.selectorAttr + ']');
  16132. elements.each(function() {
  16133. localize($(this), options);
  16134. });
  16135. });
  16136. };
  16137. }
  16138. function applyReplacement(str, replacementHash, nestedKey, options) {
  16139. if (!str) return str;
  16140. options = options || replacementHash; // first call uses replacement hash combined with options
  16141. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  16142. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  16143. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  16144. , unEscapingSuffix = 'HTML'+suffix;
  16145. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  16146. f.each(hash, function(key, value) {
  16147. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  16148. if (typeof value === 'object' && value !== null) {
  16149. str = applyReplacement(str, value, nextKey, options);
  16150. } else {
  16151. if (options.escapeInterpolation || o.escapeInterpolation) {
  16152. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  16153. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  16154. } else {
  16155. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  16156. }
  16157. // str = options.escapeInterpolation;
  16158. }
  16159. });
  16160. return str;
  16161. }
  16162. // append it to functions
  16163. f.applyReplacement = applyReplacement;
  16164. function applyReuse(translated, options) {
  16165. var comma = ',';
  16166. var options_open = '{';
  16167. var options_close = '}';
  16168. var opts = f.extend({}, options);
  16169. delete opts.postProcess;
  16170. while (translated.indexOf(o.reusePrefix) != -1) {
  16171. replacementCounter++;
  16172. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  16173. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  16174. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  16175. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  16176. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  16177. if (index_of_end_of_closing <= index_of_opening) {
  16178. f.error('there is an missing closing in following translation value', translated);
  16179. return '';
  16180. }
  16181. if (token_without_symbols.indexOf(comma) != -1) {
  16182. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  16183. 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) {
  16184. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  16185. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  16186. try {
  16187. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  16188. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  16189. } catch (e) {
  16190. }
  16191. }
  16192. }
  16193. var translated_token = _translate(token_without_symbols, opts);
  16194. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  16195. }
  16196. return translated;
  16197. }
  16198. function hasContext(options) {
  16199. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  16200. }
  16201. function needsPlural(options, lng) {
  16202. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  16203. }
  16204. function needsIndefiniteArticle(options) {
  16205. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  16206. }
  16207. function exists(key, options) {
  16208. options = options || {};
  16209. var notFound = _getDefaultValue(key, options)
  16210. , found = _find(key, options);
  16211. return found !== undefined || found === notFound;
  16212. }
  16213. function translate(key, options) {
  16214. options = options || {};
  16215. if (!initialized) {
  16216. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  16217. return options.defaultValue || '';
  16218. };
  16219. replacementCounter = 0;
  16220. return _translate.apply(null, arguments);
  16221. }
  16222. function _getDefaultValue(key, options) {
  16223. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  16224. }
  16225. function _injectSprintfProcessor() {
  16226. var values = [];
  16227. // mh: build array from second argument onwards
  16228. for (var i = 1; i < arguments.length; i++) {
  16229. values.push(arguments[i]);
  16230. }
  16231. return {
  16232. postProcess: 'sprintf',
  16233. sprintf: values
  16234. };
  16235. }
  16236. function _translate(potentialKeys, options) {
  16237. if (options && typeof options !== 'object') {
  16238. if (o.shortcutFunction === 'sprintf') {
  16239. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  16240. options = _injectSprintfProcessor.apply(null, arguments);
  16241. } else if (o.shortcutFunction === 'defaultValue') {
  16242. options = {
  16243. defaultValue: options
  16244. }
  16245. }
  16246. } else {
  16247. options = options || {};
  16248. }
  16249. if (typeof o.defaultVariables === 'object') {
  16250. options = f.extend({}, o.defaultVariables, options);
  16251. }
  16252. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  16253. if (typeof potentialKeys === 'string') {
  16254. potentialKeys = [potentialKeys];
  16255. }
  16256. var key = potentialKeys[0];
  16257. if (potentialKeys.length > 1) {
  16258. for (var i = 0; i < potentialKeys.length; i++) {
  16259. key = potentialKeys[i];
  16260. if (exists(key, options)) {
  16261. break;
  16262. }
  16263. }
  16264. }
  16265. var notFound = _getDefaultValue(key, options)
  16266. , found = _find(key, options)
  16267. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  16268. , ns = options.ns || o.ns.defaultNs
  16269. , parts;
  16270. // split ns and key
  16271. if (key.indexOf(o.nsseparator) > -1) {
  16272. parts = key.split(o.nsseparator);
  16273. ns = parts[0];
  16274. key = parts[1];
  16275. }
  16276. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  16277. if (options.lng) {
  16278. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  16279. } else {
  16280. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  16281. }
  16282. }
  16283. var postProcessor = options.postProcess || o.postProcess;
  16284. if (found !== undefined && postProcessor) {
  16285. if (postProcessors[postProcessor]) {
  16286. found = postProcessors[postProcessor](found, key, options);
  16287. }
  16288. }
  16289. // process notFound if function exists
  16290. var splitNotFound = notFound;
  16291. if (notFound.indexOf(o.nsseparator) > -1) {
  16292. parts = notFound.split(o.nsseparator);
  16293. splitNotFound = parts[1];
  16294. }
  16295. if (splitNotFound === key && o.parseMissingKey) {
  16296. notFound = o.parseMissingKey(notFound);
  16297. }
  16298. if (found === undefined) {
  16299. notFound = applyReplacement(notFound, options);
  16300. notFound = applyReuse(notFound, options);
  16301. if (postProcessor && postProcessors[postProcessor]) {
  16302. var val = _getDefaultValue(key, options);
  16303. found = postProcessors[postProcessor](val, key, options);
  16304. }
  16305. }
  16306. return (found !== undefined) ? found : notFound;
  16307. }
  16308. function _find(key, options) {
  16309. options = options || {};
  16310. var optionWithoutCount, translated
  16311. , notFound = _getDefaultValue(key, options)
  16312. , lngs = languages;
  16313. if (!resStore) { return notFound; } // no resStore to translate from
  16314. // CI mode
  16315. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  16316. // passed in lng
  16317. if (options.lngs) lngs = options.lngs;
  16318. if (options.lng) {
  16319. lngs = f.toLanguages(options.lng, options.fallbackLng);
  16320. if (!resStore[lngs[0]]) {
  16321. var oldAsync = o.getAsync;
  16322. o.getAsync = false;
  16323. i18n.sync.load(lngs, o, function(err, store) {
  16324. f.extend(resStore, store);
  16325. o.getAsync = oldAsync;
  16326. });
  16327. }
  16328. }
  16329. var ns = options.ns || o.ns.defaultNs;
  16330. if (key.indexOf(o.nsseparator) > -1) {
  16331. var parts = key.split(o.nsseparator);
  16332. ns = parts[0];
  16333. key = parts[1];
  16334. }
  16335. if (hasContext(options)) {
  16336. optionWithoutCount = f.extend({}, options);
  16337. delete optionWithoutCount.context;
  16338. optionWithoutCount.defaultValue = o.contextNotFound;
  16339. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  16340. translated = translate(contextKey, optionWithoutCount);
  16341. if (translated != o.contextNotFound) {
  16342. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  16343. } // else continue translation with original/nonContext key
  16344. }
  16345. if (needsPlural(options, lngs[0])) {
  16346. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  16347. delete optionWithoutCount.count;
  16348. delete optionWithoutCount.lng;
  16349. optionWithoutCount.defaultValue = o.pluralNotFound;
  16350. var pluralKey;
  16351. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  16352. pluralKey = ns + o.nsseparator + key;
  16353. } else {
  16354. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  16355. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  16356. if (pluralExtension >= 0) {
  16357. pluralKey = pluralKey + '_' + pluralExtension;
  16358. } else if (pluralExtension === 1) {
  16359. pluralKey = ns + o.nsseparator + key; // singular
  16360. }
  16361. }
  16362. translated = translate(pluralKey, optionWithoutCount);
  16363. if (translated != o.pluralNotFound) {
  16364. return applyReplacement(translated, {
  16365. count: options.count,
  16366. interpolationPrefix: options.interpolationPrefix,
  16367. interpolationSuffix: options.interpolationSuffix
  16368. }); // apply replacement for count only
  16369. } else if (lngs.length > 1) {
  16370. // remove failed lng
  16371. var clone = lngs.slice();
  16372. clone.shift();
  16373. options = f.extend(options, { lngs: clone });
  16374. delete options.lng;
  16375. // retry with fallbacks
  16376. translated = translate(ns + o.nsseparator + key, options);
  16377. if (translated != o.pluralNotFound) return translated;
  16378. } else {
  16379. return translated;
  16380. }
  16381. }
  16382. if (needsIndefiniteArticle(options)) {
  16383. var optionsWithoutIndef = f.extend({}, options);
  16384. delete optionsWithoutIndef.indefinite_article;
  16385. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  16386. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  16387. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  16388. translated = translate(indefiniteKey, optionsWithoutIndef);
  16389. if (translated != o.indefiniteNotFound) {
  16390. return translated;
  16391. }
  16392. }
  16393. var found;
  16394. var keys = key.split(o.keyseparator);
  16395. for (var i = 0, len = lngs.length; i < len; i++ ) {
  16396. if (found !== undefined) break;
  16397. var l = lngs[i];
  16398. var x = 0;
  16399. var value = resStore[l] && resStore[l][ns];
  16400. while (keys[x]) {
  16401. value = value && value[keys[x]];
  16402. x++;
  16403. }
  16404. if (value !== undefined) {
  16405. var valueType = Object.prototype.toString.apply(value);
  16406. if (typeof value === 'string') {
  16407. value = applyReplacement(value, options);
  16408. value = applyReuse(value, options);
  16409. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  16410. value = value.join('\n');
  16411. value = applyReplacement(value, options);
  16412. value = applyReuse(value, options);
  16413. } else if (value === null && o.fallbackOnNull === true) {
  16414. value = undefined;
  16415. } else if (value !== null) {
  16416. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  16417. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  16418. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  16419. } else {
  16420. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  16421. 'returned an object instead of string.';
  16422. f.log(value);
  16423. }
  16424. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  16425. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  16426. f.each(value, function(m) {
  16427. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  16428. });
  16429. value = copy;
  16430. }
  16431. }
  16432. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  16433. value = undefined;
  16434. found = value;
  16435. }
  16436. }
  16437. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  16438. // set flag for fallback lookup - avoid recursion
  16439. options.isFallbackLookup = true;
  16440. if (o.fallbackNS.length) {
  16441. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  16442. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  16443. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  16444. /* compare value without namespace */
  16445. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  16446. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  16447. if (foundValue !== notFoundValue) break;
  16448. }
  16449. }
  16450. } else {
  16451. found = _find(key, options); // fallback to default NS
  16452. }
  16453. options.isFallbackLookup = false;
  16454. }
  16455. return found;
  16456. }
  16457. function detectLanguage() {
  16458. var detectedLng;
  16459. var whitelist = o.lngWhitelist || [];
  16460. var userLngChoices = [];
  16461. // get from qs
  16462. var qsParm = [];
  16463. if (typeof window !== 'undefined') {
  16464. (function() {
  16465. var query = window.location.search.substring(1);
  16466. var params = query.split('&');
  16467. for (var i=0; i<params.length; i++) {
  16468. var pos = params[i].indexOf('=');
  16469. if (pos > 0) {
  16470. var key = params[i].substring(0,pos);
  16471. if (key == o.detectLngQS) {
  16472. userLngChoices.push(params[i].substring(pos+1));
  16473. }
  16474. }
  16475. }
  16476. })();
  16477. }
  16478. // get from cookie
  16479. if (o.useCookie && typeof document !== 'undefined') {
  16480. var c = f.cookie.read(o.cookieName);
  16481. if (c) userLngChoices.push(c);
  16482. }
  16483. // get from localStorage
  16484. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  16485. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  16486. }
  16487. // get from navigator
  16488. if (typeof navigator !== 'undefined') {
  16489. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  16490. for (var i=0;i<navigator.languages.length;i++) {
  16491. userLngChoices.push(navigator.languages[i]);
  16492. }
  16493. }
  16494. if (navigator.userLanguage) {
  16495. userLngChoices.push(navigator.userLanguage);
  16496. }
  16497. if (navigator.language) {
  16498. userLngChoices.push(navigator.language);
  16499. }
  16500. }
  16501. (function() {
  16502. for (var i=0;i<userLngChoices.length;i++) {
  16503. var lng = userLngChoices[i];
  16504. if (lng.indexOf('-') > -1) {
  16505. var parts = lng.split('-');
  16506. lng = o.lowerCaseLng ?
  16507. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  16508. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  16509. }
  16510. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  16511. detectedLng = lng;
  16512. break;
  16513. }
  16514. }
  16515. })();
  16516. //fallback
  16517. if (!detectedLng){
  16518. detectedLng = o.fallbackLng[0];
  16519. }
  16520. return detectedLng;
  16521. }
  16522. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  16523. /* [code, name, numbers, pluralsType] */
  16524. var _rules = [
  16525. ["ach", "Acholi", [1,2], 1],
  16526. ["af", "Afrikaans",[1,2], 2],
  16527. ["ak", "Akan", [1,2], 1],
  16528. ["am", "Amharic", [1,2], 1],
  16529. ["an", "Aragonese",[1,2], 2],
  16530. ["ar", "Arabic", [0,1,2,3,11,100],5],
  16531. ["arn", "Mapudungun",[1,2], 1],
  16532. ["ast", "Asturian", [1,2], 2],
  16533. ["ay", "Aymará", [1], 3],
  16534. ["az", "Azerbaijani",[1,2],2],
  16535. ["be", "Belarusian",[1,2,5],4],
  16536. ["bg", "Bulgarian",[1,2], 2],
  16537. ["bn", "Bengali", [1,2], 2],
  16538. ["bo", "Tibetan", [1], 3],
  16539. ["br", "Breton", [1,2], 1],
  16540. ["bs", "Bosnian", [1,2,5],4],
  16541. ["ca", "Catalan", [1,2], 2],
  16542. ["cgg", "Chiga", [1], 3],
  16543. ["cs", "Czech", [1,2,5],6],
  16544. ["csb", "Kashubian",[1,2,5],7],
  16545. ["cy", "Welsh", [1,2,3,8],8],
  16546. ["da", "Danish", [1,2], 2],
  16547. ["de", "German", [1,2], 2],
  16548. ["dev", "Development Fallback", [1,2], 2],
  16549. ["dz", "Dzongkha", [1], 3],
  16550. ["el", "Greek", [1,2], 2],
  16551. ["en", "English", [1,2], 2],
  16552. ["eo", "Esperanto",[1,2], 2],
  16553. ["es", "Spanish", [1,2], 2],
  16554. ["es_ar","Argentinean Spanish", [1,2], 2],
  16555. ["et", "Estonian", [1,2], 2],
  16556. ["eu", "Basque", [1,2], 2],
  16557. ["fa", "Persian", [1], 3],
  16558. ["fi", "Finnish", [1,2], 2],
  16559. ["fil", "Filipino", [1,2], 1],
  16560. ["fo", "Faroese", [1,2], 2],
  16561. ["fr", "French", [1,2], 9],
  16562. ["fur", "Friulian", [1,2], 2],
  16563. ["fy", "Frisian", [1,2], 2],
  16564. ["ga", "Irish", [1,2,3,7,11],10],
  16565. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  16566. ["gl", "Galician", [1,2], 2],
  16567. ["gu", "Gujarati", [1,2], 2],
  16568. ["gun", "Gun", [1,2], 1],
  16569. ["ha", "Hausa", [1,2], 2],
  16570. ["he", "Hebrew", [1,2], 2],
  16571. ["hi", "Hindi", [1,2], 2],
  16572. ["hr", "Croatian", [1,2,5],4],
  16573. ["hu", "Hungarian",[1,2], 2],
  16574. ["hy", "Armenian", [1,2], 2],
  16575. ["ia", "Interlingua",[1,2],2],
  16576. ["id", "Indonesian",[1], 3],
  16577. ["is", "Icelandic",[1,2], 12],
  16578. ["it", "Italian", [1,2], 2],
  16579. ["ja", "Japanese", [1], 3],
  16580. ["jbo", "Lojban", [1], 3],
  16581. ["jv", "Javanese", [0,1], 13],
  16582. ["ka", "Georgian", [1], 3],
  16583. ["kk", "Kazakh", [1], 3],
  16584. ["km", "Khmer", [1], 3],
  16585. ["kn", "Kannada", [1,2], 2],
  16586. ["ko", "Korean", [1], 3],
  16587. ["ku", "Kurdish", [1,2], 2],
  16588. ["kw", "Cornish", [1,2,3,4],14],
  16589. ["ky", "Kyrgyz", [1], 3],
  16590. ["lb", "Letzeburgesch",[1,2],2],
  16591. ["ln", "Lingala", [1,2], 1],
  16592. ["lo", "Lao", [1], 3],
  16593. ["lt", "Lithuanian",[1,2,10],15],
  16594. ["lv", "Latvian", [1,2,0],16],
  16595. ["mai", "Maithili", [1,2], 2],
  16596. ["mfe", "Mauritian Creole",[1,2],1],
  16597. ["mg", "Malagasy", [1,2], 1],
  16598. ["mi", "Maori", [1,2], 1],
  16599. ["mk", "Macedonian",[1,2],17],
  16600. ["ml", "Malayalam",[1,2], 2],
  16601. ["mn", "Mongolian",[1,2], 2],
  16602. ["mnk", "Mandinka", [0,1,2],18],
  16603. ["mr", "Marathi", [1,2], 2],
  16604. ["ms", "Malay", [1], 3],
  16605. ["mt", "Maltese", [1,2,11,20],19],
  16606. ["nah", "Nahuatl", [1,2], 2],
  16607. ["nap", "Neapolitan",[1,2], 2],
  16608. ["nb", "Norwegian Bokmal",[1,2],2],
  16609. ["ne", "Nepali", [1,2], 2],
  16610. ["nl", "Dutch", [1,2], 2],
  16611. ["nn", "Norwegian Nynorsk",[1,2],2],
  16612. ["no", "Norwegian",[1,2], 2],
  16613. ["nso", "Northern Sotho",[1,2],2],
  16614. ["oc", "Occitan", [1,2], 1],
  16615. ["or", "Oriya", [2,1], 2],
  16616. ["pa", "Punjabi", [1,2], 2],
  16617. ["pap", "Papiamento",[1,2], 2],
  16618. ["pl", "Polish", [1,2,5],7],
  16619. ["pms", "Piemontese",[1,2], 2],
  16620. ["ps", "Pashto", [1,2], 2],
  16621. ["pt", "Portuguese",[1,2], 2],
  16622. ["pt_br","Brazilian Portuguese",[1,2], 2],
  16623. ["rm", "Romansh", [1,2], 2],
  16624. ["ro", "Romanian", [1,2,20],20],
  16625. ["ru", "Russian", [1,2,5],4],
  16626. ["sah", "Yakut", [1], 3],
  16627. ["sco", "Scots", [1,2], 2],
  16628. ["se", "Northern Sami",[1,2], 2],
  16629. ["si", "Sinhala", [1,2], 2],
  16630. ["sk", "Slovak", [1,2,5],6],
  16631. ["sl", "Slovenian",[5,1,2,3],21],
  16632. ["so", "Somali", [1,2], 2],
  16633. ["son", "Songhay", [1,2], 2],
  16634. ["sq", "Albanian", [1,2], 2],
  16635. ["sr", "Serbian", [1,2,5],4],
  16636. ["su", "Sundanese",[1], 3],
  16637. ["sv", "Swedish", [1,2], 2],
  16638. ["sw", "Swahili", [1,2], 2],
  16639. ["ta", "Tamil", [1,2], 2],
  16640. ["te", "Telugu", [1,2], 2],
  16641. ["tg", "Tajik", [1,2], 1],
  16642. ["th", "Thai", [1], 3],
  16643. ["ti", "Tigrinya", [1,2], 1],
  16644. ["tk", "Turkmen", [1,2], 2],
  16645. ["tr", "Turkish", [1,2], 1],
  16646. ["tt", "Tatar", [1], 3],
  16647. ["ug", "Uyghur", [1], 3],
  16648. ["uk", "Ukrainian",[1,2,5],4],
  16649. ["ur", "Urdu", [1,2], 2],
  16650. ["uz", "Uzbek", [1,2], 1],
  16651. ["vi", "Vietnamese",[1], 3],
  16652. ["wa", "Walloon", [1,2], 1],
  16653. ["wo", "Wolof", [1], 3],
  16654. ["yo", "Yoruba", [1,2], 2],
  16655. ["zh", "Chinese", [1], 3]
  16656. ];
  16657. var _rulesPluralsTypes = {
  16658. 1: function(n) {return Number(n > 1);},
  16659. 2: function(n) {return Number(n != 1);},
  16660. 3: function(n) {return 0;},
  16661. 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);},
  16662. 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);},
  16663. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  16664. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16665. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  16666. 9: function(n) {return Number(n >= 2);},
  16667. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  16668. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  16669. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  16670. 13: function(n) {return Number(n !== 0);},
  16671. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  16672. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16673. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  16674. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  16675. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  16676. 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);},
  16677. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  16678. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  16679. };
  16680. var pluralExtensions = {
  16681. rules: (function () {
  16682. var l, rules = {};
  16683. for (l=_rules.length; l-- ;) {
  16684. rules[_rules[l][0]] = {
  16685. name: _rules[l][1],
  16686. numbers: _rules[l][2],
  16687. plurals: _rulesPluralsTypes[_rules[l][3]]
  16688. }
  16689. }
  16690. return rules;
  16691. }()),
  16692. // you can add your own pluralExtensions
  16693. addRule: function(lng, obj) {
  16694. pluralExtensions.rules[lng] = obj;
  16695. },
  16696. setCurrentLng: function(lng) {
  16697. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  16698. var parts = lng.split('-');
  16699. pluralExtensions.currentRule = {
  16700. lng: lng,
  16701. rule: pluralExtensions.rules[parts[0]]
  16702. };
  16703. }
  16704. },
  16705. needsPlural: function(lng, count) {
  16706. var parts = lng.split('-');
  16707. var ext;
  16708. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16709. ext = pluralExtensions.currentRule.rule;
  16710. } else {
  16711. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  16712. }
  16713. if (ext && ext.numbers.length <= 1) {
  16714. return false;
  16715. } else {
  16716. return this.get(lng, count) !== 1;
  16717. }
  16718. },
  16719. get: function(lng, count) {
  16720. var parts = lng.split('-');
  16721. function getResult(l, c) {
  16722. var ext;
  16723. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16724. ext = pluralExtensions.currentRule.rule;
  16725. } else {
  16726. ext = pluralExtensions.rules[l];
  16727. }
  16728. if (ext) {
  16729. var i;
  16730. if (ext.noAbs) {
  16731. i = ext.plurals(c);
  16732. } else {
  16733. i = ext.plurals(Math.abs(c));
  16734. }
  16735. var number = ext.numbers[i];
  16736. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  16737. if (number === 2) {
  16738. number = -1; // regular plural
  16739. } else if (number === 1) {
  16740. number = 1; // singular
  16741. }
  16742. }//console.log(count + '-' + number);
  16743. return number;
  16744. } else {
  16745. return c === 1 ? '1' : '-1';
  16746. }
  16747. }
  16748. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  16749. }
  16750. };
  16751. var postProcessors = {};
  16752. var addPostProcessor = function(name, fc) {
  16753. postProcessors[name] = fc;
  16754. };
  16755. // sprintf support
  16756. var sprintf = (function() {
  16757. function get_type(variable) {
  16758. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  16759. }
  16760. function str_repeat(input, multiplier) {
  16761. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  16762. return output.join('');
  16763. }
  16764. var str_format = function() {
  16765. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  16766. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  16767. }
  16768. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  16769. };
  16770. str_format.format = function(parse_tree, argv) {
  16771. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  16772. for (i = 0; i < tree_length; i++) {
  16773. node_type = get_type(parse_tree[i]);
  16774. if (node_type === 'string') {
  16775. output.push(parse_tree[i]);
  16776. }
  16777. else if (node_type === 'array') {
  16778. match = parse_tree[i]; // convenience purposes only
  16779. if (match[2]) { // keyword argument
  16780. arg = argv[cursor];
  16781. for (k = 0; k < match[2].length; k++) {
  16782. if (!arg.hasOwnProperty(match[2][k])) {
  16783. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  16784. }
  16785. arg = arg[match[2][k]];
  16786. }
  16787. }
  16788. else if (match[1]) { // positional argument (explicit)
  16789. arg = argv[match[1]];
  16790. }
  16791. else { // positional argument (implicit)
  16792. arg = argv[cursor++];
  16793. }
  16794. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  16795. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  16796. }
  16797. switch (match[8]) {
  16798. case 'b': arg = arg.toString(2); break;
  16799. case 'c': arg = String.fromCharCode(arg); break;
  16800. case 'd': arg = parseInt(arg, 10); break;
  16801. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  16802. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  16803. case 'o': arg = arg.toString(8); break;
  16804. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  16805. case 'u': arg = Math.abs(arg); break;
  16806. case 'x': arg = arg.toString(16); break;
  16807. case 'X': arg = arg.toString(16).toUpperCase(); break;
  16808. }
  16809. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  16810. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  16811. pad_length = match[6] - String(arg).length;
  16812. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  16813. output.push(match[5] ? arg + pad : pad + arg);
  16814. }
  16815. }
  16816. return output.join('');
  16817. };
  16818. str_format.cache = {};
  16819. str_format.parse = function(fmt) {
  16820. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  16821. while (_fmt) {
  16822. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  16823. parse_tree.push(match[0]);
  16824. }
  16825. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  16826. parse_tree.push('%');
  16827. }
  16828. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  16829. if (match[2]) {
  16830. arg_names |= 1;
  16831. var field_list = [], replacement_field = match[2], field_match = [];
  16832. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16833. field_list.push(field_match[1]);
  16834. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  16835. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16836. field_list.push(field_match[1]);
  16837. }
  16838. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  16839. field_list.push(field_match[1]);
  16840. }
  16841. else {
  16842. throw('[sprintf] huh?');
  16843. }
  16844. }
  16845. }
  16846. else {
  16847. throw('[sprintf] huh?');
  16848. }
  16849. match[2] = field_list;
  16850. }
  16851. else {
  16852. arg_names |= 2;
  16853. }
  16854. if (arg_names === 3) {
  16855. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  16856. }
  16857. parse_tree.push(match);
  16858. }
  16859. else {
  16860. throw('[sprintf] huh?');
  16861. }
  16862. _fmt = _fmt.substring(match[0].length);
  16863. }
  16864. return parse_tree;
  16865. };
  16866. return str_format;
  16867. })();
  16868. var vsprintf = function(fmt, argv) {
  16869. argv.unshift(fmt);
  16870. return sprintf.apply(null, argv);
  16871. };
  16872. addPostProcessor("sprintf", function(val, key, opts) {
  16873. if (!opts.sprintf) return val;
  16874. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  16875. return vsprintf(val, opts.sprintf);
  16876. } else if (typeof opts.sprintf === 'object') {
  16877. return sprintf(val, opts.sprintf);
  16878. }
  16879. return val;
  16880. });
  16881. // public api interface
  16882. i18n.init = init;
  16883. i18n.setLng = setLng;
  16884. i18n.preload = preload;
  16885. i18n.addResourceBundle = addResourceBundle;
  16886. i18n.hasResourceBundle = hasResourceBundle;
  16887. i18n.addResource = addResource;
  16888. i18n.addResources = addResources;
  16889. i18n.removeResourceBundle = removeResourceBundle;
  16890. i18n.loadNamespace = loadNamespace;
  16891. i18n.loadNamespaces = loadNamespaces;
  16892. i18n.setDefaultNamespace = setDefaultNamespace;
  16893. i18n.t = translate;
  16894. i18n.translate = translate;
  16895. i18n.exists = exists;
  16896. i18n.detectLanguage = f.detectLanguage;
  16897. i18n.pluralExtensions = pluralExtensions;
  16898. i18n.sync = sync;
  16899. i18n.functions = f;
  16900. i18n.lng = lng;
  16901. i18n.addPostProcessor = addPostProcessor;
  16902. i18n.options = o;
  16903. })();
  16904. },{"jquery":"jquery"}],63:[function(require,module,exports){
  16905. // Top level file is just a mixin of submodules & constants
  16906. 'use strict';
  16907. var assign = require('./lib/utils/common').assign;
  16908. var deflate = require('./lib/deflate');
  16909. var inflate = require('./lib/inflate');
  16910. var constants = require('./lib/zlib/constants');
  16911. var pako = {};
  16912. assign(pako, deflate, inflate, constants);
  16913. module.exports = pako;
  16914. },{"./lib/deflate":64,"./lib/inflate":65,"./lib/utils/common":66,"./lib/zlib/constants":69}],64:[function(require,module,exports){
  16915. 'use strict';
  16916. var zlib_deflate = require('./zlib/deflate.js');
  16917. var utils = require('./utils/common');
  16918. var strings = require('./utils/strings');
  16919. var msg = require('./zlib/messages');
  16920. var zstream = require('./zlib/zstream');
  16921. /* Public constants ==========================================================*/
  16922. /* ===========================================================================*/
  16923. var Z_NO_FLUSH = 0;
  16924. var Z_FINISH = 4;
  16925. var Z_OK = 0;
  16926. var Z_STREAM_END = 1;
  16927. var Z_DEFAULT_COMPRESSION = -1;
  16928. var Z_DEFAULT_STRATEGY = 0;
  16929. var Z_DEFLATED = 8;
  16930. /* ===========================================================================*/
  16931. /**
  16932. * class Deflate
  16933. *
  16934. * Generic JS-style wrapper for zlib calls. If you don't need
  16935. * streaming behaviour - use more simple functions: [[deflate]],
  16936. * [[deflateRaw]] and [[gzip]].
  16937. **/
  16938. /* internal
  16939. * Deflate.chunks -> Array
  16940. *
  16941. * Chunks of output data, if [[Deflate#onData]] not overriden.
  16942. **/
  16943. /**
  16944. * Deflate.result -> Uint8Array|Array
  16945. *
  16946. * Compressed result, generated by default [[Deflate#onData]]
  16947. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  16948. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  16949. **/
  16950. /**
  16951. * Deflate.err -> Number
  16952. *
  16953. * Error code after deflate finished. 0 (Z_OK) on success.
  16954. * You will not need it in real life, because deflate errors
  16955. * are possible only on wrong options or bad `onData` / `onEnd`
  16956. * custom handlers.
  16957. **/
  16958. /**
  16959. * Deflate.msg -> String
  16960. *
  16961. * Error message, if [[Deflate.err]] != 0
  16962. **/
  16963. /**
  16964. * new Deflate(options)
  16965. * - options (Object): zlib deflate options.
  16966. *
  16967. * Creates new deflator instance with specified params. Throws exception
  16968. * on bad params. Supported options:
  16969. *
  16970. * - `level`
  16971. * - `windowBits`
  16972. * - `memLevel`
  16973. * - `strategy`
  16974. *
  16975. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  16976. * for more information on these.
  16977. *
  16978. * Additional options, for internal needs:
  16979. *
  16980. * - `chunkSize` - size of generated data chunks (16K by default)
  16981. * - `raw` (Boolean) - do raw deflate
  16982. * - `gzip` (Boolean) - create gzip wrapper
  16983. * - `to` (String) - if equal to 'string', then result will be "binary string"
  16984. * (each char code [0..255])
  16985. * - `header` (Object) - custom header for gzip
  16986. * - `text` (Boolean) - true if compressed data believed to be text
  16987. * - `time` (Number) - modification time, unix timestamp
  16988. * - `os` (Number) - operation system code
  16989. * - `extra` (Array) - array of bytes with extra data (max 65536)
  16990. * - `name` (String) - file name (binary string)
  16991. * - `comment` (String) - comment (binary string)
  16992. * - `hcrc` (Boolean) - true if header crc should be added
  16993. *
  16994. * ##### Example:
  16995. *
  16996. * ```javascript
  16997. * var pako = require('pako')
  16998. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  16999. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17000. *
  17001. * var deflate = new pako.Deflate({ level: 3});
  17002. *
  17003. * deflate.push(chunk1, false);
  17004. * deflate.push(chunk2, true); // true -> last chunk
  17005. *
  17006. * if (deflate.err) { throw new Error(deflate.err); }
  17007. *
  17008. * console.log(deflate.result);
  17009. * ```
  17010. **/
  17011. var Deflate = function(options) {
  17012. this.options = utils.assign({
  17013. level: Z_DEFAULT_COMPRESSION,
  17014. method: Z_DEFLATED,
  17015. chunkSize: 16384,
  17016. windowBits: 15,
  17017. memLevel: 8,
  17018. strategy: Z_DEFAULT_STRATEGY,
  17019. to: ''
  17020. }, options || {});
  17021. var opt = this.options;
  17022. if (opt.raw && (opt.windowBits > 0)) {
  17023. opt.windowBits = -opt.windowBits;
  17024. }
  17025. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  17026. opt.windowBits += 16;
  17027. }
  17028. this.err = 0; // error code, if happens (0 = Z_OK)
  17029. this.msg = ''; // error message
  17030. this.ended = false; // used to avoid multiple onEnd() calls
  17031. this.chunks = []; // chunks of compressed data
  17032. this.strm = new zstream();
  17033. this.strm.avail_out = 0;
  17034. var status = zlib_deflate.deflateInit2(
  17035. this.strm,
  17036. opt.level,
  17037. opt.method,
  17038. opt.windowBits,
  17039. opt.memLevel,
  17040. opt.strategy
  17041. );
  17042. if (status !== Z_OK) {
  17043. throw new Error(msg[status]);
  17044. }
  17045. if (opt.header) {
  17046. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  17047. }
  17048. };
  17049. /**
  17050. * Deflate#push(data[, mode]) -> Boolean
  17051. * - data (Uint8Array|Array|String): input data. Strings will be converted to
  17052. * utf8 byte sequence.
  17053. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17054. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17055. *
  17056. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  17057. * new compressed chunks. Returns `true` on success. The last data block must have
  17058. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17059. * [[Deflate#onEnd]].
  17060. *
  17061. * On fail call [[Deflate#onEnd]] with error code and return false.
  17062. *
  17063. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17064. * array format is detected automatically). Also, don't skip last param and always
  17065. * use the same type in your code (boolean or number). That will improve JS speed.
  17066. *
  17067. * For regular `Array`-s make sure all elements are [0..255].
  17068. *
  17069. * ##### Example
  17070. *
  17071. * ```javascript
  17072. * push(chunk, false); // push one of data chunks
  17073. * ...
  17074. * push(chunk, true); // push last chunk
  17075. * ```
  17076. **/
  17077. Deflate.prototype.push = function(data, mode) {
  17078. var strm = this.strm;
  17079. var chunkSize = this.options.chunkSize;
  17080. var status, _mode;
  17081. if (this.ended) { return false; }
  17082. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  17083. // Convert data if needed
  17084. if (typeof data === 'string') {
  17085. // If we need to compress text, change encoding to utf8.
  17086. strm.input = strings.string2buf(data);
  17087. } else {
  17088. strm.input = data;
  17089. }
  17090. strm.next_in = 0;
  17091. strm.avail_in = strm.input.length;
  17092. do {
  17093. if (strm.avail_out === 0) {
  17094. strm.output = new utils.Buf8(chunkSize);
  17095. strm.next_out = 0;
  17096. strm.avail_out = chunkSize;
  17097. }
  17098. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  17099. if (status !== Z_STREAM_END && status !== Z_OK) {
  17100. this.onEnd(status);
  17101. this.ended = true;
  17102. return false;
  17103. }
  17104. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  17105. if (this.options.to === 'string') {
  17106. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  17107. } else {
  17108. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17109. }
  17110. }
  17111. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  17112. // Finalize on the last chunk.
  17113. if (_mode === Z_FINISH) {
  17114. status = zlib_deflate.deflateEnd(this.strm);
  17115. this.onEnd(status);
  17116. this.ended = true;
  17117. return status === Z_OK;
  17118. }
  17119. return true;
  17120. };
  17121. /**
  17122. * Deflate#onData(chunk) -> Void
  17123. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17124. * on js engine support. When string output requested, each chunk
  17125. * will be string.
  17126. *
  17127. * By default, stores data blocks in `chunks[]` property and glue
  17128. * those in `onEnd`. Override this handler, if you need another behaviour.
  17129. **/
  17130. Deflate.prototype.onData = function(chunk) {
  17131. this.chunks.push(chunk);
  17132. };
  17133. /**
  17134. * Deflate#onEnd(status) -> Void
  17135. * - status (Number): deflate status. 0 (Z_OK) on success,
  17136. * other if not.
  17137. *
  17138. * Called once after you tell deflate that input stream complete
  17139. * or error happenned. By default - join collected chunks,
  17140. * free memory and fill `results` / `err` properties.
  17141. **/
  17142. Deflate.prototype.onEnd = function(status) {
  17143. // On success - join
  17144. if (status === Z_OK) {
  17145. if (this.options.to === 'string') {
  17146. this.result = this.chunks.join('');
  17147. } else {
  17148. this.result = utils.flattenChunks(this.chunks);
  17149. }
  17150. }
  17151. this.chunks = [];
  17152. this.err = status;
  17153. this.msg = this.strm.msg;
  17154. };
  17155. /**
  17156. * deflate(data[, options]) -> Uint8Array|Array|String
  17157. * - data (Uint8Array|Array|String): input data to compress.
  17158. * - options (Object): zlib deflate options.
  17159. *
  17160. * Compress `data` with deflate alrorythm and `options`.
  17161. *
  17162. * Supported options are:
  17163. *
  17164. * - level
  17165. * - windowBits
  17166. * - memLevel
  17167. * - strategy
  17168. *
  17169. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17170. * for more information on these.
  17171. *
  17172. * Sugar (options):
  17173. *
  17174. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17175. * negative windowBits implicitly.
  17176. * - `to` (String) - if equal to 'string', then result will be "binary string"
  17177. * (each char code [0..255])
  17178. *
  17179. * ##### Example:
  17180. *
  17181. * ```javascript
  17182. * var pako = require('pako')
  17183. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  17184. *
  17185. * console.log(pako.deflate(data));
  17186. * ```
  17187. **/
  17188. function deflate(input, options) {
  17189. var deflator = new Deflate(options);
  17190. deflator.push(input, true);
  17191. // That will never happens, if you don't cheat with options :)
  17192. if (deflator.err) { throw deflator.msg; }
  17193. return deflator.result;
  17194. }
  17195. /**
  17196. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  17197. * - data (Uint8Array|Array|String): input data to compress.
  17198. * - options (Object): zlib deflate options.
  17199. *
  17200. * The same as [[deflate]], but creates raw data, without wrapper
  17201. * (header and adler32 crc).
  17202. **/
  17203. function deflateRaw(input, options) {
  17204. options = options || {};
  17205. options.raw = true;
  17206. return deflate(input, options);
  17207. }
  17208. /**
  17209. * gzip(data[, options]) -> Uint8Array|Array|String
  17210. * - data (Uint8Array|Array|String): input data to compress.
  17211. * - options (Object): zlib deflate options.
  17212. *
  17213. * The same as [[deflate]], but create gzip wrapper instead of
  17214. * deflate one.
  17215. **/
  17216. function gzip(input, options) {
  17217. options = options || {};
  17218. options.gzip = true;
  17219. return deflate(input, options);
  17220. }
  17221. exports.Deflate = Deflate;
  17222. exports.deflate = deflate;
  17223. exports.deflateRaw = deflateRaw;
  17224. exports.gzip = gzip;
  17225. },{"./utils/common":66,"./utils/strings":67,"./zlib/deflate.js":71,"./zlib/messages":76,"./zlib/zstream":78}],65:[function(require,module,exports){
  17226. 'use strict';
  17227. var zlib_inflate = require('./zlib/inflate.js');
  17228. var utils = require('./utils/common');
  17229. var strings = require('./utils/strings');
  17230. var c = require('./zlib/constants');
  17231. var msg = require('./zlib/messages');
  17232. var zstream = require('./zlib/zstream');
  17233. var gzheader = require('./zlib/gzheader');
  17234. /**
  17235. * class Inflate
  17236. *
  17237. * Generic JS-style wrapper for zlib calls. If you don't need
  17238. * streaming behaviour - use more simple functions: [[inflate]]
  17239. * and [[inflateRaw]].
  17240. **/
  17241. /* internal
  17242. * inflate.chunks -> Array
  17243. *
  17244. * Chunks of output data, if [[Inflate#onData]] not overriden.
  17245. **/
  17246. /**
  17247. * Inflate.result -> Uint8Array|Array|String
  17248. *
  17249. * Uncompressed result, generated by default [[Inflate#onData]]
  17250. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  17251. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  17252. **/
  17253. /**
  17254. * Inflate.err -> Number
  17255. *
  17256. * Error code after inflate finished. 0 (Z_OK) on success.
  17257. * Should be checked if broken data possible.
  17258. **/
  17259. /**
  17260. * Inflate.msg -> String
  17261. *
  17262. * Error message, if [[Inflate.err]] != 0
  17263. **/
  17264. /**
  17265. * new Inflate(options)
  17266. * - options (Object): zlib inflate options.
  17267. *
  17268. * Creates new inflator instance with specified params. Throws exception
  17269. * on bad params. Supported options:
  17270. *
  17271. * - `windowBits`
  17272. *
  17273. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17274. * for more information on these.
  17275. *
  17276. * Additional options, for internal needs:
  17277. *
  17278. * - `chunkSize` - size of generated data chunks (16K by default)
  17279. * - `raw` (Boolean) - do raw inflate
  17280. * - `to` (String) - if equal to 'string', then result will be converted
  17281. * from utf8 to utf16 (javascript) string. When string output requested,
  17282. * chunk length can differ from `chunkSize`, depending on content.
  17283. *
  17284. * By default, when no options set, autodetect deflate/gzip data format via
  17285. * wrapper header.
  17286. *
  17287. * ##### Example:
  17288. *
  17289. * ```javascript
  17290. * var pako = require('pako')
  17291. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17292. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17293. *
  17294. * var inflate = new pako.Inflate({ level: 3});
  17295. *
  17296. * inflate.push(chunk1, false);
  17297. * inflate.push(chunk2, true); // true -> last chunk
  17298. *
  17299. * if (inflate.err) { throw new Error(inflate.err); }
  17300. *
  17301. * console.log(inflate.result);
  17302. * ```
  17303. **/
  17304. var Inflate = function(options) {
  17305. this.options = utils.assign({
  17306. chunkSize: 16384,
  17307. windowBits: 0,
  17308. to: ''
  17309. }, options || {});
  17310. var opt = this.options;
  17311. // Force window size for `raw` data, if not set directly,
  17312. // because we have no header for autodetect.
  17313. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  17314. opt.windowBits = -opt.windowBits;
  17315. if (opt.windowBits === 0) { opt.windowBits = -15; }
  17316. }
  17317. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  17318. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  17319. !(options && options.windowBits)) {
  17320. opt.windowBits += 32;
  17321. }
  17322. // Gzip header has no info about windows size, we can do autodetect only
  17323. // for deflate. So, if window size not set, force it to max when gzip possible
  17324. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  17325. // bit 3 (16) -> gzipped data
  17326. // bit 4 (32) -> autodetect gzip/deflate
  17327. if ((opt.windowBits & 15) === 0) {
  17328. opt.windowBits |= 15;
  17329. }
  17330. }
  17331. this.err = 0; // error code, if happens (0 = Z_OK)
  17332. this.msg = ''; // error message
  17333. this.ended = false; // used to avoid multiple onEnd() calls
  17334. this.chunks = []; // chunks of compressed data
  17335. this.strm = new zstream();
  17336. this.strm.avail_out = 0;
  17337. var status = zlib_inflate.inflateInit2(
  17338. this.strm,
  17339. opt.windowBits
  17340. );
  17341. if (status !== c.Z_OK) {
  17342. throw new Error(msg[status]);
  17343. }
  17344. this.header = new gzheader();
  17345. zlib_inflate.inflateGetHeader(this.strm, this.header);
  17346. };
  17347. /**
  17348. * Inflate#push(data[, mode]) -> Boolean
  17349. * - data (Uint8Array|Array|String): input data
  17350. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17351. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17352. *
  17353. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  17354. * new output chunks. Returns `true` on success. The last data block must have
  17355. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17356. * [[Inflate#onEnd]].
  17357. *
  17358. * On fail call [[Inflate#onEnd]] with error code and return false.
  17359. *
  17360. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17361. * format is detected automatically). Also, don't skip last param and always
  17362. * use the same type in your code (boolean or number). That will improve JS speed.
  17363. *
  17364. * For regular `Array`-s make sure all elements are [0..255].
  17365. *
  17366. * ##### Example
  17367. *
  17368. * ```javascript
  17369. * push(chunk, false); // push one of data chunks
  17370. * ...
  17371. * push(chunk, true); // push last chunk
  17372. * ```
  17373. **/
  17374. Inflate.prototype.push = function(data, mode) {
  17375. var strm = this.strm;
  17376. var chunkSize = this.options.chunkSize;
  17377. var status, _mode;
  17378. var next_out_utf8, tail, utf8str;
  17379. if (this.ended) { return false; }
  17380. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  17381. // Convert data if needed
  17382. if (typeof data === 'string') {
  17383. // Only binary strings can be decompressed on practice
  17384. strm.input = strings.binstring2buf(data);
  17385. } else {
  17386. strm.input = data;
  17387. }
  17388. strm.next_in = 0;
  17389. strm.avail_in = strm.input.length;
  17390. do {
  17391. if (strm.avail_out === 0) {
  17392. strm.output = new utils.Buf8(chunkSize);
  17393. strm.next_out = 0;
  17394. strm.avail_out = chunkSize;
  17395. }
  17396. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  17397. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  17398. this.onEnd(status);
  17399. this.ended = true;
  17400. return false;
  17401. }
  17402. if (strm.next_out) {
  17403. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  17404. if (this.options.to === 'string') {
  17405. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  17406. tail = strm.next_out - next_out_utf8;
  17407. utf8str = strings.buf2string(strm.output, next_out_utf8);
  17408. // move tail
  17409. strm.next_out = tail;
  17410. strm.avail_out = chunkSize - tail;
  17411. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  17412. this.onData(utf8str);
  17413. } else {
  17414. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17415. }
  17416. }
  17417. }
  17418. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  17419. if (status === c.Z_STREAM_END) {
  17420. _mode = c.Z_FINISH;
  17421. }
  17422. // Finalize on the last chunk.
  17423. if (_mode === c.Z_FINISH) {
  17424. status = zlib_inflate.inflateEnd(this.strm);
  17425. this.onEnd(status);
  17426. this.ended = true;
  17427. return status === c.Z_OK;
  17428. }
  17429. return true;
  17430. };
  17431. /**
  17432. * Inflate#onData(chunk) -> Void
  17433. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17434. * on js engine support. When string output requested, each chunk
  17435. * will be string.
  17436. *
  17437. * By default, stores data blocks in `chunks[]` property and glue
  17438. * those in `onEnd`. Override this handler, if you need another behaviour.
  17439. **/
  17440. Inflate.prototype.onData = function(chunk) {
  17441. this.chunks.push(chunk);
  17442. };
  17443. /**
  17444. * Inflate#onEnd(status) -> Void
  17445. * - status (Number): inflate status. 0 (Z_OK) on success,
  17446. * other if not.
  17447. *
  17448. * Called once after you tell inflate that input stream complete
  17449. * or error happenned. By default - join collected chunks,
  17450. * free memory and fill `results` / `err` properties.
  17451. **/
  17452. Inflate.prototype.onEnd = function(status) {
  17453. // On success - join
  17454. if (status === c.Z_OK) {
  17455. if (this.options.to === 'string') {
  17456. // Glue & convert here, until we teach pako to send
  17457. // utf8 alligned strings to onData
  17458. this.result = this.chunks.join('');
  17459. } else {
  17460. this.result = utils.flattenChunks(this.chunks);
  17461. }
  17462. }
  17463. this.chunks = [];
  17464. this.err = status;
  17465. this.msg = this.strm.msg;
  17466. };
  17467. /**
  17468. * inflate(data[, options]) -> Uint8Array|Array|String
  17469. * - data (Uint8Array|Array|String): input data to decompress.
  17470. * - options (Object): zlib inflate options.
  17471. *
  17472. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  17473. * format via wrapper header by default. That's why we don't provide
  17474. * separate `ungzip` method.
  17475. *
  17476. * Supported options are:
  17477. *
  17478. * - windowBits
  17479. *
  17480. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17481. * for more information.
  17482. *
  17483. * Sugar (options):
  17484. *
  17485. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17486. * negative windowBits implicitly.
  17487. * - `to` (String) - if equal to 'string', then result will be converted
  17488. * from utf8 to utf16 (javascript) string. When string output requested,
  17489. * chunk length can differ from `chunkSize`, depending on content.
  17490. *
  17491. *
  17492. * ##### Example:
  17493. *
  17494. * ```javascript
  17495. * var pako = require('pako')
  17496. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  17497. * , output;
  17498. *
  17499. * try {
  17500. * output = pako.inflate(input);
  17501. * } catch (err)
  17502. * console.log(err);
  17503. * }
  17504. * ```
  17505. **/
  17506. function inflate(input, options) {
  17507. var inflator = new Inflate(options);
  17508. inflator.push(input, true);
  17509. // That will never happens, if you don't cheat with options :)
  17510. if (inflator.err) { throw inflator.msg; }
  17511. return inflator.result;
  17512. }
  17513. /**
  17514. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  17515. * - data (Uint8Array|Array|String): input data to decompress.
  17516. * - options (Object): zlib inflate options.
  17517. *
  17518. * The same as [[inflate]], but creates raw data, without wrapper
  17519. * (header and adler32 crc).
  17520. **/
  17521. function inflateRaw(input, options) {
  17522. options = options || {};
  17523. options.raw = true;
  17524. return inflate(input, options);
  17525. }
  17526. /**
  17527. * ungzip(data[, options]) -> Uint8Array|Array|String
  17528. * - data (Uint8Array|Array|String): input data to decompress.
  17529. * - options (Object): zlib inflate options.
  17530. *
  17531. * Just shortcut to [[inflate]], because it autodetects format
  17532. * by header.content. Done for convenience.
  17533. **/
  17534. exports.Inflate = Inflate;
  17535. exports.inflate = inflate;
  17536. exports.inflateRaw = inflateRaw;
  17537. exports.ungzip = inflate;
  17538. },{"./utils/common":66,"./utils/strings":67,"./zlib/constants":69,"./zlib/gzheader":72,"./zlib/inflate.js":74,"./zlib/messages":76,"./zlib/zstream":78}],66:[function(require,module,exports){
  17539. 'use strict';
  17540. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  17541. (typeof Uint16Array !== 'undefined') &&
  17542. (typeof Int32Array !== 'undefined');
  17543. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  17544. var sources = Array.prototype.slice.call(arguments, 1);
  17545. while (sources.length) {
  17546. var source = sources.shift();
  17547. if (!source) { continue; }
  17548. if (typeof(source) !== 'object') {
  17549. throw new TypeError(source + 'must be non-object');
  17550. }
  17551. for (var p in source) {
  17552. if (source.hasOwnProperty(p)) {
  17553. obj[p] = source[p];
  17554. }
  17555. }
  17556. }
  17557. return obj;
  17558. };
  17559. // reduce buffer size, avoiding mem copy
  17560. exports.shrinkBuf = function (buf, size) {
  17561. if (buf.length === size) { return buf; }
  17562. if (buf.subarray) { return buf.subarray(0, size); }
  17563. buf.length = size;
  17564. return buf;
  17565. };
  17566. var fnTyped = {
  17567. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17568. if (src.subarray && dest.subarray) {
  17569. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  17570. return;
  17571. }
  17572. // Fallback to ordinary array
  17573. for(var i=0; i<len; i++) {
  17574. dest[dest_offs + i] = src[src_offs + i];
  17575. }
  17576. },
  17577. // Join array of chunks to single array.
  17578. flattenChunks: function(chunks) {
  17579. var i, l, len, pos, chunk, result;
  17580. // calculate data length
  17581. len = 0;
  17582. for (i=0, l=chunks.length; i<l; i++) {
  17583. len += chunks[i].length;
  17584. }
  17585. // join chunks
  17586. result = new Uint8Array(len);
  17587. pos = 0;
  17588. for (i=0, l=chunks.length; i<l; i++) {
  17589. chunk = chunks[i];
  17590. result.set(chunk, pos);
  17591. pos += chunk.length;
  17592. }
  17593. return result;
  17594. }
  17595. };
  17596. var fnUntyped = {
  17597. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17598. for(var i=0; i<len; i++) {
  17599. dest[dest_offs + i] = src[src_offs + i];
  17600. }
  17601. },
  17602. // Join array of chunks to single array.
  17603. flattenChunks: function(chunks) {
  17604. return [].concat.apply([], chunks);
  17605. }
  17606. };
  17607. // Enable/Disable typed arrays use, for testing
  17608. //
  17609. exports.setTyped = function (on) {
  17610. if (on) {
  17611. exports.Buf8 = Uint8Array;
  17612. exports.Buf16 = Uint16Array;
  17613. exports.Buf32 = Int32Array;
  17614. exports.assign(exports, fnTyped);
  17615. } else {
  17616. exports.Buf8 = Array;
  17617. exports.Buf16 = Array;
  17618. exports.Buf32 = Array;
  17619. exports.assign(exports, fnUntyped);
  17620. }
  17621. };
  17622. exports.setTyped(TYPED_OK);
  17623. },{}],67:[function(require,module,exports){
  17624. // String encode/decode helpers
  17625. 'use strict';
  17626. var utils = require('./common');
  17627. // Quick check if we can use fast array to bin string conversion
  17628. //
  17629. // - apply(Array) can fail on Android 2.2
  17630. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  17631. //
  17632. var STR_APPLY_OK = true;
  17633. var STR_APPLY_UIA_OK = true;
  17634. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  17635. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  17636. // Table with utf8 lengths (calculated by first byte of sequence)
  17637. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  17638. // because max possible codepoint is 0x10ffff
  17639. var _utf8len = new utils.Buf8(256);
  17640. for (var i=0; i<256; i++) {
  17641. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  17642. }
  17643. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  17644. // convert string to array (typed, when possible)
  17645. exports.string2buf = function (str) {
  17646. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  17647. // count binary size
  17648. for (m_pos = 0; m_pos < str_len; m_pos++) {
  17649. c = str.charCodeAt(m_pos);
  17650. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17651. c2 = str.charCodeAt(m_pos+1);
  17652. if ((c2 & 0xfc00) === 0xdc00) {
  17653. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17654. m_pos++;
  17655. }
  17656. }
  17657. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  17658. }
  17659. // allocate buffer
  17660. buf = new utils.Buf8(buf_len);
  17661. // convert
  17662. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  17663. c = str.charCodeAt(m_pos);
  17664. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17665. c2 = str.charCodeAt(m_pos+1);
  17666. if ((c2 & 0xfc00) === 0xdc00) {
  17667. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17668. m_pos++;
  17669. }
  17670. }
  17671. if (c < 0x80) {
  17672. /* one byte */
  17673. buf[i++] = c;
  17674. } else if (c < 0x800) {
  17675. /* two bytes */
  17676. buf[i++] = 0xC0 | (c >>> 6);
  17677. buf[i++] = 0x80 | (c & 0x3f);
  17678. } else if (c < 0x10000) {
  17679. /* three bytes */
  17680. buf[i++] = 0xE0 | (c >>> 12);
  17681. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17682. buf[i++] = 0x80 | (c & 0x3f);
  17683. } else {
  17684. /* four bytes */
  17685. buf[i++] = 0xf0 | (c >>> 18);
  17686. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  17687. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17688. buf[i++] = 0x80 | (c & 0x3f);
  17689. }
  17690. }
  17691. return buf;
  17692. };
  17693. // Helper (used in 2 places)
  17694. function buf2binstring(buf, len) {
  17695. // use fallback for big arrays to avoid stack overflow
  17696. if (len < 65537) {
  17697. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  17698. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  17699. }
  17700. }
  17701. var result = '';
  17702. for(var i=0; i < len; i++) {
  17703. result += String.fromCharCode(buf[i]);
  17704. }
  17705. return result;
  17706. }
  17707. // Convert byte array to binary string
  17708. exports.buf2binstring = function(buf) {
  17709. return buf2binstring(buf, buf.length);
  17710. };
  17711. // Convert binary string (typed, when possible)
  17712. exports.binstring2buf = function(str) {
  17713. var buf = new utils.Buf8(str.length);
  17714. for(var i=0, len=buf.length; i < len; i++) {
  17715. buf[i] = str.charCodeAt(i);
  17716. }
  17717. return buf;
  17718. };
  17719. // convert array to string
  17720. exports.buf2string = function (buf, max) {
  17721. var i, out, c, c_len;
  17722. var len = max || buf.length;
  17723. // Reserve max possible length (2 words per char)
  17724. // NB: by unknown reasons, Array is significantly faster for
  17725. // String.fromCharCode.apply than Uint16Array.
  17726. var utf16buf = new Array(len*2);
  17727. for (out=0, i=0; i<len;) {
  17728. c = buf[i++];
  17729. // quick process ascii
  17730. if (c < 0x80) { utf16buf[out++] = c; continue; }
  17731. c_len = _utf8len[c];
  17732. // skip 5 & 6 byte codes
  17733. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  17734. // apply mask on first byte
  17735. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  17736. // join the rest
  17737. while (c_len > 1 && i < len) {
  17738. c = (c << 6) | (buf[i++] & 0x3f);
  17739. c_len--;
  17740. }
  17741. // terminated by end of string?
  17742. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  17743. if (c < 0x10000) {
  17744. utf16buf[out++] = c;
  17745. } else {
  17746. c -= 0x10000;
  17747. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  17748. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  17749. }
  17750. }
  17751. return buf2binstring(utf16buf, out);
  17752. };
  17753. // Calculate max possible position in utf8 buffer,
  17754. // that will not break sequence. If that's not possible
  17755. // - (very small limits) return max size as is.
  17756. //
  17757. // buf[] - utf8 bytes array
  17758. // max - length limit (mandatory);
  17759. exports.utf8border = function(buf, max) {
  17760. var pos;
  17761. max = max || buf.length;
  17762. if (max > buf.length) { max = buf.length; }
  17763. // go back from last position, until start of sequence found
  17764. pos = max-1;
  17765. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  17766. // Fuckup - very small and broken sequence,
  17767. // return max, because we should return something anyway.
  17768. if (pos < 0) { return max; }
  17769. // If we came to start of buffer - that means vuffer is too small,
  17770. // return max too.
  17771. if (pos === 0) { return max; }
  17772. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  17773. };
  17774. },{"./common":66}],68:[function(require,module,exports){
  17775. 'use strict';
  17776. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  17777. // It doesn't worth to make additional optimizationa as in original.
  17778. // Small size is preferable.
  17779. function adler32(adler, buf, len, pos) {
  17780. var s1 = (adler & 0xffff) |0
  17781. , s2 = ((adler >>> 16) & 0xffff) |0
  17782. , n = 0;
  17783. while (len !== 0) {
  17784. // Set limit ~ twice less than 5552, to keep
  17785. // s2 in 31-bits, because we force signed ints.
  17786. // in other case %= will fail.
  17787. n = len > 2000 ? 2000 : len;
  17788. len -= n;
  17789. do {
  17790. s1 = (s1 + buf[pos++]) |0;
  17791. s2 = (s2 + s1) |0;
  17792. } while (--n);
  17793. s1 %= 65521;
  17794. s2 %= 65521;
  17795. }
  17796. return (s1 | (s2 << 16)) |0;
  17797. }
  17798. module.exports = adler32;
  17799. },{}],69:[function(require,module,exports){
  17800. module.exports = {
  17801. /* Allowed flush values; see deflate() and inflate() below for details */
  17802. Z_NO_FLUSH: 0,
  17803. Z_PARTIAL_FLUSH: 1,
  17804. Z_SYNC_FLUSH: 2,
  17805. Z_FULL_FLUSH: 3,
  17806. Z_FINISH: 4,
  17807. Z_BLOCK: 5,
  17808. Z_TREES: 6,
  17809. /* Return codes for the compression/decompression functions. Negative values
  17810. * are errors, positive values are used for special but normal events.
  17811. */
  17812. Z_OK: 0,
  17813. Z_STREAM_END: 1,
  17814. Z_NEED_DICT: 2,
  17815. Z_ERRNO: -1,
  17816. Z_STREAM_ERROR: -2,
  17817. Z_DATA_ERROR: -3,
  17818. //Z_MEM_ERROR: -4,
  17819. Z_BUF_ERROR: -5,
  17820. //Z_VERSION_ERROR: -6,
  17821. /* compression levels */
  17822. Z_NO_COMPRESSION: 0,
  17823. Z_BEST_SPEED: 1,
  17824. Z_BEST_COMPRESSION: 9,
  17825. Z_DEFAULT_COMPRESSION: -1,
  17826. Z_FILTERED: 1,
  17827. Z_HUFFMAN_ONLY: 2,
  17828. Z_RLE: 3,
  17829. Z_FIXED: 4,
  17830. Z_DEFAULT_STRATEGY: 0,
  17831. /* Possible values of the data_type field (though see inflate()) */
  17832. Z_BINARY: 0,
  17833. Z_TEXT: 1,
  17834. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  17835. Z_UNKNOWN: 2,
  17836. /* The deflate compression method */
  17837. Z_DEFLATED: 8
  17838. //Z_NULL: null // Use -1 or null inline, depending on var type
  17839. };
  17840. },{}],70:[function(require,module,exports){
  17841. 'use strict';
  17842. // Note: we can't get significant speed boost here.
  17843. // So write code to minimize size - no pregenerated tables
  17844. // and array tools dependencies.
  17845. // Use ordinary array, since untyped makes no boost here
  17846. function makeTable() {
  17847. var c, table = [];
  17848. for(var n =0; n < 256; n++){
  17849. c = n;
  17850. for(var k =0; k < 8; k++){
  17851. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  17852. }
  17853. table[n] = c;
  17854. }
  17855. return table;
  17856. }
  17857. // Create table on load. Just 255 signed longs. Not a problem.
  17858. var crcTable = makeTable();
  17859. function crc32(crc, buf, len, pos) {
  17860. var t = crcTable
  17861. , end = pos + len;
  17862. crc = crc ^ (-1);
  17863. for (var i = pos; i < end; i++ ) {
  17864. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  17865. }
  17866. return (crc ^ (-1)); // >>> 0;
  17867. }
  17868. module.exports = crc32;
  17869. },{}],71:[function(require,module,exports){
  17870. 'use strict';
  17871. var utils = require('../utils/common');
  17872. var trees = require('./trees');
  17873. var adler32 = require('./adler32');
  17874. var crc32 = require('./crc32');
  17875. var msg = require('./messages');
  17876. /* Public constants ==========================================================*/
  17877. /* ===========================================================================*/
  17878. /* Allowed flush values; see deflate() and inflate() below for details */
  17879. var Z_NO_FLUSH = 0;
  17880. var Z_PARTIAL_FLUSH = 1;
  17881. //var Z_SYNC_FLUSH = 2;
  17882. var Z_FULL_FLUSH = 3;
  17883. var Z_FINISH = 4;
  17884. var Z_BLOCK = 5;
  17885. //var Z_TREES = 6;
  17886. /* Return codes for the compression/decompression functions. Negative values
  17887. * are errors, positive values are used for special but normal events.
  17888. */
  17889. var Z_OK = 0;
  17890. var Z_STREAM_END = 1;
  17891. //var Z_NEED_DICT = 2;
  17892. //var Z_ERRNO = -1;
  17893. var Z_STREAM_ERROR = -2;
  17894. var Z_DATA_ERROR = -3;
  17895. //var Z_MEM_ERROR = -4;
  17896. var Z_BUF_ERROR = -5;
  17897. //var Z_VERSION_ERROR = -6;
  17898. /* compression levels */
  17899. //var Z_NO_COMPRESSION = 0;
  17900. //var Z_BEST_SPEED = 1;
  17901. //var Z_BEST_COMPRESSION = 9;
  17902. var Z_DEFAULT_COMPRESSION = -1;
  17903. var Z_FILTERED = 1;
  17904. var Z_HUFFMAN_ONLY = 2;
  17905. var Z_RLE = 3;
  17906. var Z_FIXED = 4;
  17907. var Z_DEFAULT_STRATEGY = 0;
  17908. /* Possible values of the data_type field (though see inflate()) */
  17909. //var Z_BINARY = 0;
  17910. //var Z_TEXT = 1;
  17911. //var Z_ASCII = 1; // = Z_TEXT
  17912. var Z_UNKNOWN = 2;
  17913. /* The deflate compression method */
  17914. var Z_DEFLATED = 8;
  17915. /*============================================================================*/
  17916. var MAX_MEM_LEVEL = 9;
  17917. /* Maximum value for memLevel in deflateInit2 */
  17918. var MAX_WBITS = 15;
  17919. /* 32K LZ77 window */
  17920. var DEF_MEM_LEVEL = 8;
  17921. var LENGTH_CODES = 29;
  17922. /* number of length codes, not counting the special END_BLOCK code */
  17923. var LITERALS = 256;
  17924. /* number of literal bytes 0..255 */
  17925. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17926. /* number of Literal or Length codes, including the END_BLOCK code */
  17927. var D_CODES = 30;
  17928. /* number of distance codes */
  17929. var BL_CODES = 19;
  17930. /* number of codes used to transfer the bit lengths */
  17931. var HEAP_SIZE = 2*L_CODES + 1;
  17932. /* maximum heap size */
  17933. var MAX_BITS = 15;
  17934. /* All codes must not exceed MAX_BITS bits */
  17935. var MIN_MATCH = 3;
  17936. var MAX_MATCH = 258;
  17937. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  17938. var PRESET_DICT = 0x20;
  17939. var INIT_STATE = 42;
  17940. var EXTRA_STATE = 69;
  17941. var NAME_STATE = 73;
  17942. var COMMENT_STATE = 91;
  17943. var HCRC_STATE = 103;
  17944. var BUSY_STATE = 113;
  17945. var FINISH_STATE = 666;
  17946. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  17947. var BS_BLOCK_DONE = 2; /* block flush performed */
  17948. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  17949. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  17950. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  17951. function err(strm, errorCode) {
  17952. strm.msg = msg[errorCode];
  17953. return errorCode;
  17954. }
  17955. function rank(f) {
  17956. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  17957. }
  17958. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17959. /* =========================================================================
  17960. * Flush as much pending output as possible. All deflate() output goes
  17961. * through this function so some applications may wish to modify it
  17962. * to avoid allocating a large strm->output buffer and copying into it.
  17963. * (See also read_buf()).
  17964. */
  17965. function flush_pending(strm) {
  17966. var s = strm.state;
  17967. //_tr_flush_bits(s);
  17968. var len = s.pending;
  17969. if (len > strm.avail_out) {
  17970. len = strm.avail_out;
  17971. }
  17972. if (len === 0) { return; }
  17973. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  17974. strm.next_out += len;
  17975. s.pending_out += len;
  17976. strm.total_out += len;
  17977. strm.avail_out -= len;
  17978. s.pending -= len;
  17979. if (s.pending === 0) {
  17980. s.pending_out = 0;
  17981. }
  17982. }
  17983. function flush_block_only (s, last) {
  17984. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  17985. s.block_start = s.strstart;
  17986. flush_pending(s.strm);
  17987. }
  17988. function put_byte(s, b) {
  17989. s.pending_buf[s.pending++] = b;
  17990. }
  17991. /* =========================================================================
  17992. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  17993. * IN assertion: the stream state is correct and there is enough room in
  17994. * pending_buf.
  17995. */
  17996. function putShortMSB(s, b) {
  17997. // put_byte(s, (Byte)(b >> 8));
  17998. // put_byte(s, (Byte)(b & 0xff));
  17999. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  18000. s.pending_buf[s.pending++] = b & 0xff;
  18001. }
  18002. /* ===========================================================================
  18003. * Read a new buffer from the current input stream, update the adler32
  18004. * and total number of bytes read. All deflate() input goes through
  18005. * this function so some applications may wish to modify it to avoid
  18006. * allocating a large strm->input buffer and copying from it.
  18007. * (See also flush_pending()).
  18008. */
  18009. function read_buf(strm, buf, start, size) {
  18010. var len = strm.avail_in;
  18011. if (len > size) { len = size; }
  18012. if (len === 0) { return 0; }
  18013. strm.avail_in -= len;
  18014. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  18015. if (strm.state.wrap === 1) {
  18016. strm.adler = adler32(strm.adler, buf, len, start);
  18017. }
  18018. else if (strm.state.wrap === 2) {
  18019. strm.adler = crc32(strm.adler, buf, len, start);
  18020. }
  18021. strm.next_in += len;
  18022. strm.total_in += len;
  18023. return len;
  18024. }
  18025. /* ===========================================================================
  18026. * Set match_start to the longest match starting at the given string and
  18027. * return its length. Matches shorter or equal to prev_length are discarded,
  18028. * in which case the result is equal to prev_length and match_start is
  18029. * garbage.
  18030. * IN assertions: cur_match is the head of the hash chain for the current
  18031. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  18032. * OUT assertion: the match length is not greater than s->lookahead.
  18033. */
  18034. function longest_match(s, cur_match) {
  18035. var chain_length = s.max_chain_length; /* max hash chain length */
  18036. var scan = s.strstart; /* current string */
  18037. var match; /* matched string */
  18038. var len; /* length of current match */
  18039. var best_len = s.prev_length; /* best match length so far */
  18040. var nice_match = s.nice_match; /* stop if match long enough */
  18041. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  18042. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  18043. var _win = s.window; // shortcut
  18044. var wmask = s.w_mask;
  18045. var prev = s.prev;
  18046. /* Stop when cur_match becomes <= limit. To simplify the code,
  18047. * we prevent matches with the string of window index 0.
  18048. */
  18049. var strend = s.strstart + MAX_MATCH;
  18050. var scan_end1 = _win[scan + best_len - 1];
  18051. var scan_end = _win[scan + best_len];
  18052. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  18053. * It is easy to get rid of this optimization if necessary.
  18054. */
  18055. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  18056. /* Do not waste too much time if we already have a good match: */
  18057. if (s.prev_length >= s.good_match) {
  18058. chain_length >>= 2;
  18059. }
  18060. /* Do not look for matches beyond the end of the input. This is necessary
  18061. * to make deflate deterministic.
  18062. */
  18063. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  18064. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  18065. do {
  18066. // Assert(cur_match < s->strstart, "no future");
  18067. match = cur_match;
  18068. /* Skip to next match if the match length cannot increase
  18069. * or if the match length is less than 2. Note that the checks below
  18070. * for insufficient lookahead only occur occasionally for performance
  18071. * reasons. Therefore uninitialized memory will be accessed, and
  18072. * conditional jumps will be made that depend on those values.
  18073. * However the length of the match is limited to the lookahead, so
  18074. * the output of deflate is not affected by the uninitialized values.
  18075. */
  18076. if (_win[match + best_len] !== scan_end ||
  18077. _win[match + best_len - 1] !== scan_end1 ||
  18078. _win[match] !== _win[scan] ||
  18079. _win[++match] !== _win[scan + 1]) {
  18080. continue;
  18081. }
  18082. /* The check at best_len-1 can be removed because it will be made
  18083. * again later. (This heuristic is not always a win.)
  18084. * It is not necessary to compare scan[2] and match[2] since they
  18085. * are always equal when the other bytes match, given that
  18086. * the hash keys are equal and that HASH_BITS >= 8.
  18087. */
  18088. scan += 2;
  18089. match++;
  18090. // Assert(*scan == *match, "match[2]?");
  18091. /* We check for insufficient lookahead only every 8th comparison;
  18092. * the 256th check will be made at strstart+258.
  18093. */
  18094. do {
  18095. /*jshint noempty:false*/
  18096. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18097. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18098. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18099. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18100. scan < strend);
  18101. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  18102. len = MAX_MATCH - (strend - scan);
  18103. scan = strend - MAX_MATCH;
  18104. if (len > best_len) {
  18105. s.match_start = cur_match;
  18106. best_len = len;
  18107. if (len >= nice_match) {
  18108. break;
  18109. }
  18110. scan_end1 = _win[scan + best_len - 1];
  18111. scan_end = _win[scan + best_len];
  18112. }
  18113. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  18114. if (best_len <= s.lookahead) {
  18115. return best_len;
  18116. }
  18117. return s.lookahead;
  18118. }
  18119. /* ===========================================================================
  18120. * Fill the window when the lookahead becomes insufficient.
  18121. * Updates strstart and lookahead.
  18122. *
  18123. * IN assertion: lookahead < MIN_LOOKAHEAD
  18124. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  18125. * At least one byte has been read, or avail_in == 0; reads are
  18126. * performed for at least two bytes (required for the zip translate_eol
  18127. * option -- not supported here).
  18128. */
  18129. function fill_window(s) {
  18130. var _w_size = s.w_size;
  18131. var p, n, m, more, str;
  18132. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  18133. do {
  18134. more = s.window_size - s.lookahead - s.strstart;
  18135. // JS ints have 32 bit, block below not needed
  18136. /* Deal with !@#$% 64K limit: */
  18137. //if (sizeof(int) <= 2) {
  18138. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  18139. // more = wsize;
  18140. //
  18141. // } else if (more == (unsigned)(-1)) {
  18142. // /* Very unlikely, but possible on 16 bit machine if
  18143. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  18144. // */
  18145. // more--;
  18146. // }
  18147. //}
  18148. /* If the window is almost full and there is insufficient lookahead,
  18149. * move the upper half to the lower one to make room in the upper half.
  18150. */
  18151. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  18152. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  18153. s.match_start -= _w_size;
  18154. s.strstart -= _w_size;
  18155. /* we now have strstart >= MAX_DIST */
  18156. s.block_start -= _w_size;
  18157. /* Slide the hash table (could be avoided with 32 bit values
  18158. at the expense of memory usage). We slide even when level == 0
  18159. to keep the hash table consistent if we switch back to level > 0
  18160. later. (Using level 0 permanently is not an optimal usage of
  18161. zlib, so we don't care about this pathological case.)
  18162. */
  18163. n = s.hash_size;
  18164. p = n;
  18165. do {
  18166. m = s.head[--p];
  18167. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  18168. } while (--n);
  18169. n = _w_size;
  18170. p = n;
  18171. do {
  18172. m = s.prev[--p];
  18173. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  18174. /* If n is not on any hash chain, prev[n] is garbage but
  18175. * its value will never be used.
  18176. */
  18177. } while (--n);
  18178. more += _w_size;
  18179. }
  18180. if (s.strm.avail_in === 0) {
  18181. break;
  18182. }
  18183. /* If there was no sliding:
  18184. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  18185. * more == window_size - lookahead - strstart
  18186. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  18187. * => more >= window_size - 2*WSIZE + 2
  18188. * In the BIG_MEM or MMAP case (not yet supported),
  18189. * window_size == input_size + MIN_LOOKAHEAD &&
  18190. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  18191. * Otherwise, window_size == 2*WSIZE so more >= 2.
  18192. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  18193. */
  18194. //Assert(more >= 2, "more < 2");
  18195. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  18196. s.lookahead += n;
  18197. /* Initialize the hash value now that we have some input: */
  18198. if (s.lookahead + s.insert >= MIN_MATCH) {
  18199. str = s.strstart - s.insert;
  18200. s.ins_h = s.window[str];
  18201. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  18202. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  18203. //#if MIN_MATCH != 3
  18204. // Call update_hash() MIN_MATCH-3 more times
  18205. //#endif
  18206. while (s.insert) {
  18207. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  18208. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  18209. s.prev[str & s.w_mask] = s.head[s.ins_h];
  18210. s.head[s.ins_h] = str;
  18211. str++;
  18212. s.insert--;
  18213. if (s.lookahead + s.insert < MIN_MATCH) {
  18214. break;
  18215. }
  18216. }
  18217. }
  18218. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  18219. * but this is not important since only literal bytes will be emitted.
  18220. */
  18221. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  18222. /* If the WIN_INIT bytes after the end of the current data have never been
  18223. * written, then zero those bytes in order to avoid memory check reports of
  18224. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  18225. * the longest match routines. Update the high water mark for the next
  18226. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  18227. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  18228. */
  18229. // if (s.high_water < s.window_size) {
  18230. // var curr = s.strstart + s.lookahead;
  18231. // var init = 0;
  18232. //
  18233. // if (s.high_water < curr) {
  18234. // /* Previous high water mark below current data -- zero WIN_INIT
  18235. // * bytes or up to end of window, whichever is less.
  18236. // */
  18237. // init = s.window_size - curr;
  18238. // if (init > WIN_INIT)
  18239. // init = WIN_INIT;
  18240. // zmemzero(s->window + curr, (unsigned)init);
  18241. // s->high_water = curr + init;
  18242. // }
  18243. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  18244. // /* High water mark at or above current data, but below current data
  18245. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  18246. // * to end of window, whichever is less.
  18247. // */
  18248. // init = (ulg)curr + WIN_INIT - s->high_water;
  18249. // if (init > s->window_size - s->high_water)
  18250. // init = s->window_size - s->high_water;
  18251. // zmemzero(s->window + s->high_water, (unsigned)init);
  18252. // s->high_water += init;
  18253. // }
  18254. // }
  18255. //
  18256. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  18257. // "not enough room for search");
  18258. }
  18259. /* ===========================================================================
  18260. * Copy without compression as much as possible from the input stream, return
  18261. * the current block state.
  18262. * This function does not insert new strings in the dictionary since
  18263. * uncompressible data is probably not useful. This function is used
  18264. * only for the level=0 compression option.
  18265. * NOTE: this function should be optimized to avoid extra copying from
  18266. * window to pending_buf.
  18267. */
  18268. function deflate_stored(s, flush) {
  18269. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  18270. * to pending_buf_size, and each stored block has a 5 byte header:
  18271. */
  18272. var max_block_size = 0xffff;
  18273. if (max_block_size > s.pending_buf_size - 5) {
  18274. max_block_size = s.pending_buf_size - 5;
  18275. }
  18276. /* Copy as much as possible from input to output: */
  18277. for (;;) {
  18278. /* Fill the window as much as possible: */
  18279. if (s.lookahead <= 1) {
  18280. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  18281. // s->block_start >= (long)s->w_size, "slide too late");
  18282. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  18283. // s.block_start >= s.w_size)) {
  18284. // throw new Error("slide too late");
  18285. // }
  18286. fill_window(s);
  18287. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  18288. return BS_NEED_MORE;
  18289. }
  18290. if (s.lookahead === 0) {
  18291. break;
  18292. }
  18293. /* flush the current block */
  18294. }
  18295. //Assert(s->block_start >= 0L, "block gone");
  18296. // if (s.block_start < 0) throw new Error("block gone");
  18297. s.strstart += s.lookahead;
  18298. s.lookahead = 0;
  18299. /* Emit a stored block if pending_buf will be full: */
  18300. var max_start = s.block_start + max_block_size;
  18301. if (s.strstart === 0 || s.strstart >= max_start) {
  18302. /* strstart == 0 is possible when wraparound on 16-bit machine */
  18303. s.lookahead = s.strstart - max_start;
  18304. s.strstart = max_start;
  18305. /*** FLUSH_BLOCK(s, 0); ***/
  18306. flush_block_only(s, false);
  18307. if (s.strm.avail_out === 0) {
  18308. return BS_NEED_MORE;
  18309. }
  18310. /***/
  18311. }
  18312. /* Flush if we may have to slide, otherwise block_start may become
  18313. * negative and the data will be gone:
  18314. */
  18315. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  18316. /*** FLUSH_BLOCK(s, 0); ***/
  18317. flush_block_only(s, false);
  18318. if (s.strm.avail_out === 0) {
  18319. return BS_NEED_MORE;
  18320. }
  18321. /***/
  18322. }
  18323. }
  18324. s.insert = 0;
  18325. if (flush === Z_FINISH) {
  18326. /*** FLUSH_BLOCK(s, 1); ***/
  18327. flush_block_only(s, true);
  18328. if (s.strm.avail_out === 0) {
  18329. return BS_FINISH_STARTED;
  18330. }
  18331. /***/
  18332. return BS_FINISH_DONE;
  18333. }
  18334. if (s.strstart > s.block_start) {
  18335. /*** FLUSH_BLOCK(s, 0); ***/
  18336. flush_block_only(s, false);
  18337. if (s.strm.avail_out === 0) {
  18338. return BS_NEED_MORE;
  18339. }
  18340. /***/
  18341. }
  18342. return BS_NEED_MORE;
  18343. }
  18344. /* ===========================================================================
  18345. * Compress as much as possible from the input stream, return the current
  18346. * block state.
  18347. * This function does not perform lazy evaluation of matches and inserts
  18348. * new strings in the dictionary only for unmatched strings or for short
  18349. * matches. It is used only for the fast compression options.
  18350. */
  18351. function deflate_fast(s, flush) {
  18352. var hash_head; /* head of the hash chain */
  18353. var bflush; /* set if current block must be flushed */
  18354. for (;;) {
  18355. /* Make sure that we always have enough lookahead, except
  18356. * at the end of the input file. We need MAX_MATCH bytes
  18357. * for the next match, plus MIN_MATCH bytes to insert the
  18358. * string following the next match.
  18359. */
  18360. if (s.lookahead < MIN_LOOKAHEAD) {
  18361. fill_window(s);
  18362. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18363. return BS_NEED_MORE;
  18364. }
  18365. if (s.lookahead === 0) {
  18366. break; /* flush the current block */
  18367. }
  18368. }
  18369. /* Insert the string window[strstart .. strstart+2] in the
  18370. * dictionary, and set hash_head to the head of the hash chain:
  18371. */
  18372. hash_head = 0/*NIL*/;
  18373. if (s.lookahead >= MIN_MATCH) {
  18374. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18375. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18376. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18377. s.head[s.ins_h] = s.strstart;
  18378. /***/
  18379. }
  18380. /* Find the longest match, discarding those <= prev_length.
  18381. * At this point we have always match_length < MIN_MATCH
  18382. */
  18383. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  18384. /* To simplify the code, we prevent matches with the string
  18385. * of window index 0 (in particular we have to avoid a match
  18386. * of the string with itself at the start of the input file).
  18387. */
  18388. s.match_length = longest_match(s, hash_head);
  18389. /* longest_match() sets match_start */
  18390. }
  18391. if (s.match_length >= MIN_MATCH) {
  18392. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  18393. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  18394. s.match_length - MIN_MATCH, bflush); ***/
  18395. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  18396. s.lookahead -= s.match_length;
  18397. /* Insert new strings in the hash table only if the match length
  18398. * is not too large. This saves time but degrades compression.
  18399. */
  18400. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  18401. s.match_length--; /* string at strstart already in table */
  18402. do {
  18403. s.strstart++;
  18404. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18405. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18406. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18407. s.head[s.ins_h] = s.strstart;
  18408. /***/
  18409. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  18410. * always MIN_MATCH bytes ahead.
  18411. */
  18412. } while (--s.match_length !== 0);
  18413. s.strstart++;
  18414. } else
  18415. {
  18416. s.strstart += s.match_length;
  18417. s.match_length = 0;
  18418. s.ins_h = s.window[s.strstart];
  18419. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  18420. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  18421. //#if MIN_MATCH != 3
  18422. // Call UPDATE_HASH() MIN_MATCH-3 more times
  18423. //#endif
  18424. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  18425. * matter since it will be recomputed at next deflate call.
  18426. */
  18427. }
  18428. } else {
  18429. /* No match, output a literal byte */
  18430. //Tracevv((stderr,"%c", s.window[s.strstart]));
  18431. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18432. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18433. s.lookahead--;
  18434. s.strstart++;
  18435. }
  18436. if (bflush) {
  18437. /*** FLUSH_BLOCK(s, 0); ***/
  18438. flush_block_only(s, false);
  18439. if (s.strm.avail_out === 0) {
  18440. return BS_NEED_MORE;
  18441. }
  18442. /***/
  18443. }
  18444. }
  18445. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  18446. if (flush === Z_FINISH) {
  18447. /*** FLUSH_BLOCK(s, 1); ***/
  18448. flush_block_only(s, true);
  18449. if (s.strm.avail_out === 0) {
  18450. return BS_FINISH_STARTED;
  18451. }
  18452. /***/
  18453. return BS_FINISH_DONE;
  18454. }
  18455. if (s.last_lit) {
  18456. /*** FLUSH_BLOCK(s, 0); ***/
  18457. flush_block_only(s, false);
  18458. if (s.strm.avail_out === 0) {
  18459. return BS_NEED_MORE;
  18460. }
  18461. /***/
  18462. }
  18463. return BS_BLOCK_DONE;
  18464. }
  18465. /* ===========================================================================
  18466. * Same as above, but achieves better compression. We use a lazy
  18467. * evaluation for matches: a match is finally adopted only if there is
  18468. * no better match at the next window position.
  18469. */
  18470. function deflate_slow(s, flush) {
  18471. var hash_head; /* head of hash chain */
  18472. var bflush; /* set if current block must be flushed */
  18473. var max_insert;
  18474. /* Process the input block. */
  18475. for (;;) {
  18476. /* Make sure that we always have enough lookahead, except
  18477. * at the end of the input file. We need MAX_MATCH bytes
  18478. * for the next match, plus MIN_MATCH bytes to insert the
  18479. * string following the next match.
  18480. */
  18481. if (s.lookahead < MIN_LOOKAHEAD) {
  18482. fill_window(s);
  18483. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18484. return BS_NEED_MORE;
  18485. }
  18486. if (s.lookahead === 0) { break; } /* flush the current block */
  18487. }
  18488. /* Insert the string window[strstart .. strstart+2] in the
  18489. * dictionary, and set hash_head to the head of the hash chain:
  18490. */
  18491. hash_head = 0/*NIL*/;
  18492. if (s.lookahead >= MIN_MATCH) {
  18493. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18494. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18495. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18496. s.head[s.ins_h] = s.strstart;
  18497. /***/
  18498. }
  18499. /* Find the longest match, discarding those <= prev_length.
  18500. */
  18501. s.prev_length = s.match_length;
  18502. s.prev_match = s.match_start;
  18503. s.match_length = MIN_MATCH-1;
  18504. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  18505. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  18506. /* To simplify the code, we prevent matches with the string
  18507. * of window index 0 (in particular we have to avoid a match
  18508. * of the string with itself at the start of the input file).
  18509. */
  18510. s.match_length = longest_match(s, hash_head);
  18511. /* longest_match() sets match_start */
  18512. if (s.match_length <= 5 &&
  18513. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  18514. /* If prev_match is also MIN_MATCH, match_start is garbage
  18515. * but we will ignore the current match anyway.
  18516. */
  18517. s.match_length = MIN_MATCH-1;
  18518. }
  18519. }
  18520. /* If there was a match at the previous step and the current
  18521. * match is not better, output the previous match:
  18522. */
  18523. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  18524. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  18525. /* Do not insert strings in hash table beyond this. */
  18526. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  18527. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  18528. s.prev_length - MIN_MATCH, bflush);***/
  18529. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  18530. /* Insert in hash table all strings up to the end of the match.
  18531. * strstart-1 and strstart are already inserted. If there is not
  18532. * enough lookahead, the last two strings are not inserted in
  18533. * the hash table.
  18534. */
  18535. s.lookahead -= s.prev_length-1;
  18536. s.prev_length -= 2;
  18537. do {
  18538. if (++s.strstart <= max_insert) {
  18539. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18540. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18541. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18542. s.head[s.ins_h] = s.strstart;
  18543. /***/
  18544. }
  18545. } while (--s.prev_length !== 0);
  18546. s.match_available = 0;
  18547. s.match_length = MIN_MATCH-1;
  18548. s.strstart++;
  18549. if (bflush) {
  18550. /*** FLUSH_BLOCK(s, 0); ***/
  18551. flush_block_only(s, false);
  18552. if (s.strm.avail_out === 0) {
  18553. return BS_NEED_MORE;
  18554. }
  18555. /***/
  18556. }
  18557. } else if (s.match_available) {
  18558. /* If there was no match at the previous position, output a
  18559. * single literal. If there was a match but the current match
  18560. * is longer, truncate the previous match to a single literal.
  18561. */
  18562. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18563. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18564. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18565. if (bflush) {
  18566. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  18567. flush_block_only(s, false);
  18568. /***/
  18569. }
  18570. s.strstart++;
  18571. s.lookahead--;
  18572. if (s.strm.avail_out === 0) {
  18573. return BS_NEED_MORE;
  18574. }
  18575. } else {
  18576. /* There is no previous match to compare with, wait for
  18577. * the next step to decide.
  18578. */
  18579. s.match_available = 1;
  18580. s.strstart++;
  18581. s.lookahead--;
  18582. }
  18583. }
  18584. //Assert (flush != Z_NO_FLUSH, "no flush?");
  18585. if (s.match_available) {
  18586. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18587. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18588. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18589. s.match_available = 0;
  18590. }
  18591. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  18592. if (flush === Z_FINISH) {
  18593. /*** FLUSH_BLOCK(s, 1); ***/
  18594. flush_block_only(s, true);
  18595. if (s.strm.avail_out === 0) {
  18596. return BS_FINISH_STARTED;
  18597. }
  18598. /***/
  18599. return BS_FINISH_DONE;
  18600. }
  18601. if (s.last_lit) {
  18602. /*** FLUSH_BLOCK(s, 0); ***/
  18603. flush_block_only(s, false);
  18604. if (s.strm.avail_out === 0) {
  18605. return BS_NEED_MORE;
  18606. }
  18607. /***/
  18608. }
  18609. return BS_BLOCK_DONE;
  18610. }
  18611. /* ===========================================================================
  18612. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  18613. * one. Do not maintain a hash table. (It will be regenerated if this run of
  18614. * deflate switches away from Z_RLE.)
  18615. */
  18616. function deflate_rle(s, flush) {
  18617. var bflush; /* set if current block must be flushed */
  18618. var prev; /* byte at distance one to match */
  18619. var scan, strend; /* scan goes up to strend for length of run */
  18620. var _win = s.window;
  18621. for (;;) {
  18622. /* Make sure that we always have enough lookahead, except
  18623. * at the end of the input file. We need MAX_MATCH bytes
  18624. * for the longest run, plus one for the unrolled loop.
  18625. */
  18626. if (s.lookahead <= MAX_MATCH) {
  18627. fill_window(s);
  18628. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  18629. return BS_NEED_MORE;
  18630. }
  18631. if (s.lookahead === 0) { break; } /* flush the current block */
  18632. }
  18633. /* See how many times the previous byte repeats */
  18634. s.match_length = 0;
  18635. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  18636. scan = s.strstart - 1;
  18637. prev = _win[scan];
  18638. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  18639. strend = s.strstart + MAX_MATCH;
  18640. do {
  18641. /*jshint noempty:false*/
  18642. } while (prev === _win[++scan] && prev === _win[++scan] &&
  18643. prev === _win[++scan] && prev === _win[++scan] &&
  18644. prev === _win[++scan] && prev === _win[++scan] &&
  18645. prev === _win[++scan] && prev === _win[++scan] &&
  18646. scan < strend);
  18647. s.match_length = MAX_MATCH - (strend - scan);
  18648. if (s.match_length > s.lookahead) {
  18649. s.match_length = s.lookahead;
  18650. }
  18651. }
  18652. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  18653. }
  18654. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  18655. if (s.match_length >= MIN_MATCH) {
  18656. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  18657. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  18658. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  18659. s.lookahead -= s.match_length;
  18660. s.strstart += s.match_length;
  18661. s.match_length = 0;
  18662. } else {
  18663. /* No match, output a literal byte */
  18664. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18665. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18666. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18667. s.lookahead--;
  18668. s.strstart++;
  18669. }
  18670. if (bflush) {
  18671. /*** FLUSH_BLOCK(s, 0); ***/
  18672. flush_block_only(s, false);
  18673. if (s.strm.avail_out === 0) {
  18674. return BS_NEED_MORE;
  18675. }
  18676. /***/
  18677. }
  18678. }
  18679. s.insert = 0;
  18680. if (flush === Z_FINISH) {
  18681. /*** FLUSH_BLOCK(s, 1); ***/
  18682. flush_block_only(s, true);
  18683. if (s.strm.avail_out === 0) {
  18684. return BS_FINISH_STARTED;
  18685. }
  18686. /***/
  18687. return BS_FINISH_DONE;
  18688. }
  18689. if (s.last_lit) {
  18690. /*** FLUSH_BLOCK(s, 0); ***/
  18691. flush_block_only(s, false);
  18692. if (s.strm.avail_out === 0) {
  18693. return BS_NEED_MORE;
  18694. }
  18695. /***/
  18696. }
  18697. return BS_BLOCK_DONE;
  18698. }
  18699. /* ===========================================================================
  18700. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  18701. * (It will be regenerated if this run of deflate switches away from Huffman.)
  18702. */
  18703. function deflate_huff(s, flush) {
  18704. var bflush; /* set if current block must be flushed */
  18705. for (;;) {
  18706. /* Make sure that we have a literal to write. */
  18707. if (s.lookahead === 0) {
  18708. fill_window(s);
  18709. if (s.lookahead === 0) {
  18710. if (flush === Z_NO_FLUSH) {
  18711. return BS_NEED_MORE;
  18712. }
  18713. break; /* flush the current block */
  18714. }
  18715. }
  18716. /* Output a literal byte */
  18717. s.match_length = 0;
  18718. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18719. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18720. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18721. s.lookahead--;
  18722. s.strstart++;
  18723. if (bflush) {
  18724. /*** FLUSH_BLOCK(s, 0); ***/
  18725. flush_block_only(s, false);
  18726. if (s.strm.avail_out === 0) {
  18727. return BS_NEED_MORE;
  18728. }
  18729. /***/
  18730. }
  18731. }
  18732. s.insert = 0;
  18733. if (flush === Z_FINISH) {
  18734. /*** FLUSH_BLOCK(s, 1); ***/
  18735. flush_block_only(s, true);
  18736. if (s.strm.avail_out === 0) {
  18737. return BS_FINISH_STARTED;
  18738. }
  18739. /***/
  18740. return BS_FINISH_DONE;
  18741. }
  18742. if (s.last_lit) {
  18743. /*** FLUSH_BLOCK(s, 0); ***/
  18744. flush_block_only(s, false);
  18745. if (s.strm.avail_out === 0) {
  18746. return BS_NEED_MORE;
  18747. }
  18748. /***/
  18749. }
  18750. return BS_BLOCK_DONE;
  18751. }
  18752. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  18753. * the desired pack level (0..9). The values given below have been tuned to
  18754. * exclude worst case performance for pathological files. Better values may be
  18755. * found for specific files.
  18756. */
  18757. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  18758. this.good_length = good_length;
  18759. this.max_lazy = max_lazy;
  18760. this.nice_length = nice_length;
  18761. this.max_chain = max_chain;
  18762. this.func = func;
  18763. };
  18764. var configuration_table;
  18765. configuration_table = [
  18766. /* good lazy nice chain */
  18767. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  18768. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  18769. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  18770. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  18771. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  18772. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  18773. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  18774. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  18775. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  18776. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  18777. ];
  18778. /* ===========================================================================
  18779. * Initialize the "longest match" routines for a new zlib stream
  18780. */
  18781. function lm_init(s) {
  18782. s.window_size = 2 * s.w_size;
  18783. /*** CLEAR_HASH(s); ***/
  18784. zero(s.head); // Fill with NIL (= 0);
  18785. /* Set the default configuration parameters:
  18786. */
  18787. s.max_lazy_match = configuration_table[s.level].max_lazy;
  18788. s.good_match = configuration_table[s.level].good_length;
  18789. s.nice_match = configuration_table[s.level].nice_length;
  18790. s.max_chain_length = configuration_table[s.level].max_chain;
  18791. s.strstart = 0;
  18792. s.block_start = 0;
  18793. s.lookahead = 0;
  18794. s.insert = 0;
  18795. s.match_length = s.prev_length = MIN_MATCH - 1;
  18796. s.match_available = 0;
  18797. s.ins_h = 0;
  18798. }
  18799. function DeflateState() {
  18800. this.strm = null; /* pointer back to this zlib stream */
  18801. this.status = 0; /* as the name implies */
  18802. this.pending_buf = null; /* output still pending */
  18803. this.pending_buf_size = 0; /* size of pending_buf */
  18804. this.pending_out = 0; /* next pending byte to output to the stream */
  18805. this.pending = 0; /* nb of bytes in the pending buffer */
  18806. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  18807. this.gzhead = null; /* gzip header information to write */
  18808. this.gzindex = 0; /* where in extra, name, or comment */
  18809. this.method = Z_DEFLATED; /* can only be DEFLATED */
  18810. this.last_flush = -1; /* value of flush param for previous deflate call */
  18811. this.w_size = 0; /* LZ77 window size (32K by default) */
  18812. this.w_bits = 0; /* log2(w_size) (8..16) */
  18813. this.w_mask = 0; /* w_size - 1 */
  18814. this.window = null;
  18815. /* Sliding window. Input bytes are read into the second half of the window,
  18816. * and move to the first half later to keep a dictionary of at least wSize
  18817. * bytes. With this organization, matches are limited to a distance of
  18818. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  18819. * performed with a length multiple of the block size.
  18820. */
  18821. this.window_size = 0;
  18822. /* Actual size of window: 2*wSize, except when the user input buffer
  18823. * is directly used as sliding window.
  18824. */
  18825. this.prev = null;
  18826. /* Link to older string with same hash index. To limit the size of this
  18827. * array to 64K, this link is maintained only for the last 32K strings.
  18828. * An index in this array is thus a window index modulo 32K.
  18829. */
  18830. this.head = null; /* Heads of the hash chains or NIL. */
  18831. this.ins_h = 0; /* hash index of string to be inserted */
  18832. this.hash_size = 0; /* number of elements in hash table */
  18833. this.hash_bits = 0; /* log2(hash_size) */
  18834. this.hash_mask = 0; /* hash_size-1 */
  18835. this.hash_shift = 0;
  18836. /* Number of bits by which ins_h must be shifted at each input
  18837. * step. It must be such that after MIN_MATCH steps, the oldest
  18838. * byte no longer takes part in the hash key, that is:
  18839. * hash_shift * MIN_MATCH >= hash_bits
  18840. */
  18841. this.block_start = 0;
  18842. /* Window position at the beginning of the current output block. Gets
  18843. * negative when the window is moved backwards.
  18844. */
  18845. this.match_length = 0; /* length of best match */
  18846. this.prev_match = 0; /* previous match */
  18847. this.match_available = 0; /* set if previous match exists */
  18848. this.strstart = 0; /* start of string to insert */
  18849. this.match_start = 0; /* start of matching string */
  18850. this.lookahead = 0; /* number of valid bytes ahead in window */
  18851. this.prev_length = 0;
  18852. /* Length of the best match at previous step. Matches not greater than this
  18853. * are discarded. This is used in the lazy match evaluation.
  18854. */
  18855. this.max_chain_length = 0;
  18856. /* To speed up deflation, hash chains are never searched beyond this
  18857. * length. A higher limit improves compression ratio but degrades the
  18858. * speed.
  18859. */
  18860. this.max_lazy_match = 0;
  18861. /* Attempt to find a better match only when the current match is strictly
  18862. * smaller than this value. This mechanism is used only for compression
  18863. * levels >= 4.
  18864. */
  18865. // That's alias to max_lazy_match, don't use directly
  18866. //this.max_insert_length = 0;
  18867. /* Insert new strings in the hash table only if the match length is not
  18868. * greater than this length. This saves time but degrades compression.
  18869. * max_insert_length is used only for compression levels <= 3.
  18870. */
  18871. this.level = 0; /* compression level (1..9) */
  18872. this.strategy = 0; /* favor or force Huffman coding*/
  18873. this.good_match = 0;
  18874. /* Use a faster search when the previous match is longer than this */
  18875. this.nice_match = 0; /* Stop searching when current match exceeds this */
  18876. /* used by trees.c: */
  18877. /* Didn't use ct_data typedef below to suppress compiler warning */
  18878. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  18879. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  18880. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  18881. // Use flat array of DOUBLE size, with interleaved fata,
  18882. // because JS does not support effective
  18883. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  18884. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  18885. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  18886. zero(this.dyn_ltree);
  18887. zero(this.dyn_dtree);
  18888. zero(this.bl_tree);
  18889. this.l_desc = null; /* desc. for literal tree */
  18890. this.d_desc = null; /* desc. for distance tree */
  18891. this.bl_desc = null; /* desc. for bit length tree */
  18892. //ush bl_count[MAX_BITS+1];
  18893. this.bl_count = new utils.Buf16(MAX_BITS+1);
  18894. /* number of codes at each bit length for an optimal tree */
  18895. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  18896. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  18897. zero(this.heap);
  18898. this.heap_len = 0; /* number of elements in the heap */
  18899. this.heap_max = 0; /* element of largest frequency */
  18900. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  18901. * The same heap array is used to build all trees.
  18902. */
  18903. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  18904. zero(this.depth);
  18905. /* Depth of each subtree used as tie breaker for trees of equal frequency
  18906. */
  18907. this.l_buf = 0; /* buffer index for literals or lengths */
  18908. this.lit_bufsize = 0;
  18909. /* Size of match buffer for literals/lengths. There are 4 reasons for
  18910. * limiting lit_bufsize to 64K:
  18911. * - frequencies can be kept in 16 bit counters
  18912. * - if compression is not successful for the first block, all input
  18913. * data is still in the window so we can still emit a stored block even
  18914. * when input comes from standard input. (This can also be done for
  18915. * all blocks if lit_bufsize is not greater than 32K.)
  18916. * - if compression is not successful for a file smaller than 64K, we can
  18917. * even emit a stored file instead of a stored block (saving 5 bytes).
  18918. * This is applicable only for zip (not gzip or zlib).
  18919. * - creating new Huffman trees less frequently may not provide fast
  18920. * adaptation to changes in the input data statistics. (Take for
  18921. * example a binary file with poorly compressible code followed by
  18922. * a highly compressible string table.) Smaller buffer sizes give
  18923. * fast adaptation but have of course the overhead of transmitting
  18924. * trees more frequently.
  18925. * - I can't count above 4
  18926. */
  18927. this.last_lit = 0; /* running index in l_buf */
  18928. this.d_buf = 0;
  18929. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  18930. * the same number of elements. To use different lengths, an extra flag
  18931. * array would be necessary.
  18932. */
  18933. this.opt_len = 0; /* bit length of current block with optimal trees */
  18934. this.static_len = 0; /* bit length of current block with static trees */
  18935. this.matches = 0; /* number of string matches in current block */
  18936. this.insert = 0; /* bytes at end of window left to insert */
  18937. this.bi_buf = 0;
  18938. /* Output buffer. bits are inserted starting at the bottom (least
  18939. * significant bits).
  18940. */
  18941. this.bi_valid = 0;
  18942. /* Number of valid bits in bi_buf. All bits above the last valid bit
  18943. * are always zero.
  18944. */
  18945. // Used for window memory init. We safely ignore it for JS. That makes
  18946. // sense only for pointers and memory check tools.
  18947. //this.high_water = 0;
  18948. /* High water mark offset in window for initialized bytes -- bytes above
  18949. * this are set to zero in order to avoid memory check warnings when
  18950. * longest match routines access bytes past the input. This is then
  18951. * updated to the new high water mark.
  18952. */
  18953. }
  18954. function deflateResetKeep(strm) {
  18955. var s;
  18956. if (!strm || !strm.state) {
  18957. return err(strm, Z_STREAM_ERROR);
  18958. }
  18959. strm.total_in = strm.total_out = 0;
  18960. strm.data_type = Z_UNKNOWN;
  18961. s = strm.state;
  18962. s.pending = 0;
  18963. s.pending_out = 0;
  18964. if (s.wrap < 0) {
  18965. s.wrap = -s.wrap;
  18966. /* was made negative by deflate(..., Z_FINISH); */
  18967. }
  18968. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  18969. strm.adler = (s.wrap === 2) ?
  18970. 0 // crc32(0, Z_NULL, 0)
  18971. :
  18972. 1; // adler32(0, Z_NULL, 0)
  18973. s.last_flush = Z_NO_FLUSH;
  18974. trees._tr_init(s);
  18975. return Z_OK;
  18976. }
  18977. function deflateReset(strm) {
  18978. var ret = deflateResetKeep(strm);
  18979. if (ret === Z_OK) {
  18980. lm_init(strm.state);
  18981. }
  18982. return ret;
  18983. }
  18984. function deflateSetHeader(strm, head) {
  18985. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18986. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  18987. strm.state.gzhead = head;
  18988. return Z_OK;
  18989. }
  18990. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  18991. if (!strm) { // === Z_NULL
  18992. return Z_STREAM_ERROR;
  18993. }
  18994. var wrap = 1;
  18995. if (level === Z_DEFAULT_COMPRESSION) {
  18996. level = 6;
  18997. }
  18998. if (windowBits < 0) { /* suppress zlib wrapper */
  18999. wrap = 0;
  19000. windowBits = -windowBits;
  19001. }
  19002. else if (windowBits > 15) {
  19003. wrap = 2; /* write gzip wrapper instead */
  19004. windowBits -= 16;
  19005. }
  19006. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  19007. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  19008. strategy < 0 || strategy > Z_FIXED) {
  19009. return err(strm, Z_STREAM_ERROR);
  19010. }
  19011. if (windowBits === 8) {
  19012. windowBits = 9;
  19013. }
  19014. /* until 256-byte window bug fixed */
  19015. var s = new DeflateState();
  19016. strm.state = s;
  19017. s.strm = strm;
  19018. s.wrap = wrap;
  19019. s.gzhead = null;
  19020. s.w_bits = windowBits;
  19021. s.w_size = 1 << s.w_bits;
  19022. s.w_mask = s.w_size - 1;
  19023. s.hash_bits = memLevel + 7;
  19024. s.hash_size = 1 << s.hash_bits;
  19025. s.hash_mask = s.hash_size - 1;
  19026. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  19027. s.window = new utils.Buf8(s.w_size * 2);
  19028. s.head = new utils.Buf16(s.hash_size);
  19029. s.prev = new utils.Buf16(s.w_size);
  19030. // Don't need mem init magic for JS.
  19031. //s.high_water = 0; /* nothing written to s->window yet */
  19032. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  19033. s.pending_buf_size = s.lit_bufsize * 4;
  19034. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  19035. s.d_buf = s.lit_bufsize >> 1;
  19036. s.l_buf = (1 + 2) * s.lit_bufsize;
  19037. s.level = level;
  19038. s.strategy = strategy;
  19039. s.method = method;
  19040. return deflateReset(strm);
  19041. }
  19042. function deflateInit(strm, level) {
  19043. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  19044. }
  19045. function deflate(strm, flush) {
  19046. var old_flush, s;
  19047. var beg, val; // for gzip header write only
  19048. if (!strm || !strm.state ||
  19049. flush > Z_BLOCK || flush < 0) {
  19050. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  19051. }
  19052. s = strm.state;
  19053. if (!strm.output ||
  19054. (!strm.input && strm.avail_in !== 0) ||
  19055. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  19056. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  19057. }
  19058. s.strm = strm; /* just in case */
  19059. old_flush = s.last_flush;
  19060. s.last_flush = flush;
  19061. /* Write the header */
  19062. if (s.status === INIT_STATE) {
  19063. if (s.wrap === 2) { // GZIP header
  19064. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19065. put_byte(s, 31);
  19066. put_byte(s, 139);
  19067. put_byte(s, 8);
  19068. if (!s.gzhead) { // s->gzhead == Z_NULL
  19069. put_byte(s, 0);
  19070. put_byte(s, 0);
  19071. put_byte(s, 0);
  19072. put_byte(s, 0);
  19073. put_byte(s, 0);
  19074. put_byte(s, s.level === 9 ? 2 :
  19075. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  19076. 4 : 0));
  19077. put_byte(s, OS_CODE);
  19078. s.status = BUSY_STATE;
  19079. }
  19080. else {
  19081. put_byte(s, (s.gzhead.text ? 1 : 0) +
  19082. (s.gzhead.hcrc ? 2 : 0) +
  19083. (!s.gzhead.extra ? 0 : 4) +
  19084. (!s.gzhead.name ? 0 : 8) +
  19085. (!s.gzhead.comment ? 0 : 16)
  19086. );
  19087. put_byte(s, s.gzhead.time & 0xff);
  19088. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  19089. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  19090. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  19091. put_byte(s, s.level === 9 ? 2 :
  19092. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  19093. 4 : 0));
  19094. put_byte(s, s.gzhead.os & 0xff);
  19095. if (s.gzhead.extra && s.gzhead.extra.length) {
  19096. put_byte(s, s.gzhead.extra.length & 0xff);
  19097. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  19098. }
  19099. if (s.gzhead.hcrc) {
  19100. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  19101. }
  19102. s.gzindex = 0;
  19103. s.status = EXTRA_STATE;
  19104. }
  19105. }
  19106. else // DEFLATE header
  19107. {
  19108. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  19109. var level_flags = -1;
  19110. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  19111. level_flags = 0;
  19112. } else if (s.level < 6) {
  19113. level_flags = 1;
  19114. } else if (s.level === 6) {
  19115. level_flags = 2;
  19116. } else {
  19117. level_flags = 3;
  19118. }
  19119. header |= (level_flags << 6);
  19120. if (s.strstart !== 0) { header |= PRESET_DICT; }
  19121. header += 31 - (header % 31);
  19122. s.status = BUSY_STATE;
  19123. putShortMSB(s, header);
  19124. /* Save the adler32 of the preset dictionary: */
  19125. if (s.strstart !== 0) {
  19126. putShortMSB(s, strm.adler >>> 16);
  19127. putShortMSB(s, strm.adler & 0xffff);
  19128. }
  19129. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  19130. }
  19131. }
  19132. //#ifdef GZIP
  19133. if (s.status === EXTRA_STATE) {
  19134. if (s.gzhead.extra/* != Z_NULL*/) {
  19135. beg = s.pending; /* start of bytes to update crc */
  19136. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  19137. if (s.pending === s.pending_buf_size) {
  19138. if (s.gzhead.hcrc && s.pending > beg) {
  19139. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19140. }
  19141. flush_pending(strm);
  19142. beg = s.pending;
  19143. if (s.pending === s.pending_buf_size) {
  19144. break;
  19145. }
  19146. }
  19147. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  19148. s.gzindex++;
  19149. }
  19150. if (s.gzhead.hcrc && s.pending > beg) {
  19151. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19152. }
  19153. if (s.gzindex === s.gzhead.extra.length) {
  19154. s.gzindex = 0;
  19155. s.status = NAME_STATE;
  19156. }
  19157. }
  19158. else {
  19159. s.status = NAME_STATE;
  19160. }
  19161. }
  19162. if (s.status === NAME_STATE) {
  19163. if (s.gzhead.name/* != Z_NULL*/) {
  19164. beg = s.pending; /* start of bytes to update crc */
  19165. //int val;
  19166. do {
  19167. if (s.pending === s.pending_buf_size) {
  19168. if (s.gzhead.hcrc && s.pending > beg) {
  19169. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19170. }
  19171. flush_pending(strm);
  19172. beg = s.pending;
  19173. if (s.pending === s.pending_buf_size) {
  19174. val = 1;
  19175. break;
  19176. }
  19177. }
  19178. // JS specific: little magic to add zero terminator to end of string
  19179. if (s.gzindex < s.gzhead.name.length) {
  19180. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  19181. } else {
  19182. val = 0;
  19183. }
  19184. put_byte(s, val);
  19185. } while (val !== 0);
  19186. if (s.gzhead.hcrc && s.pending > beg){
  19187. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19188. }
  19189. if (val === 0) {
  19190. s.gzindex = 0;
  19191. s.status = COMMENT_STATE;
  19192. }
  19193. }
  19194. else {
  19195. s.status = COMMENT_STATE;
  19196. }
  19197. }
  19198. if (s.status === COMMENT_STATE) {
  19199. if (s.gzhead.comment/* != Z_NULL*/) {
  19200. beg = s.pending; /* start of bytes to update crc */
  19201. //int val;
  19202. do {
  19203. if (s.pending === s.pending_buf_size) {
  19204. if (s.gzhead.hcrc && s.pending > beg) {
  19205. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19206. }
  19207. flush_pending(strm);
  19208. beg = s.pending;
  19209. if (s.pending === s.pending_buf_size) {
  19210. val = 1;
  19211. break;
  19212. }
  19213. }
  19214. // JS specific: little magic to add zero terminator to end of string
  19215. if (s.gzindex < s.gzhead.comment.length) {
  19216. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  19217. } else {
  19218. val = 0;
  19219. }
  19220. put_byte(s, val);
  19221. } while (val !== 0);
  19222. if (s.gzhead.hcrc && s.pending > beg) {
  19223. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19224. }
  19225. if (val === 0) {
  19226. s.status = HCRC_STATE;
  19227. }
  19228. }
  19229. else {
  19230. s.status = HCRC_STATE;
  19231. }
  19232. }
  19233. if (s.status === HCRC_STATE) {
  19234. if (s.gzhead.hcrc) {
  19235. if (s.pending + 2 > s.pending_buf_size) {
  19236. flush_pending(strm);
  19237. }
  19238. if (s.pending + 2 <= s.pending_buf_size) {
  19239. put_byte(s, strm.adler & 0xff);
  19240. put_byte(s, (strm.adler >> 8) & 0xff);
  19241. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19242. s.status = BUSY_STATE;
  19243. }
  19244. }
  19245. else {
  19246. s.status = BUSY_STATE;
  19247. }
  19248. }
  19249. //#endif
  19250. /* Flush as much pending output as possible */
  19251. if (s.pending !== 0) {
  19252. flush_pending(strm);
  19253. if (strm.avail_out === 0) {
  19254. /* Since avail_out is 0, deflate will be called again with
  19255. * more output space, but possibly with both pending and
  19256. * avail_in equal to zero. There won't be anything to do,
  19257. * but this is not an error situation so make sure we
  19258. * return OK instead of BUF_ERROR at next call of deflate:
  19259. */
  19260. s.last_flush = -1;
  19261. return Z_OK;
  19262. }
  19263. /* Make sure there is something to do and avoid duplicate consecutive
  19264. * flushes. For repeated and useless calls with Z_FINISH, we keep
  19265. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  19266. */
  19267. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  19268. flush !== Z_FINISH) {
  19269. return err(strm, Z_BUF_ERROR);
  19270. }
  19271. /* User must not provide more input after the first FINISH: */
  19272. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  19273. return err(strm, Z_BUF_ERROR);
  19274. }
  19275. /* Start a new block or continue the current one.
  19276. */
  19277. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  19278. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  19279. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  19280. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  19281. configuration_table[s.level].func(s, flush));
  19282. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  19283. s.status = FINISH_STATE;
  19284. }
  19285. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  19286. if (strm.avail_out === 0) {
  19287. s.last_flush = -1;
  19288. /* avoid BUF_ERROR next call, see above */
  19289. }
  19290. return Z_OK;
  19291. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  19292. * of deflate should use the same flush parameter to make sure
  19293. * that the flush is complete. So we don't have to output an
  19294. * empty block here, this will be done at next call. This also
  19295. * ensures that for a very small output buffer, we emit at most
  19296. * one empty block.
  19297. */
  19298. }
  19299. if (bstate === BS_BLOCK_DONE) {
  19300. if (flush === Z_PARTIAL_FLUSH) {
  19301. trees._tr_align(s);
  19302. }
  19303. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  19304. trees._tr_stored_block(s, 0, 0, false);
  19305. /* For a full flush, this empty block will be recognized
  19306. * as a special marker by inflate_sync().
  19307. */
  19308. if (flush === Z_FULL_FLUSH) {
  19309. /*** CLEAR_HASH(s); ***/ /* forget history */
  19310. zero(s.head); // Fill with NIL (= 0);
  19311. if (s.lookahead === 0) {
  19312. s.strstart = 0;
  19313. s.block_start = 0;
  19314. s.insert = 0;
  19315. }
  19316. }
  19317. }
  19318. flush_pending(strm);
  19319. if (strm.avail_out === 0) {
  19320. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  19321. return Z_OK;
  19322. }
  19323. }
  19324. }
  19325. //Assert(strm->avail_out > 0, "bug2");
  19326. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  19327. if (flush !== Z_FINISH) { return Z_OK; }
  19328. if (s.wrap <= 0) { return Z_STREAM_END; }
  19329. /* Write the trailer */
  19330. if (s.wrap === 2) {
  19331. put_byte(s, strm.adler & 0xff);
  19332. put_byte(s, (strm.adler >> 8) & 0xff);
  19333. put_byte(s, (strm.adler >> 16) & 0xff);
  19334. put_byte(s, (strm.adler >> 24) & 0xff);
  19335. put_byte(s, strm.total_in & 0xff);
  19336. put_byte(s, (strm.total_in >> 8) & 0xff);
  19337. put_byte(s, (strm.total_in >> 16) & 0xff);
  19338. put_byte(s, (strm.total_in >> 24) & 0xff);
  19339. }
  19340. else
  19341. {
  19342. putShortMSB(s, strm.adler >>> 16);
  19343. putShortMSB(s, strm.adler & 0xffff);
  19344. }
  19345. flush_pending(strm);
  19346. /* If avail_out is zero, the application will call deflate again
  19347. * to flush the rest.
  19348. */
  19349. if (s.wrap > 0) { s.wrap = -s.wrap; }
  19350. /* write the trailer only once! */
  19351. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  19352. }
  19353. function deflateEnd(strm) {
  19354. var status;
  19355. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  19356. return Z_STREAM_ERROR;
  19357. }
  19358. status = strm.state.status;
  19359. if (status !== INIT_STATE &&
  19360. status !== EXTRA_STATE &&
  19361. status !== NAME_STATE &&
  19362. status !== COMMENT_STATE &&
  19363. status !== HCRC_STATE &&
  19364. status !== BUSY_STATE &&
  19365. status !== FINISH_STATE
  19366. ) {
  19367. return err(strm, Z_STREAM_ERROR);
  19368. }
  19369. strm.state = null;
  19370. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  19371. }
  19372. /* =========================================================================
  19373. * Copy the source state to the destination state
  19374. */
  19375. //function deflateCopy(dest, source) {
  19376. //
  19377. //}
  19378. exports.deflateInit = deflateInit;
  19379. exports.deflateInit2 = deflateInit2;
  19380. exports.deflateReset = deflateReset;
  19381. exports.deflateResetKeep = deflateResetKeep;
  19382. exports.deflateSetHeader = deflateSetHeader;
  19383. exports.deflate = deflate;
  19384. exports.deflateEnd = deflateEnd;
  19385. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  19386. /* Not implemented
  19387. exports.deflateBound = deflateBound;
  19388. exports.deflateCopy = deflateCopy;
  19389. exports.deflateSetDictionary = deflateSetDictionary;
  19390. exports.deflateParams = deflateParams;
  19391. exports.deflatePending = deflatePending;
  19392. exports.deflatePrime = deflatePrime;
  19393. exports.deflateTune = deflateTune;
  19394. */
  19395. },{"../utils/common":66,"./adler32":68,"./crc32":70,"./messages":76,"./trees":77}],72:[function(require,module,exports){
  19396. 'use strict';
  19397. function GZheader() {
  19398. /* true if compressed data believed to be text */
  19399. this.text = 0;
  19400. /* modification time */
  19401. this.time = 0;
  19402. /* extra flags (not used when writing a gzip file) */
  19403. this.xflags = 0;
  19404. /* operating system */
  19405. this.os = 0;
  19406. /* pointer to extra field or Z_NULL if none */
  19407. this.extra = null;
  19408. /* extra field length (valid if extra != Z_NULL) */
  19409. this.extra_len = 0; // Actually, we don't need it in JS,
  19410. // but leave for few code modifications
  19411. //
  19412. // Setup limits is not necessary because in js we should not preallocate memory
  19413. // for inflate use constant limit in 65536 bytes
  19414. //
  19415. /* space at extra (only when reading header) */
  19416. // this.extra_max = 0;
  19417. /* pointer to zero-terminated file name or Z_NULL */
  19418. this.name = '';
  19419. /* space at name (only when reading header) */
  19420. // this.name_max = 0;
  19421. /* pointer to zero-terminated comment or Z_NULL */
  19422. this.comment = '';
  19423. /* space at comment (only when reading header) */
  19424. // this.comm_max = 0;
  19425. /* true if there was or will be a header crc */
  19426. this.hcrc = 0;
  19427. /* true when done reading gzip header (not used when writing a gzip file) */
  19428. this.done = false;
  19429. }
  19430. module.exports = GZheader;
  19431. },{}],73:[function(require,module,exports){
  19432. 'use strict';
  19433. // See state defs from inflate.js
  19434. var BAD = 30; /* got a data error -- remain here until reset */
  19435. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19436. /*
  19437. Decode literal, length, and distance codes and write out the resulting
  19438. literal and match bytes until either not enough input or output is
  19439. available, an end-of-block is encountered, or a data error is encountered.
  19440. When large enough input and output buffers are supplied to inflate(), for
  19441. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  19442. inflate execution time is spent in this routine.
  19443. Entry assumptions:
  19444. state.mode === LEN
  19445. strm.avail_in >= 6
  19446. strm.avail_out >= 258
  19447. start >= strm.avail_out
  19448. state.bits < 8
  19449. On return, state.mode is one of:
  19450. LEN -- ran out of enough output space or enough available input
  19451. TYPE -- reached end of block code, inflate() to interpret next block
  19452. BAD -- error in block data
  19453. Notes:
  19454. - The maximum input bits used by a length/distance pair is 15 bits for the
  19455. length code, 5 bits for the length extra, 15 bits for the distance code,
  19456. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  19457. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  19458. checking for available input while decoding.
  19459. - The maximum bytes that a single length/distance pair can output is 258
  19460. bytes, which is the maximum length that can be coded. inflate_fast()
  19461. requires strm.avail_out >= 258 for each loop to avoid checking for
  19462. output space.
  19463. */
  19464. module.exports = function inflate_fast(strm, start) {
  19465. var state;
  19466. var _in; /* local strm.input */
  19467. var last; /* have enough input while in < last */
  19468. var _out; /* local strm.output */
  19469. var beg; /* inflate()'s initial strm.output */
  19470. var end; /* while out < end, enough space available */
  19471. //#ifdef INFLATE_STRICT
  19472. var dmax; /* maximum distance from zlib header */
  19473. //#endif
  19474. var wsize; /* window size or zero if not using window */
  19475. var whave; /* valid bytes in the window */
  19476. var wnext; /* window write index */
  19477. var window; /* allocated sliding window, if wsize != 0 */
  19478. var hold; /* local strm.hold */
  19479. var bits; /* local strm.bits */
  19480. var lcode; /* local strm.lencode */
  19481. var dcode; /* local strm.distcode */
  19482. var lmask; /* mask for first level of length codes */
  19483. var dmask; /* mask for first level of distance codes */
  19484. var here; /* retrieved table entry */
  19485. var op; /* code bits, operation, extra bits, or */
  19486. /* window position, window bytes to copy */
  19487. var len; /* match length, unused bytes */
  19488. var dist; /* match distance */
  19489. var from; /* where to copy match from */
  19490. var from_source;
  19491. var input, output; // JS specific, because we have no pointers
  19492. /* copy state to local variables */
  19493. state = strm.state;
  19494. //here = state.here;
  19495. _in = strm.next_in;
  19496. input = strm.input;
  19497. last = _in + (strm.avail_in - 5);
  19498. _out = strm.next_out;
  19499. output = strm.output;
  19500. beg = _out - (start - strm.avail_out);
  19501. end = _out + (strm.avail_out - 257);
  19502. //#ifdef INFLATE_STRICT
  19503. dmax = state.dmax;
  19504. //#endif
  19505. wsize = state.wsize;
  19506. whave = state.whave;
  19507. wnext = state.wnext;
  19508. window = state.window;
  19509. hold = state.hold;
  19510. bits = state.bits;
  19511. lcode = state.lencode;
  19512. dcode = state.distcode;
  19513. lmask = (1 << state.lenbits) - 1;
  19514. dmask = (1 << state.distbits) - 1;
  19515. /* decode literals and length/distances until end-of-block or not enough
  19516. input data or output space */
  19517. top:
  19518. do {
  19519. if (bits < 15) {
  19520. hold += input[_in++] << bits;
  19521. bits += 8;
  19522. hold += input[_in++] << bits;
  19523. bits += 8;
  19524. }
  19525. here = lcode[hold & lmask];
  19526. dolen:
  19527. for (;;) { // Goto emulation
  19528. op = here >>> 24/*here.bits*/;
  19529. hold >>>= op;
  19530. bits -= op;
  19531. op = (here >>> 16) & 0xff/*here.op*/;
  19532. if (op === 0) { /* literal */
  19533. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  19534. // "inflate: literal '%c'\n" :
  19535. // "inflate: literal 0x%02x\n", here.val));
  19536. output[_out++] = here & 0xffff/*here.val*/;
  19537. }
  19538. else if (op & 16) { /* length base */
  19539. len = here & 0xffff/*here.val*/;
  19540. op &= 15; /* number of extra bits */
  19541. if (op) {
  19542. if (bits < op) {
  19543. hold += input[_in++] << bits;
  19544. bits += 8;
  19545. }
  19546. len += hold & ((1 << op) - 1);
  19547. hold >>>= op;
  19548. bits -= op;
  19549. }
  19550. //Tracevv((stderr, "inflate: length %u\n", len));
  19551. if (bits < 15) {
  19552. hold += input[_in++] << bits;
  19553. bits += 8;
  19554. hold += input[_in++] << bits;
  19555. bits += 8;
  19556. }
  19557. here = dcode[hold & dmask];
  19558. dodist:
  19559. for (;;) { // goto emulation
  19560. op = here >>> 24/*here.bits*/;
  19561. hold >>>= op;
  19562. bits -= op;
  19563. op = (here >>> 16) & 0xff/*here.op*/;
  19564. if (op & 16) { /* distance base */
  19565. dist = here & 0xffff/*here.val*/;
  19566. op &= 15; /* number of extra bits */
  19567. if (bits < op) {
  19568. hold += input[_in++] << bits;
  19569. bits += 8;
  19570. if (bits < op) {
  19571. hold += input[_in++] << bits;
  19572. bits += 8;
  19573. }
  19574. }
  19575. dist += hold & ((1 << op) - 1);
  19576. //#ifdef INFLATE_STRICT
  19577. if (dist > dmax) {
  19578. strm.msg = 'invalid distance too far back';
  19579. state.mode = BAD;
  19580. break top;
  19581. }
  19582. //#endif
  19583. hold >>>= op;
  19584. bits -= op;
  19585. //Tracevv((stderr, "inflate: distance %u\n", dist));
  19586. op = _out - beg; /* max distance in output */
  19587. if (dist > op) { /* see if copy from window */
  19588. op = dist - op; /* distance back in window */
  19589. if (op > whave) {
  19590. if (state.sane) {
  19591. strm.msg = 'invalid distance too far back';
  19592. state.mode = BAD;
  19593. break top;
  19594. }
  19595. // (!) This block is disabled in zlib defailts,
  19596. // don't enable it for binary compatibility
  19597. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  19598. // if (len <= op - whave) {
  19599. // do {
  19600. // output[_out++] = 0;
  19601. // } while (--len);
  19602. // continue top;
  19603. // }
  19604. // len -= op - whave;
  19605. // do {
  19606. // output[_out++] = 0;
  19607. // } while (--op > whave);
  19608. // if (op === 0) {
  19609. // from = _out - dist;
  19610. // do {
  19611. // output[_out++] = output[from++];
  19612. // } while (--len);
  19613. // continue top;
  19614. // }
  19615. //#endif
  19616. }
  19617. from = 0; // window index
  19618. from_source = window;
  19619. if (wnext === 0) { /* very common case */
  19620. from += wsize - op;
  19621. if (op < len) { /* some from window */
  19622. len -= op;
  19623. do {
  19624. output[_out++] = window[from++];
  19625. } while (--op);
  19626. from = _out - dist; /* rest from output */
  19627. from_source = output;
  19628. }
  19629. }
  19630. else if (wnext < op) { /* wrap around window */
  19631. from += wsize + wnext - op;
  19632. op -= wnext;
  19633. if (op < len) { /* some from end of window */
  19634. len -= op;
  19635. do {
  19636. output[_out++] = window[from++];
  19637. } while (--op);
  19638. from = 0;
  19639. if (wnext < len) { /* some from start of window */
  19640. op = wnext;
  19641. len -= op;
  19642. do {
  19643. output[_out++] = window[from++];
  19644. } while (--op);
  19645. from = _out - dist; /* rest from output */
  19646. from_source = output;
  19647. }
  19648. }
  19649. }
  19650. else { /* contiguous in window */
  19651. from += wnext - op;
  19652. if (op < len) { /* some from window */
  19653. len -= op;
  19654. do {
  19655. output[_out++] = window[from++];
  19656. } while (--op);
  19657. from = _out - dist; /* rest from output */
  19658. from_source = output;
  19659. }
  19660. }
  19661. while (len > 2) {
  19662. output[_out++] = from_source[from++];
  19663. output[_out++] = from_source[from++];
  19664. output[_out++] = from_source[from++];
  19665. len -= 3;
  19666. }
  19667. if (len) {
  19668. output[_out++] = from_source[from++];
  19669. if (len > 1) {
  19670. output[_out++] = from_source[from++];
  19671. }
  19672. }
  19673. }
  19674. else {
  19675. from = _out - dist; /* copy direct from output */
  19676. do { /* minimum length is three */
  19677. output[_out++] = output[from++];
  19678. output[_out++] = output[from++];
  19679. output[_out++] = output[from++];
  19680. len -= 3;
  19681. } while (len > 2);
  19682. if (len) {
  19683. output[_out++] = output[from++];
  19684. if (len > 1) {
  19685. output[_out++] = output[from++];
  19686. }
  19687. }
  19688. }
  19689. }
  19690. else if ((op & 64) === 0) { /* 2nd level distance code */
  19691. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19692. continue dodist;
  19693. }
  19694. else {
  19695. strm.msg = 'invalid distance code';
  19696. state.mode = BAD;
  19697. break top;
  19698. }
  19699. break; // need to emulate goto via "continue"
  19700. }
  19701. }
  19702. else if ((op & 64) === 0) { /* 2nd level length code */
  19703. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19704. continue dolen;
  19705. }
  19706. else if (op & 32) { /* end-of-block */
  19707. //Tracevv((stderr, "inflate: end of block\n"));
  19708. state.mode = TYPE;
  19709. break top;
  19710. }
  19711. else {
  19712. strm.msg = 'invalid literal/length code';
  19713. state.mode = BAD;
  19714. break top;
  19715. }
  19716. break; // need to emulate goto via "continue"
  19717. }
  19718. } while (_in < last && _out < end);
  19719. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  19720. len = bits >> 3;
  19721. _in -= len;
  19722. bits -= len << 3;
  19723. hold &= (1 << bits) - 1;
  19724. /* update state and return */
  19725. strm.next_in = _in;
  19726. strm.next_out = _out;
  19727. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  19728. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  19729. state.hold = hold;
  19730. state.bits = bits;
  19731. return;
  19732. };
  19733. },{}],74:[function(require,module,exports){
  19734. 'use strict';
  19735. var utils = require('../utils/common');
  19736. var adler32 = require('./adler32');
  19737. var crc32 = require('./crc32');
  19738. var inflate_fast = require('./inffast');
  19739. var inflate_table = require('./inftrees');
  19740. var CODES = 0;
  19741. var LENS = 1;
  19742. var DISTS = 2;
  19743. /* Public constants ==========================================================*/
  19744. /* ===========================================================================*/
  19745. /* Allowed flush values; see deflate() and inflate() below for details */
  19746. //var Z_NO_FLUSH = 0;
  19747. //var Z_PARTIAL_FLUSH = 1;
  19748. //var Z_SYNC_FLUSH = 2;
  19749. //var Z_FULL_FLUSH = 3;
  19750. var Z_FINISH = 4;
  19751. var Z_BLOCK = 5;
  19752. var Z_TREES = 6;
  19753. /* Return codes for the compression/decompression functions. Negative values
  19754. * are errors, positive values are used for special but normal events.
  19755. */
  19756. var Z_OK = 0;
  19757. var Z_STREAM_END = 1;
  19758. var Z_NEED_DICT = 2;
  19759. //var Z_ERRNO = -1;
  19760. var Z_STREAM_ERROR = -2;
  19761. var Z_DATA_ERROR = -3;
  19762. var Z_MEM_ERROR = -4;
  19763. var Z_BUF_ERROR = -5;
  19764. //var Z_VERSION_ERROR = -6;
  19765. /* The deflate compression method */
  19766. var Z_DEFLATED = 8;
  19767. /* STATES ====================================================================*/
  19768. /* ===========================================================================*/
  19769. var HEAD = 1; /* i: waiting for magic header */
  19770. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  19771. var TIME = 3; /* i: waiting for modification time (gzip) */
  19772. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  19773. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  19774. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  19775. var NAME = 7; /* i: waiting for end of file name (gzip) */
  19776. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  19777. var HCRC = 9; /* i: waiting for header crc (gzip) */
  19778. var DICTID = 10; /* i: waiting for dictionary check value */
  19779. var DICT = 11; /* waiting for inflateSetDictionary() call */
  19780. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19781. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  19782. var STORED = 14; /* i: waiting for stored size (length and complement) */
  19783. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  19784. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  19785. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  19786. var LENLENS = 18; /* i: waiting for code length code lengths */
  19787. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  19788. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  19789. var LEN = 21; /* i: waiting for length/lit/eob code */
  19790. var LENEXT = 22; /* i: waiting for length extra bits */
  19791. var DIST = 23; /* i: waiting for distance code */
  19792. var DISTEXT = 24; /* i: waiting for distance extra bits */
  19793. var MATCH = 25; /* o: waiting for output space to copy string */
  19794. var LIT = 26; /* o: waiting for output space to write literal */
  19795. var CHECK = 27; /* i: waiting for 32-bit check value */
  19796. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  19797. var DONE = 29; /* finished check, done -- remain here until reset */
  19798. var BAD = 30; /* got a data error -- remain here until reset */
  19799. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  19800. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  19801. /* ===========================================================================*/
  19802. var ENOUGH_LENS = 852;
  19803. var ENOUGH_DISTS = 592;
  19804. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  19805. var MAX_WBITS = 15;
  19806. /* 32K LZ77 window */
  19807. var DEF_WBITS = MAX_WBITS;
  19808. function ZSWAP32(q) {
  19809. return (((q >>> 24) & 0xff) +
  19810. ((q >>> 8) & 0xff00) +
  19811. ((q & 0xff00) << 8) +
  19812. ((q & 0xff) << 24));
  19813. }
  19814. function InflateState() {
  19815. this.mode = 0; /* current inflate mode */
  19816. this.last = false; /* true if processing last block */
  19817. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  19818. this.havedict = false; /* true if dictionary provided */
  19819. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  19820. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  19821. this.check = 0; /* protected copy of check value */
  19822. this.total = 0; /* protected copy of output count */
  19823. // TODO: may be {}
  19824. this.head = null; /* where to save gzip header information */
  19825. /* sliding window */
  19826. this.wbits = 0; /* log base 2 of requested window size */
  19827. this.wsize = 0; /* window size or zero if not using window */
  19828. this.whave = 0; /* valid bytes in the window */
  19829. this.wnext = 0; /* window write index */
  19830. this.window = null; /* allocated sliding window, if needed */
  19831. /* bit accumulator */
  19832. this.hold = 0; /* input bit accumulator */
  19833. this.bits = 0; /* number of bits in "in" */
  19834. /* for string and stored block copying */
  19835. this.length = 0; /* literal or length of data to copy */
  19836. this.offset = 0; /* distance back to copy string from */
  19837. /* for table and code decoding */
  19838. this.extra = 0; /* extra bits needed */
  19839. /* fixed and dynamic code tables */
  19840. this.lencode = null; /* starting table for length/literal codes */
  19841. this.distcode = null; /* starting table for distance codes */
  19842. this.lenbits = 0; /* index bits for lencode */
  19843. this.distbits = 0; /* index bits for distcode */
  19844. /* dynamic table building */
  19845. this.ncode = 0; /* number of code length code lengths */
  19846. this.nlen = 0; /* number of length code lengths */
  19847. this.ndist = 0; /* number of distance code lengths */
  19848. this.have = 0; /* number of code lengths in lens[] */
  19849. this.next = null; /* next available space in codes[] */
  19850. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  19851. this.work = new utils.Buf16(288); /* work area for code table building */
  19852. /*
  19853. because we don't have pointers in js, we use lencode and distcode directly
  19854. as buffers so we don't need codes
  19855. */
  19856. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  19857. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  19858. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  19859. this.sane = 0; /* if false, allow invalid distance too far */
  19860. this.back = 0; /* bits back of last unprocessed length/lit */
  19861. this.was = 0; /* initial length of match */
  19862. }
  19863. function inflateResetKeep(strm) {
  19864. var state;
  19865. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19866. state = strm.state;
  19867. strm.total_in = strm.total_out = state.total = 0;
  19868. strm.msg = ''; /*Z_NULL*/
  19869. if (state.wrap) { /* to support ill-conceived Java test suite */
  19870. strm.adler = state.wrap & 1;
  19871. }
  19872. state.mode = HEAD;
  19873. state.last = 0;
  19874. state.havedict = 0;
  19875. state.dmax = 32768;
  19876. state.head = null/*Z_NULL*/;
  19877. state.hold = 0;
  19878. state.bits = 0;
  19879. //state.lencode = state.distcode = state.next = state.codes;
  19880. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  19881. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  19882. state.sane = 1;
  19883. state.back = -1;
  19884. //Tracev((stderr, "inflate: reset\n"));
  19885. return Z_OK;
  19886. }
  19887. function inflateReset(strm) {
  19888. var state;
  19889. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19890. state = strm.state;
  19891. state.wsize = 0;
  19892. state.whave = 0;
  19893. state.wnext = 0;
  19894. return inflateResetKeep(strm);
  19895. }
  19896. function inflateReset2(strm, windowBits) {
  19897. var wrap;
  19898. var state;
  19899. /* get the state */
  19900. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19901. state = strm.state;
  19902. /* extract wrap request from windowBits parameter */
  19903. if (windowBits < 0) {
  19904. wrap = 0;
  19905. windowBits = -windowBits;
  19906. }
  19907. else {
  19908. wrap = (windowBits >> 4) + 1;
  19909. if (windowBits < 48) {
  19910. windowBits &= 15;
  19911. }
  19912. }
  19913. /* set number of window bits, free window if different */
  19914. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  19915. return Z_STREAM_ERROR;
  19916. }
  19917. if (state.window !== null && state.wbits !== windowBits) {
  19918. state.window = null;
  19919. }
  19920. /* update state and reset the rest of it */
  19921. state.wrap = wrap;
  19922. state.wbits = windowBits;
  19923. return inflateReset(strm);
  19924. }
  19925. function inflateInit2(strm, windowBits) {
  19926. var ret;
  19927. var state;
  19928. if (!strm) { return Z_STREAM_ERROR; }
  19929. //strm.msg = Z_NULL; /* in case we return an error */
  19930. state = new InflateState();
  19931. //if (state === Z_NULL) return Z_MEM_ERROR;
  19932. //Tracev((stderr, "inflate: allocated\n"));
  19933. strm.state = state;
  19934. state.window = null/*Z_NULL*/;
  19935. ret = inflateReset2(strm, windowBits);
  19936. if (ret !== Z_OK) {
  19937. strm.state = null/*Z_NULL*/;
  19938. }
  19939. return ret;
  19940. }
  19941. function inflateInit(strm) {
  19942. return inflateInit2(strm, DEF_WBITS);
  19943. }
  19944. /*
  19945. Return state with length and distance decoding tables and index sizes set to
  19946. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  19947. If BUILDFIXED is defined, then instead this routine builds the tables the
  19948. first time it's called, and returns those tables the first time and
  19949. thereafter. This reduces the size of the code by about 2K bytes, in
  19950. exchange for a little execution time. However, BUILDFIXED should not be
  19951. used for threaded applications, since the rewriting of the tables and virgin
  19952. may not be thread-safe.
  19953. */
  19954. var virgin = true;
  19955. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  19956. function fixedtables(state) {
  19957. /* build fixed huffman tables if first call (may not be thread safe) */
  19958. if (virgin) {
  19959. var sym;
  19960. lenfix = new utils.Buf32(512);
  19961. distfix = new utils.Buf32(32);
  19962. /* literal/length table */
  19963. sym = 0;
  19964. while (sym < 144) { state.lens[sym++] = 8; }
  19965. while (sym < 256) { state.lens[sym++] = 9; }
  19966. while (sym < 280) { state.lens[sym++] = 7; }
  19967. while (sym < 288) { state.lens[sym++] = 8; }
  19968. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  19969. /* distance table */
  19970. sym = 0;
  19971. while (sym < 32) { state.lens[sym++] = 5; }
  19972. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  19973. /* do this just once */
  19974. virgin = false;
  19975. }
  19976. state.lencode = lenfix;
  19977. state.lenbits = 9;
  19978. state.distcode = distfix;
  19979. state.distbits = 5;
  19980. }
  19981. /*
  19982. Update the window with the last wsize (normally 32K) bytes written before
  19983. returning. If window does not exist yet, create it. This is only called
  19984. when a window is already in use, or when output has been written during this
  19985. inflate call, but the end of the deflate stream has not been reached yet.
  19986. It is also called to create a window for dictionary data when a dictionary
  19987. is loaded.
  19988. Providing output buffers larger than 32K to inflate() should provide a speed
  19989. advantage, since only the last 32K of output is copied to the sliding window
  19990. upon return from inflate(), and since all distances after the first 32K of
  19991. output will fall in the output data, making match copies simpler and faster.
  19992. The advantage may be dependent on the size of the processor's data caches.
  19993. */
  19994. function updatewindow(strm, src, end, copy) {
  19995. var dist;
  19996. var state = strm.state;
  19997. /* if it hasn't been done already, allocate space for the window */
  19998. if (state.window === null) {
  19999. state.wsize = 1 << state.wbits;
  20000. state.wnext = 0;
  20001. state.whave = 0;
  20002. state.window = new utils.Buf8(state.wsize);
  20003. }
  20004. /* copy state->wsize or less output bytes into the circular window */
  20005. if (copy >= state.wsize) {
  20006. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  20007. state.wnext = 0;
  20008. state.whave = state.wsize;
  20009. }
  20010. else {
  20011. dist = state.wsize - state.wnext;
  20012. if (dist > copy) {
  20013. dist = copy;
  20014. }
  20015. //zmemcpy(state->window + state->wnext, end - copy, dist);
  20016. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  20017. copy -= dist;
  20018. if (copy) {
  20019. //zmemcpy(state->window, end - copy, copy);
  20020. utils.arraySet(state.window,src, end - copy, copy, 0);
  20021. state.wnext = copy;
  20022. state.whave = state.wsize;
  20023. }
  20024. else {
  20025. state.wnext += dist;
  20026. if (state.wnext === state.wsize) { state.wnext = 0; }
  20027. if (state.whave < state.wsize) { state.whave += dist; }
  20028. }
  20029. }
  20030. return 0;
  20031. }
  20032. function inflate(strm, flush) {
  20033. var state;
  20034. var input, output; // input/output buffers
  20035. var next; /* next input INDEX */
  20036. var put; /* next output INDEX */
  20037. var have, left; /* available input and output */
  20038. var hold; /* bit buffer */
  20039. var bits; /* bits in bit buffer */
  20040. var _in, _out; /* save starting available input and output */
  20041. var copy; /* number of stored or match bytes to copy */
  20042. var from; /* where to copy match bytes from */
  20043. var from_source;
  20044. var here = 0; /* current decoding table entry */
  20045. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  20046. //var last; /* parent table entry */
  20047. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  20048. var len; /* length to copy for repeats, bits to drop */
  20049. var ret; /* return code */
  20050. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  20051. var opts;
  20052. var n; // temporary var for NEED_BITS
  20053. var order = /* permutation of code lengths */
  20054. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  20055. if (!strm || !strm.state || !strm.output ||
  20056. (!strm.input && strm.avail_in !== 0)) {
  20057. return Z_STREAM_ERROR;
  20058. }
  20059. state = strm.state;
  20060. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  20061. //--- LOAD() ---
  20062. put = strm.next_out;
  20063. output = strm.output;
  20064. left = strm.avail_out;
  20065. next = strm.next_in;
  20066. input = strm.input;
  20067. have = strm.avail_in;
  20068. hold = state.hold;
  20069. bits = state.bits;
  20070. //---
  20071. _in = have;
  20072. _out = left;
  20073. ret = Z_OK;
  20074. inf_leave: // goto emulation
  20075. for (;;) {
  20076. switch (state.mode) {
  20077. case HEAD:
  20078. if (state.wrap === 0) {
  20079. state.mode = TYPEDO;
  20080. break;
  20081. }
  20082. //=== NEEDBITS(16);
  20083. while (bits < 16) {
  20084. if (have === 0) { break inf_leave; }
  20085. have--;
  20086. hold += input[next++] << bits;
  20087. bits += 8;
  20088. }
  20089. //===//
  20090. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  20091. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  20092. //=== CRC2(state.check, hold);
  20093. hbuf[0] = hold & 0xff;
  20094. hbuf[1] = (hold >>> 8) & 0xff;
  20095. state.check = crc32(state.check, hbuf, 2, 0);
  20096. //===//
  20097. //=== INITBITS();
  20098. hold = 0;
  20099. bits = 0;
  20100. //===//
  20101. state.mode = FLAGS;
  20102. break;
  20103. }
  20104. state.flags = 0; /* expect zlib header */
  20105. if (state.head) {
  20106. state.head.done = false;
  20107. }
  20108. if (!(state.wrap & 1) || /* check if zlib header allowed */
  20109. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  20110. strm.msg = 'incorrect header check';
  20111. state.mode = BAD;
  20112. break;
  20113. }
  20114. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  20115. strm.msg = 'unknown compression method';
  20116. state.mode = BAD;
  20117. break;
  20118. }
  20119. //--- DROPBITS(4) ---//
  20120. hold >>>= 4;
  20121. bits -= 4;
  20122. //---//
  20123. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  20124. if (state.wbits === 0) {
  20125. state.wbits = len;
  20126. }
  20127. else if (len > state.wbits) {
  20128. strm.msg = 'invalid window size';
  20129. state.mode = BAD;
  20130. break;
  20131. }
  20132. state.dmax = 1 << len;
  20133. //Tracev((stderr, "inflate: zlib header ok\n"));
  20134. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20135. state.mode = hold & 0x200 ? DICTID : TYPE;
  20136. //=== INITBITS();
  20137. hold = 0;
  20138. bits = 0;
  20139. //===//
  20140. break;
  20141. case FLAGS:
  20142. //=== NEEDBITS(16); */
  20143. while (bits < 16) {
  20144. if (have === 0) { break inf_leave; }
  20145. have--;
  20146. hold += input[next++] << bits;
  20147. bits += 8;
  20148. }
  20149. //===//
  20150. state.flags = hold;
  20151. if ((state.flags & 0xff) !== Z_DEFLATED) {
  20152. strm.msg = 'unknown compression method';
  20153. state.mode = BAD;
  20154. break;
  20155. }
  20156. if (state.flags & 0xe000) {
  20157. strm.msg = 'unknown header flags set';
  20158. state.mode = BAD;
  20159. break;
  20160. }
  20161. if (state.head) {
  20162. state.head.text = ((hold >> 8) & 1);
  20163. }
  20164. if (state.flags & 0x0200) {
  20165. //=== CRC2(state.check, hold);
  20166. hbuf[0] = hold & 0xff;
  20167. hbuf[1] = (hold >>> 8) & 0xff;
  20168. state.check = crc32(state.check, hbuf, 2, 0);
  20169. //===//
  20170. }
  20171. //=== INITBITS();
  20172. hold = 0;
  20173. bits = 0;
  20174. //===//
  20175. state.mode = TIME;
  20176. /* falls through */
  20177. case TIME:
  20178. //=== NEEDBITS(32); */
  20179. while (bits < 32) {
  20180. if (have === 0) { break inf_leave; }
  20181. have--;
  20182. hold += input[next++] << bits;
  20183. bits += 8;
  20184. }
  20185. //===//
  20186. if (state.head) {
  20187. state.head.time = hold;
  20188. }
  20189. if (state.flags & 0x0200) {
  20190. //=== CRC4(state.check, hold)
  20191. hbuf[0] = hold & 0xff;
  20192. hbuf[1] = (hold >>> 8) & 0xff;
  20193. hbuf[2] = (hold >>> 16) & 0xff;
  20194. hbuf[3] = (hold >>> 24) & 0xff;
  20195. state.check = crc32(state.check, hbuf, 4, 0);
  20196. //===
  20197. }
  20198. //=== INITBITS();
  20199. hold = 0;
  20200. bits = 0;
  20201. //===//
  20202. state.mode = OS;
  20203. /* falls through */
  20204. case OS:
  20205. //=== NEEDBITS(16); */
  20206. while (bits < 16) {
  20207. if (have === 0) { break inf_leave; }
  20208. have--;
  20209. hold += input[next++] << bits;
  20210. bits += 8;
  20211. }
  20212. //===//
  20213. if (state.head) {
  20214. state.head.xflags = (hold & 0xff);
  20215. state.head.os = (hold >> 8);
  20216. }
  20217. if (state.flags & 0x0200) {
  20218. //=== CRC2(state.check, hold);
  20219. hbuf[0] = hold & 0xff;
  20220. hbuf[1] = (hold >>> 8) & 0xff;
  20221. state.check = crc32(state.check, hbuf, 2, 0);
  20222. //===//
  20223. }
  20224. //=== INITBITS();
  20225. hold = 0;
  20226. bits = 0;
  20227. //===//
  20228. state.mode = EXLEN;
  20229. /* falls through */
  20230. case EXLEN:
  20231. if (state.flags & 0x0400) {
  20232. //=== NEEDBITS(16); */
  20233. while (bits < 16) {
  20234. if (have === 0) { break inf_leave; }
  20235. have--;
  20236. hold += input[next++] << bits;
  20237. bits += 8;
  20238. }
  20239. //===//
  20240. state.length = hold;
  20241. if (state.head) {
  20242. state.head.extra_len = hold;
  20243. }
  20244. if (state.flags & 0x0200) {
  20245. //=== CRC2(state.check, hold);
  20246. hbuf[0] = hold & 0xff;
  20247. hbuf[1] = (hold >>> 8) & 0xff;
  20248. state.check = crc32(state.check, hbuf, 2, 0);
  20249. //===//
  20250. }
  20251. //=== INITBITS();
  20252. hold = 0;
  20253. bits = 0;
  20254. //===//
  20255. }
  20256. else if (state.head) {
  20257. state.head.extra = null/*Z_NULL*/;
  20258. }
  20259. state.mode = EXTRA;
  20260. /* falls through */
  20261. case EXTRA:
  20262. if (state.flags & 0x0400) {
  20263. copy = state.length;
  20264. if (copy > have) { copy = have; }
  20265. if (copy) {
  20266. if (state.head) {
  20267. len = state.head.extra_len - state.length;
  20268. if (!state.head.extra) {
  20269. // Use untyped array for more conveniend processing later
  20270. state.head.extra = new Array(state.head.extra_len);
  20271. }
  20272. utils.arraySet(
  20273. state.head.extra,
  20274. input,
  20275. next,
  20276. // extra field is limited to 65536 bytes
  20277. // - no need for additional size check
  20278. copy,
  20279. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  20280. len
  20281. );
  20282. //zmemcpy(state.head.extra + len, next,
  20283. // len + copy > state.head.extra_max ?
  20284. // state.head.extra_max - len : copy);
  20285. }
  20286. if (state.flags & 0x0200) {
  20287. state.check = crc32(state.check, input, copy, next);
  20288. }
  20289. have -= copy;
  20290. next += copy;
  20291. state.length -= copy;
  20292. }
  20293. if (state.length) { break inf_leave; }
  20294. }
  20295. state.length = 0;
  20296. state.mode = NAME;
  20297. /* falls through */
  20298. case NAME:
  20299. if (state.flags & 0x0800) {
  20300. if (have === 0) { break inf_leave; }
  20301. copy = 0;
  20302. do {
  20303. // TODO: 2 or 1 bytes?
  20304. len = input[next + copy++];
  20305. /* use constant limit because in js we should not preallocate memory */
  20306. if (state.head && len &&
  20307. (state.length < 65536 /*state.head.name_max*/)) {
  20308. state.head.name += String.fromCharCode(len);
  20309. }
  20310. } while (len && copy < have);
  20311. if (state.flags & 0x0200) {
  20312. state.check = crc32(state.check, input, copy, next);
  20313. }
  20314. have -= copy;
  20315. next += copy;
  20316. if (len) { break inf_leave; }
  20317. }
  20318. else if (state.head) {
  20319. state.head.name = null;
  20320. }
  20321. state.length = 0;
  20322. state.mode = COMMENT;
  20323. /* falls through */
  20324. case COMMENT:
  20325. if (state.flags & 0x1000) {
  20326. if (have === 0) { break inf_leave; }
  20327. copy = 0;
  20328. do {
  20329. len = input[next + copy++];
  20330. /* use constant limit because in js we should not preallocate memory */
  20331. if (state.head && len &&
  20332. (state.length < 65536 /*state.head.comm_max*/)) {
  20333. state.head.comment += String.fromCharCode(len);
  20334. }
  20335. } while (len && copy < have);
  20336. if (state.flags & 0x0200) {
  20337. state.check = crc32(state.check, input, copy, next);
  20338. }
  20339. have -= copy;
  20340. next += copy;
  20341. if (len) { break inf_leave; }
  20342. }
  20343. else if (state.head) {
  20344. state.head.comment = null;
  20345. }
  20346. state.mode = HCRC;
  20347. /* falls through */
  20348. case HCRC:
  20349. if (state.flags & 0x0200) {
  20350. //=== NEEDBITS(16); */
  20351. while (bits < 16) {
  20352. if (have === 0) { break inf_leave; }
  20353. have--;
  20354. hold += input[next++] << bits;
  20355. bits += 8;
  20356. }
  20357. //===//
  20358. if (hold !== (state.check & 0xffff)) {
  20359. strm.msg = 'header crc mismatch';
  20360. state.mode = BAD;
  20361. break;
  20362. }
  20363. //=== INITBITS();
  20364. hold = 0;
  20365. bits = 0;
  20366. //===//
  20367. }
  20368. if (state.head) {
  20369. state.head.hcrc = ((state.flags >> 9) & 1);
  20370. state.head.done = true;
  20371. }
  20372. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  20373. state.mode = TYPE;
  20374. break;
  20375. case DICTID:
  20376. //=== NEEDBITS(32); */
  20377. while (bits < 32) {
  20378. if (have === 0) { break inf_leave; }
  20379. have--;
  20380. hold += input[next++] << bits;
  20381. bits += 8;
  20382. }
  20383. //===//
  20384. strm.adler = state.check = ZSWAP32(hold);
  20385. //=== INITBITS();
  20386. hold = 0;
  20387. bits = 0;
  20388. //===//
  20389. state.mode = DICT;
  20390. /* falls through */
  20391. case DICT:
  20392. if (state.havedict === 0) {
  20393. //--- RESTORE() ---
  20394. strm.next_out = put;
  20395. strm.avail_out = left;
  20396. strm.next_in = next;
  20397. strm.avail_in = have;
  20398. state.hold = hold;
  20399. state.bits = bits;
  20400. //---
  20401. return Z_NEED_DICT;
  20402. }
  20403. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20404. state.mode = TYPE;
  20405. /* falls through */
  20406. case TYPE:
  20407. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  20408. /* falls through */
  20409. case TYPEDO:
  20410. if (state.last) {
  20411. //--- BYTEBITS() ---//
  20412. hold >>>= bits & 7;
  20413. bits -= bits & 7;
  20414. //---//
  20415. state.mode = CHECK;
  20416. break;
  20417. }
  20418. //=== NEEDBITS(3); */
  20419. while (bits < 3) {
  20420. if (have === 0) { break inf_leave; }
  20421. have--;
  20422. hold += input[next++] << bits;
  20423. bits += 8;
  20424. }
  20425. //===//
  20426. state.last = (hold & 0x01)/*BITS(1)*/;
  20427. //--- DROPBITS(1) ---//
  20428. hold >>>= 1;
  20429. bits -= 1;
  20430. //---//
  20431. switch ((hold & 0x03)/*BITS(2)*/) {
  20432. case 0: /* stored block */
  20433. //Tracev((stderr, "inflate: stored block%s\n",
  20434. // state.last ? " (last)" : ""));
  20435. state.mode = STORED;
  20436. break;
  20437. case 1: /* fixed block */
  20438. fixedtables(state);
  20439. //Tracev((stderr, "inflate: fixed codes block%s\n",
  20440. // state.last ? " (last)" : ""));
  20441. state.mode = LEN_; /* decode codes */
  20442. if (flush === Z_TREES) {
  20443. //--- DROPBITS(2) ---//
  20444. hold >>>= 2;
  20445. bits -= 2;
  20446. //---//
  20447. break inf_leave;
  20448. }
  20449. break;
  20450. case 2: /* dynamic block */
  20451. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  20452. // state.last ? " (last)" : ""));
  20453. state.mode = TABLE;
  20454. break;
  20455. case 3:
  20456. strm.msg = 'invalid block type';
  20457. state.mode = BAD;
  20458. }
  20459. //--- DROPBITS(2) ---//
  20460. hold >>>= 2;
  20461. bits -= 2;
  20462. //---//
  20463. break;
  20464. case STORED:
  20465. //--- BYTEBITS() ---// /* go to byte boundary */
  20466. hold >>>= bits & 7;
  20467. bits -= bits & 7;
  20468. //---//
  20469. //=== NEEDBITS(32); */
  20470. while (bits < 32) {
  20471. if (have === 0) { break inf_leave; }
  20472. have--;
  20473. hold += input[next++] << bits;
  20474. bits += 8;
  20475. }
  20476. //===//
  20477. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  20478. strm.msg = 'invalid stored block lengths';
  20479. state.mode = BAD;
  20480. break;
  20481. }
  20482. state.length = hold & 0xffff;
  20483. //Tracev((stderr, "inflate: stored length %u\n",
  20484. // state.length));
  20485. //=== INITBITS();
  20486. hold = 0;
  20487. bits = 0;
  20488. //===//
  20489. state.mode = COPY_;
  20490. if (flush === Z_TREES) { break inf_leave; }
  20491. /* falls through */
  20492. case COPY_:
  20493. state.mode = COPY;
  20494. /* falls through */
  20495. case COPY:
  20496. copy = state.length;
  20497. if (copy) {
  20498. if (copy > have) { copy = have; }
  20499. if (copy > left) { copy = left; }
  20500. if (copy === 0) { break inf_leave; }
  20501. //--- zmemcpy(put, next, copy); ---
  20502. utils.arraySet(output, input, next, copy, put);
  20503. //---//
  20504. have -= copy;
  20505. next += copy;
  20506. left -= copy;
  20507. put += copy;
  20508. state.length -= copy;
  20509. break;
  20510. }
  20511. //Tracev((stderr, "inflate: stored end\n"));
  20512. state.mode = TYPE;
  20513. break;
  20514. case TABLE:
  20515. //=== NEEDBITS(14); */
  20516. while (bits < 14) {
  20517. if (have === 0) { break inf_leave; }
  20518. have--;
  20519. hold += input[next++] << bits;
  20520. bits += 8;
  20521. }
  20522. //===//
  20523. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  20524. //--- DROPBITS(5) ---//
  20525. hold >>>= 5;
  20526. bits -= 5;
  20527. //---//
  20528. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  20529. //--- DROPBITS(5) ---//
  20530. hold >>>= 5;
  20531. bits -= 5;
  20532. //---//
  20533. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  20534. //--- DROPBITS(4) ---//
  20535. hold >>>= 4;
  20536. bits -= 4;
  20537. //---//
  20538. //#ifndef PKZIP_BUG_WORKAROUND
  20539. if (state.nlen > 286 || state.ndist > 30) {
  20540. strm.msg = 'too many length or distance symbols';
  20541. state.mode = BAD;
  20542. break;
  20543. }
  20544. //#endif
  20545. //Tracev((stderr, "inflate: table sizes ok\n"));
  20546. state.have = 0;
  20547. state.mode = LENLENS;
  20548. /* falls through */
  20549. case LENLENS:
  20550. while (state.have < state.ncode) {
  20551. //=== NEEDBITS(3);
  20552. while (bits < 3) {
  20553. if (have === 0) { break inf_leave; }
  20554. have--;
  20555. hold += input[next++] << bits;
  20556. bits += 8;
  20557. }
  20558. //===//
  20559. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  20560. //--- DROPBITS(3) ---//
  20561. hold >>>= 3;
  20562. bits -= 3;
  20563. //---//
  20564. }
  20565. while (state.have < 19) {
  20566. state.lens[order[state.have++]] = 0;
  20567. }
  20568. // We have separate tables & no pointers. 2 commented lines below not needed.
  20569. //state.next = state.codes;
  20570. //state.lencode = state.next;
  20571. // Switch to use dynamic table
  20572. state.lencode = state.lendyn;
  20573. state.lenbits = 7;
  20574. opts = {bits: state.lenbits};
  20575. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  20576. state.lenbits = opts.bits;
  20577. if (ret) {
  20578. strm.msg = 'invalid code lengths set';
  20579. state.mode = BAD;
  20580. break;
  20581. }
  20582. //Tracev((stderr, "inflate: code lengths ok\n"));
  20583. state.have = 0;
  20584. state.mode = CODELENS;
  20585. /* falls through */
  20586. case CODELENS:
  20587. while (state.have < state.nlen + state.ndist) {
  20588. for (;;) {
  20589. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  20590. here_bits = here >>> 24;
  20591. here_op = (here >>> 16) & 0xff;
  20592. here_val = here & 0xffff;
  20593. if ((here_bits) <= bits) { break; }
  20594. //--- PULLBYTE() ---//
  20595. if (have === 0) { break inf_leave; }
  20596. have--;
  20597. hold += input[next++] << bits;
  20598. bits += 8;
  20599. //---//
  20600. }
  20601. if (here_val < 16) {
  20602. //--- DROPBITS(here.bits) ---//
  20603. hold >>>= here_bits;
  20604. bits -= here_bits;
  20605. //---//
  20606. state.lens[state.have++] = here_val;
  20607. }
  20608. else {
  20609. if (here_val === 16) {
  20610. //=== NEEDBITS(here.bits + 2);
  20611. n = here_bits + 2;
  20612. while (bits < n) {
  20613. if (have === 0) { break inf_leave; }
  20614. have--;
  20615. hold += input[next++] << bits;
  20616. bits += 8;
  20617. }
  20618. //===//
  20619. //--- DROPBITS(here.bits) ---//
  20620. hold >>>= here_bits;
  20621. bits -= here_bits;
  20622. //---//
  20623. if (state.have === 0) {
  20624. strm.msg = 'invalid bit length repeat';
  20625. state.mode = BAD;
  20626. break;
  20627. }
  20628. len = state.lens[state.have - 1];
  20629. copy = 3 + (hold & 0x03);//BITS(2);
  20630. //--- DROPBITS(2) ---//
  20631. hold >>>= 2;
  20632. bits -= 2;
  20633. //---//
  20634. }
  20635. else if (here_val === 17) {
  20636. //=== NEEDBITS(here.bits + 3);
  20637. n = here_bits + 3;
  20638. while (bits < n) {
  20639. if (have === 0) { break inf_leave; }
  20640. have--;
  20641. hold += input[next++] << bits;
  20642. bits += 8;
  20643. }
  20644. //===//
  20645. //--- DROPBITS(here.bits) ---//
  20646. hold >>>= here_bits;
  20647. bits -= here_bits;
  20648. //---//
  20649. len = 0;
  20650. copy = 3 + (hold & 0x07);//BITS(3);
  20651. //--- DROPBITS(3) ---//
  20652. hold >>>= 3;
  20653. bits -= 3;
  20654. //---//
  20655. }
  20656. else {
  20657. //=== NEEDBITS(here.bits + 7);
  20658. n = here_bits + 7;
  20659. while (bits < n) {
  20660. if (have === 0) { break inf_leave; }
  20661. have--;
  20662. hold += input[next++] << bits;
  20663. bits += 8;
  20664. }
  20665. //===//
  20666. //--- DROPBITS(here.bits) ---//
  20667. hold >>>= here_bits;
  20668. bits -= here_bits;
  20669. //---//
  20670. len = 0;
  20671. copy = 11 + (hold & 0x7f);//BITS(7);
  20672. //--- DROPBITS(7) ---//
  20673. hold >>>= 7;
  20674. bits -= 7;
  20675. //---//
  20676. }
  20677. if (state.have + copy > state.nlen + state.ndist) {
  20678. strm.msg = 'invalid bit length repeat';
  20679. state.mode = BAD;
  20680. break;
  20681. }
  20682. while (copy--) {
  20683. state.lens[state.have++] = len;
  20684. }
  20685. }
  20686. }
  20687. /* handle error breaks in while */
  20688. if (state.mode === BAD) { break; }
  20689. /* check for end-of-block code (better have one) */
  20690. if (state.lens[256] === 0) {
  20691. strm.msg = 'invalid code -- missing end-of-block';
  20692. state.mode = BAD;
  20693. break;
  20694. }
  20695. /* build code tables -- note: do not change the lenbits or distbits
  20696. values here (9 and 6) without reading the comments in inftrees.h
  20697. concerning the ENOUGH constants, which depend on those values */
  20698. state.lenbits = 9;
  20699. opts = {bits: state.lenbits};
  20700. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  20701. // We have separate tables & no pointers. 2 commented lines below not needed.
  20702. // state.next_index = opts.table_index;
  20703. state.lenbits = opts.bits;
  20704. // state.lencode = state.next;
  20705. if (ret) {
  20706. strm.msg = 'invalid literal/lengths set';
  20707. state.mode = BAD;
  20708. break;
  20709. }
  20710. state.distbits = 6;
  20711. //state.distcode.copy(state.codes);
  20712. // Switch to use dynamic table
  20713. state.distcode = state.distdyn;
  20714. opts = {bits: state.distbits};
  20715. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  20716. // We have separate tables & no pointers. 2 commented lines below not needed.
  20717. // state.next_index = opts.table_index;
  20718. state.distbits = opts.bits;
  20719. // state.distcode = state.next;
  20720. if (ret) {
  20721. strm.msg = 'invalid distances set';
  20722. state.mode = BAD;
  20723. break;
  20724. }
  20725. //Tracev((stderr, 'inflate: codes ok\n'));
  20726. state.mode = LEN_;
  20727. if (flush === Z_TREES) { break inf_leave; }
  20728. /* falls through */
  20729. case LEN_:
  20730. state.mode = LEN;
  20731. /* falls through */
  20732. case LEN:
  20733. if (have >= 6 && left >= 258) {
  20734. //--- RESTORE() ---
  20735. strm.next_out = put;
  20736. strm.avail_out = left;
  20737. strm.next_in = next;
  20738. strm.avail_in = have;
  20739. state.hold = hold;
  20740. state.bits = bits;
  20741. //---
  20742. inflate_fast(strm, _out);
  20743. //--- LOAD() ---
  20744. put = strm.next_out;
  20745. output = strm.output;
  20746. left = strm.avail_out;
  20747. next = strm.next_in;
  20748. input = strm.input;
  20749. have = strm.avail_in;
  20750. hold = state.hold;
  20751. bits = state.bits;
  20752. //---
  20753. if (state.mode === TYPE) {
  20754. state.back = -1;
  20755. }
  20756. break;
  20757. }
  20758. state.back = 0;
  20759. for (;;) {
  20760. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  20761. here_bits = here >>> 24;
  20762. here_op = (here >>> 16) & 0xff;
  20763. here_val = here & 0xffff;
  20764. if (here_bits <= bits) { break; }
  20765. //--- PULLBYTE() ---//
  20766. if (have === 0) { break inf_leave; }
  20767. have--;
  20768. hold += input[next++] << bits;
  20769. bits += 8;
  20770. //---//
  20771. }
  20772. if (here_op && (here_op & 0xf0) === 0) {
  20773. last_bits = here_bits;
  20774. last_op = here_op;
  20775. last_val = here_val;
  20776. for (;;) {
  20777. here = state.lencode[last_val +
  20778. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20779. here_bits = here >>> 24;
  20780. here_op = (here >>> 16) & 0xff;
  20781. here_val = here & 0xffff;
  20782. if ((last_bits + here_bits) <= bits) { break; }
  20783. //--- PULLBYTE() ---//
  20784. if (have === 0) { break inf_leave; }
  20785. have--;
  20786. hold += input[next++] << bits;
  20787. bits += 8;
  20788. //---//
  20789. }
  20790. //--- DROPBITS(last.bits) ---//
  20791. hold >>>= last_bits;
  20792. bits -= last_bits;
  20793. //---//
  20794. state.back += last_bits;
  20795. }
  20796. //--- DROPBITS(here.bits) ---//
  20797. hold >>>= here_bits;
  20798. bits -= here_bits;
  20799. //---//
  20800. state.back += here_bits;
  20801. state.length = here_val;
  20802. if (here_op === 0) {
  20803. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  20804. // "inflate: literal '%c'\n" :
  20805. // "inflate: literal 0x%02x\n", here.val));
  20806. state.mode = LIT;
  20807. break;
  20808. }
  20809. if (here_op & 32) {
  20810. //Tracevv((stderr, "inflate: end of block\n"));
  20811. state.back = -1;
  20812. state.mode = TYPE;
  20813. break;
  20814. }
  20815. if (here_op & 64) {
  20816. strm.msg = 'invalid literal/length code';
  20817. state.mode = BAD;
  20818. break;
  20819. }
  20820. state.extra = here_op & 15;
  20821. state.mode = LENEXT;
  20822. /* falls through */
  20823. case LENEXT:
  20824. if (state.extra) {
  20825. //=== NEEDBITS(state.extra);
  20826. n = state.extra;
  20827. while (bits < n) {
  20828. if (have === 0) { break inf_leave; }
  20829. have--;
  20830. hold += input[next++] << bits;
  20831. bits += 8;
  20832. }
  20833. //===//
  20834. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20835. //--- DROPBITS(state.extra) ---//
  20836. hold >>>= state.extra;
  20837. bits -= state.extra;
  20838. //---//
  20839. state.back += state.extra;
  20840. }
  20841. //Tracevv((stderr, "inflate: length %u\n", state.length));
  20842. state.was = state.length;
  20843. state.mode = DIST;
  20844. /* falls through */
  20845. case DIST:
  20846. for (;;) {
  20847. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  20848. here_bits = here >>> 24;
  20849. here_op = (here >>> 16) & 0xff;
  20850. here_val = here & 0xffff;
  20851. if ((here_bits) <= bits) { break; }
  20852. //--- PULLBYTE() ---//
  20853. if (have === 0) { break inf_leave; }
  20854. have--;
  20855. hold += input[next++] << bits;
  20856. bits += 8;
  20857. //---//
  20858. }
  20859. if ((here_op & 0xf0) === 0) {
  20860. last_bits = here_bits;
  20861. last_op = here_op;
  20862. last_val = here_val;
  20863. for (;;) {
  20864. here = state.distcode[last_val +
  20865. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20866. here_bits = here >>> 24;
  20867. here_op = (here >>> 16) & 0xff;
  20868. here_val = here & 0xffff;
  20869. if ((last_bits + here_bits) <= bits) { break; }
  20870. //--- PULLBYTE() ---//
  20871. if (have === 0) { break inf_leave; }
  20872. have--;
  20873. hold += input[next++] << bits;
  20874. bits += 8;
  20875. //---//
  20876. }
  20877. //--- DROPBITS(last.bits) ---//
  20878. hold >>>= last_bits;
  20879. bits -= last_bits;
  20880. //---//
  20881. state.back += last_bits;
  20882. }
  20883. //--- DROPBITS(here.bits) ---//
  20884. hold >>>= here_bits;
  20885. bits -= here_bits;
  20886. //---//
  20887. state.back += here_bits;
  20888. if (here_op & 64) {
  20889. strm.msg = 'invalid distance code';
  20890. state.mode = BAD;
  20891. break;
  20892. }
  20893. state.offset = here_val;
  20894. state.extra = (here_op) & 15;
  20895. state.mode = DISTEXT;
  20896. /* falls through */
  20897. case DISTEXT:
  20898. if (state.extra) {
  20899. //=== NEEDBITS(state.extra);
  20900. n = state.extra;
  20901. while (bits < n) {
  20902. if (have === 0) { break inf_leave; }
  20903. have--;
  20904. hold += input[next++] << bits;
  20905. bits += 8;
  20906. }
  20907. //===//
  20908. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20909. //--- DROPBITS(state.extra) ---//
  20910. hold >>>= state.extra;
  20911. bits -= state.extra;
  20912. //---//
  20913. state.back += state.extra;
  20914. }
  20915. //#ifdef INFLATE_STRICT
  20916. if (state.offset > state.dmax) {
  20917. strm.msg = 'invalid distance too far back';
  20918. state.mode = BAD;
  20919. break;
  20920. }
  20921. //#endif
  20922. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  20923. state.mode = MATCH;
  20924. /* falls through */
  20925. case MATCH:
  20926. if (left === 0) { break inf_leave; }
  20927. copy = _out - left;
  20928. if (state.offset > copy) { /* copy from window */
  20929. copy = state.offset - copy;
  20930. if (copy > state.whave) {
  20931. if (state.sane) {
  20932. strm.msg = 'invalid distance too far back';
  20933. state.mode = BAD;
  20934. break;
  20935. }
  20936. // (!) This block is disabled in zlib defailts,
  20937. // don't enable it for binary compatibility
  20938. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  20939. // Trace((stderr, "inflate.c too far\n"));
  20940. // copy -= state.whave;
  20941. // if (copy > state.length) { copy = state.length; }
  20942. // if (copy > left) { copy = left; }
  20943. // left -= copy;
  20944. // state.length -= copy;
  20945. // do {
  20946. // output[put++] = 0;
  20947. // } while (--copy);
  20948. // if (state.length === 0) { state.mode = LEN; }
  20949. // break;
  20950. //#endif
  20951. }
  20952. if (copy > state.wnext) {
  20953. copy -= state.wnext;
  20954. from = state.wsize - copy;
  20955. }
  20956. else {
  20957. from = state.wnext - copy;
  20958. }
  20959. if (copy > state.length) { copy = state.length; }
  20960. from_source = state.window;
  20961. }
  20962. else { /* copy from output */
  20963. from_source = output;
  20964. from = put - state.offset;
  20965. copy = state.length;
  20966. }
  20967. if (copy > left) { copy = left; }
  20968. left -= copy;
  20969. state.length -= copy;
  20970. do {
  20971. output[put++] = from_source[from++];
  20972. } while (--copy);
  20973. if (state.length === 0) { state.mode = LEN; }
  20974. break;
  20975. case LIT:
  20976. if (left === 0) { break inf_leave; }
  20977. output[put++] = state.length;
  20978. left--;
  20979. state.mode = LEN;
  20980. break;
  20981. case CHECK:
  20982. if (state.wrap) {
  20983. //=== NEEDBITS(32);
  20984. while (bits < 32) {
  20985. if (have === 0) { break inf_leave; }
  20986. have--;
  20987. // Use '|' insdead of '+' to make sure that result is signed
  20988. hold |= input[next++] << bits;
  20989. bits += 8;
  20990. }
  20991. //===//
  20992. _out -= left;
  20993. strm.total_out += _out;
  20994. state.total += _out;
  20995. if (_out) {
  20996. strm.adler = state.check =
  20997. /*UPDATE(state.check, put - _out, _out);*/
  20998. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  20999. }
  21000. _out = left;
  21001. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  21002. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  21003. strm.msg = 'incorrect data check';
  21004. state.mode = BAD;
  21005. break;
  21006. }
  21007. //=== INITBITS();
  21008. hold = 0;
  21009. bits = 0;
  21010. //===//
  21011. //Tracev((stderr, "inflate: check matches trailer\n"));
  21012. }
  21013. state.mode = LENGTH;
  21014. /* falls through */
  21015. case LENGTH:
  21016. if (state.wrap && state.flags) {
  21017. //=== NEEDBITS(32);
  21018. while (bits < 32) {
  21019. if (have === 0) { break inf_leave; }
  21020. have--;
  21021. hold += input[next++] << bits;
  21022. bits += 8;
  21023. }
  21024. //===//
  21025. if (hold !== (state.total & 0xffffffff)) {
  21026. strm.msg = 'incorrect length check';
  21027. state.mode = BAD;
  21028. break;
  21029. }
  21030. //=== INITBITS();
  21031. hold = 0;
  21032. bits = 0;
  21033. //===//
  21034. //Tracev((stderr, "inflate: length matches trailer\n"));
  21035. }
  21036. state.mode = DONE;
  21037. /* falls through */
  21038. case DONE:
  21039. ret = Z_STREAM_END;
  21040. break inf_leave;
  21041. case BAD:
  21042. ret = Z_DATA_ERROR;
  21043. break inf_leave;
  21044. case MEM:
  21045. return Z_MEM_ERROR;
  21046. case SYNC:
  21047. /* falls through */
  21048. default:
  21049. return Z_STREAM_ERROR;
  21050. }
  21051. }
  21052. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  21053. /*
  21054. Return from inflate(), updating the total counts and the check value.
  21055. If there was no progress during the inflate() call, return a buffer
  21056. error. Call updatewindow() to create and/or update the window state.
  21057. Note: a memory error from inflate() is non-recoverable.
  21058. */
  21059. //--- RESTORE() ---
  21060. strm.next_out = put;
  21061. strm.avail_out = left;
  21062. strm.next_in = next;
  21063. strm.avail_in = have;
  21064. state.hold = hold;
  21065. state.bits = bits;
  21066. //---
  21067. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  21068. (state.mode < CHECK || flush !== Z_FINISH))) {
  21069. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  21070. state.mode = MEM;
  21071. return Z_MEM_ERROR;
  21072. }
  21073. }
  21074. _in -= strm.avail_in;
  21075. _out -= strm.avail_out;
  21076. strm.total_in += _in;
  21077. strm.total_out += _out;
  21078. state.total += _out;
  21079. if (state.wrap && _out) {
  21080. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  21081. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  21082. }
  21083. strm.data_type = state.bits + (state.last ? 64 : 0) +
  21084. (state.mode === TYPE ? 128 : 0) +
  21085. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  21086. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  21087. ret = Z_BUF_ERROR;
  21088. }
  21089. return ret;
  21090. }
  21091. function inflateEnd(strm) {
  21092. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  21093. return Z_STREAM_ERROR;
  21094. }
  21095. var state = strm.state;
  21096. if (state.window) {
  21097. state.window = null;
  21098. }
  21099. strm.state = null;
  21100. return Z_OK;
  21101. }
  21102. function inflateGetHeader(strm, head) {
  21103. var state;
  21104. /* check state */
  21105. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21106. state = strm.state;
  21107. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  21108. /* save header structure */
  21109. state.head = head;
  21110. head.done = false;
  21111. return Z_OK;
  21112. }
  21113. exports.inflateReset = inflateReset;
  21114. exports.inflateReset2 = inflateReset2;
  21115. exports.inflateResetKeep = inflateResetKeep;
  21116. exports.inflateInit = inflateInit;
  21117. exports.inflateInit2 = inflateInit2;
  21118. exports.inflate = inflate;
  21119. exports.inflateEnd = inflateEnd;
  21120. exports.inflateGetHeader = inflateGetHeader;
  21121. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  21122. /* Not implemented
  21123. exports.inflateCopy = inflateCopy;
  21124. exports.inflateGetDictionary = inflateGetDictionary;
  21125. exports.inflateMark = inflateMark;
  21126. exports.inflatePrime = inflatePrime;
  21127. exports.inflateSetDictionary = inflateSetDictionary;
  21128. exports.inflateSync = inflateSync;
  21129. exports.inflateSyncPoint = inflateSyncPoint;
  21130. exports.inflateUndermine = inflateUndermine;
  21131. */
  21132. },{"../utils/common":66,"./adler32":68,"./crc32":70,"./inffast":73,"./inftrees":75}],75:[function(require,module,exports){
  21133. 'use strict';
  21134. var utils = require('../utils/common');
  21135. var MAXBITS = 15;
  21136. var ENOUGH_LENS = 852;
  21137. var ENOUGH_DISTS = 592;
  21138. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  21139. var CODES = 0;
  21140. var LENS = 1;
  21141. var DISTS = 2;
  21142. var lbase = [ /* Length codes 257..285 base */
  21143. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  21144. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  21145. ];
  21146. var lext = [ /* Length codes 257..285 extra */
  21147. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  21148. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  21149. ];
  21150. var dbase = [ /* Distance codes 0..29 base */
  21151. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  21152. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  21153. 8193, 12289, 16385, 24577, 0, 0
  21154. ];
  21155. var dext = [ /* Distance codes 0..29 extra */
  21156. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  21157. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  21158. 28, 28, 29, 29, 64, 64
  21159. ];
  21160. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  21161. {
  21162. var bits = opts.bits;
  21163. //here = opts.here; /* table entry for duplication */
  21164. var len = 0; /* a code's length in bits */
  21165. var sym = 0; /* index of code symbols */
  21166. var min = 0, max = 0; /* minimum and maximum code lengths */
  21167. var root = 0; /* number of index bits for root table */
  21168. var curr = 0; /* number of index bits for current table */
  21169. var drop = 0; /* code bits to drop for sub-table */
  21170. var left = 0; /* number of prefix codes available */
  21171. var used = 0; /* code entries in table used */
  21172. var huff = 0; /* Huffman code */
  21173. var incr; /* for incrementing code, index */
  21174. var fill; /* index for replicating entries */
  21175. var low; /* low bits for current root entry */
  21176. var mask; /* mask for low root bits */
  21177. var next; /* next available space in table */
  21178. var base = null; /* base value table to use */
  21179. var base_index = 0;
  21180. // var shoextra; /* extra bits table to use */
  21181. var end; /* use base and extra for symbol > end */
  21182. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  21183. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  21184. var extra = null;
  21185. var extra_index = 0;
  21186. var here_bits, here_op, here_val;
  21187. /*
  21188. Process a set of code lengths to create a canonical Huffman code. The
  21189. code lengths are lens[0..codes-1]. Each length corresponds to the
  21190. symbols 0..codes-1. The Huffman code is generated by first sorting the
  21191. symbols by length from short to long, and retaining the symbol order
  21192. for codes with equal lengths. Then the code starts with all zero bits
  21193. for the first code of the shortest length, and the codes are integer
  21194. increments for the same length, and zeros are appended as the length
  21195. increases. For the deflate format, these bits are stored backwards
  21196. from their more natural integer increment ordering, and so when the
  21197. decoding tables are built in the large loop below, the integer codes
  21198. are incremented backwards.
  21199. This routine assumes, but does not check, that all of the entries in
  21200. lens[] are in the range 0..MAXBITS. The caller must assure this.
  21201. 1..MAXBITS is interpreted as that code length. zero means that that
  21202. symbol does not occur in this code.
  21203. The codes are sorted by computing a count of codes for each length,
  21204. creating from that a table of starting indices for each length in the
  21205. sorted table, and then entering the symbols in order in the sorted
  21206. table. The sorted table is work[], with that space being provided by
  21207. the caller.
  21208. The length counts are used for other purposes as well, i.e. finding
  21209. the minimum and maximum length codes, determining if there are any
  21210. codes at all, checking for a valid set of lengths, and looking ahead
  21211. at length counts to determine sub-table sizes when building the
  21212. decoding tables.
  21213. */
  21214. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  21215. for (len = 0; len <= MAXBITS; len++) {
  21216. count[len] = 0;
  21217. }
  21218. for (sym = 0; sym < codes; sym++) {
  21219. count[lens[lens_index + sym]]++;
  21220. }
  21221. /* bound code lengths, force root to be within code lengths */
  21222. root = bits;
  21223. for (max = MAXBITS; max >= 1; max--) {
  21224. if (count[max] !== 0) { break; }
  21225. }
  21226. if (root > max) {
  21227. root = max;
  21228. }
  21229. if (max === 0) { /* no symbols to code at all */
  21230. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  21231. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  21232. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  21233. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21234. //table.op[opts.table_index] = 64;
  21235. //table.bits[opts.table_index] = 1;
  21236. //table.val[opts.table_index++] = 0;
  21237. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21238. opts.bits = 1;
  21239. return 0; /* no symbols, but wait for decoding to report error */
  21240. }
  21241. for (min = 1; min < max; min++) {
  21242. if (count[min] !== 0) { break; }
  21243. }
  21244. if (root < min) {
  21245. root = min;
  21246. }
  21247. /* check for an over-subscribed or incomplete set of lengths */
  21248. left = 1;
  21249. for (len = 1; len <= MAXBITS; len++) {
  21250. left <<= 1;
  21251. left -= count[len];
  21252. if (left < 0) {
  21253. return -1;
  21254. } /* over-subscribed */
  21255. }
  21256. if (left > 0 && (type === CODES || max !== 1)) {
  21257. return -1; /* incomplete set */
  21258. }
  21259. /* generate offsets into symbol table for each length for sorting */
  21260. offs[1] = 0;
  21261. for (len = 1; len < MAXBITS; len++) {
  21262. offs[len + 1] = offs[len] + count[len];
  21263. }
  21264. /* sort symbols by length, by symbol order within each length */
  21265. for (sym = 0; sym < codes; sym++) {
  21266. if (lens[lens_index + sym] !== 0) {
  21267. work[offs[lens[lens_index + sym]]++] = sym;
  21268. }
  21269. }
  21270. /*
  21271. Create and fill in decoding tables. In this loop, the table being
  21272. filled is at next and has curr index bits. The code being used is huff
  21273. with length len. That code is converted to an index by dropping drop
  21274. bits off of the bottom. For codes where len is less than drop + curr,
  21275. those top drop + curr - len bits are incremented through all values to
  21276. fill the table with replicated entries.
  21277. root is the number of index bits for the root table. When len exceeds
  21278. root, sub-tables are created pointed to by the root entry with an index
  21279. of the low root bits of huff. This is saved in low to check for when a
  21280. new sub-table should be started. drop is zero when the root table is
  21281. being filled, and drop is root when sub-tables are being filled.
  21282. When a new sub-table is needed, it is necessary to look ahead in the
  21283. code lengths to determine what size sub-table is needed. The length
  21284. counts are used for this, and so count[] is decremented as codes are
  21285. entered in the tables.
  21286. used keeps track of how many table entries have been allocated from the
  21287. provided *table space. It is checked for LENS and DIST tables against
  21288. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  21289. the initial root table size constants. See the comments in inftrees.h
  21290. for more information.
  21291. sym increments through all symbols, and the loop terminates when
  21292. all codes of length max, i.e. all codes, have been processed. This
  21293. routine permits incomplete codes, so another loop after this one fills
  21294. in the rest of the decoding tables with invalid code markers.
  21295. */
  21296. /* set up for code type */
  21297. // poor man optimization - use if-else instead of switch,
  21298. // to avoid deopts in old v8
  21299. if (type === CODES) {
  21300. base = extra = work; /* dummy value--not used */
  21301. end = 19;
  21302. } else if (type === LENS) {
  21303. base = lbase;
  21304. base_index -= 257;
  21305. extra = lext;
  21306. extra_index -= 257;
  21307. end = 256;
  21308. } else { /* DISTS */
  21309. base = dbase;
  21310. extra = dext;
  21311. end = -1;
  21312. }
  21313. /* initialize opts for loop */
  21314. huff = 0; /* starting code */
  21315. sym = 0; /* starting code symbol */
  21316. len = min; /* starting code length */
  21317. next = table_index; /* current table to fill in */
  21318. curr = root; /* current table index bits */
  21319. drop = 0; /* current bits to drop from code for index */
  21320. low = -1; /* trigger new sub-table when len > root */
  21321. used = 1 << root; /* use root table entries */
  21322. mask = used - 1; /* mask for comparing low */
  21323. /* check available table space */
  21324. if ((type === LENS && used > ENOUGH_LENS) ||
  21325. (type === DISTS && used > ENOUGH_DISTS)) {
  21326. return 1;
  21327. }
  21328. var i=0;
  21329. /* process all codes and make table entries */
  21330. for (;;) {
  21331. i++;
  21332. /* create table entry */
  21333. here_bits = len - drop;
  21334. if (work[sym] < end) {
  21335. here_op = 0;
  21336. here_val = work[sym];
  21337. }
  21338. else if (work[sym] > end) {
  21339. here_op = extra[extra_index + work[sym]];
  21340. here_val = base[base_index + work[sym]];
  21341. }
  21342. else {
  21343. here_op = 32 + 64; /* end of block */
  21344. here_val = 0;
  21345. }
  21346. /* replicate for those indices with low len bits equal to huff */
  21347. incr = 1 << (len - drop);
  21348. fill = 1 << curr;
  21349. min = fill; /* save offset to next table */
  21350. do {
  21351. fill -= incr;
  21352. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  21353. } while (fill !== 0);
  21354. /* backwards increment the len-bit code huff */
  21355. incr = 1 << (len - 1);
  21356. while (huff & incr) {
  21357. incr >>= 1;
  21358. }
  21359. if (incr !== 0) {
  21360. huff &= incr - 1;
  21361. huff += incr;
  21362. } else {
  21363. huff = 0;
  21364. }
  21365. /* go to next symbol, update count, len */
  21366. sym++;
  21367. if (--count[len] === 0) {
  21368. if (len === max) { break; }
  21369. len = lens[lens_index + work[sym]];
  21370. }
  21371. /* create new sub-table if needed */
  21372. if (len > root && (huff & mask) !== low) {
  21373. /* if first time, transition to sub-tables */
  21374. if (drop === 0) {
  21375. drop = root;
  21376. }
  21377. /* increment past last table */
  21378. next += min; /* here min is 1 << curr */
  21379. /* determine length of next table */
  21380. curr = len - drop;
  21381. left = 1 << curr;
  21382. while (curr + drop < max) {
  21383. left -= count[curr + drop];
  21384. if (left <= 0) { break; }
  21385. curr++;
  21386. left <<= 1;
  21387. }
  21388. /* check for enough space */
  21389. used += 1 << curr;
  21390. if ((type === LENS && used > ENOUGH_LENS) ||
  21391. (type === DISTS && used > ENOUGH_DISTS)) {
  21392. return 1;
  21393. }
  21394. /* point entry in root table to sub-table */
  21395. low = huff & mask;
  21396. /*table.op[low] = curr;
  21397. table.bits[low] = root;
  21398. table.val[low] = next - opts.table_index;*/
  21399. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  21400. }
  21401. }
  21402. /* fill in remaining table entry if code is incomplete (guaranteed to have
  21403. at most one remaining entry, since if the code is incomplete, the
  21404. maximum code length that was allowed to get this far is one bit) */
  21405. if (huff !== 0) {
  21406. //table.op[next + huff] = 64; /* invalid code marker */
  21407. //table.bits[next + huff] = len - drop;
  21408. //table.val[next + huff] = 0;
  21409. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  21410. }
  21411. /* set return parameters */
  21412. //opts.table_index += used;
  21413. opts.bits = root;
  21414. return 0;
  21415. };
  21416. },{"../utils/common":66}],76:[function(require,module,exports){
  21417. 'use strict';
  21418. module.exports = {
  21419. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  21420. '1': 'stream end', /* Z_STREAM_END 1 */
  21421. '0': '', /* Z_OK 0 */
  21422. '-1': 'file error', /* Z_ERRNO (-1) */
  21423. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  21424. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  21425. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  21426. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  21427. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  21428. };
  21429. },{}],77:[function(require,module,exports){
  21430. 'use strict';
  21431. var utils = require('../utils/common');
  21432. /* Public constants ==========================================================*/
  21433. /* ===========================================================================*/
  21434. //var Z_FILTERED = 1;
  21435. //var Z_HUFFMAN_ONLY = 2;
  21436. //var Z_RLE = 3;
  21437. var Z_FIXED = 4;
  21438. //var Z_DEFAULT_STRATEGY = 0;
  21439. /* Possible values of the data_type field (though see inflate()) */
  21440. var Z_BINARY = 0;
  21441. var Z_TEXT = 1;
  21442. //var Z_ASCII = 1; // = Z_TEXT
  21443. var Z_UNKNOWN = 2;
  21444. /*============================================================================*/
  21445. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  21446. // From zutil.h
  21447. var STORED_BLOCK = 0;
  21448. var STATIC_TREES = 1;
  21449. var DYN_TREES = 2;
  21450. /* The three kinds of block type */
  21451. var MIN_MATCH = 3;
  21452. var MAX_MATCH = 258;
  21453. /* The minimum and maximum match lengths */
  21454. // From deflate.h
  21455. /* ===========================================================================
  21456. * Internal compression state.
  21457. */
  21458. var LENGTH_CODES = 29;
  21459. /* number of length codes, not counting the special END_BLOCK code */
  21460. var LITERALS = 256;
  21461. /* number of literal bytes 0..255 */
  21462. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  21463. /* number of Literal or Length codes, including the END_BLOCK code */
  21464. var D_CODES = 30;
  21465. /* number of distance codes */
  21466. var BL_CODES = 19;
  21467. /* number of codes used to transfer the bit lengths */
  21468. var HEAP_SIZE = 2*L_CODES + 1;
  21469. /* maximum heap size */
  21470. var MAX_BITS = 15;
  21471. /* All codes must not exceed MAX_BITS bits */
  21472. var Buf_size = 16;
  21473. /* size of bit buffer in bi_buf */
  21474. /* ===========================================================================
  21475. * Constants
  21476. */
  21477. var MAX_BL_BITS = 7;
  21478. /* Bit length codes must not exceed MAX_BL_BITS bits */
  21479. var END_BLOCK = 256;
  21480. /* end of block literal code */
  21481. var REP_3_6 = 16;
  21482. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  21483. var REPZ_3_10 = 17;
  21484. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  21485. var REPZ_11_138 = 18;
  21486. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  21487. var extra_lbits = /* extra bits for each length code */
  21488. [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];
  21489. var extra_dbits = /* extra bits for each distance code */
  21490. [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];
  21491. var extra_blbits = /* extra bits for each bit length code */
  21492. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  21493. var bl_order =
  21494. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  21495. /* The lengths of the bit length codes are sent in order of decreasing
  21496. * probability, to avoid transmitting the lengths for unused bit length codes.
  21497. */
  21498. /* ===========================================================================
  21499. * Local data. These are initialized only once.
  21500. */
  21501. // We pre-fill arrays with 0 to avoid uninitialized gaps
  21502. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  21503. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  21504. var static_ltree = new Array((L_CODES+2) * 2);
  21505. zero(static_ltree);
  21506. /* The static literal tree. Since the bit lengths are imposed, there is no
  21507. * need for the L_CODES extra codes used during heap construction. However
  21508. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  21509. * below).
  21510. */
  21511. var static_dtree = new Array(D_CODES * 2);
  21512. zero(static_dtree);
  21513. /* The static distance tree. (Actually a trivial tree since all codes use
  21514. * 5 bits.)
  21515. */
  21516. var _dist_code = new Array(DIST_CODE_LEN);
  21517. zero(_dist_code);
  21518. /* Distance codes. The first 256 values correspond to the distances
  21519. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  21520. * the 15 bit distances.
  21521. */
  21522. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  21523. zero(_length_code);
  21524. /* length code for each normalized match length (0 == MIN_MATCH) */
  21525. var base_length = new Array(LENGTH_CODES);
  21526. zero(base_length);
  21527. /* First normalized length for each code (0 = MIN_MATCH) */
  21528. var base_dist = new Array(D_CODES);
  21529. zero(base_dist);
  21530. /* First normalized distance for each code (0 = distance of 1) */
  21531. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  21532. this.static_tree = static_tree; /* static tree or NULL */
  21533. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  21534. this.extra_base = extra_base; /* base index for extra_bits */
  21535. this.elems = elems; /* max number of elements in the tree */
  21536. this.max_length = max_length; /* max bit length for the codes */
  21537. // show if `static_tree` has data or dummy - needed for monomorphic objects
  21538. this.has_stree = static_tree && static_tree.length;
  21539. };
  21540. var static_l_desc;
  21541. var static_d_desc;
  21542. var static_bl_desc;
  21543. var TreeDesc = function(dyn_tree, stat_desc) {
  21544. this.dyn_tree = dyn_tree; /* the dynamic tree */
  21545. this.max_code = 0; /* largest code with non zero frequency */
  21546. this.stat_desc = stat_desc; /* the corresponding static tree */
  21547. };
  21548. function d_code(dist) {
  21549. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  21550. }
  21551. /* ===========================================================================
  21552. * Output a short LSB first on the stream.
  21553. * IN assertion: there is enough room in pendingBuf.
  21554. */
  21555. function put_short (s, w) {
  21556. // put_byte(s, (uch)((w) & 0xff));
  21557. // put_byte(s, (uch)((ush)(w) >> 8));
  21558. s.pending_buf[s.pending++] = (w) & 0xff;
  21559. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  21560. }
  21561. /* ===========================================================================
  21562. * Send a value on a given number of bits.
  21563. * IN assertion: length <= 16 and value fits in length bits.
  21564. */
  21565. function send_bits(s, value, length) {
  21566. if (s.bi_valid > (Buf_size - length)) {
  21567. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21568. put_short(s, s.bi_buf);
  21569. s.bi_buf = value >> (Buf_size - s.bi_valid);
  21570. s.bi_valid += length - Buf_size;
  21571. } else {
  21572. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21573. s.bi_valid += length;
  21574. }
  21575. }
  21576. function send_code(s, c, tree) {
  21577. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  21578. }
  21579. /* ===========================================================================
  21580. * Reverse the first len bits of a code, using straightforward code (a faster
  21581. * method would use a table)
  21582. * IN assertion: 1 <= len <= 15
  21583. */
  21584. function bi_reverse(code, len) {
  21585. var res = 0;
  21586. do {
  21587. res |= code & 1;
  21588. code >>>= 1;
  21589. res <<= 1;
  21590. } while (--len > 0);
  21591. return res >>> 1;
  21592. }
  21593. /* ===========================================================================
  21594. * Flush the bit buffer, keeping at most 7 bits in it.
  21595. */
  21596. function bi_flush(s) {
  21597. if (s.bi_valid === 16) {
  21598. put_short(s, s.bi_buf);
  21599. s.bi_buf = 0;
  21600. s.bi_valid = 0;
  21601. } else if (s.bi_valid >= 8) {
  21602. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  21603. s.bi_buf >>= 8;
  21604. s.bi_valid -= 8;
  21605. }
  21606. }
  21607. /* ===========================================================================
  21608. * Compute the optimal bit lengths for a tree and update the total bit length
  21609. * for the current block.
  21610. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  21611. * above are the tree nodes sorted by increasing frequency.
  21612. * OUT assertions: the field len is set to the optimal bit length, the
  21613. * array bl_count contains the frequencies for each bit length.
  21614. * The length opt_len is updated; static_len is also updated if stree is
  21615. * not null.
  21616. */
  21617. function gen_bitlen(s, desc)
  21618. // deflate_state *s;
  21619. // tree_desc *desc; /* the tree descriptor */
  21620. {
  21621. var tree = desc.dyn_tree;
  21622. var max_code = desc.max_code;
  21623. var stree = desc.stat_desc.static_tree;
  21624. var has_stree = desc.stat_desc.has_stree;
  21625. var extra = desc.stat_desc.extra_bits;
  21626. var base = desc.stat_desc.extra_base;
  21627. var max_length = desc.stat_desc.max_length;
  21628. var h; /* heap index */
  21629. var n, m; /* iterate over the tree elements */
  21630. var bits; /* bit length */
  21631. var xbits; /* extra bits */
  21632. var f; /* frequency */
  21633. var overflow = 0; /* number of elements with bit length too large */
  21634. for (bits = 0; bits <= MAX_BITS; bits++) {
  21635. s.bl_count[bits] = 0;
  21636. }
  21637. /* In a first pass, compute the optimal bit lengths (which may
  21638. * overflow in the case of the bit length tree).
  21639. */
  21640. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  21641. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  21642. n = s.heap[h];
  21643. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  21644. if (bits > max_length) {
  21645. bits = max_length;
  21646. overflow++;
  21647. }
  21648. tree[n*2 + 1]/*.Len*/ = bits;
  21649. /* We overwrite tree[n].Dad which is no longer needed */
  21650. if (n > max_code) { continue; } /* not a leaf node */
  21651. s.bl_count[bits]++;
  21652. xbits = 0;
  21653. if (n >= base) {
  21654. xbits = extra[n-base];
  21655. }
  21656. f = tree[n * 2]/*.Freq*/;
  21657. s.opt_len += f * (bits + xbits);
  21658. if (has_stree) {
  21659. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  21660. }
  21661. }
  21662. if (overflow === 0) { return; }
  21663. // Trace((stderr,"\nbit length overflow\n"));
  21664. /* This happens for example on obj2 and pic of the Calgary corpus */
  21665. /* Find the first bit length which could increase: */
  21666. do {
  21667. bits = max_length-1;
  21668. while (s.bl_count[bits] === 0) { bits--; }
  21669. s.bl_count[bits]--; /* move one leaf down the tree */
  21670. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  21671. s.bl_count[max_length]--;
  21672. /* The brother of the overflow item also moves one step up,
  21673. * but this does not affect bl_count[max_length]
  21674. */
  21675. overflow -= 2;
  21676. } while (overflow > 0);
  21677. /* Now recompute all bit lengths, scanning in increasing frequency.
  21678. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  21679. * lengths instead of fixing only the wrong ones. This idea is taken
  21680. * from 'ar' written by Haruhiko Okumura.)
  21681. */
  21682. for (bits = max_length; bits !== 0; bits--) {
  21683. n = s.bl_count[bits];
  21684. while (n !== 0) {
  21685. m = s.heap[--h];
  21686. if (m > max_code) { continue; }
  21687. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  21688. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  21689. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  21690. tree[m*2 + 1]/*.Len*/ = bits;
  21691. }
  21692. n--;
  21693. }
  21694. }
  21695. }
  21696. /* ===========================================================================
  21697. * Generate the codes for a given tree and bit counts (which need not be
  21698. * optimal).
  21699. * IN assertion: the array bl_count contains the bit length statistics for
  21700. * the given tree and the field len is set for all tree elements.
  21701. * OUT assertion: the field code is set for all tree elements of non
  21702. * zero code length.
  21703. */
  21704. function gen_codes(tree, max_code, bl_count)
  21705. // ct_data *tree; /* the tree to decorate */
  21706. // int max_code; /* largest code with non zero frequency */
  21707. // ushf *bl_count; /* number of codes at each bit length */
  21708. {
  21709. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  21710. var code = 0; /* running code value */
  21711. var bits; /* bit index */
  21712. var n; /* code index */
  21713. /* The distribution counts are first used to generate the code values
  21714. * without bit reversal.
  21715. */
  21716. for (bits = 1; bits <= MAX_BITS; bits++) {
  21717. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  21718. }
  21719. /* Check that the bit counts in bl_count are consistent. The last code
  21720. * must be all ones.
  21721. */
  21722. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  21723. // "inconsistent bit counts");
  21724. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  21725. for (n = 0; n <= max_code; n++) {
  21726. var len = tree[n*2 + 1]/*.Len*/;
  21727. if (len === 0) { continue; }
  21728. /* Now reverse the bits */
  21729. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  21730. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  21731. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  21732. }
  21733. }
  21734. /* ===========================================================================
  21735. * Initialize the various 'constant' tables.
  21736. */
  21737. function tr_static_init() {
  21738. var n; /* iterates over tree elements */
  21739. var bits; /* bit counter */
  21740. var length; /* length value */
  21741. var code; /* code value */
  21742. var dist; /* distance index */
  21743. var bl_count = new Array(MAX_BITS+1);
  21744. /* number of codes at each bit length for an optimal tree */
  21745. // do check in _tr_init()
  21746. //if (static_init_done) return;
  21747. /* For some embedded targets, global variables are not initialized: */
  21748. /*#ifdef NO_INIT_GLOBAL_POINTERS
  21749. static_l_desc.static_tree = static_ltree;
  21750. static_l_desc.extra_bits = extra_lbits;
  21751. static_d_desc.static_tree = static_dtree;
  21752. static_d_desc.extra_bits = extra_dbits;
  21753. static_bl_desc.extra_bits = extra_blbits;
  21754. #endif*/
  21755. /* Initialize the mapping length (0..255) -> length code (0..28) */
  21756. length = 0;
  21757. for (code = 0; code < LENGTH_CODES-1; code++) {
  21758. base_length[code] = length;
  21759. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  21760. _length_code[length++] = code;
  21761. }
  21762. }
  21763. //Assert (length == 256, "tr_static_init: length != 256");
  21764. /* Note that the length 255 (match length 258) can be represented
  21765. * in two different ways: code 284 + 5 bits or code 285, so we
  21766. * overwrite length_code[255] to use the best encoding:
  21767. */
  21768. _length_code[length-1] = code;
  21769. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  21770. dist = 0;
  21771. for (code = 0 ; code < 16; code++) {
  21772. base_dist[code] = dist;
  21773. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  21774. _dist_code[dist++] = code;
  21775. }
  21776. }
  21777. //Assert (dist == 256, "tr_static_init: dist != 256");
  21778. dist >>= 7; /* from now on, all distances are divided by 128 */
  21779. for ( ; code < D_CODES; code++) {
  21780. base_dist[code] = dist << 7;
  21781. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  21782. _dist_code[256 + dist++] = code;
  21783. }
  21784. }
  21785. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  21786. /* Construct the codes of the static literal tree */
  21787. for (bits = 0; bits <= MAX_BITS; bits++) {
  21788. bl_count[bits] = 0;
  21789. }
  21790. n = 0;
  21791. while (n <= 143) {
  21792. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21793. n++;
  21794. bl_count[8]++;
  21795. }
  21796. while (n <= 255) {
  21797. static_ltree[n*2 + 1]/*.Len*/ = 9;
  21798. n++;
  21799. bl_count[9]++;
  21800. }
  21801. while (n <= 279) {
  21802. static_ltree[n*2 + 1]/*.Len*/ = 7;
  21803. n++;
  21804. bl_count[7]++;
  21805. }
  21806. while (n <= 287) {
  21807. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21808. n++;
  21809. bl_count[8]++;
  21810. }
  21811. /* Codes 286 and 287 do not exist, but we must include them in the
  21812. * tree construction to get a canonical Huffman tree (longest code
  21813. * all ones)
  21814. */
  21815. gen_codes(static_ltree, L_CODES+1, bl_count);
  21816. /* The static distance tree is trivial: */
  21817. for (n = 0; n < D_CODES; n++) {
  21818. static_dtree[n*2 + 1]/*.Len*/ = 5;
  21819. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  21820. }
  21821. // Now data ready and we can init static trees
  21822. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  21823. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  21824. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  21825. //static_init_done = true;
  21826. }
  21827. /* ===========================================================================
  21828. * Initialize a new block.
  21829. */
  21830. function init_block(s) {
  21831. var n; /* iterates over tree elements */
  21832. /* Initialize the trees. */
  21833. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  21834. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  21835. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  21836. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  21837. s.opt_len = s.static_len = 0;
  21838. s.last_lit = s.matches = 0;
  21839. }
  21840. /* ===========================================================================
  21841. * Flush the bit buffer and align the output on a byte boundary
  21842. */
  21843. function bi_windup(s)
  21844. {
  21845. if (s.bi_valid > 8) {
  21846. put_short(s, s.bi_buf);
  21847. } else if (s.bi_valid > 0) {
  21848. //put_byte(s, (Byte)s->bi_buf);
  21849. s.pending_buf[s.pending++] = s.bi_buf;
  21850. }
  21851. s.bi_buf = 0;
  21852. s.bi_valid = 0;
  21853. }
  21854. /* ===========================================================================
  21855. * Copy a stored block, storing first the length and its
  21856. * one's complement if requested.
  21857. */
  21858. function copy_block(s, buf, len, header)
  21859. //DeflateState *s;
  21860. //charf *buf; /* the input data */
  21861. //unsigned len; /* its length */
  21862. //int header; /* true if block header must be written */
  21863. {
  21864. bi_windup(s); /* align on byte boundary */
  21865. if (header) {
  21866. put_short(s, len);
  21867. put_short(s, ~len);
  21868. }
  21869. // while (len--) {
  21870. // put_byte(s, *buf++);
  21871. // }
  21872. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  21873. s.pending += len;
  21874. }
  21875. /* ===========================================================================
  21876. * Compares to subtrees, using the tree depth as tie breaker when
  21877. * the subtrees have equal frequency. This minimizes the worst case length.
  21878. */
  21879. function smaller(tree, n, m, depth) {
  21880. var _n2 = n*2;
  21881. var _m2 = m*2;
  21882. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  21883. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  21884. }
  21885. /* ===========================================================================
  21886. * Restore the heap property by moving down the tree starting at node k,
  21887. * exchanging a node with the smallest of its two sons if necessary, stopping
  21888. * when the heap property is re-established (each father smaller than its
  21889. * two sons).
  21890. */
  21891. function pqdownheap(s, tree, k)
  21892. // deflate_state *s;
  21893. // ct_data *tree; /* the tree to restore */
  21894. // int k; /* node to move down */
  21895. {
  21896. var v = s.heap[k];
  21897. var j = k << 1; /* left son of k */
  21898. while (j <= s.heap_len) {
  21899. /* Set j to the smallest of the two sons: */
  21900. if (j < s.heap_len &&
  21901. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  21902. j++;
  21903. }
  21904. /* Exit if v is smaller than both sons */
  21905. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  21906. /* Exchange v with the smallest son */
  21907. s.heap[k] = s.heap[j];
  21908. k = j;
  21909. /* And continue down the tree, setting j to the left son of k */
  21910. j <<= 1;
  21911. }
  21912. s.heap[k] = v;
  21913. }
  21914. // inlined manually
  21915. // var SMALLEST = 1;
  21916. /* ===========================================================================
  21917. * Send the block data compressed using the given Huffman trees
  21918. */
  21919. function compress_block(s, ltree, dtree)
  21920. // deflate_state *s;
  21921. // const ct_data *ltree; /* literal tree */
  21922. // const ct_data *dtree; /* distance tree */
  21923. {
  21924. var dist; /* distance of matched string */
  21925. var lc; /* match length or unmatched char (if dist == 0) */
  21926. var lx = 0; /* running index in l_buf */
  21927. var code; /* the code to send */
  21928. var extra; /* number of extra bits to send */
  21929. if (s.last_lit !== 0) {
  21930. do {
  21931. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  21932. lc = s.pending_buf[s.l_buf + lx];
  21933. lx++;
  21934. if (dist === 0) {
  21935. send_code(s, lc, ltree); /* send a literal byte */
  21936. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  21937. } else {
  21938. /* Here, lc is the match length - MIN_MATCH */
  21939. code = _length_code[lc];
  21940. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  21941. extra = extra_lbits[code];
  21942. if (extra !== 0) {
  21943. lc -= base_length[code];
  21944. send_bits(s, lc, extra); /* send the extra length bits */
  21945. }
  21946. dist--; /* dist is now the match distance - 1 */
  21947. code = d_code(dist);
  21948. //Assert (code < D_CODES, "bad d_code");
  21949. send_code(s, code, dtree); /* send the distance code */
  21950. extra = extra_dbits[code];
  21951. if (extra !== 0) {
  21952. dist -= base_dist[code];
  21953. send_bits(s, dist, extra); /* send the extra distance bits */
  21954. }
  21955. } /* literal or match pair ? */
  21956. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  21957. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  21958. // "pendingBuf overflow");
  21959. } while (lx < s.last_lit);
  21960. }
  21961. send_code(s, END_BLOCK, ltree);
  21962. }
  21963. /* ===========================================================================
  21964. * Construct one Huffman tree and assigns the code bit strings and lengths.
  21965. * Update the total bit length for the current block.
  21966. * IN assertion: the field freq is set for all tree elements.
  21967. * OUT assertions: the fields len and code are set to the optimal bit length
  21968. * and corresponding code. The length opt_len is updated; static_len is
  21969. * also updated if stree is not null. The field max_code is set.
  21970. */
  21971. function build_tree(s, desc)
  21972. // deflate_state *s;
  21973. // tree_desc *desc; /* the tree descriptor */
  21974. {
  21975. var tree = desc.dyn_tree;
  21976. var stree = desc.stat_desc.static_tree;
  21977. var has_stree = desc.stat_desc.has_stree;
  21978. var elems = desc.stat_desc.elems;
  21979. var n, m; /* iterate over heap elements */
  21980. var max_code = -1; /* largest code with non zero frequency */
  21981. var node; /* new node being created */
  21982. /* Construct the initial heap, with least frequent element in
  21983. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  21984. * heap[0] is not used.
  21985. */
  21986. s.heap_len = 0;
  21987. s.heap_max = HEAP_SIZE;
  21988. for (n = 0; n < elems; n++) {
  21989. if (tree[n * 2]/*.Freq*/ !== 0) {
  21990. s.heap[++s.heap_len] = max_code = n;
  21991. s.depth[n] = 0;
  21992. } else {
  21993. tree[n*2 + 1]/*.Len*/ = 0;
  21994. }
  21995. }
  21996. /* The pkzip format requires that at least one distance code exists,
  21997. * and that at least one bit should be sent even if there is only one
  21998. * possible code. So to avoid special checks later on we force at least
  21999. * two codes of non zero frequency.
  22000. */
  22001. while (s.heap_len < 2) {
  22002. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  22003. tree[node * 2]/*.Freq*/ = 1;
  22004. s.depth[node] = 0;
  22005. s.opt_len--;
  22006. if (has_stree) {
  22007. s.static_len -= stree[node*2 + 1]/*.Len*/;
  22008. }
  22009. /* node is 0 or 1 so it does not have extra bits */
  22010. }
  22011. desc.max_code = max_code;
  22012. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  22013. * establish sub-heaps of increasing lengths:
  22014. */
  22015. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  22016. /* Construct the Huffman tree by repeatedly combining the least two
  22017. * frequent nodes.
  22018. */
  22019. node = elems; /* next internal node of the tree */
  22020. do {
  22021. //pqremove(s, tree, n); /* n = node of least frequency */
  22022. /*** pqremove ***/
  22023. n = s.heap[1/*SMALLEST*/];
  22024. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  22025. pqdownheap(s, tree, 1/*SMALLEST*/);
  22026. /***/
  22027. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  22028. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  22029. s.heap[--s.heap_max] = m;
  22030. /* Create a new node father of n and m */
  22031. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  22032. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  22033. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  22034. /* and insert the new node in the heap */
  22035. s.heap[1/*SMALLEST*/] = node++;
  22036. pqdownheap(s, tree, 1/*SMALLEST*/);
  22037. } while (s.heap_len >= 2);
  22038. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  22039. /* At this point, the fields freq and dad are set. We can now
  22040. * generate the bit lengths.
  22041. */
  22042. gen_bitlen(s, desc);
  22043. /* The field len is now set, we can generate the bit codes */
  22044. gen_codes(tree, max_code, s.bl_count);
  22045. }
  22046. /* ===========================================================================
  22047. * Scan a literal or distance tree to determine the frequencies of the codes
  22048. * in the bit length tree.
  22049. */
  22050. function scan_tree(s, tree, max_code)
  22051. // deflate_state *s;
  22052. // ct_data *tree; /* the tree to be scanned */
  22053. // int max_code; /* and its largest code of non zero frequency */
  22054. {
  22055. var n; /* iterates over all tree elements */
  22056. var prevlen = -1; /* last emitted length */
  22057. var curlen; /* length of current code */
  22058. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  22059. var count = 0; /* repeat count of the current code */
  22060. var max_count = 7; /* max repeat count */
  22061. var min_count = 4; /* min repeat count */
  22062. if (nextlen === 0) {
  22063. max_count = 138;
  22064. min_count = 3;
  22065. }
  22066. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  22067. for (n = 0; n <= max_code; n++) {
  22068. curlen = nextlen;
  22069. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  22070. if (++count < max_count && curlen === nextlen) {
  22071. continue;
  22072. } else if (count < min_count) {
  22073. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  22074. } else if (curlen !== 0) {
  22075. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  22076. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  22077. } else if (count <= 10) {
  22078. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  22079. } else {
  22080. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  22081. }
  22082. count = 0;
  22083. prevlen = curlen;
  22084. if (nextlen === 0) {
  22085. max_count = 138;
  22086. min_count = 3;
  22087. } else if (curlen === nextlen) {
  22088. max_count = 6;
  22089. min_count = 3;
  22090. } else {
  22091. max_count = 7;
  22092. min_count = 4;
  22093. }
  22094. }
  22095. }
  22096. /* ===========================================================================
  22097. * Send a literal or distance tree in compressed form, using the codes in
  22098. * bl_tree.
  22099. */
  22100. function send_tree(s, tree, max_code)
  22101. // deflate_state *s;
  22102. // ct_data *tree; /* the tree to be scanned */
  22103. // int max_code; /* and its largest code of non zero frequency */
  22104. {
  22105. var n; /* iterates over all tree elements */
  22106. var prevlen = -1; /* last emitted length */
  22107. var curlen; /* length of current code */
  22108. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  22109. var count = 0; /* repeat count of the current code */
  22110. var max_count = 7; /* max repeat count */
  22111. var min_count = 4; /* min repeat count */
  22112. /* tree[max_code+1].Len = -1; */ /* guard already set */
  22113. if (nextlen === 0) {
  22114. max_count = 138;
  22115. min_count = 3;
  22116. }
  22117. for (n = 0; n <= max_code; n++) {
  22118. curlen = nextlen;
  22119. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  22120. if (++count < max_count && curlen === nextlen) {
  22121. continue;
  22122. } else if (count < min_count) {
  22123. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  22124. } else if (curlen !== 0) {
  22125. if (curlen !== prevlen) {
  22126. send_code(s, curlen, s.bl_tree);
  22127. count--;
  22128. }
  22129. //Assert(count >= 3 && count <= 6, " 3_6?");
  22130. send_code(s, REP_3_6, s.bl_tree);
  22131. send_bits(s, count-3, 2);
  22132. } else if (count <= 10) {
  22133. send_code(s, REPZ_3_10, s.bl_tree);
  22134. send_bits(s, count-3, 3);
  22135. } else {
  22136. send_code(s, REPZ_11_138, s.bl_tree);
  22137. send_bits(s, count-11, 7);
  22138. }
  22139. count = 0;
  22140. prevlen = curlen;
  22141. if (nextlen === 0) {
  22142. max_count = 138;
  22143. min_count = 3;
  22144. } else if (curlen === nextlen) {
  22145. max_count = 6;
  22146. min_count = 3;
  22147. } else {
  22148. max_count = 7;
  22149. min_count = 4;
  22150. }
  22151. }
  22152. }
  22153. /* ===========================================================================
  22154. * Construct the Huffman tree for the bit lengths and return the index in
  22155. * bl_order of the last bit length code to send.
  22156. */
  22157. function build_bl_tree(s) {
  22158. var max_blindex; /* index of last bit length code of non zero freq */
  22159. /* Determine the bit length frequencies for literal and distance trees */
  22160. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  22161. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  22162. /* Build the bit length tree: */
  22163. build_tree(s, s.bl_desc);
  22164. /* opt_len now includes the length of the tree representations, except
  22165. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  22166. */
  22167. /* Determine the number of bit length codes to send. The pkzip format
  22168. * requires that at least 4 bit length codes be sent. (appnote.txt says
  22169. * 3 but the actual value used is 4.)
  22170. */
  22171. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  22172. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  22173. break;
  22174. }
  22175. }
  22176. /* Update opt_len to include the bit length tree and counts */
  22177. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  22178. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  22179. // s->opt_len, s->static_len));
  22180. return max_blindex;
  22181. }
  22182. /* ===========================================================================
  22183. * Send the header for a block using dynamic Huffman trees: the counts, the
  22184. * lengths of the bit length codes, the literal tree and the distance tree.
  22185. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  22186. */
  22187. function send_all_trees(s, lcodes, dcodes, blcodes)
  22188. // deflate_state *s;
  22189. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  22190. {
  22191. var rank; /* index in bl_order */
  22192. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  22193. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  22194. // "too many codes");
  22195. //Tracev((stderr, "\nbl counts: "));
  22196. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  22197. send_bits(s, dcodes-1, 5);
  22198. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  22199. for (rank = 0; rank < blcodes; rank++) {
  22200. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  22201. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  22202. }
  22203. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  22204. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  22205. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  22206. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  22207. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  22208. }
  22209. /* ===========================================================================
  22210. * Check if the data type is TEXT or BINARY, using the following algorithm:
  22211. * - TEXT if the two conditions below are satisfied:
  22212. * a) There are no non-portable control characters belonging to the
  22213. * "black list" (0..6, 14..25, 28..31).
  22214. * b) There is at least one printable character belonging to the
  22215. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  22216. * - BINARY otherwise.
  22217. * - The following partially-portable control characters form a
  22218. * "gray list" that is ignored in this detection algorithm:
  22219. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  22220. * IN assertion: the fields Freq of dyn_ltree are set.
  22221. */
  22222. function detect_data_type(s) {
  22223. /* black_mask is the bit mask of black-listed bytes
  22224. * set bits 0..6, 14..25, and 28..31
  22225. * 0xf3ffc07f = binary 11110011111111111100000001111111
  22226. */
  22227. var black_mask = 0xf3ffc07f;
  22228. var n;
  22229. /* Check for non-textual ("black-listed") bytes. */
  22230. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  22231. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  22232. return Z_BINARY;
  22233. }
  22234. }
  22235. /* Check for textual ("white-listed") bytes. */
  22236. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  22237. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  22238. return Z_TEXT;
  22239. }
  22240. for (n = 32; n < LITERALS; n++) {
  22241. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  22242. return Z_TEXT;
  22243. }
  22244. }
  22245. /* There are no "black-listed" or "white-listed" bytes:
  22246. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  22247. */
  22248. return Z_BINARY;
  22249. }
  22250. var static_init_done = false;
  22251. /* ===========================================================================
  22252. * Initialize the tree data structures for a new zlib stream.
  22253. */
  22254. function _tr_init(s)
  22255. {
  22256. if (!static_init_done) {
  22257. tr_static_init();
  22258. static_init_done = true;
  22259. }
  22260. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  22261. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  22262. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  22263. s.bi_buf = 0;
  22264. s.bi_valid = 0;
  22265. /* Initialize the first block of the first file: */
  22266. init_block(s);
  22267. }
  22268. /* ===========================================================================
  22269. * Send a stored block
  22270. */
  22271. function _tr_stored_block(s, buf, stored_len, last)
  22272. //DeflateState *s;
  22273. //charf *buf; /* input block */
  22274. //ulg stored_len; /* length of input block */
  22275. //int last; /* one if this is the last block for a file */
  22276. {
  22277. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  22278. copy_block(s, buf, stored_len, true); /* with header */
  22279. }
  22280. /* ===========================================================================
  22281. * Send one empty static block to give enough lookahead for inflate.
  22282. * This takes 10 bits, of which 7 may remain in the bit buffer.
  22283. */
  22284. function _tr_align(s) {
  22285. send_bits(s, STATIC_TREES<<1, 3);
  22286. send_code(s, END_BLOCK, static_ltree);
  22287. bi_flush(s);
  22288. }
  22289. /* ===========================================================================
  22290. * Determine the best encoding for the current block: dynamic trees, static
  22291. * trees or store, and output the encoded block to the zip file.
  22292. */
  22293. function _tr_flush_block(s, buf, stored_len, last)
  22294. //DeflateState *s;
  22295. //charf *buf; /* input block, or NULL if too old */
  22296. //ulg stored_len; /* length of input block */
  22297. //int last; /* one if this is the last block for a file */
  22298. {
  22299. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  22300. var max_blindex = 0; /* index of last bit length code of non zero freq */
  22301. /* Build the Huffman trees unless a stored block is forced */
  22302. if (s.level > 0) {
  22303. /* Check if the file is binary or text */
  22304. if (s.strm.data_type === Z_UNKNOWN) {
  22305. s.strm.data_type = detect_data_type(s);
  22306. }
  22307. /* Construct the literal and distance trees */
  22308. build_tree(s, s.l_desc);
  22309. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  22310. // s->static_len));
  22311. build_tree(s, s.d_desc);
  22312. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  22313. // s->static_len));
  22314. /* At this point, opt_len and static_len are the total bit lengths of
  22315. * the compressed block data, excluding the tree representations.
  22316. */
  22317. /* Build the bit length tree for the above two trees, and get the index
  22318. * in bl_order of the last bit length code to send.
  22319. */
  22320. max_blindex = build_bl_tree(s);
  22321. /* Determine the best encoding. Compute the block lengths in bytes. */
  22322. opt_lenb = (s.opt_len+3+7) >>> 3;
  22323. static_lenb = (s.static_len+3+7) >>> 3;
  22324. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  22325. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  22326. // s->last_lit));
  22327. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  22328. } else {
  22329. // Assert(buf != (char*)0, "lost buf");
  22330. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  22331. }
  22332. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  22333. /* 4: two words for the lengths */
  22334. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  22335. * Otherwise we can't have processed more than WSIZE input bytes since
  22336. * the last block flush, because compression would have been
  22337. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  22338. * transform a block into a stored block.
  22339. */
  22340. _tr_stored_block(s, buf, stored_len, last);
  22341. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  22342. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  22343. compress_block(s, static_ltree, static_dtree);
  22344. } else {
  22345. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  22346. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  22347. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  22348. }
  22349. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  22350. /* The above check is made mod 2^32, for files larger than 512 MB
  22351. * and uLong implemented on 32 bits.
  22352. */
  22353. init_block(s);
  22354. if (last) {
  22355. bi_windup(s);
  22356. }
  22357. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  22358. // s->compressed_len-7*last));
  22359. }
  22360. /* ===========================================================================
  22361. * Save the match info and tally the frequency counts. Return true if
  22362. * the current block must be flushed.
  22363. */
  22364. function _tr_tally(s, dist, lc)
  22365. // deflate_state *s;
  22366. // unsigned dist; /* distance of matched string */
  22367. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  22368. {
  22369. //var out_length, in_length, dcode;
  22370. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  22371. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  22372. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  22373. s.last_lit++;
  22374. if (dist === 0) {
  22375. /* lc is the unmatched char */
  22376. s.dyn_ltree[lc*2]/*.Freq*/++;
  22377. } else {
  22378. s.matches++;
  22379. /* Here, lc is the match length - MIN_MATCH */
  22380. dist--; /* dist = match distance - 1 */
  22381. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  22382. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  22383. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  22384. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  22385. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  22386. }
  22387. // (!) This block is disabled in zlib defailts,
  22388. // don't enable it for binary compatibility
  22389. //#ifdef TRUNCATE_BLOCK
  22390. // /* Try to guess if it is profitable to stop the current block here */
  22391. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  22392. // /* Compute an upper bound for the compressed length */
  22393. // out_length = s.last_lit*8;
  22394. // in_length = s.strstart - s.block_start;
  22395. //
  22396. // for (dcode = 0; dcode < D_CODES; dcode++) {
  22397. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  22398. // }
  22399. // out_length >>>= 3;
  22400. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  22401. // // s->last_lit, in_length, out_length,
  22402. // // 100L - out_length*100L/in_length));
  22403. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  22404. // return true;
  22405. // }
  22406. // }
  22407. //#endif
  22408. return (s.last_lit === s.lit_bufsize-1);
  22409. /* We avoid equality with lit_bufsize because of wraparound at 64K
  22410. * on 16 bit machines and because stored blocks are restricted to
  22411. * 64K-1 bytes.
  22412. */
  22413. }
  22414. exports._tr_init = _tr_init;
  22415. exports._tr_stored_block = _tr_stored_block;
  22416. exports._tr_flush_block = _tr_flush_block;
  22417. exports._tr_tally = _tr_tally;
  22418. exports._tr_align = _tr_align;
  22419. },{"../utils/common":66}],78:[function(require,module,exports){
  22420. 'use strict';
  22421. function ZStream() {
  22422. /* next input byte */
  22423. this.input = null; // JS specific, because we have no pointers
  22424. this.next_in = 0;
  22425. /* number of bytes available at input */
  22426. this.avail_in = 0;
  22427. /* total number of input bytes read so far */
  22428. this.total_in = 0;
  22429. /* next output byte should be put there */
  22430. this.output = null; // JS specific, because we have no pointers
  22431. this.next_out = 0;
  22432. /* remaining free space at output */
  22433. this.avail_out = 0;
  22434. /* total number of bytes output so far */
  22435. this.total_out = 0;
  22436. /* last error message, NULL if no error */
  22437. this.msg = ''/*Z_NULL*/;
  22438. /* not visible by applications */
  22439. this.state = null;
  22440. /* best guess about the data type: binary or text */
  22441. this.data_type = 2/*Z_UNKNOWN*/;
  22442. /* adler32 value of the uncompressed data */
  22443. this.adler = 0;
  22444. }
  22445. module.exports = ZStream;
  22446. },{}],79:[function(require,module,exports){
  22447. module.exports = function arrayEquals(array) {
  22448. // if the other array is a falsy value, return
  22449. if (!array)
  22450. return false;
  22451. // compare lengths - can save a lot of time
  22452. if (this.length != array.length)
  22453. return false;
  22454. for (var i = 0, l = this.length; i < l; i++) {
  22455. // Check if we have nested arrays
  22456. if (this[i] instanceof Array && array[i] instanceof Array) {
  22457. // recurse into the nested arrays
  22458. if (!arrayEquals.apply(this[i], [array[i]]))
  22459. return false;
  22460. } else if (this[i] != array[i]) {
  22461. // Warning - two different object instances will never be equal:
  22462. // {x:20} != {x:20}
  22463. return false;
  22464. }
  22465. }
  22466. return true;
  22467. }
  22468. },{}],80:[function(require,module,exports){
  22469. exports.Interop = require('./interop');
  22470. },{"./interop":81}],81:[function(require,module,exports){
  22471. var transform = require('./transform');
  22472. var arrayEquals = require('./array-equals');
  22473. function Interop() { }
  22474. module.exports = Interop;
  22475. /**
  22476. * This map holds the most recent Plan A offer/answer SDP that was converted
  22477. * to Plan B, with the SDP type ('offer' or 'answer') as keys and the SDP
  22478. * string as values.
  22479. *
  22480. * @type {{}}
  22481. */
  22482. var cache = {};
  22483. /**
  22484. * This method transforms a Plan A SDP to an equivalent Plan B SDP. A
  22485. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  22486. * application.
  22487. *
  22488. * @param desc
  22489. * @returns {*}
  22490. */
  22491. Interop.prototype.toPlanB = function(desc) {
  22492. //#region Preliminary input validation.
  22493. if (typeof desc !== 'object' || desc === null ||
  22494. typeof desc.sdp !== 'string') {
  22495. console.warn('An empty description was passed as an argument.');
  22496. return desc;
  22497. }
  22498. // Objectify the SDP for easier manipulation.
  22499. var session = transform.parse(desc.sdp);
  22500. // If the SDP contains no media, there's nothing to transform.
  22501. if (typeof session.media === 'undefined' ||
  22502. !Array.isArray(session.media) || session.media.length === 0) {
  22503. console.warn('The description has no media.');
  22504. return desc;
  22505. }
  22506. // Try some heuristics to "make sure" this is a Plan A SDP. Plan B SDP has
  22507. // a video, an audio and a data "channel" at most.
  22508. if (session.media.length <= 3 && session.media.every(function(m) {
  22509. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  22510. })) {
  22511. console.warn('This description does not look like Plan A.');
  22512. return desc;
  22513. }
  22514. //#endregion
  22515. // Plan A SDP is our "precious". Cache it for later use in the Plan B ->
  22516. // Plan A transformation.
  22517. cache[desc.type] = desc.sdp;
  22518. //#region Convert from Plan A to Plan B.
  22519. // We rebuild the session.media array.
  22520. var media = session.media;
  22521. session.media = [];
  22522. // Associative array that maps channel types to channel objects for fast
  22523. // access to channel objects by their type, e.g. channels['audio']->channel
  22524. // obj.
  22525. var channels = {};
  22526. // Used to build the group:BUNDLE value after the channels construction
  22527. // loop.
  22528. var types = [];
  22529. // Implode the Plan A m-lines/tracks into Plan B "channels".
  22530. media.forEach(function(mLine) {
  22531. // rtcp-mux is required in the Plan B SDP.
  22532. if (typeof mLine.rtcpMux !== 'string' ||
  22533. mLine.rtcpMux !== 'rtcp-mux') {
  22534. throw new Error('Cannot convert to Plan B because m-lines ' +
  22535. 'without the rtcp-mux attribute were found.');
  22536. }
  22537. // If we don't have a channel for this mLine.type, then use this mLine
  22538. // as the channel basis.
  22539. if (typeof channels[mLine.type] === 'undefined') {
  22540. channels[mLine.type] = mLine;
  22541. }
  22542. // Add sources to the channel and handle a=msid.
  22543. if (typeof mLine.sources === 'object') {
  22544. Object.keys(mLine.sources).forEach(function(ssrc) {
  22545. // Assign the sources to the channel.
  22546. channels[mLine.type].sources[ssrc] = mLine.sources[ssrc];
  22547. // In Plan B the msid is an SSRC attribute. Also, we don't care
  22548. // about the obsolete label and mslabel attributes.
  22549. channels[mLine.type].sources[ssrc].msid = mLine.msid;
  22550. // NOTE ssrcs in ssrc groups will share msids, as
  22551. // draft-uberti-rtcweb-plan-00 mandates.
  22552. });
  22553. }
  22554. // Add ssrc groups to the channel.
  22555. if (typeof mLine.ssrcGroups !== 'undefined' &&
  22556. Array.isArray(mLine.ssrcGroups)) {
  22557. // Create the ssrcGroups array, if it's not defined.
  22558. if (typeof channel.ssrcGroups === 'undefined' ||
  22559. !Array.isArray(channel.ssrcGroups)) {
  22560. channel.ssrcGroups = [];
  22561. }
  22562. channel.ssrcGroups = channel.ssrcGroups.concat(mLine.ssrcGroups);
  22563. }
  22564. if (channels[mLine.type] === mLine) {
  22565. // Copy ICE related stuff from the principal media line.
  22566. mLine.candidates = media[0].candidates;
  22567. mLine.iceUfrag = media[0].iceUfrag;
  22568. mLine.icePwd = media[0].icePwd;
  22569. mLine.fingerprint = media[0].fingerprint;
  22570. // Plan B mids are in ['audio', 'video', 'data']
  22571. mLine.mid = mLine.type;
  22572. // Plan B doesn't support/need the bundle-only attribute.
  22573. delete mLine.bundleOnly;
  22574. // In Plan B the msid is an SSRC attribute.
  22575. delete mLine.msid;
  22576. // Used to build the group:BUNDLE value after this loop.
  22577. types.push(mLine.type);
  22578. // Add the channel to the new media array.
  22579. session.media.push(mLine);
  22580. }
  22581. });
  22582. // We regenerate the BUNDLE group with the new mids.
  22583. session.groups.every(function(group) {
  22584. if (group.type === 'BUNDLE') {
  22585. group.mids = types.join(' ');
  22586. return false;
  22587. } else {
  22588. return true;
  22589. }
  22590. });
  22591. // msid semantic
  22592. session.msidSemantic = {
  22593. semantic: 'WMS',
  22594. token: '*'
  22595. };
  22596. var resStr = transform.write(session);
  22597. return new RTCSessionDescription({
  22598. type: desc.type,
  22599. sdp: resStr
  22600. });
  22601. //#endregion
  22602. };
  22603. /**
  22604. * This method transforms a Plan B SDP to an equivalent Plan A SDP. A
  22605. * PeerConnection wrapper transforms the SDP to Plan A before passing it to FF.
  22606. *
  22607. * @param desc
  22608. * @returns {*}
  22609. */
  22610. Interop.prototype.toPlanA = function(desc) {
  22611. //#region Preliminary input validation.
  22612. if (typeof desc !== 'object' || desc === null ||
  22613. typeof desc.sdp !== 'string') {
  22614. console.warn('An empty description was passed as an argument.');
  22615. return desc;
  22616. }
  22617. var session = transform.parse(desc.sdp);
  22618. // If the SDP contains no media, there's nothing to transform.
  22619. if (typeof session.media === 'undefined' ||
  22620. !Array.isArray(session.media) || session.media.length === 0) {
  22621. console.warn('The description has no media.');
  22622. return desc;
  22623. }
  22624. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  22625. // a video, an audio and a data "channel" at most.
  22626. if (session.media.length > 3 || !session.media.every(function(m) {
  22627. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  22628. })) {
  22629. console.warn('This description does not look like Plan B.');
  22630. return desc;
  22631. }
  22632. // Make sure this Plan B SDP can be converted to a Plan A SDP.
  22633. var mids = [];
  22634. session.media.forEach(function(m) {
  22635. mids.push(m.mid);
  22636. });
  22637. var hasBundle = false;
  22638. if (typeof session.groups !== 'undefined' &&
  22639. Array.isArray(session.groups)) {
  22640. hasBundle = session.groups.every(function(g) {
  22641. return g.type !== 'BUNDLE' ||
  22642. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  22643. });
  22644. }
  22645. if (!hasBundle) {
  22646. throw new Error("Cannot convert to Plan A because m-lines that are " +
  22647. "not bundled were found.");
  22648. }
  22649. //#endregion
  22650. //#region Convert from Plan B to Plan A.
  22651. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  22652. // rebuild an equivalent Plan A offer/answer.
  22653. //
  22654. // For example, if this is a local answer (in Plan A style) that we convert
  22655. // to Plan B prior to handing it over to the application (the
  22656. // PeerConnection wrapper called us, for instance, after a successful
  22657. // createAnswer), we want to remember the m-line at which we've seen the
  22658. // (local) SSRC. That's because when the application wants to do call the
  22659. // SLD method, forcing us to do the inverse transformation (from Plan B to
  22660. // Plan A), we need to know to which m-line to assign the (local) SSRC. We
  22661. // also need to know all the other m-lines that the original answer had and
  22662. // include them in the transformed answer as well.
  22663. //
  22664. // Another example is if this is a remote offer that we convert to Plan B
  22665. // prior to giving it to the application, we want to remember the mid at
  22666. // which we've seen the (remote) SSRC.
  22667. //
  22668. // In the iteration that follows, we use the cached Plan A (if it exists)
  22669. // to assign mids to ssrcs.
  22670. var cached;
  22671. if (typeof cache[desc.type] !== 'undefined') {
  22672. cached = transform.parse(cache[desc.type]);
  22673. }
  22674. // A helper map that sends mids to m-line objects. We use it later to
  22675. // rebuild the Plan A style session.media array.
  22676. var media = {};
  22677. session.media.forEach(function(channel) {
  22678. if (typeof channel.rtcpMux !== 'string' ||
  22679. channel.rtcpMux !== 'rtcp-mux') {
  22680. throw new Error("Cannot convert to Plan A because m-lines " +
  22681. "without the rtcp-mux attribute were found.");
  22682. }
  22683. // With rtcp-mux and bundle all the channels should have the same ICE
  22684. // stuff.
  22685. var sources = channel.sources;
  22686. var ssrcGroups = channel.ssrcGroups;
  22687. var candidates = channel.candidates;
  22688. var iceUfrag = channel.iceUfrag;
  22689. var icePwd = channel.icePwd;
  22690. var fingerprint = channel.fingerprint;
  22691. var port = channel.port;
  22692. // We'll use the "channel" object as a prototype for each new "mLine"
  22693. // that we create, but first we need to clean it up a bit.
  22694. delete channel.sources;
  22695. delete channel.ssrcGroups;
  22696. delete channel.candidates;
  22697. delete channel.iceUfrag;
  22698. delete channel.icePwd;
  22699. delete channel.fingerprint;
  22700. delete channel.port;
  22701. delete channel.mid;
  22702. // inverted ssrc group map
  22703. var invertedGroups = {};
  22704. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  22705. ssrcGroups.forEach(function (ssrcGroup) {
  22706. // TODO(gp) find out how to receive simulcast with FF. For the
  22707. // time being, hide it.
  22708. if (ssrcGroup.semantics === 'SIM') {
  22709. return;
  22710. }
  22711. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  22712. Array.isArray(ssrcGroup.ssrcs)) {
  22713. ssrcGroup.ssrcs.forEach(function (ssrc) {
  22714. if (typeof invertedGroups[ssrc] === 'undefined') {
  22715. invertedGroups[ssrc] = [];
  22716. }
  22717. invertedGroups[ssrc].push(ssrcGroup);
  22718. });
  22719. }
  22720. });
  22721. }
  22722. // ssrc to m-line index.
  22723. var mLines = {};
  22724. if (typeof sources === 'object') {
  22725. // Explode the Plan B channel sources with one m-line per source.
  22726. Object.keys(sources).forEach(function(ssrc) {
  22727. var mLine;
  22728. if (typeof invertedGroups[ssrc] !== 'undefined' &&
  22729. Array.isArray(invertedGroups[ssrc])) {
  22730. invertedGroups[ssrc].every(function (ssrcGroup) {
  22731. // ssrcGroup.ssrcs *is* an Array, no need to check
  22732. // again here.
  22733. return ssrcGroup.ssrcs.every(function (related) {
  22734. if (typeof mLines[related] === 'object') {
  22735. mLine = mLines[related];
  22736. return false;
  22737. } else {
  22738. return true;
  22739. }
  22740. });
  22741. });
  22742. }
  22743. if (typeof mLine === 'object') {
  22744. // the m-line already exists. Just add the source.
  22745. mLine.sources[ssrc] = sources[ssrc];
  22746. delete sources[ssrc].msid;
  22747. } else {
  22748. // Use the "channel" as a prototype for the "mLine".
  22749. mLine = Object.create(channel);
  22750. mLines[ssrc] = mLine;
  22751. // Assign the msid of the source to the m-line.
  22752. mLine.msid = sources[ssrc].msid;
  22753. delete sources[ssrc].msid;
  22754. // We assign one SSRC per media line.
  22755. mLine.sources = {};
  22756. mLine.sources[ssrc] = sources[ssrc];
  22757. mLine.ssrcGroups = invertedGroups[ssrc];
  22758. // Use the cached Plan A SDP (if it exists) to assign SSRCs to
  22759. // mids.
  22760. if (typeof cached !== 'undefined' &&
  22761. typeof cached.media !== 'undefined' &&
  22762. Array.isArray(cached.media)) {
  22763. cached.media.forEach(function(m) {
  22764. if (typeof m.sources === 'object') {
  22765. Object.keys(m.sources).forEach(function(s) {
  22766. if (s === ssrc) {
  22767. mLine.mid = m.mid;
  22768. }
  22769. });
  22770. }
  22771. });
  22772. }
  22773. if (typeof mLine.mid === 'undefined') {
  22774. // If this is an SSRC that we see for the first time assign
  22775. // it a new mid. This is typically the case when this
  22776. // method is called to transform a remote description for
  22777. // the first time or when there is a new SSRC in the remote
  22778. // description because a new peer has joined the
  22779. // conference. Local SSRCs should have already been added
  22780. // to the map in the toPlanB method.
  22781. //
  22782. // Because FF generates answers in Plan A style, we MUST
  22783. // already have a cached answer with all the local SSRCs
  22784. // mapped to some mLine/mid.
  22785. if (desc.type === 'answer') {
  22786. throw new Error("An unmapped SSRC was found.");
  22787. }
  22788. mLine.mid = [channel.type, '-', ssrc].join('');
  22789. }
  22790. // Include the candidates in the 1st media line.
  22791. mLine.candidates = candidates;
  22792. mLine.iceUfrag = iceUfrag;
  22793. mLine.icePwd = icePwd;
  22794. mLine.fingerprint = fingerprint;
  22795. mLine.port = port;
  22796. media[mLine.mid] = mLine;
  22797. }
  22798. });
  22799. }
  22800. });
  22801. // Rebuild the media array in the right order and add the missing mLines
  22802. // (missing from the Plan B SDP).
  22803. session.media = [];
  22804. mids = []; // reuse
  22805. if (desc.type === 'answer') {
  22806. // The media lines in the answer must match the media lines in the
  22807. // offer. The order is important too. Here we use the cached offer to
  22808. // find the m-lines that are missing (from the converted answer), and
  22809. // use the cached answer to complete the converted answer.
  22810. if (typeof cache['offer'] === 'undefined') {
  22811. throw new Error("An answer is being processed but we couldn't " +
  22812. "find a cached offer.");
  22813. }
  22814. var cachedOffer = transform.parse(cache['offer']);
  22815. if (typeof cachedOffer === 'undefined' ||
  22816. typeof cachedOffer.media === 'undefined' ||
  22817. !Array.isArray(cachedOffer.media)) {
  22818. // FIXME(gp) is this really a problem in the general case?
  22819. throw new Error("The cached offer has no media.");
  22820. }
  22821. cachedOffer.media.forEach(function(mo) {
  22822. var mLine;
  22823. if (typeof media[mo.mid] === 'undefined') {
  22824. // This is probably an m-line containing a remote track only.
  22825. // It MUST exist in the cached answer as a remote track only
  22826. // mLine.
  22827. cached.media.every(function(ma) {
  22828. if (mo.mid == ma.mid) {
  22829. mLine = ma;
  22830. return false;
  22831. } else {
  22832. return true;
  22833. }
  22834. });
  22835. } else {
  22836. mLine = media[mo.mid];
  22837. }
  22838. if (typeof mLine === 'undefined') {
  22839. throw new Error("The cached offer contains an m-line that " +
  22840. "doesn't exist neither in the cached answer nor in " +
  22841. "the converted answer.");
  22842. }
  22843. session.media.push(mLine);
  22844. mids.push(mLine.mid);
  22845. });
  22846. } else {
  22847. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  22848. // under any circumstances. If we are no longer interested in sending a
  22849. // track, we just remove the msid and ssrc attributes and set it to
  22850. // either a=recvonly (as the reofferer, we must use recvonly if the
  22851. // other side was previously sending on the m-section, but we can also
  22852. // leave the possibility open if it wasn't previously in use), or
  22853. // a=inacive.
  22854. if (typeof cached !== 'undefined' &&
  22855. typeof cached.media !== 'undefined' &&
  22856. Array.isArray(cached.media)) {
  22857. cached.media.forEach(function(pm) {
  22858. mids.push(pm.mid);
  22859. if (typeof media[pm.mid] !== 'undefined') {
  22860. session.media.push(media[pm.mid]);
  22861. } else {
  22862. delete pm.msid;
  22863. delete pm.sources;
  22864. delete pm.ssrcGroups;
  22865. pm.direction = 'recvonly';
  22866. session.media.push(pm);
  22867. }
  22868. });
  22869. }
  22870. // Add all the remaining (new) m-lines of the transformed SDP.
  22871. Object.keys(media).forEach(function(mid) {
  22872. if (mids.indexOf(mid) === -1) {
  22873. mids.push(mid);
  22874. session.media.push(media[mid]);
  22875. }
  22876. });
  22877. }
  22878. // We regenerate the BUNDLE group (since we regenerated the mids)
  22879. session.groups.every(function(group) {
  22880. if (group.type === 'BUNDLE') {
  22881. group.mids = mids.join(' ');
  22882. return false;
  22883. } else {
  22884. return true;
  22885. }
  22886. });
  22887. // msid semantic
  22888. session.msidSemantic = {
  22889. semantic: 'WMS',
  22890. token: '*'
  22891. };
  22892. var resStr = transform.write(session);
  22893. // Cache the transformed SDP (Plan A) for later re-use in this function.
  22894. cache[desc.type] = resStr;
  22895. return new RTCSessionDescription({
  22896. type: desc.type,
  22897. sdp: resStr
  22898. });
  22899. //#endregion
  22900. };
  22901. },{"./array-equals":79,"./transform":82}],82:[function(require,module,exports){
  22902. var transform = require('sdp-transform');
  22903. exports.write = function(session, opts) {
  22904. if (typeof session !== 'undefined' &&
  22905. typeof session.media !== 'undefined' &&
  22906. Array.isArray(session.media)) {
  22907. session.media.forEach(function (mLine) {
  22908. // expand sources to ssrcs
  22909. if (typeof mLine.sources !== 'undefined' &&
  22910. Object.keys(mLine.sources).length !== 0) {
  22911. mLine.ssrcs = [];
  22912. Object.keys(mLine.sources).forEach(function (ssrc) {
  22913. var source = mLine.sources[ssrc];
  22914. Object.keys(source).forEach(function (attribute) {
  22915. mLine.ssrcs.push({
  22916. id: ssrc,
  22917. attribute: attribute,
  22918. value: source[attribute]
  22919. });
  22920. });
  22921. });
  22922. delete mLine.sources;
  22923. }
  22924. // join ssrcs in ssrc groups
  22925. if (typeof mLine.ssrcGroups !== 'undefined' &&
  22926. Array.isArray(mLine.ssrcGroups)) {
  22927. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  22928. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  22929. Array.isArray(ssrcGroup.ssrcs)) {
  22930. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  22931. }
  22932. });
  22933. }
  22934. });
  22935. }
  22936. // join group mids
  22937. if (typeof session !== 'undefined' &&
  22938. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  22939. session.groups.forEach(function (g) {
  22940. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  22941. g.mids = g.mids.join(' ');
  22942. }
  22943. });
  22944. }
  22945. return transform.write(session, opts);
  22946. };
  22947. exports.parse = function(sdp) {
  22948. var session = transform.parse(sdp);
  22949. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  22950. Array.isArray(session.media)) {
  22951. session.media.forEach(function (mLine) {
  22952. // group sources attributes by ssrc
  22953. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  22954. mLine.sources = {};
  22955. mLine.ssrcs.forEach(function (ssrc) {
  22956. if (!mLine.sources[ssrc.id])
  22957. mLine.sources[ssrc.id] = {};
  22958. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  22959. });
  22960. delete mLine.ssrcs;
  22961. }
  22962. // split ssrcs in ssrc groups
  22963. if (typeof mLine.ssrcGroups !== 'undefined' &&
  22964. Array.isArray(mLine.ssrcGroups)) {
  22965. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  22966. if (typeof ssrcGroup.ssrcs === 'string') {
  22967. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  22968. }
  22969. });
  22970. }
  22971. });
  22972. }
  22973. // split group mids
  22974. if (typeof session !== 'undefined' &&
  22975. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  22976. session.groups.forEach(function (g) {
  22977. if (typeof g.mids === 'string') {
  22978. g.mids = g.mids.split(' ');
  22979. }
  22980. });
  22981. }
  22982. return session;
  22983. };
  22984. },{"sdp-transform":84}],83:[function(require,module,exports){
  22985. var grammar = module.exports = {
  22986. v: [{
  22987. name: 'version',
  22988. reg: /^(\d*)$/
  22989. }],
  22990. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  22991. // NB: sessionId will be a String in most cases because it is huge
  22992. name: 'origin',
  22993. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  22994. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  22995. format: "%s %s %d %s IP%d %s"
  22996. }],
  22997. // default parsing of these only (though some of these feel outdated)
  22998. s: [{ name: 'name' }],
  22999. i: [{ name: 'description' }],
  23000. u: [{ name: 'uri' }],
  23001. e: [{ name: 'email' }],
  23002. p: [{ name: 'phone' }],
  23003. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  23004. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  23005. //k: [{}], // outdated thing ignored
  23006. t: [{ //t=0 0
  23007. name: 'timing',
  23008. reg: /^(\d*) (\d*)/,
  23009. names: ['start', 'stop'],
  23010. format: "%d %d"
  23011. }],
  23012. c: [{ //c=IN IP4 10.47.197.26
  23013. name: 'connection',
  23014. reg: /^IN IP(\d) (\S*)/,
  23015. names: ['version', 'ip'],
  23016. format: "IN IP%d %s"
  23017. }],
  23018. b: [{ //b=AS:4000
  23019. push: 'bandwidth',
  23020. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  23021. names: ['type', 'limit'],
  23022. format: "%s:%s"
  23023. }],
  23024. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  23025. // NB: special - pushes to session
  23026. // TODO: rtp/fmtp should be filtered by the payloads found here?
  23027. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  23028. names: ['type', 'port', 'protocol', 'payloads'],
  23029. format: "%s %d %s %s"
  23030. }],
  23031. a: [
  23032. { //a=rtpmap:110 opus/48000/2
  23033. push: 'rtp',
  23034. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  23035. names: ['payload', 'codec', 'rate', 'encoding'],
  23036. format: function (o) {
  23037. return (o.encoding) ?
  23038. "rtpmap:%d %s/%s/%s":
  23039. "rtpmap:%d %s/%s";
  23040. }
  23041. },
  23042. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  23043. push: 'fmtp',
  23044. reg: /^fmtp:(\d*) (\S*)/,
  23045. names: ['payload', 'config'],
  23046. format: "fmtp:%d %s"
  23047. },
  23048. { //a=control:streamid=0
  23049. name: 'control',
  23050. reg: /^control:(.*)/,
  23051. format: "control:%s"
  23052. },
  23053. { //a=rtcp:65179 IN IP4 193.84.77.194
  23054. name: 'rtcp',
  23055. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  23056. names: ['port', 'netType', 'ipVer', 'address'],
  23057. format: function (o) {
  23058. return (o.address != null) ?
  23059. "rtcp:%d %s IP%d %s":
  23060. "rtcp:%d";
  23061. }
  23062. },
  23063. { //a=rtcp-fb:98 trr-int 100
  23064. push: 'rtcpFbTrrInt',
  23065. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  23066. names: ['payload', 'value'],
  23067. format: "rtcp-fb:%d trr-int %d"
  23068. },
  23069. { //a=rtcp-fb:98 nack rpsi
  23070. push: 'rtcpFb',
  23071. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  23072. names: ['payload', 'type', 'subtype'],
  23073. format: function (o) {
  23074. return (o.subtype != null) ?
  23075. "rtcp-fb:%s %s %s":
  23076. "rtcp-fb:%s %s";
  23077. }
  23078. },
  23079. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  23080. //a=extmap:1/recvonly URI-gps-string
  23081. push: 'ext',
  23082. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  23083. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  23084. format: function (o) {
  23085. return (o.config != null) ?
  23086. "extmap:%s %s %s":
  23087. "extmap:%s %s";
  23088. }
  23089. },
  23090. {
  23091. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  23092. push: 'crypto',
  23093. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  23094. names: ['id', 'suite', 'config', 'sessionConfig'],
  23095. format: function (o) {
  23096. return (o.sessionConfig != null) ?
  23097. "crypto:%d %s %s %s":
  23098. "crypto:%d %s %s";
  23099. }
  23100. },
  23101. { //a=setup:actpass
  23102. name: 'setup',
  23103. reg: /^setup:(\w*)/,
  23104. format: "setup:%s"
  23105. },
  23106. { //a=mid:1
  23107. name: 'mid',
  23108. reg: /^mid:([^\s]*)/,
  23109. format: "mid:%s"
  23110. },
  23111. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  23112. name: 'msid',
  23113. reg: /^msid:(.*)/,
  23114. format: "msid:%s"
  23115. },
  23116. { //a=ptime:20
  23117. name: 'ptime',
  23118. reg: /^ptime:(\d*)/,
  23119. format: "ptime:%d"
  23120. },
  23121. { //a=maxptime:60
  23122. name: 'maxptime',
  23123. reg: /^maxptime:(\d*)/,
  23124. format: "maxptime:%d"
  23125. },
  23126. { //a=sendrecv
  23127. name: 'direction',
  23128. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  23129. },
  23130. { //a=ice-lite
  23131. name: 'icelite',
  23132. reg: /^(ice-lite)/
  23133. },
  23134. { //a=ice-ufrag:F7gI
  23135. name: 'iceUfrag',
  23136. reg: /^ice-ufrag:(\S*)/,
  23137. format: "ice-ufrag:%s"
  23138. },
  23139. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  23140. name: 'icePwd',
  23141. reg: /^ice-pwd:(\S*)/,
  23142. format: "ice-pwd:%s"
  23143. },
  23144. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  23145. name: 'fingerprint',
  23146. reg: /^fingerprint:(\S*) (\S*)/,
  23147. names: ['type', 'hash'],
  23148. format: "fingerprint:%s %s"
  23149. },
  23150. {
  23151. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  23152. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  23153. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  23154. push:'candidates',
  23155. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  23156. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  23157. format: function (o) {
  23158. var str = "candidate:%s %d %s %d %s %d typ %s";
  23159. // NB: candidate has two optional chunks, so %void middle one if it's missing
  23160. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  23161. if (o.generation != null) {
  23162. str += " generation %d";
  23163. }
  23164. return str;
  23165. }
  23166. },
  23167. { //a=end-of-candidates (keep after the candidates line for readability)
  23168. name: 'endOfCandidates',
  23169. reg: /^(end-of-candidates)/
  23170. },
  23171. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  23172. name: 'remoteCandidates',
  23173. reg: /^remote-candidates:(.*)/,
  23174. format: "remote-candidates:%s"
  23175. },
  23176. { //a=ice-options:google-ice
  23177. name: 'iceOptions',
  23178. reg: /^ice-options:(\S*)/,
  23179. format: "ice-options:%s"
  23180. },
  23181. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  23182. push: "ssrcs",
  23183. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  23184. names: ['id', 'attribute', 'value'],
  23185. format: "ssrc:%d %s:%s"
  23186. },
  23187. { //a=ssrc-group:FEC 1 2
  23188. push: "ssrcGroups",
  23189. reg: /^ssrc-group:(\w*) (.*)/,
  23190. names: ['semantics', 'ssrcs'],
  23191. format: "ssrc-group:%s %s"
  23192. },
  23193. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  23194. name: "msidSemantic",
  23195. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  23196. names: ['semantic', 'token'],
  23197. format: "msid-semantic: %s %s" // space after ":" is not accidental
  23198. },
  23199. { //a=group:BUNDLE audio video
  23200. push: 'groups',
  23201. reg: /^group:(\w*) (.*)/,
  23202. names: ['type', 'mids'],
  23203. format: "group:%s %s"
  23204. },
  23205. { //a=rtcp-mux
  23206. name: 'rtcpMux',
  23207. reg: /^(rtcp-mux)/
  23208. },
  23209. { // any a= that we don't understand is kepts verbatim on media.invalid
  23210. push: 'invalid',
  23211. names: ["value"]
  23212. }
  23213. ]
  23214. };
  23215. // set sensible defaults to avoid polluting the grammar with boring details
  23216. Object.keys(grammar).forEach(function (key) {
  23217. var objs = grammar[key];
  23218. objs.forEach(function (obj) {
  23219. if (!obj.reg) {
  23220. obj.reg = /(.*)/;
  23221. }
  23222. if (!obj.format) {
  23223. obj.format = "%s";
  23224. }
  23225. });
  23226. });
  23227. },{}],84:[function(require,module,exports){
  23228. var parser = require('./parser');
  23229. var writer = require('./writer');
  23230. exports.write = writer;
  23231. exports.parse = parser.parse;
  23232. exports.parseFmtpConfig = parser.parseFmtpConfig;
  23233. exports.parsePayloads = parser.parsePayloads;
  23234. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  23235. },{"./parser":85,"./writer":86}],85:[function(require,module,exports){
  23236. var toIntIfInt = function (v) {
  23237. return String(Number(v)) === v ? Number(v) : v;
  23238. };
  23239. var attachProperties = function (match, location, names, rawName) {
  23240. if (rawName && !names) {
  23241. location[rawName] = toIntIfInt(match[1]);
  23242. }
  23243. else {
  23244. for (var i = 0; i < names.length; i += 1) {
  23245. if (match[i+1] != null) {
  23246. location[names[i]] = toIntIfInt(match[i+1]);
  23247. }
  23248. }
  23249. }
  23250. };
  23251. var parseReg = function (obj, location, content) {
  23252. var needsBlank = obj.name && obj.names;
  23253. if (obj.push && !location[obj.push]) {
  23254. location[obj.push] = [];
  23255. }
  23256. else if (needsBlank && !location[obj.name]) {
  23257. location[obj.name] = {};
  23258. }
  23259. var keyLocation = obj.push ?
  23260. {} : // blank object that will be pushed
  23261. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  23262. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  23263. if (obj.push) {
  23264. location[obj.push].push(keyLocation);
  23265. }
  23266. };
  23267. var grammar = require('./grammar');
  23268. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  23269. exports.parse = function (sdp) {
  23270. var session = {}
  23271. , media = []
  23272. , location = session; // points at where properties go under (one of the above)
  23273. // parse lines we understand
  23274. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  23275. var type = l[0];
  23276. var content = l.slice(2);
  23277. if (type === 'm') {
  23278. media.push({rtp: [], fmtp: []});
  23279. location = media[media.length-1]; // point at latest media line
  23280. }
  23281. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  23282. var obj = grammar[type][j];
  23283. if (obj.reg.test(content)) {
  23284. return parseReg(obj, location, content);
  23285. }
  23286. }
  23287. });
  23288. session.media = media; // link it up
  23289. return session;
  23290. };
  23291. var fmtpReducer = function (acc, expr) {
  23292. var s = expr.split('=');
  23293. if (s.length === 2) {
  23294. acc[s[0]] = toIntIfInt(s[1]);
  23295. }
  23296. return acc;
  23297. };
  23298. exports.parseFmtpConfig = function (str) {
  23299. return str.split(';').reduce(fmtpReducer, {});
  23300. };
  23301. exports.parsePayloads = function (str) {
  23302. return str.split(' ').map(Number);
  23303. };
  23304. exports.parseRemoteCandidates = function (str) {
  23305. var candidates = [];
  23306. var parts = str.split(' ').map(toIntIfInt);
  23307. for (var i = 0; i < parts.length; i += 3) {
  23308. candidates.push({
  23309. component: parts[i],
  23310. ip: parts[i + 1],
  23311. port: parts[i + 2]
  23312. });
  23313. }
  23314. return candidates;
  23315. };
  23316. },{"./grammar":83}],86:[function(require,module,exports){
  23317. var grammar = require('./grammar');
  23318. // customized util.format - discards excess arguments and can void middle ones
  23319. var formatRegExp = /%[sdv%]/g;
  23320. var format = function (formatStr) {
  23321. var i = 1;
  23322. var args = arguments;
  23323. var len = args.length;
  23324. return formatStr.replace(formatRegExp, function (x) {
  23325. if (i >= len) {
  23326. return x; // missing argument
  23327. }
  23328. var arg = args[i];
  23329. i += 1;
  23330. switch (x) {
  23331. case '%%':
  23332. return '%';
  23333. case '%s':
  23334. return String(arg);
  23335. case '%d':
  23336. return Number(arg);
  23337. case '%v':
  23338. return '';
  23339. }
  23340. });
  23341. // NB: we discard excess arguments - they are typically undefined from makeLine
  23342. };
  23343. var makeLine = function (type, obj, location) {
  23344. var str = obj.format instanceof Function ?
  23345. (obj.format(obj.push ? location : location[obj.name])) :
  23346. obj.format;
  23347. var args = [type + '=' + str];
  23348. if (obj.names) {
  23349. for (var i = 0; i < obj.names.length; i += 1) {
  23350. var n = obj.names[i];
  23351. if (obj.name) {
  23352. args.push(location[obj.name][n]);
  23353. }
  23354. else { // for mLine and push attributes
  23355. args.push(location[obj.names[i]]);
  23356. }
  23357. }
  23358. }
  23359. else {
  23360. args.push(location[obj.name]);
  23361. }
  23362. return format.apply(null, args);
  23363. };
  23364. // RFC specified order
  23365. // TODO: extend this with all the rest
  23366. var defaultOuterOrder = [
  23367. 'v', 'o', 's', 'i',
  23368. 'u', 'e', 'p', 'c',
  23369. 'b', 't', 'r', 'z', 'a'
  23370. ];
  23371. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  23372. module.exports = function (session, opts) {
  23373. opts = opts || {};
  23374. // ensure certain properties exist
  23375. if (session.version == null) {
  23376. session.version = 0; // "v=0" must be there (only defined version atm)
  23377. }
  23378. if (session.name == null) {
  23379. session.name = " "; // "s= " must be there if no meaningful name set
  23380. }
  23381. session.media.forEach(function (mLine) {
  23382. if (mLine.payloads == null) {
  23383. mLine.payloads = "";
  23384. }
  23385. });
  23386. var outerOrder = opts.outerOrder || defaultOuterOrder;
  23387. var innerOrder = opts.innerOrder || defaultInnerOrder;
  23388. var sdp = [];
  23389. // loop through outerOrder for matching properties on session
  23390. outerOrder.forEach(function (type) {
  23391. grammar[type].forEach(function (obj) {
  23392. if (obj.name in session && session[obj.name] != null) {
  23393. sdp.push(makeLine(type, obj, session));
  23394. }
  23395. else if (obj.push in session && session[obj.push] != null) {
  23396. session[obj.push].forEach(function (el) {
  23397. sdp.push(makeLine(type, obj, el));
  23398. });
  23399. }
  23400. });
  23401. });
  23402. // then for each media line, follow the innerOrder
  23403. session.media.forEach(function (mLine) {
  23404. sdp.push(makeLine('m', grammar.m[0], mLine));
  23405. innerOrder.forEach(function (type) {
  23406. grammar[type].forEach(function (obj) {
  23407. if (obj.name in mLine && mLine[obj.name] != null) {
  23408. sdp.push(makeLine(type, obj, mLine));
  23409. }
  23410. else if (obj.push in mLine && mLine[obj.push] != null) {
  23411. mLine[obj.push].forEach(function (el) {
  23412. sdp.push(makeLine(type, obj, el));
  23413. });
  23414. }
  23415. });
  23416. });
  23417. });
  23418. return sdp.join('\r\n') + '\r\n';
  23419. };
  23420. },{"./grammar":83}],87:[function(require,module,exports){
  23421. var MediaStreamType = {
  23422. VIDEO_TYPE: "Video",
  23423. AUDIO_TYPE: "Audio"
  23424. };
  23425. module.exports = MediaStreamType;
  23426. },{}],88:[function(require,module,exports){
  23427. var RTCBrowserType = {
  23428. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  23429. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  23430. };
  23431. module.exports = RTCBrowserType;
  23432. },{}],89:[function(require,module,exports){
  23433. var RTCEvents = {
  23434. LASTN_CHANGED: "rtc.lastn_changed",
  23435. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  23436. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  23437. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  23438. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  23439. SIMULCAST_START: "rtc.simlcast_start",
  23440. SIMULCAST_STOP: "rtc.simlcast_stop"
  23441. };
  23442. module.exports = RTCEvents;
  23443. },{}],90:[function(require,module,exports){
  23444. var Resolutions = {
  23445. "1080": {
  23446. width: 1920,
  23447. height: 1080,
  23448. order: 7
  23449. },
  23450. "fullhd": {
  23451. width: 1920,
  23452. height: 1080,
  23453. order: 7
  23454. },
  23455. "720": {
  23456. width: 1280,
  23457. height: 720,
  23458. order: 6
  23459. },
  23460. "hd": {
  23461. width: 1280,
  23462. height: 720,
  23463. order: 6
  23464. },
  23465. "960": {
  23466. width: 960,
  23467. height: 720,
  23468. order: 5
  23469. },
  23470. "640": {
  23471. width: 640,
  23472. height: 480,
  23473. order: 4
  23474. },
  23475. "vga": {
  23476. width: 640,
  23477. height: 480,
  23478. order: 4
  23479. },
  23480. "360": {
  23481. width: 640,
  23482. height: 360,
  23483. order: 3
  23484. },
  23485. "320": {
  23486. width: 320,
  23487. height: 240,
  23488. order: 2
  23489. },
  23490. "180": {
  23491. width: 320,
  23492. height: 180,
  23493. order: 1
  23494. }
  23495. };
  23496. module.exports = Resolutions;
  23497. },{}],91:[function(require,module,exports){
  23498. var StreamEventTypes = {
  23499. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  23500. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  23501. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  23502. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  23503. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  23504. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  23505. };
  23506. module.exports = StreamEventTypes;
  23507. },{}],92:[function(require,module,exports){
  23508. var UIEvents = {
  23509. NICKNAME_CHANGED: "UI.nickname_changed",
  23510. SELECTED_ENDPOINT: "UI.selected_endpoint",
  23511. PINNED_ENDPOINT: "UI.pinned_endpoint"
  23512. };
  23513. module.exports = UIEvents;
  23514. },{}],93:[function(require,module,exports){
  23515. var AuthenticationEvents = {
  23516. /**
  23517. * Event callback arguments:
  23518. * function(authenticationEnabled, userIdentity)
  23519. * authenticationEnabled - indicates whether authentication has been enabled
  23520. * in this session
  23521. * userIdentity - if user has been logged in then it contains user name. If
  23522. * contains 'null' or 'undefined' then user is not logged in.
  23523. */
  23524. IDENTITY_UPDATED: "authentication.identity_updated"
  23525. };
  23526. module.exports = AuthenticationEvents;
  23527. },{}],94:[function(require,module,exports){
  23528. var CQEvents = {
  23529. LOCALSTATS_UPDATED: "cq.localstats_updated",
  23530. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  23531. STOP: "cq.stop"
  23532. };
  23533. module.exports = CQEvents;
  23534. },{}],95:[function(require,module,exports){
  23535. var DesktopSharingEventTypes = {
  23536. INIT: "ds.init",
  23537. SWITCHING_DONE: "ds.switching_done",
  23538. NEW_STREAM_CREATED: "ds.new_stream_created"
  23539. };
  23540. module.exports = DesktopSharingEventTypes;
  23541. },{}],96:[function(require,module,exports){
  23542. module.exports = {
  23543. getLanguages : function () {
  23544. var languages = [];
  23545. for(var lang in this)
  23546. {
  23547. if(typeof this[lang] === "string")
  23548. languages.push(this[lang]);
  23549. }
  23550. return languages;
  23551. },
  23552. EN: "en",
  23553. BG: "bg",
  23554. DE: "de",
  23555. TR: "tr"
  23556. }
  23557. },{}],97:[function(require,module,exports){
  23558. var XMPPEvents = {
  23559. CONFERENCE_CERATED: "xmpp.conferenceCreated.jingle",
  23560. CALL_TERMINATED: "xmpp.callterminated.jingle",
  23561. CALL_INCOMING: "xmpp.callincoming.jingle",
  23562. DISPOSE_CONFERENCE: "xmpp.dispoce_confernce",
  23563. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  23564. KICKED: "xmpp.kicked",
  23565. BRIDGE_DOWN: "xmpp.bridge_down",
  23566. USER_ID_CHANGED: "xmpp.user_id_changed",
  23567. CHANGED_STREAMS: "xmpp.changed_streams",
  23568. MUC_JOINED: "xmpp.muc_joined",
  23569. MUC_ENTER: "xmpp.muc_enter",
  23570. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  23571. MUC_LEFT: "xmpp.muc_left",
  23572. MUC_DESTROYED: "xmpp.muc_destroyed",
  23573. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  23574. REMOTE_STATS: "xmpp.remote_stats",
  23575. LOCALROLE_CHANGED: "xmpp.localrole_changed",
  23576. PRESENCE_STATUS: "xmpp.presence_status",
  23577. RESERVATION_ERROR: "xmpp.room_reservation_error",
  23578. SUBJECT_CHANGED: "xmpp.subject_changed",
  23579. MESSAGE_RECEIVED: "xmpp.message_received",
  23580. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  23581. PASSWORD_REQUIRED: "xmpp.password_required",
  23582. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  23583. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  23584. ETHERPAD: "xmpp.etherpad"
  23585. };
  23586. module.exports = XMPPEvents;
  23587. },{}],98:[function(require,module,exports){
  23588. // Copyright Joyent, Inc. and other Node contributors.
  23589. //
  23590. // Permission is hereby granted, free of charge, to any person obtaining a
  23591. // copy of this software and associated documentation files (the
  23592. // "Software"), to deal in the Software without restriction, including
  23593. // without limitation the rights to use, copy, modify, merge, publish,
  23594. // distribute, sublicense, and/or sell copies of the Software, and to permit
  23595. // persons to whom the Software is furnished to do so, subject to the
  23596. // following conditions:
  23597. //
  23598. // The above copyright notice and this permission notice shall be included
  23599. // in all copies or substantial portions of the Software.
  23600. //
  23601. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  23602. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23603. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  23604. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  23605. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  23606. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  23607. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  23608. function EventEmitter() {
  23609. this._events = this._events || {};
  23610. this._maxListeners = this._maxListeners || undefined;
  23611. }
  23612. module.exports = EventEmitter;
  23613. // Backwards-compat with node 0.10.x
  23614. EventEmitter.EventEmitter = EventEmitter;
  23615. EventEmitter.prototype._events = undefined;
  23616. EventEmitter.prototype._maxListeners = undefined;
  23617. // By default EventEmitters will print a warning if more than 10 listeners are
  23618. // added to it. This is a useful default which helps finding memory leaks.
  23619. EventEmitter.defaultMaxListeners = 10;
  23620. // Obviously not all Emitters should be limited to 10. This function allows
  23621. // that to be increased. Set to zero for unlimited.
  23622. EventEmitter.prototype.setMaxListeners = function(n) {
  23623. if (!isNumber(n) || n < 0 || isNaN(n))
  23624. throw TypeError('n must be a positive number');
  23625. this._maxListeners = n;
  23626. return this;
  23627. };
  23628. EventEmitter.prototype.emit = function(type) {
  23629. var er, handler, len, args, i, listeners;
  23630. if (!this._events)
  23631. this._events = {};
  23632. // If there is no 'error' event listener then throw.
  23633. if (type === 'error') {
  23634. if (!this._events.error ||
  23635. (isObject(this._events.error) && !this._events.error.length)) {
  23636. er = arguments[1];
  23637. if (er instanceof Error) {
  23638. throw er; // Unhandled 'error' event
  23639. }
  23640. throw TypeError('Uncaught, unspecified "error" event.');
  23641. }
  23642. }
  23643. handler = this._events[type];
  23644. if (isUndefined(handler))
  23645. return false;
  23646. if (isFunction(handler)) {
  23647. switch (arguments.length) {
  23648. // fast cases
  23649. case 1:
  23650. handler.call(this);
  23651. break;
  23652. case 2:
  23653. handler.call(this, arguments[1]);
  23654. break;
  23655. case 3:
  23656. handler.call(this, arguments[1], arguments[2]);
  23657. break;
  23658. // slower
  23659. default:
  23660. len = arguments.length;
  23661. args = new Array(len - 1);
  23662. for (i = 1; i < len; i++)
  23663. args[i - 1] = arguments[i];
  23664. handler.apply(this, args);
  23665. }
  23666. } else if (isObject(handler)) {
  23667. len = arguments.length;
  23668. args = new Array(len - 1);
  23669. for (i = 1; i < len; i++)
  23670. args[i - 1] = arguments[i];
  23671. listeners = handler.slice();
  23672. len = listeners.length;
  23673. for (i = 0; i < len; i++)
  23674. listeners[i].apply(this, args);
  23675. }
  23676. return true;
  23677. };
  23678. EventEmitter.prototype.addListener = function(type, listener) {
  23679. var m;
  23680. if (!isFunction(listener))
  23681. throw TypeError('listener must be a function');
  23682. if (!this._events)
  23683. this._events = {};
  23684. // To avoid recursion in the case that type === "newListener"! Before
  23685. // adding it to the listeners, first emit "newListener".
  23686. if (this._events.newListener)
  23687. this.emit('newListener', type,
  23688. isFunction(listener.listener) ?
  23689. listener.listener : listener);
  23690. if (!this._events[type])
  23691. // Optimize the case of one listener. Don't need the extra array object.
  23692. this._events[type] = listener;
  23693. else if (isObject(this._events[type]))
  23694. // If we've already got an array, just append.
  23695. this._events[type].push(listener);
  23696. else
  23697. // Adding the second element, need to change to array.
  23698. this._events[type] = [this._events[type], listener];
  23699. // Check for listener leak
  23700. if (isObject(this._events[type]) && !this._events[type].warned) {
  23701. var m;
  23702. if (!isUndefined(this._maxListeners)) {
  23703. m = this._maxListeners;
  23704. } else {
  23705. m = EventEmitter.defaultMaxListeners;
  23706. }
  23707. if (m && m > 0 && this._events[type].length > m) {
  23708. this._events[type].warned = true;
  23709. console.error('(node) warning: possible EventEmitter memory ' +
  23710. 'leak detected. %d listeners added. ' +
  23711. 'Use emitter.setMaxListeners() to increase limit.',
  23712. this._events[type].length);
  23713. if (typeof console.trace === 'function') {
  23714. // not supported in IE 10
  23715. console.trace();
  23716. }
  23717. }
  23718. }
  23719. return this;
  23720. };
  23721. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  23722. EventEmitter.prototype.once = function(type, listener) {
  23723. if (!isFunction(listener))
  23724. throw TypeError('listener must be a function');
  23725. var fired = false;
  23726. function g() {
  23727. this.removeListener(type, g);
  23728. if (!fired) {
  23729. fired = true;
  23730. listener.apply(this, arguments);
  23731. }
  23732. }
  23733. g.listener = listener;
  23734. this.on(type, g);
  23735. return this;
  23736. };
  23737. // emits a 'removeListener' event iff the listener was removed
  23738. EventEmitter.prototype.removeListener = function(type, listener) {
  23739. var list, position, length, i;
  23740. if (!isFunction(listener))
  23741. throw TypeError('listener must be a function');
  23742. if (!this._events || !this._events[type])
  23743. return this;
  23744. list = this._events[type];
  23745. length = list.length;
  23746. position = -1;
  23747. if (list === listener ||
  23748. (isFunction(list.listener) && list.listener === listener)) {
  23749. delete this._events[type];
  23750. if (this._events.removeListener)
  23751. this.emit('removeListener', type, listener);
  23752. } else if (isObject(list)) {
  23753. for (i = length; i-- > 0;) {
  23754. if (list[i] === listener ||
  23755. (list[i].listener && list[i].listener === listener)) {
  23756. position = i;
  23757. break;
  23758. }
  23759. }
  23760. if (position < 0)
  23761. return this;
  23762. if (list.length === 1) {
  23763. list.length = 0;
  23764. delete this._events[type];
  23765. } else {
  23766. list.splice(position, 1);
  23767. }
  23768. if (this._events.removeListener)
  23769. this.emit('removeListener', type, listener);
  23770. }
  23771. return this;
  23772. };
  23773. EventEmitter.prototype.removeAllListeners = function(type) {
  23774. var key, listeners;
  23775. if (!this._events)
  23776. return this;
  23777. // not listening for removeListener, no need to emit
  23778. if (!this._events.removeListener) {
  23779. if (arguments.length === 0)
  23780. this._events = {};
  23781. else if (this._events[type])
  23782. delete this._events[type];
  23783. return this;
  23784. }
  23785. // emit removeListener for all listeners on all events
  23786. if (arguments.length === 0) {
  23787. for (key in this._events) {
  23788. if (key === 'removeListener') continue;
  23789. this.removeAllListeners(key);
  23790. }
  23791. this.removeAllListeners('removeListener');
  23792. this._events = {};
  23793. return this;
  23794. }
  23795. listeners = this._events[type];
  23796. if (isFunction(listeners)) {
  23797. this.removeListener(type, listeners);
  23798. } else {
  23799. // LIFO order
  23800. while (listeners.length)
  23801. this.removeListener(type, listeners[listeners.length - 1]);
  23802. }
  23803. delete this._events[type];
  23804. return this;
  23805. };
  23806. EventEmitter.prototype.listeners = function(type) {
  23807. var ret;
  23808. if (!this._events || !this._events[type])
  23809. ret = [];
  23810. else if (isFunction(this._events[type]))
  23811. ret = [this._events[type]];
  23812. else
  23813. ret = this._events[type].slice();
  23814. return ret;
  23815. };
  23816. EventEmitter.listenerCount = function(emitter, type) {
  23817. var ret;
  23818. if (!emitter._events || !emitter._events[type])
  23819. ret = 0;
  23820. else if (isFunction(emitter._events[type]))
  23821. ret = 1;
  23822. else
  23823. ret = emitter._events[type].length;
  23824. return ret;
  23825. };
  23826. function isFunction(arg) {
  23827. return typeof arg === 'function';
  23828. }
  23829. function isNumber(arg) {
  23830. return typeof arg === 'number';
  23831. }
  23832. function isObject(arg) {
  23833. return typeof arg === 'object' && arg !== null;
  23834. }
  23835. function isUndefined(arg) {
  23836. return arg === void 0;
  23837. }
  23838. },{}]},{},[1])(1)
  23839. });