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.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328
  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. if(window.location.protocol != "https:" ||
  505. this.isAudioStream() || this.videoType === "screen")
  506. {
  507. var tracks = this.getTracks();
  508. for (var idx = 0; idx < tracks.length; idx++) {
  509. tracks[idx].enabled = mute;
  510. }
  511. }
  512. else
  513. {
  514. if(mute === false) {
  515. APP.xmpp.removeStream(this.stream);
  516. this.stream.stop();
  517. }
  518. else
  519. {
  520. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(["video"],
  521. function (stream) {
  522. APP.RTC.changeLocalVideo(stream, false, function () {});
  523. });
  524. }
  525. }
  526. };
  527. LocalStream.prototype.isMuted = function () {
  528. var tracks = [];
  529. if(this.type == "audio")
  530. {
  531. tracks = this.stream.getAudioTracks();
  532. }
  533. else
  534. {
  535. if(this.stream.ended)
  536. return true;
  537. tracks = this.stream.getVideoTracks();
  538. }
  539. for (var idx = 0; idx < tracks.length; idx++) {
  540. if(tracks[idx].enabled)
  541. return false;
  542. }
  543. return true;
  544. }
  545. LocalStream.prototype.getId = function () {
  546. return this.stream.getTracks()[0].id;
  547. }
  548. module.exports = LocalStream;
  549. },{"../../service/RTC/StreamEventTypes.js":91}],5:[function(require,module,exports){
  550. ////These lines should be uncommented when require works in app.js
  551. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  552. var StreamEventType = require("../../service/RTC/StreamEventTypes");
  553. /**
  554. * Creates a MediaStream object for the given data, session id and ssrc.
  555. * It is a wrapper class for the MediaStream.
  556. *
  557. * @param data the data object from which we obtain the stream,
  558. * the peerjid, etc.
  559. * @param sid the session id
  560. * @param ssrc the ssrc corresponding to this MediaStream
  561. *
  562. * @constructor
  563. */
  564. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  565. // XXX(gp) to minimize headaches in the future, we should build our
  566. // abstractions around tracks and not streams. ORTC is track based API.
  567. // Mozilla expects m-lines to represent media tracks.
  568. //
  569. // Practically, what I'm saying is that we should have a MediaTrack class
  570. // and not a MediaStream class.
  571. //
  572. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  573. // a track might have an associated RTX and FEC sources.
  574. this.sid = sid;
  575. this.stream = data.stream;
  576. this.peerjid = data.peerjid;
  577. this.ssrc = ssrc;
  578. this.type = (this.stream.getVideoTracks().length > 0)?
  579. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  580. this.videoType = null;
  581. this.muted = false;
  582. this.eventEmitter = eventEmitter;
  583. }
  584. MediaStream.prototype.getOriginalStream = function()
  585. {
  586. return this.stream;
  587. };
  588. MediaStream.prototype.setMute = function (value)
  589. {
  590. this.stream.muted = value;
  591. this.muted = value;
  592. };
  593. MediaStream.prototype.setVideoType = function (value) {
  594. if(this.videoType === value)
  595. return;
  596. this.videoType = value;
  597. this.eventEmitter.emit(StreamEventType.EVENT_TYPE_REMOTE_CHANGED,
  598. this.peerjid);
  599. };
  600. module.exports = MediaStream;
  601. },{"../../service/RTC/MediaStreamTypes":87,"../../service/RTC/StreamEventTypes":91}],6:[function(require,module,exports){
  602. var EventEmitter = require("events");
  603. var RTCUtils = require("./RTCUtils.js");
  604. var LocalStream = require("./LocalStream.js");
  605. var DataChannels = require("./DataChannels");
  606. var MediaStream = require("./MediaStream.js");
  607. var DesktopSharingEventTypes
  608. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  609. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  610. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  611. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  612. var UIEvents = require("../../service/UI/UIEvents");
  613. var eventEmitter = new EventEmitter();
  614. var RTC = {
  615. rtcUtils: null,
  616. localStreams: [],
  617. remoteStreams: {},
  618. localAudio: null,
  619. localVideo: null,
  620. addStreamListener: function (listener, eventType) {
  621. eventEmitter.on(eventType, listener);
  622. },
  623. addListener: function (type, listener) {
  624. eventEmitter.on(type, listener);
  625. },
  626. removeStreamListener: function (listener, eventType) {
  627. if(!(eventType instanceof StreamEventTypes))
  628. throw "Illegal argument";
  629. eventEmitter.removeListener(eventType, listener);
  630. },
  631. createLocalStream: function (stream, type, change, videoType) {
  632. var localStream = new LocalStream(stream, type, eventEmitter, videoType);
  633. //in firefox we have only one stream object
  634. if(this.localStreams.length == 0 ||
  635. this.localStreams[0].getOriginalStream() != stream)
  636. this.localStreams.push(localStream);
  637. if(type == "audio")
  638. {
  639. this.localAudio = localStream;
  640. }
  641. else
  642. {
  643. this.localVideo = localStream;
  644. }
  645. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  646. if(change)
  647. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  648. eventEmitter.emit(eventType, localStream);
  649. return localStream;
  650. },
  651. removeLocalStream: function (stream) {
  652. for(var i = 0; i < this.localStreams.length; i++)
  653. {
  654. if(this.localStreams[i].getOriginalStream() === stream) {
  655. delete this.localStreams[i];
  656. return;
  657. }
  658. }
  659. },
  660. createRemoteStream: function (data, sid, thessrc) {
  661. var remoteStream = new MediaStream(data, sid, thessrc,
  662. this.getBrowserType(), eventEmitter);
  663. var jid = data.peerjid || APP.xmpp.myJid();
  664. if(!this.remoteStreams[jid]) {
  665. this.remoteStreams[jid] = {};
  666. }
  667. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  668. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  669. return remoteStream;
  670. },
  671. getBrowserType: function () {
  672. return this.rtcUtils.browser;
  673. },
  674. getPCConstraints: function () {
  675. return this.rtcUtils.pc_constraints;
  676. },
  677. getUserMediaWithConstraints:function(um, success_callback,
  678. failure_callback, resolution,
  679. bandwidth, fps, desktopStream)
  680. {
  681. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  682. failure_callback, resolution, bandwidth, fps, desktopStream);
  683. },
  684. attachMediaStream: function (element, stream) {
  685. this.rtcUtils.attachMediaStream(element, stream);
  686. },
  687. getStreamID: function (stream) {
  688. return this.rtcUtils.getStreamID(stream);
  689. },
  690. getVideoSrc: function (element) {
  691. return this.rtcUtils.getVideoSrc(element);
  692. },
  693. setVideoSrc: function (element, src) {
  694. this.rtcUtils.setVideoSrc(element, src);
  695. },
  696. dispose: function() {
  697. if (this.rtcUtils) {
  698. this.rtcUtils = null;
  699. }
  700. },
  701. stop: function () {
  702. this.dispose();
  703. },
  704. start: function () {
  705. var self = this;
  706. APP.desktopsharing.addListener(
  707. function (stream, isUsingScreenStream, callback) {
  708. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  709. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  710. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  711. for(var i = 0; i < changedStreams.length; i++) {
  712. var type = changedStreams[i].type;
  713. if (type != "audio") {
  714. var peerStreams = self.remoteStreams[jid];
  715. if(!peerStreams)
  716. continue;
  717. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  718. if(!videoStream)
  719. continue;
  720. videoStream.setVideoType(changedStreams[i].type);
  721. }
  722. }
  723. });
  724. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  725. DataChannels.init(event.peerconnection, eventEmitter);
  726. });
  727. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  728. DataChannels.handleSelectedEndpointEvent);
  729. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  730. DataChannels.handlePinnedEndpointEvent);
  731. this.rtcUtils = new RTCUtils(this);
  732. this.rtcUtils.obtainAudioAndVideoPermissions();
  733. },
  734. muteRemoteVideoStream: function (jid, value) {
  735. var stream;
  736. if(this.remoteStreams[jid] &&
  737. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  738. {
  739. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  740. }
  741. if(!stream)
  742. return false;
  743. if (value != stream.muted) {
  744. stream.setMute(value);
  745. return true;
  746. }
  747. return false;
  748. },
  749. switchVideoStreams: function (new_stream) {
  750. this.localVideo.stream = new_stream;
  751. this.localStreams = [];
  752. //in firefox we have only one stream object
  753. if (this.localAudio.getOriginalStream() != new_stream)
  754. this.localStreams.push(this.localAudio);
  755. this.localStreams.push(this.localVideo);
  756. },
  757. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  758. var oldStream = this.localVideo.getOriginalStream();
  759. var type = (isUsingScreenStream? "screen" : "video");
  760. var localCallback = callback;
  761. if(this.localVideo.isMuted() && this.localVideo.videoType !== type)
  762. {
  763. localCallback = function() {
  764. APP.xmpp.setVideoMute(false, APP.UI.setVideoMuteButtonsState);
  765. callback();
  766. };
  767. }
  768. var videoStream = this.rtcUtils.createVideoStream(stream);
  769. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  770. // Stop the stream to trigger onended event for old stream
  771. oldStream.stop();
  772. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  773. },
  774. /**
  775. * Checks if video identified by given src is desktop stream.
  776. * @param videoSrc eg.
  777. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  778. * @returns {boolean}
  779. */
  780. isVideoSrcDesktop: function (jid) {
  781. if(!jid)
  782. return false;
  783. var isDesktop = false;
  784. var stream = null;
  785. if (APP.xmpp.myJid() === jid) {
  786. // local video
  787. stream = this.localVideo;
  788. } else {
  789. var peerStreams = this.remoteStreams[jid];
  790. if(!peerStreams)
  791. return false;
  792. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  793. }
  794. if(stream)
  795. isDesktop = (stream.videoType === "screen");
  796. return isDesktop;
  797. },
  798. setVideoMute: function(mute, callback, options) {
  799. if(!this.localVideo)
  800. return;
  801. if (mute == APP.RTC.localVideo.isMuted())
  802. {
  803. APP.xmpp.sendVideoInfoPresence(mute);
  804. if(callback)
  805. callback();
  806. }
  807. else
  808. {
  809. APP.RTC.localVideo.setMute(!mute);
  810. APP.xmpp.setVideoMute(
  811. mute,
  812. callback,
  813. options);
  814. }
  815. }
  816. };
  817. module.exports = RTC;
  818. },{"../../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){
  819. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  820. var Resolutions = require("../../service/RTC/Resolutions");
  821. var currentResolution = null;
  822. function getPreviousResolution(resolution) {
  823. if(!Resolutions[resolution])
  824. return null;
  825. var order = Resolutions[resolution].order;
  826. var res = null;
  827. var resName = null;
  828. for(var i in Resolutions)
  829. {
  830. var tmp = Resolutions[i];
  831. if(res == null || (res.order < tmp.order && tmp.order < order))
  832. {
  833. resName = i;
  834. res = tmp;
  835. }
  836. }
  837. return resName;
  838. }
  839. function setResolutionConstraints(constraints, resolution, isAndroid)
  840. {
  841. if (resolution && !constraints.video || isAndroid) {
  842. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  843. }
  844. if(Resolutions[resolution])
  845. {
  846. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  847. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  848. }
  849. else
  850. {
  851. if (isAndroid) {
  852. constraints.video.mandatory.minWidth = 320;
  853. constraints.video.mandatory.minHeight = 240;
  854. constraints.video.mandatory.maxFrameRate = 15;
  855. }
  856. }
  857. if (constraints.video.mandatory.minWidth)
  858. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  859. if (constraints.video.mandatory.minHeight)
  860. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  861. }
  862. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  863. {
  864. var constraints = {audio: false, video: false};
  865. if (um.indexOf('video') >= 0) {
  866. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  867. }
  868. if (um.indexOf('audio') >= 0) {
  869. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  870. }
  871. if (um.indexOf('screen') >= 0) {
  872. constraints.video = {
  873. mandatory: {
  874. chromeMediaSource: "screen",
  875. googLeakyBucket: true,
  876. maxWidth: window.screen.width,
  877. maxHeight: window.screen.height,
  878. maxFrameRate: 3
  879. },
  880. optional: []
  881. };
  882. }
  883. if (um.indexOf('desktop') >= 0) {
  884. constraints.video = {
  885. mandatory: {
  886. chromeMediaSource: "desktop",
  887. chromeMediaSourceId: desktopStream,
  888. googLeakyBucket: true,
  889. maxWidth: window.screen.width,
  890. maxHeight: window.screen.height,
  891. maxFrameRate: 3
  892. },
  893. optional: []
  894. };
  895. }
  896. if (constraints.audio) {
  897. // if it is good enough for hangouts...
  898. constraints.audio.optional.push(
  899. {googEchoCancellation: true},
  900. {googAutoGainControl: true},
  901. {googNoiseSupression: true},
  902. {googHighpassFilter: true},
  903. {googNoisesuppression2: true},
  904. {googEchoCancellation2: true},
  905. {googAutoGainControl2: true}
  906. );
  907. }
  908. if (constraints.video) {
  909. constraints.video.optional.push(
  910. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  911. );
  912. if (um.indexOf('video') >= 0) {
  913. constraints.video.optional.push(
  914. {googLeakyBucket: true}
  915. );
  916. }
  917. }
  918. if (um.indexOf('video') >= 0) {
  919. setResolutionConstraints(constraints, resolution, isAndroid);
  920. }
  921. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  922. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  923. constraints.video.optional.push({bandwidth: bandwidth});
  924. }
  925. if (fps) { // for some cameras it might be necessary to request 30fps
  926. // so they choose 30fps mjpg over 10fps yuy2
  927. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  928. constraints.video.mandatory.minFrameRate = fps;
  929. }
  930. return constraints;
  931. }
  932. function RTCUtils(RTCService)
  933. {
  934. this.service = RTCService;
  935. if (navigator.mozGetUserMedia) {
  936. console.log('This appears to be Firefox');
  937. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  938. if (version >= 39) {
  939. this.peerconnection = mozRTCPeerConnection;
  940. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  941. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  942. this.pc_constraints = {};
  943. this.attachMediaStream = function (element, stream) {
  944. // srcObject is being standardized and FF will eventually
  945. // support that unprefixed. FF also supports the
  946. // "element.src = URL.createObjectURL(...)" combo, but that
  947. // will be deprecated in favour of srcObject.
  948. //
  949. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  950. // https://github.com/webrtc/samples/issues/302
  951. element[0].mozSrcObject = stream;
  952. element[0].play();
  953. };
  954. this.getStreamID = function (stream) {
  955. var tracks = stream.getVideoTracks();
  956. if(!tracks || tracks.length == 0)
  957. {
  958. tracks = stream.getAudioTracks();
  959. }
  960. return tracks[0].id.replace(/[\{,\}]/g,"");
  961. };
  962. this.getVideoSrc = function (element) {
  963. return element.mozSrcObject;
  964. };
  965. this.setVideoSrc = function (element, src) {
  966. element.mozSrcObject = src;
  967. };
  968. RTCSessionDescription = mozRTCSessionDescription;
  969. RTCIceCandidate = mozRTCIceCandidate;
  970. } else {
  971. window.location.href = 'unsupported_browser.html';
  972. return;
  973. }
  974. } else if (navigator.webkitGetUserMedia) {
  975. console.log('This appears to be Chrome');
  976. this.peerconnection = webkitRTCPeerConnection;
  977. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  978. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  979. this.attachMediaStream = function (element, stream) {
  980. element.attr('src', webkitURL.createObjectURL(stream));
  981. };
  982. this.getStreamID = function (stream) {
  983. // streams from FF endpoints have the characters '{' and '}'
  984. // that make jQuery choke.
  985. return stream.id.replace(/[\{,\}]/g,"");
  986. };
  987. this.getVideoSrc = function (element) {
  988. return element.getAttribute("src");
  989. };
  990. this.setVideoSrc = function (element, src) {
  991. element.setAttribute("src", src);
  992. };
  993. // DTLS should now be enabled by default but..
  994. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  995. if (navigator.userAgent.indexOf('Android') != -1) {
  996. this.pc_constraints = {}; // disable DTLS on Android
  997. }
  998. if (!webkitMediaStream.prototype.getVideoTracks) {
  999. webkitMediaStream.prototype.getVideoTracks = function () {
  1000. return this.videoTracks;
  1001. };
  1002. }
  1003. if (!webkitMediaStream.prototype.getAudioTracks) {
  1004. webkitMediaStream.prototype.getAudioTracks = function () {
  1005. return this.audioTracks;
  1006. };
  1007. }
  1008. }
  1009. else
  1010. {
  1011. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  1012. window.location.href = 'unsupported_browser.html';
  1013. return;
  1014. }
  1015. }
  1016. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1017. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1018. desktopStream)
  1019. {
  1020. currentResolution = resolution;
  1021. // Check if we are running on Android device
  1022. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1023. var constraints = getConstraints(
  1024. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1025. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  1026. try {
  1027. if (config.enableSimulcast
  1028. && constraints.video
  1029. && constraints.video.chromeMediaSource !== 'screen'
  1030. && constraints.video.chromeMediaSource !== 'desktop'
  1031. && !isAndroid
  1032. // We currently do not support FF, as it doesn't have multistream support.
  1033. && !isFF) {
  1034. APP.simulcast.getUserMedia(constraints, function (stream) {
  1035. console.log('onUserMediaSuccess');
  1036. success_callback(stream);
  1037. },
  1038. function (error) {
  1039. console.warn('Failed to get access to local media. Error ', error);
  1040. if (failure_callback) {
  1041. failure_callback(error);
  1042. }
  1043. });
  1044. } else {
  1045. this.getUserMedia(constraints,
  1046. function (stream) {
  1047. console.log('onUserMediaSuccess');
  1048. success_callback(stream);
  1049. },
  1050. function (error) {
  1051. console.warn('Failed to get access to local media. Error ',
  1052. error, constraints);
  1053. if (failure_callback) {
  1054. failure_callback(error);
  1055. }
  1056. });
  1057. }
  1058. } catch (e) {
  1059. console.error('GUM failed: ', e);
  1060. if(failure_callback) {
  1061. failure_callback(e);
  1062. }
  1063. }
  1064. };
  1065. /**
  1066. * We ask for audio and video combined stream in order to get permissions and
  1067. * not to ask twice.
  1068. */
  1069. RTCUtils.prototype.obtainAudioAndVideoPermissions = function(devices, callback) {
  1070. var self = this;
  1071. // Get AV
  1072. if(!devices)
  1073. devices = ['audio', 'video'];
  1074. this.getUserMediaWithConstraints(
  1075. devices,
  1076. function (stream) {
  1077. if(callback)
  1078. callback(stream);
  1079. else
  1080. self.successCallback(stream);
  1081. },
  1082. function (error) {
  1083. self.errorCallback(error);
  1084. },
  1085. config.resolution || '360');
  1086. }
  1087. RTCUtils.prototype.successCallback = function (stream) {
  1088. if(stream)
  1089. console.log('got', stream, stream.getAudioTracks().length,
  1090. stream.getVideoTracks().length);
  1091. this.handleLocalStream(stream);
  1092. };
  1093. RTCUtils.prototype.errorCallback = function (error) {
  1094. var self = this;
  1095. console.error('failed to obtain audio/video stream - trying audio only', error);
  1096. var resolution = getPreviousResolution(currentResolution);
  1097. if(typeof error == "object" && error.constraintName && error.name
  1098. && (error.name == "ConstraintNotSatisfiedError" ||
  1099. error.name == "OverconstrainedError") &&
  1100. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1101. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1102. && resolution != null)
  1103. {
  1104. self.getUserMediaWithConstraints(['audio', 'video'],
  1105. function (stream) {
  1106. return self.successCallback(stream);
  1107. }, function (error) {
  1108. return self.errorCallback(error);
  1109. }, resolution);
  1110. }
  1111. else
  1112. {
  1113. self.getUserMediaWithConstraints(
  1114. ['audio'],
  1115. function (stream) {
  1116. return self.successCallback(stream);
  1117. },
  1118. function (error) {
  1119. console.error('failed to obtain audio/video stream - stop',
  1120. error);
  1121. // APP.UI.messageHandler.showError("dialog.error",
  1122. // "dialog.failedpermissions");
  1123. return self.successCallback(null);
  1124. }
  1125. );
  1126. }
  1127. }
  1128. RTCUtils.prototype.handleLocalStream = function(stream)
  1129. {
  1130. if(window.webkitMediaStream)
  1131. {
  1132. var audioStream = new webkitMediaStream();
  1133. var videoStream = new webkitMediaStream();
  1134. if(stream) {
  1135. var audioTracks = stream.getAudioTracks();
  1136. for (var i = 0; i < audioTracks.length; i++) {
  1137. audioStream.addTrack(audioTracks[i]);
  1138. }
  1139. var videoTracks = stream.getVideoTracks();
  1140. for (i = 0; i < videoTracks.length; i++) {
  1141. videoStream.addTrack(videoTracks[i]);
  1142. }
  1143. }
  1144. this.service.createLocalStream(audioStream, "audio");
  1145. this.service.createLocalStream(videoStream, "video");
  1146. }
  1147. else
  1148. {//firefox
  1149. this.service.createLocalStream(stream, "stream");
  1150. }
  1151. };
  1152. RTCUtils.prototype.createVideoStream = function(stream)
  1153. {
  1154. var videoStream = null;
  1155. if(window.webkitMediaStream)
  1156. {
  1157. videoStream = new webkitMediaStream();
  1158. if(stream)
  1159. {
  1160. var videoTracks = stream.getVideoTracks();
  1161. for (i = 0; i < videoTracks.length; i++) {
  1162. videoStream.addTrack(videoTracks[i]);
  1163. }
  1164. }
  1165. }
  1166. else
  1167. videoStream = stream;
  1168. return videoStream;
  1169. };
  1170. module.exports = RTCUtils;
  1171. },{"../../service/RTC/RTCBrowserType.js":88,"../../service/RTC/Resolutions":90}],8:[function(require,module,exports){
  1172. var UI = {};
  1173. var VideoLayout = require("./videolayout/VideoLayout.js");
  1174. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1175. var Prezi = require("./prezi/Prezi.js");
  1176. var Etherpad = require("./etherpad/Etherpad.js");
  1177. var Chat = require("./side_pannels/chat/Chat.js");
  1178. var Toolbar = require("./toolbars/Toolbar");
  1179. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1180. var BottomToolbar = require("./toolbars/BottomToolbar");
  1181. var ContactList = require("./side_pannels/contactlist/ContactList");
  1182. var Avatar = require("./avatar/Avatar");
  1183. var EventEmitter = require("events");
  1184. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1185. var Settings = require("./../settings/Settings");
  1186. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1187. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1188. UI.messageHandler = require("./util/MessageHandler");
  1189. var messageHandler = UI.messageHandler;
  1190. var Authentication = require("./authentication/Authentication");
  1191. var UIUtil = require("./util/UIUtil");
  1192. var NicknameHandler = require("./util/NicknameHandler");
  1193. var CQEvents = require("../../service/connectionquality/CQEvents");
  1194. var DesktopSharingEventTypes
  1195. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1196. var RTCEvents = require("../../service/RTC/RTCEvents");
  1197. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1198. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1199. var eventEmitter = new EventEmitter();
  1200. var roomName = null;
  1201. function setupPrezi()
  1202. {
  1203. $("#reloadPresentationLink").click(function()
  1204. {
  1205. Prezi.reloadPresentation();
  1206. });
  1207. }
  1208. function setupChat()
  1209. {
  1210. Chat.init();
  1211. $("#toggle_smileys").click(function() {
  1212. Chat.toggleSmileys();
  1213. });
  1214. }
  1215. function setupToolbars() {
  1216. Toolbar.init(UI);
  1217. Toolbar.setupButtonsFromConfig();
  1218. BottomToolbar.init();
  1219. }
  1220. function streamHandler(stream) {
  1221. switch (stream.type)
  1222. {
  1223. case "audio":
  1224. VideoLayout.changeLocalAudio(stream);
  1225. break;
  1226. case "video":
  1227. VideoLayout.changeLocalVideo(stream);
  1228. break;
  1229. case "stream":
  1230. VideoLayout.changeLocalStream(stream);
  1231. break;
  1232. }
  1233. }
  1234. function onDisposeConference(unload) {
  1235. Toolbar.showAuthenticateButton(false);
  1236. };
  1237. function onDisplayNameChanged(jid, displayName) {
  1238. ContactList.onDisplayNameChange(jid, displayName);
  1239. SettingsMenu.onDisplayNameChange(jid, displayName);
  1240. VideoLayout.onDisplayNameChanged(jid, displayName);
  1241. }
  1242. function registerListeners() {
  1243. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1244. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1245. APP.RTC.addStreamListener(function (stream) {
  1246. VideoLayout.onRemoteStreamAdded(stream);
  1247. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1248. APP.RTC.addStreamListener(function (jid) {
  1249. VideoLayout.onVideoTypeChanged(jid);
  1250. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  1251. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1252. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1253. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1254. });
  1255. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1256. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1257. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1258. endpointsEnteringLastN, stream);
  1259. });
  1260. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  1261. function (endpointSimulcastLayers) {
  1262. VideoLayout.onSimulcastLayersChanged(endpointSimulcastLayers);
  1263. });
  1264. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGING,
  1265. function (endpointSimulcastLayers) {
  1266. VideoLayout.onSimulcastLayersChanging(endpointSimulcastLayers);
  1267. });
  1268. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1269. {
  1270. var resourceJid;
  1271. if(jid === APP.statistics.LOCAL_JID)
  1272. {
  1273. resourceJid = AudioLevels.LOCAL_LEVEL;
  1274. if(APP.RTC.localAudio.isMuted())
  1275. {
  1276. audioLevel = 0;
  1277. }
  1278. }
  1279. else
  1280. {
  1281. resourceJid = Strophe.getResourceFromJid(jid);
  1282. }
  1283. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1284. UI.getLargeVideoState().userResourceJid);
  1285. });
  1286. APP.desktopsharing.addListener(function () {
  1287. ToolbarToggler.showDesktopSharingButton();
  1288. }, DesktopSharingEventTypes.INIT);
  1289. APP.desktopsharing.addListener(
  1290. Toolbar.changeDesktopSharingButtonState,
  1291. DesktopSharingEventTypes.SWITCHING_DONE);
  1292. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1293. VideoLayout.updateLocalConnectionStats);
  1294. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1295. VideoLayout.updateConnectionStats);
  1296. APP.connectionquality.addListener(CQEvents.STOP,
  1297. VideoLayout.onStatsStop);
  1298. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1299. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  1300. messageHandler.openMessageDialog(
  1301. 'dialog.serviceUnavailable',
  1302. 'dialog.gracefulShutdown'
  1303. );
  1304. });
  1305. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  1306. var title = APP.translation.generateTranslatonHTML(
  1307. "dialog.reservationError");
  1308. var message = APP.translation.generateTranslatonHTML(
  1309. "dialog.reservationErrorMsg", {code: code, msg: msg});
  1310. messageHandler.openDialog(
  1311. title,
  1312. message,
  1313. true, {},
  1314. function (event, value, message, formVals)
  1315. {
  1316. return false;
  1317. }
  1318. );
  1319. });
  1320. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1321. messageHandler.openMessageDialog("dialog.sessTerminated",
  1322. "dialog.kickMessage");
  1323. });
  1324. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1325. //FIXME: use Session Terminated from translation, but
  1326. // 'reason' text comes from XMPP packet and is not translated
  1327. var title = APP.translation.generateTranslatonHTML("dialog.sessTerminated");
  1328. messageHandler.openDialog(
  1329. title, reason, true, {},
  1330. function (event, value, message, formVals)
  1331. {
  1332. return false;
  1333. }
  1334. );
  1335. });
  1336. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1337. messageHandler.showError("dialog.error",
  1338. "dialog.bridgeUnavailable");
  1339. });
  1340. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1341. Avatar.setUserAvatar(from, id);
  1342. });
  1343. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  1344. for(stream in changedStreams)
  1345. {
  1346. // might need to update the direction if participant just went from sendrecv to recvonly
  1347. if (stream.type === 'video' || stream.type === 'screen') {
  1348. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1349. switch (stream.direction) {
  1350. case 'sendrecv':
  1351. el.show();
  1352. break;
  1353. case 'recvonly':
  1354. el.hide();
  1355. // FIXME: Check if we have to change large video
  1356. //VideoLayout.updateLargeVideo(el);
  1357. break;
  1358. }
  1359. }
  1360. }
  1361. });
  1362. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1363. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1364. APP.xmpp.addListener(XMPPEvents.LOCALROLE_CHANGED, onLocalRoleChange);
  1365. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, onMucEntered);
  1366. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1367. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1368. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1369. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1370. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1371. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordReqiured);
  1372. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1373. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1374. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, onAuthenticationRequired);
  1375. }
  1376. /**
  1377. * Mutes/unmutes the local video.
  1378. *
  1379. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1380. * @param options an object which specifies optional arguments such as the
  1381. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1382. * specifies whether the method was initiated in response to a user command (in
  1383. * contrast to an automatic decision taken by the application logic)
  1384. */
  1385. function setVideoMute(mute, options) {
  1386. APP.RTC.setVideoMute(mute,
  1387. UI.setVideoMuteButtonsState,
  1388. options);
  1389. }
  1390. function bindEvents()
  1391. {
  1392. /**
  1393. * Resizes and repositions videos in full screen mode.
  1394. */
  1395. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1396. function () {
  1397. VideoLayout.resizeLargeVideoContainer();
  1398. VideoLayout.positionLarge();
  1399. }
  1400. );
  1401. $(window).resize(function () {
  1402. VideoLayout.resizeLargeVideoContainer();
  1403. VideoLayout.positionLarge();
  1404. });
  1405. }
  1406. UI.start = function (init) {
  1407. document.title = interfaceConfig.APP_NAME;
  1408. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1409. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1410. {
  1411. $("#videoconference_page").hide();
  1412. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1413. setupWelcomePage();
  1414. return;
  1415. }
  1416. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1417. var leftWatermarkDiv
  1418. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1419. leftWatermarkDiv.css({display: 'block'});
  1420. leftWatermarkDiv.parent().get(0).href
  1421. = interfaceConfig.JITSI_WATERMARK_LINK;
  1422. }
  1423. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1424. var rightWatermarkDiv
  1425. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1426. rightWatermarkDiv.css({display: 'block'});
  1427. rightWatermarkDiv.parent().get(0).href
  1428. = interfaceConfig.BRAND_WATERMARK_LINK;
  1429. rightWatermarkDiv.get(0).style.backgroundImage
  1430. = "url(images/rightwatermark.png)";
  1431. }
  1432. if (interfaceConfig.SHOW_POWERED_BY) {
  1433. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1434. }
  1435. $("#welcome_page").hide();
  1436. VideoLayout.resizeLargeVideoContainer();
  1437. $("#videospace").mousemove(function () {
  1438. return ToolbarToggler.showToolbar();
  1439. });
  1440. // Set the defaults for prompt dialogs.
  1441. jQuery.prompt.setDefaults({persistent: false});
  1442. VideoLayout.init(eventEmitter);
  1443. AudioLevels.init();
  1444. NicknameHandler.init(eventEmitter);
  1445. registerListeners();
  1446. bindEvents();
  1447. setupPrezi();
  1448. setupToolbars();
  1449. setupChat();
  1450. document.title = interfaceConfig.APP_NAME;
  1451. $("#downloadlog").click(function (event) {
  1452. dump(event.target);
  1453. });
  1454. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1455. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1456. {
  1457. $("#videoconference_page").hide();
  1458. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1459. setupWelcomePage();
  1460. return;
  1461. }
  1462. $("#welcome_page").hide();
  1463. // Display notice message at the top of the toolbar
  1464. if (config.noticeMessage) {
  1465. $('#noticeText').text(config.noticeMessage);
  1466. $('#notice').css({display: 'block'});
  1467. }
  1468. document.getElementById('largeVideo').volume = 0;
  1469. if (!$('#settings').is(':visible')) {
  1470. console.log('init');
  1471. init();
  1472. } else {
  1473. loginInfo.onsubmit = function (e) {
  1474. if (e.preventDefault) e.preventDefault();
  1475. $('#settings').hide();
  1476. init();
  1477. };
  1478. }
  1479. toastr.options = {
  1480. "closeButton": true,
  1481. "debug": false,
  1482. "positionClass": "notification-bottom-right",
  1483. "onclick": null,
  1484. "showDuration": "300",
  1485. "hideDuration": "1000",
  1486. "timeOut": "2000",
  1487. "extendedTimeOut": "1000",
  1488. "showEasing": "swing",
  1489. "hideEasing": "linear",
  1490. "showMethod": "fadeIn",
  1491. "hideMethod": "fadeOut",
  1492. "reposition": function() {
  1493. if(PanelToggler.isVisible()) {
  1494. $("#toast-container").addClass("notification-bottom-right-center");
  1495. } else {
  1496. $("#toast-container").removeClass("notification-bottom-right-center");
  1497. }
  1498. },
  1499. "newestOnTop": false
  1500. };
  1501. SettingsMenu.init();
  1502. };
  1503. function chatAddError(errorMessage, originalText)
  1504. {
  1505. return Chat.chatAddError(errorMessage, originalText);
  1506. };
  1507. function chatSetSubject(text)
  1508. {
  1509. return Chat.chatSetSubject(text);
  1510. };
  1511. function updateChatConversation(from, displayName, message) {
  1512. return Chat.updateChatConversation(from, displayName, message);
  1513. };
  1514. function onMucJoined(jid, info) {
  1515. Toolbar.updateRoomUrl(window.location.href);
  1516. var meHTML = APP.translation.generateTranslatonHTML("me");
  1517. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  1518. var settings = Settings.getSettings();
  1519. // Add myself to the contact list.
  1520. ContactList.addContact(jid, settings.email || settings.uid);
  1521. // Once we've joined the muc show the toolbar
  1522. ToolbarToggler.showToolbar();
  1523. var displayName = !config.displayJids
  1524. ? info.displayName : Strophe.getResourceFromJid(jid);
  1525. if (displayName)
  1526. onDisplayNameChanged('localVideoContainer', displayName);
  1527. }
  1528. function initEtherpad(name) {
  1529. Etherpad.init(name);
  1530. };
  1531. function onMucLeft(jid) {
  1532. console.log('left.muc', jid);
  1533. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1534. '>.displayname').html();
  1535. messageHandler.notify(displayName,'notify.somebody',
  1536. 'disconnected',
  1537. 'notify.disconnected');
  1538. // Need to call this with a slight delay, otherwise the element couldn't be
  1539. // found for some reason.
  1540. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1541. window.setTimeout(function () {
  1542. var container = document.getElementById(
  1543. 'participant_' + Strophe.getResourceFromJid(jid));
  1544. if (container) {
  1545. ContactList.removeContact(jid);
  1546. VideoLayout.removeConnectionIndicator(jid);
  1547. // hide here, wait for video to close before removing
  1548. $(container).hide();
  1549. VideoLayout.resizeThumbnails();
  1550. }
  1551. }, 10);
  1552. VideoLayout.participantLeft(jid);
  1553. };
  1554. function onLocalRoleChange(jid, info, pres, isModerator)
  1555. {
  1556. console.info("My role changed, new role: " + info.role);
  1557. onModeratorStatusChanged(isModerator);
  1558. VideoLayout.showModeratorIndicator();
  1559. if (isModerator) {
  1560. Authentication.closeAuthenticationWindow();
  1561. messageHandler.notify(null, "notify.me",
  1562. 'connected', "notify.moderator");
  1563. }
  1564. }
  1565. function onModeratorStatusChanged(isModerator) {
  1566. Toolbar.showSipCallButton(isModerator);
  1567. Toolbar.showRecordingButton(
  1568. isModerator); //&&
  1569. // FIXME:
  1570. // Recording visible if
  1571. // there are at least 2(+ 1 focus) participants
  1572. //Object.keys(connection.emuc.members).length >= 3);
  1573. if (isModerator && config.etherpad_base) {
  1574. Etherpad.init();
  1575. }
  1576. };
  1577. function onPasswordReqiured(callback) {
  1578. // password is required
  1579. Toolbar.lockLockButton();
  1580. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1581. message += APP.translation.translateString(
  1582. "dialog.passwordRequired");
  1583. message += '</h2>' +
  1584. '<input name="lockKey" type="text" data-i18n=' +
  1585. '"[placeholder]dialog.password" placeholder="' +
  1586. APP.translation.translateString("dialog.password") +
  1587. '" autofocus>';
  1588. messageHandler.openTwoButtonDialog(null, null, null, message,
  1589. true,
  1590. "dialog.Ok",
  1591. function (e, v, m, f) {},
  1592. null,
  1593. function (e, v, m, f) {
  1594. if (v) {
  1595. var lockKey = f.lockKey;
  1596. if (lockKey) {
  1597. Toolbar.setSharedKey(lockKey);
  1598. callback(lockKey);
  1599. }
  1600. }
  1601. },
  1602. ':input:first'
  1603. );
  1604. }
  1605. function onMucEntered(jid, id, displayName) {
  1606. messageHandler.notify(displayName,'notify.somebody',
  1607. 'connected',
  1608. 'notify.connected');
  1609. // Add Peer's container
  1610. VideoLayout.ensurePeerContainerExists(jid,id);
  1611. }
  1612. function onMucPresenceStatus( jid, info) {
  1613. VideoLayout.setPresenceStatus(
  1614. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1615. }
  1616. function onMucRoleChanged(role, displayName) {
  1617. VideoLayout.showModeratorIndicator();
  1618. if (role === 'moderator') {
  1619. var messageKey, messageOptions = {};
  1620. if (!displayName) {
  1621. messageKey = "notify.grantedToUnknown";
  1622. }
  1623. else
  1624. {
  1625. messageKey = "notify.grantedTo";
  1626. messageOptions = {to: displayName};
  1627. }
  1628. messageHandler.notify(
  1629. displayName,'notify.somebody',
  1630. 'connected', messageKey,
  1631. messageOptions);
  1632. }
  1633. }
  1634. function onAuthenticationRequired(intervalCallback) {
  1635. Authentication.openAuthenticationDialog(
  1636. roomName, intervalCallback, function () {
  1637. Toolbar.authenticateClicked();
  1638. });
  1639. };
  1640. function onLastNChanged(oldValue, newValue) {
  1641. if (config.muteLocalVideoIfNotInLastN) {
  1642. setVideoMute(!newValue, { 'byUser': false });
  1643. }
  1644. }
  1645. UI.toggleSmileys = function () {
  1646. Chat.toggleSmileys();
  1647. };
  1648. UI.getSettings = function () {
  1649. return Settings.getSettings();
  1650. };
  1651. UI.toggleFilmStrip = function () {
  1652. return BottomToolbar.toggleFilmStrip();
  1653. };
  1654. UI.toggleChat = function () {
  1655. return BottomToolbar.toggleChat();
  1656. };
  1657. UI.toggleContactList = function () {
  1658. return BottomToolbar.toggleContactList();
  1659. };
  1660. UI.inputDisplayNameHandler = function (value) {
  1661. VideoLayout.inputDisplayNameHandler(value);
  1662. };
  1663. UI.getLargeVideoState = function()
  1664. {
  1665. return VideoLayout.getLargeVideoState();
  1666. };
  1667. UI.generateRoomName = function() {
  1668. if(roomName)
  1669. return roomName;
  1670. var roomnode = null;
  1671. var path = window.location.pathname;
  1672. // determinde the room node from the url
  1673. // TODO: just the roomnode or the whole bare jid?
  1674. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1675. // custom function might be responsible for doing the pushstate
  1676. roomnode = config.getroomnode(path);
  1677. } else {
  1678. /* fall back to default strategy
  1679. * this is making assumptions about how the URL->room mapping happens.
  1680. * It currently assumes deployment at root, with a rewrite like the
  1681. * following one (for nginx):
  1682. location ~ ^/([a-zA-Z0-9]+)$ {
  1683. rewrite ^/(.*)$ / break;
  1684. }
  1685. */
  1686. if (path.length > 1) {
  1687. roomnode = path.substr(1).toLowerCase();
  1688. } else {
  1689. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1690. roomnode = word.toLowerCase();
  1691. window.history.pushState('VideoChat',
  1692. 'Room: ' + word, window.location.pathname + word);
  1693. }
  1694. }
  1695. roomName = roomnode + '@' + config.hosts.muc;
  1696. return roomName;
  1697. };
  1698. UI.connectionIndicatorShowMore = function(id)
  1699. {
  1700. return VideoLayout.connectionIndicators[id].showMore();
  1701. };
  1702. UI.showLoginPopup = function(callback)
  1703. {
  1704. console.log('password is required');
  1705. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1706. message += APP.translation.translateString(
  1707. "dialog.passwordRequired");
  1708. message += '</h2>' +
  1709. '<input name="username" type="text" ' +
  1710. 'placeholder="user@domain.net" autofocus>' +
  1711. '<input name="password" ' +
  1712. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  1713. ' placeholder="user password">';
  1714. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  1715. true,
  1716. "dialog.Ok",
  1717. function (e, v, m, f) {
  1718. if (v) {
  1719. if (f.username !== null && f.password != null) {
  1720. callback(f.username, f.password);
  1721. }
  1722. }
  1723. },
  1724. null, null, ':input:first'
  1725. );
  1726. }
  1727. UI.checkForNicknameAndJoin = function () {
  1728. Authentication.closeAuthenticationDialog();
  1729. Authentication.stopInterval();
  1730. var nick = null;
  1731. if (config.useNicks) {
  1732. nick = window.prompt('Your nickname (optional)');
  1733. }
  1734. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1735. };
  1736. function dump(elem, filename) {
  1737. elem = elem.parentNode;
  1738. elem.download = filename || 'meetlog.json';
  1739. elem.href = 'data:application/json;charset=utf-8,\n';
  1740. var data = APP.xmpp.populateData();
  1741. var metadata = {};
  1742. metadata.time = new Date();
  1743. metadata.url = window.location.href;
  1744. metadata.ua = navigator.userAgent;
  1745. var log = APP.xmpp.getLogger();
  1746. if (log) {
  1747. metadata.xmpp = log;
  1748. }
  1749. data.metadata = metadata;
  1750. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1751. return false;
  1752. }
  1753. UI.getRoomName = function () {
  1754. return roomName;
  1755. };
  1756. /**
  1757. * Mutes/unmutes the local video.
  1758. */
  1759. UI.toggleVideo = function () {
  1760. setVideoMute(!APP.RTC.localVideo.isMuted());
  1761. };
  1762. /**
  1763. * Mutes / unmutes audio for the local participant.
  1764. */
  1765. UI.toggleAudio = function() {
  1766. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  1767. };
  1768. /**
  1769. * Sets muted audio state for the local participant.
  1770. */
  1771. UI.setAudioMuted = function (mute) {
  1772. if(!APP.xmpp.setAudioMute(mute, function () {
  1773. VideoLayout.showLocalAudioIndicator(mute);
  1774. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1775. }))
  1776. {
  1777. // We still click the button.
  1778. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1779. return;
  1780. }
  1781. }
  1782. UI.addListener = function (type, listener) {
  1783. eventEmitter.on(type, listener);
  1784. }
  1785. UI.clickOnVideo = function (videoNumber) {
  1786. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  1787. if (remoteVideos.length > videoNumber) {
  1788. remoteVideos[videoNumber].click();
  1789. }
  1790. }
  1791. //Used by torture
  1792. UI.showToolbar = function () {
  1793. return ToolbarToggler.showToolbar();
  1794. }
  1795. //Used by torture
  1796. UI.dockToolbar = function (isDock) {
  1797. return ToolbarToggler.dockToolbar(isDock);
  1798. }
  1799. UI.setVideoMuteButtonsState = function (mute) {
  1800. var video = $('#video');
  1801. var communicativeClass = "icon-camera";
  1802. var muteClass = "icon-camera icon-camera-disabled";
  1803. if (mute) {
  1804. video.removeClass(communicativeClass);
  1805. video.addClass(muteClass);
  1806. } else {
  1807. video.removeClass(muteClass);
  1808. video.addClass(communicativeClass);
  1809. }
  1810. }
  1811. module.exports = UI;
  1812. },{"../../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){
  1813. var CanvasUtil = require("./CanvasUtils");
  1814. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  1815. function initActiveSpeakerAudioLevels() {
  1816. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  1817. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  1818. // Draw a circle.
  1819. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  1820. // Add a shadow around the circle
  1821. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  1822. ASDrawContext.shadowOffsetX = 0;
  1823. ASDrawContext.shadowOffsetY = 0;
  1824. }
  1825. /**
  1826. * The audio Levels plugin.
  1827. */
  1828. var AudioLevels = (function(my) {
  1829. var audioLevelCanvasCache = {};
  1830. my.LOCAL_LEVEL = 'local';
  1831. my.init = function () {
  1832. initActiveSpeakerAudioLevels();
  1833. }
  1834. /**
  1835. * Updates the audio level canvas for the given peerJid. If the canvas
  1836. * didn't exist we create it.
  1837. */
  1838. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  1839. var resourceJid = null;
  1840. var videoSpanId = null;
  1841. if (!peerJid)
  1842. videoSpanId = 'localVideoContainer';
  1843. else {
  1844. resourceJid = Strophe.getResourceFromJid(peerJid);
  1845. videoSpanId = 'participant_' + resourceJid;
  1846. }
  1847. var videoSpan = document.getElementById(videoSpanId);
  1848. if (!videoSpan) {
  1849. if (resourceJid)
  1850. console.error("No video element for jid", resourceJid);
  1851. else
  1852. console.error("No video element for local video.");
  1853. return;
  1854. }
  1855. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  1856. var videoSpaceWidth = $('#remoteVideos').width();
  1857. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  1858. var thumbnailWidth = thumbnailSize[0];
  1859. var thumbnailHeight = thumbnailSize[1];
  1860. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  1861. audioLevelCanvas = document.createElement('canvas');
  1862. audioLevelCanvas.className = "audiolevel";
  1863. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1864. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1865. resizeAudioLevelCanvas( audioLevelCanvas,
  1866. thumbnailWidth,
  1867. thumbnailHeight);
  1868. videoSpan.appendChild(audioLevelCanvas);
  1869. } else {
  1870. audioLevelCanvas = audioLevelCanvas.get(0);
  1871. resizeAudioLevelCanvas( audioLevelCanvas,
  1872. thumbnailWidth,
  1873. thumbnailHeight);
  1874. }
  1875. };
  1876. /**
  1877. * Updates the audio level UI for the given resourceJid.
  1878. *
  1879. * @param resourceJid the resource jid indicating the video element for
  1880. * which we draw the audio level
  1881. * @param audioLevel the newAudio level to render
  1882. */
  1883. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  1884. drawAudioLevelCanvas(resourceJid, audioLevel);
  1885. var videoSpanId = getVideoSpanId(resourceJid);
  1886. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  1887. if (!audioLevelCanvas)
  1888. return;
  1889. var drawContext = audioLevelCanvas.getContext('2d');
  1890. var canvasCache = audioLevelCanvasCache[resourceJid];
  1891. drawContext.clearRect (0, 0,
  1892. audioLevelCanvas.width, audioLevelCanvas.height);
  1893. drawContext.drawImage(canvasCache, 0, 0);
  1894. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  1895. if(!APP.xmpp.myJid()) {
  1896. return;
  1897. }
  1898. resourceJid = APP.xmpp.myResource();
  1899. }
  1900. if(resourceJid === largeVideoResourceJid) {
  1901. window.requestAnimationFrame(function () {
  1902. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  1903. });
  1904. }
  1905. };
  1906. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  1907. if($("#activeSpeaker").css("visibility") == "hidden")
  1908. return;
  1909. ASDrawContext.clearRect(0, 0, 300, 300);
  1910. if(audioLevel == 0)
  1911. return;
  1912. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  1913. // Fill the shape.
  1914. ASDrawContext.fill();
  1915. };
  1916. /**
  1917. * Resizes the given audio level canvas to match the given thumbnail size.
  1918. */
  1919. function resizeAudioLevelCanvas(audioLevelCanvas,
  1920. thumbnailWidth,
  1921. thumbnailHeight) {
  1922. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  1923. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  1924. }
  1925. /**
  1926. * Draws the audio level canvas into the cached canvas object.
  1927. *
  1928. * @param resourceJid the resource jid indicating the video element for
  1929. * which we draw the audio level
  1930. * @param audioLevel the newAudio level to render
  1931. */
  1932. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  1933. if (!audioLevelCanvasCache[resourceJid]) {
  1934. var videoSpanId = getVideoSpanId(resourceJid);
  1935. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  1936. /*
  1937. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  1938. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  1939. * error. Since audio levels are frequently updated, the errors have
  1940. * been observed to pile into the console, strain the CPU.
  1941. */
  1942. if (audioLevelCanvasOrig)
  1943. {
  1944. audioLevelCanvasCache[resourceJid]
  1945. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  1946. }
  1947. }
  1948. var canvas = audioLevelCanvasCache[resourceJid];
  1949. if (!canvas)
  1950. return;
  1951. var drawContext = canvas.getContext('2d');
  1952. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  1953. var shadowLevel = getShadowLevel(audioLevel);
  1954. if (shadowLevel > 0)
  1955. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  1956. CanvasUtil.drawRoundRectGlow( drawContext,
  1957. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  1958. canvas.width - interfaceConfig.CANVAS_EXTRA,
  1959. canvas.height - interfaceConfig.CANVAS_EXTRA,
  1960. interfaceConfig.CANVAS_RADIUS,
  1961. interfaceConfig.SHADOW_COLOR,
  1962. shadowLevel);
  1963. }
  1964. /**
  1965. * Returns the shadow/glow level for the given audio level.
  1966. *
  1967. * @param audioLevel the audio level from which we determine the shadow
  1968. * level
  1969. */
  1970. function getShadowLevel (audioLevel) {
  1971. var shadowLevel = 0;
  1972. if (audioLevel <= 0.3) {
  1973. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  1974. }
  1975. else if (audioLevel <= 0.6) {
  1976. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  1977. }
  1978. else {
  1979. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  1980. }
  1981. return shadowLevel;
  1982. }
  1983. /**
  1984. * Returns the video span id corresponding to the given resourceJid or local
  1985. * user.
  1986. */
  1987. function getVideoSpanId(resourceJid) {
  1988. var videoSpanId = null;
  1989. if (resourceJid === AudioLevels.LOCAL_LEVEL
  1990. || (APP.xmpp.myResource() && resourceJid
  1991. === APP.xmpp.myResource()))
  1992. videoSpanId = 'localVideoContainer';
  1993. else
  1994. videoSpanId = 'participant_' + resourceJid;
  1995. return videoSpanId;
  1996. }
  1997. /**
  1998. * Indicates that the remote video has been resized.
  1999. */
  2000. $(document).bind('remotevideo.resized', function (event, width, height) {
  2001. var resized = false;
  2002. $('#remoteVideos>span>canvas').each(function() {
  2003. var canvas = $(this).get(0);
  2004. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  2005. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  2006. resized = true;
  2007. }
  2008. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  2009. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  2010. resized = true;
  2011. }
  2012. });
  2013. if (resized)
  2014. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  2015. audioLevelCanvasCache[resourceJid].width
  2016. = width + interfaceConfig.CANVAS_EXTRA;
  2017. audioLevelCanvasCache[resourceJid].height
  2018. = height + interfaceConfig.CANVAS_EXTRA;
  2019. });
  2020. });
  2021. return my;
  2022. })(AudioLevels || {});
  2023. module.exports = AudioLevels;
  2024. },{"./CanvasUtils":10}],10:[function(require,module,exports){
  2025. /**
  2026. * Utility class for drawing canvas shapes.
  2027. */
  2028. var CanvasUtil = (function(my) {
  2029. /**
  2030. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  2031. * of the glow.
  2032. *
  2033. * @param drawContext the context of the canvas to draw to
  2034. * @param x the x coordinate of the round rectangle
  2035. * @param y the y coordinate of the round rectangle
  2036. * @param w the width of the round rectangle
  2037. * @param h the height of the round rectangle
  2038. * @param glowColor the color of the glow
  2039. * @param glowWidth the width of the glow
  2040. */
  2041. my.drawRoundRectGlow
  2042. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  2043. // Save the previous state of the context.
  2044. drawContext.save();
  2045. if (w < 2 * r) r = w / 2;
  2046. if (h < 2 * r) r = h / 2;
  2047. // Draw a round rectangle.
  2048. drawContext.beginPath();
  2049. drawContext.moveTo(x+r, y);
  2050. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2051. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2052. drawContext.arcTo(x, y+h, x, y, r);
  2053. drawContext.arcTo(x, y, x+w, y, r);
  2054. drawContext.closePath();
  2055. // Add a shadow around the rectangle
  2056. drawContext.shadowColor = glowColor;
  2057. drawContext.shadowBlur = glowWidth;
  2058. drawContext.shadowOffsetX = 0;
  2059. drawContext.shadowOffsetY = 0;
  2060. // Fill the shape.
  2061. drawContext.fill();
  2062. drawContext.save();
  2063. drawContext.restore();
  2064. // 1) Uncomment this line to use Composite Operation, which is doing the
  2065. // same as the clip function below and is also antialiasing the round
  2066. // border, but is said to be less fast performance wise.
  2067. // drawContext.globalCompositeOperation='destination-out';
  2068. drawContext.beginPath();
  2069. drawContext.moveTo(x+r, y);
  2070. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2071. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2072. drawContext.arcTo(x, y+h, x, y, r);
  2073. drawContext.arcTo(x, y, x+w, y, r);
  2074. drawContext.closePath();
  2075. // 2) Uncomment this line to use Composite Operation, which is doing the
  2076. // same as the clip function below and is also antialiasing the round
  2077. // border, but is said to be less fast performance wise.
  2078. // drawContext.fill();
  2079. // Comment these two lines if choosing to do the same with composite
  2080. // operation above 1 and 2.
  2081. drawContext.clip();
  2082. drawContext.clearRect(0, 0, 277, 200);
  2083. // Restore the previous context state.
  2084. drawContext.restore();
  2085. };
  2086. /**
  2087. * Clones the given canvas.
  2088. *
  2089. * @return the new cloned canvas.
  2090. */
  2091. my.cloneCanvas = function (oldCanvas) {
  2092. /*
  2093. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2094. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2095. * levels are frequently updated, the errors have been observed to pile
  2096. * into the console, strain the CPU.
  2097. */
  2098. if (!oldCanvas)
  2099. return oldCanvas;
  2100. //create a new canvas
  2101. var newCanvas = document.createElement('canvas');
  2102. var context = newCanvas.getContext('2d');
  2103. //set dimensions
  2104. newCanvas.width = oldCanvas.width;
  2105. newCanvas.height = oldCanvas.height;
  2106. //apply the old canvas to the new one
  2107. context.drawImage(oldCanvas, 0, 0);
  2108. //return the new canvas
  2109. return newCanvas;
  2110. };
  2111. return my;
  2112. })(CanvasUtil || {});
  2113. module.exports = CanvasUtil;
  2114. },{}],11:[function(require,module,exports){
  2115. /* global $, APP*/
  2116. var LoginDialog = require('./LoginDialog');
  2117. var Moderator = require('../../xmpp/moderator');
  2118. /* Initial "authentication required" dialog */
  2119. var authDialog = null;
  2120. /* Loop retry ID that wits for other user to create the room */
  2121. var authRetryId = null;
  2122. var authenticationWindow = null;
  2123. var Authentication = {
  2124. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2125. // This is the loop that will wait for the room to be created by
  2126. // someone else. 'auth_required.moderator' will bring us back here.
  2127. authRetryId = window.setTimeout(intervalCallback, 5000);
  2128. // Show prompt only if it's not open
  2129. if (authDialog !== null) {
  2130. return;
  2131. }
  2132. // extract room name from 'room@muc.server.net'
  2133. var room = roomName.substr(0, roomName.indexOf('@'));
  2134. var title = APP.translation.generateTranslatonHTML("dialog.Stop");
  2135. var msg = APP.translation.generateTranslatonHTML("dialog.AuthMsg",
  2136. {room: room});
  2137. var buttonTxt
  2138. = APP.translation.generateTranslatonHTML("dialog.Authenticate");
  2139. var buttons = [];
  2140. buttons.push({title: buttonTxt, value: "authNow"});
  2141. authDialog = APP.UI.messageHandler.openDialog(
  2142. title,
  2143. msg,
  2144. true,
  2145. buttons,
  2146. function (onSubmitEvent, submitValue) {
  2147. // Do not close the dialog yet
  2148. onSubmitEvent.preventDefault();
  2149. // Open login popup
  2150. if (submitValue === 'authNow') {
  2151. callback();
  2152. }
  2153. }
  2154. );
  2155. },
  2156. closeAuthenticationWindow: function () {
  2157. if (authenticationWindow) {
  2158. authenticationWindow.close();
  2159. authenticationWindow = null;
  2160. }
  2161. },
  2162. xmppAuthenticate: function () {
  2163. var loginDialog = LoginDialog.show(
  2164. function (connection, state) {
  2165. if (!state) {
  2166. // User cancelled
  2167. loginDialog.close();
  2168. return;
  2169. } else if (state == APP.xmpp.Status.CONNECTED) {
  2170. loginDialog.close();
  2171. Authentication.stopInterval();
  2172. Authentication.closeAuthenticationDialog();
  2173. // Close the connection as anonymous one will be used
  2174. // to create the conference. Session-id will authorize
  2175. // the request.
  2176. connection.disconnect();
  2177. var roomName = APP.UI.generateRoomName();
  2178. Moderator.allocateConferenceFocus(roomName, function () {
  2179. // If it's not "on the fly" authentication now join
  2180. // the conference room
  2181. if (!APP.xmpp.getMUCJoined()) {
  2182. APP.UI.checkForNicknameAndJoin();
  2183. }
  2184. });
  2185. }
  2186. }, true);
  2187. },
  2188. focusAuthenticationWindow: function () {
  2189. // If auth window exists just bring it to the front
  2190. if (authenticationWindow) {
  2191. authenticationWindow.focus();
  2192. return;
  2193. }
  2194. },
  2195. closeAuthenticationDialog: function () {
  2196. // Close authentication dialog if opened
  2197. if (authDialog) {
  2198. authDialog.close();
  2199. authDialog = null;
  2200. }
  2201. },
  2202. createAuthenticationWindow: function (callback, url) {
  2203. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2204. url, 910, 660,
  2205. // On closed
  2206. function () {
  2207. // Close authentication dialog if opened
  2208. Authentication.closeAuthenticationDialog();
  2209. callback();
  2210. authenticationWindow = null;
  2211. });
  2212. return authenticationWindow;
  2213. },
  2214. stopInterval: function () {
  2215. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2216. if (authRetryId) {
  2217. window.clearTimeout(authRetryId);
  2218. authRetryId = null;
  2219. }
  2220. }
  2221. };
  2222. module.exports = Authentication;
  2223. },{"../../xmpp/moderator":53,"./LoginDialog":12}],12:[function(require,module,exports){
  2224. /* global $, APP, config*/
  2225. var XMPP = require('../../xmpp/xmpp');
  2226. var Moderator = require('../../xmpp/moderator');
  2227. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  2228. // anonymous domain is not enabled
  2229. /**
  2230. * Creates new <tt>Dialog</tt> instance.
  2231. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  2232. * when we either fail to connect or succeed(check Strophe.Status).
  2233. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  2234. * in order to create session-id after the connection is established.
  2235. * @constructor
  2236. */
  2237. function Dialog(callback, obtainSession) {
  2238. var self = this;
  2239. var stop = false;
  2240. var connection = APP.xmpp.createConnection();
  2241. var message = '<h2 data-i18n="dialog.passwordRequired">';
  2242. message += APP.translation.translateString("dialog.passwordRequired");
  2243. message += '</h2>' +
  2244. '<input name="username" type="text" ' +
  2245. 'placeholder="user@domain.net" autofocus>' +
  2246. '<input name="password" ' +
  2247. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  2248. ' placeholder="user password">';
  2249. var okButton = APP.translation.generateTranslatonHTML("dialog.Ok");
  2250. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel");
  2251. var states = {
  2252. login: {
  2253. html: message,
  2254. buttons: [
  2255. { title: okButton, value: true},
  2256. { title: cancelButton, value: false}
  2257. ],
  2258. focus: ':input:first',
  2259. submit: function (e, v, m, f) {
  2260. e.preventDefault();
  2261. if (v) {
  2262. var jid = f.username;
  2263. var password = f.password;
  2264. if (jid && password) {
  2265. stop = false;
  2266. connection.reset();
  2267. connDialog.goToState('connecting');
  2268. connection.connect(jid, password, stateHandler);
  2269. }
  2270. } else {
  2271. // User cancelled
  2272. stop = true;
  2273. callback();
  2274. }
  2275. }
  2276. },
  2277. connecting: {
  2278. title: APP.translation.translateString('dialog.connecting'),
  2279. html: '<div id="connectionStatus"></div>',
  2280. buttons: [],
  2281. defaultButton: 0
  2282. },
  2283. finished: {
  2284. title: APP.translation.translateString('dialog.error'),
  2285. html: '<div id="errorMessage"></div>',
  2286. buttons: [
  2287. {
  2288. title: APP.translation.translateString('dialog.retry'),
  2289. value: 'retry'
  2290. },
  2291. {
  2292. title: APP.translation.translateString('dialog.Cancel'),
  2293. value: 'cancel'
  2294. },
  2295. ],
  2296. defaultButton: 0,
  2297. submit: function (e, v, m, f) {
  2298. e.preventDefault();
  2299. if (v === 'retry')
  2300. connDialog.goToState('login');
  2301. else
  2302. callback();
  2303. }
  2304. }
  2305. };
  2306. var connDialog
  2307. = APP.UI.messageHandler.openDialogWithStates(states,
  2308. { persistent: true, closeText: '' }, null);
  2309. var stateHandler = function (status, message) {
  2310. if (stop) {
  2311. return;
  2312. }
  2313. var translateKey = "connection." + XMPP.getStatusString(status);
  2314. var statusStr = APP.translation.translateString(translateKey);
  2315. // Display current state
  2316. var connectionStatus =
  2317. connDialog.getState('connecting').find('#connectionStatus');
  2318. connectionStatus.text(statusStr);
  2319. switch (status) {
  2320. case XMPP.Status.CONNECTED:
  2321. stop = true;
  2322. if (!obtainSession) {
  2323. callback(connection, status);
  2324. return;
  2325. }
  2326. // Obtaining session-id status
  2327. connectionStatus.text(
  2328. APP.translation.translateString(
  2329. 'connection.FETCH_SESSION_ID'));
  2330. // Authenticate with Jicofo and obtain session-id
  2331. var roomName = APP.UI.generateRoomName();
  2332. // Jicofo will return new session-id when connected
  2333. // from authenticated domain
  2334. connection.sendIQ(
  2335. Moderator.createConferenceIq(roomName),
  2336. function (result) {
  2337. connectionStatus.text(
  2338. APP.translation.translateString(
  2339. 'connection.GOT_SESSION_ID'));
  2340. stop = true;
  2341. // Parse session-id
  2342. Moderator.parseSessionId(result);
  2343. callback(connection, status);
  2344. },
  2345. function (error) {
  2346. console.error("Auth on the fly failed", error);
  2347. stop = true;
  2348. var errorMsg =
  2349. APP.translation.translateString(
  2350. 'connection.GET_SESSION_ID_ERROR') +
  2351. $(error).find('>error').attr('code');
  2352. self.displayError(errorMsg);
  2353. connection.disconnect();
  2354. });
  2355. break;
  2356. case XMPP.Status.AUTHFAIL:
  2357. case XMPP.Status.CONNFAIL:
  2358. case XMPP.Status.DISCONNECTED:
  2359. stop = true;
  2360. callback(connection, status);
  2361. var errorMessage = statusStr;
  2362. if (message)
  2363. {
  2364. errorMessage += ': ' + message;
  2365. }
  2366. self.displayError(errorMessage);
  2367. break;
  2368. default:
  2369. break;
  2370. }
  2371. };
  2372. /**
  2373. * Displays error message in 'finished' state which allows either to cancel
  2374. * or retry.
  2375. * @param message the final message to be displayed.
  2376. */
  2377. this.displayError = function (message) {
  2378. var finishedState = connDialog.getState('finished');
  2379. var errorMessageElem = finishedState.find('#errorMessage');
  2380. errorMessageElem.text(message);
  2381. connDialog.goToState('finished');
  2382. };
  2383. /**
  2384. * Closes LoginDialog.
  2385. */
  2386. this.close = function () {
  2387. stop = true;
  2388. connDialog.close();
  2389. };
  2390. }
  2391. var LoginDialog = {
  2392. /**
  2393. * Displays login prompt used to establish new XMPP connection. Given
  2394. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  2395. * called when we connect successfully(status === CONNECTED) or when we fail
  2396. * to do so. On connection failure program can call Dialog.close() method in
  2397. * order to cancel or do nothing to let the user retry.
  2398. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  2399. * called when we either fail to connect or succeed(check
  2400. * Strophe.Status).
  2401. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  2402. * Jicofo in order to create session-id after the connection is
  2403. * established.
  2404. * @returns {Dialog}
  2405. */
  2406. show: function (callback, obtainSession) {
  2407. return new Dialog(callback, obtainSession);
  2408. }
  2409. };
  2410. module.exports = LoginDialog;
  2411. },{"../../xmpp/moderator":53,"../../xmpp/xmpp":61}],13:[function(require,module,exports){
  2412. var Settings = require("../../settings/Settings");
  2413. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2414. var users = {};
  2415. var activeSpeakerJid;
  2416. function setVisibility(selector, show) {
  2417. if (selector && selector.length > 0) {
  2418. selector.css("visibility", show ? "visible" : "hidden");
  2419. }
  2420. }
  2421. function isUserMuted(jid) {
  2422. // XXX(gp) we may want to rename this method to something like
  2423. // isUserStreaming, for example.
  2424. if (jid && jid != APP.xmpp.myJid()) {
  2425. var resource = Strophe.getResourceFromJid(jid);
  2426. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2427. return true;
  2428. }
  2429. }
  2430. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2431. return null;
  2432. }
  2433. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2434. }
  2435. function getGravatarUrl(id, size) {
  2436. if(id === APP.xmpp.myJid() || !id) {
  2437. id = Settings.getSettings().uid;
  2438. }
  2439. return 'https://www.gravatar.com/avatar/' +
  2440. MD5.hexdigest(id.trim().toLowerCase()) +
  2441. "?d=wavatar&size=" + (size || "30");
  2442. }
  2443. var Avatar = {
  2444. /**
  2445. * Sets the user's avatar in the settings menu(if local user), contact list
  2446. * and thumbnail
  2447. * @param jid jid of the user
  2448. * @param id email or userID to be used as a hash
  2449. */
  2450. setUserAvatar: function (jid, id) {
  2451. if (id) {
  2452. if (users[jid] === id) {
  2453. return;
  2454. }
  2455. users[jid] = id;
  2456. }
  2457. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2458. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2459. var resourceJid = Strophe.getResourceFromJid(jid);
  2460. var thumbnail = $('#participant_' + resourceJid);
  2461. var avatar = $('#avatar_' + resourceJid);
  2462. // set the avatar in the settings menu if it is local user and get the
  2463. // local video container
  2464. if (jid === APP.xmpp.myJid()) {
  2465. $('#avatar').get(0).src = thumbUrl;
  2466. thumbnail = $('#localVideoContainer');
  2467. }
  2468. // set the avatar in the contact list
  2469. var contact = $('#' + resourceJid + '>img');
  2470. if (contact && contact.length > 0) {
  2471. contact.get(0).src = contactListUrl;
  2472. }
  2473. // set the avatar in the thumbnail
  2474. if (avatar && avatar.length > 0) {
  2475. avatar[0].src = thumbUrl;
  2476. } else {
  2477. if (thumbnail && thumbnail.length > 0) {
  2478. avatar = document.createElement('img');
  2479. avatar.id = 'avatar_' + resourceJid;
  2480. avatar.className = 'userAvatar';
  2481. avatar.src = thumbUrl;
  2482. thumbnail.append(avatar);
  2483. }
  2484. }
  2485. //if the user is the current active speaker - update the active speaker
  2486. // avatar
  2487. if (jid === activeSpeakerJid) {
  2488. this.updateActiveSpeakerAvatarSrc(jid);
  2489. }
  2490. },
  2491. /**
  2492. * Hides or shows the user's avatar
  2493. * @param jid jid of the user
  2494. * @param show whether we should show the avatar or not
  2495. * video because there is no dominant speaker and no focused speaker
  2496. */
  2497. showUserAvatar: function (jid, show) {
  2498. if (users[jid]) {
  2499. var resourceJid = Strophe.getResourceFromJid(jid);
  2500. var video = $('#participant_' + resourceJid + '>video');
  2501. var avatar = $('#avatar_' + resourceJid);
  2502. if (jid === APP.xmpp.myJid()) {
  2503. video = $('#localVideoWrapper>video');
  2504. }
  2505. if (show === undefined || show === null) {
  2506. show = isUserMuted(jid);
  2507. }
  2508. //if the user is the currently focused, the dominant speaker or if
  2509. //there is no focused and no dominant speaker and the large video is
  2510. //currently shown
  2511. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2512. setVisibility($("#largeVideo"), !show);
  2513. setVisibility($('#activeSpeaker'), show);
  2514. setVisibility(avatar, false);
  2515. setVisibility(video, false);
  2516. } else {
  2517. if (video && video.length > 0) {
  2518. setVisibility(video, !show);
  2519. setVisibility(avatar, show);
  2520. }
  2521. }
  2522. }
  2523. },
  2524. /**
  2525. * Updates the src of the active speaker avatar
  2526. * @param jid of the current active speaker
  2527. */
  2528. updateActiveSpeakerAvatarSrc: function (jid) {
  2529. if (!jid) {
  2530. jid = APP.xmpp.findJidFromResource(
  2531. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2532. }
  2533. var avatar = $("#activeSpeakerAvatar")[0];
  2534. var url = getGravatarUrl(users[jid],
  2535. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2536. if (jid === activeSpeakerJid && avatar.src === url) {
  2537. return;
  2538. }
  2539. activeSpeakerJid = jid;
  2540. var isMuted = isUserMuted(jid);
  2541. if (jid && isMuted !== null) {
  2542. avatar.src = url;
  2543. setVisibility($("#largeVideo"), !isMuted);
  2544. Avatar.showUserAvatar(jid, isMuted);
  2545. }
  2546. }
  2547. };
  2548. module.exports = Avatar;
  2549. },{"../../../service/RTC/MediaStreamTypes":87,"../../settings/Settings":38,"../videolayout/VideoLayout":32}],14:[function(require,module,exports){
  2550. /* global $, config,
  2551. setLargeVideoVisible, Util */
  2552. var VideoLayout = require("../videolayout/VideoLayout");
  2553. var Prezi = require("../prezi/Prezi");
  2554. var UIUtil = require("../util/UIUtil");
  2555. var etherpadName = null;
  2556. var etherpadIFrame = null;
  2557. var domain = null;
  2558. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2559. /**
  2560. * Resizes the etherpad.
  2561. */
  2562. function resize() {
  2563. if ($('#etherpad>iframe').length) {
  2564. var remoteVideos = $('#remoteVideos');
  2565. var availableHeight
  2566. = window.innerHeight - remoteVideos.outerHeight();
  2567. var availableWidth = UIUtil.getAvailableVideoWidth();
  2568. $('#etherpad>iframe').width(availableWidth);
  2569. $('#etherpad>iframe').height(availableHeight);
  2570. }
  2571. }
  2572. /**
  2573. * Shares the Etherpad name with other participants.
  2574. */
  2575. function shareEtherpad() {
  2576. APP.xmpp.addToPresence("etherpad", etherpadName);
  2577. }
  2578. /**
  2579. * Creates the Etherpad button and adds it to the toolbar.
  2580. */
  2581. function enableEtherpadButton() {
  2582. if (!$('#etherpadButton').is(":visible"))
  2583. $('#etherpadButton').css({display: 'inline-block'});
  2584. }
  2585. /**
  2586. * Creates the IFrame for the etherpad.
  2587. */
  2588. function createIFrame() {
  2589. etherpadIFrame = document.createElement('iframe');
  2590. etherpadIFrame.src = domain + etherpadName + options;
  2591. etherpadIFrame.frameBorder = 0;
  2592. etherpadIFrame.scrolling = "no";
  2593. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2594. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2595. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2596. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2597. etherpadIFrame.onload = function() {
  2598. document.domain = document.domain;
  2599. bubbleIframeMouseMove(etherpadIFrame);
  2600. setTimeout(function() {
  2601. // the iframes inside of the etherpad are
  2602. // not yet loaded when the etherpad iframe is loaded
  2603. var outer = etherpadIFrame.
  2604. contentDocument.getElementsByName("ace_outer")[0];
  2605. bubbleIframeMouseMove(outer);
  2606. var inner = outer.
  2607. contentDocument.getElementsByName("ace_inner")[0];
  2608. bubbleIframeMouseMove(inner);
  2609. }, 2000);
  2610. };
  2611. }
  2612. function bubbleIframeMouseMove(iframe){
  2613. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2614. iframe.contentWindow.onmousemove = function(e){
  2615. if(existingOnMouseMove) existingOnMouseMove(e);
  2616. var evt = document.createEvent("MouseEvents");
  2617. var boundingClientRect = iframe.getBoundingClientRect();
  2618. evt.initMouseEvent(
  2619. "mousemove",
  2620. true, // bubbles
  2621. false, // not cancelable
  2622. window,
  2623. e.detail,
  2624. e.screenX,
  2625. e.screenY,
  2626. e.clientX + boundingClientRect.left,
  2627. e.clientY + boundingClientRect.top,
  2628. e.ctrlKey,
  2629. e.altKey,
  2630. e.shiftKey,
  2631. e.metaKey,
  2632. e.button,
  2633. null // no related element
  2634. );
  2635. iframe.dispatchEvent(evt);
  2636. };
  2637. }
  2638. /**
  2639. * On video selected event.
  2640. */
  2641. $(document).bind('video.selected', function (event, isPresentation) {
  2642. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2643. Etherpad.toggleEtherpad(isPresentation);
  2644. });
  2645. var Etherpad = {
  2646. /**
  2647. * Initializes the etherpad.
  2648. */
  2649. init: function (name) {
  2650. if (config.etherpad_base && !etherpadName) {
  2651. domain = config.etherpad_base;
  2652. if (!name) {
  2653. // In case we're the focus we generate the name.
  2654. etherpadName = Math.random().toString(36).substring(7) +
  2655. '_' + (new Date().getTime()).toString();
  2656. shareEtherpad();
  2657. }
  2658. else
  2659. etherpadName = name;
  2660. enableEtherpadButton();
  2661. /**
  2662. * Resizes the etherpad, when the window is resized.
  2663. */
  2664. $(window).resize(function () {
  2665. resize();
  2666. });
  2667. }
  2668. },
  2669. /**
  2670. * Opens/hides the Etherpad.
  2671. */
  2672. toggleEtherpad: function (isPresentation) {
  2673. if (!etherpadIFrame)
  2674. createIFrame();
  2675. var largeVideo = null;
  2676. if (Prezi.isPresentationVisible())
  2677. largeVideo = $('#presentation>iframe');
  2678. else
  2679. largeVideo = $('#largeVideo');
  2680. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2681. $('#activeSpeaker').css('visibility', 'hidden');
  2682. largeVideo.fadeOut(300, function () {
  2683. if (Prezi.isPresentationVisible()) {
  2684. largeVideo.css({opacity: '0'});
  2685. } else {
  2686. VideoLayout.setLargeVideoVisible(false);
  2687. }
  2688. });
  2689. $('#etherpad>iframe').fadeIn(300, function () {
  2690. document.body.style.background = '#eeeeee';
  2691. $('#etherpad>iframe').css({visibility: 'visible'});
  2692. $('#etherpad').css({zIndex: 2});
  2693. });
  2694. }
  2695. else if ($('#etherpad>iframe')) {
  2696. $('#etherpad>iframe').fadeOut(300, function () {
  2697. $('#etherpad>iframe').css({visibility: 'hidden'});
  2698. $('#etherpad').css({zIndex: 0});
  2699. document.body.style.background = 'black';
  2700. });
  2701. if (!isPresentation) {
  2702. $('#largeVideo').fadeIn(300, function () {
  2703. VideoLayout.setLargeVideoVisible(true);
  2704. });
  2705. }
  2706. }
  2707. resize();
  2708. },
  2709. isVisible: function() {
  2710. var etherpadIframe = $('#etherpad>iframe');
  2711. return etherpadIframe && etherpadIframe.is(':visible');
  2712. }
  2713. };
  2714. module.exports = Etherpad;
  2715. },{"../prezi/Prezi":15,"../util/UIUtil":30,"../videolayout/VideoLayout":32}],15:[function(require,module,exports){
  2716. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2717. var UIUtil = require("../util/UIUtil");
  2718. var VideoLayout = require("../videolayout/VideoLayout");
  2719. var messageHandler = require("../util/MessageHandler");
  2720. var PreziPlayer = require("./PreziPlayer");
  2721. var preziPlayer = null;
  2722. var Prezi = {
  2723. /**
  2724. * Reloads the current presentation.
  2725. */
  2726. reloadPresentation: function() {
  2727. var iframe = document.getElementById(preziPlayer.options.preziId);
  2728. iframe.src = iframe.src;
  2729. },
  2730. /**
  2731. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2732. * otherwise.
  2733. */
  2734. isPresentationVisible: function () {
  2735. return ($('#presentation>iframe') != null
  2736. && $('#presentation>iframe').css('opacity') == 1);
  2737. },
  2738. /**
  2739. * Opens the Prezi dialog, from which the user could choose a presentation
  2740. * to load.
  2741. */
  2742. openPreziDialog: function() {
  2743. var myprezi = APP.xmpp.getPrezi();
  2744. if (myprezi) {
  2745. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  2746. null,
  2747. "dialog.removePreziMsg",
  2748. null,
  2749. false,
  2750. "dialog.Remove",
  2751. function(e,v,m,f) {
  2752. if(v) {
  2753. APP.xmpp.removePreziFromPresence();
  2754. }
  2755. }
  2756. );
  2757. }
  2758. else if (preziPlayer != null) {
  2759. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  2760. null, "dialog.sharePreziMsg",
  2761. null,
  2762. false,
  2763. "dialog.Ok",
  2764. function(e,v,m,f) {
  2765. $.prompt.close();
  2766. }
  2767. );
  2768. }
  2769. else {
  2770. var html = APP.translation.generateTranslatonHTML(
  2771. "dialog.sharePreziTitle");
  2772. var cancelButton = APP.translation.generateTranslatonHTML(
  2773. "dialog.Cancel");
  2774. var shareButton = APP.translation.generateTranslatonHTML(
  2775. "dialog.Share");
  2776. var backButton = APP.translation.generateTranslatonHTML(
  2777. "dialog.Back");
  2778. var buttons = [];
  2779. var buttons1 = [];
  2780. // Cancel button to both states
  2781. buttons.push({title: cancelButton, value: false});
  2782. buttons1.push({title: cancelButton, value: false});
  2783. // Share button
  2784. buttons.push({title: shareButton, value: true});
  2785. // Back button
  2786. buttons1.push({title: backButton, value: true});
  2787. var linkError = APP.translation.generateTranslatonHTML(
  2788. "dialog.preziLinkError");
  2789. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  2790. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  2791. var openPreziState = {
  2792. state0: {
  2793. html: '<h2>' + html + '</h2>' +
  2794. '<input name="preziUrl" type="text" ' +
  2795. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  2796. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  2797. '\' placeholder="' + defaultUrl + '" autofocus>',
  2798. persistent: false,
  2799. buttons: buttons,
  2800. focus: ':input:first',
  2801. defaultButton: 0,
  2802. submit: function (e, v, m, f) {
  2803. e.preventDefault();
  2804. if(v)
  2805. {
  2806. var preziUrl = f.preziUrl;
  2807. if (preziUrl)
  2808. {
  2809. var urlValue
  2810. = encodeURI(UIUtil.escapeHtml(preziUrl));
  2811. if (urlValue.indexOf('http://prezi.com/') != 0
  2812. && urlValue.indexOf('https://prezi.com/') != 0)
  2813. {
  2814. $.prompt.goToState('state1');
  2815. return false;
  2816. }
  2817. else {
  2818. var presIdTmp = urlValue.substring(
  2819. urlValue.indexOf("prezi.com/") + 10);
  2820. if (!isAlphanumeric(presIdTmp)
  2821. || presIdTmp.indexOf('/') < 2) {
  2822. $.prompt.goToState('state1');
  2823. return false;
  2824. }
  2825. else {
  2826. APP.xmpp.addToPresence("prezi", urlValue);
  2827. $.prompt.close();
  2828. }
  2829. }
  2830. }
  2831. }
  2832. else
  2833. $.prompt.close();
  2834. }
  2835. },
  2836. state1: {
  2837. html: '<h2>' + html + '</h2>' +
  2838. linkError,
  2839. persistent: false,
  2840. buttons: buttons1,
  2841. focus: ':input:first',
  2842. defaultButton: 1,
  2843. submit: function (e, v, m, f) {
  2844. e.preventDefault();
  2845. if (v === 0)
  2846. $.prompt.close();
  2847. else
  2848. $.prompt.goToState('state0');
  2849. }
  2850. }
  2851. };
  2852. messageHandler.openDialogWithStates(openPreziState);
  2853. }
  2854. }
  2855. };
  2856. /**
  2857. * A new presentation has been added.
  2858. *
  2859. * @param event the event indicating the add of a presentation
  2860. * @param jid the jid from which the presentation was added
  2861. * @param presUrl url of the presentation
  2862. * @param currentSlide the current slide to which we should move
  2863. */
  2864. function presentationAdded(event, jid, presUrl, currentSlide) {
  2865. console.log("presentation added", presUrl);
  2866. var presId = getPresentationId(presUrl);
  2867. var elementId = 'participant_'
  2868. + Strophe.getResourceFromJid(jid)
  2869. + '_' + presId;
  2870. // We explicitly don't specify the peer jid here, because we don't want
  2871. // this video to be dealt with as a peer related one (for example we
  2872. // don't want to show a mute/kick menu for this one, etc.).
  2873. VideoLayout.addRemoteVideoContainer(null, elementId);
  2874. VideoLayout.resizeThumbnails();
  2875. var controlsEnabled = false;
  2876. if (jid === APP.xmpp.myJid())
  2877. controlsEnabled = true;
  2878. setPresentationVisible(true);
  2879. $('#largeVideoContainer').hover(
  2880. function (event) {
  2881. if (Prezi.isPresentationVisible()) {
  2882. var reloadButtonRight = window.innerWidth
  2883. - $('#presentation>iframe').offset().left
  2884. - $('#presentation>iframe').width();
  2885. $('#reloadPresentation').css({ right: reloadButtonRight,
  2886. display:'inline-block'});
  2887. }
  2888. },
  2889. function (event) {
  2890. if (!Prezi.isPresentationVisible())
  2891. $('#reloadPresentation').css({display:'none'});
  2892. else {
  2893. var e = event.toElement || event.relatedTarget;
  2894. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  2895. $('#reloadPresentation').css({display:'none'});
  2896. }
  2897. });
  2898. preziPlayer = new PreziPlayer(
  2899. 'presentation',
  2900. {preziId: presId,
  2901. width: getPresentationWidth(),
  2902. height: getPresentationHeihgt(),
  2903. controls: controlsEnabled,
  2904. debug: true
  2905. });
  2906. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  2907. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  2908. console.log("prezi status", event.value);
  2909. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  2910. if (jid != APP.xmpp.myJid())
  2911. preziPlayer.flyToStep(currentSlide);
  2912. }
  2913. });
  2914. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  2915. console.log("event value", event.value);
  2916. APP.xmpp.addToPresence("preziSlide", event.value);
  2917. });
  2918. $("#" + elementId).css( 'background-image',
  2919. 'url(../images/avatarprezi.png)');
  2920. $("#" + elementId).click(
  2921. function () {
  2922. setPresentationVisible(true);
  2923. }
  2924. );
  2925. };
  2926. /**
  2927. * A presentation has been removed.
  2928. *
  2929. * @param event the event indicating the remove of a presentation
  2930. * @param jid the jid for which the presentation was removed
  2931. * @param the url of the presentation
  2932. */
  2933. function presentationRemoved(event, jid, presUrl) {
  2934. console.log('presentation removed', presUrl);
  2935. var presId = getPresentationId(presUrl);
  2936. setPresentationVisible(false);
  2937. $('#participant_'
  2938. + Strophe.getResourceFromJid(jid)
  2939. + '_' + presId).remove();
  2940. $('#presentation>iframe').remove();
  2941. if (preziPlayer != null) {
  2942. preziPlayer.destroy();
  2943. preziPlayer = null;
  2944. }
  2945. };
  2946. /**
  2947. * Indicates if the given string is an alphanumeric string.
  2948. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  2949. * purpose of checking URIs.
  2950. */
  2951. function isAlphanumeric(unsafeText) {
  2952. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  2953. return regex.test(unsafeText);
  2954. }
  2955. /**
  2956. * Returns the presentation id from the given url.
  2957. */
  2958. function getPresentationId (presUrl) {
  2959. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  2960. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  2961. }
  2962. /**
  2963. * Returns the presentation width.
  2964. */
  2965. function getPresentationWidth() {
  2966. var availableWidth = UIUtil.getAvailableVideoWidth();
  2967. var availableHeight = getPresentationHeihgt();
  2968. var aspectRatio = 16.0 / 9.0;
  2969. if (availableHeight < availableWidth / aspectRatio) {
  2970. availableWidth = Math.floor(availableHeight * aspectRatio);
  2971. }
  2972. return availableWidth;
  2973. }
  2974. /**
  2975. * Returns the presentation height.
  2976. */
  2977. function getPresentationHeihgt() {
  2978. var remoteVideos = $('#remoteVideos');
  2979. return window.innerHeight - remoteVideos.outerHeight();
  2980. }
  2981. /**
  2982. * Resizes the presentation iframe.
  2983. */
  2984. function resize() {
  2985. if ($('#presentation>iframe')) {
  2986. $('#presentation>iframe').width(getPresentationWidth());
  2987. $('#presentation>iframe').height(getPresentationHeihgt());
  2988. }
  2989. }
  2990. /**
  2991. * Shows/hides a presentation.
  2992. */
  2993. function setPresentationVisible(visible) {
  2994. var prezi = $('#presentation>iframe');
  2995. if (visible) {
  2996. // Trigger the video.selected event to indicate a change in the
  2997. // large video.
  2998. $(document).trigger("video.selected", [true]);
  2999. $('#largeVideo').fadeOut(300);
  3000. prezi.fadeIn(300, function() {
  3001. prezi.css({opacity:'1'});
  3002. ToolbarToggler.dockToolbar(true);
  3003. VideoLayout.setLargeVideoVisible(false);
  3004. });
  3005. $('#activeSpeaker').css('visibility', 'hidden');
  3006. }
  3007. else {
  3008. if (prezi.css('opacity') == '1') {
  3009. prezi.fadeOut(300, function () {
  3010. prezi.css({opacity:'0'});
  3011. $('#reloadPresentation').css({display:'none'});
  3012. $('#largeVideo').fadeIn(300, function() {
  3013. VideoLayout.setLargeVideoVisible(true);
  3014. ToolbarToggler.dockToolbar(false);
  3015. });
  3016. });
  3017. }
  3018. }
  3019. }
  3020. /**
  3021. * Presentation has been removed.
  3022. */
  3023. $(document).bind('presentationremoved.muc', presentationRemoved);
  3024. /**
  3025. * Presentation has been added.
  3026. */
  3027. $(document).bind('presentationadded.muc', presentationAdded);
  3028. /*
  3029. * Indicates presentation slide change.
  3030. */
  3031. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  3032. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  3033. preziPlayer.flyToStep(current);
  3034. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  3035. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  3036. preziPlayer.flyToStep(current, i);
  3037. }
  3038. }
  3039. });
  3040. /**
  3041. * On video selected event.
  3042. */
  3043. $(document).bind('video.selected', function (event, isPresentation) {
  3044. if (!isPresentation && $('#presentation>iframe')) {
  3045. setPresentationVisible(false);
  3046. }
  3047. });
  3048. $(window).resize(function () {
  3049. resize();
  3050. });
  3051. module.exports = Prezi;
  3052. },{"../toolbars/ToolbarToggler":26,"../util/MessageHandler":28,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./PreziPlayer":16}],16:[function(require,module,exports){
  3053. (function() {
  3054. "use strict";
  3055. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  3056. window.PreziPlayer = (function() {
  3057. PreziPlayer.API_VERSION = 1;
  3058. PreziPlayer.CURRENT_STEP = 'currentStep';
  3059. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  3060. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  3061. PreziPlayer.STATUS_LOADING = 'loading';
  3062. PreziPlayer.STATUS_READY = 'ready';
  3063. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  3064. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  3065. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  3066. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  3067. PreziPlayer.EVENT_STATUS = "statusChange";
  3068. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  3069. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  3070. PreziPlayer.domain = "https://prezi.com";
  3071. PreziPlayer.path = "/player/";
  3072. PreziPlayer.players = {};
  3073. PreziPlayer.binded_methods = ['changesHandler'];
  3074. PreziPlayer.createMultiplePlayers = function(optionArray){
  3075. for(var i=0; i<optionArray.length; i++) {
  3076. var optionSet = optionArray[i];
  3077. new PreziPlayer(optionSet.id, optionSet);
  3078. };
  3079. };
  3080. PreziPlayer.messageReceived = function(event){
  3081. var message, item, player;
  3082. try {
  3083. message = JSON.parse(event.data);
  3084. if (message.id && (player = PreziPlayer.players[message.id])) {
  3085. if (player.options.debug === true) {
  3086. if (console && console.log)
  3087. console.log('received', message);
  3088. }
  3089. if (message.type === "changes") {
  3090. player.changesHandler(message);
  3091. }
  3092. for (var i = 0; i < player.callbacks.length; i++) {
  3093. item = player.callbacks[i];
  3094. if (item && message.type === item.event) {
  3095. item.callback(message);
  3096. }
  3097. }
  3098. }
  3099. } catch (e) { }
  3100. };
  3101. function PreziPlayer(id, options) {
  3102. var params, paramString = "", _this = this;
  3103. if (PreziPlayer.players[id]){
  3104. PreziPlayer.players[id].destroy();
  3105. }
  3106. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  3107. var method_name = PreziPlayer.binded_methods[i];
  3108. _this[method_name] = __bind(_this[method_name], _this);
  3109. };
  3110. options = options || {};
  3111. this.options = options;
  3112. this.values = {'status': PreziPlayer.STATUS_LOADING};
  3113. this.values[PreziPlayer.CURRENT_STEP] = 0;
  3114. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  3115. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  3116. this.callbacks = [];
  3117. this.id = id;
  3118. this.embedTo = document.getElementById(id);
  3119. if (!this.embedTo) {
  3120. throw "The element id is not available.";
  3121. }
  3122. this.iframe = document.createElement('iframe');
  3123. params = [
  3124. { name: 'oid', value: options.preziId },
  3125. { name: 'explorable', value: options.explorable ? 1 : 0 },
  3126. { name: 'controls', value: options.controls ? 1 : 0 }
  3127. ];
  3128. for(var i=0; i<params.length; i++) {
  3129. var param = params[i];
  3130. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  3131. };
  3132. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  3133. this.iframe.frameBorder = 0;
  3134. this.iframe.scrolling = "no";
  3135. this.iframe.width = options.width || 640;
  3136. this.iframe.height = options.height || 480;
  3137. this.embedTo.innerHTML = '';
  3138. // JITSI: IN CASE SOMETHING GOES WRONG.
  3139. try {
  3140. this.embedTo.appendChild(this.iframe);
  3141. }
  3142. catch (err) {
  3143. console.log("CATCH ERROR");
  3144. }
  3145. // JITSI: Increase interval from 200 to 500, which fixes prezi
  3146. // crashes for us.
  3147. this.initPollInterval = setInterval(function(){
  3148. _this.sendMessage({'action': 'init'});
  3149. }, 500);
  3150. PreziPlayer.players[id] = this;
  3151. }
  3152. PreziPlayer.prototype.changesHandler = function(message) {
  3153. var key, value, j, item;
  3154. if (this.initPollInterval) {
  3155. clearInterval(this.initPollInterval);
  3156. this.initPollInterval = false;
  3157. }
  3158. for (key in message.data) {
  3159. if (message.data.hasOwnProperty(key)){
  3160. value = message.data[key];
  3161. this.values[key] = value;
  3162. for (j=0; j<this.callbacks.length; j++) {
  3163. item = this.callbacks[j];
  3164. if (item && item.event === key + "Change"){
  3165. item.callback({type: item.event, value: value});
  3166. }
  3167. }
  3168. }
  3169. }
  3170. };
  3171. PreziPlayer.prototype.destroy = function() {
  3172. if (this.initPollInterval) {
  3173. clearInterval(this.initPollInterval);
  3174. this.initPollInterval = false;
  3175. }
  3176. this.embedTo.innerHTML = '';
  3177. };
  3178. PreziPlayer.prototype.sendMessage = function(message) {
  3179. if (this.options.debug === true) {
  3180. if (console && console.log) console.log('sent', message);
  3181. }
  3182. message.version = PreziPlayer.API_VERSION;
  3183. message.id = this.id;
  3184. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  3185. };
  3186. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  3187. PreziPlayer.prototype.flyToNextStep = function() {
  3188. return this.sendMessage({
  3189. 'action': 'present',
  3190. 'data': ['moveToNextStep']
  3191. });
  3192. };
  3193. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  3194. PreziPlayer.prototype.flyToPreviousStep = function() {
  3195. return this.sendMessage({
  3196. 'action': 'present',
  3197. 'data': ['moveToPrevStep']
  3198. });
  3199. };
  3200. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  3201. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  3202. var obj = this;
  3203. // check animation_step
  3204. if (animation_step > 0 &&
  3205. obj.values.animationCountOnSteps &&
  3206. obj.values.animationCountOnSteps[step] <= animation_step) {
  3207. animation_step = obj.values.animationCountOnSteps[step];
  3208. }
  3209. // jump to animation steps by calling flyToNextStep()
  3210. function doAnimationSteps() {
  3211. if (obj.values.isMoving == true) {
  3212. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  3213. return;
  3214. }
  3215. while (animation_step-- > 0) {
  3216. obj.flyToNextStep(); // do the animation steps
  3217. }
  3218. }
  3219. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  3220. // jump to the step
  3221. return this.sendMessage({
  3222. 'action': 'present',
  3223. 'data': ['moveToStep', step]
  3224. });
  3225. };
  3226. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  3227. PreziPlayer.prototype.flyToObject = function(objectId) {
  3228. return this.sendMessage({
  3229. 'action': 'present',
  3230. 'data': ['moveToObject', objectId]
  3231. });
  3232. };
  3233. PreziPlayer.prototype.play = function(defaultDelay) {
  3234. return this.sendMessage({
  3235. 'action': 'present',
  3236. 'data': ['startAutoPlay', defaultDelay]
  3237. });
  3238. };
  3239. PreziPlayer.prototype.stop = function() {
  3240. return this.sendMessage({
  3241. 'action': 'present',
  3242. 'data': ['stopAutoPlay']
  3243. });
  3244. };
  3245. PreziPlayer.prototype.pause = function(defaultDelay) {
  3246. return this.sendMessage({
  3247. 'action': 'present',
  3248. 'data': ['pauseAutoPlay', defaultDelay]
  3249. });
  3250. };
  3251. PreziPlayer.prototype.getCurrentStep = function() {
  3252. return this.values.currentStep;
  3253. };
  3254. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  3255. return this.values.currentAnimationStep;
  3256. };
  3257. PreziPlayer.prototype.getCurrentObject = function() {
  3258. return this.values.currentObject;
  3259. };
  3260. PreziPlayer.prototype.getStatus = function() {
  3261. return this.values.status;
  3262. };
  3263. PreziPlayer.prototype.isPlaying = function() {
  3264. return this.values.isAutoPlaying;
  3265. };
  3266. PreziPlayer.prototype.getStepCount = function() {
  3267. return this.values.stepCount;
  3268. };
  3269. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  3270. return this.values.animationCountOnSteps;
  3271. };
  3272. PreziPlayer.prototype.getTitle = function() {
  3273. return this.values.title;
  3274. };
  3275. PreziPlayer.prototype.setDimensions = function(dims) {
  3276. for (var parameter in dims) {
  3277. this.iframe[parameter] = dims[parameter];
  3278. }
  3279. }
  3280. PreziPlayer.prototype.getDimensions = function() {
  3281. return {
  3282. width: parseInt(this.iframe.width, 10),
  3283. height: parseInt(this.iframe.height, 10)
  3284. }
  3285. }
  3286. PreziPlayer.prototype.on = function(event, callback) {
  3287. this.callbacks.push({
  3288. event: event,
  3289. callback: callback
  3290. });
  3291. };
  3292. PreziPlayer.prototype.off = function(event, callback) {
  3293. var j, item;
  3294. if (event === undefined) {
  3295. this.callbacks = [];
  3296. }
  3297. j = this.callbacks.length;
  3298. while (j--) {
  3299. item = this.callbacks[j];
  3300. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3301. this.callbacks.splice(j, 1);
  3302. }
  3303. }
  3304. };
  3305. if (window.addEventListener) {
  3306. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3307. } else {
  3308. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3309. }
  3310. return PreziPlayer;
  3311. })();
  3312. })();
  3313. module.exports = PreziPlayer;
  3314. },{}],17:[function(require,module,exports){
  3315. var Chat = require("./chat/Chat");
  3316. var ContactList = require("./contactlist/ContactList");
  3317. var Settings = require("./../../settings/Settings");
  3318. var SettingsMenu = require("./settings/SettingsMenu");
  3319. var VideoLayout = require("../videolayout/VideoLayout");
  3320. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3321. var UIUtil = require("../util/UIUtil");
  3322. /**
  3323. * Toggler for the chat, contact list, settings menu, etc..
  3324. */
  3325. var PanelToggler = (function(my) {
  3326. var currentlyOpen = null;
  3327. var buttons = {
  3328. '#chatspace': '#chatBottomButton',
  3329. '#contactlist': '#contactListButton',
  3330. '#settingsmenu': '#settingsButton'
  3331. };
  3332. /**
  3333. * Resizes the video area
  3334. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3335. * @param completeFunction a function to be called when the video space is resized
  3336. */
  3337. var resizeVideoArea = function(isClosing, completeFunction) {
  3338. var videospace = $('#videospace');
  3339. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3340. var videospaceWidth = window.innerWidth - panelSize[0];
  3341. var videospaceHeight = window.innerHeight;
  3342. var videoSize
  3343. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3344. var videoWidth = videoSize[0];
  3345. var videoHeight = videoSize[1];
  3346. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3347. videoHeight,
  3348. videospaceWidth,
  3349. videospaceHeight);
  3350. var horizontalIndent = videoPosition[0];
  3351. var verticalIndent = videoPosition[1];
  3352. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3353. var thumbnailsWidth = thumbnailSize[0];
  3354. var thumbnailsHeight = thumbnailSize[1];
  3355. //for chat
  3356. videospace.animate({
  3357. right: panelSize[0],
  3358. width: videospaceWidth,
  3359. height: videospaceHeight
  3360. },
  3361. {
  3362. queue: false,
  3363. duration: 500,
  3364. complete: completeFunction
  3365. });
  3366. $('#remoteVideos').animate({
  3367. height: thumbnailsHeight
  3368. },
  3369. {
  3370. queue: false,
  3371. duration: 500
  3372. });
  3373. $('#remoteVideos>span').animate({
  3374. height: thumbnailsHeight,
  3375. width: thumbnailsWidth
  3376. },
  3377. {
  3378. queue: false,
  3379. duration: 500,
  3380. complete: function () {
  3381. $(document).trigger(
  3382. "remotevideo.resized",
  3383. [thumbnailsWidth,
  3384. thumbnailsHeight]);
  3385. }
  3386. });
  3387. $('#largeVideoContainer').animate({
  3388. width: videospaceWidth,
  3389. height: videospaceHeight
  3390. },
  3391. {
  3392. queue: false,
  3393. duration: 500
  3394. });
  3395. $('#largeVideo').animate({
  3396. width: videoWidth,
  3397. height: videoHeight,
  3398. top: verticalIndent,
  3399. bottom: verticalIndent,
  3400. left: horizontalIndent,
  3401. right: horizontalIndent
  3402. },
  3403. {
  3404. queue: false,
  3405. duration: 500
  3406. });
  3407. };
  3408. /**
  3409. * Toggles the windows in the side panel
  3410. * @param object the window that should be shown
  3411. * @param selector the selector for the element containing the panel
  3412. * @param onOpenComplete function to be called when the panel is opened
  3413. * @param onOpen function to be called if the window is going to be opened
  3414. * @param onClose function to be called if the window is going to be closed
  3415. */
  3416. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3417. UIUtil.buttonClick(buttons[selector], "active");
  3418. if (object.isVisible()) {
  3419. $("#toast-container").animate({
  3420. right: '5px'
  3421. },
  3422. {
  3423. queue: false,
  3424. duration: 500
  3425. });
  3426. $(selector).hide("slide", {
  3427. direction: "right",
  3428. queue: false,
  3429. duration: 500
  3430. });
  3431. if(typeof onClose === "function") {
  3432. onClose();
  3433. }
  3434. currentlyOpen = null;
  3435. }
  3436. else {
  3437. // Undock the toolbar when the chat is shown and if we're in a
  3438. // video mode.
  3439. if (VideoLayout.isLargeVideoVisible()) {
  3440. ToolbarToggler.dockToolbar(false);
  3441. }
  3442. if(currentlyOpen) {
  3443. var current = $(currentlyOpen);
  3444. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3445. current.css('z-index', 4);
  3446. setTimeout(function () {
  3447. current.css('display', 'none');
  3448. current.css('z-index', 5);
  3449. }, 500);
  3450. }
  3451. $("#toast-container").animate({
  3452. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3453. },
  3454. {
  3455. queue: false,
  3456. duration: 500
  3457. });
  3458. $(selector).show("slide", {
  3459. direction: "right",
  3460. queue: false,
  3461. duration: 500,
  3462. complete: onOpenComplete
  3463. });
  3464. if(typeof onOpen === "function") {
  3465. onOpen();
  3466. }
  3467. currentlyOpen = selector;
  3468. }
  3469. };
  3470. /**
  3471. * Opens / closes the chat area.
  3472. */
  3473. my.toggleChat = function() {
  3474. var chatCompleteFunction = Chat.isVisible() ?
  3475. function() {} : function () {
  3476. Chat.scrollChatToBottom();
  3477. $('#chatspace').trigger('shown');
  3478. };
  3479. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3480. toggle(Chat,
  3481. '#chatspace',
  3482. function () {
  3483. // Request the focus in the nickname field or the chat input field.
  3484. if ($('#nickname').css('visibility') === 'visible') {
  3485. $('#nickinput').focus();
  3486. } else {
  3487. $('#usermsg').focus();
  3488. }
  3489. },
  3490. null,
  3491. Chat.resizeChat,
  3492. null);
  3493. };
  3494. /**
  3495. * Opens / closes the contact list area.
  3496. */
  3497. my.toggleContactList = function () {
  3498. var completeFunction = ContactList.isVisible() ?
  3499. function() {} : function () { $('#contactlist').trigger('shown');};
  3500. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3501. toggle(ContactList,
  3502. '#contactlist',
  3503. null,
  3504. function() {
  3505. ContactList.setVisualNotification(false);
  3506. },
  3507. null);
  3508. };
  3509. /**
  3510. * Opens / closes the settings menu
  3511. */
  3512. my.toggleSettingsMenu = function() {
  3513. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3514. toggle(SettingsMenu,
  3515. '#settingsmenu',
  3516. null,
  3517. function() {
  3518. var settings = Settings.getSettings();
  3519. $('#setDisplayName').get(0).value = settings.displayName;
  3520. $('#setEmail').get(0).value = settings.email;
  3521. },
  3522. null);
  3523. };
  3524. /**
  3525. * Returns the size of the side panel.
  3526. */
  3527. my.getPanelSize = function () {
  3528. var availableHeight = window.innerHeight;
  3529. var availableWidth = window.innerWidth;
  3530. var panelWidth = 200;
  3531. if (availableWidth * 0.2 < 200) {
  3532. panelWidth = availableWidth * 0.2;
  3533. }
  3534. return [panelWidth, availableHeight];
  3535. };
  3536. my.isVisible = function() {
  3537. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3538. };
  3539. return my;
  3540. }(PanelToggler || {}));
  3541. module.exports = PanelToggler;
  3542. },{"../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){
  3543. /* global $, Util, nickname:true */
  3544. var Replacement = require("./Replacement");
  3545. var CommandsProcessor = require("./Commands");
  3546. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3547. var smileys = require("./smileys.json").smileys;
  3548. var NicknameHandler = require("../../util/NicknameHandler");
  3549. var UIUtil = require("../../util/UIUtil");
  3550. var UIEvents = require("../../../../service/UI/UIEvents");
  3551. var notificationInterval = false;
  3552. var unreadMessages = 0;
  3553. /**
  3554. * Shows/hides a visual notification, indicating that a message has arrived.
  3555. */
  3556. function setVisualNotification(show) {
  3557. var unreadMsgElement = document.getElementById('unreadMessages');
  3558. var unreadMsgBottomElement
  3559. = document.getElementById('bottomUnreadMessages');
  3560. var glower = $('#chatButton');
  3561. var bottomGlower = $('#chatBottomButton');
  3562. if (unreadMessages) {
  3563. unreadMsgElement.innerHTML = unreadMessages.toString();
  3564. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3565. ToolbarToggler.dockToolbar(true);
  3566. var chatButtonElement
  3567. = document.getElementById('chatButton').parentNode;
  3568. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3569. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3570. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3571. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3572. unreadMsgElement.setAttribute(
  3573. 'style',
  3574. 'top:' + topIndent +
  3575. '; left:' + leftIndent + ';');
  3576. var chatBottomButtonElement
  3577. = document.getElementById('chatBottomButton').parentNode;
  3578. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3579. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3580. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3581. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3582. unreadMsgBottomElement.setAttribute(
  3583. 'style',
  3584. 'top:' + bottomTopIndent +
  3585. '; left:' + bottomLeftIndent + ';');
  3586. if (!glower.hasClass('icon-chat-simple')) {
  3587. glower.removeClass('icon-chat');
  3588. glower.addClass('icon-chat-simple');
  3589. }
  3590. }
  3591. else {
  3592. unreadMsgElement.innerHTML = '';
  3593. unreadMsgBottomElement.innerHTML = '';
  3594. glower.removeClass('icon-chat-simple');
  3595. glower.addClass('icon-chat');
  3596. }
  3597. if (show && !notificationInterval) {
  3598. notificationInterval = window.setInterval(function () {
  3599. glower.toggleClass('active');
  3600. bottomGlower.toggleClass('active glowing');
  3601. }, 800);
  3602. }
  3603. else if (!show && notificationInterval) {
  3604. window.clearInterval(notificationInterval);
  3605. notificationInterval = false;
  3606. glower.removeClass('active');
  3607. bottomGlower.removeClass('glowing');
  3608. bottomGlower.addClass('active');
  3609. }
  3610. }
  3611. /**
  3612. * Returns the current time in the format it is shown to the user
  3613. * @returns {string}
  3614. */
  3615. function getCurrentTime() {
  3616. var now = new Date();
  3617. var hour = now.getHours();
  3618. var minute = now.getMinutes();
  3619. var second = now.getSeconds();
  3620. if(hour.toString().length === 1) {
  3621. hour = '0'+hour;
  3622. }
  3623. if(minute.toString().length === 1) {
  3624. minute = '0'+minute;
  3625. }
  3626. if(second.toString().length === 1) {
  3627. second = '0'+second;
  3628. }
  3629. return hour+':'+minute+':'+second;
  3630. }
  3631. function toggleSmileys()
  3632. {
  3633. var smileys = $('#smileysContainer');
  3634. if(!smileys.is(':visible')) {
  3635. smileys.show("slide", { direction: "down", duration: 300});
  3636. } else {
  3637. smileys.hide("slide", { direction: "down", duration: 300});
  3638. }
  3639. $('#usermsg').focus();
  3640. }
  3641. function addClickFunction(smiley, number) {
  3642. smiley.onclick = function addSmileyToMessage() {
  3643. var usermsg = $('#usermsg');
  3644. var message = usermsg.val();
  3645. message += smileys['smiley' + number];
  3646. usermsg.val(message);
  3647. usermsg.get(0).setSelectionRange(message.length, message.length);
  3648. toggleSmileys();
  3649. usermsg.focus();
  3650. };
  3651. }
  3652. /**
  3653. * Adds the smileys container to the chat
  3654. */
  3655. function addSmileys() {
  3656. var smileysContainer = document.createElement('div');
  3657. smileysContainer.id = 'smileysContainer';
  3658. for(var i = 1; i <= 21; i++) {
  3659. var smileyContainer = document.createElement('div');
  3660. smileyContainer.id = 'smiley' + i;
  3661. smileyContainer.className = 'smileyContainer';
  3662. var smiley = document.createElement('img');
  3663. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3664. smiley.className = 'smiley';
  3665. addClickFunction(smiley, i);
  3666. smileyContainer.appendChild(smiley);
  3667. smileysContainer.appendChild(smileyContainer);
  3668. }
  3669. $("#chatspace").append(smileysContainer);
  3670. }
  3671. /**
  3672. * Resizes the chat conversation.
  3673. */
  3674. function resizeChatConversation() {
  3675. var msgareaHeight = $('#usermsg').outerHeight();
  3676. var chatspace = $('#chatspace');
  3677. var width = chatspace.width();
  3678. var chat = $('#chatconversation');
  3679. var smileys = $('#smileysarea');
  3680. smileys.height(msgareaHeight);
  3681. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3682. $('#smileysContainer').css('bottom', msgareaHeight);
  3683. chat.width(width - 10);
  3684. chat.height(window.innerHeight - 15 - msgareaHeight);
  3685. }
  3686. /**
  3687. * Chat related user interface.
  3688. */
  3689. var Chat = (function (my) {
  3690. /**
  3691. * Initializes chat related interface.
  3692. */
  3693. my.init = function () {
  3694. if(NicknameHandler.getNickname())
  3695. Chat.setChatConversationMode(true);
  3696. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3697. function (nickname) {
  3698. Chat.setChatConversationMode(true);
  3699. });
  3700. $('#nickinput').keydown(function (event) {
  3701. if (event.keyCode === 13) {
  3702. event.preventDefault();
  3703. var val = UIUtil.escapeHtml(this.value);
  3704. this.value = '';
  3705. if (!NicknameHandler.getNickname()) {
  3706. NicknameHandler.setNickname(val);
  3707. return;
  3708. }
  3709. }
  3710. });
  3711. $('#usermsg').keydown(function (event) {
  3712. if (event.keyCode === 13) {
  3713. event.preventDefault();
  3714. var value = this.value;
  3715. $('#usermsg').val('').trigger('autosize.resize');
  3716. this.focus();
  3717. var command = new CommandsProcessor(value);
  3718. if(command.isCommand())
  3719. {
  3720. command.processCommand();
  3721. }
  3722. else
  3723. {
  3724. var message = UIUtil.escapeHtml(value);
  3725. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3726. }
  3727. }
  3728. });
  3729. var onTextAreaResize = function () {
  3730. resizeChatConversation();
  3731. Chat.scrollChatToBottom();
  3732. };
  3733. $('#usermsg').autosize({callback: onTextAreaResize});
  3734. $("#chatspace").bind("shown",
  3735. function () {
  3736. unreadMessages = 0;
  3737. setVisualNotification(false);
  3738. });
  3739. addSmileys();
  3740. };
  3741. /**
  3742. * Appends the given message to the chat conversation.
  3743. */
  3744. my.updateChatConversation = function (from, displayName, message) {
  3745. var divClassName = '';
  3746. if (APP.xmpp.myJid() === from) {
  3747. divClassName = "localuser";
  3748. }
  3749. else {
  3750. divClassName = "remoteuser";
  3751. if (!Chat.isVisible()) {
  3752. unreadMessages++;
  3753. UIUtil.playSoundNotification('chatNotification');
  3754. setVisualNotification(true);
  3755. }
  3756. }
  3757. // replace links and smileys
  3758. // Strophe already escapes special symbols on sending,
  3759. // so we escape here only tags to avoid double &amp;
  3760. var escMessage = message.replace(/</g, '&lt;').
  3761. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  3762. var escDisplayName = UIUtil.escapeHtml(displayName);
  3763. message = Replacement.processReplacements(escMessage);
  3764. var messageContainer =
  3765. '<div class="chatmessage">'+
  3766. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  3767. '<div class="username ' + divClassName +'">' + escDisplayName +
  3768. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  3769. '</div>' + '<div class="usermessage">' + message + '</div>' +
  3770. '</div>';
  3771. $('#chatconversation').append(messageContainer);
  3772. $('#chatconversation').animate(
  3773. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3774. };
  3775. /**
  3776. * Appends error message to the conversation
  3777. * @param errorMessage the received error message.
  3778. * @param originalText the original message.
  3779. */
  3780. my.chatAddError = function(errorMessage, originalText)
  3781. {
  3782. errorMessage = UIUtil.escapeHtml(errorMessage);
  3783. originalText = UIUtil.escapeHtml(originalText);
  3784. $('#chatconversation').append(
  3785. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  3786. (originalText? (' \"'+ originalText + '\"') : "") +
  3787. ' was not sent.' +
  3788. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  3789. $('#chatconversation').animate(
  3790. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3791. };
  3792. /**
  3793. * Sets the subject to the UI
  3794. * @param subject the subject
  3795. */
  3796. my.chatSetSubject = function(subject)
  3797. {
  3798. if(subject)
  3799. subject = subject.trim();
  3800. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  3801. if(subject === "")
  3802. {
  3803. $("#subject").css({display: "none"});
  3804. }
  3805. else
  3806. {
  3807. $("#subject").css({display: "block"});
  3808. }
  3809. };
  3810. /**
  3811. * Sets the chat conversation mode.
  3812. */
  3813. my.setChatConversationMode = function (isConversationMode) {
  3814. if (isConversationMode) {
  3815. $('#nickname').css({visibility: 'hidden'});
  3816. $('#chatconversation').css({visibility: 'visible'});
  3817. $('#usermsg').css({visibility: 'visible'});
  3818. $('#smileysarea').css({visibility: 'visible'});
  3819. $('#usermsg').focus();
  3820. }
  3821. };
  3822. /**
  3823. * Resizes the chat area.
  3824. */
  3825. my.resizeChat = function () {
  3826. var chatSize = require("../SidePanelToggler").getPanelSize();
  3827. $('#chatspace').width(chatSize[0]);
  3828. $('#chatspace').height(chatSize[1]);
  3829. resizeChatConversation();
  3830. };
  3831. /**
  3832. * Indicates if the chat is currently visible.
  3833. */
  3834. my.isVisible = function () {
  3835. return $('#chatspace').is(":visible");
  3836. };
  3837. /**
  3838. * Shows and hides the window with the smileys
  3839. */
  3840. my.toggleSmileys = toggleSmileys;
  3841. /**
  3842. * Scrolls chat to the bottom.
  3843. */
  3844. my.scrollChatToBottom = function() {
  3845. setTimeout(function () {
  3846. $('#chatconversation').scrollTop(
  3847. $('#chatconversation')[0].scrollHeight);
  3848. }, 5);
  3849. };
  3850. return my;
  3851. }(Chat || {}));
  3852. module.exports = Chat;
  3853. },{"../../../../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){
  3854. var UIUtil = require("../../util/UIUtil");
  3855. /**
  3856. * List with supported commands. The keys are the names of the commands and
  3857. * the value is the function that processes the message.
  3858. * @type {{String: function}}
  3859. */
  3860. var commands = {
  3861. "topic" : processTopic
  3862. };
  3863. /**
  3864. * Extracts the command from the message.
  3865. * @param message the received message
  3866. * @returns {string} the command
  3867. */
  3868. function getCommand(message)
  3869. {
  3870. if(message)
  3871. {
  3872. for(var command in commands)
  3873. {
  3874. if(message.indexOf("/" + command) == 0)
  3875. return command;
  3876. }
  3877. }
  3878. return "";
  3879. };
  3880. /**
  3881. * Processes the data for topic command.
  3882. * @param commandArguments the arguments of the topic command.
  3883. */
  3884. function processTopic(commandArguments)
  3885. {
  3886. var topic = UIUtil.escapeHtml(commandArguments);
  3887. APP.xmpp.setSubject(topic);
  3888. }
  3889. /**
  3890. * Constructs new CommandProccessor instance from a message that
  3891. * handles commands received via chat messages.
  3892. * @param message the message
  3893. * @constructor
  3894. */
  3895. function CommandsProcessor(message)
  3896. {
  3897. var command = getCommand(message);
  3898. /**
  3899. * Returns the name of the command.
  3900. * @returns {String} the command
  3901. */
  3902. this.getCommand = function()
  3903. {
  3904. return command;
  3905. };
  3906. var messageArgument = message.substr(command.length + 2);
  3907. /**
  3908. * Returns the arguments of the command.
  3909. * @returns {string}
  3910. */
  3911. this.getArgument = function()
  3912. {
  3913. return messageArgument;
  3914. };
  3915. }
  3916. /**
  3917. * Checks whether this instance is valid command or not.
  3918. * @returns {boolean}
  3919. */
  3920. CommandsProcessor.prototype.isCommand = function()
  3921. {
  3922. if(this.getCommand())
  3923. return true;
  3924. return false;
  3925. };
  3926. /**
  3927. * Processes the command.
  3928. */
  3929. CommandsProcessor.prototype.processCommand = function()
  3930. {
  3931. if(!this.isCommand())
  3932. return;
  3933. commands[this.getCommand()](this.getArgument());
  3934. };
  3935. module.exports = CommandsProcessor;
  3936. },{"../../util/UIUtil":30}],20:[function(require,module,exports){
  3937. var Smileys = require("./smileys.json");
  3938. /**
  3939. * Processes links and smileys in "body"
  3940. */
  3941. function processReplacements(body)
  3942. {
  3943. //make links clickable
  3944. body = linkify(body);
  3945. //add smileys
  3946. body = smilify(body);
  3947. return body;
  3948. }
  3949. /**
  3950. * Finds and replaces all links in the links in "body"
  3951. * with their <a href=""></a>
  3952. */
  3953. function linkify(inputText)
  3954. {
  3955. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  3956. //URLs starting with http://, https://, or ftp://
  3957. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  3958. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  3959. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  3960. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  3961. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  3962. //Change email addresses to mailto:: links.
  3963. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  3964. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  3965. return replacedText;
  3966. }
  3967. /**
  3968. * Replaces common smiley strings with images
  3969. */
  3970. function smilify(body)
  3971. {
  3972. if(!body) {
  3973. return body;
  3974. }
  3975. var regexs = Smileys["regexs"];
  3976. for(var smiley in regexs) {
  3977. if(regexs.hasOwnProperty(smiley)) {
  3978. body = body.replace(regexs[smiley],
  3979. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  3980. }
  3981. }
  3982. return body;
  3983. }
  3984. module.exports = {
  3985. processReplacements: processReplacements,
  3986. linkify: linkify
  3987. };
  3988. },{"./smileys.json":21}],21:[function(require,module,exports){
  3989. module.exports={
  3990. "smileys": {
  3991. "smiley1": ":)",
  3992. "smiley2": ":(",
  3993. "smiley3": ":D",
  3994. "smiley4": "(y)",
  3995. "smiley5": " :P",
  3996. "smiley6": "(wave)",
  3997. "smiley7": "(blush)",
  3998. "smiley8": "(chuckle)",
  3999. "smiley9": "(shocked)",
  4000. "smiley10": ":*",
  4001. "smiley11": "(n)",
  4002. "smiley12": "(search)",
  4003. "smiley13": " <3",
  4004. "smiley14": "(oops)",
  4005. "smiley15": "(angry)",
  4006. "smiley16": "(angel)",
  4007. "smiley17": "(sick)",
  4008. "smiley18": ";(",
  4009. "smiley19": "(bomb)",
  4010. "smiley20": "(clap)",
  4011. "smiley21": " ;)"
  4012. },
  4013. "regexs": {
  4014. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  4015. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  4016. "smiley1": /(:-\)|:\))/gi,
  4017. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  4018. "smiley5": /(:-P|:P|:-p|:p)/gi,
  4019. "smiley6": /(\(wave\))/gi,
  4020. "smiley7": /(\(blush\))/gi,
  4021. "smiley8": /(\(chuckle\))/gi,
  4022. "smiley9": /(:-0|\(shocked\))/gi,
  4023. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  4024. "smiley11": /(\(n\))/gi,
  4025. "smiley12": /(\(search\))/g,
  4026. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  4027. "smiley14": /(\(oops\))/gi,
  4028. "smiley15": /(\(angry\))/gi,
  4029. "smiley16": /(\(angel\))/gi,
  4030. "smiley17": /(\(sick\))/gi,
  4031. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  4032. "smiley19": /(\(bomb\))/gi,
  4033. "smiley20": /(\(clap\))/gi,
  4034. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  4035. }
  4036. }
  4037. },{}],22:[function(require,module,exports){
  4038. var numberOfContacts = 0;
  4039. var notificationInterval;
  4040. /**
  4041. * Updates the number of participants in the contact list button and sets
  4042. * the glow
  4043. * @param delta indicates whether a new user has joined (1) or someone has
  4044. * left(-1)
  4045. */
  4046. function updateNumberOfParticipants(delta) {
  4047. //when the user is alone we don't show the number of participants
  4048. if(numberOfContacts === 0) {
  4049. $("#numberOfParticipants").text('');
  4050. numberOfContacts += delta;
  4051. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  4052. ContactList.setVisualNotification(true);
  4053. numberOfContacts += delta;
  4054. $("#numberOfParticipants").text(numberOfContacts);
  4055. }
  4056. }
  4057. /**
  4058. * Creates the avatar element.
  4059. *
  4060. * @return the newly created avatar element
  4061. */
  4062. function createAvatar(id) {
  4063. var avatar = document.createElement('img');
  4064. avatar.className = "icon-avatar avatar";
  4065. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  4066. return avatar;
  4067. }
  4068. /**
  4069. * Creates the display name paragraph.
  4070. *
  4071. * @param displayName the display name to set
  4072. */
  4073. function createDisplayNameParagraph(key, displayName) {
  4074. var p = document.createElement('p');
  4075. if(displayName)
  4076. p.innerText = displayName;
  4077. else if(key)
  4078. {
  4079. p.setAttribute("data-i18n",key);
  4080. p.innerText = APP.translation.translateString(key);
  4081. }
  4082. return p;
  4083. }
  4084. function stopGlowing(glower) {
  4085. window.clearInterval(notificationInterval);
  4086. notificationInterval = false;
  4087. glower.removeClass('glowing');
  4088. if (!ContactList.isVisible()) {
  4089. glower.removeClass('active');
  4090. }
  4091. }
  4092. /**
  4093. * Contact list.
  4094. */
  4095. var ContactList = {
  4096. /**
  4097. * Indicates if the chat is currently visible.
  4098. *
  4099. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  4100. * otherwise
  4101. */
  4102. isVisible: function () {
  4103. return $('#contactlist').is(":visible");
  4104. },
  4105. /**
  4106. * Adds a contact for the given peerJid if such doesn't yet exist.
  4107. *
  4108. * @param peerJid the peerJid corresponding to the contact
  4109. * @param id the user's email or userId used to get the user's avatar
  4110. */
  4111. ensureAddContact: function (peerJid, id) {
  4112. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4113. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4114. if (!contact || contact.length <= 0)
  4115. ContactList.addContact(peerJid, id);
  4116. },
  4117. /**
  4118. * Adds a contact for the given peer jid.
  4119. *
  4120. * @param peerJid the jid of the contact to add
  4121. * @param id the email or userId of the user
  4122. */
  4123. addContact: function (peerJid, id) {
  4124. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4125. var contactlist = $('#contactlist>ul');
  4126. var newContact = document.createElement('li');
  4127. newContact.id = resourceJid;
  4128. newContact.className = "clickable";
  4129. newContact.onclick = function (event) {
  4130. if (event.currentTarget.className === "clickable") {
  4131. $(ContactList).trigger('contactclicked', [peerJid]);
  4132. }
  4133. };
  4134. newContact.appendChild(createAvatar(id));
  4135. newContact.appendChild(createDisplayNameParagraph("participant"));
  4136. var clElement = contactlist.get(0);
  4137. if (resourceJid === APP.xmpp.myResource()
  4138. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  4139. clElement.insertBefore(newContact,
  4140. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  4141. }
  4142. else {
  4143. clElement.appendChild(newContact);
  4144. }
  4145. updateNumberOfParticipants(1);
  4146. },
  4147. /**
  4148. * Removes a contact for the given peer jid.
  4149. *
  4150. * @param peerJid the peerJid corresponding to the contact to remove
  4151. */
  4152. removeContact: function (peerJid) {
  4153. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4154. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4155. if (contact && contact.length > 0) {
  4156. var contactlist = $('#contactlist>ul');
  4157. contactlist.get(0).removeChild(contact.get(0));
  4158. updateNumberOfParticipants(-1);
  4159. }
  4160. },
  4161. setVisualNotification: function (show, stopGlowingIn) {
  4162. var glower = $('#contactListButton');
  4163. if (show && !notificationInterval) {
  4164. notificationInterval = window.setInterval(function () {
  4165. glower.toggleClass('active glowing');
  4166. }, 800);
  4167. }
  4168. else if (!show && notificationInterval) {
  4169. stopGlowing(glower);
  4170. }
  4171. if (stopGlowingIn) {
  4172. setTimeout(function () {
  4173. stopGlowing(glower);
  4174. }, stopGlowingIn);
  4175. }
  4176. },
  4177. setClickable: function (resourceJid, isClickable) {
  4178. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4179. if (isClickable) {
  4180. contact.addClass('clickable');
  4181. } else {
  4182. contact.removeClass('clickable');
  4183. }
  4184. },
  4185. onDisplayNameChange: function (peerJid, displayName) {
  4186. if (peerJid === 'localVideoContainer')
  4187. peerJid = APP.xmpp.myJid();
  4188. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4189. var contactName = $('#contactlist #' + resourceJid + '>p');
  4190. if (contactName && displayName && displayName.length > 0)
  4191. contactName.html(displayName);
  4192. }
  4193. };
  4194. module.exports = ContactList;
  4195. },{}],23:[function(require,module,exports){
  4196. var Avatar = require("../../avatar/Avatar");
  4197. var Settings = require("./../../../settings/Settings");
  4198. var UIUtil = require("../../util/UIUtil");
  4199. var languages = require("../../../../service/translation/languages");
  4200. function generateLanguagesSelectBox()
  4201. {
  4202. var currentLang = APP.translation.getCurrentLanguage();
  4203. var html = "<select id=\"languages_selectbox\">";
  4204. var langArray = languages.getLanguages();
  4205. for(var i = 0; i < langArray.length; i++)
  4206. {
  4207. var lang = langArray[i];
  4208. html += "<option ";
  4209. if(lang === currentLang)
  4210. html += "selected ";
  4211. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  4212. html += "</option>";
  4213. }
  4214. return html + "</select>";
  4215. }
  4216. var SettingsMenu = {
  4217. init: function () {
  4218. $("#updateSettings").before(generateLanguagesSelectBox());
  4219. APP.translation.translateElement($("#languages_selectbox"));
  4220. $('#settingsmenu>input').keyup(function(event){
  4221. if(event.keyCode === 13) {//enter
  4222. SettingsMenu.update();
  4223. }
  4224. });
  4225. $("#updateSettings").click(function () {
  4226. SettingsMenu.update();
  4227. });
  4228. },
  4229. update: function() {
  4230. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  4231. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  4232. if(newDisplayName) {
  4233. var displayName = Settings.setDisplayName(newDisplayName);
  4234. APP.xmpp.addToPresence("displayName", displayName, true);
  4235. }
  4236. var language = $("#languages_selectbox").val();
  4237. APP.translation.setLanguage(language);
  4238. Settings.setLanguage(language);
  4239. APP.xmpp.addToPresence("email", newEmail);
  4240. var email = Settings.setEmail(newEmail);
  4241. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  4242. },
  4243. isVisible: function() {
  4244. return $('#settingsmenu').is(':visible');
  4245. },
  4246. setDisplayName: function(newDisplayName) {
  4247. var displayName = Settings.setDisplayName(newDisplayName);
  4248. $('#setDisplayName').get(0).value = displayName;
  4249. },
  4250. onDisplayNameChange: function(peerJid, newDisplayName) {
  4251. if(peerJid === 'localVideoContainer' ||
  4252. peerJid === APP.xmpp.myJid()) {
  4253. this.setDisplayName(newDisplayName);
  4254. }
  4255. }
  4256. };
  4257. module.exports = SettingsMenu;
  4258. },{"../../../../service/translation/languages":96,"../../avatar/Avatar":13,"../../util/UIUtil":30,"./../../../settings/Settings":38}],24:[function(require,module,exports){
  4259. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4260. var buttonHandlers = {
  4261. "bottom_toolbar_contact_list": function () {
  4262. BottomToolbar.toggleContactList();
  4263. },
  4264. "bottom_toolbar_film_strip": function () {
  4265. BottomToolbar.toggleFilmStrip();
  4266. },
  4267. "bottom_toolbar_chat": function () {
  4268. BottomToolbar.toggleChat();
  4269. }
  4270. };
  4271. var BottomToolbar = (function (my) {
  4272. my.init = function () {
  4273. for(var k in buttonHandlers)
  4274. $("#" + k).click(buttonHandlers[k]);
  4275. };
  4276. my.toggleChat = function() {
  4277. PanelToggler.toggleChat();
  4278. };
  4279. my.toggleContactList = function() {
  4280. PanelToggler.toggleContactList();
  4281. };
  4282. my.toggleFilmStrip = function() {
  4283. var filmstrip = $("#remoteVideos");
  4284. filmstrip.toggleClass("hidden");
  4285. };
  4286. $(document).bind("remotevideo.resized", function (event, width, height) {
  4287. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  4288. $('#bottomToolbar').css({bottom: bottom + 'px'});
  4289. });
  4290. return my;
  4291. }(BottomToolbar || {}));
  4292. module.exports = BottomToolbar;
  4293. },{"../side_pannels/SidePanelToggler":17}],25:[function(require,module,exports){
  4294. /* global APP,$, buttonClick, config, lockRoom,
  4295. setSharedKey, Util */
  4296. var messageHandler = require("../util/MessageHandler");
  4297. var BottomToolbar = require("./BottomToolbar");
  4298. var Prezi = require("../prezi/Prezi");
  4299. var Etherpad = require("../etherpad/Etherpad");
  4300. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4301. var Authentication = require("../authentication/Authentication");
  4302. var UIUtil = require("../util/UIUtil");
  4303. var AuthenticationEvents
  4304. = require("../../../service/authentication/AuthenticationEvents");
  4305. var roomUrl = null;
  4306. var sharedKey = '';
  4307. var UI = null;
  4308. var buttonHandlers =
  4309. {
  4310. "toolbar_button_mute": function () {
  4311. return APP.UI.toggleAudio();
  4312. },
  4313. "toolbar_button_camera": function () {
  4314. return APP.UI.toggleVideo();
  4315. },
  4316. /*"toolbar_button_authentication": function () {
  4317. return Toolbar.authenticateClicked();
  4318. },*/
  4319. "toolbar_button_record": function () {
  4320. return toggleRecording();
  4321. },
  4322. "toolbar_button_security": function () {
  4323. return Toolbar.openLockDialog();
  4324. },
  4325. "toolbar_button_link": function () {
  4326. return Toolbar.openLinkDialog();
  4327. },
  4328. "toolbar_button_chat": function () {
  4329. return BottomToolbar.toggleChat();
  4330. },
  4331. "toolbar_button_prezi": function () {
  4332. return Prezi.openPreziDialog();
  4333. },
  4334. "toolbar_button_etherpad": function () {
  4335. return Etherpad.toggleEtherpad(0);
  4336. },
  4337. "toolbar_button_desktopsharing": function () {
  4338. return APP.desktopsharing.toggleScreenSharing();
  4339. },
  4340. "toolbar_button_fullScreen": function()
  4341. {
  4342. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4343. return Toolbar.toggleFullScreen();
  4344. },
  4345. "toolbar_button_sip": function () {
  4346. return callSipButtonClicked();
  4347. },
  4348. "toolbar_button_settings": function () {
  4349. PanelToggler.toggleSettingsMenu();
  4350. },
  4351. "toolbar_button_hangup": function () {
  4352. return hangup();
  4353. },
  4354. "toolbar_button_login": function () {
  4355. Toolbar.authenticateClicked();
  4356. },
  4357. "toolbar_button_logout": function () {
  4358. // Ask for confirmation
  4359. messageHandler.openTwoButtonDialog(
  4360. "dialog.logoutTitle",
  4361. null,
  4362. "dialog.logoutQuestion",
  4363. null,
  4364. false,
  4365. "dialog.Yes",
  4366. function (evt, yes) {
  4367. if (yes) {
  4368. APP.xmpp.logout(function (url) {
  4369. if (url) {
  4370. window.location.href = url;
  4371. } else {
  4372. hangup();
  4373. }
  4374. });
  4375. }
  4376. });
  4377. }
  4378. };
  4379. function hangup() {
  4380. APP.xmpp.disposeConference();
  4381. if(config.enableWelcomePage)
  4382. {
  4383. setTimeout(function()
  4384. {
  4385. window.localStorage.welcomePageDisabled = false;
  4386. window.location.pathname = "/";
  4387. }, 10000);
  4388. }
  4389. var title = APP.translation.generateTranslatonHTML(
  4390. "dialog.sessTerminated");
  4391. var msg = APP.translation.generateTranslatonHTML(
  4392. "dialog.hungUp");
  4393. var button = APP.translation.generateTranslatonHTML(
  4394. "dialog.joinAgain");
  4395. var buttons = [];
  4396. buttons.push({title: button, value: true});
  4397. UI.messageHandler.openDialog(
  4398. title,
  4399. msg,
  4400. true,
  4401. buttons,
  4402. function(event, value, message, formVals)
  4403. {
  4404. window.location.reload();
  4405. return false;
  4406. }
  4407. );
  4408. }
  4409. /**
  4410. * Starts or stops the recording for the conference.
  4411. */
  4412. function toggleRecording() {
  4413. APP.xmpp.toggleRecording(function (callback) {
  4414. var msg = APP.translation.generateTranslatonHTML(
  4415. "dialog.recordingToken");
  4416. var token = APP.translation.translateString("dialog.token");
  4417. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  4418. '<h2>' + msg + '</h2>' +
  4419. '<input name="recordingToken" type="text" ' +
  4420. ' data-i18n="[placeholder]dialog.token" ' +
  4421. 'placeholder="' + token + '" autofocus>',
  4422. false,
  4423. "dialog.Save",
  4424. function (e, v, m, f) {
  4425. if (v) {
  4426. var token = f.recordingToken;
  4427. if (token) {
  4428. callback(UIUtil.escapeHtml(token));
  4429. }
  4430. }
  4431. },
  4432. null,
  4433. function () { },
  4434. ':input:first'
  4435. );
  4436. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4437. }
  4438. /**
  4439. * Locks / unlocks the room.
  4440. */
  4441. function lockRoom(lock) {
  4442. var currentSharedKey = '';
  4443. if (lock)
  4444. currentSharedKey = sharedKey;
  4445. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4446. // password is required
  4447. if (sharedKey)
  4448. {
  4449. console.log('set room password');
  4450. Toolbar.lockLockButton();
  4451. }
  4452. else
  4453. {
  4454. console.log('removed room password');
  4455. Toolbar.unlockLockButton();
  4456. }
  4457. }, function (err) {
  4458. console.warn('setting password failed', err);
  4459. messageHandler.showError("dialog.lockTitle",
  4460. "dialog.lockMessage");
  4461. Toolbar.setSharedKey('');
  4462. }, function () {
  4463. console.warn('room passwords not supported');
  4464. messageHandler.showError("dialog.warning",
  4465. "dialog.passwordNotSupported");
  4466. Toolbar.setSharedKey('');
  4467. });
  4468. };
  4469. /**
  4470. * Invite participants to conference.
  4471. */
  4472. function inviteParticipants() {
  4473. if (roomUrl === null)
  4474. return;
  4475. var sharedKeyText = "";
  4476. if (sharedKey && sharedKey.length > 0) {
  4477. sharedKeyText =
  4478. APP.translation.translateString("email.sharedKey",
  4479. {sharedKey: sharedKey});
  4480. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  4481. }
  4482. var supportedBrowsers = "Chromium, Google Chrome " +
  4483. APP.translation.translateString("email.and") + " Opera";
  4484. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4485. var subject = APP.translation.translateString("email.subject",
  4486. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  4487. var body = APP.translation.translateString("email.body",
  4488. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  4489. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  4490. body = body.replace(/\n/g, "%0D%0A");
  4491. if (window.localStorage.displayname) {
  4492. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4493. }
  4494. if (interfaceConfig.INVITATION_POWERED_BY) {
  4495. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4496. }
  4497. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4498. }
  4499. function callSipButtonClicked()
  4500. {
  4501. var defaultNumber
  4502. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4503. var sipMsg = APP.translation.generateTranslatonHTML(
  4504. "dialog.sipMsg");
  4505. messageHandler.openTwoButtonDialog(null, null, null,
  4506. '<h2>' + sipMsg + '</h2>' +
  4507. '<input name="sipNumber" type="text"' +
  4508. ' value="' + defaultNumber + '" autofocus>',
  4509. false,
  4510. "dialog.Dial",
  4511. function (e, v, m, f) {
  4512. if (v) {
  4513. var numberInput = f.sipNumber;
  4514. if (numberInput) {
  4515. APP.xmpp.dial(
  4516. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  4517. }
  4518. }
  4519. },
  4520. null,
  4521. ':input:first'
  4522. );
  4523. }
  4524. var Toolbar = (function (my) {
  4525. my.init = function (ui) {
  4526. for(var k in buttonHandlers)
  4527. $("#" + k).click(buttonHandlers[k]);
  4528. UI = ui;
  4529. // Update login info
  4530. APP.xmpp.addListener(
  4531. AuthenticationEvents.IDENTITY_UPDATED,
  4532. function (authenticationEnabled, userIdentity) {
  4533. var loggedIn = false;
  4534. if (userIdentity) {
  4535. loggedIn = true;
  4536. }
  4537. Toolbar.showAuthenticateButton(authenticationEnabled);
  4538. if (authenticationEnabled) {
  4539. Toolbar.setAuthenticatedIdentity(userIdentity);
  4540. Toolbar.showLoginButton(!loggedIn);
  4541. Toolbar.showLogoutButton(loggedIn);
  4542. }
  4543. }
  4544. );
  4545. },
  4546. /**
  4547. * Sets shared key
  4548. * @param sKey the shared key
  4549. */
  4550. my.setSharedKey = function (sKey) {
  4551. sharedKey = sKey;
  4552. };
  4553. my.authenticateClicked = function () {
  4554. Authentication.focusAuthenticationWindow();
  4555. if (!APP.xmpp.isExternalAuthEnabled()) {
  4556. Authentication.xmppAuthenticate();
  4557. return;
  4558. }
  4559. // Get authentication URL
  4560. if (!APP.xmpp.getMUCJoined()) {
  4561. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4562. // If conference has not been started yet - redirect to login page
  4563. window.location.href = url;
  4564. });
  4565. } else {
  4566. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4567. // Otherwise - open popup with authentication URL
  4568. var authenticationWindow = Authentication.createAuthenticationWindow(
  4569. function () {
  4570. // On popup closed - retry room allocation
  4571. APP.xmpp.allocateConferenceFocus(
  4572. APP.UI.getRoomName(),
  4573. function () { console.info("AUTH DONE"); }
  4574. );
  4575. }, url);
  4576. if (!authenticationWindow) {
  4577. messageHandler.openMessageDialog(
  4578. null, "dialog.popupError");
  4579. }
  4580. });
  4581. }
  4582. };
  4583. /**
  4584. * Updates the room invite url.
  4585. */
  4586. my.updateRoomUrl = function (newRoomUrl) {
  4587. roomUrl = newRoomUrl;
  4588. // If the invite dialog has been already opened we update the information.
  4589. var inviteLink = document.getElementById('inviteLinkRef');
  4590. if (inviteLink) {
  4591. inviteLink.value = roomUrl;
  4592. inviteLink.select();
  4593. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  4594. }
  4595. };
  4596. /**
  4597. * Disables and enables some of the buttons.
  4598. */
  4599. my.setupButtonsFromConfig = function () {
  4600. if (config.disablePrezi)
  4601. {
  4602. $("#prezi_button").css({display: "none"});
  4603. }
  4604. };
  4605. /**
  4606. * Opens the lock room dialog.
  4607. */
  4608. my.openLockDialog = function () {
  4609. // Only the focus is able to set a shared key.
  4610. if (!APP.xmpp.isModerator()) {
  4611. if (sharedKey) {
  4612. messageHandler.openMessageDialog(null,
  4613. "dialog.passwordError");
  4614. } else {
  4615. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  4616. }
  4617. } else {
  4618. if (sharedKey) {
  4619. messageHandler.openTwoButtonDialog(null, null,
  4620. "dialog.passwordCheck",
  4621. null,
  4622. false,
  4623. "dialog.Remove",
  4624. function (e, v) {
  4625. if (v) {
  4626. Toolbar.setSharedKey('');
  4627. lockRoom(false);
  4628. }
  4629. });
  4630. } else {
  4631. var msg = APP.translation.generateTranslatonHTML(
  4632. "dialog.passwordMsg");
  4633. var yourPassword = APP.translation.translateString(
  4634. "dialog.yourPassword");
  4635. messageHandler.openTwoButtonDialog(null, null, null,
  4636. '<h2>' + msg + '</h2>' +
  4637. '<input name="lockKey" type="text"' +
  4638. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  4639. 'placeholder="' + yourPassword + '" autofocus>',
  4640. false,
  4641. "dialog.Save",
  4642. function (e, v, m, f) {
  4643. if (v) {
  4644. var lockKey = f.lockKey;
  4645. if (lockKey) {
  4646. Toolbar.setSharedKey(
  4647. UIUtil.escapeHtml(lockKey));
  4648. lockRoom(true);
  4649. }
  4650. }
  4651. },
  4652. null, null, 'input:first'
  4653. );
  4654. }
  4655. }
  4656. };
  4657. /**
  4658. * Opens the invite link dialog.
  4659. */
  4660. my.openLinkDialog = function () {
  4661. var inviteAttreibutes;
  4662. if (roomUrl === null) {
  4663. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  4664. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  4665. } else {
  4666. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  4667. }
  4668. messageHandler.openTwoButtonDialog("dialog.shareLink",
  4669. null, null,
  4670. '<input id="inviteLinkRef" type="text" ' +
  4671. inviteAttreibutes + ' onclick="this.select();" readonly>',
  4672. false,
  4673. "dialog.Invite",
  4674. function (e, v) {
  4675. if (v) {
  4676. if (roomUrl) {
  4677. inviteParticipants();
  4678. }
  4679. }
  4680. },
  4681. function () {
  4682. if (roomUrl) {
  4683. document.getElementById('inviteLinkRef').select();
  4684. } else {
  4685. document.getElementById('jqi_state0_buttonInvite')
  4686. .disabled = true;
  4687. }
  4688. }
  4689. );
  4690. };
  4691. /**
  4692. * Opens the settings dialog.
  4693. * FIXME: not used ?
  4694. */
  4695. my.openSettingsDialog = function () {
  4696. var settings1 = APP.translation.generateTranslatonHTML(
  4697. "dialog.settings1");
  4698. var settings2 = APP.translation.generateTranslatonHTML(
  4699. "dialog.settings2");
  4700. var settings3 = APP.translation.generateTranslatonHTML(
  4701. "dialog.settings3");
  4702. var yourPassword = APP.translation.translateString(
  4703. "dialog.yourPassword");
  4704. messageHandler.openTwoButtonDialog(null,
  4705. '<h2>' + settings1 + '</h2>' +
  4706. '<input type="checkbox" id="initMuted">' +
  4707. settings2 + '<br/>' +
  4708. '<input type="checkbox" id="requireNicknames">' +
  4709. settings3 +
  4710. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  4711. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  4712. null,
  4713. null,
  4714. false,
  4715. "dialog.Save",
  4716. function () {
  4717. document.getElementById('lockKey').focus();
  4718. },
  4719. function (e, v) {
  4720. if (v) {
  4721. if ($('#initMuted').is(":checked")) {
  4722. // it is checked
  4723. }
  4724. if ($('#requireNicknames').is(":checked")) {
  4725. // it is checked
  4726. }
  4727. /*
  4728. var lockKey = document.getElementById('lockKey');
  4729. if (lockKey.value) {
  4730. setSharedKey(lockKey.value);
  4731. lockRoom(true);
  4732. }
  4733. */
  4734. }
  4735. }
  4736. );
  4737. };
  4738. /**
  4739. * Toggles the application in and out of full screen mode
  4740. * (a.k.a. presentation mode in Chrome).
  4741. */
  4742. my.toggleFullScreen = function () {
  4743. var fsElement = document.documentElement;
  4744. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  4745. //Enter Full Screen
  4746. if (fsElement.mozRequestFullScreen) {
  4747. fsElement.mozRequestFullScreen();
  4748. }
  4749. else {
  4750. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  4751. }
  4752. } else {
  4753. //Exit Full Screen
  4754. if (document.mozCancelFullScreen) {
  4755. document.mozCancelFullScreen();
  4756. } else {
  4757. document.webkitCancelFullScreen();
  4758. }
  4759. }
  4760. };
  4761. /**
  4762. * Unlocks the lock button state.
  4763. */
  4764. my.unlockLockButton = function () {
  4765. if ($("#lockIcon").hasClass("icon-security-locked"))
  4766. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4767. };
  4768. /**
  4769. * Updates the lock button state to locked.
  4770. */
  4771. my.lockLockButton = function () {
  4772. if ($("#lockIcon").hasClass("icon-security"))
  4773. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4774. };
  4775. /**
  4776. * Shows or hides authentication button
  4777. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  4778. */
  4779. my.showAuthenticateButton = function (show) {
  4780. if (show) {
  4781. $('#authentication').css({display: "inline"});
  4782. }
  4783. else {
  4784. $('#authentication').css({display: "none"});
  4785. }
  4786. };
  4787. // Shows or hides the 'recording' button.
  4788. my.showRecordingButton = function (show) {
  4789. if (!config.enableRecording) {
  4790. return;
  4791. }
  4792. if (show) {
  4793. $('#recording').css({display: "inline"});
  4794. }
  4795. else {
  4796. $('#recording').css({display: "none"});
  4797. }
  4798. };
  4799. // Sets the state of the recording button
  4800. my.setRecordingButtonState = function (isRecording) {
  4801. if (isRecording) {
  4802. $('#recordButton').removeClass("icon-recEnable");
  4803. $('#recordButton').addClass("icon-recEnable active");
  4804. } else {
  4805. $('#recordButton').removeClass("icon-recEnable active");
  4806. $('#recordButton').addClass("icon-recEnable");
  4807. }
  4808. };
  4809. // Shows or hides SIP calls button
  4810. my.showSipCallButton = function (show) {
  4811. if (APP.xmpp.isSipGatewayEnabled() && show) {
  4812. $('#sipCallButton').css({display: "inline-block"});
  4813. } else {
  4814. $('#sipCallButton').css({display: "none"});
  4815. }
  4816. };
  4817. /**
  4818. * Displays user authenticated identity name(login).
  4819. * @param authIdentity identity name to be displayed.
  4820. */
  4821. my.setAuthenticatedIdentity = function (authIdentity) {
  4822. if (authIdentity) {
  4823. $('#toolbar_auth_identity').css({display: "list-item"});
  4824. $('#toolbar_auth_identity').text(authIdentity);
  4825. } else {
  4826. $('#toolbar_auth_identity').css({display: "none"});
  4827. }
  4828. };
  4829. /**
  4830. * Shows/hides login button.
  4831. * @param show <tt>true</tt> to show
  4832. */
  4833. my.showLoginButton = function (show) {
  4834. if (show) {
  4835. $('#toolbar_button_login').css({display: "list-item"});
  4836. } else {
  4837. $('#toolbar_button_login').css({display: "none"});
  4838. }
  4839. };
  4840. /**
  4841. * Shows/hides logout button.
  4842. * @param show <tt>true</tt> to show
  4843. */
  4844. my.showLogoutButton = function (show) {
  4845. if (show) {
  4846. $('#toolbar_button_logout').css({display: "list-item"});
  4847. } else {
  4848. $('#toolbar_button_logout').css({display: "none"});
  4849. }
  4850. };
  4851. /**
  4852. * Sets the state of the button. The button has blue glow if desktop
  4853. * streaming is active.
  4854. * @param active the state of the desktop streaming.
  4855. */
  4856. my.changeDesktopSharingButtonState = function (active) {
  4857. var button = $("#desktopsharing > a");
  4858. if (active)
  4859. {
  4860. button.addClass("glow");
  4861. }
  4862. else
  4863. {
  4864. button.removeClass("glow");
  4865. }
  4866. };
  4867. return my;
  4868. }(Toolbar || {}));
  4869. module.exports = Toolbar;
  4870. },{"../../../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){
  4871. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  4872. var toolbarTimeoutObject,
  4873. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  4874. function showDesktopSharingButton() {
  4875. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  4876. $('#desktopsharing').css({display: "inline"});
  4877. } else {
  4878. $('#desktopsharing').css({display: "none"});
  4879. }
  4880. }
  4881. /**
  4882. * Hides the toolbar.
  4883. */
  4884. function hideToolbar() {
  4885. var header = $("#header"),
  4886. bottomToolbar = $("#bottomToolbar");
  4887. var isToolbarHover = false;
  4888. header.find('*').each(function () {
  4889. var id = $(this).attr('id');
  4890. if ($("#" + id + ":hover").length > 0) {
  4891. isToolbarHover = true;
  4892. }
  4893. });
  4894. if ($("#bottomToolbar:hover").length > 0) {
  4895. isToolbarHover = true;
  4896. }
  4897. clearTimeout(toolbarTimeoutObject);
  4898. toolbarTimeoutObject = null;
  4899. if (!isToolbarHover) {
  4900. header.hide("slide", { direction: "up", duration: 300});
  4901. $('#subject').animate({top: "-=40"}, 300);
  4902. if ($("#remoteVideos").hasClass("hidden")) {
  4903. bottomToolbar.hide(
  4904. "slide", {direction: "right", duration: 300});
  4905. }
  4906. }
  4907. else {
  4908. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4909. }
  4910. }
  4911. var ToolbarToggler = {
  4912. /**
  4913. * Shows the main toolbar.
  4914. */
  4915. showToolbar: function () {
  4916. var header = $("#header"),
  4917. bottomToolbar = $("#bottomToolbar");
  4918. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  4919. header.show("slide", { direction: "up", duration: 300});
  4920. $('#subject').animate({top: "+=40"}, 300);
  4921. if (!bottomToolbar.is(":visible")) {
  4922. bottomToolbar.show(
  4923. "slide", {direction: "right", duration: 300});
  4924. }
  4925. if (toolbarTimeoutObject) {
  4926. clearTimeout(toolbarTimeoutObject);
  4927. toolbarTimeoutObject = null;
  4928. }
  4929. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4930. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  4931. }
  4932. if (APP.xmpp.isModerator())
  4933. {
  4934. // TODO: Enable settings functionality.
  4935. // Need to uncomment the settings button in index.html.
  4936. // $('#settingsButton').css({visibility:"visible"});
  4937. }
  4938. // Show/hide desktop sharing button
  4939. showDesktopSharingButton();
  4940. },
  4941. /**
  4942. * Docks/undocks the toolbar.
  4943. *
  4944. * @param isDock indicates what operation to perform
  4945. */
  4946. dockToolbar: function (isDock) {
  4947. if (isDock) {
  4948. // First make sure the toolbar is shown.
  4949. if (!$('#header').is(':visible')) {
  4950. this.showToolbar();
  4951. }
  4952. // Then clear the time out, to dock the toolbar.
  4953. if (toolbarTimeoutObject) {
  4954. clearTimeout(toolbarTimeoutObject);
  4955. toolbarTimeoutObject = null;
  4956. }
  4957. }
  4958. else {
  4959. if (!$('#header').is(':visible')) {
  4960. this.showToolbar();
  4961. }
  4962. else {
  4963. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4964. }
  4965. }
  4966. },
  4967. showDesktopSharingButton: showDesktopSharingButton
  4968. };
  4969. module.exports = ToolbarToggler;
  4970. },{}],27:[function(require,module,exports){
  4971. var JitsiPopover = (function () {
  4972. /**
  4973. * Constructs new JitsiPopover and attaches it to the element
  4974. * @param element jquery selector
  4975. * @param options the options for the popover.
  4976. * @constructor
  4977. */
  4978. function JitsiPopover(element, options)
  4979. {
  4980. this.options = {
  4981. skin: "white",
  4982. content: ""
  4983. };
  4984. if(options)
  4985. {
  4986. if(options.skin)
  4987. this.options.skin = options.skin;
  4988. if(options.content)
  4989. this.options.content = options.content;
  4990. }
  4991. this.elementIsHovered = false;
  4992. this.popoverIsHovered = false;
  4993. this.popoverShown = false;
  4994. element.data("jitsi_popover", this);
  4995. this.element = element;
  4996. this.template = ' <div class="jitsipopover ' + this.options.skin +
  4997. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  4998. '<div class="jitsiPopupmenuPadding"></div></div>';
  4999. var self = this;
  5000. this.element.on("mouseenter", function () {
  5001. self.elementIsHovered = true;
  5002. self.show();
  5003. }).on("mouseleave", function () {
  5004. self.elementIsHovered = false;
  5005. setTimeout(function () {
  5006. self.hide();
  5007. }, 10);
  5008. });
  5009. }
  5010. /**
  5011. * Shows the popover
  5012. */
  5013. JitsiPopover.prototype.show = function () {
  5014. this.createPopover();
  5015. this.popoverShown = true;
  5016. };
  5017. /**
  5018. * Hides the popover
  5019. */
  5020. JitsiPopover.prototype.hide = function () {
  5021. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  5022. {
  5023. this.forceHide();
  5024. }
  5025. };
  5026. /**
  5027. * Hides the popover
  5028. */
  5029. JitsiPopover.prototype.forceHide = function () {
  5030. $(".jitsipopover").remove();
  5031. this.popoverShown = false;
  5032. };
  5033. /**
  5034. * Creates the popover html
  5035. */
  5036. JitsiPopover.prototype.createPopover = function () {
  5037. $("body").append(this.template);
  5038. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  5039. var self = this;
  5040. $(".jitsipopover").on("mouseenter", function () {
  5041. self.popoverIsHovered = true;
  5042. }).on("mouseleave", function () {
  5043. self.popoverIsHovered = false;
  5044. self.hide();
  5045. });
  5046. this.refreshPosition();
  5047. };
  5048. /**
  5049. * Refreshes the position of the popover
  5050. */
  5051. JitsiPopover.prototype.refreshPosition = function () {
  5052. $(".jitsipopover").position({
  5053. my: "bottom",
  5054. at: "top",
  5055. collision: "fit",
  5056. of: this.element,
  5057. using: function (position, elements) {
  5058. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  5059. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  5060. $(".jitsipopover > .arrow").css({left: calcLeft});
  5061. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  5062. }
  5063. });
  5064. };
  5065. /**
  5066. * Updates the content of popover.
  5067. * @param content new content
  5068. */
  5069. JitsiPopover.prototype.updateContent = function (content) {
  5070. this.options.content = content;
  5071. if(!this.popoverShown)
  5072. return;
  5073. $(".jitsipopover").remove();
  5074. this.createPopover();
  5075. };
  5076. return JitsiPopover;
  5077. })();
  5078. module.exports = JitsiPopover;
  5079. },{}],28:[function(require,module,exports){
  5080. /* global $, APP, jQuery, toastr */
  5081. var messageHandler = (function(my) {
  5082. /**
  5083. * Shows a message to the user.
  5084. *
  5085. * @param titleString the title of the message
  5086. * @param messageString the text of the message
  5087. */
  5088. my.openMessageDialog = function(titleKey, messageKey) {
  5089. var title = null;
  5090. if(titleKey)
  5091. {
  5092. title = APP.translation.generateTranslatonHTML(titleKey);
  5093. }
  5094. var message = APP.translation.generateTranslatonHTML(messageKey);
  5095. $.prompt(message,
  5096. {
  5097. title: title,
  5098. persistent: false
  5099. }
  5100. );
  5101. };
  5102. /**
  5103. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5104. *
  5105. * @param titleString the title of the message
  5106. * @param msgString the text of the message
  5107. * @param persistent boolean value which determines whether the message is persistent or not
  5108. * @param leftButton the fist button's text
  5109. * @param submitFunction function to be called on submit
  5110. * @param loadedFunction function to be called after the prompt is fully loaded
  5111. * @param closeFunction function to be called after the prompt is closed
  5112. * @param focus optional focus selector or button index to be focused after
  5113. * the dialog is opened
  5114. * @param defaultButton index of default button which will be activated when
  5115. * the user press 'enter'. Indexed from 0.
  5116. */
  5117. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  5118. persistent, leftButtonKey, submitFunction, loadedFunction,
  5119. closeFunction, focus, defaultButton)
  5120. {
  5121. var buttons = [];
  5122. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  5123. buttons.push({ title: leftButton, value: true});
  5124. var cancelButton
  5125. = APP.translation.generateTranslatonHTML("dialog.Cancel");
  5126. buttons.push({title: cancelButton, value: false});
  5127. var message = msgString, title = titleString;
  5128. if (titleKey)
  5129. {
  5130. title = APP.translation.generateTranslatonHTML(titleKey);
  5131. }
  5132. if (msgKey) {
  5133. message = APP.translation.generateTranslatonHTML(msgKey);
  5134. }
  5135. $.prompt(message, {
  5136. title: title,
  5137. persistent: false,
  5138. buttons: buttons,
  5139. defaultButton: defaultButton,
  5140. focus: focus,
  5141. loaded: loadedFunction,
  5142. submit: submitFunction,
  5143. close: closeFunction
  5144. });
  5145. };
  5146. /**
  5147. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5148. *
  5149. * @param titleString the title of the message
  5150. * @param msgString the text of the message
  5151. * @param persistent boolean value which determines whether the message is persistent or not
  5152. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  5153. * that will be passed to submitFunction
  5154. * @param submitFunction function to be called on submit
  5155. * @param loadedFunction function to be called after the prompt is fully loaded
  5156. */
  5157. my.openDialog = function (titleString, msgString, persistent, buttons,
  5158. submitFunction, loadedFunction) {
  5159. var args = {
  5160. title: titleString,
  5161. persistent: persistent,
  5162. buttons: buttons,
  5163. defaultButton: 1,
  5164. loaded: loadedFunction,
  5165. submit: submitFunction
  5166. };
  5167. if (persistent) {
  5168. args.closeText = '';
  5169. }
  5170. return new Impromptu(msgString, args);
  5171. };
  5172. /**
  5173. * Closes currently opened dialog.
  5174. */
  5175. my.closeDialog = function () {
  5176. $.prompt.close();
  5177. };
  5178. /**
  5179. * Shows a dialog with different states to the user.
  5180. *
  5181. * @param statesObject object containing all the states of the dialog
  5182. */
  5183. my.openDialogWithStates = function (statesObject, options) {
  5184. return new Impromptu(statesObject, options);
  5185. };
  5186. /**
  5187. * Opens new popup window for given <tt>url</tt> centered over current
  5188. * window.
  5189. *
  5190. * @param url the URL to be displayed in the popup window
  5191. * @param w the width of the popup window
  5192. * @param h the height of the popup window
  5193. * @param onPopupClosed optional callback function called when popup window
  5194. * has been closed.
  5195. *
  5196. * @returns popup window object if opened successfully or undefined
  5197. * in case we failed to open it(popup blocked)
  5198. */
  5199. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  5200. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  5201. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  5202. var popup = window.open(
  5203. url, '_blank',
  5204. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  5205. if (popup && onPopupClosed) {
  5206. var pollTimer = window.setInterval(function () {
  5207. if (popup.closed !== false) {
  5208. window.clearInterval(pollTimer);
  5209. onPopupClosed();
  5210. }
  5211. }, 200);
  5212. }
  5213. return popup;
  5214. };
  5215. /**
  5216. * Shows a dialog prompting the user to send an error report.
  5217. *
  5218. * @param titleString the title of the message
  5219. * @param msgString the text of the message
  5220. * @param error the error that is being reported
  5221. */
  5222. my.openReportDialog = function(titleKey, msgKey, error) {
  5223. my.openMessageDialog(titleKey, msgKey);
  5224. console.log(error);
  5225. //FIXME send the error to the server
  5226. };
  5227. /**
  5228. * Shows an error dialog to the user.
  5229. * @param title the title of the message
  5230. * @param message the text of the messafe
  5231. */
  5232. my.showError = function(titleKey, msgKey) {
  5233. if(!titleKey) {
  5234. titleKey = "dialog.oops";
  5235. }
  5236. if(!msgKey)
  5237. {
  5238. msgKey = "dialog.defaultError";
  5239. }
  5240. messageHandler.openMessageDialog(titleKey, msgKey);
  5241. };
  5242. my.notify = function(displayName, displayNameKey,
  5243. cls, messageKey, messageArguments) {
  5244. var displayNameSpan = '<span class="nickname" ';
  5245. if(displayName)
  5246. {
  5247. displayNameSpan += ">" + displayName;
  5248. }
  5249. else
  5250. {
  5251. displayNameSpan += "data-i18n='" + displayNameKey +
  5252. "'>" + APP.translation.translateString(displayNameKey);
  5253. }
  5254. displayNameSpan += "</span>";
  5255. toastr.info(
  5256. displayNameSpan + '<br>' +
  5257. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  5258. (messageArguments?
  5259. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  5260. : "") + ">" +
  5261. APP.translation.translateString(messageKey,
  5262. messageArguments) +
  5263. '</span>');
  5264. };
  5265. return my;
  5266. }(messageHandler || {}));
  5267. module.exports = messageHandler;
  5268. },{}],29:[function(require,module,exports){
  5269. var UIEvents = require("../../../service/UI/UIEvents");
  5270. var nickname = null;
  5271. var eventEmitter = null;
  5272. var NickanameHandler = {
  5273. init: function (emitter) {
  5274. eventEmitter = emitter;
  5275. var storedDisplayName = window.localStorage.displayname;
  5276. if (storedDisplayName) {
  5277. nickname = storedDisplayName;
  5278. }
  5279. },
  5280. setNickname: function (newNickname) {
  5281. if (!newNickname || nickname === newNickname)
  5282. return;
  5283. nickname = newNickname;
  5284. window.localStorage.displayname = nickname;
  5285. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  5286. },
  5287. getNickname: function () {
  5288. return nickname;
  5289. },
  5290. addListener: function (type, listener) {
  5291. eventEmitter.on(type, listener);
  5292. }
  5293. };
  5294. module.exports = NickanameHandler;
  5295. },{"../../../service/UI/UIEvents":92}],30:[function(require,module,exports){
  5296. /**
  5297. * Created by hristo on 12/22/14.
  5298. */
  5299. module.exports = {
  5300. /**
  5301. * Returns the available video width.
  5302. */
  5303. getAvailableVideoWidth: function () {
  5304. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5305. var rightPanelWidth
  5306. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5307. return window.innerWidth - rightPanelWidth;
  5308. },
  5309. /**
  5310. * Changes the style class of the element given by id.
  5311. */
  5312. buttonClick: function(id, classname) {
  5313. $(id).toggleClass(classname); // add the class to the clicked element
  5314. },
  5315. /**
  5316. * Returns the text width for the given element.
  5317. *
  5318. * @param el the element
  5319. */
  5320. getTextWidth: function (el) {
  5321. return (el.clientWidth + 1);
  5322. },
  5323. /**
  5324. * Returns the text height for the given element.
  5325. *
  5326. * @param el the element
  5327. */
  5328. getTextHeight: function (el) {
  5329. return (el.clientHeight + 1);
  5330. },
  5331. /**
  5332. * Plays the sound given by id.
  5333. *
  5334. * @param id the identifier of the audio element.
  5335. */
  5336. playSoundNotification: function (id) {
  5337. document.getElementById(id).play();
  5338. },
  5339. /**
  5340. * Escapes the given text.
  5341. */
  5342. escapeHtml: function (unsafeText) {
  5343. return $('<div/>').text(unsafeText).html();
  5344. },
  5345. imageToGrayScale: function (canvas) {
  5346. var context = canvas.getContext('2d');
  5347. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5348. var pixels = imgData.data;
  5349. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5350. var grayscale
  5351. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5352. pixels[i ] = grayscale; // red
  5353. pixels[i+1] = grayscale; // green
  5354. pixels[i+2] = grayscale; // blue
  5355. // pixels[i+3] is alpha
  5356. }
  5357. // redraw the image in black & white
  5358. context.putImageData(imgData, 0, 0);
  5359. },
  5360. setTooltip: function (element, key, position) {
  5361. element.setAttribute("data-i18n", "[data-content]" + key);
  5362. element.setAttribute("data-toggle", "popover");
  5363. element.setAttribute("data-placement", position);
  5364. element.setAttribute("data-html", true);
  5365. element.setAttribute("data-container", "body");
  5366. }
  5367. };
  5368. },{"../side_pannels/SidePanelToggler":17}],31:[function(require,module,exports){
  5369. var JitsiPopover = require("../util/JitsiPopover");
  5370. /**
  5371. * Constructs new connection indicator.
  5372. * @param videoContainer the video container associated with the indicator.
  5373. * @constructor
  5374. */
  5375. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5376. {
  5377. this.videoContainer = videoContainer;
  5378. this.bandwidth = null;
  5379. this.packetLoss = null;
  5380. this.bitrate = null;
  5381. this.showMoreValue = false;
  5382. this.resolution = null;
  5383. this.transport = [];
  5384. this.popover = null;
  5385. this.jid = jid;
  5386. this.create();
  5387. this.videoLayout = VideoLayout;
  5388. }
  5389. /**
  5390. * Values for the connection quality
  5391. * @type {{98: string,
  5392. * 81: string,
  5393. * 64: string,
  5394. * 47: string,
  5395. * 30: string,
  5396. * 0: string}}
  5397. */
  5398. ConnectionIndicator.connectionQualityValues = {
  5399. 98: "18px", //full
  5400. 81: "15px",//4 bars
  5401. 64: "11px",//3 bars
  5402. 47: "7px",//2 bars
  5403. 30: "3px",//1 bar
  5404. 0: "0px"//empty
  5405. };
  5406. ConnectionIndicator.getIP = function(value)
  5407. {
  5408. return value.substring(0, value.lastIndexOf(":"));
  5409. };
  5410. ConnectionIndicator.getPort = function(value)
  5411. {
  5412. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5413. };
  5414. ConnectionIndicator.getStringFromArray = function (array) {
  5415. var res = "";
  5416. for(var i = 0; i < array.length; i++)
  5417. {
  5418. res += (i === 0? "" : ", ") + array[i];
  5419. }
  5420. return res;
  5421. };
  5422. /**
  5423. * Generates the html content.
  5424. * @returns {string} the html content.
  5425. */
  5426. ConnectionIndicator.prototype.generateText = function () {
  5427. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5428. var translate = APP.translation.translateString;
  5429. if(this.bitrate === null)
  5430. {
  5431. downloadBitrate = "N/A";
  5432. uploadBitrate = "N/A";
  5433. }
  5434. else
  5435. {
  5436. downloadBitrate =
  5437. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5438. uploadBitrate =
  5439. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5440. }
  5441. if(this.packetLoss === null)
  5442. {
  5443. packetLoss = "N/A";
  5444. }
  5445. else
  5446. {
  5447. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5448. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5449. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5450. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5451. }
  5452. var resolutionValue = null;
  5453. if(this.resolution && this.jid != null)
  5454. {
  5455. var keys = Object.keys(this.resolution);
  5456. if(keys.length == 1)
  5457. {
  5458. for(var ssrc in this.resolution)
  5459. {
  5460. resolutionValue = this.resolution[ssrc];
  5461. }
  5462. }
  5463. else if(keys.length > 1)
  5464. {
  5465. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  5466. resolutionValue = this.resolution[displayedSsrc];
  5467. }
  5468. }
  5469. if(this.jid === null)
  5470. {
  5471. resolution = "";
  5472. if(this.resolution === null || !Object.keys(this.resolution) ||
  5473. Object.keys(this.resolution).length === 0)
  5474. {
  5475. resolution = "N/A";
  5476. }
  5477. else
  5478. for(i in this.resolution)
  5479. {
  5480. resolutionValue = this.resolution[i];
  5481. if(resolutionValue)
  5482. {
  5483. if(resolutionValue.height &&
  5484. resolutionValue.width)
  5485. {
  5486. resolution += (resolution === ""? "" : ", ") +
  5487. resolutionValue.width + "x" +
  5488. resolutionValue.height;
  5489. }
  5490. }
  5491. }
  5492. }
  5493. else if(!resolutionValue ||
  5494. !resolutionValue.height ||
  5495. !resolutionValue.width)
  5496. {
  5497. resolution = "N/A";
  5498. }
  5499. else
  5500. {
  5501. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5502. }
  5503. var result = "<table style='width:100%'>" +
  5504. "<tr>" +
  5505. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5506. translate("connectionindicator.bitrate") + "</span></td>" +
  5507. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5508. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5509. uploadBitrate + "</td>" +
  5510. "</tr><tr>" +
  5511. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5512. translate("connectionindicator.packetloss") + "</span></td>" +
  5513. "<td>" + packetLoss + "</td>" +
  5514. "</tr><tr>" +
  5515. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5516. translate("connectionindicator.resolution") + "</span></td>" +
  5517. "<td>" + resolution + "</td></tr></table>";
  5518. if(this.videoContainer.id == "localVideoContainer") {
  5519. result += "<div class=\"jitsipopover_showmore\" " +
  5520. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5521. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5522. (this.showMoreValue ? "less" : "more") + "'>" +
  5523. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5524. "</div><br />";
  5525. }
  5526. if(this.showMoreValue)
  5527. {
  5528. var downloadBandwidth, uploadBandwidth, transport;
  5529. if(this.bandwidth === null)
  5530. {
  5531. downloadBandwidth = "N/A";
  5532. uploadBandwidth = "N/A";
  5533. }
  5534. else
  5535. {
  5536. downloadBandwidth = this.bandwidth.download?
  5537. this.bandwidth.download + " Kbps" :
  5538. "N/A";
  5539. uploadBandwidth = this.bandwidth.upload?
  5540. this.bandwidth.upload + " Kbps" :
  5541. "N/A";
  5542. }
  5543. if(!this.transport || this.transport.length === 0)
  5544. {
  5545. transport = "<tr>" +
  5546. "<td><span class='jitsipopover_blue' " +
  5547. "data-i18n='connectionindicator.address'>" +
  5548. translate("connectionindicator.address") + "</span></td>" +
  5549. "<td> N/A</td></tr>";
  5550. }
  5551. else
  5552. {
  5553. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5554. for(i = 0; i < this.transport.length; i++)
  5555. {
  5556. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5557. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5558. var localIP =
  5559. ConnectionIndicator.getIP(this.transport[i].localip);
  5560. var localPort =
  5561. ConnectionIndicator.getPort(this.transport[i].localip);
  5562. if(data.remoteIP.indexOf(ip) == -1)
  5563. {
  5564. data.remoteIP.push(ip);
  5565. }
  5566. if(data.remotePort.indexOf(port) == -1)
  5567. {
  5568. data.remotePort.push(port);
  5569. }
  5570. if(data.localIP.indexOf(localIP) == -1)
  5571. {
  5572. data.localIP.push(localIP);
  5573. }
  5574. if(data.localPort.indexOf(localPort) == -1)
  5575. {
  5576. data.localPort.push(localPort);
  5577. }
  5578. }
  5579. var local_address_key = "connectionindicator.localaddress";
  5580. var remote_address_key = "connectionindicator.remoteaddress";
  5581. var localTransport =
  5582. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5583. local_address_key +"' data-i18n-options='" +
  5584. JSON.stringify({count: data.localIP.length}) + "'>" +
  5585. translate(local_address_key, {count: data.localIP.length}) +
  5586. "</span></td><td> " +
  5587. ConnectionIndicator.getStringFromArray(data.localIP) +
  5588. "</td></tr>";
  5589. transport =
  5590. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5591. remote_address_key + "' data-i18n-options='" +
  5592. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  5593. translate(remote_address_key,
  5594. {count: data.remoteIP.length}) +
  5595. "</span></td><td> " +
  5596. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5597. "</td></tr>";
  5598. var key_remote = "connectionindicator.remoteport",
  5599. key_local = "connectionindicator.localport";
  5600. transport += "<tr>" +
  5601. "<td>" +
  5602. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5603. "' data-i18n-options='" +
  5604. JSON.stringify({count: this.transport.length}) + "'>" +
  5605. translate(key_remote, {count: this.transport.length}) +
  5606. "</span></td><td>";
  5607. localTransport += "<tr>" +
  5608. "<td>" +
  5609. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5610. "' data-i18n-options='" +
  5611. JSON.stringify({count: this.transport.length}) + "'>" +
  5612. translate(key_local, {count: this.transport.length}) +
  5613. "</span></td><td>";
  5614. transport +=
  5615. ConnectionIndicator.getStringFromArray(data.remotePort);
  5616. localTransport +=
  5617. ConnectionIndicator.getStringFromArray(data.localPort);
  5618. transport += "</td></tr>";
  5619. transport += localTransport + "</td></tr>";
  5620. transport +="<tr>" +
  5621. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5622. translate("connectionindicator.transport") + "</span></td>" +
  5623. "<td>" + this.transport[0].type + "</td></tr>";
  5624. }
  5625. result += "<table style='width:100%'>" +
  5626. "<tr>" +
  5627. "<td>" +
  5628. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5629. translate("connectionindicator.bandwidth") + "</span>" +
  5630. "</td><td>" +
  5631. "<span class='jitsipopover_green'>&darr;</span>" +
  5632. downloadBandwidth +
  5633. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5634. uploadBandwidth + "</td></tr>";
  5635. result += transport + "</table>";
  5636. }
  5637. return result;
  5638. };
  5639. /**
  5640. * Shows or hide the additional information.
  5641. */
  5642. ConnectionIndicator.prototype.showMore = function () {
  5643. this.showMoreValue = !this.showMoreValue;
  5644. this.updatePopoverData();
  5645. };
  5646. function createIcon(classes)
  5647. {
  5648. var icon = document.createElement("span");
  5649. for(var i in classes)
  5650. {
  5651. icon.classList.add(classes[i]);
  5652. }
  5653. icon.appendChild(
  5654. document.createElement("i")).classList.add("icon-connection");
  5655. return icon;
  5656. }
  5657. /**
  5658. * Creates the indicator
  5659. */
  5660. ConnectionIndicator.prototype.create = function () {
  5661. this.connectionIndicatorContainer = document.createElement("div");
  5662. this.connectionIndicatorContainer.className = "connectionindicator";
  5663. this.connectionIndicatorContainer.style.display = "none";
  5664. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5665. this.popover = new JitsiPopover(
  5666. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5667. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5668. APP.translation.translateString("connectionindicator.na") + "</div>",
  5669. skin: "black"});
  5670. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5671. createIcon(["connection", "connection_empty"]));
  5672. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5673. createIcon(["connection", "connection_full"]));
  5674. };
  5675. /**
  5676. * Removes the indicator
  5677. */
  5678. ConnectionIndicator.prototype.remove = function()
  5679. {
  5680. this.connectionIndicatorContainer.remove();
  5681. this.popover.forceHide();
  5682. };
  5683. /**
  5684. * Updates the data of the indicator
  5685. * @param percent the percent of connection quality
  5686. * @param object the statistics data.
  5687. */
  5688. ConnectionIndicator.prototype.updateConnectionQuality =
  5689. function (percent, object) {
  5690. if(percent === null)
  5691. {
  5692. this.connectionIndicatorContainer.style.display = "none";
  5693. this.popover.forceHide();
  5694. return;
  5695. }
  5696. else
  5697. {
  5698. if(this.connectionIndicatorContainer.style.display == "none") {
  5699. this.connectionIndicatorContainer.style.display = "block";
  5700. this.videoLayout.updateMutePosition(this.videoContainer.id);
  5701. }
  5702. }
  5703. this.bandwidth = object.bandwidth;
  5704. this.bitrate = object.bitrate;
  5705. this.packetLoss = object.packetLoss;
  5706. this.transport = object.transport;
  5707. if(object.resolution)
  5708. {
  5709. this.resolution = object.resolution;
  5710. }
  5711. for(var quality in ConnectionIndicator.connectionQualityValues)
  5712. {
  5713. if(percent >= quality)
  5714. {
  5715. this.fullIcon.style.width =
  5716. ConnectionIndicator.connectionQualityValues[quality];
  5717. }
  5718. }
  5719. this.updatePopoverData();
  5720. };
  5721. /**
  5722. * Updates the resolution
  5723. * @param resolution the new resolution
  5724. */
  5725. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  5726. this.resolution = resolution;
  5727. this.updatePopoverData();
  5728. };
  5729. /**
  5730. * Updates the content of the popover
  5731. */
  5732. ConnectionIndicator.prototype.updatePopoverData = function () {
  5733. this.popover.updateContent(
  5734. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  5735. APP.translation.translateElement($(".connection_info"));
  5736. };
  5737. /**
  5738. * Hides the popover
  5739. */
  5740. ConnectionIndicator.prototype.hide = function () {
  5741. this.popover.forceHide();
  5742. };
  5743. /**
  5744. * Hides the indicator
  5745. */
  5746. ConnectionIndicator.prototype.hideIndicator = function () {
  5747. this.connectionIndicatorContainer.style.display = "none";
  5748. if(this.popover)
  5749. this.popover.forceHide();
  5750. };
  5751. module.exports = ConnectionIndicator;
  5752. },{"../util/JitsiPopover":27}],32:[function(require,module,exports){
  5753. var AudioLevels = require("../audio_levels/AudioLevels");
  5754. var Avatar = require("../avatar/Avatar");
  5755. var Chat = require("../side_pannels/chat/Chat");
  5756. var ContactList = require("../side_pannels/contactlist/ContactList");
  5757. var UIUtil = require("../util/UIUtil");
  5758. var ConnectionIndicator = require("./ConnectionIndicator");
  5759. var NicknameHandler = require("../util/NicknameHandler");
  5760. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  5761. var UIEvents = require("../../../service/UI/UIEvents");
  5762. var currentDominantSpeaker = null;
  5763. var lastNCount = config.channelLastN;
  5764. var localLastNCount = config.channelLastN;
  5765. var localLastNSet = [];
  5766. var lastNEndpointsCache = [];
  5767. var lastNPickupJid = null;
  5768. var largeVideoState = {
  5769. updateInProgress: false,
  5770. newSrc: ''
  5771. };
  5772. var eventEmitter = null;
  5773. /**
  5774. * Currently focused video "src"(displayed in large video).
  5775. * @type {String}
  5776. */
  5777. var focusedVideoInfo = null;
  5778. /**
  5779. * Indicates if we have muted our audio before the conference has started.
  5780. * @type {boolean}
  5781. */
  5782. var preMuted = false;
  5783. var mutedAudios = {};
  5784. var flipXLocalVideo = true;
  5785. var currentVideoWidth = null;
  5786. var currentVideoHeight = null;
  5787. var localVideoSrc = null;
  5788. function videoactive( videoelem) {
  5789. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  5790. // ignore mixedmslabela0 and v0
  5791. videoelem.show();
  5792. VideoLayout.resizeThumbnails();
  5793. var videoParent = videoelem.parent();
  5794. var parentResourceJid = null;
  5795. if (videoParent)
  5796. parentResourceJid
  5797. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  5798. // Update the large video to the last added video only if there's no
  5799. // current dominant, focused speaker or prezi playing or update it to
  5800. // the current dominant speaker.
  5801. if ((!focusedVideoInfo &&
  5802. !VideoLayout.getDominantSpeakerResourceJid() &&
  5803. !require("../prezi/Prezi").isPresentationVisible()) ||
  5804. (parentResourceJid &&
  5805. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  5806. VideoLayout.updateLargeVideo(
  5807. APP.RTC.getVideoSrc(videoelem[0]),
  5808. 1,
  5809. parentResourceJid);
  5810. }
  5811. VideoLayout.showModeratorIndicator();
  5812. }
  5813. }
  5814. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  5815. // XXX(gp) so, every call to this function is *always* preceded by a call
  5816. // to the RTC.attachMediaStream() function but that call is *not* followed
  5817. // by an update to the videoSrcToSsrc map!
  5818. //
  5819. // The above way of doing things results in video SRCs that don't correspond
  5820. // to any SSRC for a short period of time (to be more precise, for as long
  5821. // the waitForRemoteVideo takes to complete). This causes problems (see
  5822. // bellow).
  5823. //
  5824. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  5825. // a second time in here and only then update the videoSrcToSsrc map? Why
  5826. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  5827. // is called the first time? I actually do that in the lastN changed event
  5828. // handler because the "orphan" video SRC is causing troubles there. The
  5829. // purpose of this method would then be to fire the "videoactive.jingle".
  5830. //
  5831. // Food for though I guess :-)
  5832. if (selector.removed || !selector.parent().is(":visible")) {
  5833. console.warn("Media removed before had started", selector);
  5834. return;
  5835. }
  5836. if (stream.id === 'mixedmslabel') return;
  5837. if (selector[0].currentTime > 0) {
  5838. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  5839. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  5840. videoactive(selector);
  5841. } else {
  5842. setTimeout(function () {
  5843. waitForRemoteVideo(selector, ssrc, stream, jid);
  5844. }, 250);
  5845. }
  5846. }
  5847. /**
  5848. * Returns an array of the video horizontal and vertical indents,
  5849. * so that if fits its parent.
  5850. *
  5851. * @return an array with 2 elements, the horizontal indent and the vertical
  5852. * indent
  5853. */
  5854. function getCameraVideoPosition(videoWidth,
  5855. videoHeight,
  5856. videoSpaceWidth,
  5857. videoSpaceHeight) {
  5858. // Parent height isn't completely calculated when we position the video in
  5859. // full screen mode and this is why we use the screen height in this case.
  5860. // Need to think it further at some point and implement it properly.
  5861. var isFullScreen = document.fullScreen ||
  5862. document.mozFullScreen ||
  5863. document.webkitIsFullScreen;
  5864. if (isFullScreen)
  5865. videoSpaceHeight = window.innerHeight;
  5866. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5867. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  5868. return [horizontalIndent, verticalIndent];
  5869. }
  5870. /**
  5871. * Returns an array of the video horizontal and vertical indents.
  5872. * Centers horizontally and top aligns vertically.
  5873. *
  5874. * @return an array with 2 elements, the horizontal indent and the vertical
  5875. * indent
  5876. */
  5877. function getDesktopVideoPosition(videoWidth,
  5878. videoHeight,
  5879. videoSpaceWidth,
  5880. videoSpaceHeight) {
  5881. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5882. var verticalIndent = 0;// Top aligned
  5883. return [horizontalIndent, verticalIndent];
  5884. }
  5885. /**
  5886. * Returns an array of the video dimensions, so that it covers the screen.
  5887. * It leaves no empty areas, but some parts of the video might not be visible.
  5888. *
  5889. * @return an array with 2 elements, the video width and the video height
  5890. */
  5891. function getCameraVideoSize(videoWidth,
  5892. videoHeight,
  5893. videoSpaceWidth,
  5894. videoSpaceHeight) {
  5895. if (!videoWidth)
  5896. videoWidth = currentVideoWidth;
  5897. if (!videoHeight)
  5898. videoHeight = currentVideoHeight;
  5899. var aspectRatio = videoWidth / videoHeight;
  5900. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5901. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5902. if (availableWidth / aspectRatio < videoSpaceHeight) {
  5903. availableHeight = videoSpaceHeight;
  5904. availableWidth = availableHeight * aspectRatio;
  5905. }
  5906. if (availableHeight * aspectRatio < videoSpaceWidth) {
  5907. availableWidth = videoSpaceWidth;
  5908. availableHeight = availableWidth / aspectRatio;
  5909. }
  5910. return [availableWidth, availableHeight];
  5911. }
  5912. /**
  5913. * Sets the display name for the given video span id.
  5914. */
  5915. function setDisplayName(videoSpanId, displayName, key) {
  5916. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  5917. var defaultLocalDisplayName = APP.translation.generateTranslatonHTML(
  5918. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  5919. // If we already have a display name for this video.
  5920. if (nameSpan.length > 0) {
  5921. var nameSpanElement = nameSpan.get(0);
  5922. if (nameSpanElement.id === 'localDisplayName' &&
  5923. $('#localDisplayName').text() !== displayName) {
  5924. if (displayName && displayName.length > 0)
  5925. {
  5926. var meHTML = APP.translation.generateTranslatonHTML("me");
  5927. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  5928. }
  5929. else
  5930. $('#localDisplayName').html(defaultLocalDisplayName);
  5931. } else {
  5932. if (displayName && displayName.length > 0)
  5933. {
  5934. $('#' + videoSpanId + '_name').html(displayName);
  5935. }
  5936. else if (key && key.length > 0)
  5937. {
  5938. var nameHtml = APP.translation.generateTranslatonHTML(key);
  5939. $('#' + videoSpanId + '_name').html(nameHtml);
  5940. }
  5941. else
  5942. $('#' + videoSpanId + '_name').text(
  5943. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  5944. }
  5945. } else {
  5946. var editButton = null;
  5947. nameSpan = document.createElement('span');
  5948. nameSpan.className = 'displayname';
  5949. $('#' + videoSpanId)[0].appendChild(nameSpan);
  5950. if (videoSpanId === 'localVideoContainer') {
  5951. editButton = createEditDisplayNameButton();
  5952. if (displayName && displayName.length > 0) {
  5953. var meHTML = APP.translation.generateTranslatonHTML("me");
  5954. nameSpan.innerHTML = displayName + meHTML;
  5955. }
  5956. else
  5957. nameSpan.innerHTML = defaultLocalDisplayName;
  5958. }
  5959. else {
  5960. if (displayName && displayName.length > 0) {
  5961. nameSpan.innerText = displayName;
  5962. }
  5963. else
  5964. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  5965. }
  5966. if (!editButton) {
  5967. nameSpan.id = videoSpanId + '_name';
  5968. } else {
  5969. nameSpan.id = 'localDisplayName';
  5970. $('#' + videoSpanId)[0].appendChild(editButton);
  5971. //translates popover of edit button
  5972. APP.translation.translateElement($("a.displayname"));
  5973. var editableText = document.createElement('input');
  5974. editableText.className = 'displayname';
  5975. editableText.type = 'text';
  5976. editableText.id = 'editDisplayName';
  5977. if (displayName && displayName.length) {
  5978. editableText.value
  5979. = displayName;
  5980. }
  5981. var defaultNickname = APP.translation.translateString(
  5982. "defaultNickname", {name: "Jane Pink"});
  5983. editableText.setAttribute('style', 'display:none;');
  5984. editableText.setAttribute('data-18n',
  5985. '[placeholder]defaultNickname');
  5986. editableText.setAttribute("data-i18n-options",
  5987. JSON.stringify({name: "Jane Pink"}));
  5988. editableText.setAttribute("placeholder", defaultNickname);
  5989. $('#' + videoSpanId)[0].appendChild(editableText);
  5990. $('#localVideoContainer .displayname')
  5991. .bind("click", function (e) {
  5992. e.preventDefault();
  5993. e.stopPropagation();
  5994. $('#localDisplayName').hide();
  5995. $('#editDisplayName').show();
  5996. $('#editDisplayName').focus();
  5997. $('#editDisplayName').select();
  5998. $('#editDisplayName').one("focusout", function (e) {
  5999. VideoLayout.inputDisplayNameHandler(this.value);
  6000. });
  6001. $('#editDisplayName').on('keydown', function (e) {
  6002. if (e.keyCode === 13) {
  6003. e.preventDefault();
  6004. VideoLayout.inputDisplayNameHandler(this.value);
  6005. }
  6006. });
  6007. });
  6008. }
  6009. }
  6010. }
  6011. /**
  6012. * Gets the selector of video thumbnail container for the user identified by
  6013. * given <tt>userJid</tt>
  6014. * @param resourceJid user's Jid for whom we want to get the video container.
  6015. */
  6016. function getParticipantContainer(resourceJid)
  6017. {
  6018. if (!resourceJid)
  6019. return null;
  6020. if (resourceJid === APP.xmpp.myResource())
  6021. return $("#localVideoContainer");
  6022. else
  6023. return $("#participant_" + resourceJid);
  6024. }
  6025. /**
  6026. * Sets the size and position of the given video element.
  6027. *
  6028. * @param video the video element to position
  6029. * @param width the desired video width
  6030. * @param height the desired video height
  6031. * @param horizontalIndent the left and right indent
  6032. * @param verticalIndent the top and bottom indent
  6033. */
  6034. function positionVideo(video,
  6035. width,
  6036. height,
  6037. horizontalIndent,
  6038. verticalIndent) {
  6039. video.width(width);
  6040. video.height(height);
  6041. video.css({ top: verticalIndent + 'px',
  6042. bottom: verticalIndent + 'px',
  6043. left: horizontalIndent + 'px',
  6044. right: horizontalIndent + 'px'});
  6045. }
  6046. /**
  6047. * Adds the remote video menu element for the given <tt>jid</tt> in the
  6048. * given <tt>parentElement</tt>.
  6049. *
  6050. * @param jid the jid indicating the video for which we're adding a menu.
  6051. * @param parentElement the parent element where this menu will be added
  6052. */
  6053. function addRemoteVideoMenu(jid, parentElement) {
  6054. var spanElement = document.createElement('span');
  6055. spanElement.className = 'remotevideomenu';
  6056. parentElement.appendChild(spanElement);
  6057. var menuElement = document.createElement('i');
  6058. menuElement.className = 'fa fa-angle-down';
  6059. menuElement.title = 'Remote user controls';
  6060. spanElement.appendChild(menuElement);
  6061. // <ul class="popupmenu">
  6062. // <li><a href="#">Mute</a></li>
  6063. // <li><a href="#">Eject</a></li>
  6064. // </ul>
  6065. var popupmenuElement = document.createElement('ul');
  6066. popupmenuElement.className = 'popupmenu';
  6067. popupmenuElement.id
  6068. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  6069. spanElement.appendChild(popupmenuElement);
  6070. var muteMenuItem = document.createElement('li');
  6071. var muteLinkItem = document.createElement('a');
  6072. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  6073. if (!mutedAudios[jid]) {
  6074. muteLinkItem.innerHTML = mutedIndicator +
  6075. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6076. muteLinkItem.className = 'mutelink';
  6077. }
  6078. else {
  6079. muteLinkItem.innerHTML = mutedIndicator +
  6080. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6081. muteLinkItem.className = 'mutelink disabled';
  6082. }
  6083. muteLinkItem.onclick = function(){
  6084. if ($(this).attr('disabled') != undefined) {
  6085. event.preventDefault();
  6086. }
  6087. var isMute = mutedAudios[jid] == true;
  6088. APP.xmpp.setMute(jid, !isMute);
  6089. popupmenuElement.setAttribute('style', 'display:none;');
  6090. if (isMute) {
  6091. this.innerHTML = mutedIndicator +
  6092. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6093. this.className = 'mutelink disabled';
  6094. }
  6095. else {
  6096. this.innerHTML = mutedIndicator +
  6097. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6098. this.className = 'mutelink';
  6099. }
  6100. };
  6101. muteMenuItem.appendChild(muteLinkItem);
  6102. popupmenuElement.appendChild(muteMenuItem);
  6103. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  6104. var ejectMenuItem = document.createElement('li');
  6105. var ejectLinkItem = document.createElement('a');
  6106. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  6107. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  6108. ejectLinkItem.onclick = function(){
  6109. APP.xmpp.eject(jid);
  6110. popupmenuElement.setAttribute('style', 'display:none;');
  6111. };
  6112. ejectMenuItem.appendChild(ejectLinkItem);
  6113. popupmenuElement.appendChild(ejectMenuItem);
  6114. var paddingSpan = document.createElement('span');
  6115. paddingSpan.className = 'popupmenuPadding';
  6116. popupmenuElement.appendChild(paddingSpan);
  6117. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  6118. }
  6119. /**
  6120. * Removes remote video menu element from video element identified by
  6121. * given <tt>videoElementId</tt>.
  6122. *
  6123. * @param videoElementId the id of local or remote video element.
  6124. */
  6125. function removeRemoteVideoMenu(videoElementId) {
  6126. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  6127. if (menuSpan.length) {
  6128. menuSpan.remove();
  6129. }
  6130. }
  6131. /**
  6132. * Updates the data for the indicator
  6133. * @param id the id of the indicator
  6134. * @param percent the percent for connection quality
  6135. * @param object the data
  6136. */
  6137. function updateStatsIndicator(id, percent, object) {
  6138. if(VideoLayout.connectionIndicators[id])
  6139. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  6140. }
  6141. /**
  6142. * Returns an array of the video dimensions, so that it keeps it's aspect
  6143. * ratio and fits available area with it's larger dimension. This method
  6144. * ensures that whole video will be visible and can leave empty areas.
  6145. *
  6146. * @return an array with 2 elements, the video width and the video height
  6147. */
  6148. function getDesktopVideoSize(videoWidth,
  6149. videoHeight,
  6150. videoSpaceWidth,
  6151. videoSpaceHeight) {
  6152. if (!videoWidth)
  6153. videoWidth = currentVideoWidth;
  6154. if (!videoHeight)
  6155. videoHeight = currentVideoHeight;
  6156. var aspectRatio = videoWidth / videoHeight;
  6157. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6158. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6159. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  6160. if (availableWidth / aspectRatio >= videoSpaceHeight)
  6161. {
  6162. availableHeight = videoSpaceHeight;
  6163. availableWidth = availableHeight * aspectRatio;
  6164. }
  6165. if (availableHeight * aspectRatio >= videoSpaceWidth)
  6166. {
  6167. availableWidth = videoSpaceWidth;
  6168. availableHeight = availableWidth / aspectRatio;
  6169. }
  6170. return [availableWidth, availableHeight];
  6171. }
  6172. /**
  6173. * Creates the edit display name button.
  6174. *
  6175. * @returns the edit button
  6176. */
  6177. function createEditDisplayNameButton() {
  6178. var editButton = document.createElement('a');
  6179. editButton.className = 'displayname';
  6180. UIUtil.setTooltip(editButton,
  6181. "videothumbnail.editnickname",
  6182. "top");
  6183. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  6184. return editButton;
  6185. }
  6186. /**
  6187. * Creates the element indicating the moderator(owner) of the conference.
  6188. *
  6189. * @param parentElement the parent element where the owner indicator will
  6190. * be added
  6191. */
  6192. function createModeratorIndicatorElement(parentElement) {
  6193. var moderatorIndicator = document.createElement('i');
  6194. moderatorIndicator.className = 'fa fa-star';
  6195. parentElement.appendChild(moderatorIndicator);
  6196. UIUtil.setTooltip(parentElement,
  6197. "videothumbnail.moderator",
  6198. "top");
  6199. }
  6200. var VideoLayout = (function (my) {
  6201. my.connectionIndicators = {};
  6202. // By default we use camera
  6203. my.getVideoSize = getCameraVideoSize;
  6204. my.getVideoPosition = getCameraVideoPosition;
  6205. my.init = function (emitter) {
  6206. // Listen for large video size updates
  6207. document.getElementById('largeVideo')
  6208. .addEventListener('loadedmetadata', function (e) {
  6209. currentVideoWidth = this.videoWidth;
  6210. currentVideoHeight = this.videoHeight;
  6211. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6212. });
  6213. eventEmitter = emitter;
  6214. };
  6215. my.isInLastN = function(resource) {
  6216. return lastNCount < 0 // lastN is disabled, return true
  6217. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  6218. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  6219. };
  6220. my.changeLocalStream = function (stream) {
  6221. VideoLayout.changeLocalVideo(stream);
  6222. };
  6223. my.changeLocalAudio = function(stream) {
  6224. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  6225. document.getElementById('localAudio').autoplay = true;
  6226. document.getElementById('localAudio').volume = 0;
  6227. if (preMuted) {
  6228. if(!APP.UI.setAudioMuted(true))
  6229. {
  6230. preMuted = mute;
  6231. }
  6232. preMuted = false;
  6233. }
  6234. };
  6235. my.changeLocalVideo = function(stream) {
  6236. var flipX = true;
  6237. if(stream.videoType == "screen")
  6238. flipX = false;
  6239. var localVideo = document.createElement('video');
  6240. localVideo.id = 'localVideo_' +
  6241. APP.RTC.getStreamID(stream.getOriginalStream());
  6242. localVideo.autoplay = true;
  6243. localVideo.volume = 0; // is it required if audio is separated ?
  6244. localVideo.oncontextmenu = function () { return false; };
  6245. var localVideoContainer = document.getElementById('localVideoWrapper');
  6246. localVideoContainer.appendChild(localVideo);
  6247. // Set default display name.
  6248. setDisplayName('localVideoContainer');
  6249. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  6250. VideoLayout.connectionIndicators["localVideoContainer"]
  6251. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  6252. }
  6253. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  6254. var localVideoSelector = $('#' + localVideo.id);
  6255. function localVideoClick(event) {
  6256. event.stopPropagation();
  6257. VideoLayout.handleVideoThumbClicked(
  6258. APP.RTC.getVideoSrc(localVideo),
  6259. false,
  6260. APP.xmpp.myResource());
  6261. }
  6262. // Add click handler to both video and video wrapper elements in case
  6263. // there's no video.
  6264. localVideoSelector.click(localVideoClick);
  6265. $('#localVideoContainer').click(localVideoClick);
  6266. // Add hover handler
  6267. $('#localVideoContainer').hover(
  6268. function() {
  6269. VideoLayout.showDisplayName('localVideoContainer', true);
  6270. },
  6271. function() {
  6272. if (!VideoLayout.isLargeVideoVisible()
  6273. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6274. VideoLayout.showDisplayName('localVideoContainer', false);
  6275. }
  6276. );
  6277. // Add stream ended handler
  6278. stream.getOriginalStream().onended = function () {
  6279. localVideoContainer.removeChild(localVideo);
  6280. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  6281. };
  6282. // Flip video x axis if needed
  6283. flipXLocalVideo = flipX;
  6284. if (flipX) {
  6285. localVideoSelector.addClass("flipVideoX");
  6286. }
  6287. // Attach WebRTC stream
  6288. var videoStream = APP.simulcast.getLocalVideoStream();
  6289. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  6290. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  6291. var myResourceJid = APP.xmpp.myResource();
  6292. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  6293. myResourceJid);
  6294. };
  6295. /**
  6296. * Checks if removed video is currently displayed and tries to display
  6297. * another one instead.
  6298. * @param removedVideoSrc src stream identifier of the video.
  6299. */
  6300. my.updateRemovedVideo = function(removedVideoSrc) {
  6301. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  6302. // this is currently displayed as large
  6303. // pick the last visible video in the row
  6304. // if nobody else is left, this picks the local video
  6305. var pick
  6306. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  6307. .get(0);
  6308. if (!pick) {
  6309. console.info("Last visible video no longer exists");
  6310. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  6311. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  6312. // Try local video
  6313. console.info("Fallback to local video...");
  6314. pick = $('#remoteVideos>span>span>video').get(0);
  6315. }
  6316. }
  6317. // mute if localvideo
  6318. if (pick) {
  6319. var container = pick.parentNode;
  6320. var jid = null;
  6321. if(container)
  6322. {
  6323. if(container.id == "localVideoWrapper")
  6324. {
  6325. jid = APP.xmpp.myResource();
  6326. }
  6327. else
  6328. {
  6329. jid = VideoLayout.getPeerContainerResourceJid(container);
  6330. }
  6331. }
  6332. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(pick), pick.volume, jid);
  6333. } else {
  6334. console.warn("Failed to elect large video");
  6335. }
  6336. }
  6337. };
  6338. my.onRemoteStreamAdded = function (stream) {
  6339. var container;
  6340. var remotes = document.getElementById('remoteVideos');
  6341. if (stream.peerjid) {
  6342. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6343. container = document.getElementById(
  6344. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6345. } else {
  6346. var id = stream.getOriginalStream().id;
  6347. if (id !== 'mixedmslabel'
  6348. // FIXME: default stream is added always with new focus
  6349. // (to be investigated)
  6350. && id !== 'default') {
  6351. console.error('can not associate stream',
  6352. id,
  6353. 'with a participant');
  6354. // We don't want to add it here since it will cause troubles
  6355. return;
  6356. }
  6357. // FIXME: for the mixed ms we dont need a video -- currently
  6358. container = document.createElement('span');
  6359. container.id = 'mixedstream';
  6360. container.className = 'videocontainer';
  6361. remotes.appendChild(container);
  6362. UIUtil.playSoundNotification('userJoined');
  6363. }
  6364. if (container) {
  6365. VideoLayout.addRemoteStreamElement( container,
  6366. stream.sid,
  6367. stream.getOriginalStream(),
  6368. stream.peerjid,
  6369. stream.ssrc);
  6370. }
  6371. }
  6372. my.getLargeVideoState = function () {
  6373. return largeVideoState;
  6374. };
  6375. /**
  6376. * Updates the large video with the given new video source.
  6377. */
  6378. my.updateLargeVideo = function(newSrc, vol, resourceJid) {
  6379. console.log('hover in', newSrc);
  6380. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc) {
  6381. $('#activeSpeaker').css('visibility', 'hidden');
  6382. // Due to the simulcast the localVideoSrc may have changed when the
  6383. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6384. // isVideoSrcDesktop methods will not function correctly.
  6385. //
  6386. // Also, again due to the simulcast, the updateLargeVideo method can
  6387. // be called multiple times almost simultaneously. Therefore, we
  6388. // store the state here and update only once.
  6389. largeVideoState.newSrc = newSrc;
  6390. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6391. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(
  6392. APP.xmpp.findJidFromResource(resourceJid));
  6393. if(largeVideoState.userResourceJid) {
  6394. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6395. } else {
  6396. largeVideoState.oldResourceJid = null;
  6397. }
  6398. largeVideoState.userResourceJid = resourceJid;
  6399. // Screen stream is already rotated
  6400. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6401. var userChanged = false;
  6402. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6403. userChanged = true;
  6404. // we want the notification to trigger even if userJid is undefined,
  6405. // or null.
  6406. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6407. largeVideoState.userResourceJid);
  6408. }
  6409. if (!largeVideoState.updateInProgress) {
  6410. largeVideoState.updateInProgress = true;
  6411. var doUpdate = function () {
  6412. Avatar.updateActiveSpeakerAvatarSrc(
  6413. APP.xmpp.findJidFromResource(
  6414. largeVideoState.userResourceJid));
  6415. if (!userChanged && largeVideoState.preload &&
  6416. largeVideoState.preload !== null &&
  6417. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  6418. {
  6419. console.info('Switching to preloaded video');
  6420. var attributes = $('#largeVideo').prop("attributes");
  6421. // loop through largeVideo attributes and apply them on
  6422. // preload.
  6423. $.each(attributes, function () {
  6424. if (this.name !== 'id' && this.name !== 'src') {
  6425. largeVideoState.preload.attr(this.name, this.value);
  6426. }
  6427. });
  6428. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  6429. $('#largeVideo').attr('id', 'previousLargeVideo');
  6430. largeVideoState.preload.attr('id', 'largeVideo');
  6431. $('#previousLargeVideo').remove();
  6432. largeVideoState.preload.on('loadedmetadata', function (e) {
  6433. currentVideoWidth = this.videoWidth;
  6434. currentVideoHeight = this.videoHeight;
  6435. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6436. });
  6437. largeVideoState.preload = null;
  6438. largeVideoState.preload_ssrc = 0;
  6439. } else {
  6440. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6441. }
  6442. var videoTransform = document.getElementById('largeVideo')
  6443. .style.webkitTransform;
  6444. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6445. document.getElementById('largeVideo').style.webkitTransform
  6446. = "scaleX(-1)";
  6447. }
  6448. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6449. document.getElementById('largeVideo').style.webkitTransform
  6450. = "none";
  6451. }
  6452. // Change the way we'll be measuring and positioning large video
  6453. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6454. ? getDesktopVideoSize
  6455. : getCameraVideoSize;
  6456. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6457. ? getDesktopVideoPosition
  6458. : getCameraVideoPosition;
  6459. // Only if the large video is currently visible.
  6460. // Disable previous dominant speaker video.
  6461. if (largeVideoState.oldResourceJid) {
  6462. VideoLayout.enableDominantSpeaker(
  6463. largeVideoState.oldResourceJid,
  6464. false);
  6465. }
  6466. // Enable new dominant speaker in the remote videos section.
  6467. if (largeVideoState.userResourceJid) {
  6468. VideoLayout.enableDominantSpeaker(
  6469. largeVideoState.userResourceJid,
  6470. true);
  6471. }
  6472. if (userChanged && largeVideoState.isVisible) {
  6473. // using "this" should be ok because we're called
  6474. // from within the fadeOut event.
  6475. $(this).fadeIn(300);
  6476. }
  6477. if(userChanged) {
  6478. Avatar.showUserAvatar(
  6479. APP.xmpp.findJidFromResource(
  6480. largeVideoState.oldResourceJid));
  6481. }
  6482. largeVideoState.updateInProgress = false;
  6483. };
  6484. if (userChanged) {
  6485. $('#largeVideo').fadeOut(300, doUpdate);
  6486. } else {
  6487. doUpdate();
  6488. }
  6489. }
  6490. } else {
  6491. Avatar.showUserAvatar(
  6492. APP.xmpp.findJidFromResource(
  6493. largeVideoState.userResourceJid));
  6494. }
  6495. };
  6496. my.handleVideoThumbClicked = function(videoSrc,
  6497. noPinnedEndpointChangedEvent,
  6498. resourceJid) {
  6499. // Restore style for previously focused video
  6500. var oldContainer = null;
  6501. if(focusedVideoInfo) {
  6502. var focusResourceJid = focusedVideoInfo.resourceJid;
  6503. oldContainer = getParticipantContainer(focusResourceJid);
  6504. }
  6505. if (oldContainer) {
  6506. oldContainer.removeClass("videoContainerFocused");
  6507. }
  6508. // Unlock current focused.
  6509. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6510. {
  6511. focusedVideoInfo = null;
  6512. var dominantSpeakerVideo = null;
  6513. // Enable the currently set dominant speaker.
  6514. if (currentDominantSpeaker) {
  6515. dominantSpeakerVideo
  6516. = $('#participant_' + currentDominantSpeaker + '>video')
  6517. .get(0);
  6518. if (dominantSpeakerVideo) {
  6519. VideoLayout.updateLargeVideo(
  6520. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6521. 1,
  6522. currentDominantSpeaker);
  6523. }
  6524. }
  6525. if (!noPinnedEndpointChangedEvent) {
  6526. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6527. }
  6528. return;
  6529. }
  6530. // Lock new video
  6531. focusedVideoInfo = {
  6532. src: videoSrc,
  6533. resourceJid: resourceJid
  6534. };
  6535. // Update focused/pinned interface.
  6536. if (resourceJid)
  6537. {
  6538. var container = getParticipantContainer(resourceJid);
  6539. container.addClass("videoContainerFocused");
  6540. if (!noPinnedEndpointChangedEvent) {
  6541. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6542. }
  6543. }
  6544. if ($('#largeVideo').attr('src') === videoSrc &&
  6545. VideoLayout.isLargeVideoOnTop()) {
  6546. return;
  6547. }
  6548. // Triggers a "video.selected" event. The "false" parameter indicates
  6549. // this isn't a prezi.
  6550. $(document).trigger("video.selected", [false]);
  6551. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6552. $('audio').each(function (idx, el) {
  6553. if (el.id.indexOf('mixedmslabel') !== -1) {
  6554. el.volume = 0;
  6555. el.volume = 1;
  6556. }
  6557. });
  6558. };
  6559. /**
  6560. * Positions the large video.
  6561. *
  6562. * @param videoWidth the stream video width
  6563. * @param videoHeight the stream video height
  6564. */
  6565. my.positionLarge = function (videoWidth, videoHeight) {
  6566. var videoSpaceWidth = $('#videospace').width();
  6567. var videoSpaceHeight = window.innerHeight;
  6568. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6569. videoHeight,
  6570. videoSpaceWidth,
  6571. videoSpaceHeight);
  6572. var largeVideoWidth = videoSize[0];
  6573. var largeVideoHeight = videoSize[1];
  6574. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6575. largeVideoHeight,
  6576. videoSpaceWidth,
  6577. videoSpaceHeight);
  6578. var horizontalIndent = videoPosition[0];
  6579. var verticalIndent = videoPosition[1];
  6580. positionVideo($('#largeVideo'),
  6581. largeVideoWidth,
  6582. largeVideoHeight,
  6583. horizontalIndent, verticalIndent);
  6584. };
  6585. /**
  6586. * Shows/hides the large video.
  6587. */
  6588. my.setLargeVideoVisible = function(isVisible) {
  6589. var resourceJid = largeVideoState.userResourceJid;
  6590. if (isVisible) {
  6591. $('#largeVideo').css({visibility: 'visible'});
  6592. $('.watermark').css({visibility: 'visible'});
  6593. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6594. }
  6595. else {
  6596. $('#largeVideo').css({visibility: 'hidden'});
  6597. $('#activeSpeaker').css('visibility', 'hidden');
  6598. $('.watermark').css({visibility: 'hidden'});
  6599. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6600. if(focusedVideoInfo) {
  6601. var focusResourceJid = focusedVideoInfo.resourceJid;
  6602. var oldContainer = getParticipantContainer(focusResourceJid);
  6603. if (oldContainer && oldContainer.length > 0) {
  6604. oldContainer.removeClass("videoContainerFocused");
  6605. }
  6606. focusedVideoInfo = null;
  6607. if(focusResourceJid) {
  6608. Avatar.showUserAvatar(
  6609. APP.xmpp.findJidFromResource(focusResourceJid));
  6610. }
  6611. }
  6612. }
  6613. };
  6614. /**
  6615. * Indicates if the large video is currently visible.
  6616. *
  6617. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6618. */
  6619. my.isLargeVideoVisible = function() {
  6620. return $('#largeVideo').is(':visible');
  6621. };
  6622. my.isLargeVideoOnTop = function () {
  6623. var Etherpad = require("../etherpad/Etherpad");
  6624. var Prezi = require("../prezi/Prezi");
  6625. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6626. };
  6627. /**
  6628. * Checks if container for participant identified by given peerJid exists
  6629. * in the document and creates it eventually.
  6630. *
  6631. * @param peerJid peer Jid to check.
  6632. * @param userId user email or id for setting the avatar
  6633. *
  6634. * @return Returns <tt>true</tt> if the peer container exists,
  6635. * <tt>false</tt> - otherwise
  6636. */
  6637. my.ensurePeerContainerExists = function(peerJid, userId) {
  6638. ContactList.ensureAddContact(peerJid, userId);
  6639. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6640. var videoSpanId = 'participant_' + resourceJid;
  6641. if (!$('#' + videoSpanId).length) {
  6642. var container =
  6643. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6644. Avatar.setUserAvatar(peerJid, userId);
  6645. // Set default display name.
  6646. setDisplayName(videoSpanId);
  6647. VideoLayout.connectionIndicators[videoSpanId] =
  6648. new ConnectionIndicator(container, peerJid, VideoLayout);
  6649. var nickfield = document.createElement('span');
  6650. nickfield.className = "nick";
  6651. nickfield.appendChild(document.createTextNode(resourceJid));
  6652. container.appendChild(nickfield);
  6653. // In case this is not currently in the last n we don't show it.
  6654. if (localLastNCount
  6655. && localLastNCount > 0
  6656. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  6657. showPeerContainer(resourceJid, 'hide');
  6658. }
  6659. else
  6660. VideoLayout.resizeThumbnails();
  6661. }
  6662. };
  6663. my.addRemoteVideoContainer = function(peerJid, spanId) {
  6664. var container = document.createElement('span');
  6665. container.id = spanId;
  6666. container.className = 'videocontainer';
  6667. var remotes = document.getElementById('remoteVideos');
  6668. remotes.appendChild(container);
  6669. // If the peerJid is null then this video span couldn't be directly
  6670. // associated with a participant (this could happen in the case of prezi).
  6671. if (APP.xmpp.isModerator() && peerJid !== null)
  6672. addRemoteVideoMenu(peerJid, container);
  6673. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  6674. return container;
  6675. };
  6676. /**
  6677. * Creates an audio or video stream element.
  6678. */
  6679. my.createStreamElement = function (sid, stream) {
  6680. var isVideo = stream.getVideoTracks().length > 0;
  6681. var element = isVideo
  6682. ? document.createElement('video')
  6683. : document.createElement('audio');
  6684. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  6685. + sid + '_' + APP.RTC.getStreamID(stream);
  6686. element.id = id;
  6687. element.autoplay = true;
  6688. element.oncontextmenu = function () { return false; };
  6689. return element;
  6690. };
  6691. my.addRemoteStreamElement
  6692. = function (container, sid, stream, peerJid, thessrc) {
  6693. var newElementId = null;
  6694. var isVideo = stream.getVideoTracks().length > 0;
  6695. if (container) {
  6696. var streamElement = VideoLayout.createStreamElement(sid, stream);
  6697. newElementId = streamElement.id;
  6698. container.appendChild(streamElement);
  6699. var sel = $('#' + newElementId);
  6700. sel.hide();
  6701. // If the container is currently visible we attach the stream.
  6702. if (!isVideo
  6703. || (container.offsetParent !== null && isVideo)) {
  6704. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6705. APP.RTC.attachMediaStream(sel, videoStream);
  6706. if (isVideo)
  6707. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  6708. }
  6709. stream.onended = function () {
  6710. console.log('stream ended', this);
  6711. VideoLayout.removeRemoteStreamElement(
  6712. stream, isVideo, container);
  6713. // NOTE(gp) it seems that under certain circumstances, the
  6714. // onended event is not fired and thus the contact list is not
  6715. // updated.
  6716. //
  6717. // The onended event of a stream should be fired when the SSRCs
  6718. // corresponding to that stream are removed from the SDP; but
  6719. // this doesn't seem to always be the case, resulting in ghost
  6720. // contacts.
  6721. //
  6722. // In an attempt to fix the ghost contacts problem, I'm moving
  6723. // the removeContact() method call in app.js, inside the
  6724. // 'muc.left' event handler.
  6725. //if (peerJid)
  6726. // ContactList.removeContact(peerJid);
  6727. };
  6728. // Add click handler.
  6729. container.onclick = function (event) {
  6730. /*
  6731. * FIXME It turns out that videoThumb may not exist (if there is
  6732. * no actual video).
  6733. */
  6734. var videoThumb = $('#' + container.id + '>video').get(0);
  6735. if (videoThumb) {
  6736. VideoLayout.handleVideoThumbClicked(
  6737. APP.RTC.getVideoSrc(videoThumb),
  6738. false,
  6739. Strophe.getResourceFromJid(peerJid));
  6740. }
  6741. event.stopPropagation();
  6742. event.preventDefault();
  6743. return false;
  6744. };
  6745. // Add hover handler
  6746. $(container).hover(
  6747. function() {
  6748. VideoLayout.showDisplayName(container.id, true);
  6749. },
  6750. function() {
  6751. var videoSrc = null;
  6752. if ($('#' + container.id + '>video')
  6753. && $('#' + container.id + '>video').length > 0) {
  6754. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  6755. }
  6756. // If the video has been "pinned" by the user we want to
  6757. // keep the display name on place.
  6758. if (!VideoLayout.isLargeVideoVisible()
  6759. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6760. VideoLayout.showDisplayName(container.id, false);
  6761. }
  6762. );
  6763. }
  6764. return newElementId;
  6765. };
  6766. /**
  6767. * Removes the remote stream element corresponding to the given stream and
  6768. * parent container.
  6769. *
  6770. * @param stream the stream
  6771. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  6772. * @param container
  6773. */
  6774. my.removeRemoteStreamElement = function (stream, isVideo, container) {
  6775. if (!container)
  6776. return;
  6777. var select = null;
  6778. var removedVideoSrc = null;
  6779. if (isVideo) {
  6780. select = $('#' + container.id + '>video');
  6781. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  6782. }
  6783. else
  6784. select = $('#' + container.id + '>audio');
  6785. // Mark video as removed to cancel waiting loop(if video is removed
  6786. // before has started)
  6787. select.removed = true;
  6788. select.remove();
  6789. var audioCount = $('#' + container.id + '>audio').length;
  6790. var videoCount = $('#' + container.id + '>video').length;
  6791. if (!audioCount && !videoCount) {
  6792. console.log("Remove whole user", container.id);
  6793. if(VideoLayout.connectionIndicators[container.id])
  6794. VideoLayout.connectionIndicators[container.id].remove();
  6795. // Remove whole container
  6796. container.remove();
  6797. UIUtil.playSoundNotification('userLeft');
  6798. VideoLayout.resizeThumbnails();
  6799. }
  6800. if (removedVideoSrc)
  6801. VideoLayout.updateRemovedVideo(removedVideoSrc);
  6802. };
  6803. /**
  6804. * Show/hide peer container for the given resourceJid.
  6805. */
  6806. function showPeerContainer(resourceJid, state) {
  6807. var peerContainer = $('#participant_' + resourceJid);
  6808. if (!peerContainer)
  6809. return;
  6810. var isHide = state === 'hide';
  6811. var resizeThumbnails = false;
  6812. if (!isHide) {
  6813. if (!peerContainer.is(':visible')) {
  6814. resizeThumbnails = true;
  6815. peerContainer.show();
  6816. }
  6817. var jid = APP.xmpp.findJidFromResource(resourceJid);
  6818. if (state == 'show')
  6819. {
  6820. // peerContainer.css('-webkit-filter', '');
  6821. Avatar.showUserAvatar(jid, false);
  6822. }
  6823. else // if (state == 'avatar')
  6824. {
  6825. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  6826. Avatar.showUserAvatar(jid, true);
  6827. }
  6828. }
  6829. else if (peerContainer.is(':visible') && isHide)
  6830. {
  6831. resizeThumbnails = true;
  6832. peerContainer.hide();
  6833. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  6834. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  6835. }
  6836. if (resizeThumbnails) {
  6837. VideoLayout.resizeThumbnails();
  6838. }
  6839. // We want to be able to pin a participant from the contact list, even
  6840. // if he's not in the lastN set!
  6841. // ContactList.setClickable(resourceJid, !isHide);
  6842. };
  6843. my.inputDisplayNameHandler = function (name) {
  6844. NicknameHandler.setNickname(name);
  6845. if (!$('#localDisplayName').is(":visible")) {
  6846. if (NicknameHandler.getNickname())
  6847. {
  6848. var meHTML = APP.translation.generateTranslatonHTML("me");
  6849. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  6850. }
  6851. else
  6852. {
  6853. var defaultHTML = APP.translation.generateTranslatonHTML(
  6854. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6855. $('#localDisplayName')
  6856. .html(defaultHTML);
  6857. }
  6858. $('#localDisplayName').show();
  6859. }
  6860. $('#editDisplayName').hide();
  6861. };
  6862. /**
  6863. * Shows/hides the display name on the remote video.
  6864. * @param videoSpanId the identifier of the video span element
  6865. * @param isShow indicates if the display name should be shown or hidden
  6866. */
  6867. my.showDisplayName = function(videoSpanId, isShow) {
  6868. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  6869. if (isShow) {
  6870. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  6871. nameSpan.setAttribute("style", "display:inline-block;");
  6872. }
  6873. else {
  6874. if (nameSpan)
  6875. nameSpan.setAttribute("style", "display:none;");
  6876. }
  6877. };
  6878. /**
  6879. * Shows the presence status message for the given video.
  6880. */
  6881. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  6882. if (!$('#' + videoSpanId).length) {
  6883. // No container
  6884. return;
  6885. }
  6886. var statusSpan = $('#' + videoSpanId + '>span.status');
  6887. if (!statusSpan.length) {
  6888. //Add status span
  6889. statusSpan = document.createElement('span');
  6890. statusSpan.className = 'status';
  6891. statusSpan.id = videoSpanId + '_status';
  6892. $('#' + videoSpanId)[0].appendChild(statusSpan);
  6893. statusSpan = $('#' + videoSpanId + '>span.status');
  6894. }
  6895. // Display status
  6896. if (statusMsg && statusMsg.length) {
  6897. $('#' + videoSpanId + '_status').text(statusMsg);
  6898. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  6899. }
  6900. else {
  6901. // Hide
  6902. statusSpan.get(0).setAttribute("style", "display:none;");
  6903. }
  6904. };
  6905. /**
  6906. * Shows a visual indicator for the moderator of the conference.
  6907. */
  6908. my.showModeratorIndicator = function () {
  6909. var isModerator = APP.xmpp.isModerator();
  6910. if (isModerator) {
  6911. var indicatorSpan = $('#localVideoContainer .focusindicator');
  6912. if (indicatorSpan.children().length === 0)
  6913. {
  6914. createModeratorIndicatorElement(indicatorSpan[0]);
  6915. //translates text in focus indicator
  6916. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  6917. }
  6918. }
  6919. var members = APP.xmpp.getMembers();
  6920. Object.keys(members).forEach(function (jid) {
  6921. if (Strophe.getResourceFromJid(jid) === 'focus') {
  6922. // Skip server side focus
  6923. return;
  6924. }
  6925. var resourceJid = Strophe.getResourceFromJid(jid);
  6926. var videoSpanId = 'participant_' + resourceJid;
  6927. var videoContainer = document.getElementById(videoSpanId);
  6928. if (!videoContainer) {
  6929. console.error("No video container for " + jid);
  6930. return;
  6931. }
  6932. var member = members[jid];
  6933. if (member.role === 'moderator') {
  6934. // Remove menu if peer is moderator
  6935. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  6936. if (menuSpan.length) {
  6937. removeRemoteVideoMenu(videoSpanId);
  6938. }
  6939. // Show moderator indicator
  6940. var indicatorSpan
  6941. = $('#' + videoSpanId + ' .focusindicator');
  6942. if (!indicatorSpan || indicatorSpan.length === 0) {
  6943. indicatorSpan = document.createElement('span');
  6944. indicatorSpan.className = 'focusindicator';
  6945. videoContainer.appendChild(indicatorSpan);
  6946. createModeratorIndicatorElement(indicatorSpan);
  6947. //translates text in focus indicators
  6948. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  6949. }
  6950. } else if (isModerator) {
  6951. // We are moderator, but user is not - add menu
  6952. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  6953. addRemoteVideoMenu(
  6954. jid,
  6955. document.getElementById('participant_' + resourceJid));
  6956. }
  6957. }
  6958. });
  6959. };
  6960. /**
  6961. * Shows video muted indicator over small videos.
  6962. */
  6963. my.showVideoIndicator = function(videoSpanId, isMuted) {
  6964. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6965. if (isMuted === 'false') {
  6966. if (videoMutedSpan.length > 0) {
  6967. videoMutedSpan.remove();
  6968. }
  6969. }
  6970. else {
  6971. if(videoMutedSpan.length == 0) {
  6972. videoMutedSpan = document.createElement('span');
  6973. videoMutedSpan.className = 'videoMuted';
  6974. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  6975. var mutedIndicator = document.createElement('i');
  6976. mutedIndicator.className = 'icon-camera-disabled';
  6977. UIUtil.setTooltip(mutedIndicator,
  6978. "videothumbnail.videomute",
  6979. "top");
  6980. videoMutedSpan.appendChild(mutedIndicator);
  6981. //translate texts for muted indicator
  6982. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  6983. }
  6984. VideoLayout.updateMutePosition(videoSpanId);
  6985. }
  6986. };
  6987. my.updateMutePosition = function (videoSpanId) {
  6988. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6989. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  6990. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6991. if(connectionIndicator.length > 0
  6992. && connectionIndicator[0].style.display != "none") {
  6993. audioMutedSpan.css({right: "23px"});
  6994. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  6995. }
  6996. else
  6997. {
  6998. audioMutedSpan.css({right: "0px"});
  6999. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  7000. }
  7001. }
  7002. /**
  7003. * Shows audio muted indicator over small videos.
  7004. * @param {string} isMuted
  7005. */
  7006. my.showAudioIndicator = function(videoSpanId, isMuted) {
  7007. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  7008. if (isMuted === 'false') {
  7009. if (audioMutedSpan.length > 0) {
  7010. audioMutedSpan.popover('hide');
  7011. audioMutedSpan.remove();
  7012. }
  7013. }
  7014. else {
  7015. if(audioMutedSpan.length == 0 ) {
  7016. audioMutedSpan = document.createElement('span');
  7017. audioMutedSpan.className = 'audioMuted';
  7018. UIUtil.setTooltip(audioMutedSpan,
  7019. "videothumbnail.mute",
  7020. "top");
  7021. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  7022. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  7023. var mutedIndicator = document.createElement('i');
  7024. mutedIndicator.className = 'icon-mic-disabled';
  7025. audioMutedSpan.appendChild(mutedIndicator);
  7026. }
  7027. VideoLayout.updateMutePosition(videoSpanId);
  7028. }
  7029. };
  7030. /*
  7031. * Shows or hides the audio muted indicator over the local thumbnail video.
  7032. * @param {boolean} isMuted
  7033. */
  7034. my.showLocalAudioIndicator = function(isMuted) {
  7035. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  7036. };
  7037. /**
  7038. * Resizes the large video container.
  7039. */
  7040. my.resizeLargeVideoContainer = function () {
  7041. Chat.resizeChat();
  7042. var availableHeight = window.innerHeight;
  7043. var availableWidth = UIUtil.getAvailableVideoWidth();
  7044. if (availableWidth < 0 || availableHeight < 0) return;
  7045. $('#videospace').width(availableWidth);
  7046. $('#videospace').height(availableHeight);
  7047. $('#largeVideoContainer').width(availableWidth);
  7048. $('#largeVideoContainer').height(availableHeight);
  7049. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7050. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7051. $('#activeSpeaker').css('top', top);
  7052. VideoLayout.resizeThumbnails();
  7053. };
  7054. /**
  7055. * Resizes thumbnails.
  7056. */
  7057. my.resizeThumbnails = function() {
  7058. var videoSpaceWidth = $('#remoteVideos').width();
  7059. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  7060. var width = thumbnailSize[0];
  7061. var height = thumbnailSize[1];
  7062. // size videos so that while keeping AR and max height, we have a
  7063. // nice fit
  7064. $('#remoteVideos').height(height);
  7065. $('#remoteVideos>span').width(width);
  7066. $('#remoteVideos>span').height(height);
  7067. $('.userAvatar').css('left', (width - height) / 2);
  7068. $(document).trigger("remotevideo.resized", [width, height]);
  7069. };
  7070. /**
  7071. * Enables the dominant speaker UI.
  7072. *
  7073. * @param resourceJid the jid indicating the video element to
  7074. * activate/deactivate
  7075. * @param isEnable indicates if the dominant speaker should be enabled or
  7076. * disabled
  7077. */
  7078. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  7079. var videoSpanId = null;
  7080. var videoContainerId = null;
  7081. if (resourceJid
  7082. === APP.xmpp.myResource()) {
  7083. videoSpanId = 'localVideoWrapper';
  7084. videoContainerId = 'localVideoContainer';
  7085. }
  7086. else {
  7087. videoSpanId = 'participant_' + resourceJid;
  7088. videoContainerId = videoSpanId;
  7089. }
  7090. var displayName = resourceJid;
  7091. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  7092. if (nameSpan.length > 0)
  7093. displayName = nameSpan.html();
  7094. console.log("UI enable dominant speaker",
  7095. displayName,
  7096. resourceJid,
  7097. isEnable);
  7098. videoSpan = document.getElementById(videoContainerId);
  7099. if (!videoSpan) {
  7100. return;
  7101. }
  7102. var video = $('#' + videoSpanId + '>video');
  7103. if (video && video.length > 0) {
  7104. if (isEnable) {
  7105. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  7106. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  7107. if (!videoSpan.classList.contains("dominantspeaker"))
  7108. videoSpan.classList.add("dominantspeaker");
  7109. }
  7110. else {
  7111. VideoLayout.showDisplayName(videoContainerId, false);
  7112. if (videoSpan.classList.contains("dominantspeaker"))
  7113. videoSpan.classList.remove("dominantspeaker");
  7114. }
  7115. Avatar.showUserAvatar(
  7116. APP.xmpp.findJidFromResource(resourceJid));
  7117. }
  7118. };
  7119. /**
  7120. * Calculates the thumbnail size.
  7121. *
  7122. * @param videoSpaceWidth the width of the video space
  7123. */
  7124. my.calculateThumbnailSize = function (videoSpaceWidth) {
  7125. // Calculate the available height, which is the inner window height minus
  7126. // 39px for the header minus 2px for the delimiter lines on the top and
  7127. // bottom of the large video, minus the 36px space inside the remoteVideos
  7128. // container used for highlighting shadow.
  7129. var availableHeight = 100;
  7130. var numvids = $('#remoteVideos>span:visible').length;
  7131. if (localLastNCount && localLastNCount > 0) {
  7132. numvids = Math.min(localLastNCount + 1, numvids);
  7133. }
  7134. // Remove the 3px borders arround videos and border around the remote
  7135. // videos area and the 4 pixels between the local video and the others
  7136. //TODO: Find out where the 4 pixels come from and remove them
  7137. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  7138. var availableWidth = availableWinWidth / numvids;
  7139. var aspectRatio = 16.0 / 9.0;
  7140. var maxHeight = Math.min(160, availableHeight);
  7141. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  7142. if (availableHeight < availableWidth / aspectRatio) {
  7143. availableWidth = Math.floor(availableHeight * aspectRatio);
  7144. }
  7145. return [availableWidth, availableHeight];
  7146. };
  7147. /**
  7148. * Updates the remote video menu.
  7149. *
  7150. * @param jid the jid indicating the video for which we're adding a menu.
  7151. * @param isMuted indicates the current mute state
  7152. */
  7153. my.updateRemoteVideoMenu = function(jid, isMuted) {
  7154. var muteMenuItem
  7155. = $('#remote_popupmenu_'
  7156. + Strophe.getResourceFromJid(jid)
  7157. + '>li>a.mutelink');
  7158. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  7159. if (muteMenuItem.length) {
  7160. var muteLink = muteMenuItem.get(0);
  7161. if (isMuted === 'true') {
  7162. muteLink.innerHTML = mutedIndicator + ' Muted';
  7163. muteLink.className = 'mutelink disabled';
  7164. }
  7165. else {
  7166. muteLink.innerHTML = mutedIndicator + ' Mute';
  7167. muteLink.className = 'mutelink';
  7168. }
  7169. }
  7170. };
  7171. /**
  7172. * Returns the current dominant speaker resource jid.
  7173. */
  7174. my.getDominantSpeakerResourceJid = function () {
  7175. return currentDominantSpeaker;
  7176. };
  7177. /**
  7178. * Returns the corresponding resource jid to the given peer container
  7179. * DOM element.
  7180. *
  7181. * @return the corresponding resource jid to the given peer container
  7182. * DOM element
  7183. */
  7184. my.getPeerContainerResourceJid = function (containerElement) {
  7185. var i = containerElement.id.indexOf('participant_');
  7186. if (i >= 0)
  7187. return containerElement.id.substring(i + 12);
  7188. };
  7189. /**
  7190. * On contact list item clicked.
  7191. */
  7192. $(ContactList).bind('contactclicked', function(event, jid) {
  7193. if (!jid) {
  7194. return;
  7195. }
  7196. var resource = Strophe.getResourceFromJid(jid);
  7197. var videoContainer = $("#participant_" + resource);
  7198. if (videoContainer.length > 0) {
  7199. var videoThumb = $('video', videoContainer).get(0);
  7200. // It is not always the case that a videoThumb exists (if there is
  7201. // no actual video).
  7202. if (videoThumb) {
  7203. if (videoThumb.src && videoThumb.src != '') {
  7204. // We have a video src, great! Let's update the large video
  7205. // now.
  7206. VideoLayout.handleVideoThumbClicked(
  7207. videoThumb.src,
  7208. false,
  7209. Strophe.getResourceFromJid(jid));
  7210. } else {
  7211. // If we don't have a video src for jid, there's absolutely
  7212. // no point in calling handleVideoThumbClicked; Quite
  7213. // simply, it won't work because it needs an src to attach
  7214. // to the large video.
  7215. //
  7216. // Instead, we trigger the pinned endpoint changed event to
  7217. // let the bridge adjust its lastN set for myjid and store
  7218. // the pinned user in the lastNPickupJid variable to be
  7219. // picked up later by the lastN changed event handler.
  7220. lastNPickupJid = jid;
  7221. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  7222. Strophe.getResourceFromJid(jid));
  7223. }
  7224. } else if (jid == APP.xmpp.myJid()) {
  7225. $("#localVideoContainer").click();
  7226. }
  7227. }
  7228. });
  7229. /**
  7230. * On audio muted event.
  7231. */
  7232. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  7233. /*
  7234. // FIXME: but focus can not mute in this case ? - check
  7235. if (jid === xmpp.myJid()) {
  7236. // The local mute indicator is controlled locally
  7237. return;
  7238. }*/
  7239. var videoSpanId = null;
  7240. if (jid === APP.xmpp.myJid()) {
  7241. videoSpanId = 'localVideoContainer';
  7242. } else {
  7243. VideoLayout.ensurePeerContainerExists(jid);
  7244. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7245. }
  7246. mutedAudios[jid] = isMuted;
  7247. if (APP.xmpp.isModerator()) {
  7248. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  7249. }
  7250. if (videoSpanId)
  7251. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  7252. });
  7253. /**
  7254. * On video muted event.
  7255. */
  7256. $(document).bind('videomuted.muc', function (event, jid, value) {
  7257. var isMuted = (value === "true");
  7258. if(jid !== APP.xmpp.myJid() && !APP.RTC.muteRemoteVideoStream(jid, isMuted))
  7259. return;
  7260. Avatar.showUserAvatar(jid, isMuted);
  7261. var videoSpanId = null;
  7262. if (jid === APP.xmpp.myJid()) {
  7263. videoSpanId = 'localVideoContainer';
  7264. } else {
  7265. VideoLayout.ensurePeerContainerExists(jid);
  7266. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7267. }
  7268. if (videoSpanId)
  7269. VideoLayout.showVideoIndicator(videoSpanId, value);
  7270. });
  7271. /**
  7272. * Display name changed.
  7273. */
  7274. my.onDisplayNameChanged =
  7275. function (jid, displayName, status) {
  7276. if (jid === 'localVideoContainer'
  7277. || jid === APP.xmpp.myJid()) {
  7278. setDisplayName('localVideoContainer',
  7279. displayName);
  7280. } else {
  7281. VideoLayout.ensurePeerContainerExists(jid);
  7282. setDisplayName(
  7283. 'participant_' + Strophe.getResourceFromJid(jid),
  7284. displayName,
  7285. status);
  7286. }
  7287. };
  7288. /**
  7289. * On dominant speaker changed event.
  7290. */
  7291. my.onDominantSpeakerChanged = function (resourceJid) {
  7292. // We ignore local user events.
  7293. if (resourceJid
  7294. === APP.xmpp.myResource())
  7295. return;
  7296. var members = APP.xmpp.getMembers();
  7297. // Update the current dominant speaker.
  7298. if (resourceJid !== currentDominantSpeaker) {
  7299. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  7300. newSpeakerVideoSpanId = "participant_" + resourceJid;
  7301. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  7302. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  7303. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  7304. !members[currentJID].displayName)) {
  7305. setDisplayName(oldSpeakerVideoSpanId, null);
  7306. }
  7307. if(resourceJid && (!members || !members[newJID] ||
  7308. !members[newJID].displayName)) {
  7309. setDisplayName(newSpeakerVideoSpanId, null,
  7310. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  7311. }
  7312. currentDominantSpeaker = resourceJid;
  7313. } else {
  7314. return;
  7315. }
  7316. // Obtain container for new dominant speaker.
  7317. var container = document.getElementById(
  7318. 'participant_' + resourceJid);
  7319. // Local video will not have container found, but that's ok
  7320. // since we don't want to switch to local video.
  7321. if (container && !focusedVideoInfo)
  7322. {
  7323. var video = container.getElementsByTagName("video");
  7324. // Update the large video if the video source is already available,
  7325. // otherwise wait for the "videoactive.jingle" event.
  7326. if (video.length && video[0].currentTime > 0)
  7327. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  7328. }
  7329. };
  7330. /**
  7331. * On last N change event.
  7332. *
  7333. * @param lastNEndpoints the list of last N endpoints
  7334. * @param endpointsEnteringLastN the list currently entering last N
  7335. * endpoints
  7336. */
  7337. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7338. endpointsEnteringLastN,
  7339. stream) {
  7340. if (lastNCount !== lastNEndpoints.length)
  7341. lastNCount = lastNEndpoints.length;
  7342. lastNEndpointsCache = lastNEndpoints;
  7343. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7344. //
  7345. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7346. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7347. // so E sees them. C is only in E's local LastN set.
  7348. //
  7349. // If F starts talking and LastN = 3, then E should see thumbnails for
  7350. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7351. // enters E's local LastN ejecting C.
  7352. // Increase the local LastN set size, if necessary.
  7353. if (lastNCount > localLastNCount) {
  7354. localLastNCount = lastNCount;
  7355. }
  7356. // Update the local LastN set preserving the order in which the
  7357. // endpoints appeared in the LastN/local LastN set.
  7358. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7359. for (var i = 0; i < localLastNSet.length; i++) {
  7360. if (nextLocalLastNSet.length >= localLastNCount) {
  7361. break;
  7362. }
  7363. var resourceJid = localLastNSet[i];
  7364. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7365. nextLocalLastNSet.push(resourceJid);
  7366. }
  7367. }
  7368. localLastNSet = nextLocalLastNSet;
  7369. var updateLargeVideo = false;
  7370. // Handle LastN/local LastN changes.
  7371. $('#remoteVideos>span').each(function( index, element ) {
  7372. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7373. var isReceived = true;
  7374. if (resourceJid
  7375. && lastNEndpoints.indexOf(resourceJid) < 0
  7376. && localLastNSet.indexOf(resourceJid) < 0) {
  7377. console.log("Remove from last N", resourceJid);
  7378. showPeerContainer(resourceJid, 'hide');
  7379. isReceived = false;
  7380. } else if (resourceJid
  7381. && $('#participant_' + resourceJid).is(':visible')
  7382. && lastNEndpoints.indexOf(resourceJid) < 0
  7383. && localLastNSet.indexOf(resourceJid) >= 0) {
  7384. showPeerContainer(resourceJid, 'avatar');
  7385. isReceived = false;
  7386. }
  7387. if (!isReceived) {
  7388. // resourceJid has dropped out of the server side lastN set, so
  7389. // it is no longer being received. If resourceJid was being
  7390. // displayed in the large video we have to switch to another
  7391. // user.
  7392. var largeVideoResource = largeVideoState.userResourceJid;
  7393. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7394. updateLargeVideo = true;
  7395. }
  7396. }
  7397. });
  7398. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7399. endpointsEnteringLastN = lastNEndpoints;
  7400. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7401. endpointsEnteringLastN.forEach(function (resourceJid) {
  7402. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7403. showPeerContainer(resourceJid, 'show');
  7404. if (!isVisible) {
  7405. console.log("Add to last N", resourceJid);
  7406. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7407. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7408. var sel = $('#participant_' + resourceJid + '>video');
  7409. var videoStream = APP.simulcast.getReceivingVideoStream(
  7410. mediaStream.stream);
  7411. APP.RTC.attachMediaStream(sel, videoStream);
  7412. if (lastNPickupJid == mediaStream.peerjid) {
  7413. // Clean up the lastN pickup jid.
  7414. lastNPickupJid = null;
  7415. // Don't fire the events again, they've already
  7416. // been fired in the contact list click handler.
  7417. VideoLayout.handleVideoThumbClicked(
  7418. $(sel).attr('src'),
  7419. false,
  7420. Strophe.getResourceFromJid(mediaStream.peerjid));
  7421. updateLargeVideo = false;
  7422. }
  7423. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7424. }
  7425. })
  7426. }
  7427. // The endpoint that was being shown in the large video has dropped out
  7428. // of the lastN set and there was no lastN pickup jid. We need to update
  7429. // the large video now.
  7430. if (updateLargeVideo) {
  7431. var resource, container, src;
  7432. var myResource
  7433. = APP.xmpp.myResource();
  7434. // Find out which endpoint to show in the large video.
  7435. for (var i = 0; i < lastNEndpoints.length; i++) {
  7436. resource = lastNEndpoints[i];
  7437. if (!resource || resource === myResource)
  7438. continue;
  7439. container = $("#participant_" + resource);
  7440. if (container.length == 0)
  7441. continue;
  7442. src = $('video', container).attr('src');
  7443. if (!src)
  7444. continue;
  7445. // videoSrcToSsrc needs to be update for this call to succeed.
  7446. VideoLayout.updateLargeVideo(src);
  7447. break;
  7448. }
  7449. }
  7450. };
  7451. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  7452. endpointSimulcastLayers.forEach(function (esl) {
  7453. var resource = esl.endpoint;
  7454. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7455. // then ignore the event (= do not preload anything).
  7456. //
  7457. // The bridge could probably stop sending this message if it's for
  7458. // an endpoint that's not in lastN.
  7459. if (lastNCount != -1
  7460. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7461. return;
  7462. }
  7463. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7464. // Get session and stream from primary ssrc.
  7465. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7466. var sid = res.sid;
  7467. var electedStream = res.stream;
  7468. if (sid && electedStream) {
  7469. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7470. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7471. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  7472. if (preload) {
  7473. if (largeVideoState.preload)
  7474. {
  7475. $(largeVideoState.preload).remove();
  7476. }
  7477. console.info('Preloading remote video');
  7478. largeVideoState.preload = $('<video autoplay></video>');
  7479. // ssrcs are unique in an rtp session
  7480. largeVideoState.preload_ssrc = primarySSRC;
  7481. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  7482. }
  7483. } else {
  7484. console.error('Could not find a stream or a session.', sid, electedStream);
  7485. }
  7486. });
  7487. };
  7488. /**
  7489. * On simulcast layers changed event.
  7490. */
  7491. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  7492. endpointSimulcastLayers.forEach(function (esl) {
  7493. var resource = esl.endpoint;
  7494. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7495. // then ignore the event (= do not change large video/thumbnail
  7496. // SRCs).
  7497. //
  7498. // Note that even if we ignore the "changed" event in this event
  7499. // handler, the bridge must continue sending these events because
  7500. // the simulcast code in simulcast.js uses it to know what's going
  7501. // to be streamed by the bridge when/if the endpoint gets back into
  7502. // the lastN set.
  7503. if (lastNCount != -1
  7504. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7505. return;
  7506. }
  7507. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7508. // Get session and stream from primary ssrc.
  7509. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7510. var sid = res.sid;
  7511. var electedStream = res.stream;
  7512. if (sid && electedStream) {
  7513. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7514. console.info('Switching simulcast substream.');
  7515. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7516. var msidParts = msid.split(' ');
  7517. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  7518. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  7519. == largeVideoState.userResourceJid);
  7520. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  7521. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  7522. var electedStreamUrl;
  7523. if (largeVideoState.preload_ssrc == primarySSRC)
  7524. {
  7525. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  7526. }
  7527. else
  7528. {
  7529. if (largeVideoState.preload
  7530. && largeVideoState.preload != null) {
  7531. $(largeVideoState.preload).remove();
  7532. }
  7533. largeVideoState.preload_ssrc = 0;
  7534. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  7535. }
  7536. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  7537. if (updateLargeVideo) {
  7538. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  7539. Strophe.getResourceFromJid(jid));
  7540. }
  7541. if (updateFocusedVideoSrc) {
  7542. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  7543. }
  7544. var videoId;
  7545. if(resource == APP.xmpp.myResource())
  7546. {
  7547. videoId = "localVideoContainer";
  7548. }
  7549. else
  7550. {
  7551. videoId = "participant_" + resource;
  7552. }
  7553. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  7554. if(connectionIndicator)
  7555. connectionIndicator.updatePopoverData();
  7556. } else {
  7557. console.error('Could not find a stream or a sid.', sid, electedStream);
  7558. }
  7559. });
  7560. };
  7561. /**
  7562. * Updates local stats
  7563. * @param percent
  7564. * @param object
  7565. */
  7566. my.updateLocalConnectionStats = function (percent, object) {
  7567. var resolution = null;
  7568. if(object.resolution !== null)
  7569. {
  7570. resolution = object.resolution;
  7571. object.resolution = resolution[APP.xmpp.myJid()];
  7572. delete resolution[APP.xmpp.myJid()];
  7573. }
  7574. updateStatsIndicator("localVideoContainer", percent, object);
  7575. for(var jid in resolution)
  7576. {
  7577. if(resolution[jid] === null)
  7578. continue;
  7579. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7580. if(VideoLayout.connectionIndicators[id])
  7581. {
  7582. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7583. }
  7584. }
  7585. };
  7586. /**
  7587. * Updates remote stats.
  7588. * @param jid the jid associated with the stats
  7589. * @param percent the connection quality percent
  7590. * @param object the stats data
  7591. */
  7592. my.updateConnectionStats = function (jid, percent, object) {
  7593. var resourceJid = Strophe.getResourceFromJid(jid);
  7594. var videoSpanId = 'participant_' + resourceJid;
  7595. updateStatsIndicator(videoSpanId, percent, object);
  7596. };
  7597. /**
  7598. * Removes the connection
  7599. * @param jid
  7600. */
  7601. my.removeConnectionIndicator = function (jid) {
  7602. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7603. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7604. };
  7605. /**
  7606. * Hides the connection indicator
  7607. * @param jid
  7608. */
  7609. my.hideConnectionIndicator = function (jid) {
  7610. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7611. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7612. };
  7613. /**
  7614. * Hides all the indicators
  7615. */
  7616. my.onStatsStop = function () {
  7617. for(var indicator in VideoLayout.connectionIndicators)
  7618. {
  7619. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7620. }
  7621. };
  7622. my.participantLeft = function (jid) {
  7623. // Unlock large video
  7624. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7625. {
  7626. console.info("Focused video owner has left the conference");
  7627. focusedVideoInfo = null;
  7628. }
  7629. }
  7630. my.onVideoTypeChanged = function (jid) {
  7631. if(jid &&
  7632. Strophe.getResourceFromJid(jid) === largeVideoState.userResourceJid)
  7633. {
  7634. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  7635. VideoLayout.getVideoSize = largeVideoState.isDesktop
  7636. ? getDesktopVideoSize
  7637. : getCameraVideoSize;
  7638. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  7639. ? getDesktopVideoPosition
  7640. : getCameraVideoPosition;
  7641. VideoLayout.positionLarge(null, null);
  7642. }
  7643. }
  7644. return my;
  7645. }(VideoLayout || {}));
  7646. module.exports = VideoLayout;
  7647. },{"../../../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){
  7648. //var nouns = [
  7649. //];
  7650. var pluralNouns = [
  7651. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7652. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  7653. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  7654. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  7655. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  7656. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  7657. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  7658. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  7659. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  7660. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  7661. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  7662. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  7663. ];
  7664. //var places = [
  7665. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  7666. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  7667. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  7668. // "Bridge"
  7669. //];
  7670. var verbs = [
  7671. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  7672. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  7673. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  7674. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  7675. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  7676. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  7677. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  7678. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  7679. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  7680. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  7681. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  7682. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  7683. ];
  7684. var adverbs = [
  7685. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  7686. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  7687. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  7688. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  7689. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  7690. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  7691. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  7692. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  7693. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  7694. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  7695. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  7696. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  7697. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  7698. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  7699. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  7700. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  7701. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  7702. ];
  7703. var adjectives = [
  7704. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  7705. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  7706. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  7707. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  7708. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  7709. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  7710. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  7711. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  7712. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  7713. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  7714. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  7715. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  7716. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  7717. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  7718. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  7719. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  7720. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  7721. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  7722. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  7723. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  7724. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  7725. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  7726. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  7727. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  7728. "Zealous"
  7729. ];
  7730. //var pronouns = [
  7731. //];
  7732. //var conjunctions = [
  7733. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  7734. //];
  7735. /*
  7736. * Maps a string (category name) to the array of words from that category.
  7737. */
  7738. var CATEGORIES =
  7739. {
  7740. //"_NOUN_": nouns,
  7741. "_PLURALNOUN_": pluralNouns,
  7742. //"_PLACE_": places,
  7743. "_VERB_": verbs,
  7744. "_ADVERB_": adverbs,
  7745. "_ADJECTIVE_": adjectives
  7746. //"_PRONOUN_": pronouns,
  7747. //"_CONJUNCTION_": conjunctions,
  7748. };
  7749. var PATTERNS = [
  7750. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  7751. // BeautifulFungiOrSpaghetti
  7752. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  7753. // AmazinglyScaryToy
  7754. //"_ADVERB__ADJECTIVE__NOUN_",
  7755. // NeitherTrashNorRifle
  7756. //"Neither_NOUN_Nor_NOUN_",
  7757. //"Either_NOUN_Or_NOUN_",
  7758. // EitherCopulateOrInvestigate
  7759. //"Either_VERB_Or_VERB_",
  7760. //"Neither_VERB_Nor_VERB_",
  7761. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  7762. //"The_ADVERB__ADJECTIVE__NOUN_",
  7763. //"The_ADVERB__ADJECTIVE__NOUN_s",
  7764. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  7765. // WolvesComputeBadly
  7766. //"_PLURALNOUN__VERB__ADVERB_",
  7767. // UniteFacilitateAndMerge
  7768. //"_VERB__VERB_And_VERB_",
  7769. //NastyWitchesAtThePub
  7770. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  7771. ];
  7772. /*
  7773. * Returns a random element from the array 'arr'
  7774. */
  7775. function randomElement(arr)
  7776. {
  7777. return arr[Math.floor(Math.random() * arr.length)];
  7778. }
  7779. /*
  7780. * Returns true if the string 's' contains one of the
  7781. * template strings.
  7782. */
  7783. function hasTemplate(s)
  7784. {
  7785. for (var template in CATEGORIES){
  7786. if (s.indexOf(template) >= 0){
  7787. return true;
  7788. }
  7789. }
  7790. }
  7791. /**
  7792. * Generates new room name.
  7793. */
  7794. var RoomNameGenerator = {
  7795. generateRoomWithoutSeparator: function()
  7796. {
  7797. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  7798. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  7799. var name = randomElement(PATTERNS);
  7800. var word;
  7801. while (hasTemplate(name)){
  7802. for (var template in CATEGORIES){
  7803. word = randomElement(CATEGORIES[template]);
  7804. name = name.replace(template, word);
  7805. }
  7806. }
  7807. return name;
  7808. }
  7809. }
  7810. module.exports = RoomNameGenerator;
  7811. },{}],34:[function(require,module,exports){
  7812. var animateTimeout, updateTimeout;
  7813. var RoomNameGenerator = require("./RoomnameGenerator");
  7814. function enter_room()
  7815. {
  7816. var val = $("#enter_room_field").val();
  7817. if(!val) {
  7818. val = $("#enter_room_field").attr("room_name");
  7819. }
  7820. if (val) {
  7821. window.location.pathname = "/" + val;
  7822. }
  7823. }
  7824. function animate(word) {
  7825. var currentVal = $("#enter_room_field").attr("placeholder");
  7826. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  7827. animateTimeout = setTimeout(function() {
  7828. animate(word.substring(1, word.length))
  7829. }, 70);
  7830. }
  7831. function update_roomname()
  7832. {
  7833. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  7834. $("#enter_room_field").attr("room_name", word);
  7835. $("#enter_room_field").attr("placeholder", "");
  7836. clearTimeout(animateTimeout);
  7837. animate(word);
  7838. updateTimeout = setTimeout(update_roomname, 10000);
  7839. }
  7840. function setupWelcomePage()
  7841. {
  7842. $("#videoconference_page").hide();
  7843. $("#domain_name").text(
  7844. window.location.protocol + "//" + window.location.host + "/");
  7845. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7846. var leftWatermarkDiv
  7847. = $("#welcome_page_header div[class='watermark leftwatermark']");
  7848. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  7849. {
  7850. leftWatermarkDiv.css({display: 'block'});
  7851. leftWatermarkDiv.parent().get(0).href
  7852. = interfaceConfig.JITSI_WATERMARK_LINK;
  7853. }
  7854. }
  7855. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7856. var rightWatermarkDiv
  7857. = $("#welcome_page_header div[class='watermark rightwatermark']");
  7858. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  7859. rightWatermarkDiv.css({display: 'block'});
  7860. rightWatermarkDiv.parent().get(0).href
  7861. = interfaceConfig.BRAND_WATERMARK_LINK;
  7862. rightWatermarkDiv.get(0).style.backgroundImage
  7863. = "url(images/rightwatermark.png)";
  7864. }
  7865. }
  7866. if (interfaceConfig.SHOW_POWERED_BY) {
  7867. $("#welcome_page_header>a[class='poweredby']")
  7868. .css({display: 'block'});
  7869. }
  7870. $("#enter_room_button").click(function()
  7871. {
  7872. enter_room();
  7873. });
  7874. $("#enter_room_field").keydown(function (event) {
  7875. if (event.keyCode === 13 /* enter */) {
  7876. enter_room();
  7877. }
  7878. });
  7879. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  7880. var updateTimeout;
  7881. var animateTimeout;
  7882. $("#reload_roomname").click(function () {
  7883. clearTimeout(updateTimeout);
  7884. clearTimeout(animateTimeout);
  7885. update_roomname();
  7886. });
  7887. $("#reload_roomname").show();
  7888. update_roomname();
  7889. }
  7890. $("#disable_welcome").click(function () {
  7891. window.localStorage.welcomePageDisabled
  7892. = $("#disable_welcome").is(":checked");
  7893. });
  7894. }
  7895. module.exports = setupWelcomePage;
  7896. },{"./RoomnameGenerator":33}],35:[function(require,module,exports){
  7897. var EventEmitter = require("events");
  7898. var eventEmitter = new EventEmitter();
  7899. var CQEvents = require("../../service/connectionquality/CQEvents");
  7900. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7901. /**
  7902. * local stats
  7903. * @type {{}}
  7904. */
  7905. var stats = {};
  7906. /**
  7907. * remote stats
  7908. * @type {{}}
  7909. */
  7910. var remoteStats = {};
  7911. /**
  7912. * Interval for sending statistics to other participants
  7913. * @type {null}
  7914. */
  7915. var sendIntervalId = null;
  7916. /**
  7917. * Start statistics sending.
  7918. */
  7919. function startSendingStats() {
  7920. sendStats();
  7921. sendIntervalId = setInterval(sendStats, 10000);
  7922. }
  7923. /**
  7924. * Sends statistics to other participants
  7925. */
  7926. function sendStats() {
  7927. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  7928. }
  7929. /**
  7930. * Converts statistics to format for sending through XMPP
  7931. * @param stats the statistics
  7932. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  7933. */
  7934. function convertToMUCStats(stats) {
  7935. return {
  7936. "bitrate_download": stats.bitrate.download,
  7937. "bitrate_upload": stats.bitrate.upload,
  7938. "packetLoss_total": stats.packetLoss.total,
  7939. "packetLoss_download": stats.packetLoss.download,
  7940. "packetLoss_upload": stats.packetLoss.upload
  7941. };
  7942. }
  7943. /**
  7944. * Converts statitistics to format used by VideoLayout
  7945. * @param stats
  7946. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  7947. */
  7948. function parseMUCStats(stats) {
  7949. return {
  7950. bitrate: {
  7951. download: stats.bitrate_download,
  7952. upload: stats.bitrate_upload
  7953. },
  7954. packetLoss: {
  7955. total: stats.packetLoss_total,
  7956. download: stats.packetLoss_download,
  7957. upload: stats.packetLoss_upload
  7958. }
  7959. };
  7960. }
  7961. var ConnectionQuality = {
  7962. init: function () {
  7963. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  7964. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  7965. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  7966. },
  7967. /**
  7968. * Updates the local statistics
  7969. * @param data new statistics
  7970. */
  7971. updateLocalStats: function (data) {
  7972. stats = data;
  7973. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  7974. if (sendIntervalId == null) {
  7975. startSendingStats();
  7976. }
  7977. },
  7978. /**
  7979. * Updates remote statistics
  7980. * @param jid the jid associated with the statistics
  7981. * @param data the statistics
  7982. */
  7983. updateRemoteStats: function (jid, data) {
  7984. if (data == null || data.packetLoss_total == null) {
  7985. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  7986. return;
  7987. }
  7988. remoteStats[jid] = parseMUCStats(data);
  7989. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  7990. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  7991. },
  7992. /**
  7993. * Stops statistics sending.
  7994. */
  7995. stopSendingStats: function () {
  7996. clearInterval(sendIntervalId);
  7997. sendIntervalId = null;
  7998. //notify UI about stopping statistics gathering
  7999. eventEmitter.emit(CQEvents.STOP);
  8000. },
  8001. /**
  8002. * Returns the local statistics.
  8003. */
  8004. getStats: function () {
  8005. return stats;
  8006. },
  8007. addListener: function (type, listener) {
  8008. eventEmitter.on(type, listener);
  8009. }
  8010. };
  8011. module.exports = ConnectionQuality;
  8012. },{"../../service/connectionquality/CQEvents":94,"../../service/xmpp/XMPPEvents":97,"events":98}],36:[function(require,module,exports){
  8013. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  8014. getUserMediaWithConstraints */
  8015. /**
  8016. * Indicates that desktop stream is currently in use(for toggle purpose).
  8017. * @type {boolean}
  8018. */
  8019. var isUsingScreenStream = false;
  8020. /**
  8021. * Indicates that switch stream operation is in progress and prevent from
  8022. * triggering new events.
  8023. * @type {boolean}
  8024. */
  8025. var switchInProgress = false;
  8026. /**
  8027. * Method used to get screen sharing stream.
  8028. *
  8029. * @type {function (stream_callback, failure_callback}
  8030. */
  8031. var obtainDesktopStream = null;
  8032. /**
  8033. * Indicates whether desktop sharing extension is installed.
  8034. * @type {boolean}
  8035. */
  8036. var extInstalled = false;
  8037. /**
  8038. * Indicates whether update of desktop sharing extension is required.
  8039. * @type {boolean}
  8040. */
  8041. var extUpdateRequired = false;
  8042. /**
  8043. * Flag used to cache desktop sharing enabled state. Do not use directly as
  8044. * it can be <tt>null</tt>.
  8045. *
  8046. * @type {null|boolean}
  8047. */
  8048. var _desktopSharingEnabled = null;
  8049. var EventEmitter = require("events");
  8050. var eventEmitter = new EventEmitter();
  8051. var DesktopSharingEventTypes
  8052. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  8053. /**
  8054. * Method obtains desktop stream from WebRTC 'screen' source.
  8055. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  8056. */
  8057. function obtainWebRTCScreen(streamCallback, failCallback) {
  8058. APP.RTC.getUserMediaWithConstraints(
  8059. ['screen'],
  8060. streamCallback,
  8061. failCallback
  8062. );
  8063. }
  8064. /**
  8065. * Constructs inline install URL for Chrome desktop streaming extension.
  8066. * The 'chromeExtensionId' must be defined in config.js.
  8067. * @returns {string}
  8068. */
  8069. function getWebStoreInstallUrl()
  8070. {
  8071. return "https://chrome.google.com/webstore/detail/" +
  8072. config.chromeExtensionId;
  8073. }
  8074. /**
  8075. * Checks whether extension update is required.
  8076. * @param minVersion minimal required version
  8077. * @param extVersion current extension version
  8078. * @returns {boolean}
  8079. */
  8080. function isUpdateRequired(minVersion, extVersion)
  8081. {
  8082. try
  8083. {
  8084. var s1 = minVersion.split('.');
  8085. var s2 = extVersion.split('.');
  8086. var len = Math.max(s1.length, s2.length);
  8087. for (var i = 0; i < len; i++)
  8088. {
  8089. var n1 = 0,
  8090. n2 = 0;
  8091. if (i < s1.length)
  8092. n1 = parseInt(s1[i]);
  8093. if (i < s2.length)
  8094. n2 = parseInt(s2[i]);
  8095. if (isNaN(n1) || isNaN(n2))
  8096. {
  8097. return true;
  8098. }
  8099. else if (n1 !== n2)
  8100. {
  8101. return n1 > n2;
  8102. }
  8103. }
  8104. // will happen if boths version has identical numbers in
  8105. // their components (even if one of them is longer, has more components)
  8106. return false;
  8107. }
  8108. catch (e)
  8109. {
  8110. console.error("Failed to parse extension version", e);
  8111. APP.UI.messageHandler.showError("dialog.error",
  8112. "dialog.detectext");
  8113. return true;
  8114. }
  8115. }
  8116. function checkExtInstalled(callback) {
  8117. if (!chrome.runtime) {
  8118. // No API, so no extension for sure
  8119. callback(false, false);
  8120. return;
  8121. }
  8122. chrome.runtime.sendMessage(
  8123. config.chromeExtensionId,
  8124. { getVersion: true },
  8125. function (response) {
  8126. if (!response || !response.version) {
  8127. // Communication failure - assume that no endpoint exists
  8128. console.warn(
  8129. "Extension not installed?: ", chrome.runtime.lastError);
  8130. callback(false, false);
  8131. return;
  8132. }
  8133. // Check installed extension version
  8134. var extVersion = response.version;
  8135. console.log('Extension version is: ' + extVersion);
  8136. var updateRequired
  8137. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  8138. callback(!updateRequired, updateRequired);
  8139. }
  8140. );
  8141. }
  8142. function doGetStreamFromExtension(streamCallback, failCallback) {
  8143. // Sends 'getStream' msg to the extension.
  8144. // Extension id must be defined in the config.
  8145. chrome.runtime.sendMessage(
  8146. config.chromeExtensionId,
  8147. { getStream: true, sources: config.desktopSharingSources },
  8148. function (response) {
  8149. if (!response) {
  8150. failCallback(chrome.runtime.lastError);
  8151. return;
  8152. }
  8153. console.log("Response from extension: " + response);
  8154. if (response.streamId) {
  8155. APP.RTC.getUserMediaWithConstraints(
  8156. ['desktop'],
  8157. function (stream) {
  8158. streamCallback(stream);
  8159. },
  8160. failCallback,
  8161. null, null, null,
  8162. response.streamId);
  8163. } else {
  8164. failCallback("Extension failed to get the stream");
  8165. }
  8166. }
  8167. );
  8168. }
  8169. /**
  8170. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  8171. * stream for returned stream token.
  8172. */
  8173. function obtainScreenFromExtension(streamCallback, failCallback) {
  8174. if (extInstalled) {
  8175. doGetStreamFromExtension(streamCallback, failCallback);
  8176. } else {
  8177. if (extUpdateRequired) {
  8178. alert(
  8179. 'Jitsi Desktop Streamer requires update. ' +
  8180. 'Changes will take effect after next Chrome restart.');
  8181. }
  8182. chrome.webstore.install(
  8183. getWebStoreInstallUrl(),
  8184. function (arg) {
  8185. console.log("Extension installed successfully", arg);
  8186. // We need to reload the page in order to get the access to
  8187. // chrome.runtime
  8188. window.location.reload(false);
  8189. },
  8190. function (arg) {
  8191. console.log("Failed to install the extension", arg);
  8192. failCallback(arg);
  8193. APP.UI.messageHandler.showError("dialog.error",
  8194. "dialog.failtoinstall");
  8195. }
  8196. );
  8197. }
  8198. }
  8199. /**
  8200. * Call this method to toggle desktop sharing feature.
  8201. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  8202. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  8203. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  8204. * enabled), pass any other string or nothing in order to disable this
  8205. * feature completely.
  8206. */
  8207. function setDesktopSharing(method) {
  8208. // Check if we are running chrome
  8209. if (!navigator.webkitGetUserMedia) {
  8210. obtainDesktopStream = null;
  8211. console.info("Desktop sharing disabled");
  8212. } else if (method == "ext") {
  8213. obtainDesktopStream = obtainScreenFromExtension;
  8214. console.info("Using Chrome extension for desktop sharing");
  8215. } else if (method == "webrtc") {
  8216. obtainDesktopStream = obtainWebRTCScreen;
  8217. console.info("Using Chrome WebRTC for desktop sharing");
  8218. }
  8219. // Reset enabled cache
  8220. _desktopSharingEnabled = null;
  8221. }
  8222. /**
  8223. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  8224. * config.js to support inline installs. Host site must be selected as main
  8225. * website of published extension.
  8226. */
  8227. function initInlineInstalls()
  8228. {
  8229. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  8230. }
  8231. function getSwitchStreamFailed(error) {
  8232. console.error("Failed to obtain the stream to switch to", error);
  8233. switchInProgress = false;
  8234. isUsingScreenStream = false;
  8235. newStreamCreated(null);
  8236. }
  8237. function streamSwitchDone() {
  8238. switchInProgress = false;
  8239. eventEmitter.emit(
  8240. DesktopSharingEventTypes.SWITCHING_DONE,
  8241. isUsingScreenStream);
  8242. }
  8243. function newStreamCreated(stream)
  8244. {
  8245. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  8246. stream, isUsingScreenStream, streamSwitchDone);
  8247. }
  8248. module.exports = {
  8249. isUsingScreenStream: function () {
  8250. return isUsingScreenStream;
  8251. },
  8252. /**
  8253. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  8254. * and enabled.
  8255. */
  8256. isDesktopSharingEnabled: function () {
  8257. if (_desktopSharingEnabled === null) {
  8258. if (obtainDesktopStream === obtainScreenFromExtension) {
  8259. // Parse chrome version
  8260. var userAgent = navigator.userAgent.toLowerCase();
  8261. // We can assume that user agent is chrome, because it's
  8262. // enforced when 'ext' streaming method is set
  8263. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  8264. console.log("Chrome version" + userAgent, ver);
  8265. _desktopSharingEnabled = ver >= 34;
  8266. } else {
  8267. _desktopSharingEnabled =
  8268. obtainDesktopStream === obtainWebRTCScreen;
  8269. }
  8270. }
  8271. return _desktopSharingEnabled;
  8272. },
  8273. init: function () {
  8274. setDesktopSharing(config.desktopSharing);
  8275. // Initialize Chrome extension inline installs
  8276. if (config.chromeExtensionId) {
  8277. initInlineInstalls();
  8278. // Check if extension is installed
  8279. checkExtInstalled(function (installed, updateRequired) {
  8280. extInstalled = installed;
  8281. extUpdateRequired = updateRequired;
  8282. console.info(
  8283. "Chrome extension installed: " + extInstalled +
  8284. " updateRequired: " + extUpdateRequired);
  8285. });
  8286. }
  8287. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  8288. },
  8289. addListener: function (listener, type)
  8290. {
  8291. eventEmitter.on(type, listener);
  8292. },
  8293. removeListener: function (listener, type) {
  8294. eventEmitter.removeListener(type, listener);
  8295. },
  8296. /*
  8297. * Toggles screen sharing.
  8298. */
  8299. toggleScreenSharing: function () {
  8300. if (switchInProgress || !obtainDesktopStream) {
  8301. console.warn("Switch in progress or no method defined");
  8302. return;
  8303. }
  8304. switchInProgress = true;
  8305. if (!isUsingScreenStream)
  8306. {
  8307. // Switch to desktop stream
  8308. obtainDesktopStream(
  8309. function (stream) {
  8310. // We now use screen stream
  8311. isUsingScreenStream = true;
  8312. // Hook 'ended' event to restore camera
  8313. // when screen stream stops
  8314. stream.addEventListener('ended',
  8315. function (e) {
  8316. if (!switchInProgress && isUsingScreenStream) {
  8317. APP.desktopsharing.toggleScreenSharing();
  8318. }
  8319. }
  8320. );
  8321. newStreamCreated(stream);
  8322. },
  8323. getSwitchStreamFailed);
  8324. } else {
  8325. // Disable screen stream
  8326. APP.RTC.getUserMediaWithConstraints(
  8327. ['video'],
  8328. function (stream) {
  8329. // We are now using camera stream
  8330. isUsingScreenStream = false;
  8331. newStreamCreated(stream);
  8332. },
  8333. getSwitchStreamFailed, config.resolution || '360'
  8334. );
  8335. }
  8336. }
  8337. };
  8338. },{"../../service/desktopsharing/DesktopSharingEventTypes":95,"events":98}],37:[function(require,module,exports){
  8339. //maps keycode to character, id of popover for given function and function
  8340. var shortcuts = {
  8341. 67: {
  8342. character: "C",
  8343. id: "toggleChatPopover",
  8344. function: APP.UI.toggleChat
  8345. },
  8346. 70: {
  8347. character: "F",
  8348. id: "filmstripPopover",
  8349. function: APP.UI.toggleFilmStrip
  8350. },
  8351. 77: {
  8352. character: "M",
  8353. id: "mutePopover",
  8354. function: APP.UI.toggleAudio
  8355. },
  8356. 84: {
  8357. character: "T",
  8358. function: function() {
  8359. if(!APP.RTC.localAudio.isMuted()) {
  8360. APP.UI.toggleAudio();
  8361. }
  8362. }
  8363. },
  8364. 86: {
  8365. character: "V",
  8366. id: "toggleVideoPopover",
  8367. function: APP.UI.toggleVideo
  8368. }
  8369. };
  8370. var KeyboardShortcut = {
  8371. init: function () {
  8372. window.onkeyup = function(e) {
  8373. var keycode = e.which;
  8374. if(!($(":focus").is("input[type=text]") ||
  8375. $(":focus").is("input[type=password]") ||
  8376. $(":focus").is("textarea"))) {
  8377. if (typeof shortcuts[keycode] === "object") {
  8378. shortcuts[keycode].function();
  8379. }
  8380. else if (keycode >= "0".charCodeAt(0) &&
  8381. keycode <= "9".charCodeAt(0)) {
  8382. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8383. }
  8384. //esc while the smileys are visible hides them
  8385. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8386. APP.UI.toggleSmileys();
  8387. }
  8388. };
  8389. window.onkeydown = function(e) {
  8390. if(!($(":focus").is("input[type=text]") ||
  8391. $(":focus").is("input[type=password]") ||
  8392. $(":focus").is("textarea"))) {
  8393. if(e.which === "T".charCodeAt(0)) {
  8394. if(APP.RTC.localAudio.isMuted()) {
  8395. APP.UI.toggleAudio();
  8396. }
  8397. }
  8398. }
  8399. };
  8400. var self = this;
  8401. $('body').popover({ selector: '[data-toggle=popover]',
  8402. trigger: 'click hover',
  8403. content: function() {
  8404. return this.getAttribute("content") +
  8405. self.getShortcut(this.getAttribute("shortcut"));
  8406. }
  8407. });
  8408. },
  8409. /**
  8410. *
  8411. * @param id indicates the popover associated with the shortcut
  8412. * @returns {string} the keyboard shortcut used for the id given
  8413. */
  8414. getShortcut: function (id) {
  8415. for (var keycode in shortcuts) {
  8416. if (shortcuts.hasOwnProperty(keycode)) {
  8417. if (shortcuts[keycode].id === id) {
  8418. return " (" + shortcuts[keycode].character + ")";
  8419. }
  8420. }
  8421. }
  8422. return "";
  8423. }
  8424. };
  8425. module.exports = KeyboardShortcut;
  8426. },{}],38:[function(require,module,exports){
  8427. var email = '';
  8428. var displayName = '';
  8429. var userId;
  8430. var language = null;
  8431. function supportsLocalStorage() {
  8432. try {
  8433. return 'localStorage' in window && window.localStorage !== null;
  8434. } catch (e) {
  8435. console.log("localstorage is not supported");
  8436. return false;
  8437. }
  8438. }
  8439. function generateUniqueId() {
  8440. function _p8() {
  8441. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8442. }
  8443. return _p8() + _p8() + _p8() + _p8();
  8444. }
  8445. if (supportsLocalStorage()) {
  8446. if (!window.localStorage.jitsiMeetId) {
  8447. window.localStorage.jitsiMeetId = generateUniqueId();
  8448. console.log("generated id", window.localStorage.jitsiMeetId);
  8449. }
  8450. userId = window.localStorage.jitsiMeetId || '';
  8451. email = window.localStorage.email || '';
  8452. displayName = window.localStorage.displayname || '';
  8453. language = window.localStorage.language;
  8454. } else {
  8455. console.log("local storage is not supported");
  8456. userId = generateUniqueId();
  8457. }
  8458. var Settings =
  8459. {
  8460. setDisplayName: function (newDisplayName) {
  8461. displayName = newDisplayName;
  8462. window.localStorage.displayname = displayName;
  8463. return displayName;
  8464. },
  8465. setEmail: function (newEmail)
  8466. {
  8467. email = newEmail;
  8468. window.localStorage.email = newEmail;
  8469. return email;
  8470. },
  8471. getSettings: function () {
  8472. return {
  8473. email: email,
  8474. displayName: displayName,
  8475. uid: userId,
  8476. language: language
  8477. };
  8478. },
  8479. setLanguage: function (lang) {
  8480. language = lang;
  8481. window.localStorage.language = lang;
  8482. }
  8483. };
  8484. module.exports = Settings;
  8485. },{}],39:[function(require,module,exports){
  8486. /**
  8487. *
  8488. * @constructor
  8489. */
  8490. function SimulcastLogger(name, lvl) {
  8491. this.name = name;
  8492. this.lvl = lvl;
  8493. }
  8494. SimulcastLogger.prototype.log = function (text) {
  8495. if (this.lvl) {
  8496. console.log(text);
  8497. }
  8498. };
  8499. SimulcastLogger.prototype.info = function (text) {
  8500. if (this.lvl > 1) {
  8501. console.info(text);
  8502. }
  8503. };
  8504. SimulcastLogger.prototype.fine = function (text) {
  8505. if (this.lvl > 2) {
  8506. console.log(text);
  8507. }
  8508. };
  8509. SimulcastLogger.prototype.error = function (text) {
  8510. console.error(text);
  8511. };
  8512. module.exports = SimulcastLogger;
  8513. },{}],40:[function(require,module,exports){
  8514. var SimulcastLogger = require("./SimulcastLogger");
  8515. var SimulcastUtils = require("./SimulcastUtils");
  8516. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  8517. function SimulcastReceiver() {
  8518. this.simulcastUtils = new SimulcastUtils();
  8519. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  8520. }
  8521. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  8522. SimulcastReceiver.prototype._remoteMaps = {
  8523. msid2Quality: {},
  8524. ssrc2Msid: {},
  8525. msid2ssrc: {},
  8526. receivingVideoStreams: {}
  8527. };
  8528. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  8529. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8530. };
  8531. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  8532. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  8533. };
  8534. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  8535. var sb;
  8536. this.logger.info('Ensuring x-google-conference flag...')
  8537. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8538. // TODO(gp) do that for the audio as well as suggested by fippo.
  8539. // Add the google conference flag
  8540. sb = this.simulcastUtils._getVideoSources(lines);
  8541. sb = ['a=x-google-flag:conference'].concat(sb);
  8542. this.simulcastUtils._replaceVideoSources(lines, sb);
  8543. }
  8544. };
  8545. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  8546. this._restoreRemoteVideoSources(sb);
  8547. };
  8548. /**
  8549. * Restores the simulcast groups of the remote description. In
  8550. * transformRemoteDescription we remove those in order for the set remote
  8551. * description to succeed. The focus needs the signal the groups to new
  8552. * participants.
  8553. *
  8554. * @param desc
  8555. * @returns {*}
  8556. */
  8557. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  8558. var sb;
  8559. if (!this.simulcastUtils.isValidDescription(desc)) {
  8560. return desc;
  8561. }
  8562. if (config.enableSimulcast) {
  8563. sb = desc.sdp.split('\r\n');
  8564. this._restoreSimulcastGroups(sb);
  8565. desc = new RTCSessionDescription({
  8566. type: desc.type,
  8567. sdp: sb.join('\r\n')
  8568. });
  8569. }
  8570. return desc;
  8571. };
  8572. SimulcastUtils.prototype._ensureOrder = function (lines) {
  8573. var videoSources, sb;
  8574. videoSources = this.parseMedia(lines, ['video'])[0];
  8575. sb = this._compileVideoSources(videoSources);
  8576. this._replaceVideoSources(lines, sb);
  8577. };
  8578. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  8579. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  8580. videoSource, quality;
  8581. // (re) initialize the remote maps.
  8582. this._remoteMaps.msid2Quality = {};
  8583. this._remoteMaps.ssrc2Msid = {};
  8584. this._remoteMaps.msid2ssrc = {};
  8585. var self = this;
  8586. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  8587. remoteVideoSources.groups.forEach(function (group) {
  8588. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  8589. quality = 0;
  8590. group.ssrcs.forEach(function (ssrc) {
  8591. videoSource = remoteVideoSources.sources[ssrc];
  8592. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  8593. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  8594. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  8595. });
  8596. }
  8597. });
  8598. }
  8599. };
  8600. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  8601. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  8602. };
  8603. /**
  8604. * Returns a stream with single video track, the one currently being
  8605. * received by this endpoint.
  8606. *
  8607. * @param stream the remote simulcast stream.
  8608. * @returns {webkitMediaStream}
  8609. */
  8610. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  8611. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  8612. var self = this;
  8613. if (config.enableSimulcast) {
  8614. stream.getVideoTracks().some(function (track) {
  8615. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  8616. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  8617. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  8618. if (msid == [stream.id, track.id].join(' ')) {
  8619. electedTrack = track;
  8620. return true;
  8621. }
  8622. });
  8623. });
  8624. if (!electedTrack) {
  8625. // we don't have an elected track, choose by initial quality.
  8626. tracks = stream.getVideoTracks();
  8627. for (i = 0; i < tracks.length; i++) {
  8628. msid = [stream.id, tracks[i].id].join(' ');
  8629. if (this._remoteMaps.msid2Quality[msid] === quality) {
  8630. electedTrack = tracks[i];
  8631. break;
  8632. }
  8633. }
  8634. // TODO(gp) if the initialQuality could not be satisfied, lower
  8635. // the requirement and try again.
  8636. }
  8637. }
  8638. return (electedTrack)
  8639. ? new webkitMediaStream([electedTrack])
  8640. : stream;
  8641. };
  8642. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  8643. var resource = Strophe.getResourceFromJid(jid);
  8644. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  8645. // If we haven't receiving a "changed" event yet, then we must be receiving
  8646. // low quality (that the sender always streams).
  8647. if(!ssrc)
  8648. {
  8649. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8650. var remoteStream = remoteStreamObject.getOriginalStream();
  8651. var tracks = remoteStream.getVideoTracks();
  8652. if (tracks) {
  8653. for (var k = 0; k < tracks.length; k++) {
  8654. var track = tracks[k];
  8655. var msid = [remoteStream.id, track.id].join(' ');
  8656. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  8657. var quality = this._remoteMaps.msid2Quality[msid];
  8658. if (quality == 0) {
  8659. ssrc = _ssrc;
  8660. }
  8661. }
  8662. }
  8663. }
  8664. return ssrc;
  8665. };
  8666. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  8667. {
  8668. var sid, electedStream;
  8669. var i, j, k;
  8670. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  8671. if(jid && APP.RTC.remoteStreams[jid])
  8672. {
  8673. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8674. var remoteStream = remoteStreamObject.getOriginalStream();
  8675. var tracks = remoteStream.getVideoTracks();
  8676. if (tracks) {
  8677. for (k = 0; k < tracks.length; k++) {
  8678. var track = tracks[k];
  8679. var msid = [remoteStream.id, track.id].join(' ');
  8680. var tmp = this._remoteMaps.msid2ssrc[msid];
  8681. if (tmp == ssrc) {
  8682. electedStream = new webkitMediaStream([track]);
  8683. sid = remoteStreamObject.sid;
  8684. // stream found, stop.
  8685. break;
  8686. }
  8687. }
  8688. }
  8689. }
  8690. else
  8691. {
  8692. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  8693. }
  8694. return {
  8695. sid: sid,
  8696. stream: electedStream
  8697. };
  8698. };
  8699. /**
  8700. * Gets the fully qualified msid (stream.id + track.id) associated to the
  8701. * SSRC.
  8702. *
  8703. * @param ssrc
  8704. * @returns {*}
  8705. */
  8706. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  8707. return this._remoteMaps.ssrc2Msid[ssrc];
  8708. };
  8709. /**
  8710. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  8711. * either gets confused and thinks this is an FID group or, if an FID group
  8712. * is already present, it fails to set the remote description.
  8713. *
  8714. * @param desc
  8715. * @returns {*}
  8716. */
  8717. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  8718. if (desc && desc.sdp) {
  8719. var sb = desc.sdp.split('\r\n');
  8720. this._updateRemoteMaps(sb);
  8721. this._cacheRemoteVideoSources(sb);
  8722. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  8723. // need the simulcast group in the _updateRemoteMaps() method.
  8724. this.simulcastUtils._removeSimulcastGroup(sb);
  8725. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  8726. // We don't need the goog conference flag if we're not doing
  8727. // simulcast.
  8728. this._ensureGoogConference(sb);
  8729. }
  8730. desc = new RTCSessionDescription({
  8731. type: desc.type,
  8732. sdp: sb.join('\r\n')
  8733. });
  8734. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  8735. }
  8736. return desc;
  8737. };
  8738. module.exports = SimulcastReceiver;
  8739. },{"../../service/RTC/MediaStreamTypes":87,"./SimulcastLogger":39,"./SimulcastUtils":42}],41:[function(require,module,exports){
  8740. var SimulcastLogger = require("./SimulcastLogger");
  8741. var SimulcastUtils = require("./SimulcastUtils");
  8742. function SimulcastSender() {
  8743. this.simulcastUtils = new SimulcastUtils();
  8744. this.logger = new SimulcastLogger('SimulcastSender', 1);
  8745. }
  8746. SimulcastSender.prototype.displayedLocalVideoStream = null;
  8747. SimulcastSender.prototype._generateGuid = (function () {
  8748. function s4() {
  8749. return Math.floor((1 + Math.random()) * 0x10000)
  8750. .toString(16)
  8751. .substring(1);
  8752. }
  8753. return function () {
  8754. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  8755. s4() + '-' + s4() + s4() + s4();
  8756. };
  8757. }());
  8758. // Returns a random integer between min (included) and max (excluded)
  8759. // Using Math.round() gives a non-uniform distribution!
  8760. SimulcastSender.prototype._generateRandomSSRC = function () {
  8761. var min = 0, max = 0xffffffff;
  8762. return Math.floor(Math.random() * (max - min)) + min;
  8763. };
  8764. SimulcastSender.prototype.getLocalVideoStream = function () {
  8765. return (this.displayedLocalVideoStream != null)
  8766. ? this.displayedLocalVideoStream
  8767. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  8768. : APP.RTC.localVideo.getOriginalStream();
  8769. };
  8770. function NativeSimulcastSender() {
  8771. SimulcastSender.call(this); // call the super constructor.
  8772. }
  8773. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8774. NativeSimulcastSender.prototype._localExplosionMap = {};
  8775. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  8776. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  8777. NativeSimulcastSender.prototype.reset = function () {
  8778. this._localExplosionMap = {};
  8779. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  8780. };
  8781. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  8782. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8783. };
  8784. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  8785. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  8786. };
  8787. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  8788. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  8789. this.logger.info('Appending simulcast group...');
  8790. // Get the primary SSRC information.
  8791. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8792. // Start building the SIM SSRC group.
  8793. ssrcGroup = ['a=ssrc-group:SIM'];
  8794. // The video source buffer.
  8795. sb = [];
  8796. // Create the simulcast sub-streams.
  8797. for (i = 0; i < numOfSubs; i++) {
  8798. // TODO(gp) prevent SSRC collision.
  8799. simSSRC = this._generateRandomSSRC();
  8800. ssrcGroup.push(simSSRC);
  8801. if (videoSources.base) {
  8802. sb.splice.apply(sb, [sb.length, 0].concat(
  8803. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  8804. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  8805. ));
  8806. }
  8807. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  8808. }
  8809. // Add the group sim layers.
  8810. sb.splice(0, 0, ssrcGroup.join(' '))
  8811. this.simulcastUtils._replaceVideoSources(lines, sb);
  8812. };
  8813. // Does the actual patching.
  8814. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  8815. this.logger.info('Ensuring simulcast group...');
  8816. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8817. this._appendSimulcastGroup(lines);
  8818. this._cacheLocalVideoSources(lines);
  8819. } else {
  8820. // verify that the ssrcs participating in the SIM group are present
  8821. // in the SDP (needed for presence).
  8822. this._restoreLocalVideoSources(lines);
  8823. }
  8824. };
  8825. /**
  8826. * Produces a single stream with multiple tracks for local video sources.
  8827. *
  8828. * @param lines
  8829. * @private
  8830. */
  8831. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  8832. var sb, msid, sid, tid, videoSources, self;
  8833. this.logger.info('Exploding local video sources...');
  8834. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8835. self = this;
  8836. if (videoSources.groups && videoSources.groups.length !== 0) {
  8837. videoSources.groups.forEach(function (group) {
  8838. if (group.semantics === 'SIM') {
  8839. group.ssrcs.forEach(function (ssrc) {
  8840. // Get the msid for this ssrc..
  8841. if (self._localExplosionMap[ssrc]) {
  8842. // .. either from the explosion map..
  8843. msid = self._localExplosionMap[ssrc];
  8844. } else {
  8845. // .. or generate a new one (msid).
  8846. sid = videoSources.sources[ssrc].msid
  8847. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  8848. tid = self._generateGuid();
  8849. msid = [sid, tid].join(' ');
  8850. self._localExplosionMap[ssrc] = msid;
  8851. }
  8852. // Assign it to the source object.
  8853. videoSources.sources[ssrc].msid = msid;
  8854. // TODO(gp) Change the msid of associated sources.
  8855. });
  8856. }
  8857. });
  8858. }
  8859. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8860. this.simulcastUtils._replaceVideoSources(lines, sb);
  8861. };
  8862. /**
  8863. * GUM for simulcast.
  8864. *
  8865. * @param constraints
  8866. * @param success
  8867. * @param err
  8868. */
  8869. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8870. // There's nothing special to do for native simulcast, so just do a normal GUM.
  8871. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8872. success(hqStream);
  8873. }, err);
  8874. };
  8875. /**
  8876. * Prepares the local description for public usage (i.e. to be signaled
  8877. * through Jingle to the focus).
  8878. *
  8879. * @param desc
  8880. * @returns {RTCSessionDescription}
  8881. */
  8882. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8883. var sb;
  8884. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8885. return desc;
  8886. }
  8887. sb = desc.sdp.split('\r\n');
  8888. this._explodeSimulcastSenderSources(sb);
  8889. desc = new RTCSessionDescription({
  8890. type: desc.type,
  8891. sdp: sb.join('\r\n')
  8892. });
  8893. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  8894. return desc;
  8895. };
  8896. /**
  8897. * Ensures that the simulcast group is present in the answer, _if_ native
  8898. * simulcast is enabled,
  8899. *
  8900. * @param desc
  8901. * @returns {*}
  8902. */
  8903. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  8904. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8905. return desc;
  8906. }
  8907. var sb = desc.sdp.split('\r\n');
  8908. // Even if we have enabled native simulcasting previously
  8909. // (with a call to SLD with an appropriate SDP, for example),
  8910. // createAnswer seems to consistently generate incomplete SDP
  8911. // with missing SSRCS.
  8912. //
  8913. // So, subsequent calls to SLD will have missing SSRCS and presence
  8914. // won't have the complete list of SRCs.
  8915. this._ensureSimulcastGroup(sb);
  8916. desc = new RTCSessionDescription({
  8917. type: desc.type,
  8918. sdp: sb.join('\r\n')
  8919. });
  8920. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  8921. return desc;
  8922. };
  8923. /**
  8924. *
  8925. *
  8926. * @param desc
  8927. * @returns {*}
  8928. */
  8929. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8930. return desc;
  8931. };
  8932. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8933. // Nothing to do here, native simulcast does that auto-magically.
  8934. };
  8935. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  8936. function SimpleSimulcastSender() {
  8937. SimulcastSender.call(this);
  8938. }
  8939. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8940. SimpleSimulcastSender.prototype.localStream = null;
  8941. SimpleSimulcastSender.prototype._localMaps = {
  8942. msids: [],
  8943. msid2ssrc: {}
  8944. };
  8945. /**
  8946. * Groups local video sources together in the ssrc-group:SIM group.
  8947. *
  8948. * @param lines
  8949. * @private
  8950. */
  8951. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  8952. var sb, videoSources, ssrcs = [], ssrc;
  8953. this.logger.info('Grouping local video sources...');
  8954. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8955. for (ssrc in videoSources.sources) {
  8956. // jitsi-meet destroys/creates streams at various places causing
  8957. // the original local stream ids to change. The only thing that
  8958. // remains unchanged is the trackid.
  8959. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  8960. }
  8961. var self = this;
  8962. // TODO(gp) add only "free" sources.
  8963. this._localMaps.msids.forEach(function (msid) {
  8964. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  8965. });
  8966. if (!videoSources.groups) {
  8967. videoSources.groups = [];
  8968. }
  8969. videoSources.groups.push({
  8970. 'semantics': 'SIM',
  8971. 'ssrcs': ssrcs
  8972. });
  8973. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8974. this.simulcastUtils._replaceVideoSources(lines, sb);
  8975. };
  8976. /**
  8977. * GUM for simulcast.
  8978. *
  8979. * @param constraints
  8980. * @param success
  8981. * @param err
  8982. */
  8983. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8984. // TODO(gp) what if we request a resolution not supported by the hardware?
  8985. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  8986. var lqConstraints = {
  8987. audio: false,
  8988. video: {
  8989. mandatory: {
  8990. maxWidth: 320,
  8991. maxHeight: 180,
  8992. maxFrameRate: 15
  8993. }
  8994. }
  8995. };
  8996. this.logger.info('HQ constraints: ', constraints);
  8997. this.logger.info('LQ constraints: ', lqConstraints);
  8998. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  8999. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  9000. // reason appears to be that Chrome only acquires the cam once and
  9001. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  9002. var self = this;
  9003. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9004. self.localStream = hqStream;
  9005. // reset local maps.
  9006. self._localMaps.msids = [];
  9007. self._localMaps.msid2ssrc = {};
  9008. // add hq trackid to local map
  9009. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  9010. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  9011. self.displayedLocalVideoStream = lqStream;
  9012. // NOTE(gp) The specification says Array.forEach() will visit
  9013. // the array elements in numeric order, and that it doesn't
  9014. // visit elements that don't exist.
  9015. // add lq trackid to local map
  9016. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  9017. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  9018. success(self.localStream);
  9019. }, err);
  9020. }, err);
  9021. };
  9022. /**
  9023. * Prepares the local description for public usage (i.e. to be signaled
  9024. * through Jingle to the focus).
  9025. *
  9026. * @param desc
  9027. * @returns {RTCSessionDescription}
  9028. */
  9029. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9030. var sb;
  9031. if (!this.simulcastUtils.isValidDescription(desc)) {
  9032. return desc;
  9033. }
  9034. sb = desc.sdp.split('\r\n');
  9035. this._groupLocalVideoSources(sb);
  9036. desc = new RTCSessionDescription({
  9037. type: desc.type,
  9038. sdp: sb.join('\r\n')
  9039. });
  9040. this.logger.fine('Grouped local video sources');
  9041. this.logger.fine(desc.sdp);
  9042. return desc;
  9043. };
  9044. /**
  9045. * Ensures that the simulcast group is present in the answer, _if_ native
  9046. * simulcast is enabled,
  9047. *
  9048. * @param desc
  9049. * @returns {*}
  9050. */
  9051. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  9052. return desc;
  9053. };
  9054. /**
  9055. *
  9056. *
  9057. * @param desc
  9058. * @returns {*}
  9059. */
  9060. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9061. var sb = desc.sdp.split('\r\n');
  9062. this.simulcastUtils._removeSimulcastGroup(sb);
  9063. desc = new RTCSessionDescription({
  9064. type: desc.type,
  9065. sdp: sb.join('\r\n')
  9066. });
  9067. this.logger.fine('Transformed local description');
  9068. this.logger.fine(desc.sdp);
  9069. return desc;
  9070. };
  9071. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9072. var trackid;
  9073. var self = this;
  9074. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  9075. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  9076. // Search for the track id that corresponds to the ssrc
  9077. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  9078. trackid = tid;
  9079. return true;
  9080. }
  9081. }) && self.localStream.getVideoTracks().some(function (track) {
  9082. // Start/stop the track that corresponds to the track id
  9083. if (track.id === trackid) {
  9084. track.enabled = enabled;
  9085. return true;
  9086. }
  9087. })) {
  9088. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  9089. $(document).trigger(enabled
  9090. ? 'simulcastlayerstarted'
  9091. : 'simulcastlayerstopped');
  9092. } else {
  9093. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  9094. }
  9095. };
  9096. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  9097. function NoSimulcastSender() {
  9098. SimulcastSender.call(this);
  9099. }
  9100. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9101. /**
  9102. * GUM for simulcast.
  9103. *
  9104. * @param constraints
  9105. * @param success
  9106. * @param err
  9107. */
  9108. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9109. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9110. success(hqStream);
  9111. }, err);
  9112. };
  9113. /**
  9114. * Prepares the local description for public usage (i.e. to be signaled
  9115. * through Jingle to the focus).
  9116. *
  9117. * @param desc
  9118. * @returns {RTCSessionDescription}
  9119. */
  9120. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9121. return desc;
  9122. };
  9123. /**
  9124. * Ensures that the simulcast group is present in the answer, _if_ native
  9125. * simulcast is enabled,
  9126. *
  9127. * @param desc
  9128. * @returns {*}
  9129. */
  9130. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  9131. return desc;
  9132. };
  9133. /**
  9134. *
  9135. *
  9136. * @param desc
  9137. * @returns {*}
  9138. */
  9139. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9140. return desc;
  9141. };
  9142. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9143. };
  9144. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  9145. module.exports = {
  9146. "native": NativeSimulcastSender,
  9147. "no": NoSimulcastSender
  9148. }
  9149. },{"./SimulcastLogger":39,"./SimulcastUtils":42}],42:[function(require,module,exports){
  9150. var SimulcastLogger = require("./SimulcastLogger");
  9151. /**
  9152. *
  9153. * @constructor
  9154. */
  9155. function SimulcastUtils() {
  9156. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  9157. }
  9158. /**
  9159. *
  9160. * @type {{}}
  9161. * @private
  9162. */
  9163. SimulcastUtils.prototype._emptyCompoundIndex = {};
  9164. /**
  9165. *
  9166. * @param lines
  9167. * @param videoSources
  9168. * @private
  9169. */
  9170. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  9171. var i, inVideo = false, index = -1, howMany = 0;
  9172. this.logger.info('Replacing video sources...');
  9173. for (i = 0; i < lines.length; i++) {
  9174. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9175. // Out of video.
  9176. break;
  9177. }
  9178. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9179. // In video.
  9180. inVideo = true;
  9181. }
  9182. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  9183. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  9184. if (index === -1) {
  9185. index = i;
  9186. }
  9187. howMany++;
  9188. }
  9189. }
  9190. // efficiency baby ;)
  9191. lines.splice.apply(lines,
  9192. [index, howMany].concat(videoSources));
  9193. };
  9194. SimulcastUtils.prototype.isValidDescription = function (desc)
  9195. {
  9196. return desc && desc != null
  9197. && desc.type && desc.type != ''
  9198. && desc.sdp && desc.sdp != '';
  9199. };
  9200. SimulcastUtils.prototype._getVideoSources = function (lines) {
  9201. var i, inVideo = false, sb = [];
  9202. this.logger.info('Getting video sources...');
  9203. for (i = 0; i < lines.length; i++) {
  9204. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9205. // Out of video.
  9206. break;
  9207. }
  9208. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9209. // In video.
  9210. inVideo = true;
  9211. }
  9212. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9213. // In SSRC.
  9214. sb.push(lines[i]);
  9215. }
  9216. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9217. sb.push(lines[i]);
  9218. }
  9219. }
  9220. return sb;
  9221. };
  9222. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  9223. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  9224. ssrc_attribute, group, semantics, skip = true;
  9225. this.logger.info('Parsing media sources...');
  9226. for (i = 0; i < lines.length; i++) {
  9227. if (lines[i].substring(0, 'm='.length) === 'm=') {
  9228. type = lines[i]
  9229. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  9230. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  9231. if (!skip) {
  9232. cur_media = {
  9233. 'type': type,
  9234. 'sources': {},
  9235. 'groups': []
  9236. };
  9237. res.push(cur_media);
  9238. }
  9239. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9240. idx = lines[i].indexOf(' ');
  9241. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  9242. if (cur_media.sources[ssrc] === undefined) {
  9243. cur_ssrc = {'ssrc': ssrc};
  9244. cur_media.sources[ssrc] = cur_ssrc;
  9245. }
  9246. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  9247. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  9248. if (cur_media.base === undefined) {
  9249. cur_media.base = cur_ssrc;
  9250. }
  9251. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9252. idx = lines[i].indexOf(' ');
  9253. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  9254. ssrcs = lines[i].substr(idx).trim().split(' ');
  9255. group = {
  9256. 'semantics': semantics,
  9257. 'ssrcs': ssrcs
  9258. };
  9259. cur_media.groups.push(group);
  9260. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  9261. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  9262. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  9263. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  9264. cur_media.direction = lines[i].substring('a='.length);
  9265. }
  9266. }
  9267. return res;
  9268. };
  9269. /**
  9270. * The _indexOfArray() method returns the first a CompoundIndex at which a
  9271. * given element can be found in the array, or _emptyCompoundIndex if it is
  9272. * not present.
  9273. *
  9274. * Example:
  9275. *
  9276. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  9277. *
  9278. * returns {row: 2, column: 14}
  9279. *
  9280. * @param needle
  9281. * @param haystack
  9282. * @param start
  9283. * @returns {}
  9284. * @private
  9285. */
  9286. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  9287. var length = haystack.length, idx, i;
  9288. if (!start) {
  9289. start = 0;
  9290. }
  9291. for (i = start; i < length; i++) {
  9292. idx = haystack[i].indexOf(needle);
  9293. if (idx !== -1) {
  9294. return {row: i, column: idx};
  9295. }
  9296. }
  9297. return this._emptyCompoundIndex;
  9298. };
  9299. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  9300. var i;
  9301. for (i = lines.length - 1; i >= 0; i--) {
  9302. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  9303. lines.splice(i, 1);
  9304. }
  9305. }
  9306. };
  9307. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  9308. var sb = [], ssrc, addedSSRCs = [];
  9309. this.logger.info('Compiling video sources...');
  9310. // Add the groups
  9311. if (videoSources.groups && videoSources.groups.length !== 0) {
  9312. videoSources.groups.forEach(function (group) {
  9313. if (group.ssrcs && group.ssrcs.length !== 0) {
  9314. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  9315. // if (group.semantics !== 'SIM') {
  9316. group.ssrcs.forEach(function (ssrc) {
  9317. addedSSRCs.push(ssrc);
  9318. sb.splice.apply(sb, [sb.length, 0].concat([
  9319. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9320. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9321. });
  9322. //}
  9323. }
  9324. });
  9325. }
  9326. // Then add any free sources.
  9327. if (videoSources.sources) {
  9328. for (ssrc in videoSources.sources) {
  9329. if (addedSSRCs.indexOf(ssrc) === -1) {
  9330. sb.splice.apply(sb, [sb.length, 0].concat([
  9331. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9332. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9333. }
  9334. }
  9335. }
  9336. return sb;
  9337. };
  9338. module.exports = SimulcastUtils;
  9339. },{"./SimulcastLogger":39}],43:[function(require,module,exports){
  9340. /*jslint plusplus: true */
  9341. /*jslint nomen: true*/
  9342. var SimulcastSender = require("./SimulcastSender");
  9343. var NoSimulcastSender = SimulcastSender["no"];
  9344. var NativeSimulcastSender = SimulcastSender["native"];
  9345. var SimulcastReceiver = require("./SimulcastReceiver");
  9346. var SimulcastUtils = require("./SimulcastUtils");
  9347. var RTCEvents = require("../../service/RTC/RTCEvents");
  9348. /**
  9349. *
  9350. * @constructor
  9351. */
  9352. function SimulcastManager() {
  9353. // Create the simulcast utilities.
  9354. this.simulcastUtils = new SimulcastUtils();
  9355. // Create remote simulcast.
  9356. this.simulcastReceiver = new SimulcastReceiver();
  9357. // Initialize local simulcast.
  9358. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  9359. // account constraints.
  9360. if (!config.enableSimulcast) {
  9361. this.simulcastSender = new NoSimulcastSender();
  9362. } else {
  9363. var isChromium = window.chrome,
  9364. vendorName = window.navigator.vendor;
  9365. if(isChromium !== null && isChromium !== undefined
  9366. /* skip opera */
  9367. && vendorName === "Google Inc."
  9368. /* skip Chromium as suggested by fippo */
  9369. && !window.navigator.appVersion.match(/Chromium\//) ) {
  9370. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  9371. if (ver > 37) {
  9372. this.simulcastSender = new NativeSimulcastSender();
  9373. } else {
  9374. this.simulcastSender = new NoSimulcastSender();
  9375. }
  9376. } else {
  9377. this.simulcastSender = new NoSimulcastSender();
  9378. }
  9379. }
  9380. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  9381. function (endpointSimulcastLayers) {
  9382. endpointSimulcastLayers.forEach(function (esl) {
  9383. var ssrc = esl.simulcastLayer.primarySSRC;
  9384. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  9385. });
  9386. });
  9387. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  9388. var ssrc = simulcastLayer.primarySSRC;
  9389. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  9390. });
  9391. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  9392. var ssrc = simulcastLayer.primarySSRC;
  9393. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  9394. });
  9395. }
  9396. /**
  9397. * Restores the simulcast groups of the remote description. In
  9398. * transformRemoteDescription we remove those in order for the set remote
  9399. * description to succeed. The focus needs the signal the groups to new
  9400. * participants.
  9401. *
  9402. * @param desc
  9403. * @returns {*}
  9404. */
  9405. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  9406. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  9407. };
  9408. /**
  9409. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9410. * either gets confused and thinks this is an FID group or, if an FID group
  9411. * is already present, it fails to set the remote description.
  9412. *
  9413. * @param desc
  9414. * @returns {*}
  9415. */
  9416. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  9417. return this.simulcastReceiver.transformRemoteDescription(desc);
  9418. };
  9419. /**
  9420. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9421. * SSRC.
  9422. *
  9423. * @param ssrc
  9424. * @returns {*}
  9425. */
  9426. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9427. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  9428. };
  9429. /**
  9430. * Returns a stream with single video track, the one currently being
  9431. * received by this endpoint.
  9432. *
  9433. * @param stream the remote simulcast stream.
  9434. * @returns {webkitMediaStream}
  9435. */
  9436. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  9437. return this.simulcastReceiver.getReceivingVideoStream(stream);
  9438. };
  9439. /**
  9440. *
  9441. *
  9442. * @param desc
  9443. * @returns {*}
  9444. */
  9445. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  9446. return this.simulcastSender.transformLocalDescription(desc);
  9447. };
  9448. /**
  9449. *
  9450. * @returns {*}
  9451. */
  9452. SimulcastManager.prototype.getLocalVideoStream = function() {
  9453. return this.simulcastSender.getLocalVideoStream();
  9454. };
  9455. /**
  9456. * GUM for simulcast.
  9457. *
  9458. * @param constraints
  9459. * @param success
  9460. * @param err
  9461. */
  9462. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  9463. this.simulcastSender.getUserMedia(constraints, success, err);
  9464. };
  9465. /**
  9466. * Prepares the local description for public usage (i.e. to be signaled
  9467. * through Jingle to the focus).
  9468. *
  9469. * @param desc
  9470. * @returns {RTCSessionDescription}
  9471. */
  9472. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  9473. return this.simulcastSender.reverseTransformLocalDescription(desc);
  9474. };
  9475. /**
  9476. * Ensures that the simulcast group is present in the answer, _if_ native
  9477. * simulcast is enabled,
  9478. *
  9479. * @param desc
  9480. * @returns {*}
  9481. */
  9482. SimulcastManager.prototype.transformAnswer = function (desc) {
  9483. return this.simulcastSender.transformAnswer(desc);
  9484. };
  9485. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  9486. return this.simulcastReceiver.getReceivingSSRC(jid);
  9487. };
  9488. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  9489. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  9490. };
  9491. /**
  9492. *
  9493. * @param lines
  9494. * @param mediatypes
  9495. * @returns {*}
  9496. */
  9497. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  9498. var sb = lines.sdp.split('\r\n');
  9499. return this.simulcastUtils.parseMedia(sb, mediatypes);
  9500. };
  9501. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  9502. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  9503. };
  9504. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  9505. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  9506. };
  9507. SimulcastManager.prototype.resetSender = function() {
  9508. if (typeof this.simulcastSender.reset === 'function'){
  9509. this.simulcastSender.reset();
  9510. }
  9511. };
  9512. var simulcast = new SimulcastManager();
  9513. module.exports = simulcast;
  9514. },{"../../service/RTC/RTCEvents":89,"./SimulcastReceiver":40,"./SimulcastSender":41,"./SimulcastUtils":42}],44:[function(require,module,exports){
  9515. /**
  9516. * Provides statistics for the local stream.
  9517. */
  9518. /**
  9519. * Size of the webaudio analizer buffer.
  9520. * @type {number}
  9521. */
  9522. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  9523. /**
  9524. * Value of the webaudio analizer smoothing time parameter.
  9525. * @type {number}
  9526. */
  9527. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  9528. /**
  9529. * Converts time domain data array to audio level.
  9530. * @param array the time domain data array.
  9531. * @returns {number} the audio level
  9532. */
  9533. function timeDomainDataToAudioLevel(samples) {
  9534. var maxVolume = 0;
  9535. var length = samples.length;
  9536. for (var i = 0; i < length; i++) {
  9537. if (maxVolume < samples[i])
  9538. maxVolume = samples[i];
  9539. }
  9540. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  9541. };
  9542. /**
  9543. * Animates audio level change
  9544. * @param newLevel the new audio level
  9545. * @param lastLevel the last audio level
  9546. * @returns {Number} the audio level to be set
  9547. */
  9548. function animateLevel(newLevel, lastLevel)
  9549. {
  9550. var value = 0;
  9551. var diff = lastLevel - newLevel;
  9552. if(diff > 0.2)
  9553. {
  9554. value = lastLevel - 0.2;
  9555. }
  9556. else if(diff < -0.4)
  9557. {
  9558. value = lastLevel + 0.4;
  9559. }
  9560. else
  9561. {
  9562. value = newLevel;
  9563. }
  9564. return parseFloat(value.toFixed(3));
  9565. }
  9566. /**
  9567. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  9568. *
  9569. * @param stream the local stream
  9570. * @param interval stats refresh interval given in ms.
  9571. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  9572. * update.
  9573. * @constructor
  9574. */
  9575. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  9576. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  9577. this.stream = stream;
  9578. this.intervalId = null;
  9579. this.intervalMilis = interval;
  9580. this.eventEmitter = eventEmitter;
  9581. this.audioLevel = 0;
  9582. this.statisticsService = statisticsService;
  9583. }
  9584. /**
  9585. * Starts the collecting the statistics.
  9586. */
  9587. LocalStatsCollector.prototype.start = function () {
  9588. if (config.disableAudioLevels || !window.AudioContext)
  9589. return;
  9590. var context = new AudioContext();
  9591. var analyser = context.createAnalyser();
  9592. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  9593. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  9594. var source = context.createMediaStreamSource(this.stream);
  9595. source.connect(analyser);
  9596. var self = this;
  9597. this.intervalId = setInterval(
  9598. function () {
  9599. var array = new Uint8Array(analyser.frequencyBinCount);
  9600. analyser.getByteTimeDomainData(array);
  9601. var audioLevel = timeDomainDataToAudioLevel(array);
  9602. if(audioLevel != self.audioLevel) {
  9603. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  9604. self.eventEmitter.emit(
  9605. "statistics.audioLevel",
  9606. self.statisticsService.LOCAL_JID,
  9607. self.audioLevel);
  9608. }
  9609. },
  9610. this.intervalMilis
  9611. );
  9612. };
  9613. /**
  9614. * Stops collecting the statistics.
  9615. */
  9616. LocalStatsCollector.prototype.stop = function () {
  9617. if (this.intervalId) {
  9618. clearInterval(this.intervalId);
  9619. this.intervalId = null;
  9620. }
  9621. };
  9622. module.exports = LocalStatsCollector;
  9623. },{}],45:[function(require,module,exports){
  9624. /* global ssrc2jid */
  9625. /* jshint -W117 */
  9626. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9627. /**
  9628. * Calculates packet lost percent using the number of lost packets and the
  9629. * number of all packet.
  9630. * @param lostPackets the number of lost packets
  9631. * @param totalPackets the number of all packets.
  9632. * @returns {number} packet loss percent
  9633. */
  9634. function calculatePacketLoss(lostPackets, totalPackets) {
  9635. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  9636. return 0;
  9637. return Math.round((lostPackets/totalPackets)*100);
  9638. }
  9639. function getStatValue(item, name) {
  9640. if(!keyMap[APP.RTC.getBrowserType()][name])
  9641. throw "The property isn't supported!";
  9642. var key = keyMap[APP.RTC.getBrowserType()][name];
  9643. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  9644. }
  9645. /**
  9646. * Peer statistics data holder.
  9647. * @constructor
  9648. */
  9649. function PeerStats()
  9650. {
  9651. this.ssrc2Loss = {};
  9652. this.ssrc2AudioLevel = {};
  9653. this.ssrc2bitrate = {};
  9654. this.ssrc2resolution = {};
  9655. }
  9656. /**
  9657. * The bandwidth
  9658. * @type {{}}
  9659. */
  9660. PeerStats.bandwidth = {};
  9661. /**
  9662. * The bit rate
  9663. * @type {{}}
  9664. */
  9665. PeerStats.bitrate = {};
  9666. /**
  9667. * The packet loss rate
  9668. * @type {{}}
  9669. */
  9670. PeerStats.packetLoss = null;
  9671. /**
  9672. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  9673. * represented by this instance.
  9674. * @param ssrc audio or video RTP stream SSRC.
  9675. * @param lossRate new packet loss rate value to be set.
  9676. */
  9677. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  9678. {
  9679. this.ssrc2Loss[ssrc] = lossRate;
  9680. };
  9681. /**
  9682. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  9683. * represented by this instance.
  9684. * @param ssrc audio or video RTP stream SSRC.
  9685. * @param resolution new resolution value to be set.
  9686. */
  9687. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  9688. {
  9689. if(resolution === null && this.ssrc2resolution[ssrc])
  9690. {
  9691. delete this.ssrc2resolution[ssrc];
  9692. }
  9693. else if(resolution !== null)
  9694. this.ssrc2resolution[ssrc] = resolution;
  9695. };
  9696. /**
  9697. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  9698. * represented by this instance.
  9699. * @param ssrc audio or video RTP stream SSRC.
  9700. * @param bitrate new bitrate value to be set.
  9701. */
  9702. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  9703. {
  9704. if(this.ssrc2bitrate[ssrc])
  9705. {
  9706. this.ssrc2bitrate[ssrc].download += bitrate.download;
  9707. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  9708. }
  9709. else {
  9710. this.ssrc2bitrate[ssrc] = bitrate;
  9711. }
  9712. };
  9713. /**
  9714. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  9715. * the stream which belongs to the peer represented by this instance.
  9716. * @param ssrc RTP stream SSRC for which current audio level value will be
  9717. * updated.
  9718. * @param audioLevel the new audio level value to be set. Value is truncated to
  9719. * fit the range from 0 to 1.
  9720. */
  9721. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  9722. {
  9723. // Range limit 0 - 1
  9724. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  9725. };
  9726. function formatAudioLevel(audioLevel) {
  9727. return Math.min(Math.max(audioLevel, 0), 1);
  9728. }
  9729. /**
  9730. * Array with the transport information.
  9731. * @type {Array}
  9732. */
  9733. PeerStats.transport = [];
  9734. /**
  9735. * <tt>StatsCollector</tt> registers for stats updates of given
  9736. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  9737. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  9738. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9739. * instance as an event source.
  9740. *
  9741. * @param peerconnection webRTC peer connection object.
  9742. * @param interval stats refresh interval given in ms.
  9743. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  9744. * called on stats update.
  9745. * @constructor
  9746. */
  9747. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  9748. {
  9749. this.peerconnection = peerconnection;
  9750. this.baselineAudioLevelsReport = null;
  9751. this.currentAudioLevelsReport = null;
  9752. this.currentStatsReport = null;
  9753. this.baselineStatsReport = null;
  9754. this.audioLevelsIntervalId = null;
  9755. this.eventEmitter = eventEmitter;
  9756. /**
  9757. * Gather PeerConnection stats once every this many milliseconds.
  9758. */
  9759. this.GATHER_INTERVAL = 15000;
  9760. /**
  9761. * Log stats via the focus once every this many milliseconds.
  9762. */
  9763. this.LOG_INTERVAL = 60000;
  9764. /**
  9765. * Gather stats and store them in this.statsToBeLogged.
  9766. */
  9767. this.gatherStatsIntervalId = null;
  9768. /**
  9769. * Send the stats already saved in this.statsToBeLogged to be logged via
  9770. * the focus.
  9771. */
  9772. this.logStatsIntervalId = null;
  9773. /**
  9774. * Stores the statistics which will be send to the focus to be logged.
  9775. */
  9776. this.statsToBeLogged =
  9777. {
  9778. timestamps: [],
  9779. stats: {}
  9780. };
  9781. // Updates stats interval
  9782. this.audioLevelsIntervalMilis = audioLevelsInterval;
  9783. this.statsIntervalId = null;
  9784. this.statsIntervalMilis = statsInterval;
  9785. // Map of jids to PeerStats
  9786. this.jid2stats = {};
  9787. }
  9788. module.exports = StatsCollector;
  9789. /**
  9790. * Stops stats updates.
  9791. */
  9792. StatsCollector.prototype.stop = function () {
  9793. if (this.audioLevelsIntervalId) {
  9794. clearInterval(this.audioLevelsIntervalId);
  9795. this.audioLevelsIntervalId = null;
  9796. }
  9797. if (this.statsIntervalId)
  9798. {
  9799. clearInterval(this.statsIntervalId);
  9800. this.statsIntervalId = null;
  9801. }
  9802. if(this.logStatsIntervalId)
  9803. {
  9804. clearInterval(this.logStatsIntervalId);
  9805. this.logStatsIntervalId = null;
  9806. }
  9807. if(this.gatherStatsIntervalId)
  9808. {
  9809. clearInterval(this.gatherStatsIntervalId);
  9810. this.gatherStatsIntervalId = null;
  9811. }
  9812. };
  9813. /**
  9814. * Callback passed to <tt>getStats</tt> method.
  9815. * @param error an error that occurred on <tt>getStats</tt> call.
  9816. */
  9817. StatsCollector.prototype.errorCallback = function (error)
  9818. {
  9819. console.error("Get stats error", error);
  9820. this.stop();
  9821. };
  9822. /**
  9823. * Starts stats updates.
  9824. */
  9825. StatsCollector.prototype.start = function ()
  9826. {
  9827. var self = this;
  9828. if(!config.disableAudioLevels) {
  9829. this.audioLevelsIntervalId = setInterval(
  9830. function () {
  9831. // Interval updates
  9832. self.peerconnection.getStats(
  9833. function (report) {
  9834. var results = null;
  9835. if (!report || !report.result ||
  9836. typeof report.result != 'function') {
  9837. results = report;
  9838. }
  9839. else {
  9840. results = report.result();
  9841. }
  9842. //console.error("Got interval report", results);
  9843. self.currentAudioLevelsReport = results;
  9844. self.processAudioLevelReport();
  9845. self.baselineAudioLevelsReport =
  9846. self.currentAudioLevelsReport;
  9847. },
  9848. self.errorCallback
  9849. );
  9850. },
  9851. self.audioLevelsIntervalMilis
  9852. );
  9853. }
  9854. if(!config.disableStats) {
  9855. this.statsIntervalId = setInterval(
  9856. function () {
  9857. // Interval updates
  9858. self.peerconnection.getStats(
  9859. function (report) {
  9860. var results = null;
  9861. if (!report || !report.result ||
  9862. typeof report.result != 'function') {
  9863. //firefox
  9864. results = report;
  9865. }
  9866. else {
  9867. //chrome
  9868. results = report.result();
  9869. }
  9870. //console.error("Got interval report", results);
  9871. self.currentStatsReport = results;
  9872. try {
  9873. self.processStatsReport();
  9874. }
  9875. catch (e) {
  9876. console.error("Unsupported key:" + e, e);
  9877. }
  9878. self.baselineStatsReport = self.currentStatsReport;
  9879. },
  9880. self.errorCallback
  9881. );
  9882. },
  9883. self.statsIntervalMilis
  9884. );
  9885. }
  9886. if (config.logStats) {
  9887. this.gatherStatsIntervalId = setInterval(
  9888. function () {
  9889. self.peerconnection.getStats(
  9890. function (report) {
  9891. self.addStatsToBeLogged(report.result());
  9892. },
  9893. function () {
  9894. }
  9895. );
  9896. },
  9897. this.GATHER_INTERVAL
  9898. );
  9899. this.logStatsIntervalId = setInterval(
  9900. function() { self.logStats(); },
  9901. this.LOG_INTERVAL);
  9902. }
  9903. };
  9904. /**
  9905. * Checks whether a certain record should be included in the logged statistics.
  9906. */
  9907. function acceptStat(reportId, reportType, statName) {
  9908. if (reportType == "googCandidatePair" && statName == "googChannelId")
  9909. return false;
  9910. if (reportType == "ssrc") {
  9911. if (statName == "googTrackId" ||
  9912. statName == "transportId" ||
  9913. statName == "ssrc")
  9914. return false;
  9915. }
  9916. return true;
  9917. }
  9918. /**
  9919. * Checks whether a certain record should be included in the logged statistics.
  9920. */
  9921. function acceptReport(id, type) {
  9922. if (id.substring(0, 15) == "googCertificate" ||
  9923. id.substring(0, 9) == "googTrack" ||
  9924. id.substring(0, 20) == "googLibjingleSession")
  9925. return false;
  9926. if (type == "googComponent")
  9927. return false;
  9928. return true;
  9929. }
  9930. /**
  9931. * Converts the stats to the format used for logging, and saves the data in
  9932. * this.statsToBeLogged.
  9933. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  9934. */
  9935. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  9936. var self = this;
  9937. var num_records = this.statsToBeLogged.timestamps.length;
  9938. this.statsToBeLogged.timestamps.push(new Date().getTime());
  9939. reports.map(function (report) {
  9940. if (!acceptReport(report.id, report.type))
  9941. return;
  9942. var stat = self.statsToBeLogged.stats[report.id];
  9943. if (!stat) {
  9944. stat = self.statsToBeLogged.stats[report.id] = {};
  9945. }
  9946. stat.type = report.type;
  9947. report.names().map(function (name) {
  9948. if (!acceptStat(report.id, report.type, name))
  9949. return;
  9950. var values = stat[name];
  9951. if (!values) {
  9952. values = stat[name] = [];
  9953. }
  9954. while (values.length < num_records) {
  9955. values.push(null);
  9956. }
  9957. values.push(report.stat(name));
  9958. });
  9959. });
  9960. };
  9961. StatsCollector.prototype.logStats = function () {
  9962. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  9963. return;
  9964. // Reset the stats
  9965. this.statsToBeLogged.stats = {};
  9966. this.statsToBeLogged.timestamps = [];
  9967. };
  9968. var keyMap = {};
  9969. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  9970. "ssrc": "ssrc",
  9971. "packetsReceived": "packetsReceived",
  9972. "packetsLost": "packetsLost",
  9973. "packetsSent": "packetsSent",
  9974. "bytesReceived": "bytesReceived",
  9975. "bytesSent": "bytesSent"
  9976. };
  9977. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  9978. "receiveBandwidth": "googAvailableReceiveBandwidth",
  9979. "sendBandwidth": "googAvailableSendBandwidth",
  9980. "remoteAddress": "googRemoteAddress",
  9981. "transportType": "googTransportType",
  9982. "localAddress": "googLocalAddress",
  9983. "activeConnection": "googActiveConnection",
  9984. "ssrc": "ssrc",
  9985. "packetsReceived": "packetsReceived",
  9986. "packetsSent": "packetsSent",
  9987. "packetsLost": "packetsLost",
  9988. "bytesReceived": "bytesReceived",
  9989. "bytesSent": "bytesSent",
  9990. "googFrameHeightReceived": "googFrameHeightReceived",
  9991. "googFrameWidthReceived": "googFrameWidthReceived",
  9992. "googFrameHeightSent": "googFrameHeightSent",
  9993. "googFrameWidthSent": "googFrameWidthSent",
  9994. "audioInputLevel": "audioInputLevel",
  9995. "audioOutputLevel": "audioOutputLevel"
  9996. };
  9997. /**
  9998. * Stats processing logic.
  9999. */
  10000. StatsCollector.prototype.processStatsReport = function () {
  10001. if (!this.baselineStatsReport) {
  10002. return;
  10003. }
  10004. for (var idx in this.currentStatsReport) {
  10005. var now = this.currentStatsReport[idx];
  10006. try {
  10007. if (getStatValue(now, 'receiveBandwidth') ||
  10008. getStatValue(now, 'sendBandwidth')) {
  10009. PeerStats.bandwidth = {
  10010. "download": Math.round(
  10011. (getStatValue(now, 'receiveBandwidth')) / 1000),
  10012. "upload": Math.round(
  10013. (getStatValue(now, 'sendBandwidth')) / 1000)
  10014. };
  10015. }
  10016. }
  10017. catch(e){/*not supported*/}
  10018. if(now.type == 'googCandidatePair')
  10019. {
  10020. var ip, type, localIP, active;
  10021. try {
  10022. ip = getStatValue(now, 'remoteAddress');
  10023. type = getStatValue(now, "transportType");
  10024. localIP = getStatValue(now, "localAddress");
  10025. active = getStatValue(now, "activeConnection");
  10026. }
  10027. catch(e){/*not supported*/}
  10028. if(!ip || !type || !localIP || active != "true")
  10029. continue;
  10030. var addressSaved = false;
  10031. for(var i = 0; i < PeerStats.transport.length; i++)
  10032. {
  10033. if(PeerStats.transport[i].ip == ip &&
  10034. PeerStats.transport[i].type == type &&
  10035. PeerStats.transport[i].localip == localIP)
  10036. {
  10037. addressSaved = true;
  10038. }
  10039. }
  10040. if(addressSaved)
  10041. continue;
  10042. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  10043. continue;
  10044. }
  10045. if(now.type == "candidatepair")
  10046. {
  10047. if(now.state == "succeeded")
  10048. continue;
  10049. var local = this.currentStatsReport[now.localCandidateId];
  10050. var remote = this.currentStatsReport[now.remoteCandidateId];
  10051. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  10052. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  10053. }
  10054. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  10055. now.type != "inboundrtp") {
  10056. continue;
  10057. }
  10058. var before = this.baselineStatsReport[idx];
  10059. if (!before) {
  10060. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10061. continue;
  10062. }
  10063. var ssrc = getStatValue(now, 'ssrc');
  10064. if(!ssrc)
  10065. continue;
  10066. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10067. if (!jid && (Date.now() - now.timestamp) < 3000) {
  10068. console.warn("No jid for ssrc: " + ssrc);
  10069. continue;
  10070. }
  10071. var jidStats = this.jid2stats[jid];
  10072. if (!jidStats) {
  10073. jidStats = new PeerStats();
  10074. this.jid2stats[jid] = jidStats;
  10075. }
  10076. var isDownloadStream = true;
  10077. var key = 'packetsReceived';
  10078. if (!getStatValue(now, key))
  10079. {
  10080. isDownloadStream = false;
  10081. key = 'packetsSent';
  10082. if (!getStatValue(now, key))
  10083. {
  10084. console.warn("No packetsReceived nor packetSent stat found");
  10085. continue;
  10086. }
  10087. }
  10088. var packetsNow = getStatValue(now, key);
  10089. if(!packetsNow || packetsNow < 0)
  10090. packetsNow = 0;
  10091. var packetsBefore = getStatValue(before, key);
  10092. if(!packetsBefore || packetsBefore < 0)
  10093. packetsBefore = 0;
  10094. var packetRate = packetsNow - packetsBefore;
  10095. if(!packetRate || packetRate < 0)
  10096. packetRate = 0;
  10097. var currentLoss = getStatValue(now, 'packetsLost');
  10098. if(!currentLoss || currentLoss < 0)
  10099. currentLoss = 0;
  10100. var previousLoss = getStatValue(before, 'packetsLost');
  10101. if(!previousLoss || previousLoss < 0)
  10102. previousLoss = 0;
  10103. var lossRate = currentLoss - previousLoss;
  10104. if(!lossRate || lossRate < 0)
  10105. lossRate = 0;
  10106. var packetsTotal = (packetRate + lossRate);
  10107. jidStats.setSsrcLoss(ssrc,
  10108. {"packetsTotal": packetsTotal,
  10109. "packetsLost": lossRate,
  10110. "isDownloadStream": isDownloadStream});
  10111. var bytesReceived = 0, bytesSent = 0;
  10112. if(getStatValue(now, "bytesReceived"))
  10113. {
  10114. bytesReceived = getStatValue(now, "bytesReceived") -
  10115. getStatValue(before, "bytesReceived");
  10116. }
  10117. if(getStatValue(now, "bytesSent"))
  10118. {
  10119. bytesSent = getStatValue(now, "bytesSent") -
  10120. getStatValue(before, "bytesSent");
  10121. }
  10122. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  10123. if(bytesReceived <= 0 || time <= 0)
  10124. {
  10125. bytesReceived = 0;
  10126. }
  10127. else
  10128. {
  10129. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  10130. }
  10131. if(bytesSent <= 0 || time <= 0)
  10132. {
  10133. bytesSent = 0;
  10134. }
  10135. else
  10136. {
  10137. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  10138. }
  10139. jidStats.setSsrcBitrate(ssrc, {
  10140. "download": bytesReceived,
  10141. "upload": bytesSent});
  10142. var resolution = {height: null, width: null};
  10143. try {
  10144. if (getStatValue(now, "googFrameHeightReceived") &&
  10145. getStatValue(now, "googFrameWidthReceived")) {
  10146. resolution.height = getStatValue(now, "googFrameHeightReceived");
  10147. resolution.width = getStatValue(now, "googFrameWidthReceived");
  10148. }
  10149. else if (getStatValue(now, "googFrameHeightSent") &&
  10150. getStatValue(now, "googFrameWidthSent")) {
  10151. resolution.height = getStatValue(now, "googFrameHeightSent");
  10152. resolution.width = getStatValue(now, "googFrameWidthSent");
  10153. }
  10154. }
  10155. catch(e){/*not supported*/}
  10156. if(resolution.height && resolution.width)
  10157. {
  10158. jidStats.setSsrcResolution(ssrc, resolution);
  10159. }
  10160. else
  10161. {
  10162. jidStats.setSsrcResolution(ssrc, null);
  10163. }
  10164. }
  10165. var self = this;
  10166. // Jid stats
  10167. var totalPackets = {download: 0, upload: 0};
  10168. var lostPackets = {download: 0, upload: 0};
  10169. var bitrateDownload = 0;
  10170. var bitrateUpload = 0;
  10171. var resolutions = {};
  10172. Object.keys(this.jid2stats).forEach(
  10173. function (jid)
  10174. {
  10175. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  10176. function (ssrc)
  10177. {
  10178. var type = "upload";
  10179. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  10180. type = "download";
  10181. totalPackets[type] +=
  10182. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  10183. lostPackets[type] +=
  10184. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  10185. }
  10186. );
  10187. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  10188. function (ssrc) {
  10189. bitrateDownload +=
  10190. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  10191. bitrateUpload +=
  10192. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  10193. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  10194. }
  10195. );
  10196. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  10197. }
  10198. );
  10199. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  10200. PeerStats.packetLoss = {
  10201. total:
  10202. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  10203. totalPackets.download + totalPackets.upload),
  10204. download:
  10205. calculatePacketLoss(lostPackets.download, totalPackets.download),
  10206. upload:
  10207. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  10208. };
  10209. this.eventEmitter.emit("statistics.connectionstats",
  10210. {
  10211. "bitrate": PeerStats.bitrate,
  10212. "packetLoss": PeerStats.packetLoss,
  10213. "bandwidth": PeerStats.bandwidth,
  10214. "resolution": resolutions,
  10215. "transport": PeerStats.transport
  10216. });
  10217. PeerStats.transport = [];
  10218. };
  10219. /**
  10220. * Stats processing logic.
  10221. */
  10222. StatsCollector.prototype.processAudioLevelReport = function ()
  10223. {
  10224. if (!this.baselineAudioLevelsReport)
  10225. {
  10226. return;
  10227. }
  10228. for (var idx in this.currentAudioLevelsReport)
  10229. {
  10230. var now = this.currentAudioLevelsReport[idx];
  10231. if (now.type != 'ssrc')
  10232. {
  10233. continue;
  10234. }
  10235. var before = this.baselineAudioLevelsReport[idx];
  10236. if (!before)
  10237. {
  10238. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10239. continue;
  10240. }
  10241. var ssrc = getStatValue(now, 'ssrc');
  10242. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10243. if (!jid && (Date.now() - now.timestamp) < 3000)
  10244. {
  10245. console.warn("No jid for ssrc: " + ssrc);
  10246. continue;
  10247. }
  10248. var jidStats = this.jid2stats[jid];
  10249. if (!jidStats)
  10250. {
  10251. jidStats = new PeerStats();
  10252. this.jid2stats[jid] = jidStats;
  10253. }
  10254. // Audio level
  10255. var audioLevel = null;
  10256. try {
  10257. audioLevel = getStatValue(now, 'audioInputLevel');
  10258. if (!audioLevel)
  10259. audioLevel = getStatValue(now, 'audioOutputLevel');
  10260. }
  10261. catch(e) {/*not supported*/
  10262. console.warn("Audio Levels are not available in the statistics.");
  10263. clearInterval(this.audioLevelsIntervalId);
  10264. return;
  10265. }
  10266. if (audioLevel)
  10267. {
  10268. // TODO: can't find specs about what this value really is,
  10269. // but it seems to vary between 0 and around 32k.
  10270. audioLevel = audioLevel / 32767;
  10271. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  10272. if(jid != APP.xmpp.myJid())
  10273. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  10274. }
  10275. }
  10276. };
  10277. },{"../../service/RTC/RTCBrowserType":88}],46:[function(require,module,exports){
  10278. /**
  10279. * Created by hristo on 8/4/14.
  10280. */
  10281. var LocalStats = require("./LocalStatsCollector.js");
  10282. var RTPStats = require("./RTPStatsCollector.js");
  10283. var EventEmitter = require("events");
  10284. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  10285. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10286. var eventEmitter = new EventEmitter();
  10287. var localStats = null;
  10288. var rtpStats = null;
  10289. function stopLocal()
  10290. {
  10291. if(localStats)
  10292. {
  10293. localStats.stop();
  10294. localStats = null;
  10295. }
  10296. }
  10297. function stopRemote()
  10298. {
  10299. if(rtpStats)
  10300. {
  10301. rtpStats.stop();
  10302. eventEmitter.emit("statistics.stop");
  10303. rtpStats = null;
  10304. }
  10305. }
  10306. function startRemoteStats (peerconnection) {
  10307. if(rtpStats)
  10308. {
  10309. rtpStats.stop();
  10310. rtpStats = null;
  10311. }
  10312. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  10313. rtpStats.start();
  10314. }
  10315. function onStreamCreated(stream)
  10316. {
  10317. if(stream.getOriginalStream().getAudioTracks().length === 0)
  10318. return;
  10319. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  10320. eventEmitter);
  10321. localStats.start();
  10322. }
  10323. function onDisposeConference(onUnload) {
  10324. stopRemote();
  10325. if(onUnload) {
  10326. stopLocal();
  10327. eventEmitter.removeAllListeners();
  10328. }
  10329. }
  10330. var statistics =
  10331. {
  10332. /**
  10333. * Indicates that this audio level is for local jid.
  10334. * @type {string}
  10335. */
  10336. LOCAL_JID: 'local',
  10337. addAudioLevelListener: function(listener)
  10338. {
  10339. eventEmitter.on("statistics.audioLevel", listener);
  10340. },
  10341. removeAudioLevelListener: function(listener)
  10342. {
  10343. eventEmitter.removeListener("statistics.audioLevel", listener);
  10344. },
  10345. addConnectionStatsListener: function(listener)
  10346. {
  10347. eventEmitter.on("statistics.connectionstats", listener);
  10348. },
  10349. removeConnectionStatsListener: function(listener)
  10350. {
  10351. eventEmitter.removeListener("statistics.connectionstats", listener);
  10352. },
  10353. addRemoteStatsStopListener: function(listener)
  10354. {
  10355. eventEmitter.on("statistics.stop", listener);
  10356. },
  10357. removeRemoteStatsStopListener: function(listener)
  10358. {
  10359. eventEmitter.removeListener("statistics.stop", listener);
  10360. },
  10361. stop: function () {
  10362. stopLocal();
  10363. stopRemote();
  10364. if(eventEmitter)
  10365. {
  10366. eventEmitter.removeAllListeners();
  10367. }
  10368. },
  10369. stopRemoteStatistics: function()
  10370. {
  10371. stopRemote();
  10372. },
  10373. start: function () {
  10374. APP.RTC.addStreamListener(onStreamCreated,
  10375. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10376. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10377. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10378. startRemoteStats(event.peerconnection);
  10379. });
  10380. }
  10381. };
  10382. module.exports = statistics;
  10383. },{"../../service/RTC/StreamEventTypes.js":91,"../../service/xmpp/XMPPEvents":97,"./LocalStatsCollector.js":44,"./RTPStatsCollector.js":45,"events":98}],47:[function(require,module,exports){
  10384. var i18n = require("i18next-client");
  10385. var languages = require("../../service/translation/languages");
  10386. var Settings = require("../settings/Settings");
  10387. var DEFAULT_LANG = languages.EN;
  10388. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10389. return value.replace("__app__", interfaceConfig.APP_NAME);
  10390. });
  10391. var defaultOptions = {
  10392. detectLngQS: "lang",
  10393. useCookie: false,
  10394. fallbackLng: DEFAULT_LANG,
  10395. load: "unspecific",
  10396. resGetPath: 'lang/__ns__-__lng__.json',
  10397. ns: {
  10398. namespaces: ['main', 'languages'],
  10399. defaultNs: 'main'
  10400. },
  10401. lngWhitelist : languages.getLanguages(),
  10402. fallbackOnNull: true,
  10403. fallbackOnEmpty: true,
  10404. useDataAttrOptions: true,
  10405. defaultValueFromContent: false,
  10406. app: interfaceConfig.APP_NAME,
  10407. getAsync: false,
  10408. defaultValueFromContent: false,
  10409. customLoad: function(lng, ns, options, done) {
  10410. var resPath = "lang/__ns__-__lng__.json";
  10411. if(lng === languages.EN)
  10412. resPath = "lang/__ns__.json";
  10413. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10414. i18n.functions.ajax({
  10415. url: url,
  10416. success: function(data, status, xhr) {
  10417. i18n.functions.log('loaded: ' + url);
  10418. done(null, data);
  10419. },
  10420. error : function(xhr, status, error) {
  10421. if ((status && status == 200) ||
  10422. (xhr && xhr.status && xhr.status == 200)) {
  10423. // file loaded but invalid json, stop waste time !
  10424. i18n.functions.error('There is a typo in: ' + url);
  10425. } else if ((status && status == 404) ||
  10426. (xhr && xhr.status && xhr.status == 404)) {
  10427. i18n.functions.log('Does not exist: ' + url);
  10428. } else {
  10429. var theStatus = status ? status :
  10430. ((xhr && xhr.status) ? xhr.status : null);
  10431. i18n.functions.log(theStatus + ' when loading ' + url);
  10432. }
  10433. done(error, {});
  10434. },
  10435. dataType: "json",
  10436. async : options.getAsync
  10437. });
  10438. }
  10439. // options for caching
  10440. // useLocalStorage: true,
  10441. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10442. };
  10443. function initCompleted(t)
  10444. {
  10445. $("[data-i18n]").i18n();
  10446. }
  10447. function checkForParameter() {
  10448. var query = window.location.search.substring(1);
  10449. var vars = query.split("&");
  10450. for (var i=0;i<vars.length;i++) {
  10451. var pair = vars[i].split("=");
  10452. if(pair[0] == "lang")
  10453. {
  10454. return pair[1];
  10455. }
  10456. }
  10457. return null;
  10458. }
  10459. module.exports = {
  10460. init: function (lang) {
  10461. var options = defaultOptions;
  10462. if(!lang)
  10463. {
  10464. lang = checkForParameter();
  10465. if(!lang)
  10466. {
  10467. var settings = Settings.getSettings();
  10468. if(settings)
  10469. lang = settings.language;
  10470. }
  10471. }
  10472. if(lang) {
  10473. options.lng = lang;
  10474. }
  10475. i18n.init(options, initCompleted);
  10476. },
  10477. translateString: function (key, options) {
  10478. return i18n.t(key, options);
  10479. },
  10480. setLanguage: function (lang) {
  10481. if(!lang)
  10482. lang = DEFAULT_LANG;
  10483. i18n.setLng(lang, defaultOptions, initCompleted);
  10484. },
  10485. getCurrentLanguage: function () {
  10486. return i18n.lng();
  10487. },
  10488. translateElement: function (selector) {
  10489. selector.i18n();
  10490. },
  10491. generateTranslatonHTML: function (key, options) {
  10492. var str = "<span data-i18n=\"" + key + "\"";
  10493. if(options)
  10494. {
  10495. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10496. }
  10497. str += ">";
  10498. str += this.translateString(key, options);
  10499. str += "</span>";
  10500. return str;
  10501. }
  10502. };
  10503. },{"../../service/translation/languages":96,"../settings/Settings":38,"i18next-client":62}],48:[function(require,module,exports){
  10504. /* jshint -W117 */
  10505. var TraceablePeerConnection = require("./TraceablePeerConnection");
  10506. var SDPDiffer = require("./SDPDiffer");
  10507. var SDPUtil = require("./SDPUtil");
  10508. var SDP = require("./SDP");
  10509. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10510. // Jingle stuff
  10511. function JingleSession(me, sid, connection, service) {
  10512. this.me = me;
  10513. this.sid = sid;
  10514. this.connection = connection;
  10515. this.initiator = null;
  10516. this.responder = null;
  10517. this.isInitiator = null;
  10518. this.peerjid = null;
  10519. this.state = null;
  10520. this.localSDP = null;
  10521. this.remoteSDP = null;
  10522. this.relayedStreams = [];
  10523. this.startTime = null;
  10524. this.stopTime = null;
  10525. this.media_constraints = null;
  10526. this.pc_constraints = null;
  10527. this.ice_config = {};
  10528. this.drip_container = [];
  10529. this.service = service;
  10530. this.usetrickle = true;
  10531. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  10532. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  10533. this.hadstuncandidate = false;
  10534. this.hadturncandidate = false;
  10535. this.lasticecandidate = false;
  10536. this.statsinterval = null;
  10537. this.reason = null;
  10538. this.addssrc = [];
  10539. this.removessrc = [];
  10540. this.pendingop = null;
  10541. this.switchstreams = false;
  10542. this.wait = true;
  10543. this.localStreamsSSRC = null;
  10544. /**
  10545. * The indicator which determines whether the (local) video has been muted
  10546. * in response to a user command in contrast to an automatic decision made
  10547. * by the application logic.
  10548. */
  10549. this.videoMuteByUser = false;
  10550. }
  10551. //TODO: this array must be removed when firefox implement multistream support
  10552. JingleSession.notReceivedSSRCs = [];
  10553. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  10554. var self = this;
  10555. if (this.state !== null) {
  10556. console.error('attempt to initiate on session ' + this.sid +
  10557. 'in state ' + this.state);
  10558. return;
  10559. }
  10560. this.isInitiator = isInitiator;
  10561. this.state = 'pending';
  10562. this.initiator = isInitiator ? this.me : peerjid;
  10563. this.responder = !isInitiator ? this.me : peerjid;
  10564. this.peerjid = peerjid;
  10565. this.hadstuncandidate = false;
  10566. this.hadturncandidate = false;
  10567. this.lasticecandidate = false;
  10568. this.peerconnection
  10569. = new TraceablePeerConnection(
  10570. this.connection.jingle.ice_config,
  10571. this.connection.jingle.pc_constraints );
  10572. this.peerconnection.onicecandidate = function (event) {
  10573. self.sendIceCandidate(event.candidate);
  10574. };
  10575. this.peerconnection.onaddstream = function (event) {
  10576. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  10577. self.remoteStreamAdded(event);
  10578. };
  10579. this.peerconnection.onremovestream = function (event) {
  10580. // Remove the stream from remoteStreams
  10581. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  10582. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  10583. };
  10584. this.peerconnection.onsignalingstatechange = function (event) {
  10585. if (!(self && self.peerconnection)) return;
  10586. };
  10587. this.peerconnection.oniceconnectionstatechange = function (event) {
  10588. if (!(self && self.peerconnection)) return;
  10589. switch (self.peerconnection.iceConnectionState) {
  10590. case 'connected':
  10591. this.startTime = new Date();
  10592. break;
  10593. case 'disconnected':
  10594. this.stopTime = new Date();
  10595. break;
  10596. }
  10597. onIceConnectionStateChange(self.sid, self);
  10598. };
  10599. // add any local and relayed stream
  10600. APP.RTC.localStreams.forEach(function(stream) {
  10601. self.peerconnection.addStream(stream.getOriginalStream());
  10602. });
  10603. this.relayedStreams.forEach(function(stream) {
  10604. self.peerconnection.addStream(stream);
  10605. });
  10606. };
  10607. function onIceConnectionStateChange(sid, session) {
  10608. switch (session.peerconnection.iceConnectionState) {
  10609. case 'checking':
  10610. session.timeChecking = (new Date()).getTime();
  10611. session.firstconnect = true;
  10612. break;
  10613. case 'completed': // on caller side
  10614. case 'connected':
  10615. if (session.firstconnect) {
  10616. session.firstconnect = false;
  10617. var metadata = {};
  10618. metadata.setupTime
  10619. = (new Date()).getTime() - session.timeChecking;
  10620. session.peerconnection.getStats(function (res) {
  10621. if(res && res.result) {
  10622. res.result().forEach(function (report) {
  10623. if (report.type == 'googCandidatePair' &&
  10624. report.stat('googActiveConnection') == 'true') {
  10625. metadata.localCandidateType
  10626. = report.stat('googLocalCandidateType');
  10627. metadata.remoteCandidateType
  10628. = report.stat('googRemoteCandidateType');
  10629. // log pair as well so we can get nice pie
  10630. // charts
  10631. metadata.candidatePair
  10632. = report.stat('googLocalCandidateType') +
  10633. ';' +
  10634. report.stat('googRemoteCandidateType');
  10635. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  10636. {
  10637. metadata.ipv6 = true;
  10638. }
  10639. }
  10640. });
  10641. }
  10642. });
  10643. }
  10644. break;
  10645. }
  10646. }
  10647. JingleSession.prototype.accept = function () {
  10648. var self = this;
  10649. this.state = 'active';
  10650. var pranswer = this.peerconnection.localDescription;
  10651. if (!pranswer || pranswer.type != 'pranswer') {
  10652. return;
  10653. }
  10654. console.log('going from pranswer to answer');
  10655. if (this.usetrickle) {
  10656. // remove candidates already sent from session-accept
  10657. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  10658. for (var i = 0; i < lines.length; i++) {
  10659. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  10660. }
  10661. }
  10662. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  10663. // FIXME: change any inactive to sendrecv or whatever they were originally
  10664. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  10665. }
  10666. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  10667. var prsdp = new SDP(pranswer.sdp);
  10668. var accept = $iq({to: this.peerjid,
  10669. type: 'set'})
  10670. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10671. action: 'session-accept',
  10672. initiator: this.initiator,
  10673. responder: this.responder,
  10674. sid: this.sid });
  10675. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10676. var sdp = this.peerconnection.localDescription.sdp;
  10677. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  10678. // FIXME: change any inactive to sendrecv or whatever they were originally
  10679. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  10680. }
  10681. var self = this;
  10682. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  10683. function () {
  10684. //console.log('setLocalDescription success');
  10685. self.setLocalDescription();
  10686. self.connection.sendIQ(accept,
  10687. function () {
  10688. var ack = {};
  10689. ack.source = 'answer';
  10690. $(document).trigger('ack.jingle', [self.sid, ack]);
  10691. },
  10692. function (stanza) {
  10693. var error = ($(stanza).find('error').length) ? {
  10694. code: $(stanza).find('error').attr('code'),
  10695. reason: $(stanza).find('error :first')[0].tagName
  10696. }:{};
  10697. error.source = 'answer';
  10698. JingleSession.onJingleError(self.sid, error);
  10699. },
  10700. 10000);
  10701. },
  10702. function (e) {
  10703. console.error('setLocalDescription failed', e);
  10704. }
  10705. );
  10706. };
  10707. JingleSession.prototype.terminate = function (reason) {
  10708. this.state = 'ended';
  10709. this.reason = reason;
  10710. this.peerconnection.close();
  10711. if (this.statsinterval !== null) {
  10712. window.clearInterval(this.statsinterval);
  10713. this.statsinterval = null;
  10714. }
  10715. };
  10716. JingleSession.prototype.active = function () {
  10717. return this.state == 'active';
  10718. };
  10719. JingleSession.prototype.sendIceCandidate = function (candidate) {
  10720. var self = this;
  10721. if (candidate && !this.lasticecandidate) {
  10722. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  10723. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  10724. if (!(ice && jcand)) {
  10725. console.error('failed to get ice && jcand');
  10726. return;
  10727. }
  10728. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10729. if (jcand.type === 'srflx') {
  10730. this.hadstuncandidate = true;
  10731. } else if (jcand.type === 'relay') {
  10732. this.hadturncandidate = true;
  10733. }
  10734. if (this.usetrickle) {
  10735. if (this.usedrip) {
  10736. if (this.drip_container.length === 0) {
  10737. // start 20ms callout
  10738. window.setTimeout(function () {
  10739. if (self.drip_container.length === 0) return;
  10740. self.sendIceCandidates(self.drip_container);
  10741. self.drip_container = [];
  10742. }, 20);
  10743. }
  10744. this.drip_container.push(candidate);
  10745. return;
  10746. } else {
  10747. self.sendIceCandidate([candidate]);
  10748. }
  10749. }
  10750. } else {
  10751. //console.log('sendIceCandidate: last candidate.');
  10752. if (!this.usetrickle) {
  10753. //console.log('should send full offer now...');
  10754. var init = $iq({to: this.peerjid,
  10755. type: 'set'})
  10756. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10757. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  10758. initiator: this.initiator,
  10759. sid: this.sid});
  10760. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  10761. var self = this;
  10762. var sendJingle = function (ssrc) {
  10763. if(!ssrc)
  10764. ssrc = {};
  10765. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  10766. self.connection.sendIQ(init,
  10767. function () {
  10768. //console.log('session initiate ack');
  10769. var ack = {};
  10770. ack.source = 'offer';
  10771. $(document).trigger('ack.jingle', [self.sid, ack]);
  10772. },
  10773. function (stanza) {
  10774. self.state = 'error';
  10775. self.peerconnection.close();
  10776. var error = ($(stanza).find('error').length) ? {
  10777. code: $(stanza).find('error').attr('code'),
  10778. reason: $(stanza).find('error :first')[0].tagName,
  10779. }:{};
  10780. error.source = 'offer';
  10781. JingleSession.onJingleError(self.sid, error);
  10782. },
  10783. 10000);
  10784. }
  10785. sendJingle();
  10786. }
  10787. this.lasticecandidate = true;
  10788. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  10789. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  10790. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  10791. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  10792. }
  10793. }
  10794. };
  10795. JingleSession.prototype.sendIceCandidates = function (candidates) {
  10796. console.log('sendIceCandidates', candidates);
  10797. var cand = $iq({to: this.peerjid, type: 'set'})
  10798. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10799. action: 'transport-info',
  10800. initiator: this.initiator,
  10801. sid: this.sid});
  10802. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  10803. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  10804. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  10805. if (cands.length > 0) {
  10806. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  10807. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10808. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  10809. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  10810. }).c('transport', ice);
  10811. for (var i = 0; i < cands.length; i++) {
  10812. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  10813. }
  10814. // add fingerprint
  10815. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  10816. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  10817. tmp.required = true;
  10818. cand.c(
  10819. 'fingerprint',
  10820. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  10821. .t(tmp.fingerprint);
  10822. delete tmp.fingerprint;
  10823. cand.attrs(tmp);
  10824. cand.up();
  10825. }
  10826. cand.up(); // transport
  10827. cand.up(); // content
  10828. }
  10829. }
  10830. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  10831. //console.log('was this the last candidate', this.lasticecandidate);
  10832. this.connection.sendIQ(cand,
  10833. function () {
  10834. var ack = {};
  10835. ack.source = 'transportinfo';
  10836. $(document).trigger('ack.jingle', [this.sid, ack]);
  10837. },
  10838. function (stanza) {
  10839. var error = ($(stanza).find('error').length) ? {
  10840. code: $(stanza).find('error').attr('code'),
  10841. reason: $(stanza).find('error :first')[0].tagName,
  10842. }:{};
  10843. error.source = 'transportinfo';
  10844. JingleSession.onJingleError(this.sid, error);
  10845. },
  10846. 10000);
  10847. };
  10848. JingleSession.prototype.sendOffer = function () {
  10849. //console.log('sendOffer...');
  10850. var self = this;
  10851. this.peerconnection.createOffer(function (sdp) {
  10852. self.createdOffer(sdp);
  10853. },
  10854. function (e) {
  10855. console.error('createOffer failed', e);
  10856. },
  10857. this.media_constraints
  10858. );
  10859. };
  10860. JingleSession.prototype.createdOffer = function (sdp) {
  10861. //console.log('createdOffer', sdp);
  10862. var self = this;
  10863. this.localSDP = new SDP(sdp.sdp);
  10864. //this.localSDP.mangle();
  10865. var sendJingle = function () {
  10866. var init = $iq({to: this.peerjid,
  10867. type: 'set'})
  10868. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10869. action: 'session-initiate',
  10870. initiator: this.initiator,
  10871. sid: this.sid});
  10872. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10873. self.connection.sendIQ(init,
  10874. function () {
  10875. var ack = {};
  10876. ack.source = 'offer';
  10877. $(document).trigger('ack.jingle', [self.sid, ack]);
  10878. },
  10879. function (stanza) {
  10880. self.state = 'error';
  10881. self.peerconnection.close();
  10882. var error = ($(stanza).find('error').length) ? {
  10883. code: $(stanza).find('error').attr('code'),
  10884. reason: $(stanza).find('error :first')[0].tagName,
  10885. }:{};
  10886. error.source = 'offer';
  10887. JingleSession.onJingleError(self.sid, error);
  10888. },
  10889. 10000);
  10890. }
  10891. sdp.sdp = this.localSDP.raw;
  10892. this.peerconnection.setLocalDescription(sdp,
  10893. function () {
  10894. if(self.usetrickle)
  10895. {
  10896. sendJingle();
  10897. }
  10898. self.setLocalDescription();
  10899. //console.log('setLocalDescription success');
  10900. },
  10901. function (e) {
  10902. console.error('setLocalDescription failed', e);
  10903. }
  10904. );
  10905. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10906. for (var i = 0; i < cands.length; i++) {
  10907. var cand = SDPUtil.parse_icecandidate(cands[i]);
  10908. if (cand.type == 'srflx') {
  10909. this.hadstuncandidate = true;
  10910. } else if (cand.type == 'relay') {
  10911. this.hadturncandidate = true;
  10912. }
  10913. }
  10914. };
  10915. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  10916. //console.log('setting remote description... ', desctype);
  10917. this.remoteSDP = new SDP('');
  10918. this.remoteSDP.fromJingle(elem);
  10919. if (this.peerconnection.remoteDescription !== null) {
  10920. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  10921. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  10922. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  10923. for (var i = 0; i < pranswer.media.length; i++) {
  10924. // make sure we have ice ufrag and pwd
  10925. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  10926. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  10927. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  10928. } else {
  10929. console.warn('no ice ufrag?');
  10930. }
  10931. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  10932. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  10933. } else {
  10934. console.warn('no ice pwd?');
  10935. }
  10936. }
  10937. // copy over candidates
  10938. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  10939. for (var j = 0; j < lines.length; j++) {
  10940. this.remoteSDP.media[i] += lines[j] + '\r\n';
  10941. }
  10942. }
  10943. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10944. }
  10945. }
  10946. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  10947. this.peerconnection.setRemoteDescription(remotedesc,
  10948. function () {
  10949. //console.log('setRemoteDescription success');
  10950. },
  10951. function (e) {
  10952. console.error('setRemoteDescription error', e);
  10953. JingleSession.onJingleFatalError(self, e);
  10954. }
  10955. );
  10956. };
  10957. JingleSession.prototype.addIceCandidate = function (elem) {
  10958. var self = this;
  10959. if (this.peerconnection.signalingState == 'closed') {
  10960. return;
  10961. }
  10962. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  10963. console.log('trickle ice candidate arriving before session accept...');
  10964. // create a PRANSWER for setRemoteDescription
  10965. if (!this.remoteSDP) {
  10966. var cobbled = 'v=0\r\n' +
  10967. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  10968. 's=-\r\n' +
  10969. 't=0 0\r\n';
  10970. // first, take some things from the local description
  10971. for (var i = 0; i < this.localSDP.media.length; i++) {
  10972. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  10973. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  10974. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  10975. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  10976. }
  10977. cobbled += 'a=inactive\r\n';
  10978. }
  10979. this.remoteSDP = new SDP(cobbled);
  10980. }
  10981. // then add things like ice and dtls from remote candidate
  10982. elem.each(function () {
  10983. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  10984. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10985. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10986. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  10987. var tmp = $(this).find('transport');
  10988. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  10989. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  10990. tmp = $(this).find('transport>fingerprint');
  10991. if (tmp.length) {
  10992. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  10993. } else {
  10994. console.log('no dtls fingerprint (webrtc issue #1718?)');
  10995. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  10996. }
  10997. break;
  10998. }
  10999. }
  11000. }
  11001. });
  11002. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11003. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  11004. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  11005. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  11006. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  11007. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  11008. }).length == this.remoteSDP.media.length;
  11009. if (iscomplete) {
  11010. console.log('setting pranswer');
  11011. try {
  11012. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  11013. function() {
  11014. },
  11015. function(e) {
  11016. console.log('setRemoteDescription pranswer failed', e.toString());
  11017. });
  11018. } catch (e) {
  11019. console.error('setting pranswer failed', e);
  11020. }
  11021. } else {
  11022. //console.log('not yet setting pranswer');
  11023. }
  11024. }
  11025. // operate on each content element
  11026. elem.each(function () {
  11027. // would love to deactivate this, but firefox still requires it
  11028. var idx = -1;
  11029. var i;
  11030. for (i = 0; i < self.remoteSDP.media.length; i++) {
  11031. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11032. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11033. idx = i;
  11034. break;
  11035. }
  11036. }
  11037. if (idx == -1) { // fall back to localdescription
  11038. for (i = 0; i < self.localSDP.media.length; i++) {
  11039. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11040. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11041. idx = i;
  11042. break;
  11043. }
  11044. }
  11045. }
  11046. var name = $(this).attr('name');
  11047. // TODO: check ice-pwd and ice-ufrag?
  11048. $(this).find('transport>candidate').each(function () {
  11049. var line, candidate;
  11050. line = SDPUtil.candidateFromJingle(this);
  11051. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  11052. sdpMid: name,
  11053. candidate: line});
  11054. try {
  11055. self.peerconnection.addIceCandidate(candidate);
  11056. } catch (e) {
  11057. console.error('addIceCandidate failed', e.toString(), line);
  11058. }
  11059. });
  11060. });
  11061. };
  11062. JingleSession.prototype.sendAnswer = function (provisional) {
  11063. //console.log('createAnswer', provisional);
  11064. var self = this;
  11065. this.peerconnection.createAnswer(
  11066. function (sdp) {
  11067. self.createdAnswer(sdp, provisional);
  11068. },
  11069. function (e) {
  11070. console.error('createAnswer failed', e);
  11071. },
  11072. this.media_constraints
  11073. );
  11074. };
  11075. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  11076. //console.log('createAnswer callback');
  11077. var self = this;
  11078. this.localSDP = new SDP(sdp.sdp);
  11079. //this.localSDP.mangle();
  11080. this.usepranswer = provisional === true;
  11081. if (this.usetrickle) {
  11082. if (this.usepranswer) {
  11083. sdp.type = 'pranswer';
  11084. for (var i = 0; i < this.localSDP.media.length; i++) {
  11085. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  11086. }
  11087. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  11088. }
  11089. }
  11090. var self = this;
  11091. var sendJingle = function (ssrcs) {
  11092. var accept = $iq({to: self.peerjid,
  11093. type: 'set'})
  11094. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11095. action: 'session-accept',
  11096. initiator: self.initiator,
  11097. responder: self.responder,
  11098. sid: self.sid });
  11099. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  11100. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  11101. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  11102. self.connection.sendIQ(accept,
  11103. function () {
  11104. var ack = {};
  11105. ack.source = 'answer';
  11106. $(document).trigger('ack.jingle', [self.sid, ack]);
  11107. },
  11108. function (stanza) {
  11109. var error = ($(stanza).find('error').length) ? {
  11110. code: $(stanza).find('error').attr('code'),
  11111. reason: $(stanza).find('error :first')[0].tagName,
  11112. }:{};
  11113. error.source = 'answer';
  11114. JingleSession.onJingleError(self.sid, error);
  11115. },
  11116. 10000);
  11117. }
  11118. sdp.sdp = this.localSDP.raw;
  11119. this.peerconnection.setLocalDescription(sdp,
  11120. function () {
  11121. //console.log('setLocalDescription success');
  11122. if (self.usetrickle && !self.usepranswer) {
  11123. sendJingle();
  11124. }
  11125. self.setLocalDescription();
  11126. },
  11127. function (e) {
  11128. console.error('setLocalDescription failed', e);
  11129. }
  11130. );
  11131. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11132. for (var j = 0; j < cands.length; j++) {
  11133. var cand = SDPUtil.parse_icecandidate(cands[j]);
  11134. if (cand.type == 'srflx') {
  11135. this.hadstuncandidate = true;
  11136. } else if (cand.type == 'relay') {
  11137. this.hadturncandidate = true;
  11138. }
  11139. }
  11140. };
  11141. JingleSession.prototype.sendTerminate = function (reason, text) {
  11142. var self = this,
  11143. term = $iq({to: this.peerjid,
  11144. type: 'set'})
  11145. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11146. action: 'session-terminate',
  11147. initiator: this.initiator,
  11148. sid: this.sid})
  11149. .c('reason')
  11150. .c(reason || 'success');
  11151. if (text) {
  11152. term.up().c('text').t(text);
  11153. }
  11154. this.connection.sendIQ(term,
  11155. function () {
  11156. self.peerconnection.close();
  11157. self.peerconnection = null;
  11158. self.terminate();
  11159. var ack = {};
  11160. ack.source = 'terminate';
  11161. $(document).trigger('ack.jingle', [self.sid, ack]);
  11162. },
  11163. function (stanza) {
  11164. var error = ($(stanza).find('error').length) ? {
  11165. code: $(stanza).find('error').attr('code'),
  11166. reason: $(stanza).find('error :first')[0].tagName,
  11167. }:{};
  11168. $(document).trigger('ack.jingle', [self.sid, error]);
  11169. },
  11170. 10000);
  11171. if (this.statsinterval !== null) {
  11172. window.clearInterval(this.statsinterval);
  11173. this.statsinterval = null;
  11174. }
  11175. };
  11176. JingleSession.prototype.addSource = function (elem, fromJid) {
  11177. var self = this;
  11178. // FIXME: dirty waiting
  11179. if (!this.peerconnection.localDescription)
  11180. {
  11181. console.warn("addSource - localDescription not ready yet")
  11182. setTimeout(function()
  11183. {
  11184. self.addSource(elem, fromJid);
  11185. },
  11186. 200
  11187. );
  11188. return;
  11189. }
  11190. console.log('addssrc', new Date().getTime());
  11191. console.log('ice', this.peerconnection.iceConnectionState);
  11192. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11193. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11194. $(elem).each(function (idx, content) {
  11195. var name = $(content).attr('name');
  11196. var lines = '';
  11197. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11198. var semantics = this.getAttribute('semantics');
  11199. var ssrcs = $(this).find('>source').map(function () {
  11200. return this.getAttribute('ssrc');
  11201. }).get();
  11202. if (ssrcs.length != 0) {
  11203. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11204. }
  11205. });
  11206. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11207. tmp.each(function () {
  11208. var ssrc = $(this).attr('ssrc');
  11209. if(mySdp.containsSSRC(ssrc)){
  11210. /**
  11211. * This happens when multiple participants change their streams at the same time and
  11212. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  11213. * addssrc are scheduled for update IQ. See
  11214. */
  11215. console.warn("Got add stream request for my own ssrc: "+ssrc);
  11216. return;
  11217. }
  11218. $(this).find('>parameter').each(function () {
  11219. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11220. if ($(this).attr('value') && $(this).attr('value').length)
  11221. lines += ':' + $(this).attr('value');
  11222. lines += '\r\n';
  11223. });
  11224. });
  11225. sdp.media.forEach(function(media, idx) {
  11226. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11227. return;
  11228. sdp.media[idx] += lines;
  11229. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  11230. self.addssrc[idx] += lines;
  11231. });
  11232. sdp.raw = sdp.session + sdp.media.join('');
  11233. });
  11234. this.modifySources();
  11235. };
  11236. JingleSession.prototype.removeSource = function (elem, fromJid) {
  11237. var self = this;
  11238. // FIXME: dirty waiting
  11239. if (!this.peerconnection.localDescription)
  11240. {
  11241. console.warn("removeSource - localDescription not ready yet")
  11242. setTimeout(function()
  11243. {
  11244. self.removeSource(elem, fromJid);
  11245. },
  11246. 200
  11247. );
  11248. return;
  11249. }
  11250. console.log('removessrc', new Date().getTime());
  11251. console.log('ice', this.peerconnection.iceConnectionState);
  11252. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11253. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11254. $(elem).each(function (idx, content) {
  11255. var name = $(content).attr('name');
  11256. var lines = '';
  11257. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11258. var semantics = this.getAttribute('semantics');
  11259. var ssrcs = $(this).find('>source').map(function () {
  11260. return this.getAttribute('ssrc');
  11261. }).get();
  11262. if (ssrcs.length != 0) {
  11263. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11264. }
  11265. });
  11266. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11267. tmp.each(function () {
  11268. var ssrc = $(this).attr('ssrc');
  11269. // This should never happen, but can be useful for bug detection
  11270. if(mySdp.containsSSRC(ssrc)){
  11271. console.error("Got remove stream request for my own ssrc: "+ssrc);
  11272. return;
  11273. }
  11274. $(this).find('>parameter').each(function () {
  11275. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11276. if ($(this).attr('value') && $(this).attr('value').length)
  11277. lines += ':' + $(this).attr('value');
  11278. lines += '\r\n';
  11279. });
  11280. });
  11281. sdp.media.forEach(function(media, idx) {
  11282. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11283. return;
  11284. sdp.media[idx] += lines;
  11285. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  11286. self.removessrc[idx] += lines;
  11287. });
  11288. sdp.raw = sdp.session + sdp.media.join('');
  11289. });
  11290. this.modifySources();
  11291. };
  11292. JingleSession.prototype.modifySources = function (successCallback) {
  11293. var self = this;
  11294. if (this.peerconnection.signalingState == 'closed') return;
  11295. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  11296. // There is nothing to do since scheduled job might have been executed by another succeeding call
  11297. this.setLocalDescription();
  11298. if(successCallback){
  11299. successCallback();
  11300. }
  11301. return;
  11302. }
  11303. // FIXME: this is a big hack
  11304. // https://code.google.com/p/webrtc/issues/detail?id=2688
  11305. // ^ has been fixed.
  11306. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
  11307. console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
  11308. this.wait = true;
  11309. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  11310. return;
  11311. }
  11312. if (this.wait) {
  11313. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  11314. this.wait = false;
  11315. return;
  11316. }
  11317. // Reset switch streams flag
  11318. this.switchstreams = false;
  11319. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11320. // add sources
  11321. this.addssrc.forEach(function(lines, idx) {
  11322. sdp.media[idx] += lines;
  11323. });
  11324. this.addssrc = [];
  11325. // remove sources
  11326. this.removessrc.forEach(function(lines, idx) {
  11327. lines = lines.split('\r\n');
  11328. lines.pop(); // remove empty last element;
  11329. lines.forEach(function(line) {
  11330. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  11331. });
  11332. });
  11333. this.removessrc = [];
  11334. // FIXME:
  11335. // this was a hack for the situation when only one peer exists
  11336. // in the conference.
  11337. // check if still required and remove
  11338. if (sdp.media[0])
  11339. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  11340. if (sdp.media[1])
  11341. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11342. sdp.raw = sdp.session + sdp.media.join('');
  11343. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  11344. function() {
  11345. if(self.signalingState == 'closed') {
  11346. console.error("createAnswer attempt on closed state");
  11347. return;
  11348. }
  11349. self.peerconnection.createAnswer(
  11350. function(modifiedAnswer) {
  11351. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  11352. if (self.pendingop !== null) {
  11353. var sdp = new SDP(modifiedAnswer.sdp);
  11354. if (sdp.media.length > 1) {
  11355. switch(self.pendingop) {
  11356. case 'mute':
  11357. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  11358. break;
  11359. case 'unmute':
  11360. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11361. break;
  11362. }
  11363. sdp.raw = sdp.session + sdp.media.join('');
  11364. modifiedAnswer.sdp = sdp.raw;
  11365. }
  11366. self.pendingop = null;
  11367. }
  11368. // FIXME: pushing down an answer while ice connection state
  11369. // is still checking is bad...
  11370. //console.log(self.peerconnection.iceConnectionState);
  11371. // trying to work around another chrome bug
  11372. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11373. self.peerconnection.setLocalDescription(modifiedAnswer,
  11374. function() {
  11375. //console.log('modified setLocalDescription ok');
  11376. self.setLocalDescription();
  11377. if(successCallback){
  11378. successCallback();
  11379. }
  11380. },
  11381. function(error) {
  11382. console.error('modified setLocalDescription failed', error);
  11383. }
  11384. );
  11385. },
  11386. function(error) {
  11387. console.error('modified answer failed', error);
  11388. }
  11389. );
  11390. },
  11391. function(error) {
  11392. console.error('modify failed', error);
  11393. }
  11394. );
  11395. };
  11396. /**
  11397. * Switches video streams.
  11398. * @param new_stream new stream that will be used as video of this session.
  11399. * @param oldStream old video stream of this session.
  11400. * @param success_callback callback executed after successful stream switch.
  11401. */
  11402. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback) {
  11403. var self = this;
  11404. // Remember SDP to figure out added/removed SSRCs
  11405. var oldSdp = null;
  11406. if(self.peerconnection) {
  11407. if(self.peerconnection.localDescription) {
  11408. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11409. }
  11410. self.peerconnection.removeStream(oldStream, true);
  11411. if(new_stream)
  11412. self.peerconnection.addStream(new_stream);
  11413. }
  11414. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11415. // Conference is not active
  11416. if(!oldSdp || !self.peerconnection) {
  11417. success_callback();
  11418. return;
  11419. }
  11420. self.switchstreams = true;
  11421. self.modifySources(function() {
  11422. console.log('modify sources done');
  11423. success_callback();
  11424. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11425. console.log("SDPs", oldSdp, newSdp);
  11426. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11427. });
  11428. };
  11429. /**
  11430. * Figures out added/removed ssrcs and send update IQs.
  11431. * @param old_sdp SDP object for old description.
  11432. * @param new_sdp SDP object for new description.
  11433. */
  11434. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11435. if (!(this.peerconnection.signalingState == 'stable' &&
  11436. this.peerconnection.iceConnectionState == 'connected')){
  11437. console.log("Too early to send updates");
  11438. return;
  11439. }
  11440. // send source-remove IQ.
  11441. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11442. var remove = $iq({to: this.peerjid, type: 'set'})
  11443. .c('jingle', {
  11444. xmlns: 'urn:xmpp:jingle:1',
  11445. action: 'source-remove',
  11446. initiator: this.initiator,
  11447. sid: this.sid
  11448. }
  11449. );
  11450. var removed = sdpDiffer.toJingle(remove);
  11451. if (removed) {
  11452. this.connection.sendIQ(remove,
  11453. function (res) {
  11454. console.info('got remove result', res);
  11455. },
  11456. function (err) {
  11457. console.error('got remove error', err);
  11458. }
  11459. );
  11460. } else {
  11461. console.log('removal not necessary');
  11462. }
  11463. // send source-add IQ.
  11464. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11465. var add = $iq({to: this.peerjid, type: 'set'})
  11466. .c('jingle', {
  11467. xmlns: 'urn:xmpp:jingle:1',
  11468. action: 'source-add',
  11469. initiator: this.initiator,
  11470. sid: this.sid
  11471. }
  11472. );
  11473. var added = sdpDiffer.toJingle(add);
  11474. if (added) {
  11475. this.connection.sendIQ(add,
  11476. function (res) {
  11477. console.info('got add result', res);
  11478. },
  11479. function (err) {
  11480. console.error('got add error', err);
  11481. }
  11482. );
  11483. } else {
  11484. console.log('addition not necessary');
  11485. }
  11486. };
  11487. /**
  11488. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  11489. *
  11490. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  11491. * tracks; otherwise, <tt>false</tt>
  11492. * @param callback a function to be invoked with <tt>mute</tt> after all video
  11493. * tracks have been enabled/disabled. The function may, optionally, return
  11494. * another function which is to be invoked after the whole mute/unmute operation
  11495. * has completed successfully.
  11496. * @param options an object which specifies optional arguments such as the
  11497. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  11498. * specifies whether the method was initiated in response to a user command (in
  11499. * contrast to an automatic decision made by the application logic)
  11500. */
  11501. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  11502. var byUser;
  11503. if (options) {
  11504. byUser = options.byUser;
  11505. if (typeof byUser === 'undefined') {
  11506. byUser = true;
  11507. }
  11508. } else {
  11509. byUser = true;
  11510. }
  11511. // The user's command to mute the (local) video takes precedence over any
  11512. // automatic decision made by the application logic.
  11513. if (byUser) {
  11514. this.videoMuteByUser = mute;
  11515. } else if (this.videoMuteByUser) {
  11516. return;
  11517. }
  11518. this.hardMuteVideo(mute);
  11519. this.modifySources(callback(mute));
  11520. };
  11521. JingleSession.prototype.hardMuteVideo = function (muted) {
  11522. this.pendingop = muted ? 'mute' : 'unmute';
  11523. };
  11524. JingleSession.prototype.sendMute = function (muted, content) {
  11525. var info = $iq({to: this.peerjid,
  11526. type: 'set'})
  11527. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11528. action: 'session-info',
  11529. initiator: this.initiator,
  11530. sid: this.sid });
  11531. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11532. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  11533. if (content) {
  11534. info.attrs({'name': content});
  11535. }
  11536. this.connection.send(info);
  11537. };
  11538. JingleSession.prototype.sendRinging = function () {
  11539. var info = $iq({to: this.peerjid,
  11540. type: 'set'})
  11541. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11542. action: 'session-info',
  11543. initiator: this.initiator,
  11544. sid: this.sid });
  11545. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11546. this.connection.send(info);
  11547. };
  11548. JingleSession.prototype.getStats = function (interval) {
  11549. var self = this;
  11550. var recv = {audio: 0, video: 0};
  11551. var lost = {audio: 0, video: 0};
  11552. var lastrecv = {audio: 0, video: 0};
  11553. var lastlost = {audio: 0, video: 0};
  11554. var loss = {audio: 0, video: 0};
  11555. var delta = {audio: 0, video: 0};
  11556. this.statsinterval = window.setInterval(function () {
  11557. if (self && self.peerconnection && self.peerconnection.getStats) {
  11558. self.peerconnection.getStats(function (stats) {
  11559. var results = stats.result();
  11560. // TODO: there are so much statistics you can get from this..
  11561. for (var i = 0; i < results.length; ++i) {
  11562. if (results[i].type == 'ssrc') {
  11563. var packetsrecv = results[i].stat('packetsReceived');
  11564. var packetslost = results[i].stat('packetsLost');
  11565. if (packetsrecv && packetslost) {
  11566. packetsrecv = parseInt(packetsrecv, 10);
  11567. packetslost = parseInt(packetslost, 10);
  11568. if (results[i].stat('googFrameRateReceived')) {
  11569. lastlost.video = lost.video;
  11570. lastrecv.video = recv.video;
  11571. recv.video = packetsrecv;
  11572. lost.video = packetslost;
  11573. } else {
  11574. lastlost.audio = lost.audio;
  11575. lastrecv.audio = recv.audio;
  11576. recv.audio = packetsrecv;
  11577. lost.audio = packetslost;
  11578. }
  11579. }
  11580. }
  11581. }
  11582. delta.audio = recv.audio - lastrecv.audio;
  11583. delta.video = recv.video - lastrecv.video;
  11584. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  11585. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  11586. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  11587. });
  11588. }
  11589. }, interval || 3000);
  11590. return this.statsinterval;
  11591. };
  11592. JingleSession.onJingleError = function (session, error)
  11593. {
  11594. console.error("Jingle error", error);
  11595. }
  11596. JingleSession.onJingleFatalError = function (session, error)
  11597. {
  11598. this.service.sessionTerminated = true;
  11599. this.connection.emuc.doLeave();
  11600. APP.UI.messageHandler.showError("dialog.sorry",
  11601. "dialog.internalError");
  11602. }
  11603. JingleSession.prototype.setLocalDescription = function () {
  11604. // put our ssrcs into presence so other clients can identify our stream
  11605. var newssrcs = [];
  11606. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  11607. media.forEach(function (media) {
  11608. if(Object.keys(media.sources).length > 0) {
  11609. // TODO(gp) maybe exclude FID streams?
  11610. Object.keys(media.sources).forEach(function (ssrc) {
  11611. newssrcs.push({
  11612. 'ssrc': ssrc,
  11613. 'type': media.type,
  11614. 'direction': media.direction
  11615. });
  11616. });
  11617. }
  11618. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  11619. {
  11620. newssrcs.push({
  11621. 'ssrc': this.localStreamsSSRC[media.type],
  11622. 'type': media.type,
  11623. 'direction': media.direction
  11624. });
  11625. }
  11626. });
  11627. console.log('new ssrcs', newssrcs);
  11628. // Have to clear presence map to get rid of removed streams
  11629. this.connection.emuc.clearPresenceMedia();
  11630. if (newssrcs.length > 0) {
  11631. for (var i = 1; i <= newssrcs.length; i ++) {
  11632. // Change video type to screen
  11633. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  11634. newssrcs[i-1].type = 'screen';
  11635. }
  11636. this.connection.emuc.addMediaToPresence(i,
  11637. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  11638. }
  11639. this.connection.emuc.sendPresence();
  11640. }
  11641. }
  11642. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11643. function sendKeyframe(pc) {
  11644. console.log('sendkeyframe', pc.iceConnectionState);
  11645. if (pc.iceConnectionState !== 'connected') return; // safe...
  11646. pc.setRemoteDescription(
  11647. pc.remoteDescription,
  11648. function () {
  11649. pc.createAnswer(
  11650. function (modifiedAnswer) {
  11651. pc.setLocalDescription(
  11652. modifiedAnswer,
  11653. function () {
  11654. // noop
  11655. },
  11656. function (error) {
  11657. console.log('triggerKeyframe setLocalDescription failed', error);
  11658. APP.UI.messageHandler.showError();
  11659. }
  11660. );
  11661. },
  11662. function (error) {
  11663. console.log('triggerKeyframe createAnswer failed', error);
  11664. APP.UI.messageHandler.showError();
  11665. }
  11666. );
  11667. },
  11668. function (error) {
  11669. console.log('triggerKeyframe setRemoteDescription failed', error);
  11670. APP.UI.messageHandler.showError();
  11671. }
  11672. );
  11673. }
  11674. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  11675. var self = this;
  11676. var thessrc;
  11677. var ssrc2jid = this.connection.emuc.ssrc2jid;
  11678. // look up an associated JID for a stream id
  11679. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  11680. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  11681. var ssrclines
  11682. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  11683. ssrclines = ssrclines.filter(function (line) {
  11684. // NOTE(gp) previously we filtered on the mslabel, but that property
  11685. // is not always present.
  11686. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  11687. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  11688. });
  11689. if (ssrclines.length) {
  11690. thessrc = ssrclines[0].substring(7).split(' ')[0];
  11691. // We signal our streams (through Jingle to the focus) before we set
  11692. // our presence (through which peers associate remote streams to
  11693. // jids). So, it might arrive that a remote stream is added but
  11694. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  11695. // successfully set. Here we wait for up to a second for the
  11696. // presence to arrive.
  11697. if (!ssrc2jid[thessrc]) {
  11698. if (typeof times === 'undefined')
  11699. {
  11700. times = 0;
  11701. }
  11702. if (times > 10)
  11703. {
  11704. console.warning('Waiting for jid timed out', thessrc);
  11705. }
  11706. else
  11707. {
  11708. setTimeout(function(d) {
  11709. return function() {
  11710. self.remoteStreamAdded(d, times++);
  11711. }
  11712. }(data), 250);
  11713. }
  11714. return;
  11715. }
  11716. // ok to overwrite the one from focus? might save work in colibri.js
  11717. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  11718. if (ssrc2jid[thessrc]) {
  11719. data.peerjid = ssrc2jid[thessrc];
  11720. }
  11721. }
  11722. }
  11723. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  11724. var isVideo = data.stream.getVideoTracks().length > 0;
  11725. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11726. if (isVideo &&
  11727. data.peerjid && this.peerjid === data.peerjid &&
  11728. data.stream.getVideoTracks().length === 0 &&
  11729. APP.RTC.localVideo.getTracks().length > 0) {
  11730. window.setTimeout(function () {
  11731. sendKeyframe(self.peerconnection);
  11732. }, 3000);
  11733. }
  11734. }
  11735. module.exports = JingleSession;
  11736. },{"../../service/RTC/RTCBrowserType":88,"./SDP":49,"./SDPDiffer":50,"./SDPUtil":51,"./TraceablePeerConnection":52}],49:[function(require,module,exports){
  11737. /* jshint -W117 */
  11738. var SDPUtil = require("./SDPUtil");
  11739. // SDP STUFF
  11740. function SDP(sdp) {
  11741. this.media = sdp.split('\r\nm=');
  11742. for (var i = 1; i < this.media.length; i++) {
  11743. this.media[i] = 'm=' + this.media[i];
  11744. if (i != this.media.length - 1) {
  11745. this.media[i] += '\r\n';
  11746. }
  11747. }
  11748. this.session = this.media.shift() + '\r\n';
  11749. this.raw = this.session + this.media.join('');
  11750. }
  11751. /**
  11752. * Returns map of MediaChannel mapped per channel idx.
  11753. */
  11754. SDP.prototype.getMediaSsrcMap = function() {
  11755. var self = this;
  11756. var media_ssrcs = {};
  11757. var tmp;
  11758. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  11759. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  11760. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  11761. var media = {
  11762. mediaindex: mediaindex,
  11763. mid: mid,
  11764. ssrcs: {},
  11765. ssrcGroups: []
  11766. };
  11767. media_ssrcs[mediaindex] = media;
  11768. tmp.forEach(function (line) {
  11769. var linessrc = line.substring(7).split(' ')[0];
  11770. // allocate new ChannelSsrc
  11771. if(!media.ssrcs[linessrc]) {
  11772. media.ssrcs[linessrc] = {
  11773. ssrc: linessrc,
  11774. lines: []
  11775. };
  11776. }
  11777. media.ssrcs[linessrc].lines.push(line);
  11778. });
  11779. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  11780. tmp.forEach(function(line){
  11781. var semantics = line.substr(0, idx).substr(13);
  11782. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11783. if (ssrcs.length != 0) {
  11784. media.ssrcGroups.push({
  11785. semantics: semantics,
  11786. ssrcs: ssrcs
  11787. });
  11788. }
  11789. });
  11790. }
  11791. return media_ssrcs;
  11792. };
  11793. /**
  11794. * Returns <tt>true</tt> if this SDP contains given SSRC.
  11795. * @param ssrc the ssrc to check.
  11796. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  11797. */
  11798. SDP.prototype.containsSSRC = function(ssrc) {
  11799. var medias = this.getMediaSsrcMap();
  11800. var contains = false;
  11801. Object.keys(medias).forEach(function(mediaindex){
  11802. var media = medias[mediaindex];
  11803. //console.log("Check", channel, ssrc);
  11804. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  11805. contains = true;
  11806. }
  11807. });
  11808. return contains;
  11809. };
  11810. // remove iSAC and CN from SDP
  11811. SDP.prototype.mangle = function () {
  11812. var i, j, mline, lines, rtpmap, newdesc;
  11813. for (i = 0; i < this.media.length; i++) {
  11814. lines = this.media[i].split('\r\n');
  11815. lines.pop(); // remove empty last element
  11816. mline = SDPUtil.parse_mline(lines.shift());
  11817. if (mline.media != 'audio')
  11818. continue;
  11819. newdesc = '';
  11820. mline.fmt.length = 0;
  11821. for (j = 0; j < lines.length; j++) {
  11822. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  11823. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  11824. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  11825. continue;
  11826. mline.fmt.push(rtpmap.id);
  11827. newdesc += lines[j] + '\r\n';
  11828. } else {
  11829. newdesc += lines[j] + '\r\n';
  11830. }
  11831. }
  11832. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  11833. this.media[i] += newdesc;
  11834. }
  11835. this.raw = this.session + this.media.join('');
  11836. };
  11837. // remove lines matching prefix from session section
  11838. SDP.prototype.removeSessionLines = function(prefix) {
  11839. var self = this;
  11840. var lines = SDPUtil.find_lines(this.session, prefix);
  11841. lines.forEach(function(line) {
  11842. self.session = self.session.replace(line + '\r\n', '');
  11843. });
  11844. this.raw = this.session + this.media.join('');
  11845. return lines;
  11846. }
  11847. // remove lines matching prefix from a media section specified by mediaindex
  11848. // TODO: non-numeric mediaindex could match mid
  11849. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  11850. var self = this;
  11851. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  11852. lines.forEach(function(line) {
  11853. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  11854. });
  11855. this.raw = this.session + this.media.join('');
  11856. return lines;
  11857. }
  11858. // add content's to a jingle element
  11859. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  11860. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  11861. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  11862. var self = this;
  11863. // new bundle plan
  11864. if (SDPUtil.find_line(this.session, 'a=group:')) {
  11865. lines = SDPUtil.find_lines(this.session, 'a=group:');
  11866. for (i = 0; i < lines.length; i++) {
  11867. tmp = lines[i].split(' ');
  11868. var semantics = tmp.shift().substr(8);
  11869. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  11870. for (j = 0; j < tmp.length; j++) {
  11871. elem.c('content', {name: tmp[j]}).up();
  11872. }
  11873. elem.up();
  11874. }
  11875. }
  11876. for (i = 0; i < this.media.length; i++) {
  11877. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  11878. if (!(mline.media === 'audio' ||
  11879. mline.media === 'video' ||
  11880. mline.media === 'application'))
  11881. {
  11882. continue;
  11883. }
  11884. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  11885. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  11886. } else {
  11887. if(ssrcs && ssrcs[mline.media])
  11888. {
  11889. ssrc = ssrcs[mline.media];
  11890. }
  11891. else
  11892. ssrc = false;
  11893. }
  11894. elem.c('content', {creator: thecreator, name: mline.media});
  11895. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  11896. // prefer identifier from a=mid if present
  11897. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  11898. elem.attrs({ name: mid });
  11899. }
  11900. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  11901. {
  11902. elem.c('description',
  11903. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  11904. media: mline.media });
  11905. if (ssrc) {
  11906. elem.attrs({ssrc: ssrc});
  11907. }
  11908. for (j = 0; j < mline.fmt.length; j++) {
  11909. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  11910. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  11911. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  11912. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  11913. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  11914. for (k = 0; k < tmp.length; k++) {
  11915. elem.c('parameter', tmp[k]).up();
  11916. }
  11917. }
  11918. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  11919. elem.up();
  11920. }
  11921. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  11922. elem.c('encryption', {required: 1});
  11923. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  11924. crypto.forEach(function(line) {
  11925. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  11926. });
  11927. elem.up(); // end of encryption
  11928. }
  11929. if (ssrc) {
  11930. // new style mapping
  11931. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11932. // FIXME: group by ssrc and support multiple different ssrcs
  11933. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  11934. if(ssrclines.length > 0) {
  11935. ssrclines.forEach(function (line) {
  11936. idx = line.indexOf(' ');
  11937. var linessrc = line.substr(0, idx).substr(7);
  11938. if (linessrc != ssrc) {
  11939. elem.up();
  11940. ssrc = linessrc;
  11941. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11942. }
  11943. var kv = line.substr(idx + 1);
  11944. elem.c('parameter');
  11945. if (kv.indexOf(':') == -1) {
  11946. elem.attrs({ name: kv });
  11947. } else {
  11948. elem.attrs({ name: kv.split(':', 2)[0] });
  11949. elem.attrs({ value: kv.split(':', 2)[1] });
  11950. }
  11951. elem.up();
  11952. });
  11953. elem.up();
  11954. }
  11955. else
  11956. {
  11957. elem.up();
  11958. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11959. elem.c('parameter');
  11960. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  11961. elem.up();
  11962. var msid = null;
  11963. if(mline.media == "audio")
  11964. {
  11965. msid = APP.RTC.localAudio.getId();
  11966. }
  11967. else
  11968. {
  11969. msid = APP.RTC.localVideo.getId();
  11970. }
  11971. if(msid != null)
  11972. {
  11973. msid = msid.replace(/[\{,\}]/g,"");
  11974. elem.c('parameter');
  11975. elem.attrs({name: "msid", value:msid});
  11976. elem.up();
  11977. elem.c('parameter');
  11978. elem.attrs({name: "mslabel", value:msid});
  11979. elem.up();
  11980. elem.c('parameter');
  11981. elem.attrs({name: "label", value:msid});
  11982. elem.up();
  11983. elem.up();
  11984. }
  11985. }
  11986. // XEP-0339 handle ssrc-group attributes
  11987. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  11988. ssrc_group_lines.forEach(function(line) {
  11989. idx = line.indexOf(' ');
  11990. var semantics = line.substr(0, idx).substr(13);
  11991. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11992. if (ssrcs.length != 0) {
  11993. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11994. ssrcs.forEach(function(ssrc) {
  11995. elem.c('source', { ssrc: ssrc })
  11996. .up();
  11997. });
  11998. elem.up();
  11999. }
  12000. });
  12001. }
  12002. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  12003. elem.c('rtcp-mux').up();
  12004. }
  12005. // XEP-0293 -- map a=rtcp-fb:*
  12006. this.RtcpFbToJingle(i, elem, '*');
  12007. // XEP-0294
  12008. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  12009. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  12010. for (j = 0; j < lines.length; j++) {
  12011. tmp = SDPUtil.parse_extmap(lines[j]);
  12012. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  12013. uri: tmp.uri,
  12014. id: tmp.value });
  12015. if (tmp.hasOwnProperty('direction')) {
  12016. switch (tmp.direction) {
  12017. case 'sendonly':
  12018. elem.attrs({senders: 'responder'});
  12019. break;
  12020. case 'recvonly':
  12021. elem.attrs({senders: 'initiator'});
  12022. break;
  12023. case 'sendrecv':
  12024. elem.attrs({senders: 'both'});
  12025. break;
  12026. case 'inactive':
  12027. elem.attrs({senders: 'none'});
  12028. break;
  12029. }
  12030. }
  12031. // TODO: handle params
  12032. elem.up();
  12033. }
  12034. }
  12035. elem.up(); // end of description
  12036. }
  12037. // map ice-ufrag/pwd, dtls fingerprint, candidates
  12038. this.TransportToJingle(i, elem);
  12039. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  12040. elem.attrs({senders: 'both'});
  12041. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  12042. elem.attrs({senders: 'initiator'});
  12043. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  12044. elem.attrs({senders: 'responder'});
  12045. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  12046. elem.attrs({senders: 'none'});
  12047. }
  12048. if (mline.port == '0') {
  12049. // estos hack to reject an m-line
  12050. elem.attrs({senders: 'rejected'});
  12051. }
  12052. elem.up(); // end of content
  12053. }
  12054. elem.up();
  12055. return elem;
  12056. };
  12057. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  12058. var i = mediaindex;
  12059. var tmp;
  12060. var self = this;
  12061. elem.c('transport');
  12062. // XEP-0343 DTLS/SCTP
  12063. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  12064. {
  12065. var sctpmap = SDPUtil.find_line(
  12066. this.media[i], 'a=sctpmap:', self.session);
  12067. if (sctpmap)
  12068. {
  12069. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  12070. elem.c('sctpmap',
  12071. {
  12072. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  12073. number: sctpAttrs[0], /* SCTP port */
  12074. protocol: sctpAttrs[1], /* protocol */
  12075. });
  12076. // Optional stream count attribute
  12077. if (sctpAttrs.length > 2)
  12078. elem.attrs({ streams: sctpAttrs[2]});
  12079. elem.up();
  12080. }
  12081. }
  12082. // XEP-0320
  12083. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  12084. fingerprints.forEach(function(line) {
  12085. tmp = SDPUtil.parse_fingerprint(line);
  12086. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  12087. elem.c('fingerprint').t(tmp.fingerprint);
  12088. delete tmp.fingerprint;
  12089. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  12090. if (line) {
  12091. tmp.setup = line.substr(8);
  12092. }
  12093. elem.attrs(tmp);
  12094. elem.up(); // end of fingerprint
  12095. });
  12096. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  12097. if (tmp) {
  12098. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12099. elem.attrs(tmp);
  12100. // XEP-0176
  12101. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  12102. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  12103. lines.forEach(function (line) {
  12104. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  12105. });
  12106. }
  12107. }
  12108. elem.up(); // end of transport
  12109. }
  12110. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  12111. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  12112. lines.forEach(function (line) {
  12113. var tmp = SDPUtil.parse_rtcpfb(line);
  12114. if (tmp.type == 'trr-int') {
  12115. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  12116. elem.up();
  12117. } else {
  12118. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  12119. if (tmp.params.length > 0) {
  12120. elem.attrs({'subtype': tmp.params[0]});
  12121. }
  12122. elem.up();
  12123. }
  12124. });
  12125. };
  12126. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  12127. var media = '';
  12128. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12129. if (tmp.length) {
  12130. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  12131. if (tmp.attr('value')) {
  12132. media += tmp.attr('value');
  12133. } else {
  12134. media += '0';
  12135. }
  12136. media += '\r\n';
  12137. }
  12138. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12139. tmp.each(function () {
  12140. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  12141. if ($(this).attr('subtype')) {
  12142. media += ' ' + $(this).attr('subtype');
  12143. }
  12144. media += '\r\n';
  12145. });
  12146. return media;
  12147. };
  12148. // construct an SDP from a jingle stanza
  12149. SDP.prototype.fromJingle = function (jingle) {
  12150. var self = this;
  12151. this.raw = 'v=0\r\n' +
  12152. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12153. 's=-\r\n' +
  12154. 't=0 0\r\n';
  12155. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  12156. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  12157. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  12158. var contents = $(group).find('>content').map(function (idx, content) {
  12159. return content.getAttribute('name');
  12160. }).get();
  12161. if (contents.length > 0) {
  12162. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  12163. }
  12164. });
  12165. }
  12166. this.session = this.raw;
  12167. jingle.find('>content').each(function () {
  12168. var m = self.jingle2media($(this));
  12169. self.media.push(m);
  12170. });
  12171. // reconstruct msid-semantic -- apparently not necessary
  12172. /*
  12173. var msid = SDPUtil.parse_ssrc(this.raw);
  12174. if (msid.hasOwnProperty('mslabel')) {
  12175. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  12176. }
  12177. */
  12178. this.raw = this.session + this.media.join('');
  12179. };
  12180. // translate a jingle content element into an an SDP media part
  12181. SDP.prototype.jingle2media = function (content) {
  12182. var media = '',
  12183. desc = content.find('description'),
  12184. ssrc = desc.attr('ssrc'),
  12185. self = this,
  12186. tmp;
  12187. var sctp = content.find(
  12188. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  12189. tmp = { media: desc.attr('media') };
  12190. tmp.port = '1';
  12191. if (content.attr('senders') == 'rejected') {
  12192. // estos hack to reject an m-line.
  12193. tmp.port = '0';
  12194. }
  12195. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  12196. if (sctp.length)
  12197. tmp.proto = 'DTLS/SCTP';
  12198. else
  12199. tmp.proto = 'RTP/SAVPF';
  12200. } else {
  12201. tmp.proto = 'RTP/AVPF';
  12202. }
  12203. if (!sctp.length)
  12204. {
  12205. tmp.fmt = desc.find('payload-type').map(
  12206. function () { return this.getAttribute('id'); }).get();
  12207. media += SDPUtil.build_mline(tmp) + '\r\n';
  12208. }
  12209. else
  12210. {
  12211. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  12212. media += 'a=sctpmap:' + sctp.attr('number') +
  12213. ' ' + sctp.attr('protocol');
  12214. var streamCount = sctp.attr('streams');
  12215. if (streamCount)
  12216. media += ' ' + streamCount + '\r\n';
  12217. else
  12218. media += '\r\n';
  12219. }
  12220. media += 'c=IN IP4 0.0.0.0\r\n';
  12221. if (!sctp.length)
  12222. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  12223. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  12224. if (tmp.length) {
  12225. if (tmp.attr('ufrag')) {
  12226. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  12227. }
  12228. if (tmp.attr('pwd')) {
  12229. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  12230. }
  12231. tmp.find('>fingerprint').each(function () {
  12232. // FIXME: check namespace at some point
  12233. media += 'a=fingerprint:' + this.getAttribute('hash');
  12234. media += ' ' + $(this).text();
  12235. media += '\r\n';
  12236. if (this.getAttribute('setup')) {
  12237. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  12238. }
  12239. });
  12240. }
  12241. switch (content.attr('senders')) {
  12242. case 'initiator':
  12243. media += 'a=sendonly\r\n';
  12244. break;
  12245. case 'responder':
  12246. media += 'a=recvonly\r\n';
  12247. break;
  12248. case 'none':
  12249. media += 'a=inactive\r\n';
  12250. break;
  12251. case 'both':
  12252. media += 'a=sendrecv\r\n';
  12253. break;
  12254. }
  12255. media += 'a=mid:' + content.attr('name') + '\r\n';
  12256. // <description><rtcp-mux/></description>
  12257. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  12258. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  12259. if (desc.find('rtcp-mux').length) {
  12260. media += 'a=rtcp-mux\r\n';
  12261. }
  12262. if (desc.find('encryption').length) {
  12263. desc.find('encryption>crypto').each(function () {
  12264. media += 'a=crypto:' + this.getAttribute('tag');
  12265. media += ' ' + this.getAttribute('crypto-suite');
  12266. media += ' ' + this.getAttribute('key-params');
  12267. if (this.getAttribute('session-params')) {
  12268. media += ' ' + this.getAttribute('session-params');
  12269. }
  12270. media += '\r\n';
  12271. });
  12272. }
  12273. desc.find('payload-type').each(function () {
  12274. media += SDPUtil.build_rtpmap(this) + '\r\n';
  12275. if ($(this).find('>parameter').length) {
  12276. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  12277. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  12278. media += '\r\n';
  12279. }
  12280. // xep-0293
  12281. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  12282. });
  12283. // xep-0293
  12284. media += self.RtcpFbFromJingle(desc, '*');
  12285. // xep-0294
  12286. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  12287. tmp.each(function () {
  12288. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  12289. });
  12290. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  12291. media += SDPUtil.candidateFromJingle(this);
  12292. });
  12293. // XEP-0339 handle ssrc-group attributes
  12294. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12295. var semantics = this.getAttribute('semantics');
  12296. var ssrcs = $(this).find('>source').map(function() {
  12297. return this.getAttribute('ssrc');
  12298. }).get();
  12299. if (ssrcs.length != 0) {
  12300. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12301. }
  12302. });
  12303. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12304. tmp.each(function () {
  12305. var ssrc = this.getAttribute('ssrc');
  12306. $(this).find('>parameter').each(function () {
  12307. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  12308. if (this.getAttribute('value') && this.getAttribute('value').length)
  12309. media += ':' + this.getAttribute('value');
  12310. media += '\r\n';
  12311. });
  12312. });
  12313. return media;
  12314. };
  12315. module.exports = SDP;
  12316. },{"./SDPUtil":51}],50:[function(require,module,exports){
  12317. function SDPDiffer(mySDP, otherSDP) {
  12318. this.mySDP = mySDP;
  12319. this.otherSDP = otherSDP;
  12320. }
  12321. /**
  12322. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  12323. * @param otherSdp the other SDP to check ssrc with.
  12324. */
  12325. SDPDiffer.prototype.getNewMedia = function() {
  12326. // this could be useful in Array.prototype.
  12327. function arrayEquals(array) {
  12328. // if the other array is a falsy value, return
  12329. if (!array)
  12330. return false;
  12331. // compare lengths - can save a lot of time
  12332. if (this.length != array.length)
  12333. return false;
  12334. for (var i = 0, l=this.length; i < l; i++) {
  12335. // Check if we have nested arrays
  12336. if (this[i] instanceof Array && array[i] instanceof Array) {
  12337. // recurse into the nested arrays
  12338. if (!this[i].equals(array[i]))
  12339. return false;
  12340. }
  12341. else if (this[i] != array[i]) {
  12342. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12343. return false;
  12344. }
  12345. }
  12346. return true;
  12347. }
  12348. var myMedias = this.mySDP.getMediaSsrcMap();
  12349. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12350. var newMedia = {};
  12351. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12352. var myMedia = myMedias[othersMediaIdx];
  12353. var othersMedia = othersMedias[othersMediaIdx];
  12354. if(!myMedia && othersMedia) {
  12355. // Add whole channel
  12356. newMedia[othersMediaIdx] = othersMedia;
  12357. return;
  12358. }
  12359. // Look for new ssrcs accross the channel
  12360. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12361. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12362. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12363. if(!newMedia[othersMediaIdx]){
  12364. newMedia[othersMediaIdx] = {
  12365. mediaindex: othersMedia.mediaindex,
  12366. mid: othersMedia.mid,
  12367. ssrcs: {},
  12368. ssrcGroups: []
  12369. };
  12370. }
  12371. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12372. }
  12373. });
  12374. // Look for new ssrc groups across the channels
  12375. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12376. // try to match the other ssrc-group with an ssrc-group of ours
  12377. var matched = false;
  12378. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12379. var mySsrcGroup = myMedia.ssrcGroups[i];
  12380. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12381. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12382. matched = true;
  12383. break;
  12384. }
  12385. }
  12386. if (!matched) {
  12387. // Allocate channel if we've found an ssrc-group that doesn't
  12388. // exist in our channel
  12389. if(!newMedia[othersMediaIdx]){
  12390. newMedia[othersMediaIdx] = {
  12391. mediaindex: othersMedia.mediaindex,
  12392. mid: othersMedia.mid,
  12393. ssrcs: {},
  12394. ssrcGroups: []
  12395. };
  12396. }
  12397. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12398. }
  12399. });
  12400. });
  12401. return newMedia;
  12402. };
  12403. /**
  12404. * Sends SSRC update IQ.
  12405. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12406. * @param sid session identifier that will be put into the IQ.
  12407. * @param initiator initiator identifier.
  12408. * @param toJid destination Jid
  12409. * @param isAdd indicates if this is remove or add operation.
  12410. */
  12411. SDPDiffer.prototype.toJingle = function(modify) {
  12412. var sdpMediaSsrcs = this.getNewMedia();
  12413. var self = this;
  12414. // FIXME: only announce video ssrcs since we mix audio and dont need
  12415. // the audio ssrcs therefore
  12416. var modified = false;
  12417. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12418. modified = true;
  12419. var media = sdpMediaSsrcs[mediaindex];
  12420. modify.c('content', {name: media.mid});
  12421. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12422. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12423. // generate sources from lines
  12424. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12425. var mediaSsrc = media.ssrcs[ssrcNum];
  12426. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12427. modify.attrs({ssrc: mediaSsrc.ssrc});
  12428. // iterate over ssrc lines
  12429. mediaSsrc.lines.forEach(function (line) {
  12430. var idx = line.indexOf(' ');
  12431. var kv = line.substr(idx + 1);
  12432. modify.c('parameter');
  12433. if (kv.indexOf(':') == -1) {
  12434. modify.attrs({ name: kv });
  12435. } else {
  12436. modify.attrs({ name: kv.split(':', 2)[0] });
  12437. modify.attrs({ value: kv.split(':', 2)[1] });
  12438. }
  12439. modify.up(); // end of parameter
  12440. });
  12441. modify.up(); // end of source
  12442. });
  12443. // generate source groups from lines
  12444. media.ssrcGroups.forEach(function(ssrcGroup) {
  12445. if (ssrcGroup.ssrcs.length != 0) {
  12446. modify.c('ssrc-group', {
  12447. semantics: ssrcGroup.semantics,
  12448. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12449. });
  12450. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12451. modify.c('source', { ssrc: ssrc })
  12452. .up(); // end of source
  12453. });
  12454. modify.up(); // end of ssrc-group
  12455. }
  12456. });
  12457. modify.up(); // end of description
  12458. modify.up(); // end of content
  12459. });
  12460. return modified;
  12461. };
  12462. module.exports = SDPDiffer;
  12463. },{}],51:[function(require,module,exports){
  12464. SDPUtil = {
  12465. iceparams: function (mediadesc, sessiondesc) {
  12466. var data = null;
  12467. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  12468. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  12469. data = {
  12470. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  12471. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  12472. };
  12473. }
  12474. return data;
  12475. },
  12476. parse_iceufrag: function (line) {
  12477. return line.substring(12);
  12478. },
  12479. build_iceufrag: function (frag) {
  12480. return 'a=ice-ufrag:' + frag;
  12481. },
  12482. parse_icepwd: function (line) {
  12483. return line.substring(10);
  12484. },
  12485. build_icepwd: function (pwd) {
  12486. return 'a=ice-pwd:' + pwd;
  12487. },
  12488. parse_mid: function (line) {
  12489. return line.substring(6);
  12490. },
  12491. parse_mline: function (line) {
  12492. var parts = line.substring(2).split(' '),
  12493. data = {};
  12494. data.media = parts.shift();
  12495. data.port = parts.shift();
  12496. data.proto = parts.shift();
  12497. if (parts[parts.length - 1] === '') { // trailing whitespace
  12498. parts.pop();
  12499. }
  12500. data.fmt = parts;
  12501. return data;
  12502. },
  12503. build_mline: function (mline) {
  12504. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  12505. },
  12506. parse_rtpmap: function (line) {
  12507. var parts = line.substring(9).split(' '),
  12508. data = {};
  12509. data.id = parts.shift();
  12510. parts = parts[0].split('/');
  12511. data.name = parts.shift();
  12512. data.clockrate = parts.shift();
  12513. data.channels = parts.length ? parts.shift() : '1';
  12514. return data;
  12515. },
  12516. /**
  12517. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  12518. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  12519. * @returns [SCTP port number, protocol, streams]
  12520. */
  12521. parse_sctpmap: function (line)
  12522. {
  12523. var parts = line.substring(10).split(' ');
  12524. var sctpPort = parts[0];
  12525. var protocol = parts[1];
  12526. // Stream count is optional
  12527. var streamCount = parts.length > 2 ? parts[2] : null;
  12528. return [sctpPort, protocol, streamCount];// SCTP port
  12529. },
  12530. build_rtpmap: function (el) {
  12531. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  12532. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  12533. line += '/' + el.getAttribute('channels');
  12534. }
  12535. return line;
  12536. },
  12537. parse_crypto: function (line) {
  12538. var parts = line.substring(9).split(' '),
  12539. data = {};
  12540. data.tag = parts.shift();
  12541. data['crypto-suite'] = parts.shift();
  12542. data['key-params'] = parts.shift();
  12543. if (parts.length) {
  12544. data['session-params'] = parts.join(' ');
  12545. }
  12546. return data;
  12547. },
  12548. parse_fingerprint: function (line) { // RFC 4572
  12549. var parts = line.substring(14).split(' '),
  12550. data = {};
  12551. data.hash = parts.shift();
  12552. data.fingerprint = parts.shift();
  12553. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  12554. return data;
  12555. },
  12556. parse_fmtp: function (line) {
  12557. var parts = line.split(' '),
  12558. i, key, value,
  12559. data = [];
  12560. parts.shift();
  12561. parts = parts.join(' ').split(';');
  12562. for (i = 0; i < parts.length; i++) {
  12563. key = parts[i].split('=')[0];
  12564. while (key.length && key[0] == ' ') {
  12565. key = key.substring(1);
  12566. }
  12567. value = parts[i].split('=')[1];
  12568. if (key && value) {
  12569. data.push({name: key, value: value});
  12570. } else if (key) {
  12571. // rfc 4733 (DTMF) style stuff
  12572. data.push({name: '', value: key});
  12573. }
  12574. }
  12575. return data;
  12576. },
  12577. parse_icecandidate: function (line) {
  12578. var candidate = {},
  12579. elems = line.split(' ');
  12580. candidate.foundation = elems[0].substring(12);
  12581. candidate.component = elems[1];
  12582. candidate.protocol = elems[2].toLowerCase();
  12583. candidate.priority = elems[3];
  12584. candidate.ip = elems[4];
  12585. candidate.port = elems[5];
  12586. // elems[6] => "typ"
  12587. candidate.type = elems[7];
  12588. candidate.generation = 0; // default value, may be overwritten below
  12589. for (var i = 8; i < elems.length; i += 2) {
  12590. switch (elems[i]) {
  12591. case 'raddr':
  12592. candidate['rel-addr'] = elems[i + 1];
  12593. break;
  12594. case 'rport':
  12595. candidate['rel-port'] = elems[i + 1];
  12596. break;
  12597. case 'generation':
  12598. candidate.generation = elems[i + 1];
  12599. break;
  12600. case 'tcptype':
  12601. candidate.tcptype = elems[i + 1];
  12602. break;
  12603. default: // TODO
  12604. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12605. }
  12606. }
  12607. candidate.network = '1';
  12608. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12609. return candidate;
  12610. },
  12611. build_icecandidate: function (cand) {
  12612. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  12613. line += ' ';
  12614. switch (cand.type) {
  12615. case 'srflx':
  12616. case 'prflx':
  12617. case 'relay':
  12618. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  12619. line += 'raddr';
  12620. line += ' ';
  12621. line += cand['rel-addr'];
  12622. line += ' ';
  12623. line += 'rport';
  12624. line += ' ';
  12625. line += cand['rel-port'];
  12626. line += ' ';
  12627. }
  12628. break;
  12629. }
  12630. if (cand.hasOwnAttribute('tcptype')) {
  12631. line += 'tcptype';
  12632. line += ' ';
  12633. line += cand.tcptype;
  12634. line += ' ';
  12635. }
  12636. line += 'generation';
  12637. line += ' ';
  12638. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  12639. return line;
  12640. },
  12641. parse_ssrc: function (desc) {
  12642. // proprietary mapping of a=ssrc lines
  12643. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  12644. // and parse according to that
  12645. var lines = desc.split('\r\n'),
  12646. data = {};
  12647. for (var i = 0; i < lines.length; i++) {
  12648. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  12649. var idx = lines[i].indexOf(' ');
  12650. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  12651. }
  12652. }
  12653. return data;
  12654. },
  12655. parse_rtcpfb: function (line) {
  12656. var parts = line.substr(10).split(' ');
  12657. var data = {};
  12658. data.pt = parts.shift();
  12659. data.type = parts.shift();
  12660. data.params = parts;
  12661. return data;
  12662. },
  12663. parse_extmap: function (line) {
  12664. var parts = line.substr(9).split(' ');
  12665. var data = {};
  12666. data.value = parts.shift();
  12667. if (data.value.indexOf('/') != -1) {
  12668. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  12669. data.value = data.value.substr(0, data.value.indexOf('/'));
  12670. } else {
  12671. data.direction = 'both';
  12672. }
  12673. data.uri = parts.shift();
  12674. data.params = parts;
  12675. return data;
  12676. },
  12677. find_line: function (haystack, needle, sessionpart) {
  12678. var lines = haystack.split('\r\n');
  12679. for (var i = 0; i < lines.length; i++) {
  12680. if (lines[i].substring(0, needle.length) == needle) {
  12681. return lines[i];
  12682. }
  12683. }
  12684. if (!sessionpart) {
  12685. return false;
  12686. }
  12687. // search session part
  12688. lines = sessionpart.split('\r\n');
  12689. for (var j = 0; j < lines.length; j++) {
  12690. if (lines[j].substring(0, needle.length) == needle) {
  12691. return lines[j];
  12692. }
  12693. }
  12694. return false;
  12695. },
  12696. find_lines: function (haystack, needle, sessionpart) {
  12697. var lines = haystack.split('\r\n'),
  12698. needles = [];
  12699. for (var i = 0; i < lines.length; i++) {
  12700. if (lines[i].substring(0, needle.length) == needle)
  12701. needles.push(lines[i]);
  12702. }
  12703. if (needles.length || !sessionpart) {
  12704. return needles;
  12705. }
  12706. // search session part
  12707. lines = sessionpart.split('\r\n');
  12708. for (var j = 0; j < lines.length; j++) {
  12709. if (lines[j].substring(0, needle.length) == needle) {
  12710. needles.push(lines[j]);
  12711. }
  12712. }
  12713. return needles;
  12714. },
  12715. candidateToJingle: function (line) {
  12716. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  12717. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  12718. if (line.indexOf('candidate:') === 0) {
  12719. line = 'a=' + line;
  12720. } else if (line.substring(0, 12) != 'a=candidate:') {
  12721. console.log('parseCandidate called with a line that is not a candidate line');
  12722. console.log(line);
  12723. return null;
  12724. }
  12725. if (line.substring(line.length - 2) == '\r\n') // chomp it
  12726. line = line.substring(0, line.length - 2);
  12727. var candidate = {},
  12728. elems = line.split(' '),
  12729. i;
  12730. if (elems[6] != 'typ') {
  12731. console.log('did not find typ in the right place');
  12732. console.log(line);
  12733. return null;
  12734. }
  12735. candidate.foundation = elems[0].substring(12);
  12736. candidate.component = elems[1];
  12737. candidate.protocol = elems[2].toLowerCase();
  12738. candidate.priority = elems[3];
  12739. candidate.ip = elems[4];
  12740. candidate.port = elems[5];
  12741. // elems[6] => "typ"
  12742. candidate.type = elems[7];
  12743. candidate.generation = '0'; // default, may be overwritten below
  12744. for (i = 8; i < elems.length; i += 2) {
  12745. switch (elems[i]) {
  12746. case 'raddr':
  12747. candidate['rel-addr'] = elems[i + 1];
  12748. break;
  12749. case 'rport':
  12750. candidate['rel-port'] = elems[i + 1];
  12751. break;
  12752. case 'generation':
  12753. candidate.generation = elems[i + 1];
  12754. break;
  12755. case 'tcptype':
  12756. candidate.tcptype = elems[i + 1];
  12757. break;
  12758. default: // TODO
  12759. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12760. }
  12761. }
  12762. candidate.network = '1';
  12763. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12764. return candidate;
  12765. },
  12766. candidateFromJingle: function (cand) {
  12767. var line = 'a=candidate:';
  12768. line += cand.getAttribute('foundation');
  12769. line += ' ';
  12770. line += cand.getAttribute('component');
  12771. line += ' ';
  12772. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  12773. line += ' ';
  12774. line += cand.getAttribute('priority');
  12775. line += ' ';
  12776. line += cand.getAttribute('ip');
  12777. line += ' ';
  12778. line += cand.getAttribute('port');
  12779. line += ' ';
  12780. line += 'typ';
  12781. line += ' ' + cand.getAttribute('type');
  12782. line += ' ';
  12783. switch (cand.getAttribute('type')) {
  12784. case 'srflx':
  12785. case 'prflx':
  12786. case 'relay':
  12787. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  12788. line += 'raddr';
  12789. line += ' ';
  12790. line += cand.getAttribute('rel-addr');
  12791. line += ' ';
  12792. line += 'rport';
  12793. line += ' ';
  12794. line += cand.getAttribute('rel-port');
  12795. line += ' ';
  12796. }
  12797. break;
  12798. }
  12799. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  12800. line += 'tcptype';
  12801. line += ' ';
  12802. line += cand.getAttribute('tcptype');
  12803. line += ' ';
  12804. }
  12805. line += 'generation';
  12806. line += ' ';
  12807. line += cand.getAttribute('generation') || '0';
  12808. return line + '\r\n';
  12809. }
  12810. };
  12811. module.exports = SDPUtil;
  12812. },{}],52:[function(require,module,exports){
  12813. function TraceablePeerConnection(ice_config, constraints) {
  12814. var self = this;
  12815. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  12816. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  12817. this.updateLog = [];
  12818. this.stats = {};
  12819. this.statsinterval = null;
  12820. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  12821. var Interop = require('sdp-interop').Interop;
  12822. this.interop = new Interop();
  12823. // override as desired
  12824. this.trace = function (what, info) {
  12825. //console.warn('WTRACE', what, info);
  12826. self.updateLog.push({
  12827. time: new Date(),
  12828. type: what,
  12829. value: info || ""
  12830. });
  12831. };
  12832. this.onicecandidate = null;
  12833. this.peerconnection.onicecandidate = function (event) {
  12834. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  12835. if (self.onicecandidate !== null) {
  12836. self.onicecandidate(event);
  12837. }
  12838. };
  12839. this.onaddstream = null;
  12840. this.peerconnection.onaddstream = function (event) {
  12841. self.trace('onaddstream', event.stream.id);
  12842. if (self.onaddstream !== null) {
  12843. self.onaddstream(event);
  12844. }
  12845. };
  12846. this.onremovestream = null;
  12847. this.peerconnection.onremovestream = function (event) {
  12848. self.trace('onremovestream', event.stream.id);
  12849. if (self.onremovestream !== null) {
  12850. self.onremovestream(event);
  12851. }
  12852. };
  12853. this.onsignalingstatechange = null;
  12854. this.peerconnection.onsignalingstatechange = function (event) {
  12855. self.trace('onsignalingstatechange', self.signalingState);
  12856. if (self.onsignalingstatechange !== null) {
  12857. self.onsignalingstatechange(event);
  12858. }
  12859. };
  12860. this.oniceconnectionstatechange = null;
  12861. this.peerconnection.oniceconnectionstatechange = function (event) {
  12862. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12863. if (self.oniceconnectionstatechange !== null) {
  12864. self.oniceconnectionstatechange(event);
  12865. }
  12866. };
  12867. this.onnegotiationneeded = null;
  12868. this.peerconnection.onnegotiationneeded = function (event) {
  12869. self.trace('onnegotiationneeded');
  12870. if (self.onnegotiationneeded !== null) {
  12871. self.onnegotiationneeded(event);
  12872. }
  12873. };
  12874. self.ondatachannel = null;
  12875. this.peerconnection.ondatachannel = function (event) {
  12876. self.trace('ondatachannel', event);
  12877. if (self.ondatachannel !== null) {
  12878. self.ondatachannel(event);
  12879. }
  12880. };
  12881. if (!navigator.mozGetUserMedia && this.maxstats) {
  12882. this.statsinterval = window.setInterval(function() {
  12883. self.peerconnection.getStats(function(stats) {
  12884. var results = stats.result();
  12885. for (var i = 0; i < results.length; ++i) {
  12886. //console.log(results[i].type, results[i].id, results[i].names())
  12887. var now = new Date();
  12888. results[i].names().forEach(function (name) {
  12889. var id = results[i].id + '-' + name;
  12890. if (!self.stats[id]) {
  12891. self.stats[id] = {
  12892. startTime: now,
  12893. endTime: now,
  12894. values: [],
  12895. times: []
  12896. };
  12897. }
  12898. self.stats[id].values.push(results[i].stat(name));
  12899. self.stats[id].times.push(now.getTime());
  12900. if (self.stats[id].values.length > self.maxstats) {
  12901. self.stats[id].values.shift();
  12902. self.stats[id].times.shift();
  12903. }
  12904. self.stats[id].endTime = now;
  12905. });
  12906. }
  12907. });
  12908. }, 1000);
  12909. }
  12910. };
  12911. dumpSDP = function(description) {
  12912. if (typeof description === 'undefined' || description == null) {
  12913. return '';
  12914. }
  12915. return 'type: ' + description.type + '\r\n' + description.sdp;
  12916. };
  12917. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  12918. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  12919. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  12920. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  12921. this.trace('getLocalDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.localDescription));
  12922. // if we're running on FF, transform to Plan B first.
  12923. var desc = this.peerconnection.localDescription;
  12924. if (navigator.mozGetUserMedia) {
  12925. desc = this.interop.toPlanB(desc);
  12926. } else {
  12927. desc = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  12928. }
  12929. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  12930. return desc;
  12931. });
  12932. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  12933. this.trace('getRemoteDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.remoteDescription));
  12934. // if we're running on FF, transform to Plan B first.
  12935. var desc = this.peerconnection.remoteDescription;
  12936. if (navigator.mozGetUserMedia) {
  12937. desc = this.interop.toPlanB(desc);
  12938. } else {
  12939. desc = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  12940. }
  12941. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  12942. return desc;
  12943. });
  12944. }
  12945. TraceablePeerConnection.prototype.addStream = function (stream) {
  12946. this.trace('addStream', stream.id);
  12947. APP.simulcast.resetSender();
  12948. try
  12949. {
  12950. this.peerconnection.addStream(stream);
  12951. }
  12952. catch (e)
  12953. {
  12954. console.error(e);
  12955. return;
  12956. }
  12957. };
  12958. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  12959. this.trace('removeStream', stream.id);
  12960. APP.simulcast.resetSender();
  12961. if(stopStreams) {
  12962. stream.getAudioTracks().forEach(function (track) {
  12963. track.stop();
  12964. });
  12965. stream.getVideoTracks().forEach(function (track) {
  12966. track.stop();
  12967. });
  12968. }
  12969. try {
  12970. // FF doesn't support this yet.
  12971. this.peerconnection.removeStream(stream);
  12972. } catch (e) {
  12973. console.error(e);
  12974. }
  12975. };
  12976. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  12977. this.trace('createDataChannel', label, opts);
  12978. return this.peerconnection.createDataChannel(label, opts);
  12979. };
  12980. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  12981. this.trace('setLocalDescription::preTransform (Plan B)', dumpSDP(description));
  12982. // if we're running on FF, transform to Plan A first.
  12983. if (navigator.mozGetUserMedia) {
  12984. description = this.interop.toPlanA(description);
  12985. } else {
  12986. description = APP.simulcast.transformLocalDescription(description);
  12987. }
  12988. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  12989. var self = this;
  12990. this.peerconnection.setLocalDescription(description,
  12991. function () {
  12992. self.trace('setLocalDescriptionOnSuccess');
  12993. successCallback();
  12994. },
  12995. function (err) {
  12996. self.trace('setLocalDescriptionOnFailure', err);
  12997. failureCallback(err);
  12998. }
  12999. );
  13000. /*
  13001. if (this.statsinterval === null && this.maxstats > 0) {
  13002. // start gathering stats
  13003. }
  13004. */
  13005. };
  13006. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  13007. this.trace('setRemoteDescription::preTransform (Plan B)', dumpSDP(description));
  13008. // if we're running on FF, transform to Plan A first.
  13009. if (navigator.mozGetUserMedia) {
  13010. description = this.interop.toPlanA(description);
  13011. }
  13012. else {
  13013. description = APP.simulcast.transformRemoteDescription(description);
  13014. }
  13015. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  13016. var self = this;
  13017. this.peerconnection.setRemoteDescription(description,
  13018. function () {
  13019. self.trace('setRemoteDescriptionOnSuccess');
  13020. successCallback();
  13021. },
  13022. function (err) {
  13023. self.trace('setRemoteDescriptionOnFailure', err);
  13024. failureCallback(err);
  13025. }
  13026. );
  13027. /*
  13028. if (this.statsinterval === null && this.maxstats > 0) {
  13029. // start gathering stats
  13030. }
  13031. */
  13032. };
  13033. TraceablePeerConnection.prototype.close = function () {
  13034. this.trace('stop');
  13035. if (this.statsinterval !== null) {
  13036. window.clearInterval(this.statsinterval);
  13037. this.statsinterval = null;
  13038. }
  13039. this.peerconnection.close();
  13040. };
  13041. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  13042. var self = this;
  13043. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  13044. this.peerconnection.createOffer(
  13045. function (offer) {
  13046. self.trace('createOfferOnSuccess::preTransform (Plan A)', dumpSDP(offer));
  13047. // if we're running on FF, transform to Plan B first.
  13048. if (navigator.mozGetUserMedia) {
  13049. offer = self.interop.toPlanB(offer);
  13050. }
  13051. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  13052. successCallback(offer);
  13053. },
  13054. function(err) {
  13055. self.trace('createOfferOnFailure', err);
  13056. failureCallback(err);
  13057. },
  13058. constraints
  13059. );
  13060. };
  13061. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  13062. var self = this;
  13063. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  13064. this.peerconnection.createAnswer(
  13065. function (answer) {
  13066. self.trace('createAnswerOnSuccess::preTransfom (Plan A)', dumpSDP(answer));
  13067. // if we're running on FF, transform to Plan A first.
  13068. if (navigator.mozGetUserMedia) {
  13069. answer = self.interop.toPlanB(answer);
  13070. } else {
  13071. answer = APP.simulcast.transformAnswer(answer);
  13072. }
  13073. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  13074. successCallback(answer);
  13075. },
  13076. function(err) {
  13077. self.trace('createAnswerOnFailure', err);
  13078. failureCallback(err);
  13079. },
  13080. constraints
  13081. );
  13082. };
  13083. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  13084. var self = this;
  13085. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  13086. this.peerconnection.addIceCandidate(candidate);
  13087. /* maybe later
  13088. this.peerconnection.addIceCandidate(candidate,
  13089. function () {
  13090. self.trace('addIceCandidateOnSuccess');
  13091. successCallback();
  13092. },
  13093. function (err) {
  13094. self.trace('addIceCandidateOnFailure', err);
  13095. failureCallback(err);
  13096. }
  13097. );
  13098. */
  13099. };
  13100. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  13101. if (navigator.mozGetUserMedia) {
  13102. // ignore for now...
  13103. if(!errback)
  13104. errback = function () {
  13105. }
  13106. this.peerconnection.getStats(null,callback,errback);
  13107. } else {
  13108. this.peerconnection.getStats(callback);
  13109. }
  13110. };
  13111. module.exports = TraceablePeerConnection;
  13112. },{"sdp-interop":80}],53:[function(require,module,exports){
  13113. /* global $, $iq, APP, config, connection, UI, messageHandler,
  13114. roomName, sessionTerminated, Strophe, Util */
  13115. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13116. var Settings = require("../settings/Settings");
  13117. var AuthenticationEvents
  13118. = require("../../service/authentication/AuthenticationEvents");
  13119. /**
  13120. * Contains logic responsible for enabling/disabling functionality available
  13121. * only to moderator users.
  13122. */
  13123. var connection = null;
  13124. var focusUserJid;
  13125. function createExpBackoffTimer(step) {
  13126. var count = 1;
  13127. return function (reset) {
  13128. // Reset call
  13129. if (reset) {
  13130. count = 1;
  13131. return;
  13132. }
  13133. // Calculate next timeout
  13134. var timeout = Math.pow(2, count - 1);
  13135. count += 1;
  13136. return timeout * step;
  13137. };
  13138. }
  13139. var getNextTimeout = createExpBackoffTimer(1000);
  13140. var getNextErrorTimeout = createExpBackoffTimer(1000);
  13141. // External authentication stuff
  13142. var externalAuthEnabled = false;
  13143. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  13144. // it will be enabled automatically if focus detects the component through
  13145. // service discovery.
  13146. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  13147. var eventEmitter = null;
  13148. var Moderator = {
  13149. isModerator: function () {
  13150. return connection && connection.emuc.isModerator();
  13151. },
  13152. isPeerModerator: function (peerJid) {
  13153. return connection &&
  13154. connection.emuc.getMemberRole(peerJid) === 'moderator';
  13155. },
  13156. isExternalAuthEnabled: function () {
  13157. return externalAuthEnabled;
  13158. },
  13159. isSipGatewayEnabled: function () {
  13160. return sipGatewayEnabled;
  13161. },
  13162. setConnection: function (con) {
  13163. connection = con;
  13164. },
  13165. init: function (xmpp, emitter) {
  13166. this.xmppService = xmpp;
  13167. eventEmitter = emitter;
  13168. // Message listener that talks to POPUP window
  13169. function listener(event) {
  13170. if (event.data && event.data.sessionId) {
  13171. if (event.origin !== window.location.origin) {
  13172. console.warn(
  13173. "Ignoring sessionId from different origin: " + event.origin);
  13174. return;
  13175. }
  13176. localStorage.setItem('sessionId', event.data.sessionId);
  13177. // After popup is closed we will authenticate
  13178. }
  13179. }
  13180. // Register
  13181. if (window.addEventListener) {
  13182. window.addEventListener("message", listener, false);
  13183. } else {
  13184. window.attachEvent("onmessage", listener);
  13185. }
  13186. },
  13187. onMucLeft: function (jid) {
  13188. console.info("Someone left is it focus ? " + jid);
  13189. var resource = Strophe.getResourceFromJid(jid);
  13190. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  13191. console.info(
  13192. "Focus has left the room - leaving conference");
  13193. //hangUp();
  13194. // We'd rather reload to have everything re-initialized
  13195. // FIXME: show some message before reload
  13196. location.reload();
  13197. }
  13198. },
  13199. setFocusUserJid: function (focusJid) {
  13200. if (!focusUserJid) {
  13201. focusUserJid = focusJid;
  13202. console.info("Focus jid set to: " + focusUserJid);
  13203. }
  13204. },
  13205. getFocusUserJid: function () {
  13206. return focusUserJid;
  13207. },
  13208. getFocusComponent: function () {
  13209. // Get focus component address
  13210. var focusComponent = config.hosts.focus;
  13211. // If not specified use default: 'focus.domain'
  13212. if (!focusComponent) {
  13213. focusComponent = 'focus.' + config.hosts.domain;
  13214. }
  13215. return focusComponent;
  13216. },
  13217. createConferenceIq: function (roomName) {
  13218. // Generate create conference IQ
  13219. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13220. // Session Id used for authentication
  13221. var sessionId = localStorage.getItem('sessionId');
  13222. var machineUID = Settings.getSettings().uid;
  13223. console.info(
  13224. "Session ID: " + sessionId + " machine UID: " + machineUID);
  13225. elem.c('conference', {
  13226. xmlns: 'http://jitsi.org/protocol/focus',
  13227. room: roomName,
  13228. 'machine-uid': machineUID
  13229. });
  13230. if (sessionId) {
  13231. elem.attrs({ 'session-id': sessionId});
  13232. }
  13233. if (config.hosts.bridge !== undefined) {
  13234. elem.c(
  13235. 'property',
  13236. { name: 'bridge', value: config.hosts.bridge})
  13237. .up();
  13238. }
  13239. // Tell the focus we have Jigasi configured
  13240. if (config.hosts.call_control !== undefined) {
  13241. elem.c(
  13242. 'property',
  13243. { name: 'call_control', value: config.hosts.call_control})
  13244. .up();
  13245. }
  13246. if (config.channelLastN !== undefined) {
  13247. elem.c(
  13248. 'property',
  13249. { name: 'channelLastN', value: config.channelLastN})
  13250. .up();
  13251. }
  13252. if (config.adaptiveLastN !== undefined) {
  13253. elem.c(
  13254. 'property',
  13255. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  13256. .up();
  13257. }
  13258. if (config.adaptiveSimulcast !== undefined) {
  13259. elem.c(
  13260. 'property',
  13261. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  13262. .up();
  13263. }
  13264. if (config.openSctp !== undefined) {
  13265. elem.c(
  13266. 'property',
  13267. { name: 'openSctp', value: config.openSctp})
  13268. .up();
  13269. }
  13270. var roomName = APP.UI.generateRoomName();
  13271. if (typeof roomName !== 'string') roomName = '';
  13272. if (config.enableFirefoxSupport !== undefined && roomName.indexOf('rembson@') === -1) {
  13273. elem.c(
  13274. 'property',
  13275. { name: 'enableFirefoxHacks',
  13276. value: config.enableFirefoxSupport})
  13277. .up();
  13278. }
  13279. elem.up();
  13280. return elem;
  13281. },
  13282. parseSessionId: function (resultIq) {
  13283. var sessionId = $(resultIq).find('conference').attr('session-id');
  13284. if (sessionId) {
  13285. console.info('Received sessionId: ' + sessionId);
  13286. localStorage.setItem('sessionId', sessionId);
  13287. }
  13288. },
  13289. parseConfigOptions: function (resultIq) {
  13290. Moderator.setFocusUserJid(
  13291. $(resultIq).find('conference').attr('focusjid'));
  13292. var authenticationEnabled
  13293. = $(resultIq).find(
  13294. '>conference>property' +
  13295. '[name=\'authentication\'][value=\'true\']').length > 0;
  13296. console.info("Authentication enabled: " + authenticationEnabled);
  13297. externalAuthEnabled
  13298. = $(resultIq).find(
  13299. '>conference>property' +
  13300. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  13301. console.info('External authentication enabled: ' + externalAuthEnabled);
  13302. if (!externalAuthEnabled) {
  13303. // We expect to receive sessionId in 'internal' authentication mode
  13304. Moderator.parseSessionId(resultIq);
  13305. }
  13306. var authIdentity = $(resultIq).find('>conference').attr('identity');
  13307. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  13308. authenticationEnabled, authIdentity);
  13309. // Check if focus has auto-detected Jigasi component(this will be also
  13310. // included if we have passed our host from the config)
  13311. if ($(resultIq).find(
  13312. '>conference>property' +
  13313. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  13314. sipGatewayEnabled = true;
  13315. }
  13316. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  13317. },
  13318. // FIXME: we need to show the fact that we're waiting for the focus
  13319. // to the user(or that focus is not available)
  13320. allocateConferenceFocus: function (roomName, callback) {
  13321. // Try to use focus user JID from the config
  13322. Moderator.setFocusUserJid(config.focusUserJid);
  13323. // Send create conference IQ
  13324. var iq = Moderator.createConferenceIq(roomName);
  13325. var self = this;
  13326. connection.sendIQ(
  13327. iq,
  13328. function (result) {
  13329. // Setup config options
  13330. Moderator.parseConfigOptions(result);
  13331. if ('true' === $(result).find('conference').attr('ready')) {
  13332. // Reset both timers
  13333. getNextTimeout(true);
  13334. getNextErrorTimeout(true);
  13335. // Exec callback
  13336. callback();
  13337. } else {
  13338. var waitMs = getNextTimeout();
  13339. console.info("Waiting for the focus... " + waitMs);
  13340. // Reset error timeout
  13341. getNextErrorTimeout(true);
  13342. window.setTimeout(
  13343. function () {
  13344. Moderator.allocateConferenceFocus(
  13345. roomName, callback);
  13346. }, waitMs);
  13347. }
  13348. },
  13349. function (error) {
  13350. // Invalid session ? remove and try again
  13351. // without session ID to get a new one
  13352. var invalidSession
  13353. = $(error).find('>error>session-invalid').length;
  13354. if (invalidSession) {
  13355. console.info("Session expired! - removing");
  13356. localStorage.removeItem("sessionId");
  13357. }
  13358. if ($(error).find('>error>graceful-shutdown').length) {
  13359. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  13360. return;
  13361. }
  13362. // Check for error returned by the reservation system
  13363. var reservationErr = $(error).find('>error>reservation-error');
  13364. if (reservationErr.length) {
  13365. // Trigger error event
  13366. var errorCode = reservationErr.attr('error-code');
  13367. var errorMsg;
  13368. if ($(error).find('>error>text')) {
  13369. errorMsg = $(error).find('>error>text').text();
  13370. }
  13371. eventEmitter.emit(
  13372. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  13373. return;
  13374. }
  13375. // Not authorized to create new room
  13376. if ($(error).find('>error>not-authorized').length) {
  13377. console.warn("Unauthorized to start the conference", error);
  13378. var toDomain
  13379. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13380. if (toDomain !== config.hosts.anonymousdomain) {
  13381. // FIXME: "is external" should come either from
  13382. // the focus or config.js
  13383. externalAuthEnabled = true;
  13384. }
  13385. eventEmitter.emit(
  13386. XMPPEvents.AUTHENTICATION_REQUIRED,
  13387. function () {
  13388. Moderator.allocateConferenceFocus(
  13389. roomName, callback);
  13390. });
  13391. return;
  13392. }
  13393. var waitMs = getNextErrorTimeout();
  13394. console.error("Focus error, retry after " + waitMs, error);
  13395. // Show message
  13396. var focusComponent = Moderator.getFocusComponent();
  13397. var retrySec = waitMs / 1000;
  13398. // FIXME: message is duplicated ?
  13399. // Do not show in case of session invalid
  13400. // which means just a retry
  13401. if (!invalidSession) {
  13402. APP.UI.messageHandler.notify(
  13403. null, "notify.focus",
  13404. 'disconnected', "notify.focusFail",
  13405. {component: focusComponent, ms: retrySec});
  13406. }
  13407. // Reset response timeout
  13408. getNextTimeout(true);
  13409. window.setTimeout(
  13410. function () {
  13411. Moderator.allocateConferenceFocus(roomName, callback);
  13412. }, waitMs);
  13413. }
  13414. );
  13415. },
  13416. getLoginUrl: function (roomName, urlCallback) {
  13417. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13418. iq.c('login-url', {
  13419. xmlns: 'http://jitsi.org/protocol/focus',
  13420. room: roomName,
  13421. 'machine-uid': Settings.getSettings().uid
  13422. });
  13423. connection.sendIQ(
  13424. iq,
  13425. function (result) {
  13426. var url = $(result).find('login-url').attr('url');
  13427. url = url = decodeURIComponent(url);
  13428. if (url) {
  13429. console.info("Got auth url: " + url);
  13430. urlCallback(url);
  13431. } else {
  13432. console.error(
  13433. "Failed to get auth url from the focus", result);
  13434. }
  13435. },
  13436. function (error) {
  13437. console.error("Get auth url error", error);
  13438. }
  13439. );
  13440. },
  13441. getPopupLoginUrl: function (roomName, urlCallback) {
  13442. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13443. iq.c('login-url', {
  13444. xmlns: 'http://jitsi.org/protocol/focus',
  13445. room: roomName,
  13446. 'machine-uid': Settings.getSettings().uid,
  13447. popup: true
  13448. });
  13449. connection.sendIQ(
  13450. iq,
  13451. function (result) {
  13452. var url = $(result).find('login-url').attr('url');
  13453. url = url = decodeURIComponent(url);
  13454. if (url) {
  13455. console.info("Got POPUP auth url: " + url);
  13456. urlCallback(url);
  13457. } else {
  13458. console.error(
  13459. "Failed to get POPUP auth url from the focus", result);
  13460. }
  13461. },
  13462. function (error) {
  13463. console.error('Get POPUP auth url error', error);
  13464. }
  13465. );
  13466. },
  13467. logout: function (callback) {
  13468. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13469. var sessionId = localStorage.getItem('sessionId');
  13470. if (!sessionId) {
  13471. callback();
  13472. return;
  13473. }
  13474. iq.c('logout', {
  13475. xmlns: 'http://jitsi.org/protocol/focus',
  13476. 'session-id': sessionId
  13477. });
  13478. connection.sendIQ(
  13479. iq,
  13480. function (result) {
  13481. var logoutUrl = $(result).find('logout').attr('logout-url');
  13482. if (logoutUrl) {
  13483. logoutUrl = decodeURIComponent(logoutUrl);
  13484. }
  13485. console.info("Log out OK, url: " + logoutUrl, result);
  13486. localStorage.removeItem('sessionId');
  13487. callback(logoutUrl);
  13488. },
  13489. function (error) {
  13490. console.error("Logout error", error);
  13491. }
  13492. );
  13493. }
  13494. };
  13495. module.exports = Moderator;
  13496. },{"../../service/authentication/AuthenticationEvents":93,"../../service/xmpp/XMPPEvents":97,"../settings/Settings":38}],54:[function(require,module,exports){
  13497. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  13498. Toolbar, Util */
  13499. var Moderator = require("./moderator");
  13500. var recordingToken = null;
  13501. var recordingEnabled;
  13502. /**
  13503. * Whether to use a jirecon component for recording, or use the videobridge
  13504. * through COLIBRI.
  13505. */
  13506. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  13507. /**
  13508. * The ID of the jirecon recording session. Jirecon generates it when we
  13509. * initially start recording, and it needs to be used in subsequent requests
  13510. * to jirecon.
  13511. */
  13512. var jireconRid = null;
  13513. function setRecordingToken(token) {
  13514. recordingToken = token;
  13515. }
  13516. function setRecording(state, token, callback, connection) {
  13517. if (useJirecon){
  13518. setRecordingJirecon(state, token, callback, connection);
  13519. } else {
  13520. setRecordingColibri(state, token, callback, connection);
  13521. }
  13522. }
  13523. function setRecordingJirecon(state, token, callback, connection) {
  13524. if (state == recordingEnabled){
  13525. return;
  13526. }
  13527. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  13528. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  13529. action: state ? 'start' : 'stop',
  13530. mucjid: connection.emuc.roomjid});
  13531. if (!state){
  13532. iq.attrs({rid: jireconRid});
  13533. }
  13534. console.log('Start recording');
  13535. connection.sendIQ(
  13536. iq,
  13537. function (result) {
  13538. // TODO wait for an IQ with the real status, since this is
  13539. // provisional?
  13540. jireconRid = $(result).find('recording').attr('rid');
  13541. console.log('Recording ' + (state ? 'started' : 'stopped') +
  13542. '(jirecon)' + result);
  13543. recordingEnabled = state;
  13544. if (!state){
  13545. jireconRid = null;
  13546. }
  13547. callback(state);
  13548. },
  13549. function (error) {
  13550. console.log('Failed to start recording, error: ', error);
  13551. callback(recordingEnabled);
  13552. });
  13553. }
  13554. // Sends a COLIBRI message which enables or disables (according to 'state')
  13555. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  13556. // with the new recording state, according to the IQ.
  13557. function setRecordingColibri(state, token, callback, connection) {
  13558. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  13559. elem.c('conference', {
  13560. xmlns: 'http://jitsi.org/protocol/colibri'
  13561. });
  13562. elem.c('recording', {state: state, token: token});
  13563. connection.sendIQ(elem,
  13564. function (result) {
  13565. console.log('Set recording "', state, '". Result:', result);
  13566. var recordingElem = $(result).find('>conference>recording');
  13567. var newState = ('true' === recordingElem.attr('state'));
  13568. recordingEnabled = newState;
  13569. callback(newState);
  13570. },
  13571. function (error) {
  13572. console.warn(error);
  13573. callback(recordingEnabled);
  13574. }
  13575. );
  13576. }
  13577. var Recording = {
  13578. toggleRecording: function (tokenEmptyCallback,
  13579. startingCallback, startedCallback, connection) {
  13580. if (!Moderator.isModerator()) {
  13581. console.log(
  13582. 'non-focus, or conference not yet organized:' +
  13583. ' not enabling recording');
  13584. return;
  13585. }
  13586. var self = this;
  13587. // Jirecon does not (currently) support a token.
  13588. if (!recordingToken && !useJirecon) {
  13589. tokenEmptyCallback(function (value) {
  13590. setRecordingToken(value);
  13591. self.toggleRecording(tokenEmptyCallback,
  13592. startingCallback, startedCallback, connection);
  13593. });
  13594. return;
  13595. }
  13596. var oldState = recordingEnabled;
  13597. startingCallback(!oldState);
  13598. setRecording(!oldState,
  13599. recordingToken,
  13600. function (state) {
  13601. console.log("New recording state: ", state);
  13602. if (state === oldState) {
  13603. // FIXME: new focus:
  13604. // this will not work when moderator changes
  13605. // during active session. Then it will assume that
  13606. // recording status has changed to true, but it might have
  13607. // been already true(and we only received actual status from
  13608. // the focus).
  13609. //
  13610. // SO we start with status null, so that it is initialized
  13611. // here and will fail only after second click, so if invalid
  13612. // token was used we have to press the button twice before
  13613. // current status will be fetched and token will be reset.
  13614. //
  13615. // Reliable way would be to return authentication error.
  13616. // Or status update when moderator connects.
  13617. // Or we have to stop recording session when current
  13618. // moderator leaves the room.
  13619. // Failed to change, reset the token because it might
  13620. // have been wrong
  13621. setRecordingToken(null);
  13622. }
  13623. startedCallback(state);
  13624. },
  13625. connection
  13626. );
  13627. }
  13628. }
  13629. module.exports = Recording;
  13630. },{"./moderator":53}],55:[function(require,module,exports){
  13631. /* jshint -W117 */
  13632. /* a simple MUC connection plugin
  13633. * can only handle a single MUC room
  13634. */
  13635. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13636. var Moderator = require("./moderator");
  13637. var JingleSession = require("./JingleSession");
  13638. var bridgeIsDown = false;
  13639. module.exports = function(XMPP, eventEmitter) {
  13640. Strophe.addConnectionPlugin('emuc', {
  13641. connection: null,
  13642. roomjid: null,
  13643. myroomjid: null,
  13644. members: {},
  13645. list_members: [], // so we can elect a new focus
  13646. presMap: {},
  13647. preziMap: {},
  13648. joined: false,
  13649. isOwner: false,
  13650. role: null,
  13651. focusMucJid: null,
  13652. ssrc2jid: {},
  13653. init: function (conn) {
  13654. this.connection = conn;
  13655. },
  13656. initPresenceMap: function (myroomjid) {
  13657. this.presMap['to'] = myroomjid;
  13658. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  13659. },
  13660. doJoin: function (jid, password) {
  13661. this.myroomjid = jid;
  13662. console.info("Joined MUC as " + this.myroomjid);
  13663. this.initPresenceMap(this.myroomjid);
  13664. if (!this.roomjid) {
  13665. this.roomjid = Strophe.getBareJidFromJid(jid);
  13666. // add handlers (just once)
  13667. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  13668. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  13669. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  13670. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  13671. }
  13672. if (password !== undefined) {
  13673. this.presMap['password'] = password;
  13674. }
  13675. this.sendPresence();
  13676. },
  13677. doLeave: function () {
  13678. console.log("do leave", this.myroomjid);
  13679. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  13680. this.presMap.length = 0;
  13681. this.connection.send(pres);
  13682. },
  13683. createNonAnonymousRoom: function () {
  13684. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  13685. var getForm = $iq({type: 'get', to: this.roomjid})
  13686. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  13687. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13688. var self = this;
  13689. this.connection.sendIQ(getForm, function (form) {
  13690. if (!$(form).find(
  13691. '>query>x[xmlns="jabber:x:data"]' +
  13692. '>field[var="muc#roomconfig_whois"]').length) {
  13693. console.error('non-anonymous rooms not supported');
  13694. return;
  13695. }
  13696. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  13697. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13698. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13699. formSubmit.c('field', {'var': 'FORM_TYPE'})
  13700. .c('value')
  13701. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13702. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  13703. .c('value').t('anyone').up().up();
  13704. self.connection.sendIQ(formSubmit);
  13705. }, function (error) {
  13706. console.error("Error getting room configuration form");
  13707. });
  13708. },
  13709. onPresence: function (pres) {
  13710. var from = pres.getAttribute('from');
  13711. // What is this for? A workaround for something?
  13712. if (pres.getAttribute('type')) {
  13713. return true;
  13714. }
  13715. // Parse etherpad tag.
  13716. var etherpad = $(pres).find('>etherpad');
  13717. if (etherpad.length) {
  13718. if (config.etherpad_base && !Moderator.isModerator()) {
  13719. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  13720. }
  13721. }
  13722. // Parse prezi tag.
  13723. var presentation = $(pres).find('>prezi');
  13724. if (presentation.length) {
  13725. var url = presentation.attr('url');
  13726. var current = presentation.find('>current').text();
  13727. console.log('presentation info received from', from, url);
  13728. if (this.preziMap[from] == null) {
  13729. this.preziMap[from] = url;
  13730. $(document).trigger('presentationadded.muc', [from, url, current]);
  13731. }
  13732. else {
  13733. $(document).trigger('gotoslide.muc', [from, url, current]);
  13734. }
  13735. }
  13736. else if (this.preziMap[from] != null) {
  13737. var url = this.preziMap[from];
  13738. delete this.preziMap[from];
  13739. $(document).trigger('presentationremoved.muc', [from, url]);
  13740. }
  13741. // Parse audio info tag.
  13742. var audioMuted = $(pres).find('>audiomuted');
  13743. if (audioMuted.length) {
  13744. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  13745. }
  13746. // Parse video info tag.
  13747. var videoMuted = $(pres).find('>videomuted');
  13748. if (videoMuted.length) {
  13749. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  13750. }
  13751. var stats = $(pres).find('>stats');
  13752. if (stats.length) {
  13753. var statsObj = {};
  13754. Strophe.forEachChild(stats[0], "stat", function (el) {
  13755. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  13756. });
  13757. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  13758. }
  13759. // Parse status.
  13760. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  13761. this.isOwner = true;
  13762. this.createNonAnonymousRoom();
  13763. }
  13764. // Parse roles.
  13765. var member = {};
  13766. member.show = $(pres).find('>show').text();
  13767. member.status = $(pres).find('>status').text();
  13768. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  13769. member.affiliation = tmp.attr('affiliation');
  13770. member.role = tmp.attr('role');
  13771. // Focus recognition
  13772. member.jid = tmp.attr('jid');
  13773. member.isFocus = false;
  13774. if (member.jid
  13775. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  13776. member.isFocus = true;
  13777. }
  13778. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  13779. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  13780. if (from == this.myroomjid) {
  13781. if (member.affiliation == 'owner') this.isOwner = true;
  13782. if (this.role !== member.role) {
  13783. this.role = member.role;
  13784. eventEmitter.emit(XMPPEvents.LOCALROLE_CHANGED,
  13785. from, member, pres, Moderator.isModerator());
  13786. }
  13787. if (!this.joined) {
  13788. this.joined = true;
  13789. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  13790. this.list_members.push(from);
  13791. }
  13792. } else if (this.members[from] === undefined) {
  13793. // new participant
  13794. this.members[from] = member;
  13795. this.list_members.push(from);
  13796. console.log('entered', from, member);
  13797. if (member.isFocus) {
  13798. this.focusMucJid = from;
  13799. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  13800. }
  13801. else {
  13802. var id = $(pres).find('>userID').text();
  13803. var email = $(pres).find('>email');
  13804. if (email.length > 0) {
  13805. id = email.text();
  13806. }
  13807. eventEmitter.emit(XMPPEvents.MUC_ENTER, from, id, member.displayName);
  13808. }
  13809. } else {
  13810. // Presence update for existing participant
  13811. // Watch role change:
  13812. if (this.members[from].role != member.role) {
  13813. this.members[from].role = member.role;
  13814. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  13815. member.role, member.displayName);
  13816. }
  13817. }
  13818. // Always trigger presence to update bindings
  13819. this.parsePresence(from, member, pres);
  13820. // Trigger status message update
  13821. if (member.status) {
  13822. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  13823. }
  13824. return true;
  13825. },
  13826. onPresenceUnavailable: function (pres) {
  13827. var from = pres.getAttribute('from');
  13828. // room destroyed ?
  13829. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13830. '>destroy').length) {
  13831. var reason;
  13832. var reasonSelect = $(pres).find(
  13833. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13834. '>destroy>reason');
  13835. if (reasonSelect.length) {
  13836. reason = reasonSelect.text();
  13837. }
  13838. XMPP.disposeConference(false);
  13839. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  13840. return true;
  13841. }
  13842. // Status code 110 indicates that this notification is "self-presence".
  13843. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  13844. delete this.members[from];
  13845. this.list_members.splice(this.list_members.indexOf(from), 1);
  13846. this.onParticipantLeft(from);
  13847. }
  13848. // If the status code is 110 this means we're leaving and we would like
  13849. // to remove everyone else from our view, so we trigger the event.
  13850. else if (this.list_members.length > 1) {
  13851. for (var i = 0; i < this.list_members.length; i++) {
  13852. var member = this.list_members[i];
  13853. delete this.members[i];
  13854. this.list_members.splice(i, 1);
  13855. this.onParticipantLeft(member);
  13856. }
  13857. }
  13858. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  13859. $(document).trigger('kicked.muc', [from]);
  13860. if (this.myroomjid === from) {
  13861. XMPP.disposeConference(false);
  13862. eventEmitter.emit(XMPPEvents.KICKED);
  13863. }
  13864. }
  13865. return true;
  13866. },
  13867. onPresenceError: function (pres) {
  13868. var from = pres.getAttribute('from');
  13869. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13870. console.log('on password required', from);
  13871. var self = this;
  13872. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  13873. self.doJoin(from, value);
  13874. });
  13875. } else if ($(pres).find(
  13876. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13877. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  13878. if (toDomain === config.hosts.anonymousdomain) {
  13879. // enter the room by replying with 'not-authorized'. This would
  13880. // result in reconnection from authorized domain.
  13881. // We're either missing Jicofo/Prosody config for anonymous
  13882. // domains or something is wrong.
  13883. // XMPP.promptLogin();
  13884. APP.UI.messageHandler.openReportDialog(null,
  13885. "dialog.joinError", pres);
  13886. } else {
  13887. console.warn('onPresError ', pres);
  13888. APP.UI.messageHandler.openReportDialog(null,
  13889. "dialog.connectError",
  13890. pres);
  13891. }
  13892. } else {
  13893. console.warn('onPresError ', pres);
  13894. APP.UI.messageHandler.openReportDialog(null,
  13895. "dialog.connectError",
  13896. pres);
  13897. }
  13898. return true;
  13899. },
  13900. sendMessage: function (body, nickname) {
  13901. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13902. msg.c('body', body).up();
  13903. if (nickname) {
  13904. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  13905. }
  13906. this.connection.send(msg);
  13907. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  13908. },
  13909. setSubject: function (subject) {
  13910. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13911. msg.c('subject', subject);
  13912. this.connection.send(msg);
  13913. console.log("topic changed to " + subject);
  13914. },
  13915. onMessage: function (msg) {
  13916. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  13917. var from = msg.getAttribute('from');
  13918. var nick =
  13919. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  13920. .text() ||
  13921. Strophe.getResourceFromJid(from);
  13922. var txt = $(msg).find('>body').text();
  13923. var type = msg.getAttribute("type");
  13924. if (type == "error") {
  13925. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  13926. $(msg).find('>text').text(), txt);
  13927. return true;
  13928. }
  13929. var subject = $(msg).find('>subject');
  13930. if (subject.length) {
  13931. var subjectText = subject.text();
  13932. if (subjectText || subjectText == "") {
  13933. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  13934. console.log("Subject is changed to " + subjectText);
  13935. }
  13936. }
  13937. if (txt) {
  13938. console.log('chat', nick, txt);
  13939. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  13940. from, nick, txt, this.myroomjid);
  13941. }
  13942. return true;
  13943. },
  13944. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  13945. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  13946. var ob = this;
  13947. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  13948. function (res) {
  13949. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  13950. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13951. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13952. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13953. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  13954. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  13955. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  13956. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  13957. ob.connection.sendIQ(formsubmit,
  13958. onSuccess,
  13959. onError);
  13960. } else {
  13961. onNotSupported();
  13962. }
  13963. }, onError);
  13964. },
  13965. kick: function (jid) {
  13966. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  13967. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  13968. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  13969. .c('reason').t('You have been kicked.').up().up().up();
  13970. this.connection.sendIQ(
  13971. kickIQ,
  13972. function (result) {
  13973. console.log('Kick participant with jid: ', jid, result);
  13974. },
  13975. function (error) {
  13976. console.log('Kick participant error: ', error);
  13977. });
  13978. },
  13979. sendPresence: function () {
  13980. var pres = $pres({to: this.presMap['to'] });
  13981. pres.c('x', {xmlns: this.presMap['xns']});
  13982. if (this.presMap['password']) {
  13983. pres.c('password').t(this.presMap['password']).up();
  13984. }
  13985. pres.up();
  13986. // Send XEP-0115 'c' stanza that contains our capabilities info
  13987. if (this.connection.caps) {
  13988. this.connection.caps.node = config.clientNode;
  13989. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  13990. }
  13991. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  13992. .t(navigator.userAgent).up();
  13993. if (this.presMap['bridgeIsDown']) {
  13994. pres.c('bridgeIsDown').up();
  13995. }
  13996. if (this.presMap['email']) {
  13997. pres.c('email').t(this.presMap['email']).up();
  13998. }
  13999. if (this.presMap['userId']) {
  14000. pres.c('userId').t(this.presMap['userId']).up();
  14001. }
  14002. if (this.presMap['displayName']) {
  14003. // XEP-0172
  14004. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  14005. .t(this.presMap['displayName']).up();
  14006. }
  14007. if (this.presMap['audions']) {
  14008. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  14009. .t(this.presMap['audiomuted']).up();
  14010. }
  14011. if (this.presMap['videons']) {
  14012. pres.c('videomuted', {xmlns: this.presMap['videons']})
  14013. .t(this.presMap['videomuted']).up();
  14014. }
  14015. if (this.presMap['statsns']) {
  14016. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  14017. for (var stat in this.presMap["stats"])
  14018. if (this.presMap["stats"][stat] != null)
  14019. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  14020. pres.up();
  14021. }
  14022. if (this.presMap['prezins']) {
  14023. pres.c('prezi',
  14024. {xmlns: this.presMap['prezins'],
  14025. 'url': this.presMap['preziurl']})
  14026. .c('current').t(this.presMap['prezicurrent']).up().up();
  14027. }
  14028. if (this.presMap['etherpadns']) {
  14029. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  14030. .t(this.presMap['etherpadname']).up();
  14031. }
  14032. if (this.presMap['medians']) {
  14033. pres.c('media', {xmlns: this.presMap['medians']});
  14034. var sourceNumber = 0;
  14035. Object.keys(this.presMap).forEach(function (key) {
  14036. if (key.indexOf('source') >= 0) {
  14037. sourceNumber++;
  14038. }
  14039. });
  14040. if (sourceNumber > 0)
  14041. for (var i = 1; i <= sourceNumber / 3; i++) {
  14042. pres.c('source',
  14043. {type: this.presMap['source' + i + '_type'],
  14044. ssrc: this.presMap['source' + i + '_ssrc'],
  14045. direction: this.presMap['source' + i + '_direction']
  14046. || 'sendrecv' }
  14047. ).up();
  14048. }
  14049. }
  14050. pres.up();
  14051. this.connection.send(pres);
  14052. },
  14053. addDisplayNameToPresence: function (displayName) {
  14054. this.presMap['displayName'] = displayName;
  14055. },
  14056. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  14057. if (!this.presMap['medians'])
  14058. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  14059. this.presMap['source' + sourceNumber + '_type'] = mtype;
  14060. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  14061. this.presMap['source' + sourceNumber + '_direction'] = direction;
  14062. },
  14063. clearPresenceMedia: function () {
  14064. var self = this;
  14065. Object.keys(this.presMap).forEach(function (key) {
  14066. if (key.indexOf('source') != -1) {
  14067. delete self.presMap[key];
  14068. }
  14069. });
  14070. },
  14071. addPreziToPresence: function (url, currentSlide) {
  14072. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  14073. this.presMap['preziurl'] = url;
  14074. this.presMap['prezicurrent'] = currentSlide;
  14075. },
  14076. removePreziFromPresence: function () {
  14077. delete this.presMap['prezins'];
  14078. delete this.presMap['preziurl'];
  14079. delete this.presMap['prezicurrent'];
  14080. },
  14081. addCurrentSlideToPresence: function (currentSlide) {
  14082. this.presMap['prezicurrent'] = currentSlide;
  14083. },
  14084. getPrezi: function (roomjid) {
  14085. return this.preziMap[roomjid];
  14086. },
  14087. addEtherpadToPresence: function (etherpadName) {
  14088. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  14089. this.presMap['etherpadname'] = etherpadName;
  14090. },
  14091. addAudioInfoToPresence: function (isMuted) {
  14092. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  14093. this.presMap['audiomuted'] = isMuted.toString();
  14094. },
  14095. addVideoInfoToPresence: function (isMuted) {
  14096. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  14097. this.presMap['videomuted'] = isMuted.toString();
  14098. },
  14099. addConnectionInfoToPresence: function (stats) {
  14100. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  14101. this.presMap['stats'] = stats;
  14102. },
  14103. findJidFromResource: function (resourceJid) {
  14104. if (resourceJid &&
  14105. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  14106. return this.myroomjid;
  14107. }
  14108. var peerJid = null;
  14109. Object.keys(this.members).some(function (jid) {
  14110. peerJid = jid;
  14111. return Strophe.getResourceFromJid(jid) === resourceJid;
  14112. });
  14113. return peerJid;
  14114. },
  14115. addBridgeIsDownToPresence: function () {
  14116. this.presMap['bridgeIsDown'] = true;
  14117. },
  14118. addEmailToPresence: function (email) {
  14119. this.presMap['email'] = email;
  14120. },
  14121. addUserIdToPresence: function (userId) {
  14122. this.presMap['userId'] = userId;
  14123. },
  14124. isModerator: function () {
  14125. return this.role === 'moderator';
  14126. },
  14127. getMemberRole: function (peerJid) {
  14128. if (this.members[peerJid]) {
  14129. return this.members[peerJid].role;
  14130. }
  14131. return null;
  14132. },
  14133. onParticipantLeft: function (jid) {
  14134. eventEmitter.emit(XMPPEvents.MUC_LEFT, jid);
  14135. this.connection.jingle.terminateByJid(jid);
  14136. if (this.getPrezi(jid)) {
  14137. $(document).trigger('presentationremoved.muc',
  14138. [jid, this.getPrezi(jid)]);
  14139. }
  14140. Moderator.onMucLeft(jid);
  14141. },
  14142. parsePresence: function (from, memeber, pres) {
  14143. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  14144. bridgeIsDown = true;
  14145. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  14146. }
  14147. if(memeber.isFocus)
  14148. return;
  14149. var self = this;
  14150. // Remove old ssrcs coming from the jid
  14151. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  14152. if (self.ssrc2jid[ssrc] == from) {
  14153. delete self.ssrc2jid[ssrc];
  14154. }
  14155. });
  14156. var changedStreams = [];
  14157. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  14158. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  14159. var ssrcV = ssrc.getAttribute('ssrc');
  14160. self.ssrc2jid[ssrcV] = from;
  14161. JingleSession.notReceivedSSRCs.push(ssrcV);
  14162. var type = ssrc.getAttribute('type');
  14163. var direction = ssrc.getAttribute('direction');
  14164. changedStreams.push({type: type, direction: direction});
  14165. });
  14166. eventEmitter.emit(XMPPEvents.CHANGED_STREAMS, from, changedStreams);
  14167. var displayName = !config.displayJids
  14168. ? memeber.displayName : Strophe.getResourceFromJid(from);
  14169. if (displayName && displayName.length > 0)
  14170. {
  14171. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  14172. }
  14173. var id = $(pres).find('>userID').text();
  14174. var email = $(pres).find('>email');
  14175. if(email.length > 0) {
  14176. id = email.text();
  14177. }
  14178. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  14179. }
  14180. });
  14181. };
  14182. },{"../../service/xmpp/XMPPEvents":97,"./JingleSession":48,"./moderator":53}],56:[function(require,module,exports){
  14183. /* jshint -W117 */
  14184. var JingleSession = require("./JingleSession");
  14185. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14186. module.exports = function(XMPP, eventEmitter)
  14187. {
  14188. function CallIncomingJingle(sid, connection) {
  14189. var sess = connection.jingle.sessions[sid];
  14190. // TODO: do we check activecall == null?
  14191. connection.jingle.activecall = sess;
  14192. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  14193. // TODO: check affiliation and/or role
  14194. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  14195. sess.usedrip = true; // not-so-naive trickle ice
  14196. sess.sendAnswer();
  14197. sess.accept();
  14198. };
  14199. Strophe.addConnectionPlugin('jingle', {
  14200. connection: null,
  14201. sessions: {},
  14202. jid2session: {},
  14203. ice_config: {iceServers: []},
  14204. pc_constraints: {},
  14205. activecall: null,
  14206. media_constraints: {
  14207. mandatory: {
  14208. 'OfferToReceiveAudio': true,
  14209. 'OfferToReceiveVideo': true
  14210. }
  14211. // MozDontOfferDataChannel: true when this is firefox
  14212. },
  14213. init: function (conn) {
  14214. this.connection = conn;
  14215. if (this.connection.disco) {
  14216. // http://xmpp.org/extensions/xep-0167.html#support
  14217. // http://xmpp.org/extensions/xep-0176.html#support
  14218. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  14219. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  14220. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  14221. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  14222. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  14223. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  14224. // this is dealt with by SDP O/A so we don't need to annouce this
  14225. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  14226. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  14227. if (config.useRtcpMux) {
  14228. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  14229. }
  14230. if (config.useBundle) {
  14231. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  14232. }
  14233. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  14234. }
  14235. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  14236. },
  14237. onJingle: function (iq) {
  14238. var sid = $(iq).find('jingle').attr('sid');
  14239. var action = $(iq).find('jingle').attr('action');
  14240. var fromJid = iq.getAttribute('from');
  14241. // send ack first
  14242. var ack = $iq({type: 'result',
  14243. to: fromJid,
  14244. id: iq.getAttribute('id')
  14245. });
  14246. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  14247. var sess = this.sessions[sid];
  14248. if ('session-initiate' != action) {
  14249. if (sess === null) {
  14250. ack.type = 'error';
  14251. ack.c('error', {type: 'cancel'})
  14252. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14253. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14254. this.connection.send(ack);
  14255. return true;
  14256. }
  14257. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  14258. // local jid is not checked
  14259. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  14260. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  14261. ack.type = 'error';
  14262. ack.c('error', {type: 'cancel'})
  14263. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14264. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14265. this.connection.send(ack);
  14266. return true;
  14267. }
  14268. } else if (sess !== undefined) {
  14269. // existing session with same session id
  14270. // this might be out-of-order if the sess.peerjid is the same as from
  14271. ack.type = 'error';
  14272. ack.c('error', {type: 'cancel'})
  14273. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  14274. console.warn('duplicate session id', sid);
  14275. this.connection.send(ack);
  14276. return true;
  14277. }
  14278. // FIXME: check for a defined action
  14279. this.connection.send(ack);
  14280. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  14281. switch (action) {
  14282. case 'session-initiate':
  14283. sess = new JingleSession(
  14284. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  14285. this.connection, XMPP);
  14286. // configure session
  14287. sess.media_constraints = this.media_constraints;
  14288. sess.pc_constraints = this.pc_constraints;
  14289. sess.ice_config = this.ice_config;
  14290. sess.initiate(fromJid, false);
  14291. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  14292. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  14293. this.sessions[sess.sid] = sess;
  14294. this.jid2session[sess.peerjid] = sess;
  14295. // the callback should either
  14296. // .sendAnswer and .accept
  14297. // or .sendTerminate -- not necessarily synchronus
  14298. CallIncomingJingle(sess.sid, this.connection);
  14299. break;
  14300. case 'session-accept':
  14301. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  14302. sess.accept();
  14303. $(document).trigger('callaccepted.jingle', [sess.sid]);
  14304. break;
  14305. case 'session-terminate':
  14306. // If this is not the focus sending the terminate, we have
  14307. // nothing more to do here.
  14308. if (Object.keys(this.sessions).length < 1
  14309. || !(this.sessions[Object.keys(this.sessions)[0]]
  14310. instanceof JingleSession))
  14311. {
  14312. break;
  14313. }
  14314. console.log('terminating...', sess.sid);
  14315. sess.terminate();
  14316. this.terminate(sess.sid);
  14317. if ($(iq).find('>jingle>reason').length) {
  14318. $(document).trigger('callterminated.jingle', [
  14319. sess.sid,
  14320. sess.peerjid,
  14321. $(iq).find('>jingle>reason>:first')[0].tagName,
  14322. $(iq).find('>jingle>reason>text').text()
  14323. ]);
  14324. } else {
  14325. $(document).trigger('callterminated.jingle',
  14326. [sess.sid, sess.peerjid]);
  14327. }
  14328. break;
  14329. case 'transport-info':
  14330. sess.addIceCandidate($(iq).find('>jingle>content'));
  14331. break;
  14332. case 'session-info':
  14333. var affected;
  14334. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14335. $(document).trigger('ringing.jingle', [sess.sid]);
  14336. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14337. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14338. $(document).trigger('mute.jingle', [sess.sid, affected]);
  14339. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14340. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14341. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  14342. }
  14343. break;
  14344. case 'addsource': // FIXME: proprietary, un-jingleish
  14345. case 'source-add': // FIXME: proprietary
  14346. sess.addSource($(iq).find('>jingle>content'), fromJid);
  14347. break;
  14348. case 'removesource': // FIXME: proprietary, un-jingleish
  14349. case 'source-remove': // FIXME: proprietary
  14350. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  14351. break;
  14352. default:
  14353. console.warn('jingle action not implemented', action);
  14354. break;
  14355. }
  14356. return true;
  14357. },
  14358. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  14359. var sess = new JingleSession(myjid || this.connection.jid,
  14360. Math.random().toString(36).substr(2, 12), // random string
  14361. this.connection, XMPP);
  14362. // configure session
  14363. sess.media_constraints = this.media_constraints;
  14364. sess.pc_constraints = this.pc_constraints;
  14365. sess.ice_config = this.ice_config;
  14366. sess.initiate(peerjid, true);
  14367. this.sessions[sess.sid] = sess;
  14368. this.jid2session[sess.peerjid] = sess;
  14369. sess.sendOffer();
  14370. return sess;
  14371. },
  14372. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  14373. if (sid === null || sid === undefined) {
  14374. for (sid in this.sessions) {
  14375. if (this.sessions[sid].state != 'ended') {
  14376. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14377. this.sessions[sid].terminate();
  14378. }
  14379. delete this.jid2session[this.sessions[sid].peerjid];
  14380. delete this.sessions[sid];
  14381. }
  14382. } else if (this.sessions.hasOwnProperty(sid)) {
  14383. if (this.sessions[sid].state != 'ended') {
  14384. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14385. this.sessions[sid].terminate();
  14386. }
  14387. delete this.jid2session[this.sessions[sid].peerjid];
  14388. delete this.sessions[sid];
  14389. }
  14390. },
  14391. // Used to terminate a session when an unavailable presence is received.
  14392. terminateByJid: function (jid) {
  14393. if (this.jid2session.hasOwnProperty(jid)) {
  14394. var sess = this.jid2session[jid];
  14395. if (sess) {
  14396. sess.terminate();
  14397. console.log('peer went away silently', jid);
  14398. delete this.sessions[sess.sid];
  14399. delete this.jid2session[jid];
  14400. $(document).trigger('callterminated.jingle',
  14401. [sess.sid, jid], 'gone');
  14402. }
  14403. }
  14404. },
  14405. terminateRemoteByJid: function (jid, reason) {
  14406. if (this.jid2session.hasOwnProperty(jid)) {
  14407. var sess = this.jid2session[jid];
  14408. if (sess) {
  14409. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  14410. sess.terminate();
  14411. console.log('terminate peer with jid', sess.sid, jid);
  14412. delete this.sessions[sess.sid];
  14413. delete this.jid2session[jid];
  14414. $(document).trigger('callterminated.jingle',
  14415. [sess.sid, jid, 'kicked']);
  14416. }
  14417. }
  14418. },
  14419. getStunAndTurnCredentials: function () {
  14420. // get stun and turn configuration from server via xep-0215
  14421. // uses time-limited credentials as described in
  14422. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  14423. //
  14424. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  14425. // for a prosody module which implements this
  14426. //
  14427. // currently, this doesn't work with updateIce and therefore credentials with a long
  14428. // validity have to be fetched before creating the peerconnection
  14429. // TODO: implement refresh via updateIce as described in
  14430. // https://code.google.com/p/webrtc/issues/detail?id=1650
  14431. var self = this;
  14432. this.connection.sendIQ(
  14433. $iq({type: 'get', to: this.connection.domain})
  14434. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  14435. function (res) {
  14436. var iceservers = [];
  14437. $(res).find('>services>service').each(function (idx, el) {
  14438. el = $(el);
  14439. var dict = {};
  14440. var type = el.attr('type');
  14441. switch (type) {
  14442. case 'stun':
  14443. dict.url = 'stun:' + el.attr('host');
  14444. if (el.attr('port')) {
  14445. dict.url += ':' + el.attr('port');
  14446. }
  14447. iceservers.push(dict);
  14448. break;
  14449. case 'turn':
  14450. case 'turns':
  14451. dict.url = type + ':';
  14452. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  14453. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  14454. dict.url += el.attr('username') + '@';
  14455. } else {
  14456. dict.username = el.attr('username'); // only works in M28
  14457. }
  14458. }
  14459. dict.url += el.attr('host');
  14460. if (el.attr('port') && el.attr('port') != '3478') {
  14461. dict.url += ':' + el.attr('port');
  14462. }
  14463. if (el.attr('transport') && el.attr('transport') != 'udp') {
  14464. dict.url += '?transport=' + el.attr('transport');
  14465. }
  14466. if (el.attr('password')) {
  14467. dict.credential = el.attr('password');
  14468. }
  14469. iceservers.push(dict);
  14470. break;
  14471. }
  14472. });
  14473. self.ice_config.iceServers = iceservers;
  14474. },
  14475. function (err) {
  14476. console.warn('getting turn credentials failed', err);
  14477. console.warn('is mod_turncredentials or similar installed?');
  14478. }
  14479. );
  14480. // implement push?
  14481. },
  14482. /**
  14483. * Populates the log data
  14484. */
  14485. populateData: function () {
  14486. var data = {};
  14487. Object.keys(this.sessions).forEach(function (sid) {
  14488. var session = this.sessions[sid];
  14489. if (session.peerconnection && session.peerconnection.updateLog) {
  14490. // FIXME: should probably be a .dump call
  14491. data["jingle_" + session.sid] = {
  14492. updateLog: session.peerconnection.updateLog,
  14493. stats: session.peerconnection.stats,
  14494. url: window.location.href
  14495. };
  14496. }
  14497. });
  14498. return data;
  14499. }
  14500. });
  14501. };
  14502. },{"../../service/xmpp/XMPPEvents":97,"./JingleSession":48}],57:[function(require,module,exports){
  14503. /* global Strophe */
  14504. module.exports = function () {
  14505. Strophe.addConnectionPlugin('logger', {
  14506. // logs raw stanzas and makes them available for download as JSON
  14507. connection: null,
  14508. log: [],
  14509. init: function (conn) {
  14510. this.connection = conn;
  14511. this.connection.rawInput = this.log_incoming.bind(this);
  14512. this.connection.rawOutput = this.log_outgoing.bind(this);
  14513. },
  14514. log_incoming: function (stanza) {
  14515. this.log.push([new Date().getTime(), 'incoming', stanza]);
  14516. },
  14517. log_outgoing: function (stanza) {
  14518. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  14519. }
  14520. });
  14521. };
  14522. },{}],58:[function(require,module,exports){
  14523. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  14524. setAudioMuted, Strophe */
  14525. /**
  14526. * Moderate connection plugin.
  14527. */
  14528. module.exports = function (XMPP) {
  14529. Strophe.addConnectionPlugin('moderate', {
  14530. connection: null,
  14531. init: function (conn) {
  14532. this.connection = conn;
  14533. this.connection.addHandler(this.onMute.bind(this),
  14534. 'http://jitsi.org/jitmeet/audio',
  14535. 'iq',
  14536. 'set',
  14537. null,
  14538. null);
  14539. },
  14540. setMute: function (jid, mute) {
  14541. console.info("set mute", mute);
  14542. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  14543. .c('mute', {
  14544. xmlns: 'http://jitsi.org/jitmeet/audio',
  14545. jid: jid
  14546. })
  14547. .t(mute.toString())
  14548. .up();
  14549. this.connection.sendIQ(
  14550. iqToFocus,
  14551. function (result) {
  14552. console.log('set mute', result);
  14553. },
  14554. function (error) {
  14555. console.log('set mute error', error);
  14556. });
  14557. },
  14558. onMute: function (iq) {
  14559. var from = iq.getAttribute('from');
  14560. if (from !== this.connection.emuc.focusMucJid) {
  14561. console.warn("Ignored mute from non focus peer");
  14562. return false;
  14563. }
  14564. var mute = $(iq).find('mute');
  14565. if (mute.length) {
  14566. var doMuteAudio = mute.text() === "true";
  14567. APP.UI.setAudioMuted(doMuteAudio);
  14568. XMPP.forceMuted = doMuteAudio;
  14569. }
  14570. return true;
  14571. },
  14572. eject: function (jid) {
  14573. // We're not the focus, so can't terminate
  14574. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  14575. this.connection.emuc.kick(jid);
  14576. }
  14577. });
  14578. }
  14579. },{}],59:[function(require,module,exports){
  14580. /* jshint -W117 */
  14581. module.exports = function() {
  14582. Strophe.addConnectionPlugin('rayo',
  14583. {
  14584. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  14585. connection: null,
  14586. init: function (conn) {
  14587. this.connection = conn;
  14588. if (this.connection.disco) {
  14589. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  14590. }
  14591. this.connection.addHandler(
  14592. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  14593. },
  14594. onRayo: function (iq) {
  14595. console.info("Rayo IQ", iq);
  14596. },
  14597. dial: function (to, from, roomName, roomPass) {
  14598. var self = this;
  14599. var req = $iq(
  14600. {
  14601. type: 'set',
  14602. to: this.connection.emuc.focusMucJid
  14603. }
  14604. );
  14605. req.c('dial',
  14606. {
  14607. xmlns: this.RAYO_XMLNS,
  14608. to: to,
  14609. from: from
  14610. });
  14611. req.c('header',
  14612. {
  14613. name: 'JvbRoomName',
  14614. value: roomName
  14615. }).up();
  14616. if (roomPass !== null && roomPass.length) {
  14617. req.c('header',
  14618. {
  14619. name: 'JvbRoomPassword',
  14620. value: roomPass
  14621. }).up();
  14622. }
  14623. this.connection.sendIQ(
  14624. req,
  14625. function (result) {
  14626. console.info('Dial result ', result);
  14627. var resource = $(result).find('ref').attr('uri');
  14628. this.call_resource = resource.substr('xmpp:'.length);
  14629. console.info(
  14630. "Received call resource: " + this.call_resource);
  14631. },
  14632. function (error) {
  14633. console.info('Dial error ', error);
  14634. }
  14635. );
  14636. },
  14637. hang_up: function () {
  14638. if (!this.call_resource) {
  14639. console.warn("No call in progress");
  14640. return;
  14641. }
  14642. var self = this;
  14643. var req = $iq(
  14644. {
  14645. type: 'set',
  14646. to: this.call_resource
  14647. }
  14648. );
  14649. req.c('hangup',
  14650. {
  14651. xmlns: this.RAYO_XMLNS
  14652. });
  14653. this.connection.sendIQ(
  14654. req,
  14655. function (result) {
  14656. console.info('Hangup result ', result);
  14657. self.call_resource = null;
  14658. },
  14659. function (error) {
  14660. console.info('Hangup error ', error);
  14661. self.call_resource = null;
  14662. }
  14663. );
  14664. }
  14665. }
  14666. );
  14667. };
  14668. },{}],60:[function(require,module,exports){
  14669. /**
  14670. * Strophe logger implementation. Logs from level WARN and above.
  14671. */
  14672. module.exports = function () {
  14673. Strophe.log = function (level, msg) {
  14674. switch (level) {
  14675. case Strophe.LogLevel.WARN:
  14676. console.warn("Strophe: " + msg);
  14677. break;
  14678. case Strophe.LogLevel.ERROR:
  14679. case Strophe.LogLevel.FATAL:
  14680. console.error("Strophe: " + msg);
  14681. break;
  14682. }
  14683. };
  14684. Strophe.getStatusString = function (status) {
  14685. switch (status) {
  14686. case Strophe.Status.ERROR:
  14687. return "ERROR";
  14688. case Strophe.Status.CONNECTING:
  14689. return "CONNECTING";
  14690. case Strophe.Status.CONNFAIL:
  14691. return "CONNFAIL";
  14692. case Strophe.Status.AUTHENTICATING:
  14693. return "AUTHENTICATING";
  14694. case Strophe.Status.AUTHFAIL:
  14695. return "AUTHFAIL";
  14696. case Strophe.Status.CONNECTED:
  14697. return "CONNECTED";
  14698. case Strophe.Status.DISCONNECTED:
  14699. return "DISCONNECTED";
  14700. case Strophe.Status.DISCONNECTING:
  14701. return "DISCONNECTING";
  14702. case Strophe.Status.ATTACHED:
  14703. return "ATTACHED";
  14704. default:
  14705. return "unknown";
  14706. }
  14707. };
  14708. };
  14709. },{}],61:[function(require,module,exports){
  14710. /* global $, APP, config, Strophe*/
  14711. var Moderator = require("./moderator");
  14712. var EventEmitter = require("events");
  14713. var Recording = require("./recording");
  14714. var SDP = require("./SDP");
  14715. var Pako = require("pako");
  14716. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  14717. var UIEvents = require("../../service/UI/UIEvents");
  14718. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14719. var eventEmitter = new EventEmitter();
  14720. var connection = null;
  14721. var authenticatedUser = false;
  14722. function connect(jid, password) {
  14723. connection = XMPP.createConnection();
  14724. Moderator.setConnection(connection);
  14725. if (connection.disco) {
  14726. // for chrome, add multistream cap
  14727. }
  14728. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  14729. if (config.useIPv6) {
  14730. // https://code.google.com/p/webrtc/issues/detail?id=2828
  14731. if (!connection.jingle.pc_constraints.optional)
  14732. connection.jingle.pc_constraints.optional = [];
  14733. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  14734. }
  14735. var anonymousConnectionFailed = false;
  14736. connection.connect(jid, password, function (status, msg) {
  14737. console.log('Strophe status changed to',
  14738. Strophe.getStatusString(status));
  14739. if (status === Strophe.Status.CONNECTED) {
  14740. if (config.useStunTurn) {
  14741. connection.jingle.getStunAndTurnCredentials();
  14742. }
  14743. console.info("My Jabber ID: " + connection.jid);
  14744. if(password)
  14745. authenticatedUser = true;
  14746. maybeDoJoin();
  14747. } else if (status === Strophe.Status.CONNFAIL) {
  14748. if(msg === 'x-strophe-bad-non-anon-jid') {
  14749. anonymousConnectionFailed = true;
  14750. }
  14751. } else if (status === Strophe.Status.DISCONNECTED) {
  14752. if(anonymousConnectionFailed) {
  14753. // prompt user for username and password
  14754. XMPP.promptLogin();
  14755. }
  14756. } else if (status === Strophe.Status.AUTHFAIL) {
  14757. // wrong password or username, prompt user
  14758. XMPP.promptLogin();
  14759. }
  14760. });
  14761. }
  14762. function maybeDoJoin() {
  14763. if (connection && connection.connected &&
  14764. Strophe.getResourceFromJid(connection.jid)
  14765. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  14766. // .connected is true while connecting?
  14767. doJoin();
  14768. }
  14769. }
  14770. function doJoin() {
  14771. var roomName = APP.UI.generateRoomName();
  14772. Moderator.allocateConferenceFocus(
  14773. roomName, APP.UI.checkForNicknameAndJoin);
  14774. }
  14775. function initStrophePlugins()
  14776. {
  14777. require("./strophe.emuc")(XMPP, eventEmitter);
  14778. require("./strophe.jingle")(XMPP, eventEmitter);
  14779. require("./strophe.moderate")(XMPP);
  14780. require("./strophe.util")();
  14781. require("./strophe.rayo")();
  14782. require("./strophe.logger")();
  14783. }
  14784. function registerListeners() {
  14785. APP.RTC.addStreamListener(maybeDoJoin,
  14786. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  14787. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  14788. XMPP.addToPresence("displayName", nickname);
  14789. });
  14790. }
  14791. function setupEvents() {
  14792. $(window).bind('beforeunload', function () {
  14793. if (connection && connection.connected) {
  14794. // ensure signout
  14795. $.ajax({
  14796. type: 'POST',
  14797. url: config.bosh,
  14798. async: false,
  14799. cache: false,
  14800. contentType: 'application/xml',
  14801. data: "<body rid='" + (connection.rid || connection._proto.rid)
  14802. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  14803. + (connection.sid || connection._proto.sid)
  14804. + "' type='terminate'>" +
  14805. "<presence xmlns='jabber:client' type='unavailable'/>" +
  14806. "</body>",
  14807. success: function (data) {
  14808. console.log('signed out');
  14809. console.log(data);
  14810. },
  14811. error: function (XMLHttpRequest, textStatus, errorThrown) {
  14812. console.log('signout error',
  14813. textStatus + ' (' + errorThrown + ')');
  14814. }
  14815. });
  14816. }
  14817. XMPP.disposeConference(true);
  14818. });
  14819. }
  14820. var XMPP = {
  14821. sessionTerminated: false,
  14822. /**
  14823. * XMPP connection status
  14824. */
  14825. Status: Strophe.Status,
  14826. /**
  14827. * Remembers if we were muted by the focus.
  14828. * @type {boolean}
  14829. */
  14830. forceMuted: false,
  14831. start: function () {
  14832. setupEvents();
  14833. initStrophePlugins();
  14834. registerListeners();
  14835. Moderator.init(this, eventEmitter);
  14836. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  14837. // Force authenticated domain if room is appended with '?login=true'
  14838. if (config.hosts.anonymousdomain &&
  14839. window.location.search.indexOf("login=true") !== -1) {
  14840. configDomain = config.hosts.domain;
  14841. }
  14842. var jid = configDomain || window.location.hostname;
  14843. connect(jid, null);
  14844. },
  14845. createConnection: function () {
  14846. var bosh = config.bosh || '/http-bind';
  14847. return new Strophe.Connection(bosh);
  14848. },
  14849. getStatusString: function (status) {
  14850. return Strophe.getStatusString(status);
  14851. },
  14852. promptLogin: function () {
  14853. // FIXME: re-use LoginDialog which supports retries
  14854. APP.UI.showLoginPopup(connect);
  14855. },
  14856. joinRoom: function(roomName, useNicks, nick)
  14857. {
  14858. var roomjid;
  14859. roomjid = roomName;
  14860. if (useNicks) {
  14861. if (nick) {
  14862. roomjid += '/' + nick;
  14863. } else {
  14864. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  14865. }
  14866. } else {
  14867. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  14868. if(!authenticatedUser)
  14869. tmpJid = tmpJid.substr(0, 8);
  14870. roomjid += '/' + tmpJid;
  14871. }
  14872. connection.emuc.doJoin(roomjid);
  14873. },
  14874. myJid: function () {
  14875. if(!connection)
  14876. return null;
  14877. return connection.emuc.myroomjid;
  14878. },
  14879. myResource: function () {
  14880. if(!connection || ! connection.emuc.myroomjid)
  14881. return null;
  14882. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  14883. },
  14884. disposeConference: function (onUnload) {
  14885. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  14886. var handler = connection.jingle.activecall;
  14887. if (handler && handler.peerconnection) {
  14888. // FIXME: probably removing streams is not required and close() should
  14889. // be enough
  14890. if (APP.RTC.localAudio) {
  14891. handler.peerconnection.removeStream(
  14892. APP.RTC.localAudio.getOriginalStream(), onUnload);
  14893. }
  14894. if (APP.RTC.localVideo) {
  14895. handler.peerconnection.removeStream(
  14896. APP.RTC.localVideo.getOriginalStream(), onUnload);
  14897. }
  14898. handler.peerconnection.close();
  14899. }
  14900. connection.jingle.activecall = null;
  14901. if(!onUnload)
  14902. {
  14903. this.sessionTerminated = true;
  14904. connection.emuc.doLeave();
  14905. }
  14906. },
  14907. addListener: function(type, listener)
  14908. {
  14909. eventEmitter.on(type, listener);
  14910. },
  14911. removeListener: function (type, listener) {
  14912. eventEmitter.removeListener(type, listener);
  14913. },
  14914. allocateConferenceFocus: function(roomName, callback) {
  14915. Moderator.allocateConferenceFocus(roomName, callback);
  14916. },
  14917. getLoginUrl: function (roomName, callback) {
  14918. Moderator.getLoginUrl(roomName, callback);
  14919. },
  14920. getPopupLoginUrl: function (roomName, callback) {
  14921. Moderator.getPopupLoginUrl(roomName, callback);
  14922. },
  14923. isModerator: function () {
  14924. return Moderator.isModerator();
  14925. },
  14926. isSipGatewayEnabled: function () {
  14927. return Moderator.isSipGatewayEnabled();
  14928. },
  14929. isExternalAuthEnabled: function () {
  14930. return Moderator.isExternalAuthEnabled();
  14931. },
  14932. switchStreams: function (stream, oldStream, callback) {
  14933. if (connection && connection.jingle.activecall) {
  14934. // FIXME: will block switchInProgress on true value in case of exception
  14935. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  14936. } else {
  14937. // We are done immediately
  14938. console.warn("No conference handler or conference not started yet");
  14939. callback();
  14940. }
  14941. },
  14942. sendVideoInfoPresence: function (mute) {
  14943. connection.emuc.addVideoInfoToPresence(mute);
  14944. connection.emuc.sendPresence();
  14945. },
  14946. setVideoMute: function (mute, callback, options) {
  14947. if(!connection)
  14948. return;
  14949. var self = this;
  14950. var localCallback = function (mute) {
  14951. self.sendVideoInfoPresence(mute);
  14952. return callback(mute);
  14953. };
  14954. if(connection.jingle.activecall)
  14955. {
  14956. connection.jingle.activecall.setVideoMute(
  14957. mute, localCallback, options);
  14958. }
  14959. else {
  14960. localCallback(mute);
  14961. }
  14962. },
  14963. setAudioMute: function (mute, callback) {
  14964. if (!(connection && APP.RTC.localAudio)) {
  14965. return false;
  14966. }
  14967. if (this.forceMuted && !mute) {
  14968. console.info("Asking focus for unmute");
  14969. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  14970. // FIXME: wait for result before resetting muted status
  14971. this.forceMuted = false;
  14972. }
  14973. if (mute == APP.RTC.localAudio.isMuted()) {
  14974. // Nothing to do
  14975. return true;
  14976. }
  14977. // It is not clear what is the right way to handle multiple tracks.
  14978. // So at least make sure that they are all muted or all unmuted and
  14979. // that we send presence just once.
  14980. APP.RTC.localAudio.mute();
  14981. // isMuted is the opposite of audioEnabled
  14982. connection.emuc.addAudioInfoToPresence(mute);
  14983. connection.emuc.sendPresence();
  14984. callback();
  14985. return true;
  14986. },
  14987. // Really mute video, i.e. dont even send black frames
  14988. muteVideo: function (pc, unmute) {
  14989. // FIXME: this probably needs another of those lovely state safeguards...
  14990. // which checks for iceconn == connected and sigstate == stable
  14991. pc.setRemoteDescription(pc.remoteDescription,
  14992. function () {
  14993. pc.createAnswer(
  14994. function (answer) {
  14995. var sdp = new SDP(answer.sdp);
  14996. if (sdp.media.length > 1) {
  14997. if (unmute)
  14998. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  14999. else
  15000. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  15001. sdp.raw = sdp.session + sdp.media.join('');
  15002. answer.sdp = sdp.raw;
  15003. }
  15004. pc.setLocalDescription(answer,
  15005. function () {
  15006. console.log('mute SLD ok');
  15007. },
  15008. function (error) {
  15009. console.log('mute SLD error');
  15010. APP.UI.messageHandler.showError("dialog.error",
  15011. "dialog.SLDFailure");
  15012. }
  15013. );
  15014. },
  15015. function (error) {
  15016. console.log(error);
  15017. APP.UI.messageHandler.showError();
  15018. }
  15019. );
  15020. },
  15021. function (error) {
  15022. console.log('muteVideo SRD error');
  15023. APP.UI.messageHandler.showError("dialog.error",
  15024. "dialog.SRDFailure");
  15025. }
  15026. );
  15027. },
  15028. toggleRecording: function (tokenEmptyCallback,
  15029. startingCallback, startedCallback) {
  15030. Recording.toggleRecording(tokenEmptyCallback,
  15031. startingCallback, startedCallback, connection);
  15032. },
  15033. addToPresence: function (name, value, dontSend) {
  15034. switch (name)
  15035. {
  15036. case "displayName":
  15037. connection.emuc.addDisplayNameToPresence(value);
  15038. break;
  15039. case "etherpad":
  15040. connection.emuc.addEtherpadToPresence(value);
  15041. break;
  15042. case "prezi":
  15043. connection.emuc.addPreziToPresence(value, 0);
  15044. break;
  15045. case "preziSlide":
  15046. connection.emuc.addCurrentSlideToPresence(value);
  15047. break;
  15048. case "connectionQuality":
  15049. connection.emuc.addConnectionInfoToPresence(value);
  15050. break;
  15051. case "email":
  15052. connection.emuc.addEmailToPresence(value);
  15053. default :
  15054. console.log("Unknown tag for presence.");
  15055. return;
  15056. }
  15057. if(!dontSend)
  15058. connection.emuc.sendPresence();
  15059. },
  15060. /**
  15061. * Sends 'data' as a log message to the focus. Returns true iff a message
  15062. * was sent.
  15063. * @param data
  15064. * @returns {boolean} true iff a message was sent.
  15065. */
  15066. sendLogs: function (data) {
  15067. if(!connection.emuc.focusMucJid)
  15068. return false;
  15069. var deflate = true;
  15070. var content = JSON.stringify(data);
  15071. if (deflate) {
  15072. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  15073. }
  15074. content = Base64.encode(content);
  15075. // XEP-0337-ish
  15076. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  15077. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  15078. id: 'PeerConnectionStats'});
  15079. message.c('message').t(content).up();
  15080. if (deflate) {
  15081. message.c('tag', {name: "deflated", value: "true"}).up();
  15082. }
  15083. message.up();
  15084. connection.send(message);
  15085. return true;
  15086. },
  15087. populateData: function () {
  15088. var data = {};
  15089. if (connection.jingle) {
  15090. data = connection.jingle.populateData();
  15091. }
  15092. return data;
  15093. },
  15094. getLogger: function () {
  15095. if(connection.logger)
  15096. return connection.logger.log;
  15097. return null;
  15098. },
  15099. getPrezi: function () {
  15100. return connection.emuc.getPrezi(this.myJid());
  15101. },
  15102. removePreziFromPresence: function () {
  15103. connection.emuc.removePreziFromPresence();
  15104. connection.emuc.sendPresence();
  15105. },
  15106. sendChatMessage: function (message, nickname) {
  15107. connection.emuc.sendMessage(message, nickname);
  15108. },
  15109. setSubject: function (topic) {
  15110. connection.emuc.setSubject(topic);
  15111. },
  15112. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15113. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  15114. },
  15115. dial: function (to, from, roomName,roomPass) {
  15116. connection.rayo.dial(to, from, roomName,roomPass);
  15117. },
  15118. setMute: function (jid, mute) {
  15119. connection.moderate.setMute(jid, mute);
  15120. },
  15121. eject: function (jid) {
  15122. connection.moderate.eject(jid);
  15123. },
  15124. logout: function (callback) {
  15125. Moderator.logout(callback);
  15126. },
  15127. findJidFromResource: function (resource) {
  15128. return connection.emuc.findJidFromResource(resource);
  15129. },
  15130. getMembers: function () {
  15131. return connection.emuc.members;
  15132. },
  15133. getJidFromSSRC: function (ssrc) {
  15134. if(!connection)
  15135. return null;
  15136. return connection.emuc.ssrc2jid[ssrc];
  15137. },
  15138. getMUCJoined: function () {
  15139. return connection.emuc.joined;
  15140. },
  15141. getSessions: function () {
  15142. return connection.jingle.sessions;
  15143. },
  15144. removeStream: function (stream) {
  15145. if(!connection || !connection.jingle.activecall ||
  15146. !connection.jingle.activecall.peerconnection)
  15147. return;
  15148. connection.jingle.activecall.peerconnection.removeStream(stream);
  15149. }
  15150. };
  15151. module.exports = XMPP;
  15152. },{"../../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){
  15153. // i18next, v1.7.7
  15154. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  15155. // Distributed under MIT license
  15156. // http://i18next.com
  15157. (function() {
  15158. // add indexOf to non ECMA-262 standard compliant browsers
  15159. if (!Array.prototype.indexOf) {
  15160. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  15161. "use strict";
  15162. if (this == null) {
  15163. throw new TypeError();
  15164. }
  15165. var t = Object(this);
  15166. var len = t.length >>> 0;
  15167. if (len === 0) {
  15168. return -1;
  15169. }
  15170. var n = 0;
  15171. if (arguments.length > 0) {
  15172. n = Number(arguments[1]);
  15173. if (n != n) { // shortcut for verifying if it's NaN
  15174. n = 0;
  15175. } else if (n != 0 && n != Infinity && n != -Infinity) {
  15176. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  15177. }
  15178. }
  15179. if (n >= len) {
  15180. return -1;
  15181. }
  15182. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  15183. for (; k < len; k++) {
  15184. if (k in t && t[k] === searchElement) {
  15185. return k;
  15186. }
  15187. }
  15188. return -1;
  15189. }
  15190. }
  15191. // add lastIndexOf to non ECMA-262 standard compliant browsers
  15192. if (!Array.prototype.lastIndexOf) {
  15193. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  15194. "use strict";
  15195. if (this == null) {
  15196. throw new TypeError();
  15197. }
  15198. var t = Object(this);
  15199. var len = t.length >>> 0;
  15200. if (len === 0) {
  15201. return -1;
  15202. }
  15203. var n = len;
  15204. if (arguments.length > 1) {
  15205. n = Number(arguments[1]);
  15206. if (n != n) {
  15207. n = 0;
  15208. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  15209. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  15210. }
  15211. }
  15212. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  15213. for (; k >= 0; k--) {
  15214. if (k in t && t[k] === searchElement) {
  15215. return k;
  15216. }
  15217. }
  15218. return -1;
  15219. };
  15220. }
  15221. // Add string trim for IE8.
  15222. if (typeof String.prototype.trim !== 'function') {
  15223. String.prototype.trim = function() {
  15224. return this.replace(/^\s+|\s+$/g, '');
  15225. }
  15226. }
  15227. var root = this
  15228. , $ = root.jQuery || root.Zepto
  15229. , i18n = {}
  15230. , resStore = {}
  15231. , currentLng
  15232. , replacementCounter = 0
  15233. , languages = []
  15234. , initialized = false
  15235. , sync = {};
  15236. // Export the i18next object for **CommonJS**.
  15237. // If we're not in CommonJS, add `i18n` to the
  15238. // global object or to jquery.
  15239. if (typeof module !== 'undefined' && module.exports) {
  15240. if (!$) {
  15241. try {
  15242. $ = require('jquery');
  15243. } catch(e) {
  15244. // just ignore
  15245. }
  15246. }
  15247. if ($) {
  15248. $.i18n = $.i18n || i18n;
  15249. }
  15250. module.exports = i18n;
  15251. } else {
  15252. if ($) {
  15253. $.i18n = $.i18n || i18n;
  15254. }
  15255. root.i18n = root.i18n || i18n;
  15256. }
  15257. sync = {
  15258. load: function(lngs, options, cb) {
  15259. if (options.useLocalStorage) {
  15260. sync._loadLocal(lngs, options, function(err, store) {
  15261. var missingLngs = [];
  15262. for (var i = 0, len = lngs.length; i < len; i++) {
  15263. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  15264. }
  15265. if (missingLngs.length > 0) {
  15266. sync._fetch(missingLngs, options, function(err, fetched) {
  15267. f.extend(store, fetched);
  15268. sync._storeLocal(fetched);
  15269. cb(null, store);
  15270. });
  15271. } else {
  15272. cb(null, store);
  15273. }
  15274. });
  15275. } else {
  15276. sync._fetch(lngs, options, function(err, store){
  15277. cb(null, store);
  15278. });
  15279. }
  15280. },
  15281. _loadLocal: function(lngs, options, cb) {
  15282. var store = {}
  15283. , nowMS = new Date().getTime();
  15284. if(window.localStorage) {
  15285. var todo = lngs.length;
  15286. f.each(lngs, function(key, lng) {
  15287. var local = window.localStorage.getItem('res_' + lng);
  15288. if (local) {
  15289. local = JSON.parse(local);
  15290. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  15291. store[lng] = local;
  15292. }
  15293. }
  15294. todo--; // wait for all done befor callback
  15295. if (todo === 0) cb(null, store);
  15296. });
  15297. }
  15298. },
  15299. _storeLocal: function(store) {
  15300. if(window.localStorage) {
  15301. for (var m in store) {
  15302. store[m].i18nStamp = new Date().getTime();
  15303. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  15304. }
  15305. }
  15306. return;
  15307. },
  15308. _fetch: function(lngs, options, cb) {
  15309. var ns = options.ns
  15310. , store = {};
  15311. if (!options.dynamicLoad) {
  15312. var todo = ns.namespaces.length * lngs.length
  15313. , errors;
  15314. // load each file individual
  15315. f.each(ns.namespaces, function(nsIndex, nsValue) {
  15316. f.each(lngs, function(lngIndex, lngValue) {
  15317. // Call this once our translation has returned.
  15318. var loadComplete = function(err, data) {
  15319. if (err) {
  15320. errors = errors || [];
  15321. errors.push(err);
  15322. }
  15323. store[lngValue] = store[lngValue] || {};
  15324. store[lngValue][nsValue] = data;
  15325. todo--; // wait for all done befor callback
  15326. if (todo === 0) cb(errors, store);
  15327. };
  15328. if(typeof options.customLoad == 'function'){
  15329. // Use the specified custom callback.
  15330. options.customLoad(lngValue, nsValue, options, loadComplete);
  15331. } else {
  15332. //~ // Use our inbuilt sync.
  15333. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  15334. }
  15335. });
  15336. });
  15337. } else {
  15338. // Call this once our translation has returned.
  15339. var loadComplete = function(err, data) {
  15340. cb(null, data);
  15341. };
  15342. if(typeof options.customLoad == 'function'){
  15343. // Use the specified custom callback.
  15344. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  15345. } else {
  15346. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  15347. // load all needed stuff once
  15348. f.ajax({
  15349. url: url,
  15350. success: function(data, status, xhr) {
  15351. f.log('loaded: ' + url);
  15352. loadComplete(null, data);
  15353. },
  15354. error : function(xhr, status, error) {
  15355. f.log('failed loading: ' + url);
  15356. loadComplete('failed loading resource.json error: ' + error);
  15357. },
  15358. dataType: "json",
  15359. async : options.getAsync
  15360. });
  15361. }
  15362. }
  15363. },
  15364. _fetchOne: function(lng, ns, options, done) {
  15365. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  15366. f.ajax({
  15367. url: url,
  15368. success: function(data, status, xhr) {
  15369. f.log('loaded: ' + url);
  15370. done(null, data);
  15371. },
  15372. error : function(xhr, status, error) {
  15373. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  15374. // file loaded but invalid json, stop waste time !
  15375. f.error('There is a typo in: ' + url);
  15376. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  15377. f.log('Does not exist: ' + url);
  15378. } else {
  15379. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  15380. f.log(theStatus + ' when loading ' + url);
  15381. }
  15382. done(error, {});
  15383. },
  15384. dataType: "json",
  15385. async : options.getAsync
  15386. });
  15387. },
  15388. postMissing: function(lng, ns, key, defaultValue, lngs) {
  15389. var payload = {};
  15390. payload[key] = defaultValue;
  15391. var urls = [];
  15392. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  15393. for (var i = 0; i < o.fallbackLng.length; i++) {
  15394. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  15395. }
  15396. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  15397. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  15398. } else if (o.sendMissingTo === 'all') {
  15399. for (var i = 0, l = lngs.length; i < l; i++) {
  15400. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  15401. }
  15402. }
  15403. for (var y = 0, len = urls.length; y < len; y++) {
  15404. var item = urls[y];
  15405. f.ajax({
  15406. url: item.url,
  15407. type: o.sendType,
  15408. data: payload,
  15409. success: function(data, status, xhr) {
  15410. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  15411. // add key to resStore
  15412. var keys = key.split('.');
  15413. var x = 0;
  15414. var value = resStore[item.lng][ns];
  15415. while (keys[x]) {
  15416. if (x === keys.length - 1) {
  15417. value = value[keys[x]] = defaultValue;
  15418. } else {
  15419. value = value[keys[x]] = value[keys[x]] || {};
  15420. }
  15421. x++;
  15422. }
  15423. },
  15424. error : function(xhr, status, error) {
  15425. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  15426. },
  15427. dataType: "json",
  15428. async : o.postAsync
  15429. });
  15430. }
  15431. },
  15432. reload: reload
  15433. };
  15434. // defaults
  15435. var o = {
  15436. lng: undefined,
  15437. load: 'all',
  15438. preload: [],
  15439. lowerCaseLng: false,
  15440. returnObjectTrees: false,
  15441. fallbackLng: ['dev'],
  15442. fallbackNS: [],
  15443. detectLngQS: 'setLng',
  15444. detectLngFromLocalStorage: false,
  15445. ns: 'translation',
  15446. fallbackOnNull: true,
  15447. fallbackOnEmpty: false,
  15448. fallbackToDefaultNS: false,
  15449. nsseparator: ':',
  15450. keyseparator: '.',
  15451. selectorAttr: 'data-i18n',
  15452. debug: false,
  15453. resGetPath: 'locales/__lng__/__ns__.json',
  15454. resPostPath: 'locales/add/__lng__/__ns__',
  15455. getAsync: true,
  15456. postAsync: true,
  15457. resStore: undefined,
  15458. useLocalStorage: false,
  15459. localStorageExpirationTime: 7*24*60*60*1000,
  15460. dynamicLoad: false,
  15461. sendMissing: false,
  15462. sendMissingTo: 'fallback', // current | all
  15463. sendType: 'POST',
  15464. interpolationPrefix: '__',
  15465. interpolationSuffix: '__',
  15466. defaultVariables: false,
  15467. reusePrefix: '$t(',
  15468. reuseSuffix: ')',
  15469. pluralSuffix: '_plural',
  15470. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  15471. contextNotFound: ['context_not_found', Math.random()].join(''),
  15472. escapeInterpolation: false,
  15473. indefiniteSuffix: '_indefinite',
  15474. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  15475. setJqueryExt: true,
  15476. defaultValueFromContent: true,
  15477. useDataAttrOptions: false,
  15478. cookieExpirationTime: undefined,
  15479. useCookie: true,
  15480. cookieName: 'i18next',
  15481. cookieDomain: undefined,
  15482. objectTreeKeyHandler: undefined,
  15483. postProcess: undefined,
  15484. parseMissingKey: undefined,
  15485. missingKeyHandler: sync.postMissing,
  15486. shortcutFunction: 'sprintf' // or: defaultValue
  15487. };
  15488. function _extend(target, source) {
  15489. if (!source || typeof source === 'function') {
  15490. return target;
  15491. }
  15492. for (var attr in source) { target[attr] = source[attr]; }
  15493. return target;
  15494. }
  15495. function _deepExtend(target, source) {
  15496. for (var prop in source)
  15497. if (prop in target)
  15498. _deepExtend(target[prop], source[prop]);
  15499. else
  15500. target[prop] = source[prop];
  15501. return target;
  15502. }
  15503. function _each(object, callback, args) {
  15504. var name, i = 0,
  15505. length = object.length,
  15506. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  15507. if (args) {
  15508. if (isObj) {
  15509. for (name in object) {
  15510. if (callback.apply(object[name], args) === false) {
  15511. break;
  15512. }
  15513. }
  15514. } else {
  15515. for ( ; i < length; ) {
  15516. if (callback.apply(object[i++], args) === false) {
  15517. break;
  15518. }
  15519. }
  15520. }
  15521. // A special, fast, case for the most common use of each
  15522. } else {
  15523. if (isObj) {
  15524. for (name in object) {
  15525. if (callback.call(object[name], name, object[name]) === false) {
  15526. break;
  15527. }
  15528. }
  15529. } else {
  15530. for ( ; i < length; ) {
  15531. if (callback.call(object[i], i, object[i++]) === false) {
  15532. break;
  15533. }
  15534. }
  15535. }
  15536. }
  15537. return object;
  15538. }
  15539. var _entityMap = {
  15540. "&": "&amp;",
  15541. "<": "&lt;",
  15542. ">": "&gt;",
  15543. '"': '&quot;',
  15544. "'": '&#39;',
  15545. "/": '&#x2F;'
  15546. };
  15547. function _escape(data) {
  15548. if (typeof data === 'string') {
  15549. return data.replace(/[&<>"'\/]/g, function (s) {
  15550. return _entityMap[s];
  15551. });
  15552. }else{
  15553. return data;
  15554. }
  15555. }
  15556. function _ajax(options) {
  15557. // v0.5.0 of https://github.com/goloroden/http.js
  15558. var getXhr = function (callback) {
  15559. // Use the native XHR object if the browser supports it.
  15560. if (window.XMLHttpRequest) {
  15561. return callback(null, new XMLHttpRequest());
  15562. } else if (window.ActiveXObject) {
  15563. // In Internet Explorer check for ActiveX versions of the XHR object.
  15564. try {
  15565. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  15566. } catch (e) {
  15567. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  15568. }
  15569. }
  15570. // If no XHR support was found, throw an error.
  15571. return callback(new Error());
  15572. };
  15573. var encodeUsingUrlEncoding = function (data) {
  15574. if(typeof data === 'string') {
  15575. return data;
  15576. }
  15577. var result = [];
  15578. for(var dataItem in data) {
  15579. if(data.hasOwnProperty(dataItem)) {
  15580. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  15581. }
  15582. }
  15583. return result.join('&');
  15584. };
  15585. var utf8 = function (text) {
  15586. text = text.replace(/\r\n/g, '\n');
  15587. var result = '';
  15588. for(var i = 0; i < text.length; i++) {
  15589. var c = text.charCodeAt(i);
  15590. if(c < 128) {
  15591. result += String.fromCharCode(c);
  15592. } else if((c > 127) && (c < 2048)) {
  15593. result += String.fromCharCode((c >> 6) | 192);
  15594. result += String.fromCharCode((c & 63) | 128);
  15595. } else {
  15596. result += String.fromCharCode((c >> 12) | 224);
  15597. result += String.fromCharCode(((c >> 6) & 63) | 128);
  15598. result += String.fromCharCode((c & 63) | 128);
  15599. }
  15600. }
  15601. return result;
  15602. };
  15603. var base64 = function (text) {
  15604. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15605. text = utf8(text);
  15606. var result = '',
  15607. chr1, chr2, chr3,
  15608. enc1, enc2, enc3, enc4,
  15609. i = 0;
  15610. do {
  15611. chr1 = text.charCodeAt(i++);
  15612. chr2 = text.charCodeAt(i++);
  15613. chr3 = text.charCodeAt(i++);
  15614. enc1 = chr1 >> 2;
  15615. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  15616. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  15617. enc4 = chr3 & 63;
  15618. if(isNaN(chr2)) {
  15619. enc3 = enc4 = 64;
  15620. } else if(isNaN(chr3)) {
  15621. enc4 = 64;
  15622. }
  15623. result +=
  15624. keyStr.charAt(enc1) +
  15625. keyStr.charAt(enc2) +
  15626. keyStr.charAt(enc3) +
  15627. keyStr.charAt(enc4);
  15628. chr1 = chr2 = chr3 = '';
  15629. enc1 = enc2 = enc3 = enc4 = '';
  15630. } while(i < text.length);
  15631. return result;
  15632. };
  15633. var mergeHeaders = function () {
  15634. // Use the first header object as base.
  15635. var result = arguments[0];
  15636. // Iterate through the remaining header objects and add them.
  15637. for(var i = 1; i < arguments.length; i++) {
  15638. var currentHeaders = arguments[i];
  15639. for(var header in currentHeaders) {
  15640. if(currentHeaders.hasOwnProperty(header)) {
  15641. result[header] = currentHeaders[header];
  15642. }
  15643. }
  15644. }
  15645. // Return the merged headers.
  15646. return result;
  15647. };
  15648. var ajax = function (method, url, options, callback) {
  15649. // Adjust parameters.
  15650. if(typeof options === 'function') {
  15651. callback = options;
  15652. options = {};
  15653. }
  15654. // Set default parameter values.
  15655. options.cache = options.cache || false;
  15656. options.data = options.data || {};
  15657. options.headers = options.headers || {};
  15658. options.jsonp = options.jsonp || false;
  15659. options.async = options.async === undefined ? true : options.async;
  15660. // Merge the various header objects.
  15661. var headers = mergeHeaders({
  15662. 'accept': '*/*',
  15663. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  15664. }, ajax.headers, options.headers);
  15665. // Encode the data according to the content-type.
  15666. var payload;
  15667. if (headers['content-type'] === 'application/json') {
  15668. payload = JSON.stringify(options.data);
  15669. } else {
  15670. payload = encodeUsingUrlEncoding(options.data);
  15671. }
  15672. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  15673. // if neccessary.
  15674. if(method === 'GET') {
  15675. // Setup the query string.
  15676. var queryString = [];
  15677. if(payload) {
  15678. queryString.push(payload);
  15679. payload = null;
  15680. }
  15681. // Handle caching.
  15682. if(!options.cache) {
  15683. queryString.push('_=' + (new Date()).getTime());
  15684. }
  15685. // If neccessary prepare the query string for a JSONP call.
  15686. if(options.jsonp) {
  15687. queryString.push('callback=' + options.jsonp);
  15688. queryString.push('jsonp=' + options.jsonp);
  15689. }
  15690. // Merge the query string and attach it to the url.
  15691. queryString = queryString.join('&');
  15692. if (queryString.length > 1) {
  15693. if (url.indexOf('?') > -1) {
  15694. url += '&' + queryString;
  15695. } else {
  15696. url += '?' + queryString;
  15697. }
  15698. }
  15699. // Make a JSONP call if neccessary.
  15700. if(options.jsonp) {
  15701. var head = document.getElementsByTagName('head')[0];
  15702. var script = document.createElement('script');
  15703. script.type = 'text/javascript';
  15704. script.src = url;
  15705. head.appendChild(script);
  15706. return;
  15707. }
  15708. }
  15709. // Since we got here, it is no JSONP request, so make a normal XHR request.
  15710. getXhr(function (err, xhr) {
  15711. if(err) return callback(err);
  15712. // Open the request.
  15713. xhr.open(method, url, options.async);
  15714. // Set the request headers.
  15715. for(var header in headers) {
  15716. if(headers.hasOwnProperty(header)) {
  15717. xhr.setRequestHeader(header, headers[header]);
  15718. }
  15719. }
  15720. // Handle the request events.
  15721. xhr.onreadystatechange = function () {
  15722. if(xhr.readyState === 4) {
  15723. var data = xhr.responseText || '';
  15724. // If no callback is given, return.
  15725. if(!callback) {
  15726. return;
  15727. }
  15728. // Return an object that provides access to the data as text and JSON.
  15729. callback(xhr.status, {
  15730. text: function () {
  15731. return data;
  15732. },
  15733. json: function () {
  15734. try {
  15735. return JSON.parse(data)
  15736. } catch (e) {
  15737. f.error('Can not parse JSON. URL: ' + url);
  15738. return {};
  15739. }
  15740. }
  15741. });
  15742. }
  15743. };
  15744. // Actually send the XHR request.
  15745. xhr.send(payload);
  15746. });
  15747. };
  15748. // Define the external interface.
  15749. var http = {
  15750. authBasic: function (username, password) {
  15751. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  15752. },
  15753. connect: function (url, options, callback) {
  15754. return ajax('CONNECT', url, options, callback);
  15755. },
  15756. del: function (url, options, callback) {
  15757. return ajax('DELETE', url, options, callback);
  15758. },
  15759. get: function (url, options, callback) {
  15760. return ajax('GET', url, options, callback);
  15761. },
  15762. head: function (url, options, callback) {
  15763. return ajax('HEAD', url, options, callback);
  15764. },
  15765. headers: function (headers) {
  15766. ajax.headers = headers || {};
  15767. },
  15768. isAllowed: function (url, verb, callback) {
  15769. this.options(url, function (status, data) {
  15770. callback(data.text().indexOf(verb) !== -1);
  15771. });
  15772. },
  15773. options: function (url, options, callback) {
  15774. return ajax('OPTIONS', url, options, callback);
  15775. },
  15776. patch: function (url, options, callback) {
  15777. return ajax('PATCH', url, options, callback);
  15778. },
  15779. post: function (url, options, callback) {
  15780. return ajax('POST', url, options, callback);
  15781. },
  15782. put: function (url, options, callback) {
  15783. return ajax('PUT', url, options, callback);
  15784. },
  15785. trace: function (url, options, callback) {
  15786. return ajax('TRACE', url, options, callback);
  15787. }
  15788. };
  15789. var methode = options.type ? options.type.toLowerCase() : 'get';
  15790. http[methode](options.url, options, function (status, data) {
  15791. // file: protocol always gives status code 0, so check for data
  15792. if (status === 200 || (status === 0 && data.text())) {
  15793. options.success(data.json(), status, null);
  15794. } else {
  15795. options.error(data.text(), status, null);
  15796. }
  15797. });
  15798. }
  15799. var _cookie = {
  15800. create: function(name,value,minutes,domain) {
  15801. var expires;
  15802. if (minutes) {
  15803. var date = new Date();
  15804. date.setTime(date.getTime()+(minutes*60*1000));
  15805. expires = "; expires="+date.toGMTString();
  15806. }
  15807. else expires = "";
  15808. domain = (domain)? "domain="+domain+";" : "";
  15809. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  15810. },
  15811. read: function(name) {
  15812. var nameEQ = name + "=";
  15813. var ca = document.cookie.split(';');
  15814. for(var i=0;i < ca.length;i++) {
  15815. var c = ca[i];
  15816. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  15817. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  15818. }
  15819. return null;
  15820. },
  15821. remove: function(name) {
  15822. this.create(name,"",-1);
  15823. }
  15824. };
  15825. var cookie_noop = {
  15826. create: function(name,value,minutes,domain) {},
  15827. read: function(name) { return null; },
  15828. remove: function(name) {}
  15829. };
  15830. // move dependent functions to a container so that
  15831. // they can be overriden easier in no jquery environment (node.js)
  15832. var f = {
  15833. extend: $ ? $.extend : _extend,
  15834. deepExtend: _deepExtend,
  15835. each: $ ? $.each : _each,
  15836. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  15837. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  15838. detectLanguage: detectLanguage,
  15839. escape: _escape,
  15840. log: function(str) {
  15841. if (o.debug && typeof console !== "undefined") console.log(str);
  15842. },
  15843. error: function(str) {
  15844. if (typeof console !== "undefined") console.error(str);
  15845. },
  15846. getCountyIndexOfLng: function(lng) {
  15847. var lng_index = 0;
  15848. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  15849. return lng_index;
  15850. },
  15851. toLanguages: function(lng) {
  15852. var log = this.log;
  15853. function applyCase(l) {
  15854. var ret = l;
  15855. if (typeof l === 'string' && l.indexOf('-') > -1) {
  15856. var parts = l.split('-');
  15857. ret = o.lowerCaseLng ?
  15858. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  15859. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  15860. } else {
  15861. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  15862. }
  15863. return ret;
  15864. }
  15865. var languages = [];
  15866. var whitelist = o.lngWhitelist || false;
  15867. var addLanguage = function(language){
  15868. //reject langs not whitelisted
  15869. if(!whitelist || whitelist.indexOf(language) > -1){
  15870. languages.push(language);
  15871. }else{
  15872. log('rejecting non-whitelisted language: ' + language);
  15873. }
  15874. };
  15875. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  15876. var parts = lng.split('-');
  15877. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  15878. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  15879. } else {
  15880. addLanguage(applyCase(lng));
  15881. }
  15882. for (var i = 0; i < o.fallbackLng.length; i++) {
  15883. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  15884. }
  15885. return languages;
  15886. },
  15887. regexEscape: function(str) {
  15888. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  15889. },
  15890. regexReplacementEscape: function(strOrFn) {
  15891. if (typeof strOrFn === 'string') {
  15892. return strOrFn.replace(/\$/g, "$$$$");
  15893. } else {
  15894. return strOrFn;
  15895. }
  15896. },
  15897. localStorage: {
  15898. setItem: function(key, value) {
  15899. if (window.localStorage) {
  15900. try {
  15901. window.localStorage.setItem(key, value);
  15902. } catch (e) {
  15903. f.log('failed to set value for key "' + key + '" to localStorage.');
  15904. }
  15905. }
  15906. }
  15907. }
  15908. };
  15909. function init(options, cb) {
  15910. if (typeof options === 'function') {
  15911. cb = options;
  15912. options = {};
  15913. }
  15914. options = options || {};
  15915. // override defaults with passed in options
  15916. f.extend(o, options);
  15917. delete o.fixLng; /* passed in each time */
  15918. // override functions: .log(), .detectLanguage(), etc
  15919. if (o.functions) {
  15920. delete o.functions;
  15921. f.extend(f, options.functions);
  15922. }
  15923. // create namespace object if namespace is passed in as string
  15924. if (typeof o.ns == 'string') {
  15925. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  15926. }
  15927. // fallback namespaces
  15928. if (typeof o.fallbackNS == 'string') {
  15929. o.fallbackNS = [o.fallbackNS];
  15930. }
  15931. // fallback languages
  15932. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  15933. o.fallbackLng = [o.fallbackLng];
  15934. }
  15935. // escape prefix/suffix
  15936. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  15937. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  15938. if (!o.lng) o.lng = f.detectLanguage();
  15939. languages = f.toLanguages(o.lng);
  15940. currentLng = languages[0];
  15941. f.log('currentLng set to: ' + currentLng);
  15942. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  15943. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  15944. }
  15945. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  15946. f.localStorage.setItem('i18next_lng', currentLng);
  15947. }
  15948. var lngTranslate = translate;
  15949. if (options.fixLng) {
  15950. lngTranslate = function(key, options) {
  15951. options = options || {};
  15952. options.lng = options.lng || lngTranslate.lng;
  15953. return translate(key, options);
  15954. };
  15955. lngTranslate.lng = currentLng;
  15956. }
  15957. pluralExtensions.setCurrentLng(currentLng);
  15958. // add JQuery extensions
  15959. if ($ && o.setJqueryExt) addJqueryFunct();
  15960. // jQuery deferred
  15961. var deferred;
  15962. if ($ && $.Deferred) {
  15963. deferred = $.Deferred();
  15964. }
  15965. // return immidiatly if res are passed in
  15966. if (o.resStore) {
  15967. resStore = o.resStore;
  15968. initialized = true;
  15969. if (cb) cb(lngTranslate);
  15970. if (deferred) deferred.resolve(lngTranslate);
  15971. if (deferred) return deferred.promise();
  15972. return;
  15973. }
  15974. // languages to load
  15975. var lngsToLoad = f.toLanguages(o.lng);
  15976. if (typeof o.preload === 'string') o.preload = [o.preload];
  15977. for (var i = 0, l = o.preload.length; i < l; i++) {
  15978. var pres = f.toLanguages(o.preload[i]);
  15979. for (var y = 0, len = pres.length; y < len; y++) {
  15980. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15981. lngsToLoad.push(pres[y]);
  15982. }
  15983. }
  15984. }
  15985. // else load them
  15986. i18n.sync.load(lngsToLoad, o, function(err, store) {
  15987. resStore = store;
  15988. initialized = true;
  15989. if (cb) cb(lngTranslate);
  15990. if (deferred) deferred.resolve(lngTranslate);
  15991. });
  15992. if (deferred) return deferred.promise();
  15993. }
  15994. function preload(lngs, cb) {
  15995. if (typeof lngs === 'string') lngs = [lngs];
  15996. for (var i = 0, l = lngs.length; i < l; i++) {
  15997. if (o.preload.indexOf(lngs[i]) < 0) {
  15998. o.preload.push(lngs[i]);
  15999. }
  16000. }
  16001. return init(cb);
  16002. }
  16003. function addResourceBundle(lng, ns, resources, deep) {
  16004. if (typeof ns !== 'string') {
  16005. resources = ns;
  16006. ns = o.ns.defaultNs;
  16007. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  16008. o.ns.namespaces.push(ns);
  16009. }
  16010. resStore[lng] = resStore[lng] || {};
  16011. resStore[lng][ns] = resStore[lng][ns] || {};
  16012. if (deep) {
  16013. f.deepExtend(resStore[lng][ns], resources);
  16014. } else {
  16015. f.extend(resStore[lng][ns], resources);
  16016. }
  16017. }
  16018. function hasResourceBundle(lng, ns) {
  16019. if (typeof ns !== 'string') {
  16020. ns = o.ns.defaultNs;
  16021. }
  16022. resStore[lng] = resStore[lng] || {};
  16023. var res = resStore[lng][ns] || {};
  16024. var hasValues = false;
  16025. for(var prop in res) {
  16026. if (res.hasOwnProperty(prop)) {
  16027. hasValues = true;
  16028. }
  16029. }
  16030. return hasValues;
  16031. }
  16032. function removeResourceBundle(lng, ns) {
  16033. if (typeof ns !== 'string') {
  16034. ns = o.ns.defaultNs;
  16035. }
  16036. resStore[lng] = resStore[lng] || {};
  16037. resStore[lng][ns] = {};
  16038. }
  16039. function addResource(lng, ns, key, value) {
  16040. if (typeof ns !== 'string') {
  16041. resource = ns;
  16042. ns = o.ns.defaultNs;
  16043. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  16044. o.ns.namespaces.push(ns);
  16045. }
  16046. resStore[lng] = resStore[lng] || {};
  16047. resStore[lng][ns] = resStore[lng][ns] || {};
  16048. var keys = key.split(o.keyseparator);
  16049. var x = 0;
  16050. var node = resStore[lng][ns];
  16051. var origRef = node;
  16052. while (keys[x]) {
  16053. if (x == keys.length - 1)
  16054. node[keys[x]] = value;
  16055. else {
  16056. if (node[keys[x]] == null)
  16057. node[keys[x]] = {};
  16058. node = node[keys[x]];
  16059. }
  16060. x++;
  16061. }
  16062. }
  16063. function addResources(lng, ns, resources) {
  16064. if (typeof ns !== 'string') {
  16065. resource = ns;
  16066. ns = o.ns.defaultNs;
  16067. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  16068. o.ns.namespaces.push(ns);
  16069. }
  16070. for (var m in resources) {
  16071. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  16072. }
  16073. }
  16074. function setDefaultNamespace(ns) {
  16075. o.ns.defaultNs = ns;
  16076. }
  16077. function loadNamespace(namespace, cb) {
  16078. loadNamespaces([namespace], cb);
  16079. }
  16080. function loadNamespaces(namespaces, cb) {
  16081. var opts = {
  16082. dynamicLoad: o.dynamicLoad,
  16083. resGetPath: o.resGetPath,
  16084. getAsync: o.getAsync,
  16085. customLoad: o.customLoad,
  16086. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  16087. };
  16088. // languages to load
  16089. var lngsToLoad = f.toLanguages(o.lng);
  16090. if (typeof o.preload === 'string') o.preload = [o.preload];
  16091. for (var i = 0, l = o.preload.length; i < l; i++) {
  16092. var pres = f.toLanguages(o.preload[i]);
  16093. for (var y = 0, len = pres.length; y < len; y++) {
  16094. if (lngsToLoad.indexOf(pres[y]) < 0) {
  16095. lngsToLoad.push(pres[y]);
  16096. }
  16097. }
  16098. }
  16099. // check if we have to load
  16100. var lngNeedLoad = [];
  16101. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  16102. var needLoad = false;
  16103. var resSet = resStore[lngsToLoad[a]];
  16104. if (resSet) {
  16105. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  16106. if (!resSet[namespaces[b]]) needLoad = true;
  16107. }
  16108. } else {
  16109. needLoad = true;
  16110. }
  16111. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  16112. }
  16113. if (lngNeedLoad.length) {
  16114. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  16115. var todo = namespaces.length * lngNeedLoad.length;
  16116. // load each file individual
  16117. f.each(namespaces, function(nsIndex, nsValue) {
  16118. // append namespace to namespace array
  16119. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  16120. o.ns.namespaces.push(nsValue);
  16121. }
  16122. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  16123. resStore[lngValue] = resStore[lngValue] || {};
  16124. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  16125. todo--; // wait for all done befor callback
  16126. if (todo === 0 && cb) {
  16127. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  16128. cb();
  16129. }
  16130. });
  16131. });
  16132. });
  16133. } else {
  16134. if (cb) cb();
  16135. }
  16136. }
  16137. function setLng(lng, options, cb) {
  16138. if (typeof options === 'function') {
  16139. cb = options;
  16140. options = {};
  16141. } else if (!options) {
  16142. options = {};
  16143. }
  16144. options.lng = lng;
  16145. return init(options, cb);
  16146. }
  16147. function lng() {
  16148. return currentLng;
  16149. }
  16150. function reload(cb) {
  16151. resStore = {};
  16152. setLng(currentLng, cb);
  16153. }
  16154. function addJqueryFunct() {
  16155. // $.t shortcut
  16156. $.t = $.t || translate;
  16157. function parse(ele, key, options) {
  16158. if (key.length === 0) return;
  16159. var attr = 'text';
  16160. if (key.indexOf('[') === 0) {
  16161. var parts = key.split(']');
  16162. key = parts[1];
  16163. attr = parts[0].substr(1, parts[0].length-1);
  16164. }
  16165. if (key.indexOf(';') === key.length-1) {
  16166. key = key.substr(0, key.length-2);
  16167. }
  16168. var optionsToUse;
  16169. if (attr === 'html') {
  16170. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16171. ele.html($.t(key, optionsToUse));
  16172. } else if (attr === 'text') {
  16173. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  16174. ele.text($.t(key, optionsToUse));
  16175. } else if (attr === 'prepend') {
  16176. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16177. ele.prepend($.t(key, optionsToUse));
  16178. } else if (attr === 'append') {
  16179. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16180. ele.append($.t(key, optionsToUse));
  16181. } else if (attr.indexOf("data-") === 0) {
  16182. var dataAttr = attr.substr(("data-").length);
  16183. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  16184. var translated = $.t(key, optionsToUse);
  16185. //we change into the data cache
  16186. ele.data(dataAttr, translated);
  16187. //we change into the dom
  16188. ele.attr(attr, translated);
  16189. } else {
  16190. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  16191. ele.attr(attr, $.t(key, optionsToUse));
  16192. }
  16193. }
  16194. function localize(ele, options) {
  16195. var key = ele.attr(o.selectorAttr);
  16196. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  16197. if (!key) return;
  16198. var target = ele
  16199. , targetSelector = ele.data("i18n-target");
  16200. if (targetSelector) {
  16201. target = ele.find(targetSelector) || ele;
  16202. }
  16203. if (!options && o.useDataAttrOptions === true) {
  16204. options = ele.data("i18n-options");
  16205. }
  16206. options = options || {};
  16207. if (key.indexOf(';') >= 0) {
  16208. var keys = key.split(';');
  16209. $.each(keys, function(m, k) {
  16210. if (k !== '') parse(target, k, options);
  16211. });
  16212. } else {
  16213. parse(target, key, options);
  16214. }
  16215. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  16216. }
  16217. // fn
  16218. $.fn.i18n = function (options) {
  16219. return this.each(function() {
  16220. // localize element itself
  16221. localize($(this), options);
  16222. // localize childs
  16223. var elements = $(this).find('[' + o.selectorAttr + ']');
  16224. elements.each(function() {
  16225. localize($(this), options);
  16226. });
  16227. });
  16228. };
  16229. }
  16230. function applyReplacement(str, replacementHash, nestedKey, options) {
  16231. if (!str) return str;
  16232. options = options || replacementHash; // first call uses replacement hash combined with options
  16233. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  16234. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  16235. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  16236. , unEscapingSuffix = 'HTML'+suffix;
  16237. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  16238. f.each(hash, function(key, value) {
  16239. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  16240. if (typeof value === 'object' && value !== null) {
  16241. str = applyReplacement(str, value, nextKey, options);
  16242. } else {
  16243. if (options.escapeInterpolation || o.escapeInterpolation) {
  16244. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  16245. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  16246. } else {
  16247. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  16248. }
  16249. // str = options.escapeInterpolation;
  16250. }
  16251. });
  16252. return str;
  16253. }
  16254. // append it to functions
  16255. f.applyReplacement = applyReplacement;
  16256. function applyReuse(translated, options) {
  16257. var comma = ',';
  16258. var options_open = '{';
  16259. var options_close = '}';
  16260. var opts = f.extend({}, options);
  16261. delete opts.postProcess;
  16262. while (translated.indexOf(o.reusePrefix) != -1) {
  16263. replacementCounter++;
  16264. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  16265. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  16266. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  16267. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  16268. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  16269. if (index_of_end_of_closing <= index_of_opening) {
  16270. f.error('there is an missing closing in following translation value', translated);
  16271. return '';
  16272. }
  16273. if (token_without_symbols.indexOf(comma) != -1) {
  16274. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  16275. 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) {
  16276. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  16277. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  16278. try {
  16279. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  16280. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  16281. } catch (e) {
  16282. }
  16283. }
  16284. }
  16285. var translated_token = _translate(token_without_symbols, opts);
  16286. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  16287. }
  16288. return translated;
  16289. }
  16290. function hasContext(options) {
  16291. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  16292. }
  16293. function needsPlural(options, lng) {
  16294. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  16295. }
  16296. function needsIndefiniteArticle(options) {
  16297. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  16298. }
  16299. function exists(key, options) {
  16300. options = options || {};
  16301. var notFound = _getDefaultValue(key, options)
  16302. , found = _find(key, options);
  16303. return found !== undefined || found === notFound;
  16304. }
  16305. function translate(key, options) {
  16306. options = options || {};
  16307. if (!initialized) {
  16308. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  16309. return options.defaultValue || '';
  16310. };
  16311. replacementCounter = 0;
  16312. return _translate.apply(null, arguments);
  16313. }
  16314. function _getDefaultValue(key, options) {
  16315. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  16316. }
  16317. function _injectSprintfProcessor() {
  16318. var values = [];
  16319. // mh: build array from second argument onwards
  16320. for (var i = 1; i < arguments.length; i++) {
  16321. values.push(arguments[i]);
  16322. }
  16323. return {
  16324. postProcess: 'sprintf',
  16325. sprintf: values
  16326. };
  16327. }
  16328. function _translate(potentialKeys, options) {
  16329. if (options && typeof options !== 'object') {
  16330. if (o.shortcutFunction === 'sprintf') {
  16331. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  16332. options = _injectSprintfProcessor.apply(null, arguments);
  16333. } else if (o.shortcutFunction === 'defaultValue') {
  16334. options = {
  16335. defaultValue: options
  16336. }
  16337. }
  16338. } else {
  16339. options = options || {};
  16340. }
  16341. if (typeof o.defaultVariables === 'object') {
  16342. options = f.extend({}, o.defaultVariables, options);
  16343. }
  16344. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  16345. if (typeof potentialKeys === 'string') {
  16346. potentialKeys = [potentialKeys];
  16347. }
  16348. var key = potentialKeys[0];
  16349. if (potentialKeys.length > 1) {
  16350. for (var i = 0; i < potentialKeys.length; i++) {
  16351. key = potentialKeys[i];
  16352. if (exists(key, options)) {
  16353. break;
  16354. }
  16355. }
  16356. }
  16357. var notFound = _getDefaultValue(key, options)
  16358. , found = _find(key, options)
  16359. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  16360. , ns = options.ns || o.ns.defaultNs
  16361. , parts;
  16362. // split ns and key
  16363. if (key.indexOf(o.nsseparator) > -1) {
  16364. parts = key.split(o.nsseparator);
  16365. ns = parts[0];
  16366. key = parts[1];
  16367. }
  16368. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  16369. if (options.lng) {
  16370. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  16371. } else {
  16372. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  16373. }
  16374. }
  16375. var postProcessor = options.postProcess || o.postProcess;
  16376. if (found !== undefined && postProcessor) {
  16377. if (postProcessors[postProcessor]) {
  16378. found = postProcessors[postProcessor](found, key, options);
  16379. }
  16380. }
  16381. // process notFound if function exists
  16382. var splitNotFound = notFound;
  16383. if (notFound.indexOf(o.nsseparator) > -1) {
  16384. parts = notFound.split(o.nsseparator);
  16385. splitNotFound = parts[1];
  16386. }
  16387. if (splitNotFound === key && o.parseMissingKey) {
  16388. notFound = o.parseMissingKey(notFound);
  16389. }
  16390. if (found === undefined) {
  16391. notFound = applyReplacement(notFound, options);
  16392. notFound = applyReuse(notFound, options);
  16393. if (postProcessor && postProcessors[postProcessor]) {
  16394. var val = _getDefaultValue(key, options);
  16395. found = postProcessors[postProcessor](val, key, options);
  16396. }
  16397. }
  16398. return (found !== undefined) ? found : notFound;
  16399. }
  16400. function _find(key, options) {
  16401. options = options || {};
  16402. var optionWithoutCount, translated
  16403. , notFound = _getDefaultValue(key, options)
  16404. , lngs = languages;
  16405. if (!resStore) { return notFound; } // no resStore to translate from
  16406. // CI mode
  16407. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  16408. // passed in lng
  16409. if (options.lngs) lngs = options.lngs;
  16410. if (options.lng) {
  16411. lngs = f.toLanguages(options.lng, options.fallbackLng);
  16412. if (!resStore[lngs[0]]) {
  16413. var oldAsync = o.getAsync;
  16414. o.getAsync = false;
  16415. i18n.sync.load(lngs, o, function(err, store) {
  16416. f.extend(resStore, store);
  16417. o.getAsync = oldAsync;
  16418. });
  16419. }
  16420. }
  16421. var ns = options.ns || o.ns.defaultNs;
  16422. if (key.indexOf(o.nsseparator) > -1) {
  16423. var parts = key.split(o.nsseparator);
  16424. ns = parts[0];
  16425. key = parts[1];
  16426. }
  16427. if (hasContext(options)) {
  16428. optionWithoutCount = f.extend({}, options);
  16429. delete optionWithoutCount.context;
  16430. optionWithoutCount.defaultValue = o.contextNotFound;
  16431. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  16432. translated = translate(contextKey, optionWithoutCount);
  16433. if (translated != o.contextNotFound) {
  16434. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  16435. } // else continue translation with original/nonContext key
  16436. }
  16437. if (needsPlural(options, lngs[0])) {
  16438. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  16439. delete optionWithoutCount.count;
  16440. delete optionWithoutCount.lng;
  16441. optionWithoutCount.defaultValue = o.pluralNotFound;
  16442. var pluralKey;
  16443. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  16444. pluralKey = ns + o.nsseparator + key;
  16445. } else {
  16446. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  16447. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  16448. if (pluralExtension >= 0) {
  16449. pluralKey = pluralKey + '_' + pluralExtension;
  16450. } else if (pluralExtension === 1) {
  16451. pluralKey = ns + o.nsseparator + key; // singular
  16452. }
  16453. }
  16454. translated = translate(pluralKey, optionWithoutCount);
  16455. if (translated != o.pluralNotFound) {
  16456. return applyReplacement(translated, {
  16457. count: options.count,
  16458. interpolationPrefix: options.interpolationPrefix,
  16459. interpolationSuffix: options.interpolationSuffix
  16460. }); // apply replacement for count only
  16461. } else if (lngs.length > 1) {
  16462. // remove failed lng
  16463. var clone = lngs.slice();
  16464. clone.shift();
  16465. options = f.extend(options, { lngs: clone });
  16466. delete options.lng;
  16467. // retry with fallbacks
  16468. translated = translate(ns + o.nsseparator + key, options);
  16469. if (translated != o.pluralNotFound) return translated;
  16470. } else {
  16471. return translated;
  16472. }
  16473. }
  16474. if (needsIndefiniteArticle(options)) {
  16475. var optionsWithoutIndef = f.extend({}, options);
  16476. delete optionsWithoutIndef.indefinite_article;
  16477. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  16478. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  16479. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  16480. translated = translate(indefiniteKey, optionsWithoutIndef);
  16481. if (translated != o.indefiniteNotFound) {
  16482. return translated;
  16483. }
  16484. }
  16485. var found;
  16486. var keys = key.split(o.keyseparator);
  16487. for (var i = 0, len = lngs.length; i < len; i++ ) {
  16488. if (found !== undefined) break;
  16489. var l = lngs[i];
  16490. var x = 0;
  16491. var value = resStore[l] && resStore[l][ns];
  16492. while (keys[x]) {
  16493. value = value && value[keys[x]];
  16494. x++;
  16495. }
  16496. if (value !== undefined) {
  16497. var valueType = Object.prototype.toString.apply(value);
  16498. if (typeof value === 'string') {
  16499. value = applyReplacement(value, options);
  16500. value = applyReuse(value, options);
  16501. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  16502. value = value.join('\n');
  16503. value = applyReplacement(value, options);
  16504. value = applyReuse(value, options);
  16505. } else if (value === null && o.fallbackOnNull === true) {
  16506. value = undefined;
  16507. } else if (value !== null) {
  16508. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  16509. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  16510. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  16511. } else {
  16512. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  16513. 'returned an object instead of string.';
  16514. f.log(value);
  16515. }
  16516. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  16517. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  16518. f.each(value, function(m) {
  16519. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  16520. });
  16521. value = copy;
  16522. }
  16523. }
  16524. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  16525. value = undefined;
  16526. found = value;
  16527. }
  16528. }
  16529. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  16530. // set flag for fallback lookup - avoid recursion
  16531. options.isFallbackLookup = true;
  16532. if (o.fallbackNS.length) {
  16533. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  16534. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  16535. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  16536. /* compare value without namespace */
  16537. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  16538. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  16539. if (foundValue !== notFoundValue) break;
  16540. }
  16541. }
  16542. } else {
  16543. found = _find(key, options); // fallback to default NS
  16544. }
  16545. options.isFallbackLookup = false;
  16546. }
  16547. return found;
  16548. }
  16549. function detectLanguage() {
  16550. var detectedLng;
  16551. var whitelist = o.lngWhitelist || [];
  16552. var userLngChoices = [];
  16553. // get from qs
  16554. var qsParm = [];
  16555. if (typeof window !== 'undefined') {
  16556. (function() {
  16557. var query = window.location.search.substring(1);
  16558. var params = query.split('&');
  16559. for (var i=0; i<params.length; i++) {
  16560. var pos = params[i].indexOf('=');
  16561. if (pos > 0) {
  16562. var key = params[i].substring(0,pos);
  16563. if (key == o.detectLngQS) {
  16564. userLngChoices.push(params[i].substring(pos+1));
  16565. }
  16566. }
  16567. }
  16568. })();
  16569. }
  16570. // get from cookie
  16571. if (o.useCookie && typeof document !== 'undefined') {
  16572. var c = f.cookie.read(o.cookieName);
  16573. if (c) userLngChoices.push(c);
  16574. }
  16575. // get from localStorage
  16576. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  16577. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  16578. }
  16579. // get from navigator
  16580. if (typeof navigator !== 'undefined') {
  16581. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  16582. for (var i=0;i<navigator.languages.length;i++) {
  16583. userLngChoices.push(navigator.languages[i]);
  16584. }
  16585. }
  16586. if (navigator.userLanguage) {
  16587. userLngChoices.push(navigator.userLanguage);
  16588. }
  16589. if (navigator.language) {
  16590. userLngChoices.push(navigator.language);
  16591. }
  16592. }
  16593. (function() {
  16594. for (var i=0;i<userLngChoices.length;i++) {
  16595. var lng = userLngChoices[i];
  16596. if (lng.indexOf('-') > -1) {
  16597. var parts = lng.split('-');
  16598. lng = o.lowerCaseLng ?
  16599. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  16600. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  16601. }
  16602. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  16603. detectedLng = lng;
  16604. break;
  16605. }
  16606. }
  16607. })();
  16608. //fallback
  16609. if (!detectedLng){
  16610. detectedLng = o.fallbackLng[0];
  16611. }
  16612. return detectedLng;
  16613. }
  16614. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  16615. /* [code, name, numbers, pluralsType] */
  16616. var _rules = [
  16617. ["ach", "Acholi", [1,2], 1],
  16618. ["af", "Afrikaans",[1,2], 2],
  16619. ["ak", "Akan", [1,2], 1],
  16620. ["am", "Amharic", [1,2], 1],
  16621. ["an", "Aragonese",[1,2], 2],
  16622. ["ar", "Arabic", [0,1,2,3,11,100],5],
  16623. ["arn", "Mapudungun",[1,2], 1],
  16624. ["ast", "Asturian", [1,2], 2],
  16625. ["ay", "Aymará", [1], 3],
  16626. ["az", "Azerbaijani",[1,2],2],
  16627. ["be", "Belarusian",[1,2,5],4],
  16628. ["bg", "Bulgarian",[1,2], 2],
  16629. ["bn", "Bengali", [1,2], 2],
  16630. ["bo", "Tibetan", [1], 3],
  16631. ["br", "Breton", [1,2], 1],
  16632. ["bs", "Bosnian", [1,2,5],4],
  16633. ["ca", "Catalan", [1,2], 2],
  16634. ["cgg", "Chiga", [1], 3],
  16635. ["cs", "Czech", [1,2,5],6],
  16636. ["csb", "Kashubian",[1,2,5],7],
  16637. ["cy", "Welsh", [1,2,3,8],8],
  16638. ["da", "Danish", [1,2], 2],
  16639. ["de", "German", [1,2], 2],
  16640. ["dev", "Development Fallback", [1,2], 2],
  16641. ["dz", "Dzongkha", [1], 3],
  16642. ["el", "Greek", [1,2], 2],
  16643. ["en", "English", [1,2], 2],
  16644. ["eo", "Esperanto",[1,2], 2],
  16645. ["es", "Spanish", [1,2], 2],
  16646. ["es_ar","Argentinean Spanish", [1,2], 2],
  16647. ["et", "Estonian", [1,2], 2],
  16648. ["eu", "Basque", [1,2], 2],
  16649. ["fa", "Persian", [1], 3],
  16650. ["fi", "Finnish", [1,2], 2],
  16651. ["fil", "Filipino", [1,2], 1],
  16652. ["fo", "Faroese", [1,2], 2],
  16653. ["fr", "French", [1,2], 9],
  16654. ["fur", "Friulian", [1,2], 2],
  16655. ["fy", "Frisian", [1,2], 2],
  16656. ["ga", "Irish", [1,2,3,7,11],10],
  16657. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  16658. ["gl", "Galician", [1,2], 2],
  16659. ["gu", "Gujarati", [1,2], 2],
  16660. ["gun", "Gun", [1,2], 1],
  16661. ["ha", "Hausa", [1,2], 2],
  16662. ["he", "Hebrew", [1,2], 2],
  16663. ["hi", "Hindi", [1,2], 2],
  16664. ["hr", "Croatian", [1,2,5],4],
  16665. ["hu", "Hungarian",[1,2], 2],
  16666. ["hy", "Armenian", [1,2], 2],
  16667. ["ia", "Interlingua",[1,2],2],
  16668. ["id", "Indonesian",[1], 3],
  16669. ["is", "Icelandic",[1,2], 12],
  16670. ["it", "Italian", [1,2], 2],
  16671. ["ja", "Japanese", [1], 3],
  16672. ["jbo", "Lojban", [1], 3],
  16673. ["jv", "Javanese", [0,1], 13],
  16674. ["ka", "Georgian", [1], 3],
  16675. ["kk", "Kazakh", [1], 3],
  16676. ["km", "Khmer", [1], 3],
  16677. ["kn", "Kannada", [1,2], 2],
  16678. ["ko", "Korean", [1], 3],
  16679. ["ku", "Kurdish", [1,2], 2],
  16680. ["kw", "Cornish", [1,2,3,4],14],
  16681. ["ky", "Kyrgyz", [1], 3],
  16682. ["lb", "Letzeburgesch",[1,2],2],
  16683. ["ln", "Lingala", [1,2], 1],
  16684. ["lo", "Lao", [1], 3],
  16685. ["lt", "Lithuanian",[1,2,10],15],
  16686. ["lv", "Latvian", [1,2,0],16],
  16687. ["mai", "Maithili", [1,2], 2],
  16688. ["mfe", "Mauritian Creole",[1,2],1],
  16689. ["mg", "Malagasy", [1,2], 1],
  16690. ["mi", "Maori", [1,2], 1],
  16691. ["mk", "Macedonian",[1,2],17],
  16692. ["ml", "Malayalam",[1,2], 2],
  16693. ["mn", "Mongolian",[1,2], 2],
  16694. ["mnk", "Mandinka", [0,1,2],18],
  16695. ["mr", "Marathi", [1,2], 2],
  16696. ["ms", "Malay", [1], 3],
  16697. ["mt", "Maltese", [1,2,11,20],19],
  16698. ["nah", "Nahuatl", [1,2], 2],
  16699. ["nap", "Neapolitan",[1,2], 2],
  16700. ["nb", "Norwegian Bokmal",[1,2],2],
  16701. ["ne", "Nepali", [1,2], 2],
  16702. ["nl", "Dutch", [1,2], 2],
  16703. ["nn", "Norwegian Nynorsk",[1,2],2],
  16704. ["no", "Norwegian",[1,2], 2],
  16705. ["nso", "Northern Sotho",[1,2],2],
  16706. ["oc", "Occitan", [1,2], 1],
  16707. ["or", "Oriya", [2,1], 2],
  16708. ["pa", "Punjabi", [1,2], 2],
  16709. ["pap", "Papiamento",[1,2], 2],
  16710. ["pl", "Polish", [1,2,5],7],
  16711. ["pms", "Piemontese",[1,2], 2],
  16712. ["ps", "Pashto", [1,2], 2],
  16713. ["pt", "Portuguese",[1,2], 2],
  16714. ["pt_br","Brazilian Portuguese",[1,2], 2],
  16715. ["rm", "Romansh", [1,2], 2],
  16716. ["ro", "Romanian", [1,2,20],20],
  16717. ["ru", "Russian", [1,2,5],4],
  16718. ["sah", "Yakut", [1], 3],
  16719. ["sco", "Scots", [1,2], 2],
  16720. ["se", "Northern Sami",[1,2], 2],
  16721. ["si", "Sinhala", [1,2], 2],
  16722. ["sk", "Slovak", [1,2,5],6],
  16723. ["sl", "Slovenian",[5,1,2,3],21],
  16724. ["so", "Somali", [1,2], 2],
  16725. ["son", "Songhay", [1,2], 2],
  16726. ["sq", "Albanian", [1,2], 2],
  16727. ["sr", "Serbian", [1,2,5],4],
  16728. ["su", "Sundanese",[1], 3],
  16729. ["sv", "Swedish", [1,2], 2],
  16730. ["sw", "Swahili", [1,2], 2],
  16731. ["ta", "Tamil", [1,2], 2],
  16732. ["te", "Telugu", [1,2], 2],
  16733. ["tg", "Tajik", [1,2], 1],
  16734. ["th", "Thai", [1], 3],
  16735. ["ti", "Tigrinya", [1,2], 1],
  16736. ["tk", "Turkmen", [1,2], 2],
  16737. ["tr", "Turkish", [1,2], 1],
  16738. ["tt", "Tatar", [1], 3],
  16739. ["ug", "Uyghur", [1], 3],
  16740. ["uk", "Ukrainian",[1,2,5],4],
  16741. ["ur", "Urdu", [1,2], 2],
  16742. ["uz", "Uzbek", [1,2], 1],
  16743. ["vi", "Vietnamese",[1], 3],
  16744. ["wa", "Walloon", [1,2], 1],
  16745. ["wo", "Wolof", [1], 3],
  16746. ["yo", "Yoruba", [1,2], 2],
  16747. ["zh", "Chinese", [1], 3]
  16748. ];
  16749. var _rulesPluralsTypes = {
  16750. 1: function(n) {return Number(n > 1);},
  16751. 2: function(n) {return Number(n != 1);},
  16752. 3: function(n) {return 0;},
  16753. 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);},
  16754. 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);},
  16755. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  16756. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16757. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  16758. 9: function(n) {return Number(n >= 2);},
  16759. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  16760. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  16761. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  16762. 13: function(n) {return Number(n !== 0);},
  16763. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  16764. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16765. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  16766. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  16767. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  16768. 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);},
  16769. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  16770. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  16771. };
  16772. var pluralExtensions = {
  16773. rules: (function () {
  16774. var l, rules = {};
  16775. for (l=_rules.length; l-- ;) {
  16776. rules[_rules[l][0]] = {
  16777. name: _rules[l][1],
  16778. numbers: _rules[l][2],
  16779. plurals: _rulesPluralsTypes[_rules[l][3]]
  16780. }
  16781. }
  16782. return rules;
  16783. }()),
  16784. // you can add your own pluralExtensions
  16785. addRule: function(lng, obj) {
  16786. pluralExtensions.rules[lng] = obj;
  16787. },
  16788. setCurrentLng: function(lng) {
  16789. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  16790. var parts = lng.split('-');
  16791. pluralExtensions.currentRule = {
  16792. lng: lng,
  16793. rule: pluralExtensions.rules[parts[0]]
  16794. };
  16795. }
  16796. },
  16797. needsPlural: function(lng, count) {
  16798. var parts = lng.split('-');
  16799. var ext;
  16800. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16801. ext = pluralExtensions.currentRule.rule;
  16802. } else {
  16803. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  16804. }
  16805. if (ext && ext.numbers.length <= 1) {
  16806. return false;
  16807. } else {
  16808. return this.get(lng, count) !== 1;
  16809. }
  16810. },
  16811. get: function(lng, count) {
  16812. var parts = lng.split('-');
  16813. function getResult(l, c) {
  16814. var ext;
  16815. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16816. ext = pluralExtensions.currentRule.rule;
  16817. } else {
  16818. ext = pluralExtensions.rules[l];
  16819. }
  16820. if (ext) {
  16821. var i;
  16822. if (ext.noAbs) {
  16823. i = ext.plurals(c);
  16824. } else {
  16825. i = ext.plurals(Math.abs(c));
  16826. }
  16827. var number = ext.numbers[i];
  16828. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  16829. if (number === 2) {
  16830. number = -1; // regular plural
  16831. } else if (number === 1) {
  16832. number = 1; // singular
  16833. }
  16834. }//console.log(count + '-' + number);
  16835. return number;
  16836. } else {
  16837. return c === 1 ? '1' : '-1';
  16838. }
  16839. }
  16840. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  16841. }
  16842. };
  16843. var postProcessors = {};
  16844. var addPostProcessor = function(name, fc) {
  16845. postProcessors[name] = fc;
  16846. };
  16847. // sprintf support
  16848. var sprintf = (function() {
  16849. function get_type(variable) {
  16850. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  16851. }
  16852. function str_repeat(input, multiplier) {
  16853. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  16854. return output.join('');
  16855. }
  16856. var str_format = function() {
  16857. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  16858. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  16859. }
  16860. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  16861. };
  16862. str_format.format = function(parse_tree, argv) {
  16863. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  16864. for (i = 0; i < tree_length; i++) {
  16865. node_type = get_type(parse_tree[i]);
  16866. if (node_type === 'string') {
  16867. output.push(parse_tree[i]);
  16868. }
  16869. else if (node_type === 'array') {
  16870. match = parse_tree[i]; // convenience purposes only
  16871. if (match[2]) { // keyword argument
  16872. arg = argv[cursor];
  16873. for (k = 0; k < match[2].length; k++) {
  16874. if (!arg.hasOwnProperty(match[2][k])) {
  16875. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  16876. }
  16877. arg = arg[match[2][k]];
  16878. }
  16879. }
  16880. else if (match[1]) { // positional argument (explicit)
  16881. arg = argv[match[1]];
  16882. }
  16883. else { // positional argument (implicit)
  16884. arg = argv[cursor++];
  16885. }
  16886. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  16887. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  16888. }
  16889. switch (match[8]) {
  16890. case 'b': arg = arg.toString(2); break;
  16891. case 'c': arg = String.fromCharCode(arg); break;
  16892. case 'd': arg = parseInt(arg, 10); break;
  16893. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  16894. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  16895. case 'o': arg = arg.toString(8); break;
  16896. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  16897. case 'u': arg = Math.abs(arg); break;
  16898. case 'x': arg = arg.toString(16); break;
  16899. case 'X': arg = arg.toString(16).toUpperCase(); break;
  16900. }
  16901. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  16902. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  16903. pad_length = match[6] - String(arg).length;
  16904. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  16905. output.push(match[5] ? arg + pad : pad + arg);
  16906. }
  16907. }
  16908. return output.join('');
  16909. };
  16910. str_format.cache = {};
  16911. str_format.parse = function(fmt) {
  16912. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  16913. while (_fmt) {
  16914. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  16915. parse_tree.push(match[0]);
  16916. }
  16917. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  16918. parse_tree.push('%');
  16919. }
  16920. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  16921. if (match[2]) {
  16922. arg_names |= 1;
  16923. var field_list = [], replacement_field = match[2], field_match = [];
  16924. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16925. field_list.push(field_match[1]);
  16926. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  16927. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16928. field_list.push(field_match[1]);
  16929. }
  16930. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  16931. field_list.push(field_match[1]);
  16932. }
  16933. else {
  16934. throw('[sprintf] huh?');
  16935. }
  16936. }
  16937. }
  16938. else {
  16939. throw('[sprintf] huh?');
  16940. }
  16941. match[2] = field_list;
  16942. }
  16943. else {
  16944. arg_names |= 2;
  16945. }
  16946. if (arg_names === 3) {
  16947. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  16948. }
  16949. parse_tree.push(match);
  16950. }
  16951. else {
  16952. throw('[sprintf] huh?');
  16953. }
  16954. _fmt = _fmt.substring(match[0].length);
  16955. }
  16956. return parse_tree;
  16957. };
  16958. return str_format;
  16959. })();
  16960. var vsprintf = function(fmt, argv) {
  16961. argv.unshift(fmt);
  16962. return sprintf.apply(null, argv);
  16963. };
  16964. addPostProcessor("sprintf", function(val, key, opts) {
  16965. if (!opts.sprintf) return val;
  16966. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  16967. return vsprintf(val, opts.sprintf);
  16968. } else if (typeof opts.sprintf === 'object') {
  16969. return sprintf(val, opts.sprintf);
  16970. }
  16971. return val;
  16972. });
  16973. // public api interface
  16974. i18n.init = init;
  16975. i18n.setLng = setLng;
  16976. i18n.preload = preload;
  16977. i18n.addResourceBundle = addResourceBundle;
  16978. i18n.hasResourceBundle = hasResourceBundle;
  16979. i18n.addResource = addResource;
  16980. i18n.addResources = addResources;
  16981. i18n.removeResourceBundle = removeResourceBundle;
  16982. i18n.loadNamespace = loadNamespace;
  16983. i18n.loadNamespaces = loadNamespaces;
  16984. i18n.setDefaultNamespace = setDefaultNamespace;
  16985. i18n.t = translate;
  16986. i18n.translate = translate;
  16987. i18n.exists = exists;
  16988. i18n.detectLanguage = f.detectLanguage;
  16989. i18n.pluralExtensions = pluralExtensions;
  16990. i18n.sync = sync;
  16991. i18n.functions = f;
  16992. i18n.lng = lng;
  16993. i18n.addPostProcessor = addPostProcessor;
  16994. i18n.options = o;
  16995. })();
  16996. },{"jquery":"jquery"}],63:[function(require,module,exports){
  16997. // Top level file is just a mixin of submodules & constants
  16998. 'use strict';
  16999. var assign = require('./lib/utils/common').assign;
  17000. var deflate = require('./lib/deflate');
  17001. var inflate = require('./lib/inflate');
  17002. var constants = require('./lib/zlib/constants');
  17003. var pako = {};
  17004. assign(pako, deflate, inflate, constants);
  17005. module.exports = pako;
  17006. },{"./lib/deflate":64,"./lib/inflate":65,"./lib/utils/common":66,"./lib/zlib/constants":69}],64:[function(require,module,exports){
  17007. 'use strict';
  17008. var zlib_deflate = require('./zlib/deflate.js');
  17009. var utils = require('./utils/common');
  17010. var strings = require('./utils/strings');
  17011. var msg = require('./zlib/messages');
  17012. var zstream = require('./zlib/zstream');
  17013. var toString = Object.prototype.toString;
  17014. /* Public constants ==========================================================*/
  17015. /* ===========================================================================*/
  17016. var Z_NO_FLUSH = 0;
  17017. var Z_FINISH = 4;
  17018. var Z_OK = 0;
  17019. var Z_STREAM_END = 1;
  17020. var Z_DEFAULT_COMPRESSION = -1;
  17021. var Z_DEFAULT_STRATEGY = 0;
  17022. var Z_DEFLATED = 8;
  17023. /* ===========================================================================*/
  17024. /**
  17025. * class Deflate
  17026. *
  17027. * Generic JS-style wrapper for zlib calls. If you don't need
  17028. * streaming behaviour - use more simple functions: [[deflate]],
  17029. * [[deflateRaw]] and [[gzip]].
  17030. **/
  17031. /* internal
  17032. * Deflate.chunks -> Array
  17033. *
  17034. * Chunks of output data, if [[Deflate#onData]] not overriden.
  17035. **/
  17036. /**
  17037. * Deflate.result -> Uint8Array|Array
  17038. *
  17039. * Compressed result, generated by default [[Deflate#onData]]
  17040. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  17041. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  17042. **/
  17043. /**
  17044. * Deflate.err -> Number
  17045. *
  17046. * Error code after deflate finished. 0 (Z_OK) on success.
  17047. * You will not need it in real life, because deflate errors
  17048. * are possible only on wrong options or bad `onData` / `onEnd`
  17049. * custom handlers.
  17050. **/
  17051. /**
  17052. * Deflate.msg -> String
  17053. *
  17054. * Error message, if [[Deflate.err]] != 0
  17055. **/
  17056. /**
  17057. * new Deflate(options)
  17058. * - options (Object): zlib deflate options.
  17059. *
  17060. * Creates new deflator instance with specified params. Throws exception
  17061. * on bad params. Supported options:
  17062. *
  17063. * - `level`
  17064. * - `windowBits`
  17065. * - `memLevel`
  17066. * - `strategy`
  17067. *
  17068. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17069. * for more information on these.
  17070. *
  17071. * Additional options, for internal needs:
  17072. *
  17073. * - `chunkSize` - size of generated data chunks (16K by default)
  17074. * - `raw` (Boolean) - do raw deflate
  17075. * - `gzip` (Boolean) - create gzip wrapper
  17076. * - `to` (String) - if equal to 'string', then result will be "binary string"
  17077. * (each char code [0..255])
  17078. * - `header` (Object) - custom header for gzip
  17079. * - `text` (Boolean) - true if compressed data believed to be text
  17080. * - `time` (Number) - modification time, unix timestamp
  17081. * - `os` (Number) - operation system code
  17082. * - `extra` (Array) - array of bytes with extra data (max 65536)
  17083. * - `name` (String) - file name (binary string)
  17084. * - `comment` (String) - comment (binary string)
  17085. * - `hcrc` (Boolean) - true if header crc should be added
  17086. *
  17087. * ##### Example:
  17088. *
  17089. * ```javascript
  17090. * var pako = require('pako')
  17091. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17092. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17093. *
  17094. * var deflate = new pako.Deflate({ level: 3});
  17095. *
  17096. * deflate.push(chunk1, false);
  17097. * deflate.push(chunk2, true); // true -> last chunk
  17098. *
  17099. * if (deflate.err) { throw new Error(deflate.err); }
  17100. *
  17101. * console.log(deflate.result);
  17102. * ```
  17103. **/
  17104. var Deflate = function(options) {
  17105. this.options = utils.assign({
  17106. level: Z_DEFAULT_COMPRESSION,
  17107. method: Z_DEFLATED,
  17108. chunkSize: 16384,
  17109. windowBits: 15,
  17110. memLevel: 8,
  17111. strategy: Z_DEFAULT_STRATEGY,
  17112. to: ''
  17113. }, options || {});
  17114. var opt = this.options;
  17115. if (opt.raw && (opt.windowBits > 0)) {
  17116. opt.windowBits = -opt.windowBits;
  17117. }
  17118. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  17119. opt.windowBits += 16;
  17120. }
  17121. this.err = 0; // error code, if happens (0 = Z_OK)
  17122. this.msg = ''; // error message
  17123. this.ended = false; // used to avoid multiple onEnd() calls
  17124. this.chunks = []; // chunks of compressed data
  17125. this.strm = new zstream();
  17126. this.strm.avail_out = 0;
  17127. var status = zlib_deflate.deflateInit2(
  17128. this.strm,
  17129. opt.level,
  17130. opt.method,
  17131. opt.windowBits,
  17132. opt.memLevel,
  17133. opt.strategy
  17134. );
  17135. if (status !== Z_OK) {
  17136. throw new Error(msg[status]);
  17137. }
  17138. if (opt.header) {
  17139. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  17140. }
  17141. };
  17142. /**
  17143. * Deflate#push(data[, mode]) -> Boolean
  17144. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  17145. * converted to utf8 byte sequence.
  17146. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17147. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17148. *
  17149. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  17150. * new compressed chunks. Returns `true` on success. The last data block must have
  17151. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17152. * [[Deflate#onEnd]].
  17153. *
  17154. * On fail call [[Deflate#onEnd]] with error code and return false.
  17155. *
  17156. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17157. * array format is detected automatically). Also, don't skip last param and always
  17158. * use the same type in your code (boolean or number). That will improve JS speed.
  17159. *
  17160. * For regular `Array`-s make sure all elements are [0..255].
  17161. *
  17162. * ##### Example
  17163. *
  17164. * ```javascript
  17165. * push(chunk, false); // push one of data chunks
  17166. * ...
  17167. * push(chunk, true); // push last chunk
  17168. * ```
  17169. **/
  17170. Deflate.prototype.push = function(data, mode) {
  17171. var strm = this.strm;
  17172. var chunkSize = this.options.chunkSize;
  17173. var status, _mode;
  17174. if (this.ended) { return false; }
  17175. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  17176. // Convert data if needed
  17177. if (typeof data === 'string') {
  17178. // If we need to compress text, change encoding to utf8.
  17179. strm.input = strings.string2buf(data);
  17180. } else if (toString.call(data) === '[object ArrayBuffer]') {
  17181. strm.input = new Uint8Array(data);
  17182. } else {
  17183. strm.input = data;
  17184. }
  17185. strm.next_in = 0;
  17186. strm.avail_in = strm.input.length;
  17187. do {
  17188. if (strm.avail_out === 0) {
  17189. strm.output = new utils.Buf8(chunkSize);
  17190. strm.next_out = 0;
  17191. strm.avail_out = chunkSize;
  17192. }
  17193. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  17194. if (status !== Z_STREAM_END && status !== Z_OK) {
  17195. this.onEnd(status);
  17196. this.ended = true;
  17197. return false;
  17198. }
  17199. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  17200. if (this.options.to === 'string') {
  17201. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  17202. } else {
  17203. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17204. }
  17205. }
  17206. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  17207. // Finalize on the last chunk.
  17208. if (_mode === Z_FINISH) {
  17209. status = zlib_deflate.deflateEnd(this.strm);
  17210. this.onEnd(status);
  17211. this.ended = true;
  17212. return status === Z_OK;
  17213. }
  17214. return true;
  17215. };
  17216. /**
  17217. * Deflate#onData(chunk) -> Void
  17218. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17219. * on js engine support. When string output requested, each chunk
  17220. * will be string.
  17221. *
  17222. * By default, stores data blocks in `chunks[]` property and glue
  17223. * those in `onEnd`. Override this handler, if you need another behaviour.
  17224. **/
  17225. Deflate.prototype.onData = function(chunk) {
  17226. this.chunks.push(chunk);
  17227. };
  17228. /**
  17229. * Deflate#onEnd(status) -> Void
  17230. * - status (Number): deflate status. 0 (Z_OK) on success,
  17231. * other if not.
  17232. *
  17233. * Called once after you tell deflate that input stream complete
  17234. * or error happenned. By default - join collected chunks,
  17235. * free memory and fill `results` / `err` properties.
  17236. **/
  17237. Deflate.prototype.onEnd = function(status) {
  17238. // On success - join
  17239. if (status === Z_OK) {
  17240. if (this.options.to === 'string') {
  17241. this.result = this.chunks.join('');
  17242. } else {
  17243. this.result = utils.flattenChunks(this.chunks);
  17244. }
  17245. }
  17246. this.chunks = [];
  17247. this.err = status;
  17248. this.msg = this.strm.msg;
  17249. };
  17250. /**
  17251. * deflate(data[, options]) -> Uint8Array|Array|String
  17252. * - data (Uint8Array|Array|String): input data to compress.
  17253. * - options (Object): zlib deflate options.
  17254. *
  17255. * Compress `data` with deflate alrorythm and `options`.
  17256. *
  17257. * Supported options are:
  17258. *
  17259. * - level
  17260. * - windowBits
  17261. * - memLevel
  17262. * - strategy
  17263. *
  17264. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17265. * for more information on these.
  17266. *
  17267. * Sugar (options):
  17268. *
  17269. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17270. * negative windowBits implicitly.
  17271. * - `to` (String) - if equal to 'string', then result will be "binary string"
  17272. * (each char code [0..255])
  17273. *
  17274. * ##### Example:
  17275. *
  17276. * ```javascript
  17277. * var pako = require('pako')
  17278. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  17279. *
  17280. * console.log(pako.deflate(data));
  17281. * ```
  17282. **/
  17283. function deflate(input, options) {
  17284. var deflator = new Deflate(options);
  17285. deflator.push(input, true);
  17286. // That will never happens, if you don't cheat with options :)
  17287. if (deflator.err) { throw deflator.msg; }
  17288. return deflator.result;
  17289. }
  17290. /**
  17291. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  17292. * - data (Uint8Array|Array|String): input data to compress.
  17293. * - options (Object): zlib deflate options.
  17294. *
  17295. * The same as [[deflate]], but creates raw data, without wrapper
  17296. * (header and adler32 crc).
  17297. **/
  17298. function deflateRaw(input, options) {
  17299. options = options || {};
  17300. options.raw = true;
  17301. return deflate(input, options);
  17302. }
  17303. /**
  17304. * gzip(data[, options]) -> Uint8Array|Array|String
  17305. * - data (Uint8Array|Array|String): input data to compress.
  17306. * - options (Object): zlib deflate options.
  17307. *
  17308. * The same as [[deflate]], but create gzip wrapper instead of
  17309. * deflate one.
  17310. **/
  17311. function gzip(input, options) {
  17312. options = options || {};
  17313. options.gzip = true;
  17314. return deflate(input, options);
  17315. }
  17316. exports.Deflate = Deflate;
  17317. exports.deflate = deflate;
  17318. exports.deflateRaw = deflateRaw;
  17319. exports.gzip = gzip;
  17320. },{"./utils/common":66,"./utils/strings":67,"./zlib/deflate.js":71,"./zlib/messages":76,"./zlib/zstream":78}],65:[function(require,module,exports){
  17321. 'use strict';
  17322. var zlib_inflate = require('./zlib/inflate.js');
  17323. var utils = require('./utils/common');
  17324. var strings = require('./utils/strings');
  17325. var c = require('./zlib/constants');
  17326. var msg = require('./zlib/messages');
  17327. var zstream = require('./zlib/zstream');
  17328. var gzheader = require('./zlib/gzheader');
  17329. var toString = Object.prototype.toString;
  17330. /**
  17331. * class Inflate
  17332. *
  17333. * Generic JS-style wrapper for zlib calls. If you don't need
  17334. * streaming behaviour - use more simple functions: [[inflate]]
  17335. * and [[inflateRaw]].
  17336. **/
  17337. /* internal
  17338. * inflate.chunks -> Array
  17339. *
  17340. * Chunks of output data, if [[Inflate#onData]] not overriden.
  17341. **/
  17342. /**
  17343. * Inflate.result -> Uint8Array|Array|String
  17344. *
  17345. * Uncompressed result, generated by default [[Inflate#onData]]
  17346. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  17347. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  17348. **/
  17349. /**
  17350. * Inflate.err -> Number
  17351. *
  17352. * Error code after inflate finished. 0 (Z_OK) on success.
  17353. * Should be checked if broken data possible.
  17354. **/
  17355. /**
  17356. * Inflate.msg -> String
  17357. *
  17358. * Error message, if [[Inflate.err]] != 0
  17359. **/
  17360. /**
  17361. * new Inflate(options)
  17362. * - options (Object): zlib inflate options.
  17363. *
  17364. * Creates new inflator instance with specified params. Throws exception
  17365. * on bad params. Supported options:
  17366. *
  17367. * - `windowBits`
  17368. *
  17369. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17370. * for more information on these.
  17371. *
  17372. * Additional options, for internal needs:
  17373. *
  17374. * - `chunkSize` - size of generated data chunks (16K by default)
  17375. * - `raw` (Boolean) - do raw inflate
  17376. * - `to` (String) - if equal to 'string', then result will be converted
  17377. * from utf8 to utf16 (javascript) string. When string output requested,
  17378. * chunk length can differ from `chunkSize`, depending on content.
  17379. *
  17380. * By default, when no options set, autodetect deflate/gzip data format via
  17381. * wrapper header.
  17382. *
  17383. * ##### Example:
  17384. *
  17385. * ```javascript
  17386. * var pako = require('pako')
  17387. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17388. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17389. *
  17390. * var inflate = new pako.Inflate({ level: 3});
  17391. *
  17392. * inflate.push(chunk1, false);
  17393. * inflate.push(chunk2, true); // true -> last chunk
  17394. *
  17395. * if (inflate.err) { throw new Error(inflate.err); }
  17396. *
  17397. * console.log(inflate.result);
  17398. * ```
  17399. **/
  17400. var Inflate = function(options) {
  17401. this.options = utils.assign({
  17402. chunkSize: 16384,
  17403. windowBits: 0,
  17404. to: ''
  17405. }, options || {});
  17406. var opt = this.options;
  17407. // Force window size for `raw` data, if not set directly,
  17408. // because we have no header for autodetect.
  17409. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  17410. opt.windowBits = -opt.windowBits;
  17411. if (opt.windowBits === 0) { opt.windowBits = -15; }
  17412. }
  17413. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  17414. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  17415. !(options && options.windowBits)) {
  17416. opt.windowBits += 32;
  17417. }
  17418. // Gzip header has no info about windows size, we can do autodetect only
  17419. // for deflate. So, if window size not set, force it to max when gzip possible
  17420. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  17421. // bit 3 (16) -> gzipped data
  17422. // bit 4 (32) -> autodetect gzip/deflate
  17423. if ((opt.windowBits & 15) === 0) {
  17424. opt.windowBits |= 15;
  17425. }
  17426. }
  17427. this.err = 0; // error code, if happens (0 = Z_OK)
  17428. this.msg = ''; // error message
  17429. this.ended = false; // used to avoid multiple onEnd() calls
  17430. this.chunks = []; // chunks of compressed data
  17431. this.strm = new zstream();
  17432. this.strm.avail_out = 0;
  17433. var status = zlib_inflate.inflateInit2(
  17434. this.strm,
  17435. opt.windowBits
  17436. );
  17437. if (status !== c.Z_OK) {
  17438. throw new Error(msg[status]);
  17439. }
  17440. this.header = new gzheader();
  17441. zlib_inflate.inflateGetHeader(this.strm, this.header);
  17442. };
  17443. /**
  17444. * Inflate#push(data[, mode]) -> Boolean
  17445. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  17446. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17447. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17448. *
  17449. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  17450. * new output chunks. Returns `true` on success. The last data block must have
  17451. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17452. * [[Inflate#onEnd]].
  17453. *
  17454. * On fail call [[Inflate#onEnd]] with error code and return false.
  17455. *
  17456. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17457. * format is detected automatically). Also, don't skip last param and always
  17458. * use the same type in your code (boolean or number). That will improve JS speed.
  17459. *
  17460. * For regular `Array`-s make sure all elements are [0..255].
  17461. *
  17462. * ##### Example
  17463. *
  17464. * ```javascript
  17465. * push(chunk, false); // push one of data chunks
  17466. * ...
  17467. * push(chunk, true); // push last chunk
  17468. * ```
  17469. **/
  17470. Inflate.prototype.push = function(data, mode) {
  17471. var strm = this.strm;
  17472. var chunkSize = this.options.chunkSize;
  17473. var status, _mode;
  17474. var next_out_utf8, tail, utf8str;
  17475. if (this.ended) { return false; }
  17476. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  17477. // Convert data if needed
  17478. if (typeof data === 'string') {
  17479. // Only binary strings can be decompressed on practice
  17480. strm.input = strings.binstring2buf(data);
  17481. } else if (toString.call(data) === '[object ArrayBuffer]') {
  17482. strm.input = new Uint8Array(data);
  17483. } else {
  17484. strm.input = data;
  17485. }
  17486. strm.next_in = 0;
  17487. strm.avail_in = strm.input.length;
  17488. do {
  17489. if (strm.avail_out === 0) {
  17490. strm.output = new utils.Buf8(chunkSize);
  17491. strm.next_out = 0;
  17492. strm.avail_out = chunkSize;
  17493. }
  17494. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  17495. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  17496. this.onEnd(status);
  17497. this.ended = true;
  17498. return false;
  17499. }
  17500. if (strm.next_out) {
  17501. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  17502. if (this.options.to === 'string') {
  17503. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  17504. tail = strm.next_out - next_out_utf8;
  17505. utf8str = strings.buf2string(strm.output, next_out_utf8);
  17506. // move tail
  17507. strm.next_out = tail;
  17508. strm.avail_out = chunkSize - tail;
  17509. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  17510. this.onData(utf8str);
  17511. } else {
  17512. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17513. }
  17514. }
  17515. }
  17516. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  17517. if (status === c.Z_STREAM_END) {
  17518. _mode = c.Z_FINISH;
  17519. }
  17520. // Finalize on the last chunk.
  17521. if (_mode === c.Z_FINISH) {
  17522. status = zlib_inflate.inflateEnd(this.strm);
  17523. this.onEnd(status);
  17524. this.ended = true;
  17525. return status === c.Z_OK;
  17526. }
  17527. return true;
  17528. };
  17529. /**
  17530. * Inflate#onData(chunk) -> Void
  17531. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17532. * on js engine support. When string output requested, each chunk
  17533. * will be string.
  17534. *
  17535. * By default, stores data blocks in `chunks[]` property and glue
  17536. * those in `onEnd`. Override this handler, if you need another behaviour.
  17537. **/
  17538. Inflate.prototype.onData = function(chunk) {
  17539. this.chunks.push(chunk);
  17540. };
  17541. /**
  17542. * Inflate#onEnd(status) -> Void
  17543. * - status (Number): inflate status. 0 (Z_OK) on success,
  17544. * other if not.
  17545. *
  17546. * Called once after you tell inflate that input stream complete
  17547. * or error happenned. By default - join collected chunks,
  17548. * free memory and fill `results` / `err` properties.
  17549. **/
  17550. Inflate.prototype.onEnd = function(status) {
  17551. // On success - join
  17552. if (status === c.Z_OK) {
  17553. if (this.options.to === 'string') {
  17554. // Glue & convert here, until we teach pako to send
  17555. // utf8 alligned strings to onData
  17556. this.result = this.chunks.join('');
  17557. } else {
  17558. this.result = utils.flattenChunks(this.chunks);
  17559. }
  17560. }
  17561. this.chunks = [];
  17562. this.err = status;
  17563. this.msg = this.strm.msg;
  17564. };
  17565. /**
  17566. * inflate(data[, options]) -> Uint8Array|Array|String
  17567. * - data (Uint8Array|Array|String): input data to decompress.
  17568. * - options (Object): zlib inflate options.
  17569. *
  17570. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  17571. * format via wrapper header by default. That's why we don't provide
  17572. * separate `ungzip` method.
  17573. *
  17574. * Supported options are:
  17575. *
  17576. * - windowBits
  17577. *
  17578. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17579. * for more information.
  17580. *
  17581. * Sugar (options):
  17582. *
  17583. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17584. * negative windowBits implicitly.
  17585. * - `to` (String) - if equal to 'string', then result will be converted
  17586. * from utf8 to utf16 (javascript) string. When string output requested,
  17587. * chunk length can differ from `chunkSize`, depending on content.
  17588. *
  17589. *
  17590. * ##### Example:
  17591. *
  17592. * ```javascript
  17593. * var pako = require('pako')
  17594. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  17595. * , output;
  17596. *
  17597. * try {
  17598. * output = pako.inflate(input);
  17599. * } catch (err)
  17600. * console.log(err);
  17601. * }
  17602. * ```
  17603. **/
  17604. function inflate(input, options) {
  17605. var inflator = new Inflate(options);
  17606. inflator.push(input, true);
  17607. // That will never happens, if you don't cheat with options :)
  17608. if (inflator.err) { throw inflator.msg; }
  17609. return inflator.result;
  17610. }
  17611. /**
  17612. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  17613. * - data (Uint8Array|Array|String): input data to decompress.
  17614. * - options (Object): zlib inflate options.
  17615. *
  17616. * The same as [[inflate]], but creates raw data, without wrapper
  17617. * (header and adler32 crc).
  17618. **/
  17619. function inflateRaw(input, options) {
  17620. options = options || {};
  17621. options.raw = true;
  17622. return inflate(input, options);
  17623. }
  17624. /**
  17625. * ungzip(data[, options]) -> Uint8Array|Array|String
  17626. * - data (Uint8Array|Array|String): input data to decompress.
  17627. * - options (Object): zlib inflate options.
  17628. *
  17629. * Just shortcut to [[inflate]], because it autodetects format
  17630. * by header.content. Done for convenience.
  17631. **/
  17632. exports.Inflate = Inflate;
  17633. exports.inflate = inflate;
  17634. exports.inflateRaw = inflateRaw;
  17635. exports.ungzip = inflate;
  17636. },{"./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){
  17637. 'use strict';
  17638. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  17639. (typeof Uint16Array !== 'undefined') &&
  17640. (typeof Int32Array !== 'undefined');
  17641. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  17642. var sources = Array.prototype.slice.call(arguments, 1);
  17643. while (sources.length) {
  17644. var source = sources.shift();
  17645. if (!source) { continue; }
  17646. if (typeof(source) !== 'object') {
  17647. throw new TypeError(source + 'must be non-object');
  17648. }
  17649. for (var p in source) {
  17650. if (source.hasOwnProperty(p)) {
  17651. obj[p] = source[p];
  17652. }
  17653. }
  17654. }
  17655. return obj;
  17656. };
  17657. // reduce buffer size, avoiding mem copy
  17658. exports.shrinkBuf = function (buf, size) {
  17659. if (buf.length === size) { return buf; }
  17660. if (buf.subarray) { return buf.subarray(0, size); }
  17661. buf.length = size;
  17662. return buf;
  17663. };
  17664. var fnTyped = {
  17665. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17666. if (src.subarray && dest.subarray) {
  17667. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  17668. return;
  17669. }
  17670. // Fallback to ordinary array
  17671. for(var i=0; i<len; i++) {
  17672. dest[dest_offs + i] = src[src_offs + i];
  17673. }
  17674. },
  17675. // Join array of chunks to single array.
  17676. flattenChunks: function(chunks) {
  17677. var i, l, len, pos, chunk, result;
  17678. // calculate data length
  17679. len = 0;
  17680. for (i=0, l=chunks.length; i<l; i++) {
  17681. len += chunks[i].length;
  17682. }
  17683. // join chunks
  17684. result = new Uint8Array(len);
  17685. pos = 0;
  17686. for (i=0, l=chunks.length; i<l; i++) {
  17687. chunk = chunks[i];
  17688. result.set(chunk, pos);
  17689. pos += chunk.length;
  17690. }
  17691. return result;
  17692. }
  17693. };
  17694. var fnUntyped = {
  17695. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17696. for(var i=0; i<len; i++) {
  17697. dest[dest_offs + i] = src[src_offs + i];
  17698. }
  17699. },
  17700. // Join array of chunks to single array.
  17701. flattenChunks: function(chunks) {
  17702. return [].concat.apply([], chunks);
  17703. }
  17704. };
  17705. // Enable/Disable typed arrays use, for testing
  17706. //
  17707. exports.setTyped = function (on) {
  17708. if (on) {
  17709. exports.Buf8 = Uint8Array;
  17710. exports.Buf16 = Uint16Array;
  17711. exports.Buf32 = Int32Array;
  17712. exports.assign(exports, fnTyped);
  17713. } else {
  17714. exports.Buf8 = Array;
  17715. exports.Buf16 = Array;
  17716. exports.Buf32 = Array;
  17717. exports.assign(exports, fnUntyped);
  17718. }
  17719. };
  17720. exports.setTyped(TYPED_OK);
  17721. },{}],67:[function(require,module,exports){
  17722. // String encode/decode helpers
  17723. 'use strict';
  17724. var utils = require('./common');
  17725. // Quick check if we can use fast array to bin string conversion
  17726. //
  17727. // - apply(Array) can fail on Android 2.2
  17728. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  17729. //
  17730. var STR_APPLY_OK = true;
  17731. var STR_APPLY_UIA_OK = true;
  17732. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  17733. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  17734. // Table with utf8 lengths (calculated by first byte of sequence)
  17735. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  17736. // because max possible codepoint is 0x10ffff
  17737. var _utf8len = new utils.Buf8(256);
  17738. for (var i=0; i<256; i++) {
  17739. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  17740. }
  17741. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  17742. // convert string to array (typed, when possible)
  17743. exports.string2buf = function (str) {
  17744. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  17745. // count binary size
  17746. for (m_pos = 0; m_pos < str_len; m_pos++) {
  17747. c = str.charCodeAt(m_pos);
  17748. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17749. c2 = str.charCodeAt(m_pos+1);
  17750. if ((c2 & 0xfc00) === 0xdc00) {
  17751. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17752. m_pos++;
  17753. }
  17754. }
  17755. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  17756. }
  17757. // allocate buffer
  17758. buf = new utils.Buf8(buf_len);
  17759. // convert
  17760. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  17761. c = str.charCodeAt(m_pos);
  17762. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17763. c2 = str.charCodeAt(m_pos+1);
  17764. if ((c2 & 0xfc00) === 0xdc00) {
  17765. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17766. m_pos++;
  17767. }
  17768. }
  17769. if (c < 0x80) {
  17770. /* one byte */
  17771. buf[i++] = c;
  17772. } else if (c < 0x800) {
  17773. /* two bytes */
  17774. buf[i++] = 0xC0 | (c >>> 6);
  17775. buf[i++] = 0x80 | (c & 0x3f);
  17776. } else if (c < 0x10000) {
  17777. /* three bytes */
  17778. buf[i++] = 0xE0 | (c >>> 12);
  17779. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17780. buf[i++] = 0x80 | (c & 0x3f);
  17781. } else {
  17782. /* four bytes */
  17783. buf[i++] = 0xf0 | (c >>> 18);
  17784. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  17785. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17786. buf[i++] = 0x80 | (c & 0x3f);
  17787. }
  17788. }
  17789. return buf;
  17790. };
  17791. // Helper (used in 2 places)
  17792. function buf2binstring(buf, len) {
  17793. // use fallback for big arrays to avoid stack overflow
  17794. if (len < 65537) {
  17795. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  17796. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  17797. }
  17798. }
  17799. var result = '';
  17800. for(var i=0; i < len; i++) {
  17801. result += String.fromCharCode(buf[i]);
  17802. }
  17803. return result;
  17804. }
  17805. // Convert byte array to binary string
  17806. exports.buf2binstring = function(buf) {
  17807. return buf2binstring(buf, buf.length);
  17808. };
  17809. // Convert binary string (typed, when possible)
  17810. exports.binstring2buf = function(str) {
  17811. var buf = new utils.Buf8(str.length);
  17812. for(var i=0, len=buf.length; i < len; i++) {
  17813. buf[i] = str.charCodeAt(i);
  17814. }
  17815. return buf;
  17816. };
  17817. // convert array to string
  17818. exports.buf2string = function (buf, max) {
  17819. var i, out, c, c_len;
  17820. var len = max || buf.length;
  17821. // Reserve max possible length (2 words per char)
  17822. // NB: by unknown reasons, Array is significantly faster for
  17823. // String.fromCharCode.apply than Uint16Array.
  17824. var utf16buf = new Array(len*2);
  17825. for (out=0, i=0; i<len;) {
  17826. c = buf[i++];
  17827. // quick process ascii
  17828. if (c < 0x80) { utf16buf[out++] = c; continue; }
  17829. c_len = _utf8len[c];
  17830. // skip 5 & 6 byte codes
  17831. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  17832. // apply mask on first byte
  17833. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  17834. // join the rest
  17835. while (c_len > 1 && i < len) {
  17836. c = (c << 6) | (buf[i++] & 0x3f);
  17837. c_len--;
  17838. }
  17839. // terminated by end of string?
  17840. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  17841. if (c < 0x10000) {
  17842. utf16buf[out++] = c;
  17843. } else {
  17844. c -= 0x10000;
  17845. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  17846. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  17847. }
  17848. }
  17849. return buf2binstring(utf16buf, out);
  17850. };
  17851. // Calculate max possible position in utf8 buffer,
  17852. // that will not break sequence. If that's not possible
  17853. // - (very small limits) return max size as is.
  17854. //
  17855. // buf[] - utf8 bytes array
  17856. // max - length limit (mandatory);
  17857. exports.utf8border = function(buf, max) {
  17858. var pos;
  17859. max = max || buf.length;
  17860. if (max > buf.length) { max = buf.length; }
  17861. // go back from last position, until start of sequence found
  17862. pos = max-1;
  17863. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  17864. // Fuckup - very small and broken sequence,
  17865. // return max, because we should return something anyway.
  17866. if (pos < 0) { return max; }
  17867. // If we came to start of buffer - that means vuffer is too small,
  17868. // return max too.
  17869. if (pos === 0) { return max; }
  17870. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  17871. };
  17872. },{"./common":66}],68:[function(require,module,exports){
  17873. 'use strict';
  17874. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  17875. // It doesn't worth to make additional optimizationa as in original.
  17876. // Small size is preferable.
  17877. function adler32(adler, buf, len, pos) {
  17878. var s1 = (adler & 0xffff) |0
  17879. , s2 = ((adler >>> 16) & 0xffff) |0
  17880. , n = 0;
  17881. while (len !== 0) {
  17882. // Set limit ~ twice less than 5552, to keep
  17883. // s2 in 31-bits, because we force signed ints.
  17884. // in other case %= will fail.
  17885. n = len > 2000 ? 2000 : len;
  17886. len -= n;
  17887. do {
  17888. s1 = (s1 + buf[pos++]) |0;
  17889. s2 = (s2 + s1) |0;
  17890. } while (--n);
  17891. s1 %= 65521;
  17892. s2 %= 65521;
  17893. }
  17894. return (s1 | (s2 << 16)) |0;
  17895. }
  17896. module.exports = adler32;
  17897. },{}],69:[function(require,module,exports){
  17898. module.exports = {
  17899. /* Allowed flush values; see deflate() and inflate() below for details */
  17900. Z_NO_FLUSH: 0,
  17901. Z_PARTIAL_FLUSH: 1,
  17902. Z_SYNC_FLUSH: 2,
  17903. Z_FULL_FLUSH: 3,
  17904. Z_FINISH: 4,
  17905. Z_BLOCK: 5,
  17906. Z_TREES: 6,
  17907. /* Return codes for the compression/decompression functions. Negative values
  17908. * are errors, positive values are used for special but normal events.
  17909. */
  17910. Z_OK: 0,
  17911. Z_STREAM_END: 1,
  17912. Z_NEED_DICT: 2,
  17913. Z_ERRNO: -1,
  17914. Z_STREAM_ERROR: -2,
  17915. Z_DATA_ERROR: -3,
  17916. //Z_MEM_ERROR: -4,
  17917. Z_BUF_ERROR: -5,
  17918. //Z_VERSION_ERROR: -6,
  17919. /* compression levels */
  17920. Z_NO_COMPRESSION: 0,
  17921. Z_BEST_SPEED: 1,
  17922. Z_BEST_COMPRESSION: 9,
  17923. Z_DEFAULT_COMPRESSION: -1,
  17924. Z_FILTERED: 1,
  17925. Z_HUFFMAN_ONLY: 2,
  17926. Z_RLE: 3,
  17927. Z_FIXED: 4,
  17928. Z_DEFAULT_STRATEGY: 0,
  17929. /* Possible values of the data_type field (though see inflate()) */
  17930. Z_BINARY: 0,
  17931. Z_TEXT: 1,
  17932. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  17933. Z_UNKNOWN: 2,
  17934. /* The deflate compression method */
  17935. Z_DEFLATED: 8
  17936. //Z_NULL: null // Use -1 or null inline, depending on var type
  17937. };
  17938. },{}],70:[function(require,module,exports){
  17939. 'use strict';
  17940. // Note: we can't get significant speed boost here.
  17941. // So write code to minimize size - no pregenerated tables
  17942. // and array tools dependencies.
  17943. // Use ordinary array, since untyped makes no boost here
  17944. function makeTable() {
  17945. var c, table = [];
  17946. for(var n =0; n < 256; n++){
  17947. c = n;
  17948. for(var k =0; k < 8; k++){
  17949. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  17950. }
  17951. table[n] = c;
  17952. }
  17953. return table;
  17954. }
  17955. // Create table on load. Just 255 signed longs. Not a problem.
  17956. var crcTable = makeTable();
  17957. function crc32(crc, buf, len, pos) {
  17958. var t = crcTable
  17959. , end = pos + len;
  17960. crc = crc ^ (-1);
  17961. for (var i = pos; i < end; i++ ) {
  17962. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  17963. }
  17964. return (crc ^ (-1)); // >>> 0;
  17965. }
  17966. module.exports = crc32;
  17967. },{}],71:[function(require,module,exports){
  17968. 'use strict';
  17969. var utils = require('../utils/common');
  17970. var trees = require('./trees');
  17971. var adler32 = require('./adler32');
  17972. var crc32 = require('./crc32');
  17973. var msg = require('./messages');
  17974. /* Public constants ==========================================================*/
  17975. /* ===========================================================================*/
  17976. /* Allowed flush values; see deflate() and inflate() below for details */
  17977. var Z_NO_FLUSH = 0;
  17978. var Z_PARTIAL_FLUSH = 1;
  17979. //var Z_SYNC_FLUSH = 2;
  17980. var Z_FULL_FLUSH = 3;
  17981. var Z_FINISH = 4;
  17982. var Z_BLOCK = 5;
  17983. //var Z_TREES = 6;
  17984. /* Return codes for the compression/decompression functions. Negative values
  17985. * are errors, positive values are used for special but normal events.
  17986. */
  17987. var Z_OK = 0;
  17988. var Z_STREAM_END = 1;
  17989. //var Z_NEED_DICT = 2;
  17990. //var Z_ERRNO = -1;
  17991. var Z_STREAM_ERROR = -2;
  17992. var Z_DATA_ERROR = -3;
  17993. //var Z_MEM_ERROR = -4;
  17994. var Z_BUF_ERROR = -5;
  17995. //var Z_VERSION_ERROR = -6;
  17996. /* compression levels */
  17997. //var Z_NO_COMPRESSION = 0;
  17998. //var Z_BEST_SPEED = 1;
  17999. //var Z_BEST_COMPRESSION = 9;
  18000. var Z_DEFAULT_COMPRESSION = -1;
  18001. var Z_FILTERED = 1;
  18002. var Z_HUFFMAN_ONLY = 2;
  18003. var Z_RLE = 3;
  18004. var Z_FIXED = 4;
  18005. var Z_DEFAULT_STRATEGY = 0;
  18006. /* Possible values of the data_type field (though see inflate()) */
  18007. //var Z_BINARY = 0;
  18008. //var Z_TEXT = 1;
  18009. //var Z_ASCII = 1; // = Z_TEXT
  18010. var Z_UNKNOWN = 2;
  18011. /* The deflate compression method */
  18012. var Z_DEFLATED = 8;
  18013. /*============================================================================*/
  18014. var MAX_MEM_LEVEL = 9;
  18015. /* Maximum value for memLevel in deflateInit2 */
  18016. var MAX_WBITS = 15;
  18017. /* 32K LZ77 window */
  18018. var DEF_MEM_LEVEL = 8;
  18019. var LENGTH_CODES = 29;
  18020. /* number of length codes, not counting the special END_BLOCK code */
  18021. var LITERALS = 256;
  18022. /* number of literal bytes 0..255 */
  18023. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  18024. /* number of Literal or Length codes, including the END_BLOCK code */
  18025. var D_CODES = 30;
  18026. /* number of distance codes */
  18027. var BL_CODES = 19;
  18028. /* number of codes used to transfer the bit lengths */
  18029. var HEAP_SIZE = 2*L_CODES + 1;
  18030. /* maximum heap size */
  18031. var MAX_BITS = 15;
  18032. /* All codes must not exceed MAX_BITS bits */
  18033. var MIN_MATCH = 3;
  18034. var MAX_MATCH = 258;
  18035. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  18036. var PRESET_DICT = 0x20;
  18037. var INIT_STATE = 42;
  18038. var EXTRA_STATE = 69;
  18039. var NAME_STATE = 73;
  18040. var COMMENT_STATE = 91;
  18041. var HCRC_STATE = 103;
  18042. var BUSY_STATE = 113;
  18043. var FINISH_STATE = 666;
  18044. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  18045. var BS_BLOCK_DONE = 2; /* block flush performed */
  18046. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  18047. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  18048. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  18049. function err(strm, errorCode) {
  18050. strm.msg = msg[errorCode];
  18051. return errorCode;
  18052. }
  18053. function rank(f) {
  18054. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  18055. }
  18056. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  18057. /* =========================================================================
  18058. * Flush as much pending output as possible. All deflate() output goes
  18059. * through this function so some applications may wish to modify it
  18060. * to avoid allocating a large strm->output buffer and copying into it.
  18061. * (See also read_buf()).
  18062. */
  18063. function flush_pending(strm) {
  18064. var s = strm.state;
  18065. //_tr_flush_bits(s);
  18066. var len = s.pending;
  18067. if (len > strm.avail_out) {
  18068. len = strm.avail_out;
  18069. }
  18070. if (len === 0) { return; }
  18071. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  18072. strm.next_out += len;
  18073. s.pending_out += len;
  18074. strm.total_out += len;
  18075. strm.avail_out -= len;
  18076. s.pending -= len;
  18077. if (s.pending === 0) {
  18078. s.pending_out = 0;
  18079. }
  18080. }
  18081. function flush_block_only (s, last) {
  18082. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  18083. s.block_start = s.strstart;
  18084. flush_pending(s.strm);
  18085. }
  18086. function put_byte(s, b) {
  18087. s.pending_buf[s.pending++] = b;
  18088. }
  18089. /* =========================================================================
  18090. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  18091. * IN assertion: the stream state is correct and there is enough room in
  18092. * pending_buf.
  18093. */
  18094. function putShortMSB(s, b) {
  18095. // put_byte(s, (Byte)(b >> 8));
  18096. // put_byte(s, (Byte)(b & 0xff));
  18097. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  18098. s.pending_buf[s.pending++] = b & 0xff;
  18099. }
  18100. /* ===========================================================================
  18101. * Read a new buffer from the current input stream, update the adler32
  18102. * and total number of bytes read. All deflate() input goes through
  18103. * this function so some applications may wish to modify it to avoid
  18104. * allocating a large strm->input buffer and copying from it.
  18105. * (See also flush_pending()).
  18106. */
  18107. function read_buf(strm, buf, start, size) {
  18108. var len = strm.avail_in;
  18109. if (len > size) { len = size; }
  18110. if (len === 0) { return 0; }
  18111. strm.avail_in -= len;
  18112. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  18113. if (strm.state.wrap === 1) {
  18114. strm.adler = adler32(strm.adler, buf, len, start);
  18115. }
  18116. else if (strm.state.wrap === 2) {
  18117. strm.adler = crc32(strm.adler, buf, len, start);
  18118. }
  18119. strm.next_in += len;
  18120. strm.total_in += len;
  18121. return len;
  18122. }
  18123. /* ===========================================================================
  18124. * Set match_start to the longest match starting at the given string and
  18125. * return its length. Matches shorter or equal to prev_length are discarded,
  18126. * in which case the result is equal to prev_length and match_start is
  18127. * garbage.
  18128. * IN assertions: cur_match is the head of the hash chain for the current
  18129. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  18130. * OUT assertion: the match length is not greater than s->lookahead.
  18131. */
  18132. function longest_match(s, cur_match) {
  18133. var chain_length = s.max_chain_length; /* max hash chain length */
  18134. var scan = s.strstart; /* current string */
  18135. var match; /* matched string */
  18136. var len; /* length of current match */
  18137. var best_len = s.prev_length; /* best match length so far */
  18138. var nice_match = s.nice_match; /* stop if match long enough */
  18139. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  18140. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  18141. var _win = s.window; // shortcut
  18142. var wmask = s.w_mask;
  18143. var prev = s.prev;
  18144. /* Stop when cur_match becomes <= limit. To simplify the code,
  18145. * we prevent matches with the string of window index 0.
  18146. */
  18147. var strend = s.strstart + MAX_MATCH;
  18148. var scan_end1 = _win[scan + best_len - 1];
  18149. var scan_end = _win[scan + best_len];
  18150. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  18151. * It is easy to get rid of this optimization if necessary.
  18152. */
  18153. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  18154. /* Do not waste too much time if we already have a good match: */
  18155. if (s.prev_length >= s.good_match) {
  18156. chain_length >>= 2;
  18157. }
  18158. /* Do not look for matches beyond the end of the input. This is necessary
  18159. * to make deflate deterministic.
  18160. */
  18161. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  18162. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  18163. do {
  18164. // Assert(cur_match < s->strstart, "no future");
  18165. match = cur_match;
  18166. /* Skip to next match if the match length cannot increase
  18167. * or if the match length is less than 2. Note that the checks below
  18168. * for insufficient lookahead only occur occasionally for performance
  18169. * reasons. Therefore uninitialized memory will be accessed, and
  18170. * conditional jumps will be made that depend on those values.
  18171. * However the length of the match is limited to the lookahead, so
  18172. * the output of deflate is not affected by the uninitialized values.
  18173. */
  18174. if (_win[match + best_len] !== scan_end ||
  18175. _win[match + best_len - 1] !== scan_end1 ||
  18176. _win[match] !== _win[scan] ||
  18177. _win[++match] !== _win[scan + 1]) {
  18178. continue;
  18179. }
  18180. /* The check at best_len-1 can be removed because it will be made
  18181. * again later. (This heuristic is not always a win.)
  18182. * It is not necessary to compare scan[2] and match[2] since they
  18183. * are always equal when the other bytes match, given that
  18184. * the hash keys are equal and that HASH_BITS >= 8.
  18185. */
  18186. scan += 2;
  18187. match++;
  18188. // Assert(*scan == *match, "match[2]?");
  18189. /* We check for insufficient lookahead only every 8th comparison;
  18190. * the 256th check will be made at strstart+258.
  18191. */
  18192. do {
  18193. /*jshint noempty:false*/
  18194. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18195. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18196. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18197. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18198. scan < strend);
  18199. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  18200. len = MAX_MATCH - (strend - scan);
  18201. scan = strend - MAX_MATCH;
  18202. if (len > best_len) {
  18203. s.match_start = cur_match;
  18204. best_len = len;
  18205. if (len >= nice_match) {
  18206. break;
  18207. }
  18208. scan_end1 = _win[scan + best_len - 1];
  18209. scan_end = _win[scan + best_len];
  18210. }
  18211. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  18212. if (best_len <= s.lookahead) {
  18213. return best_len;
  18214. }
  18215. return s.lookahead;
  18216. }
  18217. /* ===========================================================================
  18218. * Fill the window when the lookahead becomes insufficient.
  18219. * Updates strstart and lookahead.
  18220. *
  18221. * IN assertion: lookahead < MIN_LOOKAHEAD
  18222. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  18223. * At least one byte has been read, or avail_in == 0; reads are
  18224. * performed for at least two bytes (required for the zip translate_eol
  18225. * option -- not supported here).
  18226. */
  18227. function fill_window(s) {
  18228. var _w_size = s.w_size;
  18229. var p, n, m, more, str;
  18230. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  18231. do {
  18232. more = s.window_size - s.lookahead - s.strstart;
  18233. // JS ints have 32 bit, block below not needed
  18234. /* Deal with !@#$% 64K limit: */
  18235. //if (sizeof(int) <= 2) {
  18236. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  18237. // more = wsize;
  18238. //
  18239. // } else if (more == (unsigned)(-1)) {
  18240. // /* Very unlikely, but possible on 16 bit machine if
  18241. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  18242. // */
  18243. // more--;
  18244. // }
  18245. //}
  18246. /* If the window is almost full and there is insufficient lookahead,
  18247. * move the upper half to the lower one to make room in the upper half.
  18248. */
  18249. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  18250. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  18251. s.match_start -= _w_size;
  18252. s.strstart -= _w_size;
  18253. /* we now have strstart >= MAX_DIST */
  18254. s.block_start -= _w_size;
  18255. /* Slide the hash table (could be avoided with 32 bit values
  18256. at the expense of memory usage). We slide even when level == 0
  18257. to keep the hash table consistent if we switch back to level > 0
  18258. later. (Using level 0 permanently is not an optimal usage of
  18259. zlib, so we don't care about this pathological case.)
  18260. */
  18261. n = s.hash_size;
  18262. p = n;
  18263. do {
  18264. m = s.head[--p];
  18265. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  18266. } while (--n);
  18267. n = _w_size;
  18268. p = n;
  18269. do {
  18270. m = s.prev[--p];
  18271. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  18272. /* If n is not on any hash chain, prev[n] is garbage but
  18273. * its value will never be used.
  18274. */
  18275. } while (--n);
  18276. more += _w_size;
  18277. }
  18278. if (s.strm.avail_in === 0) {
  18279. break;
  18280. }
  18281. /* If there was no sliding:
  18282. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  18283. * more == window_size - lookahead - strstart
  18284. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  18285. * => more >= window_size - 2*WSIZE + 2
  18286. * In the BIG_MEM or MMAP case (not yet supported),
  18287. * window_size == input_size + MIN_LOOKAHEAD &&
  18288. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  18289. * Otherwise, window_size == 2*WSIZE so more >= 2.
  18290. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  18291. */
  18292. //Assert(more >= 2, "more < 2");
  18293. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  18294. s.lookahead += n;
  18295. /* Initialize the hash value now that we have some input: */
  18296. if (s.lookahead + s.insert >= MIN_MATCH) {
  18297. str = s.strstart - s.insert;
  18298. s.ins_h = s.window[str];
  18299. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  18300. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  18301. //#if MIN_MATCH != 3
  18302. // Call update_hash() MIN_MATCH-3 more times
  18303. //#endif
  18304. while (s.insert) {
  18305. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  18306. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  18307. s.prev[str & s.w_mask] = s.head[s.ins_h];
  18308. s.head[s.ins_h] = str;
  18309. str++;
  18310. s.insert--;
  18311. if (s.lookahead + s.insert < MIN_MATCH) {
  18312. break;
  18313. }
  18314. }
  18315. }
  18316. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  18317. * but this is not important since only literal bytes will be emitted.
  18318. */
  18319. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  18320. /* If the WIN_INIT bytes after the end of the current data have never been
  18321. * written, then zero those bytes in order to avoid memory check reports of
  18322. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  18323. * the longest match routines. Update the high water mark for the next
  18324. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  18325. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  18326. */
  18327. // if (s.high_water < s.window_size) {
  18328. // var curr = s.strstart + s.lookahead;
  18329. // var init = 0;
  18330. //
  18331. // if (s.high_water < curr) {
  18332. // /* Previous high water mark below current data -- zero WIN_INIT
  18333. // * bytes or up to end of window, whichever is less.
  18334. // */
  18335. // init = s.window_size - curr;
  18336. // if (init > WIN_INIT)
  18337. // init = WIN_INIT;
  18338. // zmemzero(s->window + curr, (unsigned)init);
  18339. // s->high_water = curr + init;
  18340. // }
  18341. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  18342. // /* High water mark at or above current data, but below current data
  18343. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  18344. // * to end of window, whichever is less.
  18345. // */
  18346. // init = (ulg)curr + WIN_INIT - s->high_water;
  18347. // if (init > s->window_size - s->high_water)
  18348. // init = s->window_size - s->high_water;
  18349. // zmemzero(s->window + s->high_water, (unsigned)init);
  18350. // s->high_water += init;
  18351. // }
  18352. // }
  18353. //
  18354. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  18355. // "not enough room for search");
  18356. }
  18357. /* ===========================================================================
  18358. * Copy without compression as much as possible from the input stream, return
  18359. * the current block state.
  18360. * This function does not insert new strings in the dictionary since
  18361. * uncompressible data is probably not useful. This function is used
  18362. * only for the level=0 compression option.
  18363. * NOTE: this function should be optimized to avoid extra copying from
  18364. * window to pending_buf.
  18365. */
  18366. function deflate_stored(s, flush) {
  18367. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  18368. * to pending_buf_size, and each stored block has a 5 byte header:
  18369. */
  18370. var max_block_size = 0xffff;
  18371. if (max_block_size > s.pending_buf_size - 5) {
  18372. max_block_size = s.pending_buf_size - 5;
  18373. }
  18374. /* Copy as much as possible from input to output: */
  18375. for (;;) {
  18376. /* Fill the window as much as possible: */
  18377. if (s.lookahead <= 1) {
  18378. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  18379. // s->block_start >= (long)s->w_size, "slide too late");
  18380. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  18381. // s.block_start >= s.w_size)) {
  18382. // throw new Error("slide too late");
  18383. // }
  18384. fill_window(s);
  18385. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  18386. return BS_NEED_MORE;
  18387. }
  18388. if (s.lookahead === 0) {
  18389. break;
  18390. }
  18391. /* flush the current block */
  18392. }
  18393. //Assert(s->block_start >= 0L, "block gone");
  18394. // if (s.block_start < 0) throw new Error("block gone");
  18395. s.strstart += s.lookahead;
  18396. s.lookahead = 0;
  18397. /* Emit a stored block if pending_buf will be full: */
  18398. var max_start = s.block_start + max_block_size;
  18399. if (s.strstart === 0 || s.strstart >= max_start) {
  18400. /* strstart == 0 is possible when wraparound on 16-bit machine */
  18401. s.lookahead = s.strstart - max_start;
  18402. s.strstart = max_start;
  18403. /*** FLUSH_BLOCK(s, 0); ***/
  18404. flush_block_only(s, false);
  18405. if (s.strm.avail_out === 0) {
  18406. return BS_NEED_MORE;
  18407. }
  18408. /***/
  18409. }
  18410. /* Flush if we may have to slide, otherwise block_start may become
  18411. * negative and the data will be gone:
  18412. */
  18413. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  18414. /*** FLUSH_BLOCK(s, 0); ***/
  18415. flush_block_only(s, false);
  18416. if (s.strm.avail_out === 0) {
  18417. return BS_NEED_MORE;
  18418. }
  18419. /***/
  18420. }
  18421. }
  18422. s.insert = 0;
  18423. if (flush === Z_FINISH) {
  18424. /*** FLUSH_BLOCK(s, 1); ***/
  18425. flush_block_only(s, true);
  18426. if (s.strm.avail_out === 0) {
  18427. return BS_FINISH_STARTED;
  18428. }
  18429. /***/
  18430. return BS_FINISH_DONE;
  18431. }
  18432. if (s.strstart > s.block_start) {
  18433. /*** FLUSH_BLOCK(s, 0); ***/
  18434. flush_block_only(s, false);
  18435. if (s.strm.avail_out === 0) {
  18436. return BS_NEED_MORE;
  18437. }
  18438. /***/
  18439. }
  18440. return BS_NEED_MORE;
  18441. }
  18442. /* ===========================================================================
  18443. * Compress as much as possible from the input stream, return the current
  18444. * block state.
  18445. * This function does not perform lazy evaluation of matches and inserts
  18446. * new strings in the dictionary only for unmatched strings or for short
  18447. * matches. It is used only for the fast compression options.
  18448. */
  18449. function deflate_fast(s, flush) {
  18450. var hash_head; /* head of the hash chain */
  18451. var bflush; /* set if current block must be flushed */
  18452. for (;;) {
  18453. /* Make sure that we always have enough lookahead, except
  18454. * at the end of the input file. We need MAX_MATCH bytes
  18455. * for the next match, plus MIN_MATCH bytes to insert the
  18456. * string following the next match.
  18457. */
  18458. if (s.lookahead < MIN_LOOKAHEAD) {
  18459. fill_window(s);
  18460. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18461. return BS_NEED_MORE;
  18462. }
  18463. if (s.lookahead === 0) {
  18464. break; /* flush the current block */
  18465. }
  18466. }
  18467. /* Insert the string window[strstart .. strstart+2] in the
  18468. * dictionary, and set hash_head to the head of the hash chain:
  18469. */
  18470. hash_head = 0/*NIL*/;
  18471. if (s.lookahead >= MIN_MATCH) {
  18472. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18473. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18474. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18475. s.head[s.ins_h] = s.strstart;
  18476. /***/
  18477. }
  18478. /* Find the longest match, discarding those <= prev_length.
  18479. * At this point we have always match_length < MIN_MATCH
  18480. */
  18481. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  18482. /* To simplify the code, we prevent matches with the string
  18483. * of window index 0 (in particular we have to avoid a match
  18484. * of the string with itself at the start of the input file).
  18485. */
  18486. s.match_length = longest_match(s, hash_head);
  18487. /* longest_match() sets match_start */
  18488. }
  18489. if (s.match_length >= MIN_MATCH) {
  18490. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  18491. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  18492. s.match_length - MIN_MATCH, bflush); ***/
  18493. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  18494. s.lookahead -= s.match_length;
  18495. /* Insert new strings in the hash table only if the match length
  18496. * is not too large. This saves time but degrades compression.
  18497. */
  18498. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  18499. s.match_length--; /* string at strstart already in table */
  18500. do {
  18501. s.strstart++;
  18502. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18503. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18504. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18505. s.head[s.ins_h] = s.strstart;
  18506. /***/
  18507. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  18508. * always MIN_MATCH bytes ahead.
  18509. */
  18510. } while (--s.match_length !== 0);
  18511. s.strstart++;
  18512. } else
  18513. {
  18514. s.strstart += s.match_length;
  18515. s.match_length = 0;
  18516. s.ins_h = s.window[s.strstart];
  18517. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  18518. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  18519. //#if MIN_MATCH != 3
  18520. // Call UPDATE_HASH() MIN_MATCH-3 more times
  18521. //#endif
  18522. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  18523. * matter since it will be recomputed at next deflate call.
  18524. */
  18525. }
  18526. } else {
  18527. /* No match, output a literal byte */
  18528. //Tracevv((stderr,"%c", s.window[s.strstart]));
  18529. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18530. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18531. s.lookahead--;
  18532. s.strstart++;
  18533. }
  18534. if (bflush) {
  18535. /*** FLUSH_BLOCK(s, 0); ***/
  18536. flush_block_only(s, false);
  18537. if (s.strm.avail_out === 0) {
  18538. return BS_NEED_MORE;
  18539. }
  18540. /***/
  18541. }
  18542. }
  18543. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  18544. if (flush === Z_FINISH) {
  18545. /*** FLUSH_BLOCK(s, 1); ***/
  18546. flush_block_only(s, true);
  18547. if (s.strm.avail_out === 0) {
  18548. return BS_FINISH_STARTED;
  18549. }
  18550. /***/
  18551. return BS_FINISH_DONE;
  18552. }
  18553. if (s.last_lit) {
  18554. /*** FLUSH_BLOCK(s, 0); ***/
  18555. flush_block_only(s, false);
  18556. if (s.strm.avail_out === 0) {
  18557. return BS_NEED_MORE;
  18558. }
  18559. /***/
  18560. }
  18561. return BS_BLOCK_DONE;
  18562. }
  18563. /* ===========================================================================
  18564. * Same as above, but achieves better compression. We use a lazy
  18565. * evaluation for matches: a match is finally adopted only if there is
  18566. * no better match at the next window position.
  18567. */
  18568. function deflate_slow(s, flush) {
  18569. var hash_head; /* head of hash chain */
  18570. var bflush; /* set if current block must be flushed */
  18571. var max_insert;
  18572. /* Process the input block. */
  18573. for (;;) {
  18574. /* Make sure that we always have enough lookahead, except
  18575. * at the end of the input file. We need MAX_MATCH bytes
  18576. * for the next match, plus MIN_MATCH bytes to insert the
  18577. * string following the next match.
  18578. */
  18579. if (s.lookahead < MIN_LOOKAHEAD) {
  18580. fill_window(s);
  18581. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18582. return BS_NEED_MORE;
  18583. }
  18584. if (s.lookahead === 0) { break; } /* flush the current block */
  18585. }
  18586. /* Insert the string window[strstart .. strstart+2] in the
  18587. * dictionary, and set hash_head to the head of the hash chain:
  18588. */
  18589. hash_head = 0/*NIL*/;
  18590. if (s.lookahead >= MIN_MATCH) {
  18591. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18592. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18593. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18594. s.head[s.ins_h] = s.strstart;
  18595. /***/
  18596. }
  18597. /* Find the longest match, discarding those <= prev_length.
  18598. */
  18599. s.prev_length = s.match_length;
  18600. s.prev_match = s.match_start;
  18601. s.match_length = MIN_MATCH-1;
  18602. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  18603. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  18604. /* To simplify the code, we prevent matches with the string
  18605. * of window index 0 (in particular we have to avoid a match
  18606. * of the string with itself at the start of the input file).
  18607. */
  18608. s.match_length = longest_match(s, hash_head);
  18609. /* longest_match() sets match_start */
  18610. if (s.match_length <= 5 &&
  18611. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  18612. /* If prev_match is also MIN_MATCH, match_start is garbage
  18613. * but we will ignore the current match anyway.
  18614. */
  18615. s.match_length = MIN_MATCH-1;
  18616. }
  18617. }
  18618. /* If there was a match at the previous step and the current
  18619. * match is not better, output the previous match:
  18620. */
  18621. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  18622. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  18623. /* Do not insert strings in hash table beyond this. */
  18624. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  18625. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  18626. s.prev_length - MIN_MATCH, bflush);***/
  18627. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  18628. /* Insert in hash table all strings up to the end of the match.
  18629. * strstart-1 and strstart are already inserted. If there is not
  18630. * enough lookahead, the last two strings are not inserted in
  18631. * the hash table.
  18632. */
  18633. s.lookahead -= s.prev_length-1;
  18634. s.prev_length -= 2;
  18635. do {
  18636. if (++s.strstart <= max_insert) {
  18637. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18638. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18639. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18640. s.head[s.ins_h] = s.strstart;
  18641. /***/
  18642. }
  18643. } while (--s.prev_length !== 0);
  18644. s.match_available = 0;
  18645. s.match_length = MIN_MATCH-1;
  18646. s.strstart++;
  18647. if (bflush) {
  18648. /*** FLUSH_BLOCK(s, 0); ***/
  18649. flush_block_only(s, false);
  18650. if (s.strm.avail_out === 0) {
  18651. return BS_NEED_MORE;
  18652. }
  18653. /***/
  18654. }
  18655. } else if (s.match_available) {
  18656. /* If there was no match at the previous position, output a
  18657. * single literal. If there was a match but the current match
  18658. * is longer, truncate the previous match to a single literal.
  18659. */
  18660. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18661. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18662. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18663. if (bflush) {
  18664. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  18665. flush_block_only(s, false);
  18666. /***/
  18667. }
  18668. s.strstart++;
  18669. s.lookahead--;
  18670. if (s.strm.avail_out === 0) {
  18671. return BS_NEED_MORE;
  18672. }
  18673. } else {
  18674. /* There is no previous match to compare with, wait for
  18675. * the next step to decide.
  18676. */
  18677. s.match_available = 1;
  18678. s.strstart++;
  18679. s.lookahead--;
  18680. }
  18681. }
  18682. //Assert (flush != Z_NO_FLUSH, "no flush?");
  18683. if (s.match_available) {
  18684. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18685. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18686. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18687. s.match_available = 0;
  18688. }
  18689. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  18690. if (flush === Z_FINISH) {
  18691. /*** FLUSH_BLOCK(s, 1); ***/
  18692. flush_block_only(s, true);
  18693. if (s.strm.avail_out === 0) {
  18694. return BS_FINISH_STARTED;
  18695. }
  18696. /***/
  18697. return BS_FINISH_DONE;
  18698. }
  18699. if (s.last_lit) {
  18700. /*** FLUSH_BLOCK(s, 0); ***/
  18701. flush_block_only(s, false);
  18702. if (s.strm.avail_out === 0) {
  18703. return BS_NEED_MORE;
  18704. }
  18705. /***/
  18706. }
  18707. return BS_BLOCK_DONE;
  18708. }
  18709. /* ===========================================================================
  18710. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  18711. * one. Do not maintain a hash table. (It will be regenerated if this run of
  18712. * deflate switches away from Z_RLE.)
  18713. */
  18714. function deflate_rle(s, flush) {
  18715. var bflush; /* set if current block must be flushed */
  18716. var prev; /* byte at distance one to match */
  18717. var scan, strend; /* scan goes up to strend for length of run */
  18718. var _win = s.window;
  18719. for (;;) {
  18720. /* Make sure that we always have enough lookahead, except
  18721. * at the end of the input file. We need MAX_MATCH bytes
  18722. * for the longest run, plus one for the unrolled loop.
  18723. */
  18724. if (s.lookahead <= MAX_MATCH) {
  18725. fill_window(s);
  18726. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  18727. return BS_NEED_MORE;
  18728. }
  18729. if (s.lookahead === 0) { break; } /* flush the current block */
  18730. }
  18731. /* See how many times the previous byte repeats */
  18732. s.match_length = 0;
  18733. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  18734. scan = s.strstart - 1;
  18735. prev = _win[scan];
  18736. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  18737. strend = s.strstart + MAX_MATCH;
  18738. do {
  18739. /*jshint noempty:false*/
  18740. } while (prev === _win[++scan] && prev === _win[++scan] &&
  18741. prev === _win[++scan] && prev === _win[++scan] &&
  18742. prev === _win[++scan] && prev === _win[++scan] &&
  18743. prev === _win[++scan] && prev === _win[++scan] &&
  18744. scan < strend);
  18745. s.match_length = MAX_MATCH - (strend - scan);
  18746. if (s.match_length > s.lookahead) {
  18747. s.match_length = s.lookahead;
  18748. }
  18749. }
  18750. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  18751. }
  18752. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  18753. if (s.match_length >= MIN_MATCH) {
  18754. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  18755. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  18756. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  18757. s.lookahead -= s.match_length;
  18758. s.strstart += s.match_length;
  18759. s.match_length = 0;
  18760. } else {
  18761. /* No match, output a literal byte */
  18762. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18763. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18764. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18765. s.lookahead--;
  18766. s.strstart++;
  18767. }
  18768. if (bflush) {
  18769. /*** FLUSH_BLOCK(s, 0); ***/
  18770. flush_block_only(s, false);
  18771. if (s.strm.avail_out === 0) {
  18772. return BS_NEED_MORE;
  18773. }
  18774. /***/
  18775. }
  18776. }
  18777. s.insert = 0;
  18778. if (flush === Z_FINISH) {
  18779. /*** FLUSH_BLOCK(s, 1); ***/
  18780. flush_block_only(s, true);
  18781. if (s.strm.avail_out === 0) {
  18782. return BS_FINISH_STARTED;
  18783. }
  18784. /***/
  18785. return BS_FINISH_DONE;
  18786. }
  18787. if (s.last_lit) {
  18788. /*** FLUSH_BLOCK(s, 0); ***/
  18789. flush_block_only(s, false);
  18790. if (s.strm.avail_out === 0) {
  18791. return BS_NEED_MORE;
  18792. }
  18793. /***/
  18794. }
  18795. return BS_BLOCK_DONE;
  18796. }
  18797. /* ===========================================================================
  18798. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  18799. * (It will be regenerated if this run of deflate switches away from Huffman.)
  18800. */
  18801. function deflate_huff(s, flush) {
  18802. var bflush; /* set if current block must be flushed */
  18803. for (;;) {
  18804. /* Make sure that we have a literal to write. */
  18805. if (s.lookahead === 0) {
  18806. fill_window(s);
  18807. if (s.lookahead === 0) {
  18808. if (flush === Z_NO_FLUSH) {
  18809. return BS_NEED_MORE;
  18810. }
  18811. break; /* flush the current block */
  18812. }
  18813. }
  18814. /* Output a literal byte */
  18815. s.match_length = 0;
  18816. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18817. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18818. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18819. s.lookahead--;
  18820. s.strstart++;
  18821. if (bflush) {
  18822. /*** FLUSH_BLOCK(s, 0); ***/
  18823. flush_block_only(s, false);
  18824. if (s.strm.avail_out === 0) {
  18825. return BS_NEED_MORE;
  18826. }
  18827. /***/
  18828. }
  18829. }
  18830. s.insert = 0;
  18831. if (flush === Z_FINISH) {
  18832. /*** FLUSH_BLOCK(s, 1); ***/
  18833. flush_block_only(s, true);
  18834. if (s.strm.avail_out === 0) {
  18835. return BS_FINISH_STARTED;
  18836. }
  18837. /***/
  18838. return BS_FINISH_DONE;
  18839. }
  18840. if (s.last_lit) {
  18841. /*** FLUSH_BLOCK(s, 0); ***/
  18842. flush_block_only(s, false);
  18843. if (s.strm.avail_out === 0) {
  18844. return BS_NEED_MORE;
  18845. }
  18846. /***/
  18847. }
  18848. return BS_BLOCK_DONE;
  18849. }
  18850. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  18851. * the desired pack level (0..9). The values given below have been tuned to
  18852. * exclude worst case performance for pathological files. Better values may be
  18853. * found for specific files.
  18854. */
  18855. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  18856. this.good_length = good_length;
  18857. this.max_lazy = max_lazy;
  18858. this.nice_length = nice_length;
  18859. this.max_chain = max_chain;
  18860. this.func = func;
  18861. };
  18862. var configuration_table;
  18863. configuration_table = [
  18864. /* good lazy nice chain */
  18865. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  18866. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  18867. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  18868. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  18869. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  18870. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  18871. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  18872. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  18873. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  18874. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  18875. ];
  18876. /* ===========================================================================
  18877. * Initialize the "longest match" routines for a new zlib stream
  18878. */
  18879. function lm_init(s) {
  18880. s.window_size = 2 * s.w_size;
  18881. /*** CLEAR_HASH(s); ***/
  18882. zero(s.head); // Fill with NIL (= 0);
  18883. /* Set the default configuration parameters:
  18884. */
  18885. s.max_lazy_match = configuration_table[s.level].max_lazy;
  18886. s.good_match = configuration_table[s.level].good_length;
  18887. s.nice_match = configuration_table[s.level].nice_length;
  18888. s.max_chain_length = configuration_table[s.level].max_chain;
  18889. s.strstart = 0;
  18890. s.block_start = 0;
  18891. s.lookahead = 0;
  18892. s.insert = 0;
  18893. s.match_length = s.prev_length = MIN_MATCH - 1;
  18894. s.match_available = 0;
  18895. s.ins_h = 0;
  18896. }
  18897. function DeflateState() {
  18898. this.strm = null; /* pointer back to this zlib stream */
  18899. this.status = 0; /* as the name implies */
  18900. this.pending_buf = null; /* output still pending */
  18901. this.pending_buf_size = 0; /* size of pending_buf */
  18902. this.pending_out = 0; /* next pending byte to output to the stream */
  18903. this.pending = 0; /* nb of bytes in the pending buffer */
  18904. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  18905. this.gzhead = null; /* gzip header information to write */
  18906. this.gzindex = 0; /* where in extra, name, or comment */
  18907. this.method = Z_DEFLATED; /* can only be DEFLATED */
  18908. this.last_flush = -1; /* value of flush param for previous deflate call */
  18909. this.w_size = 0; /* LZ77 window size (32K by default) */
  18910. this.w_bits = 0; /* log2(w_size) (8..16) */
  18911. this.w_mask = 0; /* w_size - 1 */
  18912. this.window = null;
  18913. /* Sliding window. Input bytes are read into the second half of the window,
  18914. * and move to the first half later to keep a dictionary of at least wSize
  18915. * bytes. With this organization, matches are limited to a distance of
  18916. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  18917. * performed with a length multiple of the block size.
  18918. */
  18919. this.window_size = 0;
  18920. /* Actual size of window: 2*wSize, except when the user input buffer
  18921. * is directly used as sliding window.
  18922. */
  18923. this.prev = null;
  18924. /* Link to older string with same hash index. To limit the size of this
  18925. * array to 64K, this link is maintained only for the last 32K strings.
  18926. * An index in this array is thus a window index modulo 32K.
  18927. */
  18928. this.head = null; /* Heads of the hash chains or NIL. */
  18929. this.ins_h = 0; /* hash index of string to be inserted */
  18930. this.hash_size = 0; /* number of elements in hash table */
  18931. this.hash_bits = 0; /* log2(hash_size) */
  18932. this.hash_mask = 0; /* hash_size-1 */
  18933. this.hash_shift = 0;
  18934. /* Number of bits by which ins_h must be shifted at each input
  18935. * step. It must be such that after MIN_MATCH steps, the oldest
  18936. * byte no longer takes part in the hash key, that is:
  18937. * hash_shift * MIN_MATCH >= hash_bits
  18938. */
  18939. this.block_start = 0;
  18940. /* Window position at the beginning of the current output block. Gets
  18941. * negative when the window is moved backwards.
  18942. */
  18943. this.match_length = 0; /* length of best match */
  18944. this.prev_match = 0; /* previous match */
  18945. this.match_available = 0; /* set if previous match exists */
  18946. this.strstart = 0; /* start of string to insert */
  18947. this.match_start = 0; /* start of matching string */
  18948. this.lookahead = 0; /* number of valid bytes ahead in window */
  18949. this.prev_length = 0;
  18950. /* Length of the best match at previous step. Matches not greater than this
  18951. * are discarded. This is used in the lazy match evaluation.
  18952. */
  18953. this.max_chain_length = 0;
  18954. /* To speed up deflation, hash chains are never searched beyond this
  18955. * length. A higher limit improves compression ratio but degrades the
  18956. * speed.
  18957. */
  18958. this.max_lazy_match = 0;
  18959. /* Attempt to find a better match only when the current match is strictly
  18960. * smaller than this value. This mechanism is used only for compression
  18961. * levels >= 4.
  18962. */
  18963. // That's alias to max_lazy_match, don't use directly
  18964. //this.max_insert_length = 0;
  18965. /* Insert new strings in the hash table only if the match length is not
  18966. * greater than this length. This saves time but degrades compression.
  18967. * max_insert_length is used only for compression levels <= 3.
  18968. */
  18969. this.level = 0; /* compression level (1..9) */
  18970. this.strategy = 0; /* favor or force Huffman coding*/
  18971. this.good_match = 0;
  18972. /* Use a faster search when the previous match is longer than this */
  18973. this.nice_match = 0; /* Stop searching when current match exceeds this */
  18974. /* used by trees.c: */
  18975. /* Didn't use ct_data typedef below to suppress compiler warning */
  18976. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  18977. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  18978. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  18979. // Use flat array of DOUBLE size, with interleaved fata,
  18980. // because JS does not support effective
  18981. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  18982. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  18983. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  18984. zero(this.dyn_ltree);
  18985. zero(this.dyn_dtree);
  18986. zero(this.bl_tree);
  18987. this.l_desc = null; /* desc. for literal tree */
  18988. this.d_desc = null; /* desc. for distance tree */
  18989. this.bl_desc = null; /* desc. for bit length tree */
  18990. //ush bl_count[MAX_BITS+1];
  18991. this.bl_count = new utils.Buf16(MAX_BITS+1);
  18992. /* number of codes at each bit length for an optimal tree */
  18993. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  18994. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  18995. zero(this.heap);
  18996. this.heap_len = 0; /* number of elements in the heap */
  18997. this.heap_max = 0; /* element of largest frequency */
  18998. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  18999. * The same heap array is used to build all trees.
  19000. */
  19001. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  19002. zero(this.depth);
  19003. /* Depth of each subtree used as tie breaker for trees of equal frequency
  19004. */
  19005. this.l_buf = 0; /* buffer index for literals or lengths */
  19006. this.lit_bufsize = 0;
  19007. /* Size of match buffer for literals/lengths. There are 4 reasons for
  19008. * limiting lit_bufsize to 64K:
  19009. * - frequencies can be kept in 16 bit counters
  19010. * - if compression is not successful for the first block, all input
  19011. * data is still in the window so we can still emit a stored block even
  19012. * when input comes from standard input. (This can also be done for
  19013. * all blocks if lit_bufsize is not greater than 32K.)
  19014. * - if compression is not successful for a file smaller than 64K, we can
  19015. * even emit a stored file instead of a stored block (saving 5 bytes).
  19016. * This is applicable only for zip (not gzip or zlib).
  19017. * - creating new Huffman trees less frequently may not provide fast
  19018. * adaptation to changes in the input data statistics. (Take for
  19019. * example a binary file with poorly compressible code followed by
  19020. * a highly compressible string table.) Smaller buffer sizes give
  19021. * fast adaptation but have of course the overhead of transmitting
  19022. * trees more frequently.
  19023. * - I can't count above 4
  19024. */
  19025. this.last_lit = 0; /* running index in l_buf */
  19026. this.d_buf = 0;
  19027. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  19028. * the same number of elements. To use different lengths, an extra flag
  19029. * array would be necessary.
  19030. */
  19031. this.opt_len = 0; /* bit length of current block with optimal trees */
  19032. this.static_len = 0; /* bit length of current block with static trees */
  19033. this.matches = 0; /* number of string matches in current block */
  19034. this.insert = 0; /* bytes at end of window left to insert */
  19035. this.bi_buf = 0;
  19036. /* Output buffer. bits are inserted starting at the bottom (least
  19037. * significant bits).
  19038. */
  19039. this.bi_valid = 0;
  19040. /* Number of valid bits in bi_buf. All bits above the last valid bit
  19041. * are always zero.
  19042. */
  19043. // Used for window memory init. We safely ignore it for JS. That makes
  19044. // sense only for pointers and memory check tools.
  19045. //this.high_water = 0;
  19046. /* High water mark offset in window for initialized bytes -- bytes above
  19047. * this are set to zero in order to avoid memory check warnings when
  19048. * longest match routines access bytes past the input. This is then
  19049. * updated to the new high water mark.
  19050. */
  19051. }
  19052. function deflateResetKeep(strm) {
  19053. var s;
  19054. if (!strm || !strm.state) {
  19055. return err(strm, Z_STREAM_ERROR);
  19056. }
  19057. strm.total_in = strm.total_out = 0;
  19058. strm.data_type = Z_UNKNOWN;
  19059. s = strm.state;
  19060. s.pending = 0;
  19061. s.pending_out = 0;
  19062. if (s.wrap < 0) {
  19063. s.wrap = -s.wrap;
  19064. /* was made negative by deflate(..., Z_FINISH); */
  19065. }
  19066. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  19067. strm.adler = (s.wrap === 2) ?
  19068. 0 // crc32(0, Z_NULL, 0)
  19069. :
  19070. 1; // adler32(0, Z_NULL, 0)
  19071. s.last_flush = Z_NO_FLUSH;
  19072. trees._tr_init(s);
  19073. return Z_OK;
  19074. }
  19075. function deflateReset(strm) {
  19076. var ret = deflateResetKeep(strm);
  19077. if (ret === Z_OK) {
  19078. lm_init(strm.state);
  19079. }
  19080. return ret;
  19081. }
  19082. function deflateSetHeader(strm, head) {
  19083. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19084. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  19085. strm.state.gzhead = head;
  19086. return Z_OK;
  19087. }
  19088. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  19089. if (!strm) { // === Z_NULL
  19090. return Z_STREAM_ERROR;
  19091. }
  19092. var wrap = 1;
  19093. if (level === Z_DEFAULT_COMPRESSION) {
  19094. level = 6;
  19095. }
  19096. if (windowBits < 0) { /* suppress zlib wrapper */
  19097. wrap = 0;
  19098. windowBits = -windowBits;
  19099. }
  19100. else if (windowBits > 15) {
  19101. wrap = 2; /* write gzip wrapper instead */
  19102. windowBits -= 16;
  19103. }
  19104. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  19105. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  19106. strategy < 0 || strategy > Z_FIXED) {
  19107. return err(strm, Z_STREAM_ERROR);
  19108. }
  19109. if (windowBits === 8) {
  19110. windowBits = 9;
  19111. }
  19112. /* until 256-byte window bug fixed */
  19113. var s = new DeflateState();
  19114. strm.state = s;
  19115. s.strm = strm;
  19116. s.wrap = wrap;
  19117. s.gzhead = null;
  19118. s.w_bits = windowBits;
  19119. s.w_size = 1 << s.w_bits;
  19120. s.w_mask = s.w_size - 1;
  19121. s.hash_bits = memLevel + 7;
  19122. s.hash_size = 1 << s.hash_bits;
  19123. s.hash_mask = s.hash_size - 1;
  19124. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  19125. s.window = new utils.Buf8(s.w_size * 2);
  19126. s.head = new utils.Buf16(s.hash_size);
  19127. s.prev = new utils.Buf16(s.w_size);
  19128. // Don't need mem init magic for JS.
  19129. //s.high_water = 0; /* nothing written to s->window yet */
  19130. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  19131. s.pending_buf_size = s.lit_bufsize * 4;
  19132. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  19133. s.d_buf = s.lit_bufsize >> 1;
  19134. s.l_buf = (1 + 2) * s.lit_bufsize;
  19135. s.level = level;
  19136. s.strategy = strategy;
  19137. s.method = method;
  19138. return deflateReset(strm);
  19139. }
  19140. function deflateInit(strm, level) {
  19141. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  19142. }
  19143. function deflate(strm, flush) {
  19144. var old_flush, s;
  19145. var beg, val; // for gzip header write only
  19146. if (!strm || !strm.state ||
  19147. flush > Z_BLOCK || flush < 0) {
  19148. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  19149. }
  19150. s = strm.state;
  19151. if (!strm.output ||
  19152. (!strm.input && strm.avail_in !== 0) ||
  19153. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  19154. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  19155. }
  19156. s.strm = strm; /* just in case */
  19157. old_flush = s.last_flush;
  19158. s.last_flush = flush;
  19159. /* Write the header */
  19160. if (s.status === INIT_STATE) {
  19161. if (s.wrap === 2) { // GZIP header
  19162. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19163. put_byte(s, 31);
  19164. put_byte(s, 139);
  19165. put_byte(s, 8);
  19166. if (!s.gzhead) { // s->gzhead == Z_NULL
  19167. put_byte(s, 0);
  19168. put_byte(s, 0);
  19169. put_byte(s, 0);
  19170. put_byte(s, 0);
  19171. put_byte(s, 0);
  19172. put_byte(s, s.level === 9 ? 2 :
  19173. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  19174. 4 : 0));
  19175. put_byte(s, OS_CODE);
  19176. s.status = BUSY_STATE;
  19177. }
  19178. else {
  19179. put_byte(s, (s.gzhead.text ? 1 : 0) +
  19180. (s.gzhead.hcrc ? 2 : 0) +
  19181. (!s.gzhead.extra ? 0 : 4) +
  19182. (!s.gzhead.name ? 0 : 8) +
  19183. (!s.gzhead.comment ? 0 : 16)
  19184. );
  19185. put_byte(s, s.gzhead.time & 0xff);
  19186. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  19187. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  19188. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  19189. put_byte(s, s.level === 9 ? 2 :
  19190. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  19191. 4 : 0));
  19192. put_byte(s, s.gzhead.os & 0xff);
  19193. if (s.gzhead.extra && s.gzhead.extra.length) {
  19194. put_byte(s, s.gzhead.extra.length & 0xff);
  19195. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  19196. }
  19197. if (s.gzhead.hcrc) {
  19198. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  19199. }
  19200. s.gzindex = 0;
  19201. s.status = EXTRA_STATE;
  19202. }
  19203. }
  19204. else // DEFLATE header
  19205. {
  19206. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  19207. var level_flags = -1;
  19208. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  19209. level_flags = 0;
  19210. } else if (s.level < 6) {
  19211. level_flags = 1;
  19212. } else if (s.level === 6) {
  19213. level_flags = 2;
  19214. } else {
  19215. level_flags = 3;
  19216. }
  19217. header |= (level_flags << 6);
  19218. if (s.strstart !== 0) { header |= PRESET_DICT; }
  19219. header += 31 - (header % 31);
  19220. s.status = BUSY_STATE;
  19221. putShortMSB(s, header);
  19222. /* Save the adler32 of the preset dictionary: */
  19223. if (s.strstart !== 0) {
  19224. putShortMSB(s, strm.adler >>> 16);
  19225. putShortMSB(s, strm.adler & 0xffff);
  19226. }
  19227. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  19228. }
  19229. }
  19230. //#ifdef GZIP
  19231. if (s.status === EXTRA_STATE) {
  19232. if (s.gzhead.extra/* != Z_NULL*/) {
  19233. beg = s.pending; /* start of bytes to update crc */
  19234. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  19235. if (s.pending === s.pending_buf_size) {
  19236. if (s.gzhead.hcrc && s.pending > beg) {
  19237. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19238. }
  19239. flush_pending(strm);
  19240. beg = s.pending;
  19241. if (s.pending === s.pending_buf_size) {
  19242. break;
  19243. }
  19244. }
  19245. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  19246. s.gzindex++;
  19247. }
  19248. if (s.gzhead.hcrc && s.pending > beg) {
  19249. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19250. }
  19251. if (s.gzindex === s.gzhead.extra.length) {
  19252. s.gzindex = 0;
  19253. s.status = NAME_STATE;
  19254. }
  19255. }
  19256. else {
  19257. s.status = NAME_STATE;
  19258. }
  19259. }
  19260. if (s.status === NAME_STATE) {
  19261. if (s.gzhead.name/* != Z_NULL*/) {
  19262. beg = s.pending; /* start of bytes to update crc */
  19263. //int val;
  19264. do {
  19265. if (s.pending === s.pending_buf_size) {
  19266. if (s.gzhead.hcrc && s.pending > beg) {
  19267. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19268. }
  19269. flush_pending(strm);
  19270. beg = s.pending;
  19271. if (s.pending === s.pending_buf_size) {
  19272. val = 1;
  19273. break;
  19274. }
  19275. }
  19276. // JS specific: little magic to add zero terminator to end of string
  19277. if (s.gzindex < s.gzhead.name.length) {
  19278. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  19279. } else {
  19280. val = 0;
  19281. }
  19282. put_byte(s, val);
  19283. } while (val !== 0);
  19284. if (s.gzhead.hcrc && s.pending > beg){
  19285. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19286. }
  19287. if (val === 0) {
  19288. s.gzindex = 0;
  19289. s.status = COMMENT_STATE;
  19290. }
  19291. }
  19292. else {
  19293. s.status = COMMENT_STATE;
  19294. }
  19295. }
  19296. if (s.status === COMMENT_STATE) {
  19297. if (s.gzhead.comment/* != Z_NULL*/) {
  19298. beg = s.pending; /* start of bytes to update crc */
  19299. //int val;
  19300. do {
  19301. if (s.pending === s.pending_buf_size) {
  19302. if (s.gzhead.hcrc && s.pending > beg) {
  19303. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19304. }
  19305. flush_pending(strm);
  19306. beg = s.pending;
  19307. if (s.pending === s.pending_buf_size) {
  19308. val = 1;
  19309. break;
  19310. }
  19311. }
  19312. // JS specific: little magic to add zero terminator to end of string
  19313. if (s.gzindex < s.gzhead.comment.length) {
  19314. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  19315. } else {
  19316. val = 0;
  19317. }
  19318. put_byte(s, val);
  19319. } while (val !== 0);
  19320. if (s.gzhead.hcrc && s.pending > beg) {
  19321. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19322. }
  19323. if (val === 0) {
  19324. s.status = HCRC_STATE;
  19325. }
  19326. }
  19327. else {
  19328. s.status = HCRC_STATE;
  19329. }
  19330. }
  19331. if (s.status === HCRC_STATE) {
  19332. if (s.gzhead.hcrc) {
  19333. if (s.pending + 2 > s.pending_buf_size) {
  19334. flush_pending(strm);
  19335. }
  19336. if (s.pending + 2 <= s.pending_buf_size) {
  19337. put_byte(s, strm.adler & 0xff);
  19338. put_byte(s, (strm.adler >> 8) & 0xff);
  19339. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19340. s.status = BUSY_STATE;
  19341. }
  19342. }
  19343. else {
  19344. s.status = BUSY_STATE;
  19345. }
  19346. }
  19347. //#endif
  19348. /* Flush as much pending output as possible */
  19349. if (s.pending !== 0) {
  19350. flush_pending(strm);
  19351. if (strm.avail_out === 0) {
  19352. /* Since avail_out is 0, deflate will be called again with
  19353. * more output space, but possibly with both pending and
  19354. * avail_in equal to zero. There won't be anything to do,
  19355. * but this is not an error situation so make sure we
  19356. * return OK instead of BUF_ERROR at next call of deflate:
  19357. */
  19358. s.last_flush = -1;
  19359. return Z_OK;
  19360. }
  19361. /* Make sure there is something to do and avoid duplicate consecutive
  19362. * flushes. For repeated and useless calls with Z_FINISH, we keep
  19363. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  19364. */
  19365. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  19366. flush !== Z_FINISH) {
  19367. return err(strm, Z_BUF_ERROR);
  19368. }
  19369. /* User must not provide more input after the first FINISH: */
  19370. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  19371. return err(strm, Z_BUF_ERROR);
  19372. }
  19373. /* Start a new block or continue the current one.
  19374. */
  19375. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  19376. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  19377. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  19378. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  19379. configuration_table[s.level].func(s, flush));
  19380. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  19381. s.status = FINISH_STATE;
  19382. }
  19383. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  19384. if (strm.avail_out === 0) {
  19385. s.last_flush = -1;
  19386. /* avoid BUF_ERROR next call, see above */
  19387. }
  19388. return Z_OK;
  19389. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  19390. * of deflate should use the same flush parameter to make sure
  19391. * that the flush is complete. So we don't have to output an
  19392. * empty block here, this will be done at next call. This also
  19393. * ensures that for a very small output buffer, we emit at most
  19394. * one empty block.
  19395. */
  19396. }
  19397. if (bstate === BS_BLOCK_DONE) {
  19398. if (flush === Z_PARTIAL_FLUSH) {
  19399. trees._tr_align(s);
  19400. }
  19401. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  19402. trees._tr_stored_block(s, 0, 0, false);
  19403. /* For a full flush, this empty block will be recognized
  19404. * as a special marker by inflate_sync().
  19405. */
  19406. if (flush === Z_FULL_FLUSH) {
  19407. /*** CLEAR_HASH(s); ***/ /* forget history */
  19408. zero(s.head); // Fill with NIL (= 0);
  19409. if (s.lookahead === 0) {
  19410. s.strstart = 0;
  19411. s.block_start = 0;
  19412. s.insert = 0;
  19413. }
  19414. }
  19415. }
  19416. flush_pending(strm);
  19417. if (strm.avail_out === 0) {
  19418. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  19419. return Z_OK;
  19420. }
  19421. }
  19422. }
  19423. //Assert(strm->avail_out > 0, "bug2");
  19424. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  19425. if (flush !== Z_FINISH) { return Z_OK; }
  19426. if (s.wrap <= 0) { return Z_STREAM_END; }
  19427. /* Write the trailer */
  19428. if (s.wrap === 2) {
  19429. put_byte(s, strm.adler & 0xff);
  19430. put_byte(s, (strm.adler >> 8) & 0xff);
  19431. put_byte(s, (strm.adler >> 16) & 0xff);
  19432. put_byte(s, (strm.adler >> 24) & 0xff);
  19433. put_byte(s, strm.total_in & 0xff);
  19434. put_byte(s, (strm.total_in >> 8) & 0xff);
  19435. put_byte(s, (strm.total_in >> 16) & 0xff);
  19436. put_byte(s, (strm.total_in >> 24) & 0xff);
  19437. }
  19438. else
  19439. {
  19440. putShortMSB(s, strm.adler >>> 16);
  19441. putShortMSB(s, strm.adler & 0xffff);
  19442. }
  19443. flush_pending(strm);
  19444. /* If avail_out is zero, the application will call deflate again
  19445. * to flush the rest.
  19446. */
  19447. if (s.wrap > 0) { s.wrap = -s.wrap; }
  19448. /* write the trailer only once! */
  19449. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  19450. }
  19451. function deflateEnd(strm) {
  19452. var status;
  19453. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  19454. return Z_STREAM_ERROR;
  19455. }
  19456. status = strm.state.status;
  19457. if (status !== INIT_STATE &&
  19458. status !== EXTRA_STATE &&
  19459. status !== NAME_STATE &&
  19460. status !== COMMENT_STATE &&
  19461. status !== HCRC_STATE &&
  19462. status !== BUSY_STATE &&
  19463. status !== FINISH_STATE
  19464. ) {
  19465. return err(strm, Z_STREAM_ERROR);
  19466. }
  19467. strm.state = null;
  19468. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  19469. }
  19470. /* =========================================================================
  19471. * Copy the source state to the destination state
  19472. */
  19473. //function deflateCopy(dest, source) {
  19474. //
  19475. //}
  19476. exports.deflateInit = deflateInit;
  19477. exports.deflateInit2 = deflateInit2;
  19478. exports.deflateReset = deflateReset;
  19479. exports.deflateResetKeep = deflateResetKeep;
  19480. exports.deflateSetHeader = deflateSetHeader;
  19481. exports.deflate = deflate;
  19482. exports.deflateEnd = deflateEnd;
  19483. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  19484. /* Not implemented
  19485. exports.deflateBound = deflateBound;
  19486. exports.deflateCopy = deflateCopy;
  19487. exports.deflateSetDictionary = deflateSetDictionary;
  19488. exports.deflateParams = deflateParams;
  19489. exports.deflatePending = deflatePending;
  19490. exports.deflatePrime = deflatePrime;
  19491. exports.deflateTune = deflateTune;
  19492. */
  19493. },{"../utils/common":66,"./adler32":68,"./crc32":70,"./messages":76,"./trees":77}],72:[function(require,module,exports){
  19494. 'use strict';
  19495. function GZheader() {
  19496. /* true if compressed data believed to be text */
  19497. this.text = 0;
  19498. /* modification time */
  19499. this.time = 0;
  19500. /* extra flags (not used when writing a gzip file) */
  19501. this.xflags = 0;
  19502. /* operating system */
  19503. this.os = 0;
  19504. /* pointer to extra field or Z_NULL if none */
  19505. this.extra = null;
  19506. /* extra field length (valid if extra != Z_NULL) */
  19507. this.extra_len = 0; // Actually, we don't need it in JS,
  19508. // but leave for few code modifications
  19509. //
  19510. // Setup limits is not necessary because in js we should not preallocate memory
  19511. // for inflate use constant limit in 65536 bytes
  19512. //
  19513. /* space at extra (only when reading header) */
  19514. // this.extra_max = 0;
  19515. /* pointer to zero-terminated file name or Z_NULL */
  19516. this.name = '';
  19517. /* space at name (only when reading header) */
  19518. // this.name_max = 0;
  19519. /* pointer to zero-terminated comment or Z_NULL */
  19520. this.comment = '';
  19521. /* space at comment (only when reading header) */
  19522. // this.comm_max = 0;
  19523. /* true if there was or will be a header crc */
  19524. this.hcrc = 0;
  19525. /* true when done reading gzip header (not used when writing a gzip file) */
  19526. this.done = false;
  19527. }
  19528. module.exports = GZheader;
  19529. },{}],73:[function(require,module,exports){
  19530. 'use strict';
  19531. // See state defs from inflate.js
  19532. var BAD = 30; /* got a data error -- remain here until reset */
  19533. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19534. /*
  19535. Decode literal, length, and distance codes and write out the resulting
  19536. literal and match bytes until either not enough input or output is
  19537. available, an end-of-block is encountered, or a data error is encountered.
  19538. When large enough input and output buffers are supplied to inflate(), for
  19539. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  19540. inflate execution time is spent in this routine.
  19541. Entry assumptions:
  19542. state.mode === LEN
  19543. strm.avail_in >= 6
  19544. strm.avail_out >= 258
  19545. start >= strm.avail_out
  19546. state.bits < 8
  19547. On return, state.mode is one of:
  19548. LEN -- ran out of enough output space or enough available input
  19549. TYPE -- reached end of block code, inflate() to interpret next block
  19550. BAD -- error in block data
  19551. Notes:
  19552. - The maximum input bits used by a length/distance pair is 15 bits for the
  19553. length code, 5 bits for the length extra, 15 bits for the distance code,
  19554. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  19555. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  19556. checking for available input while decoding.
  19557. - The maximum bytes that a single length/distance pair can output is 258
  19558. bytes, which is the maximum length that can be coded. inflate_fast()
  19559. requires strm.avail_out >= 258 for each loop to avoid checking for
  19560. output space.
  19561. */
  19562. module.exports = function inflate_fast(strm, start) {
  19563. var state;
  19564. var _in; /* local strm.input */
  19565. var last; /* have enough input while in < last */
  19566. var _out; /* local strm.output */
  19567. var beg; /* inflate()'s initial strm.output */
  19568. var end; /* while out < end, enough space available */
  19569. //#ifdef INFLATE_STRICT
  19570. var dmax; /* maximum distance from zlib header */
  19571. //#endif
  19572. var wsize; /* window size or zero if not using window */
  19573. var whave; /* valid bytes in the window */
  19574. var wnext; /* window write index */
  19575. var window; /* allocated sliding window, if wsize != 0 */
  19576. var hold; /* local strm.hold */
  19577. var bits; /* local strm.bits */
  19578. var lcode; /* local strm.lencode */
  19579. var dcode; /* local strm.distcode */
  19580. var lmask; /* mask for first level of length codes */
  19581. var dmask; /* mask for first level of distance codes */
  19582. var here; /* retrieved table entry */
  19583. var op; /* code bits, operation, extra bits, or */
  19584. /* window position, window bytes to copy */
  19585. var len; /* match length, unused bytes */
  19586. var dist; /* match distance */
  19587. var from; /* where to copy match from */
  19588. var from_source;
  19589. var input, output; // JS specific, because we have no pointers
  19590. /* copy state to local variables */
  19591. state = strm.state;
  19592. //here = state.here;
  19593. _in = strm.next_in;
  19594. input = strm.input;
  19595. last = _in + (strm.avail_in - 5);
  19596. _out = strm.next_out;
  19597. output = strm.output;
  19598. beg = _out - (start - strm.avail_out);
  19599. end = _out + (strm.avail_out - 257);
  19600. //#ifdef INFLATE_STRICT
  19601. dmax = state.dmax;
  19602. //#endif
  19603. wsize = state.wsize;
  19604. whave = state.whave;
  19605. wnext = state.wnext;
  19606. window = state.window;
  19607. hold = state.hold;
  19608. bits = state.bits;
  19609. lcode = state.lencode;
  19610. dcode = state.distcode;
  19611. lmask = (1 << state.lenbits) - 1;
  19612. dmask = (1 << state.distbits) - 1;
  19613. /* decode literals and length/distances until end-of-block or not enough
  19614. input data or output space */
  19615. top:
  19616. do {
  19617. if (bits < 15) {
  19618. hold += input[_in++] << bits;
  19619. bits += 8;
  19620. hold += input[_in++] << bits;
  19621. bits += 8;
  19622. }
  19623. here = lcode[hold & lmask];
  19624. dolen:
  19625. for (;;) { // Goto emulation
  19626. op = here >>> 24/*here.bits*/;
  19627. hold >>>= op;
  19628. bits -= op;
  19629. op = (here >>> 16) & 0xff/*here.op*/;
  19630. if (op === 0) { /* literal */
  19631. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  19632. // "inflate: literal '%c'\n" :
  19633. // "inflate: literal 0x%02x\n", here.val));
  19634. output[_out++] = here & 0xffff/*here.val*/;
  19635. }
  19636. else if (op & 16) { /* length base */
  19637. len = here & 0xffff/*here.val*/;
  19638. op &= 15; /* number of extra bits */
  19639. if (op) {
  19640. if (bits < op) {
  19641. hold += input[_in++] << bits;
  19642. bits += 8;
  19643. }
  19644. len += hold & ((1 << op) - 1);
  19645. hold >>>= op;
  19646. bits -= op;
  19647. }
  19648. //Tracevv((stderr, "inflate: length %u\n", len));
  19649. if (bits < 15) {
  19650. hold += input[_in++] << bits;
  19651. bits += 8;
  19652. hold += input[_in++] << bits;
  19653. bits += 8;
  19654. }
  19655. here = dcode[hold & dmask];
  19656. dodist:
  19657. for (;;) { // goto emulation
  19658. op = here >>> 24/*here.bits*/;
  19659. hold >>>= op;
  19660. bits -= op;
  19661. op = (here >>> 16) & 0xff/*here.op*/;
  19662. if (op & 16) { /* distance base */
  19663. dist = here & 0xffff/*here.val*/;
  19664. op &= 15; /* number of extra bits */
  19665. if (bits < op) {
  19666. hold += input[_in++] << bits;
  19667. bits += 8;
  19668. if (bits < op) {
  19669. hold += input[_in++] << bits;
  19670. bits += 8;
  19671. }
  19672. }
  19673. dist += hold & ((1 << op) - 1);
  19674. //#ifdef INFLATE_STRICT
  19675. if (dist > dmax) {
  19676. strm.msg = 'invalid distance too far back';
  19677. state.mode = BAD;
  19678. break top;
  19679. }
  19680. //#endif
  19681. hold >>>= op;
  19682. bits -= op;
  19683. //Tracevv((stderr, "inflate: distance %u\n", dist));
  19684. op = _out - beg; /* max distance in output */
  19685. if (dist > op) { /* see if copy from window */
  19686. op = dist - op; /* distance back in window */
  19687. if (op > whave) {
  19688. if (state.sane) {
  19689. strm.msg = 'invalid distance too far back';
  19690. state.mode = BAD;
  19691. break top;
  19692. }
  19693. // (!) This block is disabled in zlib defailts,
  19694. // don't enable it for binary compatibility
  19695. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  19696. // if (len <= op - whave) {
  19697. // do {
  19698. // output[_out++] = 0;
  19699. // } while (--len);
  19700. // continue top;
  19701. // }
  19702. // len -= op - whave;
  19703. // do {
  19704. // output[_out++] = 0;
  19705. // } while (--op > whave);
  19706. // if (op === 0) {
  19707. // from = _out - dist;
  19708. // do {
  19709. // output[_out++] = output[from++];
  19710. // } while (--len);
  19711. // continue top;
  19712. // }
  19713. //#endif
  19714. }
  19715. from = 0; // window index
  19716. from_source = window;
  19717. if (wnext === 0) { /* very common case */
  19718. from += wsize - op;
  19719. if (op < len) { /* some from window */
  19720. len -= op;
  19721. do {
  19722. output[_out++] = window[from++];
  19723. } while (--op);
  19724. from = _out - dist; /* rest from output */
  19725. from_source = output;
  19726. }
  19727. }
  19728. else if (wnext < op) { /* wrap around window */
  19729. from += wsize + wnext - op;
  19730. op -= wnext;
  19731. if (op < len) { /* some from end of window */
  19732. len -= op;
  19733. do {
  19734. output[_out++] = window[from++];
  19735. } while (--op);
  19736. from = 0;
  19737. if (wnext < len) { /* some from start of window */
  19738. op = wnext;
  19739. len -= op;
  19740. do {
  19741. output[_out++] = window[from++];
  19742. } while (--op);
  19743. from = _out - dist; /* rest from output */
  19744. from_source = output;
  19745. }
  19746. }
  19747. }
  19748. else { /* contiguous in window */
  19749. from += wnext - op;
  19750. if (op < len) { /* some from window */
  19751. len -= op;
  19752. do {
  19753. output[_out++] = window[from++];
  19754. } while (--op);
  19755. from = _out - dist; /* rest from output */
  19756. from_source = output;
  19757. }
  19758. }
  19759. while (len > 2) {
  19760. output[_out++] = from_source[from++];
  19761. output[_out++] = from_source[from++];
  19762. output[_out++] = from_source[from++];
  19763. len -= 3;
  19764. }
  19765. if (len) {
  19766. output[_out++] = from_source[from++];
  19767. if (len > 1) {
  19768. output[_out++] = from_source[from++];
  19769. }
  19770. }
  19771. }
  19772. else {
  19773. from = _out - dist; /* copy direct from output */
  19774. do { /* minimum length is three */
  19775. output[_out++] = output[from++];
  19776. output[_out++] = output[from++];
  19777. output[_out++] = output[from++];
  19778. len -= 3;
  19779. } while (len > 2);
  19780. if (len) {
  19781. output[_out++] = output[from++];
  19782. if (len > 1) {
  19783. output[_out++] = output[from++];
  19784. }
  19785. }
  19786. }
  19787. }
  19788. else if ((op & 64) === 0) { /* 2nd level distance code */
  19789. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19790. continue dodist;
  19791. }
  19792. else {
  19793. strm.msg = 'invalid distance code';
  19794. state.mode = BAD;
  19795. break top;
  19796. }
  19797. break; // need to emulate goto via "continue"
  19798. }
  19799. }
  19800. else if ((op & 64) === 0) { /* 2nd level length code */
  19801. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19802. continue dolen;
  19803. }
  19804. else if (op & 32) { /* end-of-block */
  19805. //Tracevv((stderr, "inflate: end of block\n"));
  19806. state.mode = TYPE;
  19807. break top;
  19808. }
  19809. else {
  19810. strm.msg = 'invalid literal/length code';
  19811. state.mode = BAD;
  19812. break top;
  19813. }
  19814. break; // need to emulate goto via "continue"
  19815. }
  19816. } while (_in < last && _out < end);
  19817. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  19818. len = bits >> 3;
  19819. _in -= len;
  19820. bits -= len << 3;
  19821. hold &= (1 << bits) - 1;
  19822. /* update state and return */
  19823. strm.next_in = _in;
  19824. strm.next_out = _out;
  19825. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  19826. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  19827. state.hold = hold;
  19828. state.bits = bits;
  19829. return;
  19830. };
  19831. },{}],74:[function(require,module,exports){
  19832. 'use strict';
  19833. var utils = require('../utils/common');
  19834. var adler32 = require('./adler32');
  19835. var crc32 = require('./crc32');
  19836. var inflate_fast = require('./inffast');
  19837. var inflate_table = require('./inftrees');
  19838. var CODES = 0;
  19839. var LENS = 1;
  19840. var DISTS = 2;
  19841. /* Public constants ==========================================================*/
  19842. /* ===========================================================================*/
  19843. /* Allowed flush values; see deflate() and inflate() below for details */
  19844. //var Z_NO_FLUSH = 0;
  19845. //var Z_PARTIAL_FLUSH = 1;
  19846. //var Z_SYNC_FLUSH = 2;
  19847. //var Z_FULL_FLUSH = 3;
  19848. var Z_FINISH = 4;
  19849. var Z_BLOCK = 5;
  19850. var Z_TREES = 6;
  19851. /* Return codes for the compression/decompression functions. Negative values
  19852. * are errors, positive values are used for special but normal events.
  19853. */
  19854. var Z_OK = 0;
  19855. var Z_STREAM_END = 1;
  19856. var Z_NEED_DICT = 2;
  19857. //var Z_ERRNO = -1;
  19858. var Z_STREAM_ERROR = -2;
  19859. var Z_DATA_ERROR = -3;
  19860. var Z_MEM_ERROR = -4;
  19861. var Z_BUF_ERROR = -5;
  19862. //var Z_VERSION_ERROR = -6;
  19863. /* The deflate compression method */
  19864. var Z_DEFLATED = 8;
  19865. /* STATES ====================================================================*/
  19866. /* ===========================================================================*/
  19867. var HEAD = 1; /* i: waiting for magic header */
  19868. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  19869. var TIME = 3; /* i: waiting for modification time (gzip) */
  19870. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  19871. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  19872. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  19873. var NAME = 7; /* i: waiting for end of file name (gzip) */
  19874. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  19875. var HCRC = 9; /* i: waiting for header crc (gzip) */
  19876. var DICTID = 10; /* i: waiting for dictionary check value */
  19877. var DICT = 11; /* waiting for inflateSetDictionary() call */
  19878. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19879. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  19880. var STORED = 14; /* i: waiting for stored size (length and complement) */
  19881. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  19882. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  19883. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  19884. var LENLENS = 18; /* i: waiting for code length code lengths */
  19885. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  19886. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  19887. var LEN = 21; /* i: waiting for length/lit/eob code */
  19888. var LENEXT = 22; /* i: waiting for length extra bits */
  19889. var DIST = 23; /* i: waiting for distance code */
  19890. var DISTEXT = 24; /* i: waiting for distance extra bits */
  19891. var MATCH = 25; /* o: waiting for output space to copy string */
  19892. var LIT = 26; /* o: waiting for output space to write literal */
  19893. var CHECK = 27; /* i: waiting for 32-bit check value */
  19894. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  19895. var DONE = 29; /* finished check, done -- remain here until reset */
  19896. var BAD = 30; /* got a data error -- remain here until reset */
  19897. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  19898. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  19899. /* ===========================================================================*/
  19900. var ENOUGH_LENS = 852;
  19901. var ENOUGH_DISTS = 592;
  19902. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  19903. var MAX_WBITS = 15;
  19904. /* 32K LZ77 window */
  19905. var DEF_WBITS = MAX_WBITS;
  19906. function ZSWAP32(q) {
  19907. return (((q >>> 24) & 0xff) +
  19908. ((q >>> 8) & 0xff00) +
  19909. ((q & 0xff00) << 8) +
  19910. ((q & 0xff) << 24));
  19911. }
  19912. function InflateState() {
  19913. this.mode = 0; /* current inflate mode */
  19914. this.last = false; /* true if processing last block */
  19915. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  19916. this.havedict = false; /* true if dictionary provided */
  19917. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  19918. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  19919. this.check = 0; /* protected copy of check value */
  19920. this.total = 0; /* protected copy of output count */
  19921. // TODO: may be {}
  19922. this.head = null; /* where to save gzip header information */
  19923. /* sliding window */
  19924. this.wbits = 0; /* log base 2 of requested window size */
  19925. this.wsize = 0; /* window size or zero if not using window */
  19926. this.whave = 0; /* valid bytes in the window */
  19927. this.wnext = 0; /* window write index */
  19928. this.window = null; /* allocated sliding window, if needed */
  19929. /* bit accumulator */
  19930. this.hold = 0; /* input bit accumulator */
  19931. this.bits = 0; /* number of bits in "in" */
  19932. /* for string and stored block copying */
  19933. this.length = 0; /* literal or length of data to copy */
  19934. this.offset = 0; /* distance back to copy string from */
  19935. /* for table and code decoding */
  19936. this.extra = 0; /* extra bits needed */
  19937. /* fixed and dynamic code tables */
  19938. this.lencode = null; /* starting table for length/literal codes */
  19939. this.distcode = null; /* starting table for distance codes */
  19940. this.lenbits = 0; /* index bits for lencode */
  19941. this.distbits = 0; /* index bits for distcode */
  19942. /* dynamic table building */
  19943. this.ncode = 0; /* number of code length code lengths */
  19944. this.nlen = 0; /* number of length code lengths */
  19945. this.ndist = 0; /* number of distance code lengths */
  19946. this.have = 0; /* number of code lengths in lens[] */
  19947. this.next = null; /* next available space in codes[] */
  19948. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  19949. this.work = new utils.Buf16(288); /* work area for code table building */
  19950. /*
  19951. because we don't have pointers in js, we use lencode and distcode directly
  19952. as buffers so we don't need codes
  19953. */
  19954. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  19955. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  19956. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  19957. this.sane = 0; /* if false, allow invalid distance too far */
  19958. this.back = 0; /* bits back of last unprocessed length/lit */
  19959. this.was = 0; /* initial length of match */
  19960. }
  19961. function inflateResetKeep(strm) {
  19962. var state;
  19963. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19964. state = strm.state;
  19965. strm.total_in = strm.total_out = state.total = 0;
  19966. strm.msg = ''; /*Z_NULL*/
  19967. if (state.wrap) { /* to support ill-conceived Java test suite */
  19968. strm.adler = state.wrap & 1;
  19969. }
  19970. state.mode = HEAD;
  19971. state.last = 0;
  19972. state.havedict = 0;
  19973. state.dmax = 32768;
  19974. state.head = null/*Z_NULL*/;
  19975. state.hold = 0;
  19976. state.bits = 0;
  19977. //state.lencode = state.distcode = state.next = state.codes;
  19978. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  19979. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  19980. state.sane = 1;
  19981. state.back = -1;
  19982. //Tracev((stderr, "inflate: reset\n"));
  19983. return Z_OK;
  19984. }
  19985. function inflateReset(strm) {
  19986. var state;
  19987. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19988. state = strm.state;
  19989. state.wsize = 0;
  19990. state.whave = 0;
  19991. state.wnext = 0;
  19992. return inflateResetKeep(strm);
  19993. }
  19994. function inflateReset2(strm, windowBits) {
  19995. var wrap;
  19996. var state;
  19997. /* get the state */
  19998. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19999. state = strm.state;
  20000. /* extract wrap request from windowBits parameter */
  20001. if (windowBits < 0) {
  20002. wrap = 0;
  20003. windowBits = -windowBits;
  20004. }
  20005. else {
  20006. wrap = (windowBits >> 4) + 1;
  20007. if (windowBits < 48) {
  20008. windowBits &= 15;
  20009. }
  20010. }
  20011. /* set number of window bits, free window if different */
  20012. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  20013. return Z_STREAM_ERROR;
  20014. }
  20015. if (state.window !== null && state.wbits !== windowBits) {
  20016. state.window = null;
  20017. }
  20018. /* update state and reset the rest of it */
  20019. state.wrap = wrap;
  20020. state.wbits = windowBits;
  20021. return inflateReset(strm);
  20022. }
  20023. function inflateInit2(strm, windowBits) {
  20024. var ret;
  20025. var state;
  20026. if (!strm) { return Z_STREAM_ERROR; }
  20027. //strm.msg = Z_NULL; /* in case we return an error */
  20028. state = new InflateState();
  20029. //if (state === Z_NULL) return Z_MEM_ERROR;
  20030. //Tracev((stderr, "inflate: allocated\n"));
  20031. strm.state = state;
  20032. state.window = null/*Z_NULL*/;
  20033. ret = inflateReset2(strm, windowBits);
  20034. if (ret !== Z_OK) {
  20035. strm.state = null/*Z_NULL*/;
  20036. }
  20037. return ret;
  20038. }
  20039. function inflateInit(strm) {
  20040. return inflateInit2(strm, DEF_WBITS);
  20041. }
  20042. /*
  20043. Return state with length and distance decoding tables and index sizes set to
  20044. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  20045. If BUILDFIXED is defined, then instead this routine builds the tables the
  20046. first time it's called, and returns those tables the first time and
  20047. thereafter. This reduces the size of the code by about 2K bytes, in
  20048. exchange for a little execution time. However, BUILDFIXED should not be
  20049. used for threaded applications, since the rewriting of the tables and virgin
  20050. may not be thread-safe.
  20051. */
  20052. var virgin = true;
  20053. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  20054. function fixedtables(state) {
  20055. /* build fixed huffman tables if first call (may not be thread safe) */
  20056. if (virgin) {
  20057. var sym;
  20058. lenfix = new utils.Buf32(512);
  20059. distfix = new utils.Buf32(32);
  20060. /* literal/length table */
  20061. sym = 0;
  20062. while (sym < 144) { state.lens[sym++] = 8; }
  20063. while (sym < 256) { state.lens[sym++] = 9; }
  20064. while (sym < 280) { state.lens[sym++] = 7; }
  20065. while (sym < 288) { state.lens[sym++] = 8; }
  20066. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  20067. /* distance table */
  20068. sym = 0;
  20069. while (sym < 32) { state.lens[sym++] = 5; }
  20070. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  20071. /* do this just once */
  20072. virgin = false;
  20073. }
  20074. state.lencode = lenfix;
  20075. state.lenbits = 9;
  20076. state.distcode = distfix;
  20077. state.distbits = 5;
  20078. }
  20079. /*
  20080. Update the window with the last wsize (normally 32K) bytes written before
  20081. returning. If window does not exist yet, create it. This is only called
  20082. when a window is already in use, or when output has been written during this
  20083. inflate call, but the end of the deflate stream has not been reached yet.
  20084. It is also called to create a window for dictionary data when a dictionary
  20085. is loaded.
  20086. Providing output buffers larger than 32K to inflate() should provide a speed
  20087. advantage, since only the last 32K of output is copied to the sliding window
  20088. upon return from inflate(), and since all distances after the first 32K of
  20089. output will fall in the output data, making match copies simpler and faster.
  20090. The advantage may be dependent on the size of the processor's data caches.
  20091. */
  20092. function updatewindow(strm, src, end, copy) {
  20093. var dist;
  20094. var state = strm.state;
  20095. /* if it hasn't been done already, allocate space for the window */
  20096. if (state.window === null) {
  20097. state.wsize = 1 << state.wbits;
  20098. state.wnext = 0;
  20099. state.whave = 0;
  20100. state.window = new utils.Buf8(state.wsize);
  20101. }
  20102. /* copy state->wsize or less output bytes into the circular window */
  20103. if (copy >= state.wsize) {
  20104. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  20105. state.wnext = 0;
  20106. state.whave = state.wsize;
  20107. }
  20108. else {
  20109. dist = state.wsize - state.wnext;
  20110. if (dist > copy) {
  20111. dist = copy;
  20112. }
  20113. //zmemcpy(state->window + state->wnext, end - copy, dist);
  20114. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  20115. copy -= dist;
  20116. if (copy) {
  20117. //zmemcpy(state->window, end - copy, copy);
  20118. utils.arraySet(state.window,src, end - copy, copy, 0);
  20119. state.wnext = copy;
  20120. state.whave = state.wsize;
  20121. }
  20122. else {
  20123. state.wnext += dist;
  20124. if (state.wnext === state.wsize) { state.wnext = 0; }
  20125. if (state.whave < state.wsize) { state.whave += dist; }
  20126. }
  20127. }
  20128. return 0;
  20129. }
  20130. function inflate(strm, flush) {
  20131. var state;
  20132. var input, output; // input/output buffers
  20133. var next; /* next input INDEX */
  20134. var put; /* next output INDEX */
  20135. var have, left; /* available input and output */
  20136. var hold; /* bit buffer */
  20137. var bits; /* bits in bit buffer */
  20138. var _in, _out; /* save starting available input and output */
  20139. var copy; /* number of stored or match bytes to copy */
  20140. var from; /* where to copy match bytes from */
  20141. var from_source;
  20142. var here = 0; /* current decoding table entry */
  20143. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  20144. //var last; /* parent table entry */
  20145. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  20146. var len; /* length to copy for repeats, bits to drop */
  20147. var ret; /* return code */
  20148. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  20149. var opts;
  20150. var n; // temporary var for NEED_BITS
  20151. var order = /* permutation of code lengths */
  20152. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  20153. if (!strm || !strm.state || !strm.output ||
  20154. (!strm.input && strm.avail_in !== 0)) {
  20155. return Z_STREAM_ERROR;
  20156. }
  20157. state = strm.state;
  20158. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  20159. //--- LOAD() ---
  20160. put = strm.next_out;
  20161. output = strm.output;
  20162. left = strm.avail_out;
  20163. next = strm.next_in;
  20164. input = strm.input;
  20165. have = strm.avail_in;
  20166. hold = state.hold;
  20167. bits = state.bits;
  20168. //---
  20169. _in = have;
  20170. _out = left;
  20171. ret = Z_OK;
  20172. inf_leave: // goto emulation
  20173. for (;;) {
  20174. switch (state.mode) {
  20175. case HEAD:
  20176. if (state.wrap === 0) {
  20177. state.mode = TYPEDO;
  20178. break;
  20179. }
  20180. //=== NEEDBITS(16);
  20181. while (bits < 16) {
  20182. if (have === 0) { break inf_leave; }
  20183. have--;
  20184. hold += input[next++] << bits;
  20185. bits += 8;
  20186. }
  20187. //===//
  20188. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  20189. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  20190. //=== CRC2(state.check, hold);
  20191. hbuf[0] = hold & 0xff;
  20192. hbuf[1] = (hold >>> 8) & 0xff;
  20193. state.check = crc32(state.check, hbuf, 2, 0);
  20194. //===//
  20195. //=== INITBITS();
  20196. hold = 0;
  20197. bits = 0;
  20198. //===//
  20199. state.mode = FLAGS;
  20200. break;
  20201. }
  20202. state.flags = 0; /* expect zlib header */
  20203. if (state.head) {
  20204. state.head.done = false;
  20205. }
  20206. if (!(state.wrap & 1) || /* check if zlib header allowed */
  20207. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  20208. strm.msg = 'incorrect header check';
  20209. state.mode = BAD;
  20210. break;
  20211. }
  20212. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  20213. strm.msg = 'unknown compression method';
  20214. state.mode = BAD;
  20215. break;
  20216. }
  20217. //--- DROPBITS(4) ---//
  20218. hold >>>= 4;
  20219. bits -= 4;
  20220. //---//
  20221. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  20222. if (state.wbits === 0) {
  20223. state.wbits = len;
  20224. }
  20225. else if (len > state.wbits) {
  20226. strm.msg = 'invalid window size';
  20227. state.mode = BAD;
  20228. break;
  20229. }
  20230. state.dmax = 1 << len;
  20231. //Tracev((stderr, "inflate: zlib header ok\n"));
  20232. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20233. state.mode = hold & 0x200 ? DICTID : TYPE;
  20234. //=== INITBITS();
  20235. hold = 0;
  20236. bits = 0;
  20237. //===//
  20238. break;
  20239. case FLAGS:
  20240. //=== NEEDBITS(16); */
  20241. while (bits < 16) {
  20242. if (have === 0) { break inf_leave; }
  20243. have--;
  20244. hold += input[next++] << bits;
  20245. bits += 8;
  20246. }
  20247. //===//
  20248. state.flags = hold;
  20249. if ((state.flags & 0xff) !== Z_DEFLATED) {
  20250. strm.msg = 'unknown compression method';
  20251. state.mode = BAD;
  20252. break;
  20253. }
  20254. if (state.flags & 0xe000) {
  20255. strm.msg = 'unknown header flags set';
  20256. state.mode = BAD;
  20257. break;
  20258. }
  20259. if (state.head) {
  20260. state.head.text = ((hold >> 8) & 1);
  20261. }
  20262. if (state.flags & 0x0200) {
  20263. //=== CRC2(state.check, hold);
  20264. hbuf[0] = hold & 0xff;
  20265. hbuf[1] = (hold >>> 8) & 0xff;
  20266. state.check = crc32(state.check, hbuf, 2, 0);
  20267. //===//
  20268. }
  20269. //=== INITBITS();
  20270. hold = 0;
  20271. bits = 0;
  20272. //===//
  20273. state.mode = TIME;
  20274. /* falls through */
  20275. case TIME:
  20276. //=== NEEDBITS(32); */
  20277. while (bits < 32) {
  20278. if (have === 0) { break inf_leave; }
  20279. have--;
  20280. hold += input[next++] << bits;
  20281. bits += 8;
  20282. }
  20283. //===//
  20284. if (state.head) {
  20285. state.head.time = hold;
  20286. }
  20287. if (state.flags & 0x0200) {
  20288. //=== CRC4(state.check, hold)
  20289. hbuf[0] = hold & 0xff;
  20290. hbuf[1] = (hold >>> 8) & 0xff;
  20291. hbuf[2] = (hold >>> 16) & 0xff;
  20292. hbuf[3] = (hold >>> 24) & 0xff;
  20293. state.check = crc32(state.check, hbuf, 4, 0);
  20294. //===
  20295. }
  20296. //=== INITBITS();
  20297. hold = 0;
  20298. bits = 0;
  20299. //===//
  20300. state.mode = OS;
  20301. /* falls through */
  20302. case OS:
  20303. //=== NEEDBITS(16); */
  20304. while (bits < 16) {
  20305. if (have === 0) { break inf_leave; }
  20306. have--;
  20307. hold += input[next++] << bits;
  20308. bits += 8;
  20309. }
  20310. //===//
  20311. if (state.head) {
  20312. state.head.xflags = (hold & 0xff);
  20313. state.head.os = (hold >> 8);
  20314. }
  20315. if (state.flags & 0x0200) {
  20316. //=== CRC2(state.check, hold);
  20317. hbuf[0] = hold & 0xff;
  20318. hbuf[1] = (hold >>> 8) & 0xff;
  20319. state.check = crc32(state.check, hbuf, 2, 0);
  20320. //===//
  20321. }
  20322. //=== INITBITS();
  20323. hold = 0;
  20324. bits = 0;
  20325. //===//
  20326. state.mode = EXLEN;
  20327. /* falls through */
  20328. case EXLEN:
  20329. if (state.flags & 0x0400) {
  20330. //=== NEEDBITS(16); */
  20331. while (bits < 16) {
  20332. if (have === 0) { break inf_leave; }
  20333. have--;
  20334. hold += input[next++] << bits;
  20335. bits += 8;
  20336. }
  20337. //===//
  20338. state.length = hold;
  20339. if (state.head) {
  20340. state.head.extra_len = hold;
  20341. }
  20342. if (state.flags & 0x0200) {
  20343. //=== CRC2(state.check, hold);
  20344. hbuf[0] = hold & 0xff;
  20345. hbuf[1] = (hold >>> 8) & 0xff;
  20346. state.check = crc32(state.check, hbuf, 2, 0);
  20347. //===//
  20348. }
  20349. //=== INITBITS();
  20350. hold = 0;
  20351. bits = 0;
  20352. //===//
  20353. }
  20354. else if (state.head) {
  20355. state.head.extra = null/*Z_NULL*/;
  20356. }
  20357. state.mode = EXTRA;
  20358. /* falls through */
  20359. case EXTRA:
  20360. if (state.flags & 0x0400) {
  20361. copy = state.length;
  20362. if (copy > have) { copy = have; }
  20363. if (copy) {
  20364. if (state.head) {
  20365. len = state.head.extra_len - state.length;
  20366. if (!state.head.extra) {
  20367. // Use untyped array for more conveniend processing later
  20368. state.head.extra = new Array(state.head.extra_len);
  20369. }
  20370. utils.arraySet(
  20371. state.head.extra,
  20372. input,
  20373. next,
  20374. // extra field is limited to 65536 bytes
  20375. // - no need for additional size check
  20376. copy,
  20377. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  20378. len
  20379. );
  20380. //zmemcpy(state.head.extra + len, next,
  20381. // len + copy > state.head.extra_max ?
  20382. // state.head.extra_max - len : copy);
  20383. }
  20384. if (state.flags & 0x0200) {
  20385. state.check = crc32(state.check, input, copy, next);
  20386. }
  20387. have -= copy;
  20388. next += copy;
  20389. state.length -= copy;
  20390. }
  20391. if (state.length) { break inf_leave; }
  20392. }
  20393. state.length = 0;
  20394. state.mode = NAME;
  20395. /* falls through */
  20396. case NAME:
  20397. if (state.flags & 0x0800) {
  20398. if (have === 0) { break inf_leave; }
  20399. copy = 0;
  20400. do {
  20401. // TODO: 2 or 1 bytes?
  20402. len = input[next + copy++];
  20403. /* use constant limit because in js we should not preallocate memory */
  20404. if (state.head && len &&
  20405. (state.length < 65536 /*state.head.name_max*/)) {
  20406. state.head.name += String.fromCharCode(len);
  20407. }
  20408. } while (len && copy < have);
  20409. if (state.flags & 0x0200) {
  20410. state.check = crc32(state.check, input, copy, next);
  20411. }
  20412. have -= copy;
  20413. next += copy;
  20414. if (len) { break inf_leave; }
  20415. }
  20416. else if (state.head) {
  20417. state.head.name = null;
  20418. }
  20419. state.length = 0;
  20420. state.mode = COMMENT;
  20421. /* falls through */
  20422. case COMMENT:
  20423. if (state.flags & 0x1000) {
  20424. if (have === 0) { break inf_leave; }
  20425. copy = 0;
  20426. do {
  20427. len = input[next + copy++];
  20428. /* use constant limit because in js we should not preallocate memory */
  20429. if (state.head && len &&
  20430. (state.length < 65536 /*state.head.comm_max*/)) {
  20431. state.head.comment += String.fromCharCode(len);
  20432. }
  20433. } while (len && copy < have);
  20434. if (state.flags & 0x0200) {
  20435. state.check = crc32(state.check, input, copy, next);
  20436. }
  20437. have -= copy;
  20438. next += copy;
  20439. if (len) { break inf_leave; }
  20440. }
  20441. else if (state.head) {
  20442. state.head.comment = null;
  20443. }
  20444. state.mode = HCRC;
  20445. /* falls through */
  20446. case HCRC:
  20447. if (state.flags & 0x0200) {
  20448. //=== NEEDBITS(16); */
  20449. while (bits < 16) {
  20450. if (have === 0) { break inf_leave; }
  20451. have--;
  20452. hold += input[next++] << bits;
  20453. bits += 8;
  20454. }
  20455. //===//
  20456. if (hold !== (state.check & 0xffff)) {
  20457. strm.msg = 'header crc mismatch';
  20458. state.mode = BAD;
  20459. break;
  20460. }
  20461. //=== INITBITS();
  20462. hold = 0;
  20463. bits = 0;
  20464. //===//
  20465. }
  20466. if (state.head) {
  20467. state.head.hcrc = ((state.flags >> 9) & 1);
  20468. state.head.done = true;
  20469. }
  20470. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  20471. state.mode = TYPE;
  20472. break;
  20473. case DICTID:
  20474. //=== NEEDBITS(32); */
  20475. while (bits < 32) {
  20476. if (have === 0) { break inf_leave; }
  20477. have--;
  20478. hold += input[next++] << bits;
  20479. bits += 8;
  20480. }
  20481. //===//
  20482. strm.adler = state.check = ZSWAP32(hold);
  20483. //=== INITBITS();
  20484. hold = 0;
  20485. bits = 0;
  20486. //===//
  20487. state.mode = DICT;
  20488. /* falls through */
  20489. case DICT:
  20490. if (state.havedict === 0) {
  20491. //--- RESTORE() ---
  20492. strm.next_out = put;
  20493. strm.avail_out = left;
  20494. strm.next_in = next;
  20495. strm.avail_in = have;
  20496. state.hold = hold;
  20497. state.bits = bits;
  20498. //---
  20499. return Z_NEED_DICT;
  20500. }
  20501. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20502. state.mode = TYPE;
  20503. /* falls through */
  20504. case TYPE:
  20505. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  20506. /* falls through */
  20507. case TYPEDO:
  20508. if (state.last) {
  20509. //--- BYTEBITS() ---//
  20510. hold >>>= bits & 7;
  20511. bits -= bits & 7;
  20512. //---//
  20513. state.mode = CHECK;
  20514. break;
  20515. }
  20516. //=== NEEDBITS(3); */
  20517. while (bits < 3) {
  20518. if (have === 0) { break inf_leave; }
  20519. have--;
  20520. hold += input[next++] << bits;
  20521. bits += 8;
  20522. }
  20523. //===//
  20524. state.last = (hold & 0x01)/*BITS(1)*/;
  20525. //--- DROPBITS(1) ---//
  20526. hold >>>= 1;
  20527. bits -= 1;
  20528. //---//
  20529. switch ((hold & 0x03)/*BITS(2)*/) {
  20530. case 0: /* stored block */
  20531. //Tracev((stderr, "inflate: stored block%s\n",
  20532. // state.last ? " (last)" : ""));
  20533. state.mode = STORED;
  20534. break;
  20535. case 1: /* fixed block */
  20536. fixedtables(state);
  20537. //Tracev((stderr, "inflate: fixed codes block%s\n",
  20538. // state.last ? " (last)" : ""));
  20539. state.mode = LEN_; /* decode codes */
  20540. if (flush === Z_TREES) {
  20541. //--- DROPBITS(2) ---//
  20542. hold >>>= 2;
  20543. bits -= 2;
  20544. //---//
  20545. break inf_leave;
  20546. }
  20547. break;
  20548. case 2: /* dynamic block */
  20549. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  20550. // state.last ? " (last)" : ""));
  20551. state.mode = TABLE;
  20552. break;
  20553. case 3:
  20554. strm.msg = 'invalid block type';
  20555. state.mode = BAD;
  20556. }
  20557. //--- DROPBITS(2) ---//
  20558. hold >>>= 2;
  20559. bits -= 2;
  20560. //---//
  20561. break;
  20562. case STORED:
  20563. //--- BYTEBITS() ---// /* go to byte boundary */
  20564. hold >>>= bits & 7;
  20565. bits -= bits & 7;
  20566. //---//
  20567. //=== NEEDBITS(32); */
  20568. while (bits < 32) {
  20569. if (have === 0) { break inf_leave; }
  20570. have--;
  20571. hold += input[next++] << bits;
  20572. bits += 8;
  20573. }
  20574. //===//
  20575. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  20576. strm.msg = 'invalid stored block lengths';
  20577. state.mode = BAD;
  20578. break;
  20579. }
  20580. state.length = hold & 0xffff;
  20581. //Tracev((stderr, "inflate: stored length %u\n",
  20582. // state.length));
  20583. //=== INITBITS();
  20584. hold = 0;
  20585. bits = 0;
  20586. //===//
  20587. state.mode = COPY_;
  20588. if (flush === Z_TREES) { break inf_leave; }
  20589. /* falls through */
  20590. case COPY_:
  20591. state.mode = COPY;
  20592. /* falls through */
  20593. case COPY:
  20594. copy = state.length;
  20595. if (copy) {
  20596. if (copy > have) { copy = have; }
  20597. if (copy > left) { copy = left; }
  20598. if (copy === 0) { break inf_leave; }
  20599. //--- zmemcpy(put, next, copy); ---
  20600. utils.arraySet(output, input, next, copy, put);
  20601. //---//
  20602. have -= copy;
  20603. next += copy;
  20604. left -= copy;
  20605. put += copy;
  20606. state.length -= copy;
  20607. break;
  20608. }
  20609. //Tracev((stderr, "inflate: stored end\n"));
  20610. state.mode = TYPE;
  20611. break;
  20612. case TABLE:
  20613. //=== NEEDBITS(14); */
  20614. while (bits < 14) {
  20615. if (have === 0) { break inf_leave; }
  20616. have--;
  20617. hold += input[next++] << bits;
  20618. bits += 8;
  20619. }
  20620. //===//
  20621. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  20622. //--- DROPBITS(5) ---//
  20623. hold >>>= 5;
  20624. bits -= 5;
  20625. //---//
  20626. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  20627. //--- DROPBITS(5) ---//
  20628. hold >>>= 5;
  20629. bits -= 5;
  20630. //---//
  20631. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  20632. //--- DROPBITS(4) ---//
  20633. hold >>>= 4;
  20634. bits -= 4;
  20635. //---//
  20636. //#ifndef PKZIP_BUG_WORKAROUND
  20637. if (state.nlen > 286 || state.ndist > 30) {
  20638. strm.msg = 'too many length or distance symbols';
  20639. state.mode = BAD;
  20640. break;
  20641. }
  20642. //#endif
  20643. //Tracev((stderr, "inflate: table sizes ok\n"));
  20644. state.have = 0;
  20645. state.mode = LENLENS;
  20646. /* falls through */
  20647. case LENLENS:
  20648. while (state.have < state.ncode) {
  20649. //=== NEEDBITS(3);
  20650. while (bits < 3) {
  20651. if (have === 0) { break inf_leave; }
  20652. have--;
  20653. hold += input[next++] << bits;
  20654. bits += 8;
  20655. }
  20656. //===//
  20657. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  20658. //--- DROPBITS(3) ---//
  20659. hold >>>= 3;
  20660. bits -= 3;
  20661. //---//
  20662. }
  20663. while (state.have < 19) {
  20664. state.lens[order[state.have++]] = 0;
  20665. }
  20666. // We have separate tables & no pointers. 2 commented lines below not needed.
  20667. //state.next = state.codes;
  20668. //state.lencode = state.next;
  20669. // Switch to use dynamic table
  20670. state.lencode = state.lendyn;
  20671. state.lenbits = 7;
  20672. opts = {bits: state.lenbits};
  20673. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  20674. state.lenbits = opts.bits;
  20675. if (ret) {
  20676. strm.msg = 'invalid code lengths set';
  20677. state.mode = BAD;
  20678. break;
  20679. }
  20680. //Tracev((stderr, "inflate: code lengths ok\n"));
  20681. state.have = 0;
  20682. state.mode = CODELENS;
  20683. /* falls through */
  20684. case CODELENS:
  20685. while (state.have < state.nlen + state.ndist) {
  20686. for (;;) {
  20687. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  20688. here_bits = here >>> 24;
  20689. here_op = (here >>> 16) & 0xff;
  20690. here_val = here & 0xffff;
  20691. if ((here_bits) <= bits) { break; }
  20692. //--- PULLBYTE() ---//
  20693. if (have === 0) { break inf_leave; }
  20694. have--;
  20695. hold += input[next++] << bits;
  20696. bits += 8;
  20697. //---//
  20698. }
  20699. if (here_val < 16) {
  20700. //--- DROPBITS(here.bits) ---//
  20701. hold >>>= here_bits;
  20702. bits -= here_bits;
  20703. //---//
  20704. state.lens[state.have++] = here_val;
  20705. }
  20706. else {
  20707. if (here_val === 16) {
  20708. //=== NEEDBITS(here.bits + 2);
  20709. n = here_bits + 2;
  20710. while (bits < n) {
  20711. if (have === 0) { break inf_leave; }
  20712. have--;
  20713. hold += input[next++] << bits;
  20714. bits += 8;
  20715. }
  20716. //===//
  20717. //--- DROPBITS(here.bits) ---//
  20718. hold >>>= here_bits;
  20719. bits -= here_bits;
  20720. //---//
  20721. if (state.have === 0) {
  20722. strm.msg = 'invalid bit length repeat';
  20723. state.mode = BAD;
  20724. break;
  20725. }
  20726. len = state.lens[state.have - 1];
  20727. copy = 3 + (hold & 0x03);//BITS(2);
  20728. //--- DROPBITS(2) ---//
  20729. hold >>>= 2;
  20730. bits -= 2;
  20731. //---//
  20732. }
  20733. else if (here_val === 17) {
  20734. //=== NEEDBITS(here.bits + 3);
  20735. n = here_bits + 3;
  20736. while (bits < n) {
  20737. if (have === 0) { break inf_leave; }
  20738. have--;
  20739. hold += input[next++] << bits;
  20740. bits += 8;
  20741. }
  20742. //===//
  20743. //--- DROPBITS(here.bits) ---//
  20744. hold >>>= here_bits;
  20745. bits -= here_bits;
  20746. //---//
  20747. len = 0;
  20748. copy = 3 + (hold & 0x07);//BITS(3);
  20749. //--- DROPBITS(3) ---//
  20750. hold >>>= 3;
  20751. bits -= 3;
  20752. //---//
  20753. }
  20754. else {
  20755. //=== NEEDBITS(here.bits + 7);
  20756. n = here_bits + 7;
  20757. while (bits < n) {
  20758. if (have === 0) { break inf_leave; }
  20759. have--;
  20760. hold += input[next++] << bits;
  20761. bits += 8;
  20762. }
  20763. //===//
  20764. //--- DROPBITS(here.bits) ---//
  20765. hold >>>= here_bits;
  20766. bits -= here_bits;
  20767. //---//
  20768. len = 0;
  20769. copy = 11 + (hold & 0x7f);//BITS(7);
  20770. //--- DROPBITS(7) ---//
  20771. hold >>>= 7;
  20772. bits -= 7;
  20773. //---//
  20774. }
  20775. if (state.have + copy > state.nlen + state.ndist) {
  20776. strm.msg = 'invalid bit length repeat';
  20777. state.mode = BAD;
  20778. break;
  20779. }
  20780. while (copy--) {
  20781. state.lens[state.have++] = len;
  20782. }
  20783. }
  20784. }
  20785. /* handle error breaks in while */
  20786. if (state.mode === BAD) { break; }
  20787. /* check for end-of-block code (better have one) */
  20788. if (state.lens[256] === 0) {
  20789. strm.msg = 'invalid code -- missing end-of-block';
  20790. state.mode = BAD;
  20791. break;
  20792. }
  20793. /* build code tables -- note: do not change the lenbits or distbits
  20794. values here (9 and 6) without reading the comments in inftrees.h
  20795. concerning the ENOUGH constants, which depend on those values */
  20796. state.lenbits = 9;
  20797. opts = {bits: state.lenbits};
  20798. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  20799. // We have separate tables & no pointers. 2 commented lines below not needed.
  20800. // state.next_index = opts.table_index;
  20801. state.lenbits = opts.bits;
  20802. // state.lencode = state.next;
  20803. if (ret) {
  20804. strm.msg = 'invalid literal/lengths set';
  20805. state.mode = BAD;
  20806. break;
  20807. }
  20808. state.distbits = 6;
  20809. //state.distcode.copy(state.codes);
  20810. // Switch to use dynamic table
  20811. state.distcode = state.distdyn;
  20812. opts = {bits: state.distbits};
  20813. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  20814. // We have separate tables & no pointers. 2 commented lines below not needed.
  20815. // state.next_index = opts.table_index;
  20816. state.distbits = opts.bits;
  20817. // state.distcode = state.next;
  20818. if (ret) {
  20819. strm.msg = 'invalid distances set';
  20820. state.mode = BAD;
  20821. break;
  20822. }
  20823. //Tracev((stderr, 'inflate: codes ok\n'));
  20824. state.mode = LEN_;
  20825. if (flush === Z_TREES) { break inf_leave; }
  20826. /* falls through */
  20827. case LEN_:
  20828. state.mode = LEN;
  20829. /* falls through */
  20830. case LEN:
  20831. if (have >= 6 && left >= 258) {
  20832. //--- RESTORE() ---
  20833. strm.next_out = put;
  20834. strm.avail_out = left;
  20835. strm.next_in = next;
  20836. strm.avail_in = have;
  20837. state.hold = hold;
  20838. state.bits = bits;
  20839. //---
  20840. inflate_fast(strm, _out);
  20841. //--- LOAD() ---
  20842. put = strm.next_out;
  20843. output = strm.output;
  20844. left = strm.avail_out;
  20845. next = strm.next_in;
  20846. input = strm.input;
  20847. have = strm.avail_in;
  20848. hold = state.hold;
  20849. bits = state.bits;
  20850. //---
  20851. if (state.mode === TYPE) {
  20852. state.back = -1;
  20853. }
  20854. break;
  20855. }
  20856. state.back = 0;
  20857. for (;;) {
  20858. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  20859. here_bits = here >>> 24;
  20860. here_op = (here >>> 16) & 0xff;
  20861. here_val = here & 0xffff;
  20862. if (here_bits <= bits) { break; }
  20863. //--- PULLBYTE() ---//
  20864. if (have === 0) { break inf_leave; }
  20865. have--;
  20866. hold += input[next++] << bits;
  20867. bits += 8;
  20868. //---//
  20869. }
  20870. if (here_op && (here_op & 0xf0) === 0) {
  20871. last_bits = here_bits;
  20872. last_op = here_op;
  20873. last_val = here_val;
  20874. for (;;) {
  20875. here = state.lencode[last_val +
  20876. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20877. here_bits = here >>> 24;
  20878. here_op = (here >>> 16) & 0xff;
  20879. here_val = here & 0xffff;
  20880. if ((last_bits + here_bits) <= bits) { break; }
  20881. //--- PULLBYTE() ---//
  20882. if (have === 0) { break inf_leave; }
  20883. have--;
  20884. hold += input[next++] << bits;
  20885. bits += 8;
  20886. //---//
  20887. }
  20888. //--- DROPBITS(last.bits) ---//
  20889. hold >>>= last_bits;
  20890. bits -= last_bits;
  20891. //---//
  20892. state.back += last_bits;
  20893. }
  20894. //--- DROPBITS(here.bits) ---//
  20895. hold >>>= here_bits;
  20896. bits -= here_bits;
  20897. //---//
  20898. state.back += here_bits;
  20899. state.length = here_val;
  20900. if (here_op === 0) {
  20901. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  20902. // "inflate: literal '%c'\n" :
  20903. // "inflate: literal 0x%02x\n", here.val));
  20904. state.mode = LIT;
  20905. break;
  20906. }
  20907. if (here_op & 32) {
  20908. //Tracevv((stderr, "inflate: end of block\n"));
  20909. state.back = -1;
  20910. state.mode = TYPE;
  20911. break;
  20912. }
  20913. if (here_op & 64) {
  20914. strm.msg = 'invalid literal/length code';
  20915. state.mode = BAD;
  20916. break;
  20917. }
  20918. state.extra = here_op & 15;
  20919. state.mode = LENEXT;
  20920. /* falls through */
  20921. case LENEXT:
  20922. if (state.extra) {
  20923. //=== NEEDBITS(state.extra);
  20924. n = state.extra;
  20925. while (bits < n) {
  20926. if (have === 0) { break inf_leave; }
  20927. have--;
  20928. hold += input[next++] << bits;
  20929. bits += 8;
  20930. }
  20931. //===//
  20932. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20933. //--- DROPBITS(state.extra) ---//
  20934. hold >>>= state.extra;
  20935. bits -= state.extra;
  20936. //---//
  20937. state.back += state.extra;
  20938. }
  20939. //Tracevv((stderr, "inflate: length %u\n", state.length));
  20940. state.was = state.length;
  20941. state.mode = DIST;
  20942. /* falls through */
  20943. case DIST:
  20944. for (;;) {
  20945. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  20946. here_bits = here >>> 24;
  20947. here_op = (here >>> 16) & 0xff;
  20948. here_val = here & 0xffff;
  20949. if ((here_bits) <= bits) { break; }
  20950. //--- PULLBYTE() ---//
  20951. if (have === 0) { break inf_leave; }
  20952. have--;
  20953. hold += input[next++] << bits;
  20954. bits += 8;
  20955. //---//
  20956. }
  20957. if ((here_op & 0xf0) === 0) {
  20958. last_bits = here_bits;
  20959. last_op = here_op;
  20960. last_val = here_val;
  20961. for (;;) {
  20962. here = state.distcode[last_val +
  20963. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20964. here_bits = here >>> 24;
  20965. here_op = (here >>> 16) & 0xff;
  20966. here_val = here & 0xffff;
  20967. if ((last_bits + here_bits) <= bits) { break; }
  20968. //--- PULLBYTE() ---//
  20969. if (have === 0) { break inf_leave; }
  20970. have--;
  20971. hold += input[next++] << bits;
  20972. bits += 8;
  20973. //---//
  20974. }
  20975. //--- DROPBITS(last.bits) ---//
  20976. hold >>>= last_bits;
  20977. bits -= last_bits;
  20978. //---//
  20979. state.back += last_bits;
  20980. }
  20981. //--- DROPBITS(here.bits) ---//
  20982. hold >>>= here_bits;
  20983. bits -= here_bits;
  20984. //---//
  20985. state.back += here_bits;
  20986. if (here_op & 64) {
  20987. strm.msg = 'invalid distance code';
  20988. state.mode = BAD;
  20989. break;
  20990. }
  20991. state.offset = here_val;
  20992. state.extra = (here_op) & 15;
  20993. state.mode = DISTEXT;
  20994. /* falls through */
  20995. case DISTEXT:
  20996. if (state.extra) {
  20997. //=== NEEDBITS(state.extra);
  20998. n = state.extra;
  20999. while (bits < n) {
  21000. if (have === 0) { break inf_leave; }
  21001. have--;
  21002. hold += input[next++] << bits;
  21003. bits += 8;
  21004. }
  21005. //===//
  21006. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  21007. //--- DROPBITS(state.extra) ---//
  21008. hold >>>= state.extra;
  21009. bits -= state.extra;
  21010. //---//
  21011. state.back += state.extra;
  21012. }
  21013. //#ifdef INFLATE_STRICT
  21014. if (state.offset > state.dmax) {
  21015. strm.msg = 'invalid distance too far back';
  21016. state.mode = BAD;
  21017. break;
  21018. }
  21019. //#endif
  21020. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  21021. state.mode = MATCH;
  21022. /* falls through */
  21023. case MATCH:
  21024. if (left === 0) { break inf_leave; }
  21025. copy = _out - left;
  21026. if (state.offset > copy) { /* copy from window */
  21027. copy = state.offset - copy;
  21028. if (copy > state.whave) {
  21029. if (state.sane) {
  21030. strm.msg = 'invalid distance too far back';
  21031. state.mode = BAD;
  21032. break;
  21033. }
  21034. // (!) This block is disabled in zlib defailts,
  21035. // don't enable it for binary compatibility
  21036. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  21037. // Trace((stderr, "inflate.c too far\n"));
  21038. // copy -= state.whave;
  21039. // if (copy > state.length) { copy = state.length; }
  21040. // if (copy > left) { copy = left; }
  21041. // left -= copy;
  21042. // state.length -= copy;
  21043. // do {
  21044. // output[put++] = 0;
  21045. // } while (--copy);
  21046. // if (state.length === 0) { state.mode = LEN; }
  21047. // break;
  21048. //#endif
  21049. }
  21050. if (copy > state.wnext) {
  21051. copy -= state.wnext;
  21052. from = state.wsize - copy;
  21053. }
  21054. else {
  21055. from = state.wnext - copy;
  21056. }
  21057. if (copy > state.length) { copy = state.length; }
  21058. from_source = state.window;
  21059. }
  21060. else { /* copy from output */
  21061. from_source = output;
  21062. from = put - state.offset;
  21063. copy = state.length;
  21064. }
  21065. if (copy > left) { copy = left; }
  21066. left -= copy;
  21067. state.length -= copy;
  21068. do {
  21069. output[put++] = from_source[from++];
  21070. } while (--copy);
  21071. if (state.length === 0) { state.mode = LEN; }
  21072. break;
  21073. case LIT:
  21074. if (left === 0) { break inf_leave; }
  21075. output[put++] = state.length;
  21076. left--;
  21077. state.mode = LEN;
  21078. break;
  21079. case CHECK:
  21080. if (state.wrap) {
  21081. //=== NEEDBITS(32);
  21082. while (bits < 32) {
  21083. if (have === 0) { break inf_leave; }
  21084. have--;
  21085. // Use '|' insdead of '+' to make sure that result is signed
  21086. hold |= input[next++] << bits;
  21087. bits += 8;
  21088. }
  21089. //===//
  21090. _out -= left;
  21091. strm.total_out += _out;
  21092. state.total += _out;
  21093. if (_out) {
  21094. strm.adler = state.check =
  21095. /*UPDATE(state.check, put - _out, _out);*/
  21096. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  21097. }
  21098. _out = left;
  21099. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  21100. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  21101. strm.msg = 'incorrect data check';
  21102. state.mode = BAD;
  21103. break;
  21104. }
  21105. //=== INITBITS();
  21106. hold = 0;
  21107. bits = 0;
  21108. //===//
  21109. //Tracev((stderr, "inflate: check matches trailer\n"));
  21110. }
  21111. state.mode = LENGTH;
  21112. /* falls through */
  21113. case LENGTH:
  21114. if (state.wrap && state.flags) {
  21115. //=== NEEDBITS(32);
  21116. while (bits < 32) {
  21117. if (have === 0) { break inf_leave; }
  21118. have--;
  21119. hold += input[next++] << bits;
  21120. bits += 8;
  21121. }
  21122. //===//
  21123. if (hold !== (state.total & 0xffffffff)) {
  21124. strm.msg = 'incorrect length check';
  21125. state.mode = BAD;
  21126. break;
  21127. }
  21128. //=== INITBITS();
  21129. hold = 0;
  21130. bits = 0;
  21131. //===//
  21132. //Tracev((stderr, "inflate: length matches trailer\n"));
  21133. }
  21134. state.mode = DONE;
  21135. /* falls through */
  21136. case DONE:
  21137. ret = Z_STREAM_END;
  21138. break inf_leave;
  21139. case BAD:
  21140. ret = Z_DATA_ERROR;
  21141. break inf_leave;
  21142. case MEM:
  21143. return Z_MEM_ERROR;
  21144. case SYNC:
  21145. /* falls through */
  21146. default:
  21147. return Z_STREAM_ERROR;
  21148. }
  21149. }
  21150. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  21151. /*
  21152. Return from inflate(), updating the total counts and the check value.
  21153. If there was no progress during the inflate() call, return a buffer
  21154. error. Call updatewindow() to create and/or update the window state.
  21155. Note: a memory error from inflate() is non-recoverable.
  21156. */
  21157. //--- RESTORE() ---
  21158. strm.next_out = put;
  21159. strm.avail_out = left;
  21160. strm.next_in = next;
  21161. strm.avail_in = have;
  21162. state.hold = hold;
  21163. state.bits = bits;
  21164. //---
  21165. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  21166. (state.mode < CHECK || flush !== Z_FINISH))) {
  21167. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  21168. state.mode = MEM;
  21169. return Z_MEM_ERROR;
  21170. }
  21171. }
  21172. _in -= strm.avail_in;
  21173. _out -= strm.avail_out;
  21174. strm.total_in += _in;
  21175. strm.total_out += _out;
  21176. state.total += _out;
  21177. if (state.wrap && _out) {
  21178. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  21179. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  21180. }
  21181. strm.data_type = state.bits + (state.last ? 64 : 0) +
  21182. (state.mode === TYPE ? 128 : 0) +
  21183. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  21184. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  21185. ret = Z_BUF_ERROR;
  21186. }
  21187. return ret;
  21188. }
  21189. function inflateEnd(strm) {
  21190. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  21191. return Z_STREAM_ERROR;
  21192. }
  21193. var state = strm.state;
  21194. if (state.window) {
  21195. state.window = null;
  21196. }
  21197. strm.state = null;
  21198. return Z_OK;
  21199. }
  21200. function inflateGetHeader(strm, head) {
  21201. var state;
  21202. /* check state */
  21203. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21204. state = strm.state;
  21205. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  21206. /* save header structure */
  21207. state.head = head;
  21208. head.done = false;
  21209. return Z_OK;
  21210. }
  21211. exports.inflateReset = inflateReset;
  21212. exports.inflateReset2 = inflateReset2;
  21213. exports.inflateResetKeep = inflateResetKeep;
  21214. exports.inflateInit = inflateInit;
  21215. exports.inflateInit2 = inflateInit2;
  21216. exports.inflate = inflate;
  21217. exports.inflateEnd = inflateEnd;
  21218. exports.inflateGetHeader = inflateGetHeader;
  21219. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  21220. /* Not implemented
  21221. exports.inflateCopy = inflateCopy;
  21222. exports.inflateGetDictionary = inflateGetDictionary;
  21223. exports.inflateMark = inflateMark;
  21224. exports.inflatePrime = inflatePrime;
  21225. exports.inflateSetDictionary = inflateSetDictionary;
  21226. exports.inflateSync = inflateSync;
  21227. exports.inflateSyncPoint = inflateSyncPoint;
  21228. exports.inflateUndermine = inflateUndermine;
  21229. */
  21230. },{"../utils/common":66,"./adler32":68,"./crc32":70,"./inffast":73,"./inftrees":75}],75:[function(require,module,exports){
  21231. 'use strict';
  21232. var utils = require('../utils/common');
  21233. var MAXBITS = 15;
  21234. var ENOUGH_LENS = 852;
  21235. var ENOUGH_DISTS = 592;
  21236. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  21237. var CODES = 0;
  21238. var LENS = 1;
  21239. var DISTS = 2;
  21240. var lbase = [ /* Length codes 257..285 base */
  21241. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  21242. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  21243. ];
  21244. var lext = [ /* Length codes 257..285 extra */
  21245. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  21246. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  21247. ];
  21248. var dbase = [ /* Distance codes 0..29 base */
  21249. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  21250. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  21251. 8193, 12289, 16385, 24577, 0, 0
  21252. ];
  21253. var dext = [ /* Distance codes 0..29 extra */
  21254. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  21255. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  21256. 28, 28, 29, 29, 64, 64
  21257. ];
  21258. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  21259. {
  21260. var bits = opts.bits;
  21261. //here = opts.here; /* table entry for duplication */
  21262. var len = 0; /* a code's length in bits */
  21263. var sym = 0; /* index of code symbols */
  21264. var min = 0, max = 0; /* minimum and maximum code lengths */
  21265. var root = 0; /* number of index bits for root table */
  21266. var curr = 0; /* number of index bits for current table */
  21267. var drop = 0; /* code bits to drop for sub-table */
  21268. var left = 0; /* number of prefix codes available */
  21269. var used = 0; /* code entries in table used */
  21270. var huff = 0; /* Huffman code */
  21271. var incr; /* for incrementing code, index */
  21272. var fill; /* index for replicating entries */
  21273. var low; /* low bits for current root entry */
  21274. var mask; /* mask for low root bits */
  21275. var next; /* next available space in table */
  21276. var base = null; /* base value table to use */
  21277. var base_index = 0;
  21278. // var shoextra; /* extra bits table to use */
  21279. var end; /* use base and extra for symbol > end */
  21280. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  21281. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  21282. var extra = null;
  21283. var extra_index = 0;
  21284. var here_bits, here_op, here_val;
  21285. /*
  21286. Process a set of code lengths to create a canonical Huffman code. The
  21287. code lengths are lens[0..codes-1]. Each length corresponds to the
  21288. symbols 0..codes-1. The Huffman code is generated by first sorting the
  21289. symbols by length from short to long, and retaining the symbol order
  21290. for codes with equal lengths. Then the code starts with all zero bits
  21291. for the first code of the shortest length, and the codes are integer
  21292. increments for the same length, and zeros are appended as the length
  21293. increases. For the deflate format, these bits are stored backwards
  21294. from their more natural integer increment ordering, and so when the
  21295. decoding tables are built in the large loop below, the integer codes
  21296. are incremented backwards.
  21297. This routine assumes, but does not check, that all of the entries in
  21298. lens[] are in the range 0..MAXBITS. The caller must assure this.
  21299. 1..MAXBITS is interpreted as that code length. zero means that that
  21300. symbol does not occur in this code.
  21301. The codes are sorted by computing a count of codes for each length,
  21302. creating from that a table of starting indices for each length in the
  21303. sorted table, and then entering the symbols in order in the sorted
  21304. table. The sorted table is work[], with that space being provided by
  21305. the caller.
  21306. The length counts are used for other purposes as well, i.e. finding
  21307. the minimum and maximum length codes, determining if there are any
  21308. codes at all, checking for a valid set of lengths, and looking ahead
  21309. at length counts to determine sub-table sizes when building the
  21310. decoding tables.
  21311. */
  21312. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  21313. for (len = 0; len <= MAXBITS; len++) {
  21314. count[len] = 0;
  21315. }
  21316. for (sym = 0; sym < codes; sym++) {
  21317. count[lens[lens_index + sym]]++;
  21318. }
  21319. /* bound code lengths, force root to be within code lengths */
  21320. root = bits;
  21321. for (max = MAXBITS; max >= 1; max--) {
  21322. if (count[max] !== 0) { break; }
  21323. }
  21324. if (root > max) {
  21325. root = max;
  21326. }
  21327. if (max === 0) { /* no symbols to code at all */
  21328. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  21329. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  21330. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  21331. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21332. //table.op[opts.table_index] = 64;
  21333. //table.bits[opts.table_index] = 1;
  21334. //table.val[opts.table_index++] = 0;
  21335. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21336. opts.bits = 1;
  21337. return 0; /* no symbols, but wait for decoding to report error */
  21338. }
  21339. for (min = 1; min < max; min++) {
  21340. if (count[min] !== 0) { break; }
  21341. }
  21342. if (root < min) {
  21343. root = min;
  21344. }
  21345. /* check for an over-subscribed or incomplete set of lengths */
  21346. left = 1;
  21347. for (len = 1; len <= MAXBITS; len++) {
  21348. left <<= 1;
  21349. left -= count[len];
  21350. if (left < 0) {
  21351. return -1;
  21352. } /* over-subscribed */
  21353. }
  21354. if (left > 0 && (type === CODES || max !== 1)) {
  21355. return -1; /* incomplete set */
  21356. }
  21357. /* generate offsets into symbol table for each length for sorting */
  21358. offs[1] = 0;
  21359. for (len = 1; len < MAXBITS; len++) {
  21360. offs[len + 1] = offs[len] + count[len];
  21361. }
  21362. /* sort symbols by length, by symbol order within each length */
  21363. for (sym = 0; sym < codes; sym++) {
  21364. if (lens[lens_index + sym] !== 0) {
  21365. work[offs[lens[lens_index + sym]]++] = sym;
  21366. }
  21367. }
  21368. /*
  21369. Create and fill in decoding tables. In this loop, the table being
  21370. filled is at next and has curr index bits. The code being used is huff
  21371. with length len. That code is converted to an index by dropping drop
  21372. bits off of the bottom. For codes where len is less than drop + curr,
  21373. those top drop + curr - len bits are incremented through all values to
  21374. fill the table with replicated entries.
  21375. root is the number of index bits for the root table. When len exceeds
  21376. root, sub-tables are created pointed to by the root entry with an index
  21377. of the low root bits of huff. This is saved in low to check for when a
  21378. new sub-table should be started. drop is zero when the root table is
  21379. being filled, and drop is root when sub-tables are being filled.
  21380. When a new sub-table is needed, it is necessary to look ahead in the
  21381. code lengths to determine what size sub-table is needed. The length
  21382. counts are used for this, and so count[] is decremented as codes are
  21383. entered in the tables.
  21384. used keeps track of how many table entries have been allocated from the
  21385. provided *table space. It is checked for LENS and DIST tables against
  21386. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  21387. the initial root table size constants. See the comments in inftrees.h
  21388. for more information.
  21389. sym increments through all symbols, and the loop terminates when
  21390. all codes of length max, i.e. all codes, have been processed. This
  21391. routine permits incomplete codes, so another loop after this one fills
  21392. in the rest of the decoding tables with invalid code markers.
  21393. */
  21394. /* set up for code type */
  21395. // poor man optimization - use if-else instead of switch,
  21396. // to avoid deopts in old v8
  21397. if (type === CODES) {
  21398. base = extra = work; /* dummy value--not used */
  21399. end = 19;
  21400. } else if (type === LENS) {
  21401. base = lbase;
  21402. base_index -= 257;
  21403. extra = lext;
  21404. extra_index -= 257;
  21405. end = 256;
  21406. } else { /* DISTS */
  21407. base = dbase;
  21408. extra = dext;
  21409. end = -1;
  21410. }
  21411. /* initialize opts for loop */
  21412. huff = 0; /* starting code */
  21413. sym = 0; /* starting code symbol */
  21414. len = min; /* starting code length */
  21415. next = table_index; /* current table to fill in */
  21416. curr = root; /* current table index bits */
  21417. drop = 0; /* current bits to drop from code for index */
  21418. low = -1; /* trigger new sub-table when len > root */
  21419. used = 1 << root; /* use root table entries */
  21420. mask = used - 1; /* mask for comparing low */
  21421. /* check available table space */
  21422. if ((type === LENS && used > ENOUGH_LENS) ||
  21423. (type === DISTS && used > ENOUGH_DISTS)) {
  21424. return 1;
  21425. }
  21426. var i=0;
  21427. /* process all codes and make table entries */
  21428. for (;;) {
  21429. i++;
  21430. /* create table entry */
  21431. here_bits = len - drop;
  21432. if (work[sym] < end) {
  21433. here_op = 0;
  21434. here_val = work[sym];
  21435. }
  21436. else if (work[sym] > end) {
  21437. here_op = extra[extra_index + work[sym]];
  21438. here_val = base[base_index + work[sym]];
  21439. }
  21440. else {
  21441. here_op = 32 + 64; /* end of block */
  21442. here_val = 0;
  21443. }
  21444. /* replicate for those indices with low len bits equal to huff */
  21445. incr = 1 << (len - drop);
  21446. fill = 1 << curr;
  21447. min = fill; /* save offset to next table */
  21448. do {
  21449. fill -= incr;
  21450. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  21451. } while (fill !== 0);
  21452. /* backwards increment the len-bit code huff */
  21453. incr = 1 << (len - 1);
  21454. while (huff & incr) {
  21455. incr >>= 1;
  21456. }
  21457. if (incr !== 0) {
  21458. huff &= incr - 1;
  21459. huff += incr;
  21460. } else {
  21461. huff = 0;
  21462. }
  21463. /* go to next symbol, update count, len */
  21464. sym++;
  21465. if (--count[len] === 0) {
  21466. if (len === max) { break; }
  21467. len = lens[lens_index + work[sym]];
  21468. }
  21469. /* create new sub-table if needed */
  21470. if (len > root && (huff & mask) !== low) {
  21471. /* if first time, transition to sub-tables */
  21472. if (drop === 0) {
  21473. drop = root;
  21474. }
  21475. /* increment past last table */
  21476. next += min; /* here min is 1 << curr */
  21477. /* determine length of next table */
  21478. curr = len - drop;
  21479. left = 1 << curr;
  21480. while (curr + drop < max) {
  21481. left -= count[curr + drop];
  21482. if (left <= 0) { break; }
  21483. curr++;
  21484. left <<= 1;
  21485. }
  21486. /* check for enough space */
  21487. used += 1 << curr;
  21488. if ((type === LENS && used > ENOUGH_LENS) ||
  21489. (type === DISTS && used > ENOUGH_DISTS)) {
  21490. return 1;
  21491. }
  21492. /* point entry in root table to sub-table */
  21493. low = huff & mask;
  21494. /*table.op[low] = curr;
  21495. table.bits[low] = root;
  21496. table.val[low] = next - opts.table_index;*/
  21497. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  21498. }
  21499. }
  21500. /* fill in remaining table entry if code is incomplete (guaranteed to have
  21501. at most one remaining entry, since if the code is incomplete, the
  21502. maximum code length that was allowed to get this far is one bit) */
  21503. if (huff !== 0) {
  21504. //table.op[next + huff] = 64; /* invalid code marker */
  21505. //table.bits[next + huff] = len - drop;
  21506. //table.val[next + huff] = 0;
  21507. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  21508. }
  21509. /* set return parameters */
  21510. //opts.table_index += used;
  21511. opts.bits = root;
  21512. return 0;
  21513. };
  21514. },{"../utils/common":66}],76:[function(require,module,exports){
  21515. 'use strict';
  21516. module.exports = {
  21517. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  21518. '1': 'stream end', /* Z_STREAM_END 1 */
  21519. '0': '', /* Z_OK 0 */
  21520. '-1': 'file error', /* Z_ERRNO (-1) */
  21521. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  21522. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  21523. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  21524. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  21525. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  21526. };
  21527. },{}],77:[function(require,module,exports){
  21528. 'use strict';
  21529. var utils = require('../utils/common');
  21530. /* Public constants ==========================================================*/
  21531. /* ===========================================================================*/
  21532. //var Z_FILTERED = 1;
  21533. //var Z_HUFFMAN_ONLY = 2;
  21534. //var Z_RLE = 3;
  21535. var Z_FIXED = 4;
  21536. //var Z_DEFAULT_STRATEGY = 0;
  21537. /* Possible values of the data_type field (though see inflate()) */
  21538. var Z_BINARY = 0;
  21539. var Z_TEXT = 1;
  21540. //var Z_ASCII = 1; // = Z_TEXT
  21541. var Z_UNKNOWN = 2;
  21542. /*============================================================================*/
  21543. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  21544. // From zutil.h
  21545. var STORED_BLOCK = 0;
  21546. var STATIC_TREES = 1;
  21547. var DYN_TREES = 2;
  21548. /* The three kinds of block type */
  21549. var MIN_MATCH = 3;
  21550. var MAX_MATCH = 258;
  21551. /* The minimum and maximum match lengths */
  21552. // From deflate.h
  21553. /* ===========================================================================
  21554. * Internal compression state.
  21555. */
  21556. var LENGTH_CODES = 29;
  21557. /* number of length codes, not counting the special END_BLOCK code */
  21558. var LITERALS = 256;
  21559. /* number of literal bytes 0..255 */
  21560. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  21561. /* number of Literal or Length codes, including the END_BLOCK code */
  21562. var D_CODES = 30;
  21563. /* number of distance codes */
  21564. var BL_CODES = 19;
  21565. /* number of codes used to transfer the bit lengths */
  21566. var HEAP_SIZE = 2*L_CODES + 1;
  21567. /* maximum heap size */
  21568. var MAX_BITS = 15;
  21569. /* All codes must not exceed MAX_BITS bits */
  21570. var Buf_size = 16;
  21571. /* size of bit buffer in bi_buf */
  21572. /* ===========================================================================
  21573. * Constants
  21574. */
  21575. var MAX_BL_BITS = 7;
  21576. /* Bit length codes must not exceed MAX_BL_BITS bits */
  21577. var END_BLOCK = 256;
  21578. /* end of block literal code */
  21579. var REP_3_6 = 16;
  21580. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  21581. var REPZ_3_10 = 17;
  21582. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  21583. var REPZ_11_138 = 18;
  21584. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  21585. var extra_lbits = /* extra bits for each length code */
  21586. [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];
  21587. var extra_dbits = /* extra bits for each distance code */
  21588. [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];
  21589. var extra_blbits = /* extra bits for each bit length code */
  21590. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  21591. var bl_order =
  21592. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  21593. /* The lengths of the bit length codes are sent in order of decreasing
  21594. * probability, to avoid transmitting the lengths for unused bit length codes.
  21595. */
  21596. /* ===========================================================================
  21597. * Local data. These are initialized only once.
  21598. */
  21599. // We pre-fill arrays with 0 to avoid uninitialized gaps
  21600. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  21601. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  21602. var static_ltree = new Array((L_CODES+2) * 2);
  21603. zero(static_ltree);
  21604. /* The static literal tree. Since the bit lengths are imposed, there is no
  21605. * need for the L_CODES extra codes used during heap construction. However
  21606. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  21607. * below).
  21608. */
  21609. var static_dtree = new Array(D_CODES * 2);
  21610. zero(static_dtree);
  21611. /* The static distance tree. (Actually a trivial tree since all codes use
  21612. * 5 bits.)
  21613. */
  21614. var _dist_code = new Array(DIST_CODE_LEN);
  21615. zero(_dist_code);
  21616. /* Distance codes. The first 256 values correspond to the distances
  21617. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  21618. * the 15 bit distances.
  21619. */
  21620. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  21621. zero(_length_code);
  21622. /* length code for each normalized match length (0 == MIN_MATCH) */
  21623. var base_length = new Array(LENGTH_CODES);
  21624. zero(base_length);
  21625. /* First normalized length for each code (0 = MIN_MATCH) */
  21626. var base_dist = new Array(D_CODES);
  21627. zero(base_dist);
  21628. /* First normalized distance for each code (0 = distance of 1) */
  21629. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  21630. this.static_tree = static_tree; /* static tree or NULL */
  21631. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  21632. this.extra_base = extra_base; /* base index for extra_bits */
  21633. this.elems = elems; /* max number of elements in the tree */
  21634. this.max_length = max_length; /* max bit length for the codes */
  21635. // show if `static_tree` has data or dummy - needed for monomorphic objects
  21636. this.has_stree = static_tree && static_tree.length;
  21637. };
  21638. var static_l_desc;
  21639. var static_d_desc;
  21640. var static_bl_desc;
  21641. var TreeDesc = function(dyn_tree, stat_desc) {
  21642. this.dyn_tree = dyn_tree; /* the dynamic tree */
  21643. this.max_code = 0; /* largest code with non zero frequency */
  21644. this.stat_desc = stat_desc; /* the corresponding static tree */
  21645. };
  21646. function d_code(dist) {
  21647. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  21648. }
  21649. /* ===========================================================================
  21650. * Output a short LSB first on the stream.
  21651. * IN assertion: there is enough room in pendingBuf.
  21652. */
  21653. function put_short (s, w) {
  21654. // put_byte(s, (uch)((w) & 0xff));
  21655. // put_byte(s, (uch)((ush)(w) >> 8));
  21656. s.pending_buf[s.pending++] = (w) & 0xff;
  21657. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  21658. }
  21659. /* ===========================================================================
  21660. * Send a value on a given number of bits.
  21661. * IN assertion: length <= 16 and value fits in length bits.
  21662. */
  21663. function send_bits(s, value, length) {
  21664. if (s.bi_valid > (Buf_size - length)) {
  21665. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21666. put_short(s, s.bi_buf);
  21667. s.bi_buf = value >> (Buf_size - s.bi_valid);
  21668. s.bi_valid += length - Buf_size;
  21669. } else {
  21670. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21671. s.bi_valid += length;
  21672. }
  21673. }
  21674. function send_code(s, c, tree) {
  21675. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  21676. }
  21677. /* ===========================================================================
  21678. * Reverse the first len bits of a code, using straightforward code (a faster
  21679. * method would use a table)
  21680. * IN assertion: 1 <= len <= 15
  21681. */
  21682. function bi_reverse(code, len) {
  21683. var res = 0;
  21684. do {
  21685. res |= code & 1;
  21686. code >>>= 1;
  21687. res <<= 1;
  21688. } while (--len > 0);
  21689. return res >>> 1;
  21690. }
  21691. /* ===========================================================================
  21692. * Flush the bit buffer, keeping at most 7 bits in it.
  21693. */
  21694. function bi_flush(s) {
  21695. if (s.bi_valid === 16) {
  21696. put_short(s, s.bi_buf);
  21697. s.bi_buf = 0;
  21698. s.bi_valid = 0;
  21699. } else if (s.bi_valid >= 8) {
  21700. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  21701. s.bi_buf >>= 8;
  21702. s.bi_valid -= 8;
  21703. }
  21704. }
  21705. /* ===========================================================================
  21706. * Compute the optimal bit lengths for a tree and update the total bit length
  21707. * for the current block.
  21708. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  21709. * above are the tree nodes sorted by increasing frequency.
  21710. * OUT assertions: the field len is set to the optimal bit length, the
  21711. * array bl_count contains the frequencies for each bit length.
  21712. * The length opt_len is updated; static_len is also updated if stree is
  21713. * not null.
  21714. */
  21715. function gen_bitlen(s, desc)
  21716. // deflate_state *s;
  21717. // tree_desc *desc; /* the tree descriptor */
  21718. {
  21719. var tree = desc.dyn_tree;
  21720. var max_code = desc.max_code;
  21721. var stree = desc.stat_desc.static_tree;
  21722. var has_stree = desc.stat_desc.has_stree;
  21723. var extra = desc.stat_desc.extra_bits;
  21724. var base = desc.stat_desc.extra_base;
  21725. var max_length = desc.stat_desc.max_length;
  21726. var h; /* heap index */
  21727. var n, m; /* iterate over the tree elements */
  21728. var bits; /* bit length */
  21729. var xbits; /* extra bits */
  21730. var f; /* frequency */
  21731. var overflow = 0; /* number of elements with bit length too large */
  21732. for (bits = 0; bits <= MAX_BITS; bits++) {
  21733. s.bl_count[bits] = 0;
  21734. }
  21735. /* In a first pass, compute the optimal bit lengths (which may
  21736. * overflow in the case of the bit length tree).
  21737. */
  21738. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  21739. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  21740. n = s.heap[h];
  21741. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  21742. if (bits > max_length) {
  21743. bits = max_length;
  21744. overflow++;
  21745. }
  21746. tree[n*2 + 1]/*.Len*/ = bits;
  21747. /* We overwrite tree[n].Dad which is no longer needed */
  21748. if (n > max_code) { continue; } /* not a leaf node */
  21749. s.bl_count[bits]++;
  21750. xbits = 0;
  21751. if (n >= base) {
  21752. xbits = extra[n-base];
  21753. }
  21754. f = tree[n * 2]/*.Freq*/;
  21755. s.opt_len += f * (bits + xbits);
  21756. if (has_stree) {
  21757. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  21758. }
  21759. }
  21760. if (overflow === 0) { return; }
  21761. // Trace((stderr,"\nbit length overflow\n"));
  21762. /* This happens for example on obj2 and pic of the Calgary corpus */
  21763. /* Find the first bit length which could increase: */
  21764. do {
  21765. bits = max_length-1;
  21766. while (s.bl_count[bits] === 0) { bits--; }
  21767. s.bl_count[bits]--; /* move one leaf down the tree */
  21768. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  21769. s.bl_count[max_length]--;
  21770. /* The brother of the overflow item also moves one step up,
  21771. * but this does not affect bl_count[max_length]
  21772. */
  21773. overflow -= 2;
  21774. } while (overflow > 0);
  21775. /* Now recompute all bit lengths, scanning in increasing frequency.
  21776. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  21777. * lengths instead of fixing only the wrong ones. This idea is taken
  21778. * from 'ar' written by Haruhiko Okumura.)
  21779. */
  21780. for (bits = max_length; bits !== 0; bits--) {
  21781. n = s.bl_count[bits];
  21782. while (n !== 0) {
  21783. m = s.heap[--h];
  21784. if (m > max_code) { continue; }
  21785. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  21786. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  21787. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  21788. tree[m*2 + 1]/*.Len*/ = bits;
  21789. }
  21790. n--;
  21791. }
  21792. }
  21793. }
  21794. /* ===========================================================================
  21795. * Generate the codes for a given tree and bit counts (which need not be
  21796. * optimal).
  21797. * IN assertion: the array bl_count contains the bit length statistics for
  21798. * the given tree and the field len is set for all tree elements.
  21799. * OUT assertion: the field code is set for all tree elements of non
  21800. * zero code length.
  21801. */
  21802. function gen_codes(tree, max_code, bl_count)
  21803. // ct_data *tree; /* the tree to decorate */
  21804. // int max_code; /* largest code with non zero frequency */
  21805. // ushf *bl_count; /* number of codes at each bit length */
  21806. {
  21807. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  21808. var code = 0; /* running code value */
  21809. var bits; /* bit index */
  21810. var n; /* code index */
  21811. /* The distribution counts are first used to generate the code values
  21812. * without bit reversal.
  21813. */
  21814. for (bits = 1; bits <= MAX_BITS; bits++) {
  21815. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  21816. }
  21817. /* Check that the bit counts in bl_count are consistent. The last code
  21818. * must be all ones.
  21819. */
  21820. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  21821. // "inconsistent bit counts");
  21822. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  21823. for (n = 0; n <= max_code; n++) {
  21824. var len = tree[n*2 + 1]/*.Len*/;
  21825. if (len === 0) { continue; }
  21826. /* Now reverse the bits */
  21827. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  21828. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  21829. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  21830. }
  21831. }
  21832. /* ===========================================================================
  21833. * Initialize the various 'constant' tables.
  21834. */
  21835. function tr_static_init() {
  21836. var n; /* iterates over tree elements */
  21837. var bits; /* bit counter */
  21838. var length; /* length value */
  21839. var code; /* code value */
  21840. var dist; /* distance index */
  21841. var bl_count = new Array(MAX_BITS+1);
  21842. /* number of codes at each bit length for an optimal tree */
  21843. // do check in _tr_init()
  21844. //if (static_init_done) return;
  21845. /* For some embedded targets, global variables are not initialized: */
  21846. /*#ifdef NO_INIT_GLOBAL_POINTERS
  21847. static_l_desc.static_tree = static_ltree;
  21848. static_l_desc.extra_bits = extra_lbits;
  21849. static_d_desc.static_tree = static_dtree;
  21850. static_d_desc.extra_bits = extra_dbits;
  21851. static_bl_desc.extra_bits = extra_blbits;
  21852. #endif*/
  21853. /* Initialize the mapping length (0..255) -> length code (0..28) */
  21854. length = 0;
  21855. for (code = 0; code < LENGTH_CODES-1; code++) {
  21856. base_length[code] = length;
  21857. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  21858. _length_code[length++] = code;
  21859. }
  21860. }
  21861. //Assert (length == 256, "tr_static_init: length != 256");
  21862. /* Note that the length 255 (match length 258) can be represented
  21863. * in two different ways: code 284 + 5 bits or code 285, so we
  21864. * overwrite length_code[255] to use the best encoding:
  21865. */
  21866. _length_code[length-1] = code;
  21867. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  21868. dist = 0;
  21869. for (code = 0 ; code < 16; code++) {
  21870. base_dist[code] = dist;
  21871. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  21872. _dist_code[dist++] = code;
  21873. }
  21874. }
  21875. //Assert (dist == 256, "tr_static_init: dist != 256");
  21876. dist >>= 7; /* from now on, all distances are divided by 128 */
  21877. for ( ; code < D_CODES; code++) {
  21878. base_dist[code] = dist << 7;
  21879. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  21880. _dist_code[256 + dist++] = code;
  21881. }
  21882. }
  21883. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  21884. /* Construct the codes of the static literal tree */
  21885. for (bits = 0; bits <= MAX_BITS; bits++) {
  21886. bl_count[bits] = 0;
  21887. }
  21888. n = 0;
  21889. while (n <= 143) {
  21890. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21891. n++;
  21892. bl_count[8]++;
  21893. }
  21894. while (n <= 255) {
  21895. static_ltree[n*2 + 1]/*.Len*/ = 9;
  21896. n++;
  21897. bl_count[9]++;
  21898. }
  21899. while (n <= 279) {
  21900. static_ltree[n*2 + 1]/*.Len*/ = 7;
  21901. n++;
  21902. bl_count[7]++;
  21903. }
  21904. while (n <= 287) {
  21905. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21906. n++;
  21907. bl_count[8]++;
  21908. }
  21909. /* Codes 286 and 287 do not exist, but we must include them in the
  21910. * tree construction to get a canonical Huffman tree (longest code
  21911. * all ones)
  21912. */
  21913. gen_codes(static_ltree, L_CODES+1, bl_count);
  21914. /* The static distance tree is trivial: */
  21915. for (n = 0; n < D_CODES; n++) {
  21916. static_dtree[n*2 + 1]/*.Len*/ = 5;
  21917. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  21918. }
  21919. // Now data ready and we can init static trees
  21920. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  21921. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  21922. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  21923. //static_init_done = true;
  21924. }
  21925. /* ===========================================================================
  21926. * Initialize a new block.
  21927. */
  21928. function init_block(s) {
  21929. var n; /* iterates over tree elements */
  21930. /* Initialize the trees. */
  21931. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  21932. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  21933. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  21934. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  21935. s.opt_len = s.static_len = 0;
  21936. s.last_lit = s.matches = 0;
  21937. }
  21938. /* ===========================================================================
  21939. * Flush the bit buffer and align the output on a byte boundary
  21940. */
  21941. function bi_windup(s)
  21942. {
  21943. if (s.bi_valid > 8) {
  21944. put_short(s, s.bi_buf);
  21945. } else if (s.bi_valid > 0) {
  21946. //put_byte(s, (Byte)s->bi_buf);
  21947. s.pending_buf[s.pending++] = s.bi_buf;
  21948. }
  21949. s.bi_buf = 0;
  21950. s.bi_valid = 0;
  21951. }
  21952. /* ===========================================================================
  21953. * Copy a stored block, storing first the length and its
  21954. * one's complement if requested.
  21955. */
  21956. function copy_block(s, buf, len, header)
  21957. //DeflateState *s;
  21958. //charf *buf; /* the input data */
  21959. //unsigned len; /* its length */
  21960. //int header; /* true if block header must be written */
  21961. {
  21962. bi_windup(s); /* align on byte boundary */
  21963. if (header) {
  21964. put_short(s, len);
  21965. put_short(s, ~len);
  21966. }
  21967. // while (len--) {
  21968. // put_byte(s, *buf++);
  21969. // }
  21970. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  21971. s.pending += len;
  21972. }
  21973. /* ===========================================================================
  21974. * Compares to subtrees, using the tree depth as tie breaker when
  21975. * the subtrees have equal frequency. This minimizes the worst case length.
  21976. */
  21977. function smaller(tree, n, m, depth) {
  21978. var _n2 = n*2;
  21979. var _m2 = m*2;
  21980. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  21981. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  21982. }
  21983. /* ===========================================================================
  21984. * Restore the heap property by moving down the tree starting at node k,
  21985. * exchanging a node with the smallest of its two sons if necessary, stopping
  21986. * when the heap property is re-established (each father smaller than its
  21987. * two sons).
  21988. */
  21989. function pqdownheap(s, tree, k)
  21990. // deflate_state *s;
  21991. // ct_data *tree; /* the tree to restore */
  21992. // int k; /* node to move down */
  21993. {
  21994. var v = s.heap[k];
  21995. var j = k << 1; /* left son of k */
  21996. while (j <= s.heap_len) {
  21997. /* Set j to the smallest of the two sons: */
  21998. if (j < s.heap_len &&
  21999. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  22000. j++;
  22001. }
  22002. /* Exit if v is smaller than both sons */
  22003. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  22004. /* Exchange v with the smallest son */
  22005. s.heap[k] = s.heap[j];
  22006. k = j;
  22007. /* And continue down the tree, setting j to the left son of k */
  22008. j <<= 1;
  22009. }
  22010. s.heap[k] = v;
  22011. }
  22012. // inlined manually
  22013. // var SMALLEST = 1;
  22014. /* ===========================================================================
  22015. * Send the block data compressed using the given Huffman trees
  22016. */
  22017. function compress_block(s, ltree, dtree)
  22018. // deflate_state *s;
  22019. // const ct_data *ltree; /* literal tree */
  22020. // const ct_data *dtree; /* distance tree */
  22021. {
  22022. var dist; /* distance of matched string */
  22023. var lc; /* match length or unmatched char (if dist == 0) */
  22024. var lx = 0; /* running index in l_buf */
  22025. var code; /* the code to send */
  22026. var extra; /* number of extra bits to send */
  22027. if (s.last_lit !== 0) {
  22028. do {
  22029. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  22030. lc = s.pending_buf[s.l_buf + lx];
  22031. lx++;
  22032. if (dist === 0) {
  22033. send_code(s, lc, ltree); /* send a literal byte */
  22034. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  22035. } else {
  22036. /* Here, lc is the match length - MIN_MATCH */
  22037. code = _length_code[lc];
  22038. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  22039. extra = extra_lbits[code];
  22040. if (extra !== 0) {
  22041. lc -= base_length[code];
  22042. send_bits(s, lc, extra); /* send the extra length bits */
  22043. }
  22044. dist--; /* dist is now the match distance - 1 */
  22045. code = d_code(dist);
  22046. //Assert (code < D_CODES, "bad d_code");
  22047. send_code(s, code, dtree); /* send the distance code */
  22048. extra = extra_dbits[code];
  22049. if (extra !== 0) {
  22050. dist -= base_dist[code];
  22051. send_bits(s, dist, extra); /* send the extra distance bits */
  22052. }
  22053. } /* literal or match pair ? */
  22054. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  22055. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  22056. // "pendingBuf overflow");
  22057. } while (lx < s.last_lit);
  22058. }
  22059. send_code(s, END_BLOCK, ltree);
  22060. }
  22061. /* ===========================================================================
  22062. * Construct one Huffman tree and assigns the code bit strings and lengths.
  22063. * Update the total bit length for the current block.
  22064. * IN assertion: the field freq is set for all tree elements.
  22065. * OUT assertions: the fields len and code are set to the optimal bit length
  22066. * and corresponding code. The length opt_len is updated; static_len is
  22067. * also updated if stree is not null. The field max_code is set.
  22068. */
  22069. function build_tree(s, desc)
  22070. // deflate_state *s;
  22071. // tree_desc *desc; /* the tree descriptor */
  22072. {
  22073. var tree = desc.dyn_tree;
  22074. var stree = desc.stat_desc.static_tree;
  22075. var has_stree = desc.stat_desc.has_stree;
  22076. var elems = desc.stat_desc.elems;
  22077. var n, m; /* iterate over heap elements */
  22078. var max_code = -1; /* largest code with non zero frequency */
  22079. var node; /* new node being created */
  22080. /* Construct the initial heap, with least frequent element in
  22081. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  22082. * heap[0] is not used.
  22083. */
  22084. s.heap_len = 0;
  22085. s.heap_max = HEAP_SIZE;
  22086. for (n = 0; n < elems; n++) {
  22087. if (tree[n * 2]/*.Freq*/ !== 0) {
  22088. s.heap[++s.heap_len] = max_code = n;
  22089. s.depth[n] = 0;
  22090. } else {
  22091. tree[n*2 + 1]/*.Len*/ = 0;
  22092. }
  22093. }
  22094. /* The pkzip format requires that at least one distance code exists,
  22095. * and that at least one bit should be sent even if there is only one
  22096. * possible code. So to avoid special checks later on we force at least
  22097. * two codes of non zero frequency.
  22098. */
  22099. while (s.heap_len < 2) {
  22100. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  22101. tree[node * 2]/*.Freq*/ = 1;
  22102. s.depth[node] = 0;
  22103. s.opt_len--;
  22104. if (has_stree) {
  22105. s.static_len -= stree[node*2 + 1]/*.Len*/;
  22106. }
  22107. /* node is 0 or 1 so it does not have extra bits */
  22108. }
  22109. desc.max_code = max_code;
  22110. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  22111. * establish sub-heaps of increasing lengths:
  22112. */
  22113. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  22114. /* Construct the Huffman tree by repeatedly combining the least two
  22115. * frequent nodes.
  22116. */
  22117. node = elems; /* next internal node of the tree */
  22118. do {
  22119. //pqremove(s, tree, n); /* n = node of least frequency */
  22120. /*** pqremove ***/
  22121. n = s.heap[1/*SMALLEST*/];
  22122. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  22123. pqdownheap(s, tree, 1/*SMALLEST*/);
  22124. /***/
  22125. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  22126. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  22127. s.heap[--s.heap_max] = m;
  22128. /* Create a new node father of n and m */
  22129. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  22130. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  22131. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  22132. /* and insert the new node in the heap */
  22133. s.heap[1/*SMALLEST*/] = node++;
  22134. pqdownheap(s, tree, 1/*SMALLEST*/);
  22135. } while (s.heap_len >= 2);
  22136. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  22137. /* At this point, the fields freq and dad are set. We can now
  22138. * generate the bit lengths.
  22139. */
  22140. gen_bitlen(s, desc);
  22141. /* The field len is now set, we can generate the bit codes */
  22142. gen_codes(tree, max_code, s.bl_count);
  22143. }
  22144. /* ===========================================================================
  22145. * Scan a literal or distance tree to determine the frequencies of the codes
  22146. * in the bit length tree.
  22147. */
  22148. function scan_tree(s, tree, max_code)
  22149. // deflate_state *s;
  22150. // ct_data *tree; /* the tree to be scanned */
  22151. // int max_code; /* and its largest code of non zero frequency */
  22152. {
  22153. var n; /* iterates over all tree elements */
  22154. var prevlen = -1; /* last emitted length */
  22155. var curlen; /* length of current code */
  22156. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  22157. var count = 0; /* repeat count of the current code */
  22158. var max_count = 7; /* max repeat count */
  22159. var min_count = 4; /* min repeat count */
  22160. if (nextlen === 0) {
  22161. max_count = 138;
  22162. min_count = 3;
  22163. }
  22164. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  22165. for (n = 0; n <= max_code; n++) {
  22166. curlen = nextlen;
  22167. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  22168. if (++count < max_count && curlen === nextlen) {
  22169. continue;
  22170. } else if (count < min_count) {
  22171. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  22172. } else if (curlen !== 0) {
  22173. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  22174. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  22175. } else if (count <= 10) {
  22176. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  22177. } else {
  22178. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  22179. }
  22180. count = 0;
  22181. prevlen = curlen;
  22182. if (nextlen === 0) {
  22183. max_count = 138;
  22184. min_count = 3;
  22185. } else if (curlen === nextlen) {
  22186. max_count = 6;
  22187. min_count = 3;
  22188. } else {
  22189. max_count = 7;
  22190. min_count = 4;
  22191. }
  22192. }
  22193. }
  22194. /* ===========================================================================
  22195. * Send a literal or distance tree in compressed form, using the codes in
  22196. * bl_tree.
  22197. */
  22198. function send_tree(s, tree, max_code)
  22199. // deflate_state *s;
  22200. // ct_data *tree; /* the tree to be scanned */
  22201. // int max_code; /* and its largest code of non zero frequency */
  22202. {
  22203. var n; /* iterates over all tree elements */
  22204. var prevlen = -1; /* last emitted length */
  22205. var curlen; /* length of current code */
  22206. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  22207. var count = 0; /* repeat count of the current code */
  22208. var max_count = 7; /* max repeat count */
  22209. var min_count = 4; /* min repeat count */
  22210. /* tree[max_code+1].Len = -1; */ /* guard already set */
  22211. if (nextlen === 0) {
  22212. max_count = 138;
  22213. min_count = 3;
  22214. }
  22215. for (n = 0; n <= max_code; n++) {
  22216. curlen = nextlen;
  22217. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  22218. if (++count < max_count && curlen === nextlen) {
  22219. continue;
  22220. } else if (count < min_count) {
  22221. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  22222. } else if (curlen !== 0) {
  22223. if (curlen !== prevlen) {
  22224. send_code(s, curlen, s.bl_tree);
  22225. count--;
  22226. }
  22227. //Assert(count >= 3 && count <= 6, " 3_6?");
  22228. send_code(s, REP_3_6, s.bl_tree);
  22229. send_bits(s, count-3, 2);
  22230. } else if (count <= 10) {
  22231. send_code(s, REPZ_3_10, s.bl_tree);
  22232. send_bits(s, count-3, 3);
  22233. } else {
  22234. send_code(s, REPZ_11_138, s.bl_tree);
  22235. send_bits(s, count-11, 7);
  22236. }
  22237. count = 0;
  22238. prevlen = curlen;
  22239. if (nextlen === 0) {
  22240. max_count = 138;
  22241. min_count = 3;
  22242. } else if (curlen === nextlen) {
  22243. max_count = 6;
  22244. min_count = 3;
  22245. } else {
  22246. max_count = 7;
  22247. min_count = 4;
  22248. }
  22249. }
  22250. }
  22251. /* ===========================================================================
  22252. * Construct the Huffman tree for the bit lengths and return the index in
  22253. * bl_order of the last bit length code to send.
  22254. */
  22255. function build_bl_tree(s) {
  22256. var max_blindex; /* index of last bit length code of non zero freq */
  22257. /* Determine the bit length frequencies for literal and distance trees */
  22258. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  22259. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  22260. /* Build the bit length tree: */
  22261. build_tree(s, s.bl_desc);
  22262. /* opt_len now includes the length of the tree representations, except
  22263. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  22264. */
  22265. /* Determine the number of bit length codes to send. The pkzip format
  22266. * requires that at least 4 bit length codes be sent. (appnote.txt says
  22267. * 3 but the actual value used is 4.)
  22268. */
  22269. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  22270. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  22271. break;
  22272. }
  22273. }
  22274. /* Update opt_len to include the bit length tree and counts */
  22275. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  22276. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  22277. // s->opt_len, s->static_len));
  22278. return max_blindex;
  22279. }
  22280. /* ===========================================================================
  22281. * Send the header for a block using dynamic Huffman trees: the counts, the
  22282. * lengths of the bit length codes, the literal tree and the distance tree.
  22283. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  22284. */
  22285. function send_all_trees(s, lcodes, dcodes, blcodes)
  22286. // deflate_state *s;
  22287. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  22288. {
  22289. var rank; /* index in bl_order */
  22290. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  22291. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  22292. // "too many codes");
  22293. //Tracev((stderr, "\nbl counts: "));
  22294. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  22295. send_bits(s, dcodes-1, 5);
  22296. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  22297. for (rank = 0; rank < blcodes; rank++) {
  22298. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  22299. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  22300. }
  22301. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  22302. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  22303. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  22304. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  22305. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  22306. }
  22307. /* ===========================================================================
  22308. * Check if the data type is TEXT or BINARY, using the following algorithm:
  22309. * - TEXT if the two conditions below are satisfied:
  22310. * a) There are no non-portable control characters belonging to the
  22311. * "black list" (0..6, 14..25, 28..31).
  22312. * b) There is at least one printable character belonging to the
  22313. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  22314. * - BINARY otherwise.
  22315. * - The following partially-portable control characters form a
  22316. * "gray list" that is ignored in this detection algorithm:
  22317. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  22318. * IN assertion: the fields Freq of dyn_ltree are set.
  22319. */
  22320. function detect_data_type(s) {
  22321. /* black_mask is the bit mask of black-listed bytes
  22322. * set bits 0..6, 14..25, and 28..31
  22323. * 0xf3ffc07f = binary 11110011111111111100000001111111
  22324. */
  22325. var black_mask = 0xf3ffc07f;
  22326. var n;
  22327. /* Check for non-textual ("black-listed") bytes. */
  22328. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  22329. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  22330. return Z_BINARY;
  22331. }
  22332. }
  22333. /* Check for textual ("white-listed") bytes. */
  22334. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  22335. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  22336. return Z_TEXT;
  22337. }
  22338. for (n = 32; n < LITERALS; n++) {
  22339. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  22340. return Z_TEXT;
  22341. }
  22342. }
  22343. /* There are no "black-listed" or "white-listed" bytes:
  22344. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  22345. */
  22346. return Z_BINARY;
  22347. }
  22348. var static_init_done = false;
  22349. /* ===========================================================================
  22350. * Initialize the tree data structures for a new zlib stream.
  22351. */
  22352. function _tr_init(s)
  22353. {
  22354. if (!static_init_done) {
  22355. tr_static_init();
  22356. static_init_done = true;
  22357. }
  22358. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  22359. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  22360. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  22361. s.bi_buf = 0;
  22362. s.bi_valid = 0;
  22363. /* Initialize the first block of the first file: */
  22364. init_block(s);
  22365. }
  22366. /* ===========================================================================
  22367. * Send a stored block
  22368. */
  22369. function _tr_stored_block(s, buf, stored_len, last)
  22370. //DeflateState *s;
  22371. //charf *buf; /* input block */
  22372. //ulg stored_len; /* length of input block */
  22373. //int last; /* one if this is the last block for a file */
  22374. {
  22375. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  22376. copy_block(s, buf, stored_len, true); /* with header */
  22377. }
  22378. /* ===========================================================================
  22379. * Send one empty static block to give enough lookahead for inflate.
  22380. * This takes 10 bits, of which 7 may remain in the bit buffer.
  22381. */
  22382. function _tr_align(s) {
  22383. send_bits(s, STATIC_TREES<<1, 3);
  22384. send_code(s, END_BLOCK, static_ltree);
  22385. bi_flush(s);
  22386. }
  22387. /* ===========================================================================
  22388. * Determine the best encoding for the current block: dynamic trees, static
  22389. * trees or store, and output the encoded block to the zip file.
  22390. */
  22391. function _tr_flush_block(s, buf, stored_len, last)
  22392. //DeflateState *s;
  22393. //charf *buf; /* input block, or NULL if too old */
  22394. //ulg stored_len; /* length of input block */
  22395. //int last; /* one if this is the last block for a file */
  22396. {
  22397. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  22398. var max_blindex = 0; /* index of last bit length code of non zero freq */
  22399. /* Build the Huffman trees unless a stored block is forced */
  22400. if (s.level > 0) {
  22401. /* Check if the file is binary or text */
  22402. if (s.strm.data_type === Z_UNKNOWN) {
  22403. s.strm.data_type = detect_data_type(s);
  22404. }
  22405. /* Construct the literal and distance trees */
  22406. build_tree(s, s.l_desc);
  22407. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  22408. // s->static_len));
  22409. build_tree(s, s.d_desc);
  22410. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  22411. // s->static_len));
  22412. /* At this point, opt_len and static_len are the total bit lengths of
  22413. * the compressed block data, excluding the tree representations.
  22414. */
  22415. /* Build the bit length tree for the above two trees, and get the index
  22416. * in bl_order of the last bit length code to send.
  22417. */
  22418. max_blindex = build_bl_tree(s);
  22419. /* Determine the best encoding. Compute the block lengths in bytes. */
  22420. opt_lenb = (s.opt_len+3+7) >>> 3;
  22421. static_lenb = (s.static_len+3+7) >>> 3;
  22422. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  22423. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  22424. // s->last_lit));
  22425. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  22426. } else {
  22427. // Assert(buf != (char*)0, "lost buf");
  22428. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  22429. }
  22430. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  22431. /* 4: two words for the lengths */
  22432. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  22433. * Otherwise we can't have processed more than WSIZE input bytes since
  22434. * the last block flush, because compression would have been
  22435. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  22436. * transform a block into a stored block.
  22437. */
  22438. _tr_stored_block(s, buf, stored_len, last);
  22439. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  22440. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  22441. compress_block(s, static_ltree, static_dtree);
  22442. } else {
  22443. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  22444. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  22445. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  22446. }
  22447. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  22448. /* The above check is made mod 2^32, for files larger than 512 MB
  22449. * and uLong implemented on 32 bits.
  22450. */
  22451. init_block(s);
  22452. if (last) {
  22453. bi_windup(s);
  22454. }
  22455. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  22456. // s->compressed_len-7*last));
  22457. }
  22458. /* ===========================================================================
  22459. * Save the match info and tally the frequency counts. Return true if
  22460. * the current block must be flushed.
  22461. */
  22462. function _tr_tally(s, dist, lc)
  22463. // deflate_state *s;
  22464. // unsigned dist; /* distance of matched string */
  22465. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  22466. {
  22467. //var out_length, in_length, dcode;
  22468. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  22469. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  22470. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  22471. s.last_lit++;
  22472. if (dist === 0) {
  22473. /* lc is the unmatched char */
  22474. s.dyn_ltree[lc*2]/*.Freq*/++;
  22475. } else {
  22476. s.matches++;
  22477. /* Here, lc is the match length - MIN_MATCH */
  22478. dist--; /* dist = match distance - 1 */
  22479. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  22480. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  22481. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  22482. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  22483. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  22484. }
  22485. // (!) This block is disabled in zlib defailts,
  22486. // don't enable it for binary compatibility
  22487. //#ifdef TRUNCATE_BLOCK
  22488. // /* Try to guess if it is profitable to stop the current block here */
  22489. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  22490. // /* Compute an upper bound for the compressed length */
  22491. // out_length = s.last_lit*8;
  22492. // in_length = s.strstart - s.block_start;
  22493. //
  22494. // for (dcode = 0; dcode < D_CODES; dcode++) {
  22495. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  22496. // }
  22497. // out_length >>>= 3;
  22498. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  22499. // // s->last_lit, in_length, out_length,
  22500. // // 100L - out_length*100L/in_length));
  22501. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  22502. // return true;
  22503. // }
  22504. // }
  22505. //#endif
  22506. return (s.last_lit === s.lit_bufsize-1);
  22507. /* We avoid equality with lit_bufsize because of wraparound at 64K
  22508. * on 16 bit machines and because stored blocks are restricted to
  22509. * 64K-1 bytes.
  22510. */
  22511. }
  22512. exports._tr_init = _tr_init;
  22513. exports._tr_stored_block = _tr_stored_block;
  22514. exports._tr_flush_block = _tr_flush_block;
  22515. exports._tr_tally = _tr_tally;
  22516. exports._tr_align = _tr_align;
  22517. },{"../utils/common":66}],78:[function(require,module,exports){
  22518. 'use strict';
  22519. function ZStream() {
  22520. /* next input byte */
  22521. this.input = null; // JS specific, because we have no pointers
  22522. this.next_in = 0;
  22523. /* number of bytes available at input */
  22524. this.avail_in = 0;
  22525. /* total number of input bytes read so far */
  22526. this.total_in = 0;
  22527. /* next output byte should be put there */
  22528. this.output = null; // JS specific, because we have no pointers
  22529. this.next_out = 0;
  22530. /* remaining free space at output */
  22531. this.avail_out = 0;
  22532. /* total number of bytes output so far */
  22533. this.total_out = 0;
  22534. /* last error message, NULL if no error */
  22535. this.msg = ''/*Z_NULL*/;
  22536. /* not visible by applications */
  22537. this.state = null;
  22538. /* best guess about the data type: binary or text */
  22539. this.data_type = 2/*Z_UNKNOWN*/;
  22540. /* adler32 value of the uncompressed data */
  22541. this.adler = 0;
  22542. }
  22543. module.exports = ZStream;
  22544. },{}],79:[function(require,module,exports){
  22545. module.exports = function arrayEquals(array) {
  22546. // if the other array is a falsy value, return
  22547. if (!array)
  22548. return false;
  22549. // compare lengths - can save a lot of time
  22550. if (this.length != array.length)
  22551. return false;
  22552. for (var i = 0, l = this.length; i < l; i++) {
  22553. // Check if we have nested arrays
  22554. if (this[i] instanceof Array && array[i] instanceof Array) {
  22555. // recurse into the nested arrays
  22556. if (!arrayEquals.apply(this[i], [array[i]]))
  22557. return false;
  22558. } else if (this[i] != array[i]) {
  22559. // Warning - two different object instances will never be equal:
  22560. // {x:20} != {x:20}
  22561. return false;
  22562. }
  22563. }
  22564. return true;
  22565. }
  22566. },{}],80:[function(require,module,exports){
  22567. exports.Interop = require('./interop');
  22568. },{"./interop":81}],81:[function(require,module,exports){
  22569. var transform = require('./transform');
  22570. var arrayEquals = require('./array-equals');
  22571. function Interop() { }
  22572. module.exports = Interop;
  22573. /**
  22574. * This map holds the most recent Plan A offer/answer SDP that was converted
  22575. * to Plan B, with the SDP type ('offer' or 'answer') as keys and the SDP
  22576. * string as values.
  22577. *
  22578. * @type {{}}
  22579. */
  22580. var cache = {};
  22581. /**
  22582. * This method transforms a Plan A SDP to an equivalent Plan B SDP. A
  22583. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  22584. * application.
  22585. *
  22586. * @param desc
  22587. * @returns {*}
  22588. */
  22589. Interop.prototype.toPlanB = function(desc) {
  22590. //#region Preliminary input validation.
  22591. if (typeof desc !== 'object' || desc === null ||
  22592. typeof desc.sdp !== 'string') {
  22593. console.warn('An empty description was passed as an argument.');
  22594. return desc;
  22595. }
  22596. // Objectify the SDP for easier manipulation.
  22597. var session = transform.parse(desc.sdp);
  22598. // If the SDP contains no media, there's nothing to transform.
  22599. if (typeof session.media === 'undefined' ||
  22600. !Array.isArray(session.media) || session.media.length === 0) {
  22601. console.warn('The description has no media.');
  22602. return desc;
  22603. }
  22604. // Try some heuristics to "make sure" this is a Plan A SDP. Plan B SDP has
  22605. // a video, an audio and a data "channel" at most.
  22606. if (session.media.length <= 3 && session.media.every(function(m) {
  22607. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  22608. })) {
  22609. console.warn('This description does not look like Plan A.');
  22610. return desc;
  22611. }
  22612. //#endregion
  22613. // Plan A SDP is our "precious". Cache it for later use in the Plan B ->
  22614. // Plan A transformation.
  22615. cache[desc.type] = desc.sdp;
  22616. //#region Convert from Plan A to Plan B.
  22617. // We rebuild the session.media array.
  22618. var media = session.media;
  22619. session.media = [];
  22620. // Associative array that maps channel types to channel objects for fast
  22621. // access to channel objects by their type, e.g. channels['audio']->channel
  22622. // obj.
  22623. var channels = {};
  22624. // Used to build the group:BUNDLE value after the channels construction
  22625. // loop.
  22626. var types = [];
  22627. // Implode the Plan A m-lines/tracks into Plan B "channels".
  22628. media.forEach(function(mLine) {
  22629. // rtcp-mux is required in the Plan B SDP.
  22630. if (typeof mLine.rtcpMux !== 'string' ||
  22631. mLine.rtcpMux !== 'rtcp-mux') {
  22632. throw new Error('Cannot convert to Plan B because m-lines ' +
  22633. 'without the rtcp-mux attribute were found.');
  22634. }
  22635. // If we don't have a channel for this mLine.type, then use this mLine
  22636. // as the channel basis.
  22637. if (typeof channels[mLine.type] === 'undefined') {
  22638. channels[mLine.type] = mLine;
  22639. }
  22640. // Add sources to the channel and handle a=msid.
  22641. if (typeof mLine.sources === 'object') {
  22642. Object.keys(mLine.sources).forEach(function(ssrc) {
  22643. // Assign the sources to the channel.
  22644. channels[mLine.type].sources[ssrc] = mLine.sources[ssrc];
  22645. // In Plan B the msid is an SSRC attribute. Also, we don't care
  22646. // about the obsolete label and mslabel attributes.
  22647. channels[mLine.type].sources[ssrc].msid = mLine.msid;
  22648. // NOTE ssrcs in ssrc groups will share msids, as
  22649. // draft-uberti-rtcweb-plan-00 mandates.
  22650. });
  22651. }
  22652. // Add ssrc groups to the channel.
  22653. if (typeof mLine.ssrcGroups !== 'undefined' &&
  22654. Array.isArray(mLine.ssrcGroups)) {
  22655. // Create the ssrcGroups array, if it's not defined.
  22656. if (typeof channel.ssrcGroups === 'undefined' ||
  22657. !Array.isArray(channel.ssrcGroups)) {
  22658. channel.ssrcGroups = [];
  22659. }
  22660. channel.ssrcGroups = channel.ssrcGroups.concat(mLine.ssrcGroups);
  22661. }
  22662. if (channels[mLine.type] === mLine) {
  22663. // Copy ICE related stuff from the principal media line.
  22664. mLine.candidates = media[0].candidates;
  22665. mLine.iceUfrag = media[0].iceUfrag;
  22666. mLine.icePwd = media[0].icePwd;
  22667. mLine.fingerprint = media[0].fingerprint;
  22668. // Plan B mids are in ['audio', 'video', 'data']
  22669. mLine.mid = mLine.type;
  22670. // Plan B doesn't support/need the bundle-only attribute.
  22671. delete mLine.bundleOnly;
  22672. // In Plan B the msid is an SSRC attribute.
  22673. delete mLine.msid;
  22674. // Used to build the group:BUNDLE value after this loop.
  22675. types.push(mLine.type);
  22676. // Add the channel to the new media array.
  22677. session.media.push(mLine);
  22678. }
  22679. });
  22680. // We regenerate the BUNDLE group with the new mids.
  22681. session.groups.every(function(group) {
  22682. if (group.type === 'BUNDLE') {
  22683. group.mids = types.join(' ');
  22684. return false;
  22685. } else {
  22686. return true;
  22687. }
  22688. });
  22689. // msid semantic
  22690. session.msidSemantic = {
  22691. semantic: 'WMS',
  22692. token: '*'
  22693. };
  22694. var resStr = transform.write(session);
  22695. return new RTCSessionDescription({
  22696. type: desc.type,
  22697. sdp: resStr
  22698. });
  22699. //#endregion
  22700. };
  22701. /**
  22702. * This method transforms a Plan B SDP to an equivalent Plan A SDP. A
  22703. * PeerConnection wrapper transforms the SDP to Plan A before passing it to FF.
  22704. *
  22705. * @param desc
  22706. * @returns {*}
  22707. */
  22708. Interop.prototype.toPlanA = function(desc) {
  22709. //#region Preliminary input validation.
  22710. if (typeof desc !== 'object' || desc === null ||
  22711. typeof desc.sdp !== 'string') {
  22712. console.warn('An empty description was passed as an argument.');
  22713. return desc;
  22714. }
  22715. var session = transform.parse(desc.sdp);
  22716. // If the SDP contains no media, there's nothing to transform.
  22717. if (typeof session.media === 'undefined' ||
  22718. !Array.isArray(session.media) || session.media.length === 0) {
  22719. console.warn('The description has no media.');
  22720. return desc;
  22721. }
  22722. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  22723. // a video, an audio and a data "channel" at most.
  22724. if (session.media.length > 3 || !session.media.every(function(m) {
  22725. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  22726. })) {
  22727. console.warn('This description does not look like Plan B.');
  22728. return desc;
  22729. }
  22730. // Make sure this Plan B SDP can be converted to a Plan A SDP.
  22731. var mids = [];
  22732. session.media.forEach(function(m) {
  22733. mids.push(m.mid);
  22734. });
  22735. var hasBundle = false;
  22736. if (typeof session.groups !== 'undefined' &&
  22737. Array.isArray(session.groups)) {
  22738. hasBundle = session.groups.every(function(g) {
  22739. return g.type !== 'BUNDLE' ||
  22740. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  22741. });
  22742. }
  22743. if (!hasBundle) {
  22744. throw new Error("Cannot convert to Plan A because m-lines that are " +
  22745. "not bundled were found.");
  22746. }
  22747. //#endregion
  22748. //#region Convert from Plan B to Plan A.
  22749. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  22750. // rebuild an equivalent Plan A offer/answer.
  22751. //
  22752. // For example, if this is a local answer (in Plan A style) that we convert
  22753. // to Plan B prior to handing it over to the application (the
  22754. // PeerConnection wrapper called us, for instance, after a successful
  22755. // createAnswer), we want to remember the m-line at which we've seen the
  22756. // (local) SSRC. That's because when the application wants to do call the
  22757. // SLD method, forcing us to do the inverse transformation (from Plan B to
  22758. // Plan A), we need to know to which m-line to assign the (local) SSRC. We
  22759. // also need to know all the other m-lines that the original answer had and
  22760. // include them in the transformed answer as well.
  22761. //
  22762. // Another example is if this is a remote offer that we convert to Plan B
  22763. // prior to giving it to the application, we want to remember the mid at
  22764. // which we've seen the (remote) SSRC.
  22765. //
  22766. // In the iteration that follows, we use the cached Plan A (if it exists)
  22767. // to assign mids to ssrcs.
  22768. var cached;
  22769. if (typeof cache[desc.type] !== 'undefined') {
  22770. cached = transform.parse(cache[desc.type]);
  22771. }
  22772. // A helper map that sends mids to m-line objects. We use it later to
  22773. // rebuild the Plan A style session.media array.
  22774. var media = {};
  22775. session.media.forEach(function(channel) {
  22776. if (typeof channel.rtcpMux !== 'string' ||
  22777. channel.rtcpMux !== 'rtcp-mux') {
  22778. throw new Error("Cannot convert to Plan A because m-lines " +
  22779. "without the rtcp-mux attribute were found.");
  22780. }
  22781. // With rtcp-mux and bundle all the channels should have the same ICE
  22782. // stuff.
  22783. var sources = channel.sources;
  22784. var ssrcGroups = channel.ssrcGroups;
  22785. var candidates = channel.candidates;
  22786. var iceUfrag = channel.iceUfrag;
  22787. var icePwd = channel.icePwd;
  22788. var fingerprint = channel.fingerprint;
  22789. var port = channel.port;
  22790. // We'll use the "channel" object as a prototype for each new "mLine"
  22791. // that we create, but first we need to clean it up a bit.
  22792. delete channel.sources;
  22793. delete channel.ssrcGroups;
  22794. delete channel.candidates;
  22795. delete channel.iceUfrag;
  22796. delete channel.icePwd;
  22797. delete channel.fingerprint;
  22798. delete channel.port;
  22799. delete channel.mid;
  22800. // inverted ssrc group map
  22801. var invertedGroups = {};
  22802. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  22803. ssrcGroups.forEach(function (ssrcGroup) {
  22804. // TODO(gp) find out how to receive simulcast with FF. For the
  22805. // time being, hide it.
  22806. if (ssrcGroup.semantics === 'SIM') {
  22807. return;
  22808. }
  22809. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  22810. Array.isArray(ssrcGroup.ssrcs)) {
  22811. ssrcGroup.ssrcs.forEach(function (ssrc) {
  22812. if (typeof invertedGroups[ssrc] === 'undefined') {
  22813. invertedGroups[ssrc] = [];
  22814. }
  22815. invertedGroups[ssrc].push(ssrcGroup);
  22816. });
  22817. }
  22818. });
  22819. }
  22820. // ssrc to m-line index.
  22821. var mLines = {};
  22822. if (typeof sources === 'object') {
  22823. // Explode the Plan B channel sources with one m-line per source.
  22824. Object.keys(sources).forEach(function(ssrc) {
  22825. var mLine;
  22826. if (typeof invertedGroups[ssrc] !== 'undefined' &&
  22827. Array.isArray(invertedGroups[ssrc])) {
  22828. invertedGroups[ssrc].every(function (ssrcGroup) {
  22829. // ssrcGroup.ssrcs *is* an Array, no need to check
  22830. // again here.
  22831. return ssrcGroup.ssrcs.every(function (related) {
  22832. if (typeof mLines[related] === 'object') {
  22833. mLine = mLines[related];
  22834. return false;
  22835. } else {
  22836. return true;
  22837. }
  22838. });
  22839. });
  22840. }
  22841. if (typeof mLine === 'object') {
  22842. // the m-line already exists. Just add the source.
  22843. mLine.sources[ssrc] = sources[ssrc];
  22844. delete sources[ssrc].msid;
  22845. } else {
  22846. // Use the "channel" as a prototype for the "mLine".
  22847. mLine = Object.create(channel);
  22848. mLines[ssrc] = mLine;
  22849. // Assign the msid of the source to the m-line.
  22850. mLine.msid = sources[ssrc].msid;
  22851. delete sources[ssrc].msid;
  22852. // We assign one SSRC per media line.
  22853. mLine.sources = {};
  22854. mLine.sources[ssrc] = sources[ssrc];
  22855. mLine.ssrcGroups = invertedGroups[ssrc];
  22856. // Use the cached Plan A SDP (if it exists) to assign SSRCs to
  22857. // mids.
  22858. if (typeof cached !== 'undefined' &&
  22859. typeof cached.media !== 'undefined' &&
  22860. Array.isArray(cached.media)) {
  22861. cached.media.forEach(function(m) {
  22862. if (typeof m.sources === 'object') {
  22863. Object.keys(m.sources).forEach(function(s) {
  22864. if (s === ssrc) {
  22865. mLine.mid = m.mid;
  22866. }
  22867. });
  22868. }
  22869. });
  22870. }
  22871. if (typeof mLine.mid === 'undefined') {
  22872. // If this is an SSRC that we see for the first time assign
  22873. // it a new mid. This is typically the case when this
  22874. // method is called to transform a remote description for
  22875. // the first time or when there is a new SSRC in the remote
  22876. // description because a new peer has joined the
  22877. // conference. Local SSRCs should have already been added
  22878. // to the map in the toPlanB method.
  22879. //
  22880. // Because FF generates answers in Plan A style, we MUST
  22881. // already have a cached answer with all the local SSRCs
  22882. // mapped to some mLine/mid.
  22883. if (desc.type === 'answer') {
  22884. throw new Error("An unmapped SSRC was found.");
  22885. }
  22886. mLine.mid = [channel.type, '-', ssrc].join('');
  22887. }
  22888. // Include the candidates in the 1st media line.
  22889. mLine.candidates = candidates;
  22890. mLine.iceUfrag = iceUfrag;
  22891. mLine.icePwd = icePwd;
  22892. mLine.fingerprint = fingerprint;
  22893. mLine.port = port;
  22894. media[mLine.mid] = mLine;
  22895. }
  22896. });
  22897. }
  22898. });
  22899. // Rebuild the media array in the right order and add the missing mLines
  22900. // (missing from the Plan B SDP).
  22901. session.media = [];
  22902. mids = []; // reuse
  22903. if (desc.type === 'answer') {
  22904. // The media lines in the answer must match the media lines in the
  22905. // offer. The order is important too. Here we use the cached offer to
  22906. // find the m-lines that are missing (from the converted answer), and
  22907. // use the cached answer to complete the converted answer.
  22908. if (typeof cache['offer'] === 'undefined') {
  22909. throw new Error("An answer is being processed but we couldn't " +
  22910. "find a cached offer.");
  22911. }
  22912. var cachedOffer = transform.parse(cache['offer']);
  22913. if (typeof cachedOffer === 'undefined' ||
  22914. typeof cachedOffer.media === 'undefined' ||
  22915. !Array.isArray(cachedOffer.media)) {
  22916. // FIXME(gp) is this really a problem in the general case?
  22917. throw new Error("The cached offer has no media.");
  22918. }
  22919. cachedOffer.media.forEach(function(mo) {
  22920. var mLine;
  22921. if (typeof media[mo.mid] === 'undefined') {
  22922. // This is probably an m-line containing a remote track only.
  22923. // It MUST exist in the cached answer as a remote track only
  22924. // mLine.
  22925. cached.media.every(function(ma) {
  22926. if (mo.mid == ma.mid) {
  22927. mLine = ma;
  22928. return false;
  22929. } else {
  22930. return true;
  22931. }
  22932. });
  22933. } else {
  22934. mLine = media[mo.mid];
  22935. }
  22936. if (typeof mLine === 'undefined') {
  22937. throw new Error("The cached offer contains an m-line that " +
  22938. "doesn't exist neither in the cached answer nor in " +
  22939. "the converted answer.");
  22940. }
  22941. session.media.push(mLine);
  22942. mids.push(mLine.mid);
  22943. });
  22944. } else {
  22945. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  22946. // under any circumstances. If we are no longer interested in sending a
  22947. // track, we just remove the msid and ssrc attributes and set it to
  22948. // either a=recvonly (as the reofferer, we must use recvonly if the
  22949. // other side was previously sending on the m-section, but we can also
  22950. // leave the possibility open if it wasn't previously in use), or
  22951. // a=inacive.
  22952. if (typeof cached !== 'undefined' &&
  22953. typeof cached.media !== 'undefined' &&
  22954. Array.isArray(cached.media)) {
  22955. cached.media.forEach(function(pm) {
  22956. mids.push(pm.mid);
  22957. if (typeof media[pm.mid] !== 'undefined') {
  22958. session.media.push(media[pm.mid]);
  22959. } else {
  22960. delete pm.msid;
  22961. delete pm.sources;
  22962. delete pm.ssrcGroups;
  22963. pm.direction = 'recvonly';
  22964. session.media.push(pm);
  22965. }
  22966. });
  22967. }
  22968. // Add all the remaining (new) m-lines of the transformed SDP.
  22969. Object.keys(media).forEach(function(mid) {
  22970. if (mids.indexOf(mid) === -1) {
  22971. mids.push(mid);
  22972. session.media.push(media[mid]);
  22973. }
  22974. });
  22975. }
  22976. // We regenerate the BUNDLE group (since we regenerated the mids)
  22977. session.groups.every(function(group) {
  22978. if (group.type === 'BUNDLE') {
  22979. group.mids = mids.join(' ');
  22980. return false;
  22981. } else {
  22982. return true;
  22983. }
  22984. });
  22985. // msid semantic
  22986. session.msidSemantic = {
  22987. semantic: 'WMS',
  22988. token: '*'
  22989. };
  22990. var resStr = transform.write(session);
  22991. // Cache the transformed SDP (Plan A) for later re-use in this function.
  22992. cache[desc.type] = resStr;
  22993. return new RTCSessionDescription({
  22994. type: desc.type,
  22995. sdp: resStr
  22996. });
  22997. //#endregion
  22998. };
  22999. },{"./array-equals":79,"./transform":82}],82:[function(require,module,exports){
  23000. var transform = require('sdp-transform');
  23001. exports.write = function(session, opts) {
  23002. if (typeof session !== 'undefined' &&
  23003. typeof session.media !== 'undefined' &&
  23004. Array.isArray(session.media)) {
  23005. session.media.forEach(function (mLine) {
  23006. // expand sources to ssrcs
  23007. if (typeof mLine.sources !== 'undefined' &&
  23008. Object.keys(mLine.sources).length !== 0) {
  23009. mLine.ssrcs = [];
  23010. Object.keys(mLine.sources).forEach(function (ssrc) {
  23011. var source = mLine.sources[ssrc];
  23012. Object.keys(source).forEach(function (attribute) {
  23013. mLine.ssrcs.push({
  23014. id: ssrc,
  23015. attribute: attribute,
  23016. value: source[attribute]
  23017. });
  23018. });
  23019. });
  23020. delete mLine.sources;
  23021. }
  23022. // join ssrcs in ssrc groups
  23023. if (typeof mLine.ssrcGroups !== 'undefined' &&
  23024. Array.isArray(mLine.ssrcGroups)) {
  23025. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  23026. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  23027. Array.isArray(ssrcGroup.ssrcs)) {
  23028. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  23029. }
  23030. });
  23031. }
  23032. });
  23033. }
  23034. // join group mids
  23035. if (typeof session !== 'undefined' &&
  23036. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  23037. session.groups.forEach(function (g) {
  23038. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  23039. g.mids = g.mids.join(' ');
  23040. }
  23041. });
  23042. }
  23043. return transform.write(session, opts);
  23044. };
  23045. exports.parse = function(sdp) {
  23046. var session = transform.parse(sdp);
  23047. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  23048. Array.isArray(session.media)) {
  23049. session.media.forEach(function (mLine) {
  23050. // group sources attributes by ssrc
  23051. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  23052. mLine.sources = {};
  23053. mLine.ssrcs.forEach(function (ssrc) {
  23054. if (!mLine.sources[ssrc.id])
  23055. mLine.sources[ssrc.id] = {};
  23056. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  23057. });
  23058. delete mLine.ssrcs;
  23059. }
  23060. // split ssrcs in ssrc groups
  23061. if (typeof mLine.ssrcGroups !== 'undefined' &&
  23062. Array.isArray(mLine.ssrcGroups)) {
  23063. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  23064. if (typeof ssrcGroup.ssrcs === 'string') {
  23065. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  23066. }
  23067. });
  23068. }
  23069. });
  23070. }
  23071. // split group mids
  23072. if (typeof session !== 'undefined' &&
  23073. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  23074. session.groups.forEach(function (g) {
  23075. if (typeof g.mids === 'string') {
  23076. g.mids = g.mids.split(' ');
  23077. }
  23078. });
  23079. }
  23080. return session;
  23081. };
  23082. },{"sdp-transform":84}],83:[function(require,module,exports){
  23083. var grammar = module.exports = {
  23084. v: [{
  23085. name: 'version',
  23086. reg: /^(\d*)$/
  23087. }],
  23088. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  23089. // NB: sessionId will be a String in most cases because it is huge
  23090. name: 'origin',
  23091. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  23092. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  23093. format: "%s %s %d %s IP%d %s"
  23094. }],
  23095. // default parsing of these only (though some of these feel outdated)
  23096. s: [{ name: 'name' }],
  23097. i: [{ name: 'description' }],
  23098. u: [{ name: 'uri' }],
  23099. e: [{ name: 'email' }],
  23100. p: [{ name: 'phone' }],
  23101. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  23102. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  23103. //k: [{}], // outdated thing ignored
  23104. t: [{ //t=0 0
  23105. name: 'timing',
  23106. reg: /^(\d*) (\d*)/,
  23107. names: ['start', 'stop'],
  23108. format: "%d %d"
  23109. }],
  23110. c: [{ //c=IN IP4 10.47.197.26
  23111. name: 'connection',
  23112. reg: /^IN IP(\d) (\S*)/,
  23113. names: ['version', 'ip'],
  23114. format: "IN IP%d %s"
  23115. }],
  23116. b: [{ //b=AS:4000
  23117. push: 'bandwidth',
  23118. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  23119. names: ['type', 'limit'],
  23120. format: "%s:%s"
  23121. }],
  23122. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  23123. // NB: special - pushes to session
  23124. // TODO: rtp/fmtp should be filtered by the payloads found here?
  23125. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  23126. names: ['type', 'port', 'protocol', 'payloads'],
  23127. format: "%s %d %s %s"
  23128. }],
  23129. a: [
  23130. { //a=rtpmap:110 opus/48000/2
  23131. push: 'rtp',
  23132. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  23133. names: ['payload', 'codec', 'rate', 'encoding'],
  23134. format: function (o) {
  23135. return (o.encoding) ?
  23136. "rtpmap:%d %s/%s/%s":
  23137. "rtpmap:%d %s/%s";
  23138. }
  23139. },
  23140. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  23141. push: 'fmtp',
  23142. reg: /^fmtp:(\d*) (\S*)/,
  23143. names: ['payload', 'config'],
  23144. format: "fmtp:%d %s"
  23145. },
  23146. { //a=control:streamid=0
  23147. name: 'control',
  23148. reg: /^control:(.*)/,
  23149. format: "control:%s"
  23150. },
  23151. { //a=rtcp:65179 IN IP4 193.84.77.194
  23152. name: 'rtcp',
  23153. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  23154. names: ['port', 'netType', 'ipVer', 'address'],
  23155. format: function (o) {
  23156. return (o.address != null) ?
  23157. "rtcp:%d %s IP%d %s":
  23158. "rtcp:%d";
  23159. }
  23160. },
  23161. { //a=rtcp-fb:98 trr-int 100
  23162. push: 'rtcpFbTrrInt',
  23163. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  23164. names: ['payload', 'value'],
  23165. format: "rtcp-fb:%d trr-int %d"
  23166. },
  23167. { //a=rtcp-fb:98 nack rpsi
  23168. push: 'rtcpFb',
  23169. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  23170. names: ['payload', 'type', 'subtype'],
  23171. format: function (o) {
  23172. return (o.subtype != null) ?
  23173. "rtcp-fb:%s %s %s":
  23174. "rtcp-fb:%s %s";
  23175. }
  23176. },
  23177. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  23178. //a=extmap:1/recvonly URI-gps-string
  23179. push: 'ext',
  23180. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  23181. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  23182. format: function (o) {
  23183. return (o.config != null) ?
  23184. "extmap:%s %s %s":
  23185. "extmap:%s %s";
  23186. }
  23187. },
  23188. {
  23189. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  23190. push: 'crypto',
  23191. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  23192. names: ['id', 'suite', 'config', 'sessionConfig'],
  23193. format: function (o) {
  23194. return (o.sessionConfig != null) ?
  23195. "crypto:%d %s %s %s":
  23196. "crypto:%d %s %s";
  23197. }
  23198. },
  23199. { //a=setup:actpass
  23200. name: 'setup',
  23201. reg: /^setup:(\w*)/,
  23202. format: "setup:%s"
  23203. },
  23204. { //a=mid:1
  23205. name: 'mid',
  23206. reg: /^mid:([^\s]*)/,
  23207. format: "mid:%s"
  23208. },
  23209. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  23210. name: 'msid',
  23211. reg: /^msid:(.*)/,
  23212. format: "msid:%s"
  23213. },
  23214. { //a=ptime:20
  23215. name: 'ptime',
  23216. reg: /^ptime:(\d*)/,
  23217. format: "ptime:%d"
  23218. },
  23219. { //a=maxptime:60
  23220. name: 'maxptime',
  23221. reg: /^maxptime:(\d*)/,
  23222. format: "maxptime:%d"
  23223. },
  23224. { //a=sendrecv
  23225. name: 'direction',
  23226. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  23227. },
  23228. { //a=ice-lite
  23229. name: 'icelite',
  23230. reg: /^(ice-lite)/
  23231. },
  23232. { //a=ice-ufrag:F7gI
  23233. name: 'iceUfrag',
  23234. reg: /^ice-ufrag:(\S*)/,
  23235. format: "ice-ufrag:%s"
  23236. },
  23237. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  23238. name: 'icePwd',
  23239. reg: /^ice-pwd:(\S*)/,
  23240. format: "ice-pwd:%s"
  23241. },
  23242. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  23243. name: 'fingerprint',
  23244. reg: /^fingerprint:(\S*) (\S*)/,
  23245. names: ['type', 'hash'],
  23246. format: "fingerprint:%s %s"
  23247. },
  23248. {
  23249. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  23250. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  23251. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  23252. push:'candidates',
  23253. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  23254. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  23255. format: function (o) {
  23256. var str = "candidate:%s %d %s %d %s %d typ %s";
  23257. // NB: candidate has two optional chunks, so %void middle one if it's missing
  23258. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  23259. if (o.generation != null) {
  23260. str += " generation %d";
  23261. }
  23262. return str;
  23263. }
  23264. },
  23265. { //a=end-of-candidates (keep after the candidates line for readability)
  23266. name: 'endOfCandidates',
  23267. reg: /^(end-of-candidates)/
  23268. },
  23269. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  23270. name: 'remoteCandidates',
  23271. reg: /^remote-candidates:(.*)/,
  23272. format: "remote-candidates:%s"
  23273. },
  23274. { //a=ice-options:google-ice
  23275. name: 'iceOptions',
  23276. reg: /^ice-options:(\S*)/,
  23277. format: "ice-options:%s"
  23278. },
  23279. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  23280. push: "ssrcs",
  23281. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  23282. names: ['id', 'attribute', 'value'],
  23283. format: "ssrc:%d %s:%s"
  23284. },
  23285. { //a=ssrc-group:FEC 1 2
  23286. push: "ssrcGroups",
  23287. reg: /^ssrc-group:(\w*) (.*)/,
  23288. names: ['semantics', 'ssrcs'],
  23289. format: "ssrc-group:%s %s"
  23290. },
  23291. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  23292. name: "msidSemantic",
  23293. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  23294. names: ['semantic', 'token'],
  23295. format: "msid-semantic: %s %s" // space after ":" is not accidental
  23296. },
  23297. { //a=group:BUNDLE audio video
  23298. push: 'groups',
  23299. reg: /^group:(\w*) (.*)/,
  23300. names: ['type', 'mids'],
  23301. format: "group:%s %s"
  23302. },
  23303. { //a=rtcp-mux
  23304. name: 'rtcpMux',
  23305. reg: /^(rtcp-mux)/
  23306. },
  23307. { // any a= that we don't understand is kepts verbatim on media.invalid
  23308. push: 'invalid',
  23309. names: ["value"]
  23310. }
  23311. ]
  23312. };
  23313. // set sensible defaults to avoid polluting the grammar with boring details
  23314. Object.keys(grammar).forEach(function (key) {
  23315. var objs = grammar[key];
  23316. objs.forEach(function (obj) {
  23317. if (!obj.reg) {
  23318. obj.reg = /(.*)/;
  23319. }
  23320. if (!obj.format) {
  23321. obj.format = "%s";
  23322. }
  23323. });
  23324. });
  23325. },{}],84:[function(require,module,exports){
  23326. var parser = require('./parser');
  23327. var writer = require('./writer');
  23328. exports.write = writer;
  23329. exports.parse = parser.parse;
  23330. exports.parseFmtpConfig = parser.parseFmtpConfig;
  23331. exports.parsePayloads = parser.parsePayloads;
  23332. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  23333. },{"./parser":85,"./writer":86}],85:[function(require,module,exports){
  23334. var toIntIfInt = function (v) {
  23335. return String(Number(v)) === v ? Number(v) : v;
  23336. };
  23337. var attachProperties = function (match, location, names, rawName) {
  23338. if (rawName && !names) {
  23339. location[rawName] = toIntIfInt(match[1]);
  23340. }
  23341. else {
  23342. for (var i = 0; i < names.length; i += 1) {
  23343. if (match[i+1] != null) {
  23344. location[names[i]] = toIntIfInt(match[i+1]);
  23345. }
  23346. }
  23347. }
  23348. };
  23349. var parseReg = function (obj, location, content) {
  23350. var needsBlank = obj.name && obj.names;
  23351. if (obj.push && !location[obj.push]) {
  23352. location[obj.push] = [];
  23353. }
  23354. else if (needsBlank && !location[obj.name]) {
  23355. location[obj.name] = {};
  23356. }
  23357. var keyLocation = obj.push ?
  23358. {} : // blank object that will be pushed
  23359. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  23360. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  23361. if (obj.push) {
  23362. location[obj.push].push(keyLocation);
  23363. }
  23364. };
  23365. var grammar = require('./grammar');
  23366. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  23367. exports.parse = function (sdp) {
  23368. var session = {}
  23369. , media = []
  23370. , location = session; // points at where properties go under (one of the above)
  23371. // parse lines we understand
  23372. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  23373. var type = l[0];
  23374. var content = l.slice(2);
  23375. if (type === 'm') {
  23376. media.push({rtp: [], fmtp: []});
  23377. location = media[media.length-1]; // point at latest media line
  23378. }
  23379. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  23380. var obj = grammar[type][j];
  23381. if (obj.reg.test(content)) {
  23382. return parseReg(obj, location, content);
  23383. }
  23384. }
  23385. });
  23386. session.media = media; // link it up
  23387. return session;
  23388. };
  23389. var fmtpReducer = function (acc, expr) {
  23390. var s = expr.split('=');
  23391. if (s.length === 2) {
  23392. acc[s[0]] = toIntIfInt(s[1]);
  23393. }
  23394. return acc;
  23395. };
  23396. exports.parseFmtpConfig = function (str) {
  23397. return str.split(';').reduce(fmtpReducer, {});
  23398. };
  23399. exports.parsePayloads = function (str) {
  23400. return str.split(' ').map(Number);
  23401. };
  23402. exports.parseRemoteCandidates = function (str) {
  23403. var candidates = [];
  23404. var parts = str.split(' ').map(toIntIfInt);
  23405. for (var i = 0; i < parts.length; i += 3) {
  23406. candidates.push({
  23407. component: parts[i],
  23408. ip: parts[i + 1],
  23409. port: parts[i + 2]
  23410. });
  23411. }
  23412. return candidates;
  23413. };
  23414. },{"./grammar":83}],86:[function(require,module,exports){
  23415. var grammar = require('./grammar');
  23416. // customized util.format - discards excess arguments and can void middle ones
  23417. var formatRegExp = /%[sdv%]/g;
  23418. var format = function (formatStr) {
  23419. var i = 1;
  23420. var args = arguments;
  23421. var len = args.length;
  23422. return formatStr.replace(formatRegExp, function (x) {
  23423. if (i >= len) {
  23424. return x; // missing argument
  23425. }
  23426. var arg = args[i];
  23427. i += 1;
  23428. switch (x) {
  23429. case '%%':
  23430. return '%';
  23431. case '%s':
  23432. return String(arg);
  23433. case '%d':
  23434. return Number(arg);
  23435. case '%v':
  23436. return '';
  23437. }
  23438. });
  23439. // NB: we discard excess arguments - they are typically undefined from makeLine
  23440. };
  23441. var makeLine = function (type, obj, location) {
  23442. var str = obj.format instanceof Function ?
  23443. (obj.format(obj.push ? location : location[obj.name])) :
  23444. obj.format;
  23445. var args = [type + '=' + str];
  23446. if (obj.names) {
  23447. for (var i = 0; i < obj.names.length; i += 1) {
  23448. var n = obj.names[i];
  23449. if (obj.name) {
  23450. args.push(location[obj.name][n]);
  23451. }
  23452. else { // for mLine and push attributes
  23453. args.push(location[obj.names[i]]);
  23454. }
  23455. }
  23456. }
  23457. else {
  23458. args.push(location[obj.name]);
  23459. }
  23460. return format.apply(null, args);
  23461. };
  23462. // RFC specified order
  23463. // TODO: extend this with all the rest
  23464. var defaultOuterOrder = [
  23465. 'v', 'o', 's', 'i',
  23466. 'u', 'e', 'p', 'c',
  23467. 'b', 't', 'r', 'z', 'a'
  23468. ];
  23469. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  23470. module.exports = function (session, opts) {
  23471. opts = opts || {};
  23472. // ensure certain properties exist
  23473. if (session.version == null) {
  23474. session.version = 0; // "v=0" must be there (only defined version atm)
  23475. }
  23476. if (session.name == null) {
  23477. session.name = " "; // "s= " must be there if no meaningful name set
  23478. }
  23479. session.media.forEach(function (mLine) {
  23480. if (mLine.payloads == null) {
  23481. mLine.payloads = "";
  23482. }
  23483. });
  23484. var outerOrder = opts.outerOrder || defaultOuterOrder;
  23485. var innerOrder = opts.innerOrder || defaultInnerOrder;
  23486. var sdp = [];
  23487. // loop through outerOrder for matching properties on session
  23488. outerOrder.forEach(function (type) {
  23489. grammar[type].forEach(function (obj) {
  23490. if (obj.name in session && session[obj.name] != null) {
  23491. sdp.push(makeLine(type, obj, session));
  23492. }
  23493. else if (obj.push in session && session[obj.push] != null) {
  23494. session[obj.push].forEach(function (el) {
  23495. sdp.push(makeLine(type, obj, el));
  23496. });
  23497. }
  23498. });
  23499. });
  23500. // then for each media line, follow the innerOrder
  23501. session.media.forEach(function (mLine) {
  23502. sdp.push(makeLine('m', grammar.m[0], mLine));
  23503. innerOrder.forEach(function (type) {
  23504. grammar[type].forEach(function (obj) {
  23505. if (obj.name in mLine && mLine[obj.name] != null) {
  23506. sdp.push(makeLine(type, obj, mLine));
  23507. }
  23508. else if (obj.push in mLine && mLine[obj.push] != null) {
  23509. mLine[obj.push].forEach(function (el) {
  23510. sdp.push(makeLine(type, obj, el));
  23511. });
  23512. }
  23513. });
  23514. });
  23515. });
  23516. return sdp.join('\r\n') + '\r\n';
  23517. };
  23518. },{"./grammar":83}],87:[function(require,module,exports){
  23519. var MediaStreamType = {
  23520. VIDEO_TYPE: "Video",
  23521. AUDIO_TYPE: "Audio"
  23522. };
  23523. module.exports = MediaStreamType;
  23524. },{}],88:[function(require,module,exports){
  23525. var RTCBrowserType = {
  23526. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  23527. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  23528. };
  23529. module.exports = RTCBrowserType;
  23530. },{}],89:[function(require,module,exports){
  23531. var RTCEvents = {
  23532. LASTN_CHANGED: "rtc.lastn_changed",
  23533. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  23534. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  23535. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  23536. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  23537. SIMULCAST_START: "rtc.simlcast_start",
  23538. SIMULCAST_STOP: "rtc.simlcast_stop"
  23539. };
  23540. module.exports = RTCEvents;
  23541. },{}],90:[function(require,module,exports){
  23542. var Resolutions = {
  23543. "1080": {
  23544. width: 1920,
  23545. height: 1080,
  23546. order: 7
  23547. },
  23548. "fullhd": {
  23549. width: 1920,
  23550. height: 1080,
  23551. order: 7
  23552. },
  23553. "720": {
  23554. width: 1280,
  23555. height: 720,
  23556. order: 6
  23557. },
  23558. "hd": {
  23559. width: 1280,
  23560. height: 720,
  23561. order: 6
  23562. },
  23563. "960": {
  23564. width: 960,
  23565. height: 720,
  23566. order: 5
  23567. },
  23568. "640": {
  23569. width: 640,
  23570. height: 480,
  23571. order: 4
  23572. },
  23573. "vga": {
  23574. width: 640,
  23575. height: 480,
  23576. order: 4
  23577. },
  23578. "360": {
  23579. width: 640,
  23580. height: 360,
  23581. order: 3
  23582. },
  23583. "320": {
  23584. width: 320,
  23585. height: 240,
  23586. order: 2
  23587. },
  23588. "180": {
  23589. width: 320,
  23590. height: 180,
  23591. order: 1
  23592. }
  23593. };
  23594. module.exports = Resolutions;
  23595. },{}],91:[function(require,module,exports){
  23596. var StreamEventTypes = {
  23597. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  23598. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  23599. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  23600. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  23601. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  23602. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  23603. };
  23604. module.exports = StreamEventTypes;
  23605. },{}],92:[function(require,module,exports){
  23606. var UIEvents = {
  23607. NICKNAME_CHANGED: "UI.nickname_changed",
  23608. SELECTED_ENDPOINT: "UI.selected_endpoint",
  23609. PINNED_ENDPOINT: "UI.pinned_endpoint"
  23610. };
  23611. module.exports = UIEvents;
  23612. },{}],93:[function(require,module,exports){
  23613. var AuthenticationEvents = {
  23614. /**
  23615. * Event callback arguments:
  23616. * function(authenticationEnabled, userIdentity)
  23617. * authenticationEnabled - indicates whether authentication has been enabled
  23618. * in this session
  23619. * userIdentity - if user has been logged in then it contains user name. If
  23620. * contains 'null' or 'undefined' then user is not logged in.
  23621. */
  23622. IDENTITY_UPDATED: "authentication.identity_updated"
  23623. };
  23624. module.exports = AuthenticationEvents;
  23625. },{}],94:[function(require,module,exports){
  23626. var CQEvents = {
  23627. LOCALSTATS_UPDATED: "cq.localstats_updated",
  23628. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  23629. STOP: "cq.stop"
  23630. };
  23631. module.exports = CQEvents;
  23632. },{}],95:[function(require,module,exports){
  23633. var DesktopSharingEventTypes = {
  23634. INIT: "ds.init",
  23635. SWITCHING_DONE: "ds.switching_done",
  23636. NEW_STREAM_CREATED: "ds.new_stream_created"
  23637. };
  23638. module.exports = DesktopSharingEventTypes;
  23639. },{}],96:[function(require,module,exports){
  23640. module.exports = {
  23641. getLanguages : function () {
  23642. var languages = [];
  23643. for(var lang in this)
  23644. {
  23645. if(typeof this[lang] === "string")
  23646. languages.push(this[lang]);
  23647. }
  23648. return languages;
  23649. },
  23650. EN: "en",
  23651. BG: "bg",
  23652. DE: "de",
  23653. TR: "tr"
  23654. }
  23655. },{}],97:[function(require,module,exports){
  23656. var XMPPEvents = {
  23657. CONFERENCE_CERATED: "xmpp.conferenceCreated.jingle",
  23658. CALL_TERMINATED: "xmpp.callterminated.jingle",
  23659. CALL_INCOMING: "xmpp.callincoming.jingle",
  23660. DISPOSE_CONFERENCE: "xmpp.dispoce_confernce",
  23661. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  23662. KICKED: "xmpp.kicked",
  23663. BRIDGE_DOWN: "xmpp.bridge_down",
  23664. USER_ID_CHANGED: "xmpp.user_id_changed",
  23665. CHANGED_STREAMS: "xmpp.changed_streams",
  23666. MUC_JOINED: "xmpp.muc_joined",
  23667. MUC_ENTER: "xmpp.muc_enter",
  23668. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  23669. MUC_LEFT: "xmpp.muc_left",
  23670. MUC_DESTROYED: "xmpp.muc_destroyed",
  23671. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  23672. REMOTE_STATS: "xmpp.remote_stats",
  23673. LOCALROLE_CHANGED: "xmpp.localrole_changed",
  23674. PRESENCE_STATUS: "xmpp.presence_status",
  23675. RESERVATION_ERROR: "xmpp.room_reservation_error",
  23676. SUBJECT_CHANGED: "xmpp.subject_changed",
  23677. MESSAGE_RECEIVED: "xmpp.message_received",
  23678. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  23679. PASSWORD_REQUIRED: "xmpp.password_required",
  23680. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  23681. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  23682. ETHERPAD: "xmpp.etherpad"
  23683. };
  23684. module.exports = XMPPEvents;
  23685. },{}],98:[function(require,module,exports){
  23686. // Copyright Joyent, Inc. and other Node contributors.
  23687. //
  23688. // Permission is hereby granted, free of charge, to any person obtaining a
  23689. // copy of this software and associated documentation files (the
  23690. // "Software"), to deal in the Software without restriction, including
  23691. // without limitation the rights to use, copy, modify, merge, publish,
  23692. // distribute, sublicense, and/or sell copies of the Software, and to permit
  23693. // persons to whom the Software is furnished to do so, subject to the
  23694. // following conditions:
  23695. //
  23696. // The above copyright notice and this permission notice shall be included
  23697. // in all copies or substantial portions of the Software.
  23698. //
  23699. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  23700. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23701. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  23702. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  23703. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  23704. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  23705. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  23706. function EventEmitter() {
  23707. this._events = this._events || {};
  23708. this._maxListeners = this._maxListeners || undefined;
  23709. }
  23710. module.exports = EventEmitter;
  23711. // Backwards-compat with node 0.10.x
  23712. EventEmitter.EventEmitter = EventEmitter;
  23713. EventEmitter.prototype._events = undefined;
  23714. EventEmitter.prototype._maxListeners = undefined;
  23715. // By default EventEmitters will print a warning if more than 10 listeners are
  23716. // added to it. This is a useful default which helps finding memory leaks.
  23717. EventEmitter.defaultMaxListeners = 10;
  23718. // Obviously not all Emitters should be limited to 10. This function allows
  23719. // that to be increased. Set to zero for unlimited.
  23720. EventEmitter.prototype.setMaxListeners = function(n) {
  23721. if (!isNumber(n) || n < 0 || isNaN(n))
  23722. throw TypeError('n must be a positive number');
  23723. this._maxListeners = n;
  23724. return this;
  23725. };
  23726. EventEmitter.prototype.emit = function(type) {
  23727. var er, handler, len, args, i, listeners;
  23728. if (!this._events)
  23729. this._events = {};
  23730. // If there is no 'error' event listener then throw.
  23731. if (type === 'error') {
  23732. if (!this._events.error ||
  23733. (isObject(this._events.error) && !this._events.error.length)) {
  23734. er = arguments[1];
  23735. if (er instanceof Error) {
  23736. throw er; // Unhandled 'error' event
  23737. }
  23738. throw TypeError('Uncaught, unspecified "error" event.');
  23739. }
  23740. }
  23741. handler = this._events[type];
  23742. if (isUndefined(handler))
  23743. return false;
  23744. if (isFunction(handler)) {
  23745. switch (arguments.length) {
  23746. // fast cases
  23747. case 1:
  23748. handler.call(this);
  23749. break;
  23750. case 2:
  23751. handler.call(this, arguments[1]);
  23752. break;
  23753. case 3:
  23754. handler.call(this, arguments[1], arguments[2]);
  23755. break;
  23756. // slower
  23757. default:
  23758. len = arguments.length;
  23759. args = new Array(len - 1);
  23760. for (i = 1; i < len; i++)
  23761. args[i - 1] = arguments[i];
  23762. handler.apply(this, args);
  23763. }
  23764. } else if (isObject(handler)) {
  23765. len = arguments.length;
  23766. args = new Array(len - 1);
  23767. for (i = 1; i < len; i++)
  23768. args[i - 1] = arguments[i];
  23769. listeners = handler.slice();
  23770. len = listeners.length;
  23771. for (i = 0; i < len; i++)
  23772. listeners[i].apply(this, args);
  23773. }
  23774. return true;
  23775. };
  23776. EventEmitter.prototype.addListener = function(type, listener) {
  23777. var m;
  23778. if (!isFunction(listener))
  23779. throw TypeError('listener must be a function');
  23780. if (!this._events)
  23781. this._events = {};
  23782. // To avoid recursion in the case that type === "newListener"! Before
  23783. // adding it to the listeners, first emit "newListener".
  23784. if (this._events.newListener)
  23785. this.emit('newListener', type,
  23786. isFunction(listener.listener) ?
  23787. listener.listener : listener);
  23788. if (!this._events[type])
  23789. // Optimize the case of one listener. Don't need the extra array object.
  23790. this._events[type] = listener;
  23791. else if (isObject(this._events[type]))
  23792. // If we've already got an array, just append.
  23793. this._events[type].push(listener);
  23794. else
  23795. // Adding the second element, need to change to array.
  23796. this._events[type] = [this._events[type], listener];
  23797. // Check for listener leak
  23798. if (isObject(this._events[type]) && !this._events[type].warned) {
  23799. var m;
  23800. if (!isUndefined(this._maxListeners)) {
  23801. m = this._maxListeners;
  23802. } else {
  23803. m = EventEmitter.defaultMaxListeners;
  23804. }
  23805. if (m && m > 0 && this._events[type].length > m) {
  23806. this._events[type].warned = true;
  23807. console.error('(node) warning: possible EventEmitter memory ' +
  23808. 'leak detected. %d listeners added. ' +
  23809. 'Use emitter.setMaxListeners() to increase limit.',
  23810. this._events[type].length);
  23811. if (typeof console.trace === 'function') {
  23812. // not supported in IE 10
  23813. console.trace();
  23814. }
  23815. }
  23816. }
  23817. return this;
  23818. };
  23819. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  23820. EventEmitter.prototype.once = function(type, listener) {
  23821. if (!isFunction(listener))
  23822. throw TypeError('listener must be a function');
  23823. var fired = false;
  23824. function g() {
  23825. this.removeListener(type, g);
  23826. if (!fired) {
  23827. fired = true;
  23828. listener.apply(this, arguments);
  23829. }
  23830. }
  23831. g.listener = listener;
  23832. this.on(type, g);
  23833. return this;
  23834. };
  23835. // emits a 'removeListener' event iff the listener was removed
  23836. EventEmitter.prototype.removeListener = function(type, listener) {
  23837. var list, position, length, i;
  23838. if (!isFunction(listener))
  23839. throw TypeError('listener must be a function');
  23840. if (!this._events || !this._events[type])
  23841. return this;
  23842. list = this._events[type];
  23843. length = list.length;
  23844. position = -1;
  23845. if (list === listener ||
  23846. (isFunction(list.listener) && list.listener === listener)) {
  23847. delete this._events[type];
  23848. if (this._events.removeListener)
  23849. this.emit('removeListener', type, listener);
  23850. } else if (isObject(list)) {
  23851. for (i = length; i-- > 0;) {
  23852. if (list[i] === listener ||
  23853. (list[i].listener && list[i].listener === listener)) {
  23854. position = i;
  23855. break;
  23856. }
  23857. }
  23858. if (position < 0)
  23859. return this;
  23860. if (list.length === 1) {
  23861. list.length = 0;
  23862. delete this._events[type];
  23863. } else {
  23864. list.splice(position, 1);
  23865. }
  23866. if (this._events.removeListener)
  23867. this.emit('removeListener', type, listener);
  23868. }
  23869. return this;
  23870. };
  23871. EventEmitter.prototype.removeAllListeners = function(type) {
  23872. var key, listeners;
  23873. if (!this._events)
  23874. return this;
  23875. // not listening for removeListener, no need to emit
  23876. if (!this._events.removeListener) {
  23877. if (arguments.length === 0)
  23878. this._events = {};
  23879. else if (this._events[type])
  23880. delete this._events[type];
  23881. return this;
  23882. }
  23883. // emit removeListener for all listeners on all events
  23884. if (arguments.length === 0) {
  23885. for (key in this._events) {
  23886. if (key === 'removeListener') continue;
  23887. this.removeAllListeners(key);
  23888. }
  23889. this.removeAllListeners('removeListener');
  23890. this._events = {};
  23891. return this;
  23892. }
  23893. listeners = this._events[type];
  23894. if (isFunction(listeners)) {
  23895. this.removeListener(type, listeners);
  23896. } else {
  23897. // LIFO order
  23898. while (listeners.length)
  23899. this.removeListener(type, listeners[listeners.length - 1]);
  23900. }
  23901. delete this._events[type];
  23902. return this;
  23903. };
  23904. EventEmitter.prototype.listeners = function(type) {
  23905. var ret;
  23906. if (!this._events || !this._events[type])
  23907. ret = [];
  23908. else if (isFunction(this._events[type]))
  23909. ret = [this._events[type]];
  23910. else
  23911. ret = this._events[type].slice();
  23912. return ret;
  23913. };
  23914. EventEmitter.listenerCount = function(emitter, type) {
  23915. var ret;
  23916. if (!emitter._events || !emitter._events[type])
  23917. ret = 0;
  23918. else if (isFunction(emitter._events[type]))
  23919. ret = 1;
  23920. else
  23921. ret = emitter._events[type].length;
  23922. return ret;
  23923. };
  23924. function isFunction(arg) {
  23925. return typeof arg === 'function';
  23926. }
  23927. function isNumber(arg) {
  23928. return typeof arg === 'number';
  23929. }
  23930. function isObject(arg) {
  23931. return typeof arg === 'object' && arg !== null;
  23932. }
  23933. function isUndefined(arg) {
  23934. return arg === void 0;
  23935. }
  23936. },{}]},{},[1])(1)
  23937. });