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.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599
  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. this.DTMF = require("./modules/DTMF/DTMF");
  19. this.members = require("./modules/members/MemberList");
  20. }
  21. };
  22. function init() {
  23. APP.RTC.start();
  24. APP.xmpp.start();
  25. APP.statistics.start();
  26. APP.connectionquality.init();
  27. // Set default desktop sharing method
  28. APP.desktopsharing.init();
  29. APP.keyboardshortcut.init();
  30. APP.members.start();
  31. }
  32. $(document).ready(function () {
  33. var URLPRocessor = require("./modules/URLProcessor/URLProcessor");
  34. URLPRocessor.setConfigParametersFromUrl();
  35. APP.init();
  36. APP.translation.init();
  37. if(APP.API.isEnabled())
  38. APP.API.init();
  39. APP.UI.start(init);
  40. });
  41. $(window).bind('beforeunload', function () {
  42. if(APP.API.isEnabled())
  43. APP.API.dispose();
  44. });
  45. module.exports = APP;
  46. },{"./modules/API/API":2,"./modules/DTMF/DTMF":3,"./modules/RTC/RTC":7,"./modules/UI/UI":9,"./modules/URLProcessor/URLProcessor":36,"./modules/connectionquality/connectionquality":37,"./modules/desktopsharing/desktopsharing":38,"./modules/keyboardshortcut/keyboardshortcut":39,"./modules/members/MemberList":40,"./modules/settings/Settings":41,"./modules/simulcast/simulcast":46,"./modules/statistics/statistics":49,"./modules/translation/translation":50,"./modules/xmpp/xmpp":64}],2:[function(require,module,exports){
  47. /**
  48. * Implements API class that communicates with external api class
  49. * and provides interface to access Jitsi Meet features by external
  50. * applications that embed Jitsi Meet
  51. */
  52. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  53. /**
  54. * List of the available commands.
  55. * @type {{
  56. * displayName: inputDisplayNameHandler,
  57. * muteAudio: toggleAudio,
  58. * muteVideo: toggleVideo,
  59. * filmStrip: toggleFilmStrip
  60. * }}
  61. */
  62. var commands =
  63. {
  64. displayName: APP.UI.inputDisplayNameHandler,
  65. muteAudio: APP.UI.toggleAudio,
  66. muteVideo: APP.UI.toggleVideo,
  67. toggleFilmStrip: APP.UI.toggleFilmStrip,
  68. toggleChat: APP.UI.toggleChat,
  69. toggleContactList: APP.UI.toggleContactList
  70. };
  71. /**
  72. * Maps the supported events and their status
  73. * (true it the event is enabled and false if it is disabled)
  74. * @type {{
  75. * incomingMessage: boolean,
  76. * outgoingMessage: boolean,
  77. * displayNameChange: boolean,
  78. * participantJoined: boolean,
  79. * participantLeft: boolean
  80. * }}
  81. */
  82. var events =
  83. {
  84. incomingMessage: false,
  85. outgoingMessage:false,
  86. displayNameChange: false,
  87. participantJoined: false,
  88. participantLeft: false
  89. };
  90. var displayName = {};
  91. /**
  92. * Processes commands from external applicaiton.
  93. * @param message the object with the command
  94. */
  95. function processCommand(message)
  96. {
  97. if(message.action != "execute")
  98. {
  99. console.error("Unknown action of the message");
  100. return;
  101. }
  102. for(var key in message)
  103. {
  104. if(commands[key])
  105. commands[key].apply(null, message[key]);
  106. }
  107. }
  108. /**
  109. * Processes events objects from external applications
  110. * @param event the event
  111. */
  112. function processEvent(event) {
  113. if(!event.action)
  114. {
  115. console.error("Event with no action is received.");
  116. return;
  117. }
  118. var i = 0;
  119. switch(event.action)
  120. {
  121. case "add":
  122. for(; i < event.events.length; i++)
  123. {
  124. events[event.events[i]] = true;
  125. }
  126. break;
  127. case "remove":
  128. for(; i < event.events.length; i++)
  129. {
  130. events[event.events[i]] = false;
  131. }
  132. break;
  133. default:
  134. console.error("Unknown action for event.");
  135. }
  136. }
  137. /**
  138. * Sends message to the external application.
  139. * @param object
  140. */
  141. function sendMessage(object) {
  142. window.parent.postMessage(JSON.stringify(object), "*");
  143. }
  144. /**
  145. * Processes a message event from the external application
  146. * @param event the message event
  147. */
  148. function processMessage(event)
  149. {
  150. var message;
  151. try {
  152. message = JSON.parse(event.data);
  153. } catch (e) {}
  154. if(!message.type)
  155. return;
  156. switch (message.type)
  157. {
  158. case "command":
  159. processCommand(message);
  160. break;
  161. case "event":
  162. processEvent(message);
  163. break;
  164. default:
  165. console.error("Unknown type of the message");
  166. return;
  167. }
  168. }
  169. function setupListeners() {
  170. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  171. API.triggerEvent("participantJoined", {jid: from});
  172. });
  173. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid) {
  174. if (from != myjid)
  175. API.triggerEvent("incomingMessage",
  176. {"from": from, "nick": nick, "message": txt});
  177. });
  178. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  179. API.triggerEvent("participantLeft", {jid: jid});
  180. });
  181. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  182. name = displayName[jid];
  183. if(!name || name != newDisplayName) {
  184. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  185. displayName[jid] = newDisplayName;
  186. }
  187. });
  188. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  189. APP.API.triggerEvent("outgoingMessage", {"message": body});
  190. });
  191. }
  192. var API = {
  193. /**
  194. * Check whether the API should be enabled or not.
  195. * @returns {boolean}
  196. */
  197. isEnabled: function () {
  198. var hash = location.hash;
  199. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  200. return true;
  201. return false;
  202. },
  203. /**
  204. * Initializes the APIConnector. Setups message event listeners that will
  205. * receive information from external applications that embed Jitsi Meet.
  206. * It also sends a message to the external application that APIConnector
  207. * is initialized.
  208. */
  209. init: function () {
  210. if (window.addEventListener)
  211. {
  212. window.addEventListener('message',
  213. processMessage, false);
  214. }
  215. else
  216. {
  217. window.attachEvent('onmessage', processMessage);
  218. }
  219. sendMessage({type: "system", loaded: true});
  220. setupListeners();
  221. },
  222. /**
  223. * Checks whether the event is enabled ot not.
  224. * @param name the name of the event.
  225. * @returns {*}
  226. */
  227. isEventEnabled: function (name) {
  228. return events[name];
  229. },
  230. /**
  231. * Sends event object to the external application that has been subscribed
  232. * for that event.
  233. * @param name the name event
  234. * @param object data associated with the event
  235. */
  236. triggerEvent: function (name, object) {
  237. if(this.isEnabled() && this.isEventEnabled(name))
  238. sendMessage({
  239. type: "event", action: "result", event: name, result: object});
  240. },
  241. /**
  242. * Removes the listeners.
  243. */
  244. dispose: function () {
  245. if(window.removeEventListener)
  246. {
  247. window.removeEventListener("message",
  248. processMessage, false);
  249. }
  250. else
  251. {
  252. window.detachEvent('onmessage', processMessage);
  253. }
  254. }
  255. };
  256. module.exports = API;
  257. },{"../../service/xmpp/XMPPEvents":105}],3:[function(require,module,exports){
  258. /* global APP */
  259. /**
  260. * A module for sending DTMF tones.
  261. */
  262. var DTMFSender;
  263. var initDtmfSender = function() {
  264. // TODO: This needs to reset this if the peerconnection changes
  265. // (e.g. the call is re-made)
  266. if (DTMFSender)
  267. return;
  268. var localAudio = APP.RTC.localAudio;
  269. if (localAudio && localAudio.getTracks().length > 0)
  270. {
  271. var peerconnection
  272. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  273. if (peerconnection) {
  274. DTMFSender =
  275. peerconnection.peerconnection
  276. .createDTMFSender(localAudio.getTracks()[0]);
  277. console.log("Initialized DTMFSender");
  278. }
  279. else {
  280. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  281. }
  282. }
  283. else {
  284. console.log("Failed to initialize DTMFSender: no audio track.");
  285. }
  286. };
  287. var DTMF = {
  288. sendTones: function (tones, duration, pause) {
  289. if (!DTMFSender)
  290. initDtmfSender();
  291. if (DTMFSender){
  292. DTMFSender.insertDTMF(tones,
  293. (duration || 200),
  294. (pause || 200));
  295. }
  296. }
  297. };
  298. module.exports = DTMF;
  299. },{}],4:[function(require,module,exports){
  300. /* global Strophe, focusedVideoSrc*/
  301. // cache datachannels to avoid garbage collection
  302. // https://code.google.com/p/chromium/issues/detail?id=405545
  303. var RTCEvents = require("../../service/RTC/RTCEvents");
  304. var _dataChannels = [];
  305. var eventEmitter = null;
  306. var DataChannels =
  307. {
  308. /**
  309. * Callback triggered by PeerConnection when new data channel is opened
  310. * on the bridge.
  311. * @param event the event info object.
  312. */
  313. onDataChannel: function (event)
  314. {
  315. var dataChannel = event.channel;
  316. dataChannel.onopen = function () {
  317. console.info("Data channel opened by the Videobridge!", dataChannel);
  318. // Code sample for sending string and/or binary data
  319. // Sends String message to the bridge
  320. //dataChannel.send("Hello bridge!");
  321. // Sends 12 bytes binary message to the bridge
  322. //dataChannel.send(new ArrayBuffer(12));
  323. // when the data channel becomes available, tell the bridge about video
  324. // selections so that it can do adaptive simulcast,
  325. // we want the notification to trigger even if userJid is undefined,
  326. // or null.
  327. var userJid = APP.UI.getLargeVideoState().userResourceJid;
  328. // we want the notification to trigger even if userJid is undefined,
  329. // or null.
  330. onSelectedEndpointChanged(userJid);
  331. };
  332. dataChannel.onerror = function (error) {
  333. console.error("Data Channel Error:", error, dataChannel);
  334. };
  335. dataChannel.onmessage = function (event) {
  336. var data = event.data;
  337. // JSON
  338. var obj;
  339. try {
  340. obj = JSON.parse(data);
  341. }
  342. catch (e) {
  343. console.error(
  344. "Failed to parse data channel message as JSON: ",
  345. data,
  346. dataChannel);
  347. }
  348. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  349. var colibriClass = obj.colibriClass;
  350. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  351. // Endpoint ID from the Videobridge.
  352. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  353. console.info(
  354. "Data channel new dominant speaker event: ",
  355. dominantSpeakerEndpoint);
  356. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  357. }
  358. else if ("InLastNChangeEvent" === colibriClass)
  359. {
  360. var oldValue = obj.oldValue;
  361. var newValue = obj.newValue;
  362. // Make sure that oldValue and newValue are of type boolean.
  363. var type;
  364. if ((type = typeof oldValue) !== 'boolean') {
  365. if (type === 'string') {
  366. oldValue = (oldValue == "true");
  367. } else {
  368. oldValue = new Boolean(oldValue).valueOf();
  369. }
  370. }
  371. if ((type = typeof newValue) !== 'boolean') {
  372. if (type === 'string') {
  373. newValue = (newValue == "true");
  374. } else {
  375. newValue = new Boolean(newValue).valueOf();
  376. }
  377. }
  378. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  379. }
  380. else if ("LastNEndpointsChangeEvent" === colibriClass)
  381. {
  382. // The new/latest list of last-n endpoint IDs.
  383. var lastNEndpoints = obj.lastNEndpoints;
  384. // The list of endpoint IDs which are entering the list of
  385. // last-n at this time i.e. were not in the old list of last-n
  386. // endpoint IDs.
  387. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  388. var stream = obj.stream;
  389. console.log(
  390. "Data channel new last-n event: ",
  391. lastNEndpoints, endpointsEnteringLastN, obj);
  392. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  393. lastNEndpoints, endpointsEnteringLastN, obj);
  394. }
  395. else if ("SimulcastLayersChangedEvent" === colibriClass)
  396. {
  397. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGED,
  398. obj.endpointSimulcastLayers);
  399. }
  400. else if ("SimulcastLayersChangingEvent" === colibriClass)
  401. {
  402. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGING,
  403. obj.endpointSimulcastLayers);
  404. }
  405. else if ("StartSimulcastLayerEvent" === colibriClass)
  406. {
  407. eventEmitter.emit(RTCEvents.SIMULCAST_START, obj.simulcastLayer);
  408. }
  409. else if ("StopSimulcastLayerEvent" === colibriClass)
  410. {
  411. eventEmitter.emit(RTCEvents.SIMULCAST_STOP, obj.simulcastLayer);
  412. }
  413. else
  414. {
  415. console.debug("Data channel JSON-formatted message: ", obj);
  416. }
  417. }
  418. };
  419. dataChannel.onclose = function ()
  420. {
  421. console.info("The Data Channel closed", dataChannel);
  422. var idx = _dataChannels.indexOf(dataChannel);
  423. if (idx > -1)
  424. _dataChannels = _dataChannels.splice(idx, 1);
  425. };
  426. _dataChannels.push(dataChannel);
  427. },
  428. /**
  429. * Binds "ondatachannel" event listener to given PeerConnection instance.
  430. * @param peerConnection WebRTC peer connection instance.
  431. */
  432. init: function (peerConnection, emitter) {
  433. if(!config.openSctp)
  434. return;
  435. peerConnection.ondatachannel = this.onDataChannel;
  436. eventEmitter = emitter;
  437. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  438. // Although it's not a requirement to open separate channels from both bridge
  439. // and peer as single channel can be used for sending and receiving data.
  440. // So either channel opened by the bridge or the one opened here is enough
  441. // for communication with the bridge.
  442. /*var dataChannelOptions =
  443. {
  444. reliable: true
  445. };
  446. var dataChannel
  447. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  448. // Can be used only when is in open state
  449. dataChannel.onopen = function ()
  450. {
  451. dataChannel.send("My channel !!!");
  452. };
  453. dataChannel.onmessage = function (event)
  454. {
  455. var msgData = event.data;
  456. console.info("Got My Data Channel Message:", msgData, dataChannel);
  457. };*/
  458. },
  459. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  460. handlePinnedEndpointEvent: onPinnedEndpointChanged
  461. };
  462. function onSelectedEndpointChanged(userResource)
  463. {
  464. console.log('selected endpoint changed: ', userResource);
  465. if (_dataChannels && _dataChannels.length != 0)
  466. {
  467. _dataChannels.some(function (dataChannel) {
  468. if (dataChannel.readyState == 'open')
  469. {
  470. console.log('sending selected endpoint changed '
  471. + 'notification to the bridge: ', userResource);
  472. dataChannel.send(JSON.stringify({
  473. 'colibriClass': 'SelectedEndpointChangedEvent',
  474. 'selectedEndpoint':
  475. (!userResource || userResource === null)?
  476. null : userResource
  477. }));
  478. return true;
  479. }
  480. });
  481. }
  482. }
  483. function onPinnedEndpointChanged(userResource)
  484. {
  485. console.log('pinned endpoint changed: ', userResource);
  486. if (_dataChannels && _dataChannels.length != 0)
  487. {
  488. _dataChannels.some(function (dataChannel) {
  489. if (dataChannel.readyState == 'open')
  490. {
  491. dataChannel.send(JSON.stringify({
  492. 'colibriClass': 'PinnedEndpointChangedEvent',
  493. 'pinnedEndpoint':
  494. (!userResource || userResource == null)?
  495. null : userResource
  496. }));
  497. return true;
  498. }
  499. });
  500. }
  501. }
  502. module.exports = DataChannels;
  503. },{"../../service/RTC/RTCEvents":96}],5:[function(require,module,exports){
  504. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  505. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream)
  506. {
  507. this.stream = stream;
  508. this.eventEmitter = eventEmitter;
  509. this.type = type;
  510. this.videoType = videoType;
  511. this.isGUMStream = true;
  512. if(isGUMStream === false)
  513. this.isGUMStream = isGUMStream;
  514. var self = this;
  515. if(type == "audio")
  516. {
  517. this.getTracks = function () {
  518. return self.stream.getAudioTracks();
  519. };
  520. }
  521. else
  522. {
  523. this.getTracks = function () {
  524. return self.stream.getVideoTracks();
  525. };
  526. }
  527. this.stream.onended = function()
  528. {
  529. self.streamEnded();
  530. };
  531. }
  532. LocalStream.prototype.streamEnded = function () {
  533. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  534. }
  535. LocalStream.prototype.getOriginalStream = function()
  536. {
  537. return this.stream;
  538. }
  539. LocalStream.prototype.isAudioStream = function () {
  540. return this.type === "audio";
  541. };
  542. LocalStream.prototype.setMute = function(mute)
  543. {
  544. if((window.location.protocol != "https:" && this.isGUMStream) ||
  545. (this.isAudioStream() && this.isGUMStream) || this.videoType === "screen")
  546. {
  547. var tracks = this.getTracks();
  548. for (var idx = 0; idx < tracks.length; idx++) {
  549. tracks[idx].enabled = mute;
  550. }
  551. }
  552. else
  553. {
  554. if(mute === false) {
  555. APP.xmpp.removeStream(this.stream);
  556. this.stream.stop();
  557. }
  558. else
  559. {
  560. var self = this;
  561. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  562. (this.isAudioStream() ? ["audio"] : ["video"]),
  563. function (stream) {
  564. if(self.isAudioStream())
  565. {
  566. APP.RTC.changeLocalAudio(stream, function () {});
  567. }
  568. else
  569. {
  570. APP.RTC.changeLocalVideo(stream, false, function () {});
  571. }
  572. });
  573. }
  574. }
  575. };
  576. LocalStream.prototype.isMuted = function () {
  577. var tracks = [];
  578. if(this.type == "audio")
  579. {
  580. tracks = this.stream.getAudioTracks();
  581. }
  582. else
  583. {
  584. if(this.stream.ended)
  585. return true;
  586. tracks = this.stream.getVideoTracks();
  587. }
  588. for (var idx = 0; idx < tracks.length; idx++) {
  589. if(tracks[idx].enabled)
  590. return false;
  591. }
  592. return true;
  593. }
  594. LocalStream.prototype.getId = function () {
  595. return this.stream.getTracks()[0].id;
  596. }
  597. module.exports = LocalStream;
  598. },{"../../service/RTC/StreamEventTypes.js":98}],6:[function(require,module,exports){
  599. ////These lines should be uncommented when require works in app.js
  600. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  601. var StreamEventType = require("../../service/RTC/StreamEventTypes");
  602. /**
  603. * Creates a MediaStream object for the given data, session id and ssrc.
  604. * It is a wrapper class for the MediaStream.
  605. *
  606. * @param data the data object from which we obtain the stream,
  607. * the peerjid, etc.
  608. * @param sid the session id
  609. * @param ssrc the ssrc corresponding to this MediaStream
  610. *
  611. * @constructor
  612. */
  613. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  614. // XXX(gp) to minimize headaches in the future, we should build our
  615. // abstractions around tracks and not streams. ORTC is track based API.
  616. // Mozilla expects m-lines to represent media tracks.
  617. //
  618. // Practically, what I'm saying is that we should have a MediaTrack class
  619. // and not a MediaStream class.
  620. //
  621. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  622. // a track might have an associated RTX and FEC sources.
  623. this.sid = sid;
  624. this.stream = data.stream;
  625. this.peerjid = data.peerjid;
  626. this.ssrc = ssrc;
  627. this.type = (this.stream.getVideoTracks().length > 0)?
  628. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  629. this.videoType = null;
  630. this.muted = false;
  631. this.eventEmitter = eventEmitter;
  632. }
  633. MediaStream.prototype.getOriginalStream = function()
  634. {
  635. return this.stream;
  636. };
  637. MediaStream.prototype.setMute = function (value)
  638. {
  639. this.stream.muted = value;
  640. this.muted = value;
  641. };
  642. MediaStream.prototype.setVideoType = function (value) {
  643. if(this.videoType === value)
  644. return;
  645. this.videoType = value;
  646. this.eventEmitter.emit(StreamEventType.EVENT_TYPE_REMOTE_CHANGED,
  647. this.peerjid);
  648. };
  649. module.exports = MediaStream;
  650. },{"../../service/RTC/MediaStreamTypes":94,"../../service/RTC/StreamEventTypes":98}],7:[function(require,module,exports){
  651. var EventEmitter = require("events");
  652. var RTCUtils = require("./RTCUtils.js");
  653. var LocalStream = require("./LocalStream.js");
  654. var DataChannels = require("./DataChannels");
  655. var MediaStream = require("./MediaStream.js");
  656. var DesktopSharingEventTypes
  657. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  658. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  659. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  660. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  661. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  662. var UIEvents = require("../../service/UI/UIEvents");
  663. var eventEmitter = new EventEmitter();
  664. function getMediaStreamUsage()
  665. {
  666. var result = {
  667. audio: true,
  668. video: true
  669. };
  670. /** There are some issues with the desktop sharing
  671. * when this property is enabled.
  672. * WARNING: We must change the implementation to start video/audio if we
  673. * receive from the focus that the peer is not muted.
  674. var isSecureConnection = window.location.protocol == "https:";
  675. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  676. {
  677. result = {
  678. audio: false,
  679. video: false
  680. };
  681. }
  682. **/
  683. return result;
  684. }
  685. var RTC = {
  686. rtcUtils: null,
  687. devices: {
  688. audio: true,
  689. video: true
  690. },
  691. localStreams: [],
  692. remoteStreams: {},
  693. localAudio: null,
  694. localVideo: null,
  695. addStreamListener: function (listener, eventType) {
  696. eventEmitter.on(eventType, listener);
  697. },
  698. addListener: function (type, listener) {
  699. eventEmitter.on(type, listener);
  700. },
  701. removeStreamListener: function (listener, eventType) {
  702. if(!(eventType instanceof StreamEventTypes))
  703. throw "Illegal argument";
  704. eventEmitter.removeListener(eventType, listener);
  705. },
  706. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  707. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  708. //in firefox we have only one stream object
  709. if(this.localStreams.length == 0 ||
  710. this.localStreams[0].getOriginalStream() != stream)
  711. this.localStreams.push(localStream);
  712. if(isMuted === true)
  713. localStream.setMute(false);
  714. if(type == "audio")
  715. {
  716. this.localAudio = localStream;
  717. }
  718. else
  719. {
  720. this.localVideo = localStream;
  721. }
  722. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  723. if(change)
  724. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  725. eventEmitter.emit(eventType, localStream, isMuted);
  726. return localStream;
  727. },
  728. removeLocalStream: function (stream) {
  729. for(var i = 0; i < this.localStreams.length; i++)
  730. {
  731. if(this.localStreams[i].getOriginalStream() === stream) {
  732. delete this.localStreams[i];
  733. return;
  734. }
  735. }
  736. },
  737. createRemoteStream: function (data, sid, thessrc) {
  738. var remoteStream = new MediaStream(data, sid, thessrc,
  739. this.getBrowserType(), eventEmitter);
  740. var jid = data.peerjid || APP.xmpp.myJid();
  741. if(!this.remoteStreams[jid]) {
  742. this.remoteStreams[jid] = {};
  743. }
  744. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  745. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  746. return remoteStream;
  747. },
  748. getBrowserType: function () {
  749. return this.rtcUtils.browser;
  750. },
  751. getPCConstraints: function () {
  752. return this.rtcUtils.pc_constraints;
  753. },
  754. getUserMediaWithConstraints:function(um, success_callback,
  755. failure_callback, resolution,
  756. bandwidth, fps, desktopStream)
  757. {
  758. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  759. failure_callback, resolution, bandwidth, fps, desktopStream);
  760. },
  761. attachMediaStream: function (element, stream) {
  762. this.rtcUtils.attachMediaStream(element, stream);
  763. },
  764. getStreamID: function (stream) {
  765. return this.rtcUtils.getStreamID(stream);
  766. },
  767. getVideoSrc: function (element) {
  768. return this.rtcUtils.getVideoSrc(element);
  769. },
  770. setVideoSrc: function (element, src) {
  771. this.rtcUtils.setVideoSrc(element, src);
  772. },
  773. dispose: function() {
  774. if (this.rtcUtils) {
  775. this.rtcUtils = null;
  776. }
  777. },
  778. stop: function () {
  779. this.dispose();
  780. },
  781. start: function () {
  782. var self = this;
  783. APP.desktopsharing.addListener(
  784. function (stream, isUsingScreenStream, callback) {
  785. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  786. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  787. APP.xmpp.addListener(XMPPEvents.STREAMS_CHANGED, function (jid, changedStreams) {
  788. for(var i = 0; i < changedStreams.length; i++) {
  789. var type = changedStreams[i].type;
  790. if (type != "audio") {
  791. var peerStreams = self.remoteStreams[jid];
  792. if(!peerStreams)
  793. continue;
  794. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  795. if(!videoStream)
  796. continue;
  797. videoStream.setVideoType(changedStreams[i].type);
  798. }
  799. }
  800. });
  801. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  802. DataChannels.init(event.peerconnection, eventEmitter);
  803. });
  804. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  805. DataChannels.handleSelectedEndpointEvent);
  806. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  807. DataChannels.handlePinnedEndpointEvent);
  808. this.rtcUtils = new RTCUtils(this);
  809. this.rtcUtils.obtainAudioAndVideoPermissions(
  810. null, null, getMediaStreamUsage());
  811. },
  812. muteRemoteVideoStream: function (jid, value) {
  813. var stream;
  814. if(this.remoteStreams[jid] &&
  815. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  816. {
  817. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  818. }
  819. if(!stream)
  820. return true;
  821. if (value != stream.muted) {
  822. stream.setMute(value);
  823. return true;
  824. }
  825. return false;
  826. },
  827. switchVideoStreams: function (new_stream) {
  828. this.localVideo.stream = new_stream;
  829. this.localStreams = [];
  830. //in firefox we have only one stream object
  831. if (this.localAudio.getOriginalStream() != new_stream)
  832. this.localStreams.push(this.localAudio);
  833. this.localStreams.push(this.localVideo);
  834. },
  835. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  836. var oldStream = this.localVideo.getOriginalStream();
  837. var type = (isUsingScreenStream? "screen" : "video");
  838. var localCallback = callback;
  839. if(this.localVideo.isMuted() && this.localVideo.videoType !== type)
  840. {
  841. localCallback = function() {
  842. APP.xmpp.setVideoMute(false, APP.UI.setVideoMuteButtonsState);
  843. callback();
  844. };
  845. }
  846. var videoStream = this.rtcUtils.createStream(stream, true);
  847. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  848. // Stop the stream to trigger onended event for old stream
  849. oldStream.stop();
  850. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  851. },
  852. changeLocalAudio: function (stream, callback) {
  853. var oldStream = this.localAudio.getOriginalStream();
  854. var newStream = this.rtcUtils.createStream(stream);
  855. this.localAudio = this.createLocalStream(newStream, "audio", true);
  856. // Stop the stream to trigger onended event for old stream
  857. oldStream.stop();
  858. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  859. },
  860. /**
  861. * Checks if video identified by given src is desktop stream.
  862. * @param videoSrc eg.
  863. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  864. * @returns {boolean}
  865. */
  866. isVideoSrcDesktop: function (jid) {
  867. if(!jid)
  868. return false;
  869. var isDesktop = false;
  870. var stream = null;
  871. if (APP.xmpp.myJid() === jid) {
  872. // local video
  873. stream = this.localVideo;
  874. } else {
  875. var peerStreams = this.remoteStreams[jid];
  876. if(!peerStreams)
  877. return false;
  878. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  879. }
  880. if(stream)
  881. isDesktop = (stream.videoType === "screen");
  882. return isDesktop;
  883. },
  884. setVideoMute: function(mute, callback, options) {
  885. if(!this.localVideo)
  886. return;
  887. if (mute == APP.RTC.localVideo.isMuted())
  888. {
  889. APP.xmpp.sendVideoInfoPresence(mute);
  890. if(callback)
  891. callback(mute);
  892. }
  893. else
  894. {
  895. APP.RTC.localVideo.setMute(!mute);
  896. APP.xmpp.setVideoMute(
  897. mute,
  898. callback,
  899. options);
  900. }
  901. },
  902. setDeviceAvailability: function (devices) {
  903. if(!devices)
  904. return;
  905. if(devices.audio === true || devices.audio === false)
  906. this.devices.audio = devices.audio;
  907. if(devices.video === true || devices.video === false)
  908. this.devices.video = devices.video;
  909. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  910. }
  911. };
  912. module.exports = RTC;
  913. },{"../../service/RTC/MediaStreamTypes":94,"../../service/RTC/RTCEvents.js":96,"../../service/RTC/StreamEventTypes.js":98,"../../service/UI/UIEvents":99,"../../service/desktopsharing/DesktopSharingEventTypes":102,"../../service/xmpp/XMPPEvents":105,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCUtils.js":8,"events":106}],8:[function(require,module,exports){
  914. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  915. var Resolutions = require("../../service/RTC/Resolutions");
  916. var currentResolution = null;
  917. function getPreviousResolution(resolution) {
  918. if(!Resolutions[resolution])
  919. return null;
  920. var order = Resolutions[resolution].order;
  921. var res = null;
  922. var resName = null;
  923. for(var i in Resolutions)
  924. {
  925. var tmp = Resolutions[i];
  926. if(res == null || (res.order < tmp.order && tmp.order < order))
  927. {
  928. resName = i;
  929. res = tmp;
  930. }
  931. }
  932. return resName;
  933. }
  934. function setResolutionConstraints(constraints, resolution, isAndroid)
  935. {
  936. if (resolution && !constraints.video || isAndroid) {
  937. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  938. }
  939. if(Resolutions[resolution])
  940. {
  941. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  942. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  943. }
  944. else
  945. {
  946. if (isAndroid) {
  947. constraints.video.mandatory.minWidth = 320;
  948. constraints.video.mandatory.minHeight = 240;
  949. constraints.video.mandatory.maxFrameRate = 15;
  950. }
  951. }
  952. if (constraints.video.mandatory.minWidth)
  953. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  954. if (constraints.video.mandatory.minHeight)
  955. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  956. }
  957. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  958. {
  959. var constraints = {audio: false, video: false};
  960. if (um.indexOf('video') >= 0) {
  961. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  962. }
  963. if (um.indexOf('audio') >= 0) {
  964. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  965. }
  966. if (um.indexOf('screen') >= 0) {
  967. constraints.video = {
  968. mandatory: {
  969. chromeMediaSource: "screen",
  970. googLeakyBucket: true,
  971. maxWidth: window.screen.width,
  972. maxHeight: window.screen.height,
  973. maxFrameRate: 3
  974. },
  975. optional: []
  976. };
  977. }
  978. if (um.indexOf('desktop') >= 0) {
  979. constraints.video = {
  980. mandatory: {
  981. chromeMediaSource: "desktop",
  982. chromeMediaSourceId: desktopStream,
  983. googLeakyBucket: true,
  984. maxWidth: window.screen.width,
  985. maxHeight: window.screen.height,
  986. maxFrameRate: 3
  987. },
  988. optional: []
  989. };
  990. }
  991. if (constraints.audio) {
  992. // if it is good enough for hangouts...
  993. constraints.audio.optional.push(
  994. {googEchoCancellation: true},
  995. {googAutoGainControl: true},
  996. {googNoiseSupression: true},
  997. {googHighpassFilter: true},
  998. {googNoisesuppression2: true},
  999. {googEchoCancellation2: true},
  1000. {googAutoGainControl2: true}
  1001. );
  1002. }
  1003. if (constraints.video) {
  1004. constraints.video.optional.push(
  1005. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  1006. );
  1007. if (um.indexOf('video') >= 0) {
  1008. constraints.video.optional.push(
  1009. {googLeakyBucket: true}
  1010. );
  1011. }
  1012. }
  1013. if (um.indexOf('video') >= 0) {
  1014. setResolutionConstraints(constraints, resolution, isAndroid);
  1015. }
  1016. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  1017. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  1018. constraints.video.optional.push({bandwidth: bandwidth});
  1019. }
  1020. if (fps) { // for some cameras it might be necessary to request 30fps
  1021. // so they choose 30fps mjpg over 10fps yuy2
  1022. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  1023. constraints.video.mandatory.minFrameRate = fps;
  1024. }
  1025. return constraints;
  1026. }
  1027. function RTCUtils(RTCService)
  1028. {
  1029. this.service = RTCService;
  1030. if (navigator.mozGetUserMedia) {
  1031. console.log('This appears to be Firefox');
  1032. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1033. if (version >= 38
  1034. && !config.enableSimulcast && config.useBundle && config.useRtcpMux) {
  1035. this.peerconnection = mozRTCPeerConnection;
  1036. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1037. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1038. this.pc_constraints = {};
  1039. this.attachMediaStream = function (element, stream) {
  1040. // srcObject is being standardized and FF will eventually
  1041. // support that unprefixed. FF also supports the
  1042. // "element.src = URL.createObjectURL(...)" combo, but that
  1043. // will be deprecated in favour of srcObject.
  1044. //
  1045. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1046. // https://github.com/webrtc/samples/issues/302
  1047. if(!element[0])
  1048. return;
  1049. element[0].mozSrcObject = stream;
  1050. element[0].play();
  1051. };
  1052. this.getStreamID = function (stream) {
  1053. var tracks = stream.getVideoTracks();
  1054. if(!tracks || tracks.length == 0)
  1055. {
  1056. tracks = stream.getAudioTracks();
  1057. }
  1058. return tracks[0].id.replace(/[\{,\}]/g,"");
  1059. };
  1060. this.getVideoSrc = function (element) {
  1061. if(!element)
  1062. return null;
  1063. return element.mozSrcObject;
  1064. };
  1065. this.setVideoSrc = function (element, src) {
  1066. if(element)
  1067. element.mozSrcObject = src;
  1068. };
  1069. RTCSessionDescription = mozRTCSessionDescription;
  1070. RTCIceCandidate = mozRTCIceCandidate;
  1071. } else {
  1072. window.location.href = 'unsupported_browser.html';
  1073. return;
  1074. }
  1075. } else if (navigator.webkitGetUserMedia) {
  1076. console.log('This appears to be Chrome');
  1077. this.peerconnection = webkitRTCPeerConnection;
  1078. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  1079. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1080. this.attachMediaStream = function (element, stream) {
  1081. element.attr('src', webkitURL.createObjectURL(stream));
  1082. };
  1083. this.getStreamID = function (stream) {
  1084. // streams from FF endpoints have the characters '{' and '}'
  1085. // that make jQuery choke.
  1086. return stream.id.replace(/[\{,\}]/g,"");
  1087. };
  1088. this.getVideoSrc = function (element) {
  1089. if(!element)
  1090. return null;
  1091. return element.getAttribute("src");
  1092. };
  1093. this.setVideoSrc = function (element, src) {
  1094. if(element)
  1095. element.setAttribute("src", src);
  1096. };
  1097. // DTLS should now be enabled by default but..
  1098. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1099. if (navigator.userAgent.indexOf('Android') != -1) {
  1100. this.pc_constraints = {}; // disable DTLS on Android
  1101. }
  1102. if (!webkitMediaStream.prototype.getVideoTracks) {
  1103. webkitMediaStream.prototype.getVideoTracks = function () {
  1104. return this.videoTracks;
  1105. };
  1106. }
  1107. if (!webkitMediaStream.prototype.getAudioTracks) {
  1108. webkitMediaStream.prototype.getAudioTracks = function () {
  1109. return this.audioTracks;
  1110. };
  1111. }
  1112. }
  1113. else
  1114. {
  1115. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  1116. window.location.href = 'unsupported_browser.html';
  1117. return;
  1118. }
  1119. }
  1120. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1121. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1122. desktopStream)
  1123. {
  1124. currentResolution = resolution;
  1125. // Check if we are running on Android device
  1126. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1127. var constraints = getConstraints(
  1128. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1129. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  1130. var self = this;
  1131. try {
  1132. if (config.enableSimulcast
  1133. && constraints.video
  1134. && constraints.video.chromeMediaSource !== 'screen'
  1135. && constraints.video.chromeMediaSource !== 'desktop'
  1136. && !isAndroid
  1137. // We currently do not support FF, as it doesn't have multistream support.
  1138. && !isFF) {
  1139. APP.simulcast.getUserMedia(constraints, function (stream) {
  1140. console.log('onUserMediaSuccess');
  1141. self.setAvailableDevices(um, true);
  1142. success_callback(stream);
  1143. },
  1144. function (error) {
  1145. console.warn('Failed to get access to local media. Error ', error);
  1146. self.setAvailableDevices(um, false);
  1147. if (failure_callback) {
  1148. failure_callback(error);
  1149. }
  1150. });
  1151. } else {
  1152. this.getUserMedia(constraints,
  1153. function (stream) {
  1154. console.log('onUserMediaSuccess');
  1155. self.setAvailableDevices(um, true);
  1156. success_callback(stream);
  1157. },
  1158. function (error) {
  1159. self.setAvailableDevices(um, false);
  1160. console.warn('Failed to get access to local media. Error ',
  1161. error, constraints);
  1162. if (failure_callback) {
  1163. failure_callback(error);
  1164. }
  1165. });
  1166. }
  1167. } catch (e) {
  1168. console.error('GUM failed: ', e);
  1169. if(failure_callback) {
  1170. failure_callback(e);
  1171. }
  1172. }
  1173. };
  1174. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1175. var devices = {};
  1176. if(um.indexOf("video") != -1)
  1177. {
  1178. devices.video = available;
  1179. }
  1180. if(um.indexOf("audio") != -1)
  1181. {
  1182. devices.audio = available;
  1183. }
  1184. this.service.setDeviceAvailability(devices);
  1185. }
  1186. /**
  1187. * We ask for audio and video combined stream in order to get permissions and
  1188. * not to ask twice.
  1189. */
  1190. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1191. function(devices, callback, usageOptions)
  1192. {
  1193. var self = this;
  1194. // Get AV
  1195. var successCallback = function (stream) {
  1196. if(callback)
  1197. callback(stream, usageOptions);
  1198. else
  1199. self.successCallback(stream, usageOptions);
  1200. };
  1201. if(!devices)
  1202. devices = ['audio', 'video'];
  1203. var newDevices = [];
  1204. if(usageOptions)
  1205. for(var i = 0; i < devices.length; i++)
  1206. {
  1207. var device = devices[i];
  1208. if(usageOptions[device] === true)
  1209. newDevices.push(device);
  1210. }
  1211. else
  1212. newDevices = devices;
  1213. if(newDevices.length === 0)
  1214. {
  1215. successCallback();
  1216. return;
  1217. }
  1218. if (navigator.mozGetUserMedia) {
  1219. // With FF we can't split the stream into audio and video because FF
  1220. // doesn't support media stream constructors. So, we need to get the
  1221. // audio stream separately from the video stream using two distinct GUM
  1222. // calls. Not very user friendly :-( but we don't have many other
  1223. // options neither.
  1224. //
  1225. // Note that we pack those 2 streams in a single object and pass it to
  1226. // the successCallback method.
  1227. self.getUserMediaWithConstraints(
  1228. ['audio'],
  1229. function (audioStream) {
  1230. self.getUserMediaWithConstraints(
  1231. ['video'],
  1232. function (videoStream) {
  1233. return self.successCallback({
  1234. audioStream: audioStream,
  1235. videoStream: videoStream
  1236. });
  1237. },
  1238. function (error) {
  1239. console.error('failed to obtain video stream - stop',
  1240. error);
  1241. return self.successCallback(null);
  1242. },
  1243. config.resolution || '360');
  1244. },
  1245. function (error) {
  1246. console.error('failed to obtain audio stream - stop',
  1247. error);
  1248. return self.successCallback(null);
  1249. }
  1250. );
  1251. } else {
  1252. this.getUserMediaWithConstraints(
  1253. newDevices,
  1254. function (stream) {
  1255. successCallback(stream);
  1256. },
  1257. function (error) {
  1258. self.errorCallback(error);
  1259. },
  1260. config.resolution || '360');
  1261. }
  1262. }
  1263. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1264. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1265. // an object with two properties: audioStream, videoStream.
  1266. if(stream && !navigator.mozGetUserMedia)
  1267. console.log('got', stream, stream.getAudioTracks().length,
  1268. stream.getVideoTracks().length);
  1269. this.handleLocalStream(stream, usageOptions);
  1270. };
  1271. RTCUtils.prototype.errorCallback = function (error) {
  1272. var self = this;
  1273. console.error('failed to obtain audio/video stream - trying audio only', error);
  1274. var resolution = getPreviousResolution(currentResolution);
  1275. if(typeof error == "object" && error.constraintName && error.name
  1276. && (error.name == "ConstraintNotSatisfiedError" ||
  1277. error.name == "OverconstrainedError") &&
  1278. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1279. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1280. && resolution != null)
  1281. {
  1282. self.getUserMediaWithConstraints(['audio', 'video'],
  1283. function (stream) {
  1284. return self.successCallback(stream);
  1285. }, function (error) {
  1286. return self.errorCallback(error);
  1287. }, resolution);
  1288. }
  1289. else
  1290. {
  1291. self.getUserMediaWithConstraints(
  1292. ['audio'],
  1293. function (stream) {
  1294. return self.successCallback(stream);
  1295. },
  1296. function (error) {
  1297. console.error('failed to obtain audio/video stream - stop',
  1298. error);
  1299. return self.successCallback(null);
  1300. }
  1301. );
  1302. }
  1303. }
  1304. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions)
  1305. {
  1306. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1307. // an object with two properties: audioStream, videoStream.
  1308. var audioStream, videoStream;
  1309. if(window.webkitMediaStream)
  1310. {
  1311. audioStream = new webkitMediaStream();
  1312. videoStream = new webkitMediaStream();
  1313. if(stream) {
  1314. var audioTracks = stream.getAudioTracks();
  1315. for (var i = 0; i < audioTracks.length; i++) {
  1316. audioStream.addTrack(audioTracks[i]);
  1317. }
  1318. var videoTracks = stream.getVideoTracks();
  1319. for (i = 0; i < videoTracks.length; i++) {
  1320. videoStream.addTrack(videoTracks[i]);
  1321. }
  1322. }
  1323. }
  1324. else
  1325. {//firefox
  1326. audioStream = stream.audioStream;
  1327. videoStream = stream.videoStream;
  1328. }
  1329. var audioMuted = (usageOptions && usageOptions.audio === false),
  1330. videoMuted = (usageOptions && usageOptions.video === false);
  1331. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1332. videoGUM = (!usageOptions || usageOptions.video !== false);
  1333. this.service.createLocalStream(audioStream, "audio", null, null,
  1334. audioMuted, audioGUM);
  1335. this.service.createLocalStream(videoStream, "video", null, null,
  1336. videoMuted, videoGUM);
  1337. };
  1338. RTCUtils.prototype.createStream = function(stream, isVideo)
  1339. {
  1340. var newStream = null;
  1341. if(window.webkitMediaStream)
  1342. {
  1343. newStream = new webkitMediaStream();
  1344. if(newStream)
  1345. {
  1346. var tracks = (isVideo? stream.getVideoTracks() : stream.getAudioTracks());
  1347. for (i = 0; i < tracks.length; i++) {
  1348. newStream.addTrack(tracks[i]);
  1349. }
  1350. }
  1351. }
  1352. else
  1353. newStream = stream;
  1354. return newStream;
  1355. };
  1356. module.exports = RTCUtils;
  1357. },{"../../service/RTC/RTCBrowserType.js":95,"../../service/RTC/Resolutions":97}],9:[function(require,module,exports){
  1358. var UI = {};
  1359. var VideoLayout = require("./videolayout/VideoLayout.js");
  1360. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1361. var Prezi = require("./prezi/Prezi.js");
  1362. var Etherpad = require("./etherpad/Etherpad.js");
  1363. var Chat = require("./side_pannels/chat/Chat.js");
  1364. var Toolbar = require("./toolbars/Toolbar");
  1365. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1366. var BottomToolbar = require("./toolbars/BottomToolbar");
  1367. var ContactList = require("./side_pannels/contactlist/ContactList");
  1368. var Avatar = require("./avatar/Avatar");
  1369. var EventEmitter = require("events");
  1370. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1371. var Settings = require("./../settings/Settings");
  1372. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1373. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1374. UI.messageHandler = require("./util/MessageHandler");
  1375. var messageHandler = UI.messageHandler;
  1376. var Authentication = require("./authentication/Authentication");
  1377. var UIUtil = require("./util/UIUtil");
  1378. var NicknameHandler = require("./util/NicknameHandler");
  1379. var CQEvents = require("../../service/connectionquality/CQEvents");
  1380. var DesktopSharingEventTypes
  1381. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1382. var RTCEvents = require("../../service/RTC/RTCEvents");
  1383. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1384. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1385. var MemberEvents = require("../../service/members/Events");
  1386. var eventEmitter = new EventEmitter();
  1387. var roomName = null;
  1388. function notifyForInitialMute()
  1389. {
  1390. messageHandler.notify(null, "notify.mutedTitle", "connected",
  1391. "notify.muted", null, {timeOut: 120000});
  1392. }
  1393. function setupPrezi()
  1394. {
  1395. $("#reloadPresentationLink").click(function()
  1396. {
  1397. Prezi.reloadPresentation();
  1398. });
  1399. }
  1400. function setupChat()
  1401. {
  1402. Chat.init();
  1403. $("#toggle_smileys").click(function() {
  1404. Chat.toggleSmileys();
  1405. });
  1406. }
  1407. function setupToolbars() {
  1408. Toolbar.init(UI);
  1409. Toolbar.setupButtonsFromConfig();
  1410. BottomToolbar.init();
  1411. }
  1412. function streamHandler(stream, isMuted) {
  1413. switch (stream.type)
  1414. {
  1415. case "audio":
  1416. VideoLayout.changeLocalAudio(stream, isMuted);
  1417. break;
  1418. case "video":
  1419. VideoLayout.changeLocalVideo(stream, isMuted);
  1420. break;
  1421. case "stream":
  1422. VideoLayout.changeLocalStream(stream, isMuted);
  1423. break;
  1424. }
  1425. }
  1426. function onXmppConnectionFailed(stropheErrorMsg) {
  1427. var title = APP.translation.generateTranslatonHTML(
  1428. "dialog.error");
  1429. var message;
  1430. if (stropheErrorMsg) {
  1431. message = APP.translation.generateTranslatonHTML(
  1432. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  1433. } else {
  1434. message = APP.translation.generateTranslatonHTML(
  1435. "dialog.connectError");
  1436. }
  1437. messageHandler.openDialog(
  1438. title, message, true, {}, function (e, v, m, f) { return false; });
  1439. }
  1440. function onDisposeConference(unload) {
  1441. Toolbar.showAuthenticateButton(false);
  1442. }
  1443. function onDisplayNameChanged(jid, displayName) {
  1444. ContactList.onDisplayNameChange(jid, displayName);
  1445. SettingsMenu.onDisplayNameChange(jid, displayName);
  1446. VideoLayout.onDisplayNameChanged(jid, displayName);
  1447. }
  1448. function registerListeners() {
  1449. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1450. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1451. APP.RTC.addStreamListener(function (stream) {
  1452. VideoLayout.onRemoteStreamAdded(stream);
  1453. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1454. APP.RTC.addStreamListener(function (jid) {
  1455. VideoLayout.onVideoTypeChanged(jid);
  1456. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  1457. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1458. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1459. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1460. });
  1461. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1462. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1463. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1464. endpointsEnteringLastN, stream);
  1465. });
  1466. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  1467. function (endpointSimulcastLayers) {
  1468. VideoLayout.onSimulcastLayersChanged(endpointSimulcastLayers);
  1469. });
  1470. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGING,
  1471. function (endpointSimulcastLayers) {
  1472. VideoLayout.onSimulcastLayersChanging(endpointSimulcastLayers);
  1473. });
  1474. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  1475. function (devices) {
  1476. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  1477. })
  1478. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1479. {
  1480. var resourceJid;
  1481. if(jid === APP.statistics.LOCAL_JID)
  1482. {
  1483. resourceJid = AudioLevels.LOCAL_LEVEL;
  1484. if(APP.RTC.localAudio.isMuted())
  1485. {
  1486. audioLevel = 0;
  1487. }
  1488. }
  1489. else
  1490. {
  1491. resourceJid = Strophe.getResourceFromJid(jid);
  1492. }
  1493. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1494. UI.getLargeVideoState().userResourceJid);
  1495. });
  1496. APP.desktopsharing.addListener(function () {
  1497. ToolbarToggler.showDesktopSharingButton();
  1498. }, DesktopSharingEventTypes.INIT);
  1499. APP.desktopsharing.addListener(
  1500. Toolbar.changeDesktopSharingButtonState,
  1501. DesktopSharingEventTypes.SWITCHING_DONE);
  1502. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1503. VideoLayout.updateLocalConnectionStats);
  1504. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1505. VideoLayout.updateConnectionStats);
  1506. APP.connectionquality.addListener(CQEvents.STOP,
  1507. VideoLayout.onStatsStop);
  1508. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  1509. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1510. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  1511. messageHandler.openMessageDialog(
  1512. 'dialog.serviceUnavailable',
  1513. 'dialog.gracefulShutdown'
  1514. );
  1515. });
  1516. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  1517. var title = APP.translation.generateTranslatonHTML(
  1518. "dialog.reservationError");
  1519. var message = APP.translation.generateTranslatonHTML(
  1520. "dialog.reservationErrorMsg", {code: code, msg: msg});
  1521. messageHandler.openDialog(
  1522. title,
  1523. message,
  1524. true, {},
  1525. function (event, value, message, formVals)
  1526. {
  1527. return false;
  1528. }
  1529. );
  1530. });
  1531. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1532. messageHandler.openMessageDialog("dialog.sessTerminated",
  1533. "dialog.kickMessage");
  1534. });
  1535. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1536. //FIXME: use Session Terminated from translation, but
  1537. // 'reason' text comes from XMPP packet and is not translated
  1538. var title = APP.translation.generateTranslatonHTML("dialog.sessTerminated");
  1539. messageHandler.openDialog(
  1540. title, reason, true, {},
  1541. function (event, value, message, formVals)
  1542. {
  1543. return false;
  1544. }
  1545. );
  1546. });
  1547. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1548. messageHandler.showError("dialog.error",
  1549. "dialog.bridgeUnavailable");
  1550. });
  1551. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1552. Avatar.setUserAvatar(from, id);
  1553. });
  1554. APP.xmpp.addListener(XMPPEvents.STREAMS_CHANGED, function (jid, changedStreams) {
  1555. for(stream in changedStreams)
  1556. {
  1557. // might need to update the direction if participant just went from sendrecv to recvonly
  1558. if (stream.type === 'video' || stream.type === 'screen') {
  1559. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1560. switch (stream.direction) {
  1561. case 'sendrecv':
  1562. el.show();
  1563. break;
  1564. case 'recvonly':
  1565. el.hide();
  1566. // FIXME: Check if we have to change large video
  1567. //VideoLayout.updateLargeVideo(el);
  1568. break;
  1569. }
  1570. }
  1571. }
  1572. });
  1573. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1574. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1575. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  1576. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  1577. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1578. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1579. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1580. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1581. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  1582. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  1583. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1584. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1585. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  1586. onAuthenticationRequired);
  1587. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  1588. function (resource, devices) {
  1589. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  1590. });
  1591. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  1592. onDtmfSupportChanged);
  1593. APP.xmpp.addListener(XMPPEvents.START_MUTED, function (audio, video) {
  1594. SettingsMenu.setStartMuted(audio, video);
  1595. });
  1596. }
  1597. /**
  1598. * Mutes/unmutes the local video.
  1599. *
  1600. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1601. * @param options an object which specifies optional arguments such as the
  1602. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1603. * specifies whether the method was initiated in response to a user command (in
  1604. * contrast to an automatic decision taken by the application logic)
  1605. */
  1606. function setVideoMute(mute, options) {
  1607. APP.RTC.setVideoMute(mute,
  1608. UI.setVideoMuteButtonsState,
  1609. options);
  1610. }
  1611. function bindEvents()
  1612. {
  1613. /**
  1614. * Resizes and repositions videos in full screen mode.
  1615. */
  1616. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1617. function () {
  1618. VideoLayout.resizeLargeVideoContainer();
  1619. VideoLayout.positionLarge();
  1620. }
  1621. );
  1622. $(window).resize(function () {
  1623. VideoLayout.resizeLargeVideoContainer();
  1624. VideoLayout.positionLarge();
  1625. });
  1626. }
  1627. UI.start = function (init) {
  1628. document.title = interfaceConfig.APP_NAME;
  1629. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1630. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1631. {
  1632. $("#videoconference_page").hide();
  1633. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1634. setupWelcomePage();
  1635. return;
  1636. }
  1637. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1638. var leftWatermarkDiv
  1639. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1640. leftWatermarkDiv.css({display: 'block'});
  1641. leftWatermarkDiv.parent().get(0).href
  1642. = interfaceConfig.JITSI_WATERMARK_LINK;
  1643. }
  1644. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1645. var rightWatermarkDiv
  1646. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1647. rightWatermarkDiv.css({display: 'block'});
  1648. rightWatermarkDiv.parent().get(0).href
  1649. = interfaceConfig.BRAND_WATERMARK_LINK;
  1650. rightWatermarkDiv.get(0).style.backgroundImage
  1651. = "url(images/rightwatermark.png)";
  1652. }
  1653. if (interfaceConfig.SHOW_POWERED_BY) {
  1654. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1655. }
  1656. $("#welcome_page").hide();
  1657. VideoLayout.resizeLargeVideoContainer();
  1658. $("#videospace").mousemove(function () {
  1659. return ToolbarToggler.showToolbar();
  1660. });
  1661. // Set the defaults for prompt dialogs.
  1662. jQuery.prompt.setDefaults({persistent: false});
  1663. VideoLayout.init(eventEmitter);
  1664. AudioLevels.init();
  1665. NicknameHandler.init(eventEmitter);
  1666. registerListeners();
  1667. bindEvents();
  1668. setupPrezi();
  1669. setupToolbars();
  1670. setupChat();
  1671. document.title = interfaceConfig.APP_NAME;
  1672. $("#downloadlog").click(function (event) {
  1673. dump(event.target);
  1674. });
  1675. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1676. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1677. {
  1678. $("#videoconference_page").hide();
  1679. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1680. setupWelcomePage();
  1681. return;
  1682. }
  1683. $("#welcome_page").hide();
  1684. // Display notice message at the top of the toolbar
  1685. if (config.noticeMessage) {
  1686. $('#noticeText').text(config.noticeMessage);
  1687. $('#notice').css({display: 'block'});
  1688. }
  1689. document.getElementById('largeVideo').volume = 0;
  1690. if (!$('#settings').is(':visible')) {
  1691. console.log('init');
  1692. init();
  1693. } else {
  1694. loginInfo.onsubmit = function (e) {
  1695. if (e.preventDefault) e.preventDefault();
  1696. $('#settings').hide();
  1697. init();
  1698. };
  1699. }
  1700. toastr.options = {
  1701. "closeButton": true,
  1702. "debug": false,
  1703. "positionClass": "notification-bottom-right",
  1704. "onclick": null,
  1705. "showDuration": "300",
  1706. "hideDuration": "1000",
  1707. "timeOut": "2000",
  1708. "extendedTimeOut": "1000",
  1709. "showEasing": "swing",
  1710. "hideEasing": "linear",
  1711. "showMethod": "fadeIn",
  1712. "hideMethod": "fadeOut",
  1713. "reposition": function() {
  1714. if(PanelToggler.isVisible()) {
  1715. $("#toast-container").addClass("notification-bottom-right-center");
  1716. } else {
  1717. $("#toast-container").removeClass("notification-bottom-right-center");
  1718. }
  1719. },
  1720. "newestOnTop": false
  1721. };
  1722. SettingsMenu.init();
  1723. };
  1724. function chatAddError(errorMessage, originalText)
  1725. {
  1726. return Chat.chatAddError(errorMessage, originalText);
  1727. };
  1728. function chatSetSubject(text)
  1729. {
  1730. return Chat.chatSetSubject(text);
  1731. };
  1732. function updateChatConversation(from, displayName, message) {
  1733. return Chat.updateChatConversation(from, displayName, message);
  1734. };
  1735. function onMucJoined(jid, info) {
  1736. Toolbar.updateRoomUrl(window.location.href);
  1737. var meHTML = APP.translation.generateTranslatonHTML("me");
  1738. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  1739. var settings = Settings.getSettings();
  1740. // Add myself to the contact list.
  1741. ContactList.addContact(jid, settings.email || settings.uid);
  1742. // Once we've joined the muc show the toolbar
  1743. ToolbarToggler.showToolbar();
  1744. var displayName = !config.displayJids
  1745. ? info.displayName : Strophe.getResourceFromJid(jid);
  1746. if (displayName)
  1747. onDisplayNameChanged('localVideoContainer', displayName);
  1748. VideoLayout.mucJoined();
  1749. }
  1750. function initEtherpad(name) {
  1751. Etherpad.init(name);
  1752. };
  1753. function onMucMemberLeft(jid) {
  1754. console.log('left.muc', jid);
  1755. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1756. '>.displayname').html();
  1757. messageHandler.notify(displayName,'notify.somebody',
  1758. 'disconnected',
  1759. 'notify.disconnected');
  1760. // Need to call this with a slight delay, otherwise the element couldn't be
  1761. // found for some reason.
  1762. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1763. window.setTimeout(function () {
  1764. var container = document.getElementById(
  1765. 'participant_' + Strophe.getResourceFromJid(jid));
  1766. if (container) {
  1767. ContactList.removeContact(jid);
  1768. VideoLayout.removeConnectionIndicator(jid);
  1769. // hide here, wait for video to close before removing
  1770. $(container).hide();
  1771. VideoLayout.resizeThumbnails();
  1772. }
  1773. }, 10);
  1774. VideoLayout.participantLeft(jid);
  1775. };
  1776. function onLocalRoleChanged(jid, info, pres, isModerator)
  1777. {
  1778. console.info("My role changed, new role: " + info.role);
  1779. onModeratorStatusChanged(isModerator);
  1780. VideoLayout.showModeratorIndicator();
  1781. SettingsMenu.onRoleChanged();
  1782. if (isModerator) {
  1783. Authentication.closeAuthenticationWindow();
  1784. messageHandler.notify(null, "notify.me",
  1785. 'connected', "notify.moderator");
  1786. }
  1787. }
  1788. function onModeratorStatusChanged(isModerator) {
  1789. Toolbar.showSipCallButton(isModerator);
  1790. Toolbar.showRecordingButton(
  1791. isModerator); //&&
  1792. // FIXME:
  1793. // Recording visible if
  1794. // there are at least 2(+ 1 focus) participants
  1795. //Object.keys(connection.emuc.members).length >= 3);
  1796. if (isModerator && config.etherpad_base) {
  1797. Etherpad.init();
  1798. }
  1799. };
  1800. function onPasswordRequired(callback) {
  1801. // password is required
  1802. Toolbar.lockLockButton();
  1803. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1804. message += APP.translation.translateString(
  1805. "dialog.passwordRequired");
  1806. message += '</h2>' +
  1807. '<input name="lockKey" type="text" data-i18n=' +
  1808. '"[placeholder]dialog.password" placeholder="' +
  1809. APP.translation.translateString("dialog.password") +
  1810. '" autofocus>';
  1811. messageHandler.openTwoButtonDialog(null, null, null, message,
  1812. true,
  1813. "dialog.Ok",
  1814. function (e, v, m, f) {},
  1815. null,
  1816. function (e, v, m, f) {
  1817. if (v) {
  1818. var lockKey = f.lockKey;
  1819. if (lockKey) {
  1820. Toolbar.setSharedKey(lockKey);
  1821. callback(lockKey);
  1822. }
  1823. }
  1824. },
  1825. ':input:first'
  1826. );
  1827. }
  1828. /**
  1829. * The dialpad button is shown iff there is at least one member that supports
  1830. * DTMF (e.g. jigasi).
  1831. */
  1832. function onDtmfSupportChanged(dtmfSupport) {
  1833. //TODO: enable when the UI is ready
  1834. //Toolbar.showDialPadButton(dtmfSupport);
  1835. }
  1836. function onMucMemberJoined(jid, id, displayName) {
  1837. messageHandler.notify(displayName,'notify.somebody',
  1838. 'connected',
  1839. 'notify.connected');
  1840. // Add Peer's container
  1841. VideoLayout.ensurePeerContainerExists(jid,id);
  1842. }
  1843. function onMucPresenceStatus( jid, info) {
  1844. VideoLayout.setPresenceStatus(
  1845. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1846. }
  1847. function onMucRoleChanged(role, displayName) {
  1848. VideoLayout.showModeratorIndicator();
  1849. if (role === 'moderator') {
  1850. var messageKey, messageOptions = {};
  1851. if (!displayName) {
  1852. messageKey = "notify.grantedToUnknown";
  1853. }
  1854. else
  1855. {
  1856. messageKey = "notify.grantedTo";
  1857. messageOptions = {to: displayName};
  1858. }
  1859. messageHandler.notify(
  1860. displayName,'notify.somebody',
  1861. 'connected', messageKey,
  1862. messageOptions);
  1863. }
  1864. }
  1865. function onAuthenticationRequired(intervalCallback) {
  1866. Authentication.openAuthenticationDialog(
  1867. roomName, intervalCallback, function () {
  1868. Toolbar.authenticateClicked();
  1869. });
  1870. };
  1871. function onLastNChanged(oldValue, newValue) {
  1872. if (config.muteLocalVideoIfNotInLastN) {
  1873. setVideoMute(!newValue, { 'byUser': false });
  1874. }
  1875. }
  1876. UI.toggleSmileys = function () {
  1877. Chat.toggleSmileys();
  1878. };
  1879. UI.getSettings = function () {
  1880. return Settings.getSettings();
  1881. };
  1882. UI.toggleFilmStrip = function () {
  1883. return BottomToolbar.toggleFilmStrip();
  1884. };
  1885. UI.toggleChat = function () {
  1886. return BottomToolbar.toggleChat();
  1887. };
  1888. UI.toggleContactList = function () {
  1889. return BottomToolbar.toggleContactList();
  1890. };
  1891. UI.inputDisplayNameHandler = function (value) {
  1892. VideoLayout.inputDisplayNameHandler(value);
  1893. };
  1894. UI.getLargeVideoState = function()
  1895. {
  1896. return VideoLayout.getLargeVideoState();
  1897. };
  1898. UI.generateRoomName = function() {
  1899. if(roomName)
  1900. return roomName;
  1901. var roomnode = null;
  1902. var path = window.location.pathname;
  1903. // determinde the room node from the url
  1904. // TODO: just the roomnode or the whole bare jid?
  1905. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1906. // custom function might be responsible for doing the pushstate
  1907. roomnode = config.getroomnode(path);
  1908. } else {
  1909. /* fall back to default strategy
  1910. * this is making assumptions about how the URL->room mapping happens.
  1911. * It currently assumes deployment at root, with a rewrite like the
  1912. * following one (for nginx):
  1913. location ~ ^/([a-zA-Z0-9]+)$ {
  1914. rewrite ^/(.*)$ / break;
  1915. }
  1916. */
  1917. if (path.length > 1) {
  1918. roomnode = path.substr(1).toLowerCase();
  1919. } else {
  1920. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1921. roomnode = word.toLowerCase();
  1922. window.history.pushState('VideoChat',
  1923. 'Room: ' + word, window.location.pathname + word);
  1924. }
  1925. }
  1926. roomName = roomnode + '@' + config.hosts.muc;
  1927. return roomName;
  1928. };
  1929. UI.connectionIndicatorShowMore = function(id)
  1930. {
  1931. return VideoLayout.connectionIndicators[id].showMore();
  1932. };
  1933. UI.showLoginPopup = function(callback)
  1934. {
  1935. console.log('password is required');
  1936. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1937. message += APP.translation.translateString(
  1938. "dialog.passwordRequired");
  1939. message += '</h2>' +
  1940. '<input name="username" type="text" ' +
  1941. 'placeholder="user@domain.net" autofocus>' +
  1942. '<input name="password" ' +
  1943. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  1944. ' placeholder="user password">';
  1945. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  1946. true,
  1947. "dialog.Ok",
  1948. function (e, v, m, f) {
  1949. if (v) {
  1950. if (f.username !== null && f.password != null) {
  1951. callback(f.username, f.password);
  1952. }
  1953. }
  1954. },
  1955. null, null, ':input:first'
  1956. );
  1957. }
  1958. UI.checkForNicknameAndJoin = function () {
  1959. Authentication.closeAuthenticationDialog();
  1960. Authentication.stopInterval();
  1961. var nick = null;
  1962. if (config.useNicks) {
  1963. nick = window.prompt('Your nickname (optional)');
  1964. }
  1965. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1966. };
  1967. function dump(elem, filename) {
  1968. elem = elem.parentNode;
  1969. elem.download = filename || 'meetlog.json';
  1970. elem.href = 'data:application/json;charset=utf-8,\n';
  1971. var data = APP.xmpp.populateData();
  1972. var metadata = {};
  1973. metadata.time = new Date();
  1974. metadata.url = window.location.href;
  1975. metadata.ua = navigator.userAgent;
  1976. var log = APP.xmpp.getLogger();
  1977. if (log) {
  1978. metadata.xmpp = log;
  1979. }
  1980. data.metadata = metadata;
  1981. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1982. return false;
  1983. }
  1984. UI.getRoomName = function () {
  1985. return roomName;
  1986. };
  1987. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  1988. if(muteAudio || muteVideo) notifyForInitialMute();
  1989. if(muteAudio) UI.setAudioMuted(true);
  1990. if(muteVideo) UI.setVideoMute(true);
  1991. }
  1992. /**
  1993. * Mutes/unmutes the local video.
  1994. */
  1995. UI.toggleVideo = function () {
  1996. setVideoMute(!APP.RTC.localVideo.isMuted());
  1997. };
  1998. /**
  1999. * Mutes / unmutes audio for the local participant.
  2000. */
  2001. UI.toggleAudio = function() {
  2002. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  2003. };
  2004. /**
  2005. * Sets muted audio state for the local participant.
  2006. */
  2007. UI.setAudioMuted = function (mute, earlyMute) {
  2008. var audioMute = null;
  2009. if(earlyMute)
  2010. audioMute = function (mute, cb) {
  2011. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  2012. };
  2013. else
  2014. audioMute = function (mute, cb) {
  2015. return APP.xmpp.setAudioMute(mute, cb);
  2016. }
  2017. if(!audioMute(mute, function () {
  2018. VideoLayout.showLocalAudioIndicator(mute);
  2019. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  2020. }))
  2021. {
  2022. // We still click the button.
  2023. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  2024. return;
  2025. }
  2026. }
  2027. UI.addListener = function (type, listener) {
  2028. eventEmitter.on(type, listener);
  2029. }
  2030. UI.clickOnVideo = function (videoNumber) {
  2031. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  2032. if (remoteVideos.length > videoNumber) {
  2033. remoteVideos[videoNumber].click();
  2034. }
  2035. }
  2036. //Used by torture
  2037. UI.showToolbar = function () {
  2038. return ToolbarToggler.showToolbar();
  2039. }
  2040. //Used by torture
  2041. UI.dockToolbar = function (isDock) {
  2042. return ToolbarToggler.dockToolbar(isDock);
  2043. }
  2044. UI.setVideoMuteButtonsState = function (mute) {
  2045. var video = $('#video');
  2046. var communicativeClass = "icon-camera";
  2047. var muteClass = "icon-camera icon-camera-disabled";
  2048. if (mute) {
  2049. video.removeClass(communicativeClass);
  2050. video.addClass(muteClass);
  2051. } else {
  2052. video.removeClass(muteClass);
  2053. video.addClass(communicativeClass);
  2054. }
  2055. }
  2056. UI.setVideoMute = setVideoMute;
  2057. module.exports = UI;
  2058. },{"../../service/RTC/RTCEvents":96,"../../service/RTC/StreamEventTypes":98,"../../service/connectionquality/CQEvents":101,"../../service/desktopsharing/DesktopSharingEventTypes":102,"../../service/members/Events":103,"../../service/xmpp/XMPPEvents":105,"./../settings/Settings":41,"./audio_levels/AudioLevels.js":10,"./authentication/Authentication":12,"./avatar/Avatar":14,"./etherpad/Etherpad.js":15,"./prezi/Prezi.js":16,"./side_pannels/SidePanelToggler":18,"./side_pannels/chat/Chat.js":19,"./side_pannels/contactlist/ContactList":23,"./side_pannels/settings/SettingsMenu":24,"./toolbars/BottomToolbar":25,"./toolbars/Toolbar":26,"./toolbars/ToolbarToggler":27,"./util/MessageHandler":29,"./util/NicknameHandler":30,"./util/UIUtil":31,"./videolayout/VideoLayout.js":33,"./welcome_page/RoomnameGenerator":34,"./welcome_page/WelcomePage":35,"events":106}],10:[function(require,module,exports){
  2059. var CanvasUtil = require("./CanvasUtils");
  2060. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  2061. function initActiveSpeakerAudioLevels() {
  2062. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  2063. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  2064. // Draw a circle.
  2065. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  2066. // Add a shadow around the circle
  2067. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  2068. ASDrawContext.shadowOffsetX = 0;
  2069. ASDrawContext.shadowOffsetY = 0;
  2070. }
  2071. /**
  2072. * The audio Levels plugin.
  2073. */
  2074. var AudioLevels = (function(my) {
  2075. var audioLevelCanvasCache = {};
  2076. my.LOCAL_LEVEL = 'local';
  2077. my.init = function () {
  2078. initActiveSpeakerAudioLevels();
  2079. }
  2080. /**
  2081. * Updates the audio level canvas for the given peerJid. If the canvas
  2082. * didn't exist we create it.
  2083. */
  2084. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  2085. var resourceJid = null;
  2086. var videoSpanId = null;
  2087. if (!peerJid)
  2088. videoSpanId = 'localVideoContainer';
  2089. else {
  2090. resourceJid = Strophe.getResourceFromJid(peerJid);
  2091. videoSpanId = 'participant_' + resourceJid;
  2092. }
  2093. var videoSpan = document.getElementById(videoSpanId);
  2094. if (!videoSpan) {
  2095. if (resourceJid)
  2096. console.error("No video element for jid", resourceJid);
  2097. else
  2098. console.error("No video element for local video.");
  2099. return;
  2100. }
  2101. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  2102. var videoSpaceWidth = $('#remoteVideos').width();
  2103. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  2104. var thumbnailWidth = thumbnailSize[0];
  2105. var thumbnailHeight = thumbnailSize[1];
  2106. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  2107. audioLevelCanvas = document.createElement('canvas');
  2108. audioLevelCanvas.className = "audiolevel";
  2109. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  2110. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  2111. resizeAudioLevelCanvas( audioLevelCanvas,
  2112. thumbnailWidth,
  2113. thumbnailHeight);
  2114. videoSpan.appendChild(audioLevelCanvas);
  2115. } else {
  2116. audioLevelCanvas = audioLevelCanvas.get(0);
  2117. resizeAudioLevelCanvas( audioLevelCanvas,
  2118. thumbnailWidth,
  2119. thumbnailHeight);
  2120. }
  2121. };
  2122. /**
  2123. * Updates the audio level UI for the given resourceJid.
  2124. *
  2125. * @param resourceJid the resource jid indicating the video element for
  2126. * which we draw the audio level
  2127. * @param audioLevel the newAudio level to render
  2128. */
  2129. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  2130. drawAudioLevelCanvas(resourceJid, audioLevel);
  2131. var videoSpanId = getVideoSpanId(resourceJid);
  2132. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  2133. if (!audioLevelCanvas)
  2134. return;
  2135. var drawContext = audioLevelCanvas.getContext('2d');
  2136. var canvasCache = audioLevelCanvasCache[resourceJid];
  2137. drawContext.clearRect (0, 0,
  2138. audioLevelCanvas.width, audioLevelCanvas.height);
  2139. drawContext.drawImage(canvasCache, 0, 0);
  2140. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  2141. if(!APP.xmpp.myJid()) {
  2142. return;
  2143. }
  2144. resourceJid = APP.xmpp.myResource();
  2145. }
  2146. if(resourceJid === largeVideoResourceJid) {
  2147. window.requestAnimationFrame(function () {
  2148. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  2149. });
  2150. }
  2151. };
  2152. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  2153. if($("#activeSpeaker").css("visibility") == "hidden")
  2154. return;
  2155. ASDrawContext.clearRect(0, 0, 300, 300);
  2156. if(audioLevel == 0)
  2157. return;
  2158. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  2159. // Fill the shape.
  2160. ASDrawContext.fill();
  2161. };
  2162. /**
  2163. * Resizes the given audio level canvas to match the given thumbnail size.
  2164. */
  2165. function resizeAudioLevelCanvas(audioLevelCanvas,
  2166. thumbnailWidth,
  2167. thumbnailHeight) {
  2168. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  2169. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  2170. }
  2171. /**
  2172. * Draws the audio level canvas into the cached canvas object.
  2173. *
  2174. * @param resourceJid the resource jid indicating the video element for
  2175. * which we draw the audio level
  2176. * @param audioLevel the newAudio level to render
  2177. */
  2178. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  2179. if (!audioLevelCanvasCache[resourceJid]) {
  2180. var videoSpanId = getVideoSpanId(resourceJid);
  2181. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  2182. /*
  2183. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  2184. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  2185. * error. Since audio levels are frequently updated, the errors have
  2186. * been observed to pile into the console, strain the CPU.
  2187. */
  2188. if (audioLevelCanvasOrig)
  2189. {
  2190. audioLevelCanvasCache[resourceJid]
  2191. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  2192. }
  2193. }
  2194. var canvas = audioLevelCanvasCache[resourceJid];
  2195. if (!canvas)
  2196. return;
  2197. var drawContext = canvas.getContext('2d');
  2198. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  2199. var shadowLevel = getShadowLevel(audioLevel);
  2200. if (shadowLevel > 0)
  2201. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  2202. CanvasUtil.drawRoundRectGlow( drawContext,
  2203. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  2204. canvas.width - interfaceConfig.CANVAS_EXTRA,
  2205. canvas.height - interfaceConfig.CANVAS_EXTRA,
  2206. interfaceConfig.CANVAS_RADIUS,
  2207. interfaceConfig.SHADOW_COLOR,
  2208. shadowLevel);
  2209. }
  2210. /**
  2211. * Returns the shadow/glow level for the given audio level.
  2212. *
  2213. * @param audioLevel the audio level from which we determine the shadow
  2214. * level
  2215. */
  2216. function getShadowLevel (audioLevel) {
  2217. var shadowLevel = 0;
  2218. if (audioLevel <= 0.3) {
  2219. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  2220. }
  2221. else if (audioLevel <= 0.6) {
  2222. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  2223. }
  2224. else {
  2225. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  2226. }
  2227. return shadowLevel;
  2228. }
  2229. /**
  2230. * Returns the video span id corresponding to the given resourceJid or local
  2231. * user.
  2232. */
  2233. function getVideoSpanId(resourceJid) {
  2234. var videoSpanId = null;
  2235. if (resourceJid === AudioLevels.LOCAL_LEVEL
  2236. || (APP.xmpp.myResource() && resourceJid
  2237. === APP.xmpp.myResource()))
  2238. videoSpanId = 'localVideoContainer';
  2239. else
  2240. videoSpanId = 'participant_' + resourceJid;
  2241. return videoSpanId;
  2242. }
  2243. /**
  2244. * Indicates that the remote video has been resized.
  2245. */
  2246. $(document).bind('remotevideo.resized', function (event, width, height) {
  2247. var resized = false;
  2248. $('#remoteVideos>span>canvas').each(function() {
  2249. var canvas = $(this).get(0);
  2250. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  2251. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  2252. resized = true;
  2253. }
  2254. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  2255. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  2256. resized = true;
  2257. }
  2258. });
  2259. if (resized)
  2260. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  2261. audioLevelCanvasCache[resourceJid].width
  2262. = width + interfaceConfig.CANVAS_EXTRA;
  2263. audioLevelCanvasCache[resourceJid].height
  2264. = height + interfaceConfig.CANVAS_EXTRA;
  2265. });
  2266. });
  2267. return my;
  2268. })(AudioLevels || {});
  2269. module.exports = AudioLevels;
  2270. },{"./CanvasUtils":11}],11:[function(require,module,exports){
  2271. /**
  2272. * Utility class for drawing canvas shapes.
  2273. */
  2274. var CanvasUtil = (function(my) {
  2275. /**
  2276. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  2277. * of the glow.
  2278. *
  2279. * @param drawContext the context of the canvas to draw to
  2280. * @param x the x coordinate of the round rectangle
  2281. * @param y the y coordinate of the round rectangle
  2282. * @param w the width of the round rectangle
  2283. * @param h the height of the round rectangle
  2284. * @param glowColor the color of the glow
  2285. * @param glowWidth the width of the glow
  2286. */
  2287. my.drawRoundRectGlow
  2288. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  2289. // Save the previous state of the context.
  2290. drawContext.save();
  2291. if (w < 2 * r) r = w / 2;
  2292. if (h < 2 * r) r = h / 2;
  2293. // Draw a round rectangle.
  2294. drawContext.beginPath();
  2295. drawContext.moveTo(x+r, y);
  2296. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2297. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2298. drawContext.arcTo(x, y+h, x, y, r);
  2299. drawContext.arcTo(x, y, x+w, y, r);
  2300. drawContext.closePath();
  2301. // Add a shadow around the rectangle
  2302. drawContext.shadowColor = glowColor;
  2303. drawContext.shadowBlur = glowWidth;
  2304. drawContext.shadowOffsetX = 0;
  2305. drawContext.shadowOffsetY = 0;
  2306. // Fill the shape.
  2307. drawContext.fill();
  2308. drawContext.save();
  2309. drawContext.restore();
  2310. // 1) Uncomment this line to use Composite Operation, which is doing the
  2311. // same as the clip function below and is also antialiasing the round
  2312. // border, but is said to be less fast performance wise.
  2313. // drawContext.globalCompositeOperation='destination-out';
  2314. drawContext.beginPath();
  2315. drawContext.moveTo(x+r, y);
  2316. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2317. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2318. drawContext.arcTo(x, y+h, x, y, r);
  2319. drawContext.arcTo(x, y, x+w, y, r);
  2320. drawContext.closePath();
  2321. // 2) Uncomment this line to use Composite Operation, which is doing the
  2322. // same as the clip function below and is also antialiasing the round
  2323. // border, but is said to be less fast performance wise.
  2324. // drawContext.fill();
  2325. // Comment these two lines if choosing to do the same with composite
  2326. // operation above 1 and 2.
  2327. drawContext.clip();
  2328. drawContext.clearRect(0, 0, 277, 200);
  2329. // Restore the previous context state.
  2330. drawContext.restore();
  2331. };
  2332. /**
  2333. * Clones the given canvas.
  2334. *
  2335. * @return the new cloned canvas.
  2336. */
  2337. my.cloneCanvas = function (oldCanvas) {
  2338. /*
  2339. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2340. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2341. * levels are frequently updated, the errors have been observed to pile
  2342. * into the console, strain the CPU.
  2343. */
  2344. if (!oldCanvas)
  2345. return oldCanvas;
  2346. //create a new canvas
  2347. var newCanvas = document.createElement('canvas');
  2348. var context = newCanvas.getContext('2d');
  2349. //set dimensions
  2350. newCanvas.width = oldCanvas.width;
  2351. newCanvas.height = oldCanvas.height;
  2352. //apply the old canvas to the new one
  2353. context.drawImage(oldCanvas, 0, 0);
  2354. //return the new canvas
  2355. return newCanvas;
  2356. };
  2357. return my;
  2358. })(CanvasUtil || {});
  2359. module.exports = CanvasUtil;
  2360. },{}],12:[function(require,module,exports){
  2361. /* global $, APP*/
  2362. var LoginDialog = require('./LoginDialog');
  2363. var Moderator = require('../../xmpp/moderator');
  2364. /* Initial "authentication required" dialog */
  2365. var authDialog = null;
  2366. /* Loop retry ID that wits for other user to create the room */
  2367. var authRetryId = null;
  2368. var authenticationWindow = null;
  2369. var Authentication = {
  2370. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2371. // This is the loop that will wait for the room to be created by
  2372. // someone else. 'auth_required.moderator' will bring us back here.
  2373. authRetryId = window.setTimeout(intervalCallback, 5000);
  2374. // Show prompt only if it's not open
  2375. if (authDialog !== null) {
  2376. return;
  2377. }
  2378. // extract room name from 'room@muc.server.net'
  2379. var room = roomName.substr(0, roomName.indexOf('@'));
  2380. var title
  2381. = APP.translation.generateTranslatonHTML("dialog.WaitingForHost");
  2382. var msg
  2383. = APP.translation.generateTranslatonHTML(
  2384. "dialog.WaitForHostMsg", {room: room});
  2385. var buttonTxt
  2386. = APP.translation.generateTranslatonHTML("dialog.IamHost");
  2387. var buttons = [];
  2388. buttons.push({title: buttonTxt, value: "authNow"});
  2389. authDialog = APP.UI.messageHandler.openDialog(
  2390. title,
  2391. msg,
  2392. true,
  2393. buttons,
  2394. function (onSubmitEvent, submitValue) {
  2395. // Do not close the dialog yet
  2396. onSubmitEvent.preventDefault();
  2397. // Open login popup
  2398. if (submitValue === 'authNow') {
  2399. callback();
  2400. }
  2401. }
  2402. );
  2403. },
  2404. closeAuthenticationWindow: function () {
  2405. if (authenticationWindow) {
  2406. authenticationWindow.close();
  2407. authenticationWindow = null;
  2408. }
  2409. },
  2410. xmppAuthenticate: function () {
  2411. var loginDialog = LoginDialog.show(
  2412. function (connection, state) {
  2413. if (!state) {
  2414. // User cancelled
  2415. loginDialog.close();
  2416. return;
  2417. } else if (state == APP.xmpp.Status.CONNECTED) {
  2418. loginDialog.close();
  2419. Authentication.stopInterval();
  2420. Authentication.closeAuthenticationDialog();
  2421. // Close the connection as anonymous one will be used
  2422. // to create the conference. Session-id will authorize
  2423. // the request.
  2424. connection.disconnect();
  2425. var roomName = APP.UI.generateRoomName();
  2426. Moderator.allocateConferenceFocus(roomName, function () {
  2427. // If it's not "on the fly" authentication now join
  2428. // the conference room
  2429. if (!APP.xmpp.getMUCJoined()) {
  2430. APP.UI.checkForNicknameAndJoin();
  2431. }
  2432. });
  2433. }
  2434. }, true);
  2435. },
  2436. focusAuthenticationWindow: function () {
  2437. // If auth window exists just bring it to the front
  2438. if (authenticationWindow) {
  2439. authenticationWindow.focus();
  2440. return;
  2441. }
  2442. },
  2443. closeAuthenticationDialog: function () {
  2444. // Close authentication dialog if opened
  2445. if (authDialog) {
  2446. authDialog.close();
  2447. authDialog = null;
  2448. }
  2449. },
  2450. createAuthenticationWindow: function (callback, url) {
  2451. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2452. url, 910, 660,
  2453. // On closed
  2454. function () {
  2455. // Close authentication dialog if opened
  2456. Authentication.closeAuthenticationDialog();
  2457. callback();
  2458. authenticationWindow = null;
  2459. });
  2460. return authenticationWindow;
  2461. },
  2462. stopInterval: function () {
  2463. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2464. if (authRetryId) {
  2465. window.clearTimeout(authRetryId);
  2466. authRetryId = null;
  2467. }
  2468. }
  2469. };
  2470. module.exports = Authentication;
  2471. },{"../../xmpp/moderator":56,"./LoginDialog":13}],13:[function(require,module,exports){
  2472. /* global $, APP, config*/
  2473. var XMPP = require('../../xmpp/xmpp');
  2474. var Moderator = require('../../xmpp/moderator');
  2475. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  2476. // anonymous domain is not enabled
  2477. /**
  2478. * Creates new <tt>Dialog</tt> instance.
  2479. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  2480. * when we either fail to connect or succeed(check Strophe.Status).
  2481. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  2482. * in order to create session-id after the connection is established.
  2483. * @constructor
  2484. */
  2485. function Dialog(callback, obtainSession) {
  2486. var self = this;
  2487. var stop = false;
  2488. var connection = APP.xmpp.createConnection();
  2489. var message = '<h2 data-i18n="dialog.passwordRequired">';
  2490. message += APP.translation.translateString("dialog.passwordRequired");
  2491. message += '</h2>' +
  2492. '<input name="username" type="text" ' +
  2493. 'placeholder="user@domain.net" autofocus>' +
  2494. '<input name="password" ' +
  2495. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  2496. ' placeholder="user password">';
  2497. var okButton = APP.translation.generateTranslatonHTML("dialog.Ok");
  2498. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel");
  2499. var states = {
  2500. login: {
  2501. html: message,
  2502. buttons: [
  2503. { title: okButton, value: true},
  2504. { title: cancelButton, value: false}
  2505. ],
  2506. focus: ':input:first',
  2507. submit: function (e, v, m, f) {
  2508. e.preventDefault();
  2509. if (v) {
  2510. var jid = f.username;
  2511. var password = f.password;
  2512. if (jid && password) {
  2513. stop = false;
  2514. connection.reset();
  2515. connDialog.goToState('connecting');
  2516. connection.connect(jid, password, stateHandler);
  2517. }
  2518. } else {
  2519. // User cancelled
  2520. stop = true;
  2521. callback();
  2522. }
  2523. }
  2524. },
  2525. connecting: {
  2526. title: APP.translation.translateString('dialog.connecting'),
  2527. html: '<div id="connectionStatus"></div>',
  2528. buttons: [],
  2529. defaultButton: 0
  2530. },
  2531. finished: {
  2532. title: APP.translation.translateString('dialog.error'),
  2533. html: '<div id="errorMessage"></div>',
  2534. buttons: [
  2535. {
  2536. title: APP.translation.translateString('dialog.retry'),
  2537. value: 'retry'
  2538. },
  2539. {
  2540. title: APP.translation.translateString('dialog.Cancel'),
  2541. value: 'cancel'
  2542. },
  2543. ],
  2544. defaultButton: 0,
  2545. submit: function (e, v, m, f) {
  2546. e.preventDefault();
  2547. if (v === 'retry')
  2548. connDialog.goToState('login');
  2549. else
  2550. callback();
  2551. }
  2552. }
  2553. };
  2554. var connDialog
  2555. = APP.UI.messageHandler.openDialogWithStates(states,
  2556. { persistent: true, closeText: '' }, null);
  2557. var stateHandler = function (status, message) {
  2558. if (stop) {
  2559. return;
  2560. }
  2561. var translateKey = "connection." + XMPP.getStatusString(status);
  2562. var statusStr = APP.translation.translateString(translateKey);
  2563. // Display current state
  2564. var connectionStatus =
  2565. connDialog.getState('connecting').find('#connectionStatus');
  2566. connectionStatus.text(statusStr);
  2567. switch (status) {
  2568. case XMPP.Status.CONNECTED:
  2569. stop = true;
  2570. if (!obtainSession) {
  2571. callback(connection, status);
  2572. return;
  2573. }
  2574. // Obtaining session-id status
  2575. connectionStatus.text(
  2576. APP.translation.translateString(
  2577. 'connection.FETCH_SESSION_ID'));
  2578. // Authenticate with Jicofo and obtain session-id
  2579. var roomName = APP.UI.generateRoomName();
  2580. // Jicofo will return new session-id when connected
  2581. // from authenticated domain
  2582. connection.sendIQ(
  2583. Moderator.createConferenceIq(roomName),
  2584. function (result) {
  2585. connectionStatus.text(
  2586. APP.translation.translateString(
  2587. 'connection.GOT_SESSION_ID'));
  2588. stop = true;
  2589. // Parse session-id
  2590. Moderator.parseSessionId(result);
  2591. callback(connection, status);
  2592. },
  2593. function (error) {
  2594. console.error("Auth on the fly failed", error);
  2595. stop = true;
  2596. var errorMsg =
  2597. APP.translation.translateString(
  2598. 'connection.GET_SESSION_ID_ERROR') +
  2599. $(error).find('>error').attr('code');
  2600. self.displayError(errorMsg);
  2601. connection.disconnect();
  2602. });
  2603. break;
  2604. case XMPP.Status.AUTHFAIL:
  2605. case XMPP.Status.CONNFAIL:
  2606. case XMPP.Status.DISCONNECTED:
  2607. stop = true;
  2608. callback(connection, status);
  2609. var errorMessage = statusStr;
  2610. if (message)
  2611. {
  2612. errorMessage += ': ' + message;
  2613. }
  2614. self.displayError(errorMessage);
  2615. break;
  2616. default:
  2617. break;
  2618. }
  2619. };
  2620. /**
  2621. * Displays error message in 'finished' state which allows either to cancel
  2622. * or retry.
  2623. * @param message the final message to be displayed.
  2624. */
  2625. this.displayError = function (message) {
  2626. var finishedState = connDialog.getState('finished');
  2627. var errorMessageElem = finishedState.find('#errorMessage');
  2628. errorMessageElem.text(message);
  2629. connDialog.goToState('finished');
  2630. };
  2631. /**
  2632. * Closes LoginDialog.
  2633. */
  2634. this.close = function () {
  2635. stop = true;
  2636. connDialog.close();
  2637. };
  2638. }
  2639. var LoginDialog = {
  2640. /**
  2641. * Displays login prompt used to establish new XMPP connection. Given
  2642. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  2643. * called when we connect successfully(status === CONNECTED) or when we fail
  2644. * to do so. On connection failure program can call Dialog.close() method in
  2645. * order to cancel or do nothing to let the user retry.
  2646. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  2647. * called when we either fail to connect or succeed(check
  2648. * Strophe.Status).
  2649. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  2650. * Jicofo in order to create session-id after the connection is
  2651. * established.
  2652. * @returns {Dialog}
  2653. */
  2654. show: function (callback, obtainSession) {
  2655. return new Dialog(callback, obtainSession);
  2656. }
  2657. };
  2658. module.exports = LoginDialog;
  2659. },{"../../xmpp/moderator":56,"../../xmpp/xmpp":64}],14:[function(require,module,exports){
  2660. var Settings = require("../../settings/Settings");
  2661. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2662. var users = {};
  2663. var activeSpeakerJid;
  2664. function setVisibility(selector, show) {
  2665. if (selector && selector.length > 0) {
  2666. selector.css("visibility", show ? "visible" : "hidden");
  2667. }
  2668. }
  2669. function isUserMuted(jid) {
  2670. // XXX(gp) we may want to rename this method to something like
  2671. // isUserStreaming, for example.
  2672. if (jid && jid != APP.xmpp.myJid()) {
  2673. var resource = Strophe.getResourceFromJid(jid);
  2674. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2675. return true;
  2676. }
  2677. }
  2678. if(jid && jid == APP.xmpp.myJid())
  2679. {
  2680. var localVideo = APP.RTC.localVideo;
  2681. return (!localVideo || localVideo.isMuted());
  2682. }
  2683. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2684. return null;
  2685. }
  2686. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2687. }
  2688. function getGravatarUrl(id, size) {
  2689. if(id === APP.xmpp.myJid() || !id) {
  2690. id = Settings.getSettings().uid;
  2691. }
  2692. return 'https://www.gravatar.com/avatar/' +
  2693. MD5.hexdigest(id.trim().toLowerCase()) +
  2694. "?d=wavatar&size=" + (size || "30");
  2695. }
  2696. var Avatar = {
  2697. /**
  2698. * Sets the user's avatar in the settings menu(if local user), contact list
  2699. * and thumbnail
  2700. * @param jid jid of the user
  2701. * @param id email or userID to be used as a hash
  2702. */
  2703. setUserAvatar: function (jid, id) {
  2704. if (id) {
  2705. if (users[jid] === id) {
  2706. return;
  2707. }
  2708. users[jid] = id;
  2709. }
  2710. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2711. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2712. var resourceJid = Strophe.getResourceFromJid(jid);
  2713. var thumbnail = $('#participant_' + resourceJid);
  2714. var avatar = $('#avatar_' + resourceJid);
  2715. // set the avatar in the settings menu if it is local user and get the
  2716. // local video container
  2717. if (jid === APP.xmpp.myJid()) {
  2718. $('#avatar').get(0).src = thumbUrl;
  2719. thumbnail = $('#localVideoContainer');
  2720. }
  2721. // set the avatar in the contact list
  2722. var contact = $('#' + resourceJid + '>img');
  2723. if (contact && contact.length > 0) {
  2724. contact.get(0).src = contactListUrl;
  2725. }
  2726. // set the avatar in the thumbnail
  2727. if (avatar && avatar.length > 0) {
  2728. avatar[0].src = thumbUrl;
  2729. } else {
  2730. if (thumbnail && thumbnail.length > 0) {
  2731. avatar = document.createElement('img');
  2732. avatar.id = 'avatar_' + resourceJid;
  2733. avatar.className = 'userAvatar';
  2734. avatar.src = thumbUrl;
  2735. thumbnail.append(avatar);
  2736. }
  2737. }
  2738. //if the user is the current active speaker - update the active speaker
  2739. // avatar
  2740. if (jid === activeSpeakerJid) {
  2741. this.updateActiveSpeakerAvatarSrc(jid);
  2742. }
  2743. },
  2744. /**
  2745. * Hides or shows the user's avatar
  2746. * @param jid jid of the user
  2747. * @param show whether we should show the avatar or not
  2748. * video because there is no dominant speaker and no focused speaker
  2749. */
  2750. showUserAvatar: function (jid, show) {
  2751. if (users[jid]) {
  2752. var resourceJid = Strophe.getResourceFromJid(jid);
  2753. var video = $('#participant_' + resourceJid + '>video');
  2754. var avatar = $('#avatar_' + resourceJid);
  2755. if (jid === APP.xmpp.myJid()) {
  2756. video = $('#localVideoWrapper>video');
  2757. }
  2758. if (show === undefined || show === null) {
  2759. show = isUserMuted(jid);
  2760. }
  2761. //if the user is the currently focused, the dominant speaker or if
  2762. //there is no focused and no dominant speaker and the large video is
  2763. //currently shown
  2764. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2765. setVisibility($("#largeVideo"), !show);
  2766. setVisibility($('#activeSpeaker'), show);
  2767. setVisibility(avatar, false);
  2768. setVisibility(video, false);
  2769. } else {
  2770. if (video && video.length > 0) {
  2771. setVisibility(video, !show);
  2772. }
  2773. setVisibility(avatar, show);
  2774. }
  2775. }
  2776. },
  2777. /**
  2778. * Updates the src of the active speaker avatar
  2779. * @param jid of the current active speaker
  2780. */
  2781. updateActiveSpeakerAvatarSrc: function (jid) {
  2782. if (!jid) {
  2783. jid = APP.xmpp.findJidFromResource(
  2784. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2785. }
  2786. var avatar = $("#activeSpeakerAvatar")[0];
  2787. var url = getGravatarUrl(users[jid],
  2788. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2789. if (jid === activeSpeakerJid && avatar.src === url) {
  2790. return;
  2791. }
  2792. activeSpeakerJid = jid;
  2793. var isMuted = isUserMuted(jid);
  2794. if (jid && isMuted !== null) {
  2795. avatar.src = url;
  2796. setVisibility($("#largeVideo"), !isMuted);
  2797. Avatar.showUserAvatar(jid, isMuted);
  2798. }
  2799. }
  2800. };
  2801. module.exports = Avatar;
  2802. },{"../../../service/RTC/MediaStreamTypes":94,"../../settings/Settings":41,"../videolayout/VideoLayout":33}],15:[function(require,module,exports){
  2803. /* global $, config,
  2804. setLargeVideoVisible, Util */
  2805. var VideoLayout = require("../videolayout/VideoLayout");
  2806. var Prezi = require("../prezi/Prezi");
  2807. var UIUtil = require("../util/UIUtil");
  2808. var etherpadName = null;
  2809. var etherpadIFrame = null;
  2810. var domain = null;
  2811. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2812. /**
  2813. * Resizes the etherpad.
  2814. */
  2815. function resize() {
  2816. if ($('#etherpad>iframe').length) {
  2817. var remoteVideos = $('#remoteVideos');
  2818. var availableHeight
  2819. = window.innerHeight - remoteVideos.outerHeight();
  2820. var availableWidth = UIUtil.getAvailableVideoWidth();
  2821. $('#etherpad>iframe').width(availableWidth);
  2822. $('#etherpad>iframe').height(availableHeight);
  2823. }
  2824. }
  2825. /**
  2826. * Shares the Etherpad name with other participants.
  2827. */
  2828. function shareEtherpad() {
  2829. APP.xmpp.addToPresence("etherpad", etherpadName);
  2830. }
  2831. /**
  2832. * Creates the Etherpad button and adds it to the toolbar.
  2833. */
  2834. function enableEtherpadButton() {
  2835. if (!$('#etherpadButton').is(":visible"))
  2836. $('#etherpadButton').css({display: 'inline-block'});
  2837. }
  2838. /**
  2839. * Creates the IFrame for the etherpad.
  2840. */
  2841. function createIFrame() {
  2842. etherpadIFrame = document.createElement('iframe');
  2843. etherpadIFrame.src = domain + etherpadName + options;
  2844. etherpadIFrame.frameBorder = 0;
  2845. etherpadIFrame.scrolling = "no";
  2846. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2847. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2848. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2849. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2850. etherpadIFrame.onload = function() {
  2851. document.domain = document.domain;
  2852. bubbleIframeMouseMove(etherpadIFrame);
  2853. setTimeout(function() {
  2854. // the iframes inside of the etherpad are
  2855. // not yet loaded when the etherpad iframe is loaded
  2856. var outer = etherpadIFrame.
  2857. contentDocument.getElementsByName("ace_outer")[0];
  2858. bubbleIframeMouseMove(outer);
  2859. var inner = outer.
  2860. contentDocument.getElementsByName("ace_inner")[0];
  2861. bubbleIframeMouseMove(inner);
  2862. }, 2000);
  2863. };
  2864. }
  2865. function bubbleIframeMouseMove(iframe){
  2866. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2867. iframe.contentWindow.onmousemove = function(e){
  2868. if(existingOnMouseMove) existingOnMouseMove(e);
  2869. var evt = document.createEvent("MouseEvents");
  2870. var boundingClientRect = iframe.getBoundingClientRect();
  2871. evt.initMouseEvent(
  2872. "mousemove",
  2873. true, // bubbles
  2874. false, // not cancelable
  2875. window,
  2876. e.detail,
  2877. e.screenX,
  2878. e.screenY,
  2879. e.clientX + boundingClientRect.left,
  2880. e.clientY + boundingClientRect.top,
  2881. e.ctrlKey,
  2882. e.altKey,
  2883. e.shiftKey,
  2884. e.metaKey,
  2885. e.button,
  2886. null // no related element
  2887. );
  2888. iframe.dispatchEvent(evt);
  2889. };
  2890. }
  2891. /**
  2892. * On video selected event.
  2893. */
  2894. $(document).bind('video.selected', function (event, isPresentation) {
  2895. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2896. Etherpad.toggleEtherpad(isPresentation);
  2897. });
  2898. var Etherpad = {
  2899. /**
  2900. * Initializes the etherpad.
  2901. */
  2902. init: function (name) {
  2903. if (config.etherpad_base && !etherpadName) {
  2904. domain = config.etherpad_base;
  2905. if (!name) {
  2906. // In case we're the focus we generate the name.
  2907. etherpadName = Math.random().toString(36).substring(7) +
  2908. '_' + (new Date().getTime()).toString();
  2909. shareEtherpad();
  2910. }
  2911. else
  2912. etherpadName = name;
  2913. enableEtherpadButton();
  2914. /**
  2915. * Resizes the etherpad, when the window is resized.
  2916. */
  2917. $(window).resize(function () {
  2918. resize();
  2919. });
  2920. }
  2921. },
  2922. /**
  2923. * Opens/hides the Etherpad.
  2924. */
  2925. toggleEtherpad: function (isPresentation) {
  2926. if (!etherpadIFrame)
  2927. createIFrame();
  2928. var largeVideo = null;
  2929. if (Prezi.isPresentationVisible())
  2930. largeVideo = $('#presentation>iframe');
  2931. else
  2932. largeVideo = $('#largeVideo');
  2933. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2934. $('#activeSpeaker').css('visibility', 'hidden');
  2935. largeVideo.fadeOut(300, function () {
  2936. if (Prezi.isPresentationVisible()) {
  2937. largeVideo.css({opacity: '0'});
  2938. } else {
  2939. VideoLayout.setLargeVideoVisible(false);
  2940. }
  2941. });
  2942. $('#etherpad>iframe').fadeIn(300, function () {
  2943. document.body.style.background = '#eeeeee';
  2944. $('#etherpad>iframe').css({visibility: 'visible'});
  2945. $('#etherpad').css({zIndex: 2});
  2946. });
  2947. }
  2948. else if ($('#etherpad>iframe')) {
  2949. $('#etherpad>iframe').fadeOut(300, function () {
  2950. $('#etherpad>iframe').css({visibility: 'hidden'});
  2951. $('#etherpad').css({zIndex: 0});
  2952. document.body.style.background = 'black';
  2953. });
  2954. if (!isPresentation) {
  2955. $('#largeVideo').fadeIn(300, function () {
  2956. VideoLayout.setLargeVideoVisible(true);
  2957. });
  2958. }
  2959. }
  2960. resize();
  2961. },
  2962. isVisible: function() {
  2963. var etherpadIframe = $('#etherpad>iframe');
  2964. return etherpadIframe && etherpadIframe.is(':visible');
  2965. }
  2966. };
  2967. module.exports = Etherpad;
  2968. },{"../prezi/Prezi":16,"../util/UIUtil":31,"../videolayout/VideoLayout":33}],16:[function(require,module,exports){
  2969. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2970. var UIUtil = require("../util/UIUtil");
  2971. var VideoLayout = require("../videolayout/VideoLayout");
  2972. var messageHandler = require("../util/MessageHandler");
  2973. var PreziPlayer = require("./PreziPlayer");
  2974. var preziPlayer = null;
  2975. var Prezi = {
  2976. /**
  2977. * Reloads the current presentation.
  2978. */
  2979. reloadPresentation: function() {
  2980. var iframe = document.getElementById(preziPlayer.options.preziId);
  2981. iframe.src = iframe.src;
  2982. },
  2983. /**
  2984. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2985. * otherwise.
  2986. */
  2987. isPresentationVisible: function () {
  2988. return ($('#presentation>iframe') != null
  2989. && $('#presentation>iframe').css('opacity') == 1);
  2990. },
  2991. /**
  2992. * Opens the Prezi dialog, from which the user could choose a presentation
  2993. * to load.
  2994. */
  2995. openPreziDialog: function() {
  2996. var myprezi = APP.xmpp.getPrezi();
  2997. if (myprezi) {
  2998. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  2999. null,
  3000. "dialog.removePreziMsg",
  3001. null,
  3002. false,
  3003. "dialog.Remove",
  3004. function(e,v,m,f) {
  3005. if(v) {
  3006. APP.xmpp.removePreziFromPresence();
  3007. }
  3008. }
  3009. );
  3010. }
  3011. else if (preziPlayer != null) {
  3012. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  3013. null, "dialog.sharePreziMsg",
  3014. null,
  3015. false,
  3016. "dialog.Ok",
  3017. function(e,v,m,f) {
  3018. $.prompt.close();
  3019. }
  3020. );
  3021. }
  3022. else {
  3023. var html = APP.translation.generateTranslatonHTML(
  3024. "dialog.sharePreziTitle");
  3025. var cancelButton = APP.translation.generateTranslatonHTML(
  3026. "dialog.Cancel");
  3027. var shareButton = APP.translation.generateTranslatonHTML(
  3028. "dialog.Share");
  3029. var backButton = APP.translation.generateTranslatonHTML(
  3030. "dialog.Back");
  3031. var buttons = [];
  3032. var buttons1 = [];
  3033. // Cancel button to both states
  3034. buttons.push({title: cancelButton, value: false});
  3035. buttons1.push({title: cancelButton, value: false});
  3036. // Share button
  3037. buttons.push({title: shareButton, value: true});
  3038. // Back button
  3039. buttons1.push({title: backButton, value: true});
  3040. var linkError = APP.translation.generateTranslatonHTML(
  3041. "dialog.preziLinkError");
  3042. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  3043. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  3044. var openPreziState = {
  3045. state0: {
  3046. html: '<h2>' + html + '</h2>' +
  3047. '<input name="preziUrl" type="text" ' +
  3048. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  3049. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  3050. '\' placeholder="' + defaultUrl + '" autofocus>',
  3051. persistent: false,
  3052. buttons: buttons,
  3053. focus: ':input:first',
  3054. defaultButton: 0,
  3055. submit: function (e, v, m, f) {
  3056. e.preventDefault();
  3057. if(v)
  3058. {
  3059. var preziUrl = f.preziUrl;
  3060. if (preziUrl)
  3061. {
  3062. var urlValue
  3063. = encodeURI(UIUtil.escapeHtml(preziUrl));
  3064. if (urlValue.indexOf('http://prezi.com/') != 0
  3065. && urlValue.indexOf('https://prezi.com/') != 0)
  3066. {
  3067. $.prompt.goToState('state1');
  3068. return false;
  3069. }
  3070. else {
  3071. var presIdTmp = urlValue.substring(
  3072. urlValue.indexOf("prezi.com/") + 10);
  3073. if (!isAlphanumeric(presIdTmp)
  3074. || presIdTmp.indexOf('/') < 2) {
  3075. $.prompt.goToState('state1');
  3076. return false;
  3077. }
  3078. else {
  3079. APP.xmpp.addToPresence("prezi", urlValue);
  3080. $.prompt.close();
  3081. }
  3082. }
  3083. }
  3084. }
  3085. else
  3086. $.prompt.close();
  3087. }
  3088. },
  3089. state1: {
  3090. html: '<h2>' + html + '</h2>' +
  3091. linkError,
  3092. persistent: false,
  3093. buttons: buttons1,
  3094. focus: ':input:first',
  3095. defaultButton: 1,
  3096. submit: function (e, v, m, f) {
  3097. e.preventDefault();
  3098. if (v === 0)
  3099. $.prompt.close();
  3100. else
  3101. $.prompt.goToState('state0');
  3102. }
  3103. }
  3104. };
  3105. messageHandler.openDialogWithStates(openPreziState);
  3106. }
  3107. }
  3108. };
  3109. /**
  3110. * A new presentation has been added.
  3111. *
  3112. * @param event the event indicating the add of a presentation
  3113. * @param jid the jid from which the presentation was added
  3114. * @param presUrl url of the presentation
  3115. * @param currentSlide the current slide to which we should move
  3116. */
  3117. function presentationAdded(event, jid, presUrl, currentSlide) {
  3118. console.log("presentation added", presUrl);
  3119. var presId = getPresentationId(presUrl);
  3120. var elementId = 'participant_'
  3121. + Strophe.getResourceFromJid(jid)
  3122. + '_' + presId;
  3123. // We explicitly don't specify the peer jid here, because we don't want
  3124. // this video to be dealt with as a peer related one (for example we
  3125. // don't want to show a mute/kick menu for this one, etc.).
  3126. VideoLayout.addRemoteVideoContainer(null, elementId);
  3127. VideoLayout.resizeThumbnails();
  3128. var controlsEnabled = false;
  3129. if (jid === APP.xmpp.myJid())
  3130. controlsEnabled = true;
  3131. setPresentationVisible(true);
  3132. $('#largeVideoContainer').hover(
  3133. function (event) {
  3134. if (Prezi.isPresentationVisible()) {
  3135. var reloadButtonRight = window.innerWidth
  3136. - $('#presentation>iframe').offset().left
  3137. - $('#presentation>iframe').width();
  3138. $('#reloadPresentation').css({ right: reloadButtonRight,
  3139. display:'inline-block'});
  3140. }
  3141. },
  3142. function (event) {
  3143. if (!Prezi.isPresentationVisible())
  3144. $('#reloadPresentation').css({display:'none'});
  3145. else {
  3146. var e = event.toElement || event.relatedTarget;
  3147. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  3148. $('#reloadPresentation').css({display:'none'});
  3149. }
  3150. });
  3151. preziPlayer = new PreziPlayer(
  3152. 'presentation',
  3153. {preziId: presId,
  3154. width: getPresentationWidth(),
  3155. height: getPresentationHeihgt(),
  3156. controls: controlsEnabled,
  3157. debug: true
  3158. });
  3159. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  3160. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  3161. console.log("prezi status", event.value);
  3162. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  3163. if (jid != APP.xmpp.myJid())
  3164. preziPlayer.flyToStep(currentSlide);
  3165. }
  3166. });
  3167. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  3168. console.log("event value", event.value);
  3169. APP.xmpp.addToPresence("preziSlide", event.value);
  3170. });
  3171. $("#" + elementId).css( 'background-image',
  3172. 'url(../images/avatarprezi.png)');
  3173. $("#" + elementId).click(
  3174. function () {
  3175. setPresentationVisible(true);
  3176. }
  3177. );
  3178. };
  3179. /**
  3180. * A presentation has been removed.
  3181. *
  3182. * @param event the event indicating the remove of a presentation
  3183. * @param jid the jid for which the presentation was removed
  3184. * @param the url of the presentation
  3185. */
  3186. function presentationRemoved(event, jid, presUrl) {
  3187. console.log('presentation removed', presUrl);
  3188. var presId = getPresentationId(presUrl);
  3189. setPresentationVisible(false);
  3190. $('#participant_'
  3191. + Strophe.getResourceFromJid(jid)
  3192. + '_' + presId).remove();
  3193. $('#presentation>iframe').remove();
  3194. if (preziPlayer != null) {
  3195. preziPlayer.destroy();
  3196. preziPlayer = null;
  3197. }
  3198. };
  3199. /**
  3200. * Indicates if the given string is an alphanumeric string.
  3201. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  3202. * purpose of checking URIs.
  3203. */
  3204. function isAlphanumeric(unsafeText) {
  3205. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  3206. return regex.test(unsafeText);
  3207. }
  3208. /**
  3209. * Returns the presentation id from the given url.
  3210. */
  3211. function getPresentationId (presUrl) {
  3212. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  3213. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  3214. }
  3215. /**
  3216. * Returns the presentation width.
  3217. */
  3218. function getPresentationWidth() {
  3219. var availableWidth = UIUtil.getAvailableVideoWidth();
  3220. var availableHeight = getPresentationHeihgt();
  3221. var aspectRatio = 16.0 / 9.0;
  3222. if (availableHeight < availableWidth / aspectRatio) {
  3223. availableWidth = Math.floor(availableHeight * aspectRatio);
  3224. }
  3225. return availableWidth;
  3226. }
  3227. /**
  3228. * Returns the presentation height.
  3229. */
  3230. function getPresentationHeihgt() {
  3231. var remoteVideos = $('#remoteVideos');
  3232. return window.innerHeight - remoteVideos.outerHeight();
  3233. }
  3234. /**
  3235. * Resizes the presentation iframe.
  3236. */
  3237. function resize() {
  3238. if ($('#presentation>iframe')) {
  3239. $('#presentation>iframe').width(getPresentationWidth());
  3240. $('#presentation>iframe').height(getPresentationHeihgt());
  3241. }
  3242. }
  3243. /**
  3244. * Shows/hides a presentation.
  3245. */
  3246. function setPresentationVisible(visible) {
  3247. var prezi = $('#presentation>iframe');
  3248. if (visible) {
  3249. // Trigger the video.selected event to indicate a change in the
  3250. // large video.
  3251. $(document).trigger("video.selected", [true]);
  3252. $('#largeVideo').fadeOut(300);
  3253. prezi.fadeIn(300, function() {
  3254. prezi.css({opacity:'1'});
  3255. ToolbarToggler.dockToolbar(true);
  3256. VideoLayout.setLargeVideoVisible(false);
  3257. });
  3258. $('#activeSpeaker').css('visibility', 'hidden');
  3259. }
  3260. else {
  3261. if (prezi.css('opacity') == '1') {
  3262. prezi.fadeOut(300, function () {
  3263. prezi.css({opacity:'0'});
  3264. $('#reloadPresentation').css({display:'none'});
  3265. $('#largeVideo').fadeIn(300, function() {
  3266. VideoLayout.setLargeVideoVisible(true);
  3267. ToolbarToggler.dockToolbar(false);
  3268. });
  3269. });
  3270. }
  3271. }
  3272. }
  3273. /**
  3274. * Presentation has been removed.
  3275. */
  3276. $(document).bind('presentationremoved.muc', presentationRemoved);
  3277. /**
  3278. * Presentation has been added.
  3279. */
  3280. $(document).bind('presentationadded.muc', presentationAdded);
  3281. /*
  3282. * Indicates presentation slide change.
  3283. */
  3284. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  3285. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  3286. preziPlayer.flyToStep(current);
  3287. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  3288. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  3289. preziPlayer.flyToStep(current, i);
  3290. }
  3291. }
  3292. });
  3293. /**
  3294. * On video selected event.
  3295. */
  3296. $(document).bind('video.selected', function (event, isPresentation) {
  3297. if (!isPresentation && $('#presentation>iframe')) {
  3298. setPresentationVisible(false);
  3299. }
  3300. });
  3301. $(window).resize(function () {
  3302. resize();
  3303. });
  3304. module.exports = Prezi;
  3305. },{"../toolbars/ToolbarToggler":27,"../util/MessageHandler":29,"../util/UIUtil":31,"../videolayout/VideoLayout":33,"./PreziPlayer":17}],17:[function(require,module,exports){
  3306. (function() {
  3307. "use strict";
  3308. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  3309. window.PreziPlayer = (function() {
  3310. PreziPlayer.API_VERSION = 1;
  3311. PreziPlayer.CURRENT_STEP = 'currentStep';
  3312. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  3313. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  3314. PreziPlayer.STATUS_LOADING = 'loading';
  3315. PreziPlayer.STATUS_READY = 'ready';
  3316. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  3317. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  3318. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  3319. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  3320. PreziPlayer.EVENT_STATUS = "statusChange";
  3321. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  3322. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  3323. PreziPlayer.domain = "https://prezi.com";
  3324. PreziPlayer.path = "/player/";
  3325. PreziPlayer.players = {};
  3326. PreziPlayer.binded_methods = ['changesHandler'];
  3327. PreziPlayer.createMultiplePlayers = function(optionArray){
  3328. for(var i=0; i<optionArray.length; i++) {
  3329. var optionSet = optionArray[i];
  3330. new PreziPlayer(optionSet.id, optionSet);
  3331. };
  3332. };
  3333. PreziPlayer.messageReceived = function(event){
  3334. var message, item, player;
  3335. try {
  3336. message = JSON.parse(event.data);
  3337. if (message.id && (player = PreziPlayer.players[message.id])) {
  3338. if (player.options.debug === true) {
  3339. if (console && console.log)
  3340. console.log('received', message);
  3341. }
  3342. if (message.type === "changes") {
  3343. player.changesHandler(message);
  3344. }
  3345. for (var i = 0; i < player.callbacks.length; i++) {
  3346. item = player.callbacks[i];
  3347. if (item && message.type === item.event) {
  3348. item.callback(message);
  3349. }
  3350. }
  3351. }
  3352. } catch (e) { }
  3353. };
  3354. function PreziPlayer(id, options) {
  3355. var params, paramString = "", _this = this;
  3356. if (PreziPlayer.players[id]){
  3357. PreziPlayer.players[id].destroy();
  3358. }
  3359. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  3360. var method_name = PreziPlayer.binded_methods[i];
  3361. _this[method_name] = __bind(_this[method_name], _this);
  3362. };
  3363. options = options || {};
  3364. this.options = options;
  3365. this.values = {'status': PreziPlayer.STATUS_LOADING};
  3366. this.values[PreziPlayer.CURRENT_STEP] = 0;
  3367. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  3368. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  3369. this.callbacks = [];
  3370. this.id = id;
  3371. this.embedTo = document.getElementById(id);
  3372. if (!this.embedTo) {
  3373. throw "The element id is not available.";
  3374. }
  3375. this.iframe = document.createElement('iframe');
  3376. params = [
  3377. { name: 'oid', value: options.preziId },
  3378. { name: 'explorable', value: options.explorable ? 1 : 0 },
  3379. { name: 'controls', value: options.controls ? 1 : 0 }
  3380. ];
  3381. for(var i=0; i<params.length; i++) {
  3382. var param = params[i];
  3383. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  3384. };
  3385. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  3386. this.iframe.frameBorder = 0;
  3387. this.iframe.scrolling = "no";
  3388. this.iframe.width = options.width || 640;
  3389. this.iframe.height = options.height || 480;
  3390. this.embedTo.innerHTML = '';
  3391. // JITSI: IN CASE SOMETHING GOES WRONG.
  3392. try {
  3393. this.embedTo.appendChild(this.iframe);
  3394. }
  3395. catch (err) {
  3396. console.log("CATCH ERROR");
  3397. }
  3398. // JITSI: Increase interval from 200 to 500, which fixes prezi
  3399. // crashes for us.
  3400. this.initPollInterval = setInterval(function(){
  3401. _this.sendMessage({'action': 'init'});
  3402. }, 500);
  3403. PreziPlayer.players[id] = this;
  3404. }
  3405. PreziPlayer.prototype.changesHandler = function(message) {
  3406. var key, value, j, item;
  3407. if (this.initPollInterval) {
  3408. clearInterval(this.initPollInterval);
  3409. this.initPollInterval = false;
  3410. }
  3411. for (key in message.data) {
  3412. if (message.data.hasOwnProperty(key)){
  3413. value = message.data[key];
  3414. this.values[key] = value;
  3415. for (j=0; j<this.callbacks.length; j++) {
  3416. item = this.callbacks[j];
  3417. if (item && item.event === key + "Change"){
  3418. item.callback({type: item.event, value: value});
  3419. }
  3420. }
  3421. }
  3422. }
  3423. };
  3424. PreziPlayer.prototype.destroy = function() {
  3425. if (this.initPollInterval) {
  3426. clearInterval(this.initPollInterval);
  3427. this.initPollInterval = false;
  3428. }
  3429. this.embedTo.innerHTML = '';
  3430. };
  3431. PreziPlayer.prototype.sendMessage = function(message) {
  3432. if (this.options.debug === true) {
  3433. if (console && console.log) console.log('sent', message);
  3434. }
  3435. message.version = PreziPlayer.API_VERSION;
  3436. message.id = this.id;
  3437. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  3438. };
  3439. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  3440. PreziPlayer.prototype.flyToNextStep = function() {
  3441. return this.sendMessage({
  3442. 'action': 'present',
  3443. 'data': ['moveToNextStep']
  3444. });
  3445. };
  3446. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  3447. PreziPlayer.prototype.flyToPreviousStep = function() {
  3448. return this.sendMessage({
  3449. 'action': 'present',
  3450. 'data': ['moveToPrevStep']
  3451. });
  3452. };
  3453. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  3454. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  3455. var obj = this;
  3456. // check animation_step
  3457. if (animation_step > 0 &&
  3458. obj.values.animationCountOnSteps &&
  3459. obj.values.animationCountOnSteps[step] <= animation_step) {
  3460. animation_step = obj.values.animationCountOnSteps[step];
  3461. }
  3462. // jump to animation steps by calling flyToNextStep()
  3463. function doAnimationSteps() {
  3464. if (obj.values.isMoving == true) {
  3465. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  3466. return;
  3467. }
  3468. while (animation_step-- > 0) {
  3469. obj.flyToNextStep(); // do the animation steps
  3470. }
  3471. }
  3472. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  3473. // jump to the step
  3474. return this.sendMessage({
  3475. 'action': 'present',
  3476. 'data': ['moveToStep', step]
  3477. });
  3478. };
  3479. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  3480. PreziPlayer.prototype.flyToObject = function(objectId) {
  3481. return this.sendMessage({
  3482. 'action': 'present',
  3483. 'data': ['moveToObject', objectId]
  3484. });
  3485. };
  3486. PreziPlayer.prototype.play = function(defaultDelay) {
  3487. return this.sendMessage({
  3488. 'action': 'present',
  3489. 'data': ['startAutoPlay', defaultDelay]
  3490. });
  3491. };
  3492. PreziPlayer.prototype.stop = function() {
  3493. return this.sendMessage({
  3494. 'action': 'present',
  3495. 'data': ['stopAutoPlay']
  3496. });
  3497. };
  3498. PreziPlayer.prototype.pause = function(defaultDelay) {
  3499. return this.sendMessage({
  3500. 'action': 'present',
  3501. 'data': ['pauseAutoPlay', defaultDelay]
  3502. });
  3503. };
  3504. PreziPlayer.prototype.getCurrentStep = function() {
  3505. return this.values.currentStep;
  3506. };
  3507. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  3508. return this.values.currentAnimationStep;
  3509. };
  3510. PreziPlayer.prototype.getCurrentObject = function() {
  3511. return this.values.currentObject;
  3512. };
  3513. PreziPlayer.prototype.getStatus = function() {
  3514. return this.values.status;
  3515. };
  3516. PreziPlayer.prototype.isPlaying = function() {
  3517. return this.values.isAutoPlaying;
  3518. };
  3519. PreziPlayer.prototype.getStepCount = function() {
  3520. return this.values.stepCount;
  3521. };
  3522. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  3523. return this.values.animationCountOnSteps;
  3524. };
  3525. PreziPlayer.prototype.getTitle = function() {
  3526. return this.values.title;
  3527. };
  3528. PreziPlayer.prototype.setDimensions = function(dims) {
  3529. for (var parameter in dims) {
  3530. this.iframe[parameter] = dims[parameter];
  3531. }
  3532. }
  3533. PreziPlayer.prototype.getDimensions = function() {
  3534. return {
  3535. width: parseInt(this.iframe.width, 10),
  3536. height: parseInt(this.iframe.height, 10)
  3537. }
  3538. }
  3539. PreziPlayer.prototype.on = function(event, callback) {
  3540. this.callbacks.push({
  3541. event: event,
  3542. callback: callback
  3543. });
  3544. };
  3545. PreziPlayer.prototype.off = function(event, callback) {
  3546. var j, item;
  3547. if (event === undefined) {
  3548. this.callbacks = [];
  3549. }
  3550. j = this.callbacks.length;
  3551. while (j--) {
  3552. item = this.callbacks[j];
  3553. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3554. this.callbacks.splice(j, 1);
  3555. }
  3556. }
  3557. };
  3558. if (window.addEventListener) {
  3559. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3560. } else {
  3561. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3562. }
  3563. return PreziPlayer;
  3564. })();
  3565. })();
  3566. module.exports = PreziPlayer;
  3567. },{}],18:[function(require,module,exports){
  3568. var Chat = require("./chat/Chat");
  3569. var ContactList = require("./contactlist/ContactList");
  3570. var Settings = require("./../../settings/Settings");
  3571. var SettingsMenu = require("./settings/SettingsMenu");
  3572. var VideoLayout = require("../videolayout/VideoLayout");
  3573. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3574. var UIUtil = require("../util/UIUtil");
  3575. /**
  3576. * Toggler for the chat, contact list, settings menu, etc..
  3577. */
  3578. var PanelToggler = (function(my) {
  3579. var currentlyOpen = null;
  3580. var buttons = {
  3581. '#chatspace': '#chatBottomButton',
  3582. '#contactlist': '#contactListButton',
  3583. '#settingsmenu': '#settingsButton'
  3584. };
  3585. /**
  3586. * Resizes the video area
  3587. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3588. * @param completeFunction a function to be called when the video space is resized
  3589. */
  3590. var resizeVideoArea = function(isClosing, completeFunction) {
  3591. var videospace = $('#videospace');
  3592. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3593. var videospaceWidth = window.innerWidth - panelSize[0];
  3594. var videospaceHeight = window.innerHeight;
  3595. var videoSize
  3596. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3597. var videoWidth = videoSize[0];
  3598. var videoHeight = videoSize[1];
  3599. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3600. videoHeight,
  3601. videospaceWidth,
  3602. videospaceHeight);
  3603. var horizontalIndent = videoPosition[0];
  3604. var verticalIndent = videoPosition[1];
  3605. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3606. var thumbnailsWidth = thumbnailSize[0];
  3607. var thumbnailsHeight = thumbnailSize[1];
  3608. //for chat
  3609. videospace.animate({
  3610. right: panelSize[0],
  3611. width: videospaceWidth,
  3612. height: videospaceHeight
  3613. },
  3614. {
  3615. queue: false,
  3616. duration: 500,
  3617. complete: completeFunction
  3618. });
  3619. $('#remoteVideos').animate({
  3620. height: thumbnailsHeight
  3621. },
  3622. {
  3623. queue: false,
  3624. duration: 500
  3625. });
  3626. $('#remoteVideos>span').animate({
  3627. height: thumbnailsHeight,
  3628. width: thumbnailsWidth
  3629. },
  3630. {
  3631. queue: false,
  3632. duration: 500,
  3633. complete: function () {
  3634. $(document).trigger(
  3635. "remotevideo.resized",
  3636. [thumbnailsWidth,
  3637. thumbnailsHeight]);
  3638. }
  3639. });
  3640. $('#largeVideoContainer').animate({
  3641. width: videospaceWidth,
  3642. height: videospaceHeight
  3643. },
  3644. {
  3645. queue: false,
  3646. duration: 500
  3647. });
  3648. $('#largeVideo').animate({
  3649. width: videoWidth,
  3650. height: videoHeight,
  3651. top: verticalIndent,
  3652. bottom: verticalIndent,
  3653. left: horizontalIndent,
  3654. right: horizontalIndent
  3655. },
  3656. {
  3657. queue: false,
  3658. duration: 500
  3659. });
  3660. };
  3661. /**
  3662. * Toggles the windows in the side panel
  3663. * @param object the window that should be shown
  3664. * @param selector the selector for the element containing the panel
  3665. * @param onOpenComplete function to be called when the panel is opened
  3666. * @param onOpen function to be called if the window is going to be opened
  3667. * @param onClose function to be called if the window is going to be closed
  3668. */
  3669. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3670. UIUtil.buttonClick(buttons[selector], "active");
  3671. if (object.isVisible()) {
  3672. $("#toast-container").animate({
  3673. right: '5px'
  3674. },
  3675. {
  3676. queue: false,
  3677. duration: 500
  3678. });
  3679. $(selector).hide("slide", {
  3680. direction: "right",
  3681. queue: false,
  3682. duration: 500
  3683. });
  3684. if(typeof onClose === "function") {
  3685. onClose();
  3686. }
  3687. currentlyOpen = null;
  3688. }
  3689. else {
  3690. // Undock the toolbar when the chat is shown and if we're in a
  3691. // video mode.
  3692. if (VideoLayout.isLargeVideoVisible()) {
  3693. ToolbarToggler.dockToolbar(false);
  3694. }
  3695. if(currentlyOpen) {
  3696. var current = $(currentlyOpen);
  3697. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3698. current.css('z-index', 4);
  3699. setTimeout(function () {
  3700. current.css('display', 'none');
  3701. current.css('z-index', 5);
  3702. }, 500);
  3703. }
  3704. $("#toast-container").animate({
  3705. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3706. },
  3707. {
  3708. queue: false,
  3709. duration: 500
  3710. });
  3711. $(selector).show("slide", {
  3712. direction: "right",
  3713. queue: false,
  3714. duration: 500,
  3715. complete: onOpenComplete
  3716. });
  3717. if(typeof onOpen === "function") {
  3718. onOpen();
  3719. }
  3720. currentlyOpen = selector;
  3721. }
  3722. };
  3723. /**
  3724. * Opens / closes the chat area.
  3725. */
  3726. my.toggleChat = function() {
  3727. var chatCompleteFunction = Chat.isVisible() ?
  3728. function() {} : function () {
  3729. Chat.scrollChatToBottom();
  3730. $('#chatspace').trigger('shown');
  3731. };
  3732. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3733. toggle(Chat,
  3734. '#chatspace',
  3735. function () {
  3736. // Request the focus in the nickname field or the chat input field.
  3737. if ($('#nickname').css('visibility') === 'visible') {
  3738. $('#nickinput').focus();
  3739. } else {
  3740. $('#usermsg').focus();
  3741. }
  3742. },
  3743. null,
  3744. Chat.resizeChat,
  3745. null);
  3746. };
  3747. /**
  3748. * Opens / closes the contact list area.
  3749. */
  3750. my.toggleContactList = function () {
  3751. var completeFunction = ContactList.isVisible() ?
  3752. function() {} : function () { $('#contactlist').trigger('shown');};
  3753. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3754. toggle(ContactList,
  3755. '#contactlist',
  3756. null,
  3757. function() {
  3758. ContactList.setVisualNotification(false);
  3759. },
  3760. null);
  3761. };
  3762. /**
  3763. * Opens / closes the settings menu
  3764. */
  3765. my.toggleSettingsMenu = function() {
  3766. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3767. toggle(SettingsMenu,
  3768. '#settingsmenu',
  3769. null,
  3770. function() {
  3771. var settings = Settings.getSettings();
  3772. $('#setDisplayName').get(0).value = settings.displayName;
  3773. $('#setEmail').get(0).value = settings.email;
  3774. },
  3775. null);
  3776. };
  3777. /**
  3778. * Returns the size of the side panel.
  3779. */
  3780. my.getPanelSize = function () {
  3781. var availableHeight = window.innerHeight;
  3782. var availableWidth = window.innerWidth;
  3783. var panelWidth = 200;
  3784. if (availableWidth * 0.2 < 200) {
  3785. panelWidth = availableWidth * 0.2;
  3786. }
  3787. return [panelWidth, availableHeight];
  3788. };
  3789. my.isVisible = function() {
  3790. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3791. };
  3792. return my;
  3793. }(PanelToggler || {}));
  3794. module.exports = PanelToggler;
  3795. },{"../toolbars/ToolbarToggler":27,"../util/UIUtil":31,"../videolayout/VideoLayout":33,"./../../settings/Settings":41,"./chat/Chat":19,"./contactlist/ContactList":23,"./settings/SettingsMenu":24}],19:[function(require,module,exports){
  3796. /* global $, Util, nickname:true */
  3797. var Replacement = require("./Replacement");
  3798. var CommandsProcessor = require("./Commands");
  3799. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3800. var smileys = require("./smileys.json").smileys;
  3801. var NicknameHandler = require("../../util/NicknameHandler");
  3802. var UIUtil = require("../../util/UIUtil");
  3803. var UIEvents = require("../../../../service/UI/UIEvents");
  3804. var notificationInterval = false;
  3805. var unreadMessages = 0;
  3806. /**
  3807. * Shows/hides a visual notification, indicating that a message has arrived.
  3808. */
  3809. function setVisualNotification(show) {
  3810. var unreadMsgElement = document.getElementById('unreadMessages');
  3811. var unreadMsgBottomElement
  3812. = document.getElementById('bottomUnreadMessages');
  3813. var glower = $('#chatButton');
  3814. var bottomGlower = $('#chatBottomButton');
  3815. if (unreadMessages) {
  3816. unreadMsgElement.innerHTML = unreadMessages.toString();
  3817. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3818. ToolbarToggler.dockToolbar(true);
  3819. var chatButtonElement
  3820. = document.getElementById('chatButton').parentNode;
  3821. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3822. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3823. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3824. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3825. unreadMsgElement.setAttribute(
  3826. 'style',
  3827. 'top:' + topIndent +
  3828. '; left:' + leftIndent + ';');
  3829. var chatBottomButtonElement
  3830. = document.getElementById('chatBottomButton').parentNode;
  3831. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3832. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3833. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3834. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3835. unreadMsgBottomElement.setAttribute(
  3836. 'style',
  3837. 'top:' + bottomTopIndent +
  3838. '; left:' + bottomLeftIndent + ';');
  3839. if (!glower.hasClass('icon-chat-simple')) {
  3840. glower.removeClass('icon-chat');
  3841. glower.addClass('icon-chat-simple');
  3842. }
  3843. }
  3844. else {
  3845. unreadMsgElement.innerHTML = '';
  3846. unreadMsgBottomElement.innerHTML = '';
  3847. glower.removeClass('icon-chat-simple');
  3848. glower.addClass('icon-chat');
  3849. }
  3850. if (show && !notificationInterval) {
  3851. notificationInterval = window.setInterval(function () {
  3852. glower.toggleClass('active');
  3853. bottomGlower.toggleClass('active glowing');
  3854. }, 800);
  3855. }
  3856. else if (!show && notificationInterval) {
  3857. window.clearInterval(notificationInterval);
  3858. notificationInterval = false;
  3859. glower.removeClass('active');
  3860. bottomGlower.removeClass('glowing');
  3861. bottomGlower.addClass('active');
  3862. }
  3863. }
  3864. /**
  3865. * Returns the current time in the format it is shown to the user
  3866. * @returns {string}
  3867. */
  3868. function getCurrentTime() {
  3869. var now = new Date();
  3870. var hour = now.getHours();
  3871. var minute = now.getMinutes();
  3872. var second = now.getSeconds();
  3873. if(hour.toString().length === 1) {
  3874. hour = '0'+hour;
  3875. }
  3876. if(minute.toString().length === 1) {
  3877. minute = '0'+minute;
  3878. }
  3879. if(second.toString().length === 1) {
  3880. second = '0'+second;
  3881. }
  3882. return hour+':'+minute+':'+second;
  3883. }
  3884. function toggleSmileys()
  3885. {
  3886. var smileys = $('#smileysContainer');
  3887. if(!smileys.is(':visible')) {
  3888. smileys.show("slide", { direction: "down", duration: 300});
  3889. } else {
  3890. smileys.hide("slide", { direction: "down", duration: 300});
  3891. }
  3892. $('#usermsg').focus();
  3893. }
  3894. function addClickFunction(smiley, number) {
  3895. smiley.onclick = function addSmileyToMessage() {
  3896. var usermsg = $('#usermsg');
  3897. var message = usermsg.val();
  3898. message += smileys['smiley' + number];
  3899. usermsg.val(message);
  3900. usermsg.get(0).setSelectionRange(message.length, message.length);
  3901. toggleSmileys();
  3902. usermsg.focus();
  3903. };
  3904. }
  3905. /**
  3906. * Adds the smileys container to the chat
  3907. */
  3908. function addSmileys() {
  3909. var smileysContainer = document.createElement('div');
  3910. smileysContainer.id = 'smileysContainer';
  3911. for(var i = 1; i <= 21; i++) {
  3912. var smileyContainer = document.createElement('div');
  3913. smileyContainer.id = 'smiley' + i;
  3914. smileyContainer.className = 'smileyContainer';
  3915. var smiley = document.createElement('img');
  3916. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3917. smiley.className = 'smiley';
  3918. addClickFunction(smiley, i);
  3919. smileyContainer.appendChild(smiley);
  3920. smileysContainer.appendChild(smileyContainer);
  3921. }
  3922. $("#chatspace").append(smileysContainer);
  3923. }
  3924. /**
  3925. * Resizes the chat conversation.
  3926. */
  3927. function resizeChatConversation() {
  3928. var msgareaHeight = $('#usermsg').outerHeight();
  3929. var chatspace = $('#chatspace');
  3930. var width = chatspace.width();
  3931. var chat = $('#chatconversation');
  3932. var smileys = $('#smileysarea');
  3933. smileys.height(msgareaHeight);
  3934. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3935. $('#smileysContainer').css('bottom', msgareaHeight);
  3936. chat.width(width - 10);
  3937. chat.height(window.innerHeight - 15 - msgareaHeight);
  3938. }
  3939. /**
  3940. * Chat related user interface.
  3941. */
  3942. var Chat = (function (my) {
  3943. /**
  3944. * Initializes chat related interface.
  3945. */
  3946. my.init = function () {
  3947. if(NicknameHandler.getNickname())
  3948. Chat.setChatConversationMode(true);
  3949. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3950. function (nickname) {
  3951. Chat.setChatConversationMode(true);
  3952. });
  3953. $('#nickinput').keydown(function (event) {
  3954. if (event.keyCode === 13) {
  3955. event.preventDefault();
  3956. var val = UIUtil.escapeHtml(this.value);
  3957. this.value = '';
  3958. if (!NicknameHandler.getNickname()) {
  3959. NicknameHandler.setNickname(val);
  3960. return;
  3961. }
  3962. }
  3963. });
  3964. $('#usermsg').keydown(function (event) {
  3965. if (event.keyCode === 13) {
  3966. event.preventDefault();
  3967. var value = this.value;
  3968. $('#usermsg').val('').trigger('autosize.resize');
  3969. this.focus();
  3970. var command = new CommandsProcessor(value);
  3971. if(command.isCommand())
  3972. {
  3973. command.processCommand();
  3974. }
  3975. else
  3976. {
  3977. var message = UIUtil.escapeHtml(value);
  3978. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3979. }
  3980. }
  3981. });
  3982. var onTextAreaResize = function () {
  3983. resizeChatConversation();
  3984. Chat.scrollChatToBottom();
  3985. };
  3986. $('#usermsg').autosize({callback: onTextAreaResize});
  3987. $("#chatspace").bind("shown",
  3988. function () {
  3989. unreadMessages = 0;
  3990. setVisualNotification(false);
  3991. });
  3992. addSmileys();
  3993. };
  3994. /**
  3995. * Appends the given message to the chat conversation.
  3996. */
  3997. my.updateChatConversation = function (from, displayName, message) {
  3998. var divClassName = '';
  3999. if (APP.xmpp.myJid() === from) {
  4000. divClassName = "localuser";
  4001. }
  4002. else {
  4003. divClassName = "remoteuser";
  4004. if (!Chat.isVisible()) {
  4005. unreadMessages++;
  4006. UIUtil.playSoundNotification('chatNotification');
  4007. setVisualNotification(true);
  4008. }
  4009. }
  4010. // replace links and smileys
  4011. // Strophe already escapes special symbols on sending,
  4012. // so we escape here only tags to avoid double &amp;
  4013. var escMessage = message.replace(/</g, '&lt;').
  4014. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  4015. var escDisplayName = UIUtil.escapeHtml(displayName);
  4016. message = Replacement.processReplacements(escMessage);
  4017. var messageContainer =
  4018. '<div class="chatmessage">'+
  4019. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  4020. '<div class="username ' + divClassName +'">' + escDisplayName +
  4021. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  4022. '</div>' + '<div class="usermessage">' + message + '</div>' +
  4023. '</div>';
  4024. $('#chatconversation').append(messageContainer);
  4025. $('#chatconversation').animate(
  4026. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  4027. };
  4028. /**
  4029. * Appends error message to the conversation
  4030. * @param errorMessage the received error message.
  4031. * @param originalText the original message.
  4032. */
  4033. my.chatAddError = function(errorMessage, originalText)
  4034. {
  4035. errorMessage = UIUtil.escapeHtml(errorMessage);
  4036. originalText = UIUtil.escapeHtml(originalText);
  4037. $('#chatconversation').append(
  4038. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  4039. (originalText? (' \"'+ originalText + '\"') : "") +
  4040. ' was not sent.' +
  4041. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  4042. $('#chatconversation').animate(
  4043. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  4044. };
  4045. /**
  4046. * Sets the subject to the UI
  4047. * @param subject the subject
  4048. */
  4049. my.chatSetSubject = function(subject)
  4050. {
  4051. if(subject)
  4052. subject = subject.trim();
  4053. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  4054. if(subject === "")
  4055. {
  4056. $("#subject").css({display: "none"});
  4057. }
  4058. else
  4059. {
  4060. $("#subject").css({display: "block"});
  4061. }
  4062. };
  4063. /**
  4064. * Sets the chat conversation mode.
  4065. */
  4066. my.setChatConversationMode = function (isConversationMode) {
  4067. if (isConversationMode) {
  4068. $('#nickname').css({visibility: 'hidden'});
  4069. $('#chatconversation').css({visibility: 'visible'});
  4070. $('#usermsg').css({visibility: 'visible'});
  4071. $('#smileysarea').css({visibility: 'visible'});
  4072. $('#usermsg').focus();
  4073. }
  4074. };
  4075. /**
  4076. * Resizes the chat area.
  4077. */
  4078. my.resizeChat = function () {
  4079. var chatSize = require("../SidePanelToggler").getPanelSize();
  4080. $('#chatspace').width(chatSize[0]);
  4081. $('#chatspace').height(chatSize[1]);
  4082. resizeChatConversation();
  4083. };
  4084. /**
  4085. * Indicates if the chat is currently visible.
  4086. */
  4087. my.isVisible = function () {
  4088. return $('#chatspace').is(":visible");
  4089. };
  4090. /**
  4091. * Shows and hides the window with the smileys
  4092. */
  4093. my.toggleSmileys = toggleSmileys;
  4094. /**
  4095. * Scrolls chat to the bottom.
  4096. */
  4097. my.scrollChatToBottom = function() {
  4098. setTimeout(function () {
  4099. $('#chatconversation').scrollTop(
  4100. $('#chatconversation')[0].scrollHeight);
  4101. }, 5);
  4102. };
  4103. return my;
  4104. }(Chat || {}));
  4105. module.exports = Chat;
  4106. },{"../../../../service/UI/UIEvents":99,"../../toolbars/ToolbarToggler":27,"../../util/NicknameHandler":30,"../../util/UIUtil":31,"../SidePanelToggler":18,"./Commands":20,"./Replacement":21,"./smileys.json":22}],20:[function(require,module,exports){
  4107. var UIUtil = require("../../util/UIUtil");
  4108. /**
  4109. * List with supported commands. The keys are the names of the commands and
  4110. * the value is the function that processes the message.
  4111. * @type {{String: function}}
  4112. */
  4113. var commands = {
  4114. "topic" : processTopic
  4115. };
  4116. /**
  4117. * Extracts the command from the message.
  4118. * @param message the received message
  4119. * @returns {string} the command
  4120. */
  4121. function getCommand(message)
  4122. {
  4123. if(message)
  4124. {
  4125. for(var command in commands)
  4126. {
  4127. if(message.indexOf("/" + command) == 0)
  4128. return command;
  4129. }
  4130. }
  4131. return "";
  4132. };
  4133. /**
  4134. * Processes the data for topic command.
  4135. * @param commandArguments the arguments of the topic command.
  4136. */
  4137. function processTopic(commandArguments)
  4138. {
  4139. var topic = UIUtil.escapeHtml(commandArguments);
  4140. APP.xmpp.setSubject(topic);
  4141. }
  4142. /**
  4143. * Constructs new CommandProccessor instance from a message that
  4144. * handles commands received via chat messages.
  4145. * @param message the message
  4146. * @constructor
  4147. */
  4148. function CommandsProcessor(message)
  4149. {
  4150. var command = getCommand(message);
  4151. /**
  4152. * Returns the name of the command.
  4153. * @returns {String} the command
  4154. */
  4155. this.getCommand = function()
  4156. {
  4157. return command;
  4158. };
  4159. var messageArgument = message.substr(command.length + 2);
  4160. /**
  4161. * Returns the arguments of the command.
  4162. * @returns {string}
  4163. */
  4164. this.getArgument = function()
  4165. {
  4166. return messageArgument;
  4167. };
  4168. }
  4169. /**
  4170. * Checks whether this instance is valid command or not.
  4171. * @returns {boolean}
  4172. */
  4173. CommandsProcessor.prototype.isCommand = function()
  4174. {
  4175. if(this.getCommand())
  4176. return true;
  4177. return false;
  4178. };
  4179. /**
  4180. * Processes the command.
  4181. */
  4182. CommandsProcessor.prototype.processCommand = function()
  4183. {
  4184. if(!this.isCommand())
  4185. return;
  4186. commands[this.getCommand()](this.getArgument());
  4187. };
  4188. module.exports = CommandsProcessor;
  4189. },{"../../util/UIUtil":31}],21:[function(require,module,exports){
  4190. var Smileys = require("./smileys.json");
  4191. /**
  4192. * Processes links and smileys in "body"
  4193. */
  4194. function processReplacements(body)
  4195. {
  4196. //make links clickable
  4197. body = linkify(body);
  4198. //add smileys
  4199. body = smilify(body);
  4200. return body;
  4201. }
  4202. /**
  4203. * Finds and replaces all links in the links in "body"
  4204. * with their <a href=""></a>
  4205. */
  4206. function linkify(inputText)
  4207. {
  4208. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  4209. //URLs starting with http://, https://, or ftp://
  4210. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  4211. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  4212. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  4213. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  4214. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  4215. //Change email addresses to mailto:: links.
  4216. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  4217. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  4218. return replacedText;
  4219. }
  4220. /**
  4221. * Replaces common smiley strings with images
  4222. */
  4223. function smilify(body)
  4224. {
  4225. if(!body) {
  4226. return body;
  4227. }
  4228. var regexs = Smileys["regexs"];
  4229. for(var smiley in regexs) {
  4230. if(regexs.hasOwnProperty(smiley)) {
  4231. body = body.replace(regexs[smiley],
  4232. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  4233. }
  4234. }
  4235. return body;
  4236. }
  4237. module.exports = {
  4238. processReplacements: processReplacements,
  4239. linkify: linkify
  4240. };
  4241. },{"./smileys.json":22}],22:[function(require,module,exports){
  4242. module.exports={
  4243. "smileys": {
  4244. "smiley1": ":)",
  4245. "smiley2": ":(",
  4246. "smiley3": ":D",
  4247. "smiley4": "(y)",
  4248. "smiley5": " :P",
  4249. "smiley6": "(wave)",
  4250. "smiley7": "(blush)",
  4251. "smiley8": "(chuckle)",
  4252. "smiley9": "(shocked)",
  4253. "smiley10": ":*",
  4254. "smiley11": "(n)",
  4255. "smiley12": "(search)",
  4256. "smiley13": " <3",
  4257. "smiley14": "(oops)",
  4258. "smiley15": "(angry)",
  4259. "smiley16": "(angel)",
  4260. "smiley17": "(sick)",
  4261. "smiley18": ";(",
  4262. "smiley19": "(bomb)",
  4263. "smiley20": "(clap)",
  4264. "smiley21": " ;)"
  4265. },
  4266. "regexs": {
  4267. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  4268. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  4269. "smiley1": /(:-\)|:\))/gi,
  4270. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  4271. "smiley5": /(:-P|:P|:-p|:p)/gi,
  4272. "smiley6": /(\(wave\))/gi,
  4273. "smiley7": /(\(blush\))/gi,
  4274. "smiley8": /(\(chuckle\))/gi,
  4275. "smiley9": /(:-0|\(shocked\))/gi,
  4276. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  4277. "smiley11": /(\(n\))/gi,
  4278. "smiley12": /(\(search\))/g,
  4279. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  4280. "smiley14": /(\(oops\))/gi,
  4281. "smiley15": /(\(angry\))/gi,
  4282. "smiley16": /(\(angel\))/gi,
  4283. "smiley17": /(\(sick\))/gi,
  4284. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  4285. "smiley19": /(\(bomb\))/gi,
  4286. "smiley20": /(\(clap\))/gi,
  4287. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  4288. }
  4289. }
  4290. },{}],23:[function(require,module,exports){
  4291. var numberOfContacts = 0;
  4292. var notificationInterval;
  4293. /**
  4294. * Updates the number of participants in the contact list button and sets
  4295. * the glow
  4296. * @param delta indicates whether a new user has joined (1) or someone has
  4297. * left(-1)
  4298. */
  4299. function updateNumberOfParticipants(delta) {
  4300. //when the user is alone we don't show the number of participants
  4301. if(numberOfContacts === 0) {
  4302. $("#numberOfParticipants").text('');
  4303. numberOfContacts += delta;
  4304. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  4305. ContactList.setVisualNotification(true);
  4306. numberOfContacts += delta;
  4307. $("#numberOfParticipants").text(numberOfContacts);
  4308. }
  4309. }
  4310. /**
  4311. * Creates the avatar element.
  4312. *
  4313. * @return the newly created avatar element
  4314. */
  4315. function createAvatar(id) {
  4316. var avatar = document.createElement('img');
  4317. avatar.className = "icon-avatar avatar";
  4318. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  4319. return avatar;
  4320. }
  4321. /**
  4322. * Creates the display name paragraph.
  4323. *
  4324. * @param displayName the display name to set
  4325. */
  4326. function createDisplayNameParagraph(key, displayName) {
  4327. var p = document.createElement('p');
  4328. if(displayName)
  4329. p.innerText = displayName;
  4330. else if(key)
  4331. {
  4332. p.setAttribute("data-i18n",key);
  4333. p.innerText = APP.translation.translateString(key);
  4334. }
  4335. return p;
  4336. }
  4337. function stopGlowing(glower) {
  4338. window.clearInterval(notificationInterval);
  4339. notificationInterval = false;
  4340. glower.removeClass('glowing');
  4341. if (!ContactList.isVisible()) {
  4342. glower.removeClass('active');
  4343. }
  4344. }
  4345. /**
  4346. * Contact list.
  4347. */
  4348. var ContactList = {
  4349. /**
  4350. * Indicates if the chat is currently visible.
  4351. *
  4352. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  4353. * otherwise
  4354. */
  4355. isVisible: function () {
  4356. return $('#contactlist').is(":visible");
  4357. },
  4358. /**
  4359. * Adds a contact for the given peerJid if such doesn't yet exist.
  4360. *
  4361. * @param peerJid the peerJid corresponding to the contact
  4362. * @param id the user's email or userId used to get the user's avatar
  4363. */
  4364. ensureAddContact: function (peerJid, id) {
  4365. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4366. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4367. if (!contact || contact.length <= 0)
  4368. ContactList.addContact(peerJid, id);
  4369. },
  4370. /**
  4371. * Adds a contact for the given peer jid.
  4372. *
  4373. * @param peerJid the jid of the contact to add
  4374. * @param id the email or userId of the user
  4375. */
  4376. addContact: function (peerJid, id) {
  4377. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4378. var contactlist = $('#contactlist>ul');
  4379. var newContact = document.createElement('li');
  4380. newContact.id = resourceJid;
  4381. newContact.className = "clickable";
  4382. newContact.onclick = function (event) {
  4383. if (event.currentTarget.className === "clickable") {
  4384. $(ContactList).trigger('contactclicked', [peerJid]);
  4385. }
  4386. };
  4387. newContact.appendChild(createAvatar(id));
  4388. newContact.appendChild(createDisplayNameParagraph("participant"));
  4389. var clElement = contactlist.get(0);
  4390. if (resourceJid === APP.xmpp.myResource()
  4391. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  4392. clElement.insertBefore(newContact,
  4393. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  4394. }
  4395. else {
  4396. clElement.appendChild(newContact);
  4397. }
  4398. updateNumberOfParticipants(1);
  4399. },
  4400. /**
  4401. * Removes a contact for the given peer jid.
  4402. *
  4403. * @param peerJid the peerJid corresponding to the contact to remove
  4404. */
  4405. removeContact: function (peerJid) {
  4406. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4407. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4408. if (contact && contact.length > 0) {
  4409. var contactlist = $('#contactlist>ul');
  4410. contactlist.get(0).removeChild(contact.get(0));
  4411. updateNumberOfParticipants(-1);
  4412. }
  4413. },
  4414. setVisualNotification: function (show, stopGlowingIn) {
  4415. var glower = $('#contactListButton');
  4416. if (show && !notificationInterval) {
  4417. notificationInterval = window.setInterval(function () {
  4418. glower.toggleClass('active glowing');
  4419. }, 800);
  4420. }
  4421. else if (!show && notificationInterval) {
  4422. stopGlowing(glower);
  4423. }
  4424. if (stopGlowingIn) {
  4425. setTimeout(function () {
  4426. stopGlowing(glower);
  4427. }, stopGlowingIn);
  4428. }
  4429. },
  4430. setClickable: function (resourceJid, isClickable) {
  4431. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4432. if (isClickable) {
  4433. contact.addClass('clickable');
  4434. } else {
  4435. contact.removeClass('clickable');
  4436. }
  4437. },
  4438. onDisplayNameChange: function (peerJid, displayName) {
  4439. if (peerJid === 'localVideoContainer')
  4440. peerJid = APP.xmpp.myJid();
  4441. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4442. var contactName = $('#contactlist #' + resourceJid + '>p');
  4443. if (contactName && displayName && displayName.length > 0)
  4444. contactName.html(displayName);
  4445. }
  4446. };
  4447. module.exports = ContactList;
  4448. },{}],24:[function(require,module,exports){
  4449. var Avatar = require("../../avatar/Avatar");
  4450. var Settings = require("./../../../settings/Settings");
  4451. var UIUtil = require("../../util/UIUtil");
  4452. var languages = require("../../../../service/translation/languages");
  4453. function generateLanguagesSelectBox()
  4454. {
  4455. var currentLang = APP.translation.getCurrentLanguage();
  4456. var html = "<select id=\"languages_selectbox\">";
  4457. var langArray = languages.getLanguages();
  4458. for(var i = 0; i < langArray.length; i++)
  4459. {
  4460. var lang = langArray[i];
  4461. html += "<option ";
  4462. if(lang === currentLang)
  4463. html += "selected ";
  4464. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  4465. html += "</option>";
  4466. }
  4467. return html + "</select>";
  4468. }
  4469. var SettingsMenu = {
  4470. init: function () {
  4471. $("#startMutedOptions").before(generateLanguagesSelectBox());
  4472. APP.translation.translateElement($("#languages_selectbox"));
  4473. $('#settingsmenu>input').keyup(function(event){
  4474. if(event.keyCode === 13) {//enter
  4475. SettingsMenu.update();
  4476. }
  4477. });
  4478. if(APP.xmpp.isModerator())
  4479. {
  4480. $("#startMutedOptions").css("display", "block");
  4481. }
  4482. else
  4483. {
  4484. $("#startMutedOptions").css("display", "none");
  4485. }
  4486. $("#updateSettings").click(function () {
  4487. SettingsMenu.update();
  4488. });
  4489. },
  4490. onRoleChanged: function () {
  4491. if(APP.xmpp.isModerator())
  4492. {
  4493. $("#startMutedOptions").css("display", "block");
  4494. }
  4495. else
  4496. {
  4497. $("#startMutedOptions").css("display", "none");
  4498. }
  4499. },
  4500. setStartMuted: function (audio, video) {
  4501. $("#startAudioMuted").attr("checked", audio);
  4502. $("#startVideoMuted").attr("checked", video);
  4503. },
  4504. update: function() {
  4505. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  4506. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  4507. if(newDisplayName) {
  4508. var displayName = Settings.setDisplayName(newDisplayName);
  4509. APP.xmpp.addToPresence("displayName", displayName, true);
  4510. }
  4511. var language = $("#languages_selectbox").val();
  4512. APP.translation.setLanguage(language);
  4513. Settings.setLanguage(language);
  4514. APP.xmpp.addToPresence("email", newEmail);
  4515. var email = Settings.setEmail(newEmail);
  4516. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  4517. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  4518. APP.xmpp.addToPresence("startMuted",
  4519. [startAudioMuted, startVideoMuted]);
  4520. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  4521. },
  4522. isVisible: function() {
  4523. return $('#settingsmenu').is(':visible');
  4524. },
  4525. setDisplayName: function(newDisplayName) {
  4526. var displayName = Settings.setDisplayName(newDisplayName);
  4527. $('#setDisplayName').get(0).value = displayName;
  4528. },
  4529. onDisplayNameChange: function(peerJid, newDisplayName) {
  4530. if(peerJid === 'localVideoContainer' ||
  4531. peerJid === APP.xmpp.myJid()) {
  4532. this.setDisplayName(newDisplayName);
  4533. }
  4534. }
  4535. };
  4536. module.exports = SettingsMenu;
  4537. },{"../../../../service/translation/languages":104,"../../avatar/Avatar":14,"../../util/UIUtil":31,"./../../../settings/Settings":41}],25:[function(require,module,exports){
  4538. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4539. var buttonHandlers = {
  4540. "bottom_toolbar_contact_list": function () {
  4541. BottomToolbar.toggleContactList();
  4542. },
  4543. "bottom_toolbar_film_strip": function () {
  4544. BottomToolbar.toggleFilmStrip();
  4545. },
  4546. "bottom_toolbar_chat": function () {
  4547. BottomToolbar.toggleChat();
  4548. }
  4549. };
  4550. var BottomToolbar = (function (my) {
  4551. my.init = function () {
  4552. for(var k in buttonHandlers)
  4553. $("#" + k).click(buttonHandlers[k]);
  4554. };
  4555. my.toggleChat = function() {
  4556. PanelToggler.toggleChat();
  4557. };
  4558. my.toggleContactList = function() {
  4559. PanelToggler.toggleContactList();
  4560. };
  4561. my.toggleFilmStrip = function() {
  4562. var filmstrip = $("#remoteVideos");
  4563. filmstrip.toggleClass("hidden");
  4564. };
  4565. $(document).bind("remotevideo.resized", function (event, width, height) {
  4566. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  4567. $('#bottomToolbar').css({bottom: bottom + 'px'});
  4568. });
  4569. return my;
  4570. }(BottomToolbar || {}));
  4571. module.exports = BottomToolbar;
  4572. },{"../side_pannels/SidePanelToggler":18}],26:[function(require,module,exports){
  4573. /* global APP,$, buttonClick, config, lockRoom,
  4574. setSharedKey, Util */
  4575. var messageHandler = require("../util/MessageHandler");
  4576. var BottomToolbar = require("./BottomToolbar");
  4577. var Prezi = require("../prezi/Prezi");
  4578. var Etherpad = require("../etherpad/Etherpad");
  4579. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4580. var Authentication = require("../authentication/Authentication");
  4581. var UIUtil = require("../util/UIUtil");
  4582. var AuthenticationEvents
  4583. = require("../../../service/authentication/AuthenticationEvents");
  4584. var roomUrl = null;
  4585. var sharedKey = '';
  4586. var UI = null;
  4587. var buttonHandlers =
  4588. {
  4589. "toolbar_button_mute": function () {
  4590. return APP.UI.toggleAudio();
  4591. },
  4592. "toolbar_button_camera": function () {
  4593. return APP.UI.toggleVideo();
  4594. },
  4595. /*"toolbar_button_authentication": function () {
  4596. return Toolbar.authenticateClicked();
  4597. },*/
  4598. "toolbar_button_record": function () {
  4599. return toggleRecording();
  4600. },
  4601. "toolbar_button_security": function () {
  4602. return Toolbar.openLockDialog();
  4603. },
  4604. "toolbar_button_link": function () {
  4605. return Toolbar.openLinkDialog();
  4606. },
  4607. "toolbar_button_chat": function () {
  4608. return BottomToolbar.toggleChat();
  4609. },
  4610. "toolbar_button_prezi": function () {
  4611. return Prezi.openPreziDialog();
  4612. },
  4613. "toolbar_button_etherpad": function () {
  4614. return Etherpad.toggleEtherpad(0);
  4615. },
  4616. "toolbar_button_desktopsharing": function () {
  4617. return APP.desktopsharing.toggleScreenSharing();
  4618. },
  4619. "toolbar_button_fullScreen": function()
  4620. {
  4621. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4622. return Toolbar.toggleFullScreen();
  4623. },
  4624. "toolbar_button_sip": function () {
  4625. return callSipButtonClicked();
  4626. },
  4627. "toolbar_button_dialpad": function () {
  4628. return dialpadButtonClicked();
  4629. },
  4630. "toolbar_button_settings": function () {
  4631. PanelToggler.toggleSettingsMenu();
  4632. },
  4633. "toolbar_button_hangup": function () {
  4634. return hangup();
  4635. },
  4636. "toolbar_button_login": function () {
  4637. Toolbar.authenticateClicked();
  4638. },
  4639. "toolbar_button_logout": function () {
  4640. // Ask for confirmation
  4641. messageHandler.openTwoButtonDialog(
  4642. "dialog.logoutTitle",
  4643. null,
  4644. "dialog.logoutQuestion",
  4645. null,
  4646. false,
  4647. "dialog.Yes",
  4648. function (evt, yes) {
  4649. if (yes) {
  4650. APP.xmpp.logout(function (url) {
  4651. if (url) {
  4652. window.location.href = url;
  4653. } else {
  4654. hangup();
  4655. }
  4656. });
  4657. }
  4658. });
  4659. }
  4660. };
  4661. function hangup() {
  4662. APP.xmpp.disposeConference();
  4663. if(config.enableWelcomePage)
  4664. {
  4665. setTimeout(function()
  4666. {
  4667. window.localStorage.welcomePageDisabled = false;
  4668. window.location.pathname = "/";
  4669. }, 10000);
  4670. }
  4671. var title = APP.translation.generateTranslatonHTML(
  4672. "dialog.sessTerminated");
  4673. var msg = APP.translation.generateTranslatonHTML(
  4674. "dialog.hungUp");
  4675. var button = APP.translation.generateTranslatonHTML(
  4676. "dialog.joinAgain");
  4677. var buttons = [];
  4678. buttons.push({title: button, value: true});
  4679. UI.messageHandler.openDialog(
  4680. title,
  4681. msg,
  4682. true,
  4683. buttons,
  4684. function(event, value, message, formVals)
  4685. {
  4686. window.location.reload();
  4687. return false;
  4688. }
  4689. );
  4690. }
  4691. /**
  4692. * Starts or stops the recording for the conference.
  4693. */
  4694. function toggleRecording() {
  4695. APP.xmpp.toggleRecording(function (callback) {
  4696. var msg = APP.translation.generateTranslatonHTML(
  4697. "dialog.recordingToken");
  4698. var token = APP.translation.translateString("dialog.token");
  4699. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  4700. '<h2>' + msg + '</h2>' +
  4701. '<input name="recordingToken" type="text" ' +
  4702. ' data-i18n="[placeholder]dialog.token" ' +
  4703. 'placeholder="' + token + '" autofocus>',
  4704. false,
  4705. "dialog.Save",
  4706. function (e, v, m, f) {
  4707. if (v) {
  4708. var token = f.recordingToken;
  4709. if (token) {
  4710. callback(UIUtil.escapeHtml(token));
  4711. }
  4712. }
  4713. },
  4714. null,
  4715. function () { },
  4716. ':input:first'
  4717. );
  4718. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4719. }
  4720. /**
  4721. * Locks / unlocks the room.
  4722. */
  4723. function lockRoom(lock) {
  4724. var currentSharedKey = '';
  4725. if (lock)
  4726. currentSharedKey = sharedKey;
  4727. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4728. // password is required
  4729. if (sharedKey)
  4730. {
  4731. console.log('set room password');
  4732. Toolbar.lockLockButton();
  4733. }
  4734. else
  4735. {
  4736. console.log('removed room password');
  4737. Toolbar.unlockLockButton();
  4738. }
  4739. }, function (err) {
  4740. console.warn('setting password failed', err);
  4741. messageHandler.showError("dialog.lockTitle",
  4742. "dialog.lockMessage");
  4743. Toolbar.setSharedKey('');
  4744. }, function () {
  4745. console.warn('room passwords not supported');
  4746. messageHandler.showError("dialog.warning",
  4747. "dialog.passwordNotSupported");
  4748. Toolbar.setSharedKey('');
  4749. });
  4750. };
  4751. /**
  4752. * Invite participants to conference.
  4753. */
  4754. function inviteParticipants() {
  4755. if (roomUrl === null)
  4756. return;
  4757. var sharedKeyText = "";
  4758. if (sharedKey && sharedKey.length > 0) {
  4759. sharedKeyText =
  4760. APP.translation.translateString("email.sharedKey",
  4761. {sharedKey: sharedKey});
  4762. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  4763. }
  4764. var supportedBrowsers = "Chromium, Google Chrome " +
  4765. APP.translation.translateString("email.and") + " Opera";
  4766. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4767. var subject = APP.translation.translateString("email.subject",
  4768. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  4769. var body = APP.translation.translateString("email.body",
  4770. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  4771. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  4772. body = body.replace(/\n/g, "%0D%0A");
  4773. if (window.localStorage.displayname) {
  4774. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4775. }
  4776. if (interfaceConfig.INVITATION_POWERED_BY) {
  4777. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4778. }
  4779. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4780. }
  4781. function dialpadButtonClicked()
  4782. {
  4783. //TODO show the dialpad window
  4784. }
  4785. function callSipButtonClicked()
  4786. {
  4787. var defaultNumber
  4788. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4789. var sipMsg = APP.translation.generateTranslatonHTML(
  4790. "dialog.sipMsg");
  4791. messageHandler.openTwoButtonDialog(null, null, null,
  4792. '<h2>' + sipMsg + '</h2>' +
  4793. '<input name="sipNumber" type="text"' +
  4794. ' value="' + defaultNumber + '" autofocus>',
  4795. false,
  4796. "dialog.Dial",
  4797. function (e, v, m, f) {
  4798. if (v) {
  4799. var numberInput = f.sipNumber;
  4800. if (numberInput) {
  4801. APP.xmpp.dial(
  4802. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  4803. }
  4804. }
  4805. },
  4806. null, null, ':input:first'
  4807. );
  4808. }
  4809. var Toolbar = (function (my) {
  4810. my.init = function (ui) {
  4811. for(var k in buttonHandlers)
  4812. $("#" + k).click(buttonHandlers[k]);
  4813. UI = ui;
  4814. // Update login info
  4815. APP.xmpp.addListener(
  4816. AuthenticationEvents.IDENTITY_UPDATED,
  4817. function (authenticationEnabled, userIdentity) {
  4818. var loggedIn = false;
  4819. if (userIdentity) {
  4820. loggedIn = true;
  4821. }
  4822. Toolbar.showAuthenticateButton(authenticationEnabled);
  4823. if (authenticationEnabled) {
  4824. Toolbar.setAuthenticatedIdentity(userIdentity);
  4825. Toolbar.showLoginButton(!loggedIn);
  4826. Toolbar.showLogoutButton(loggedIn);
  4827. }
  4828. }
  4829. );
  4830. },
  4831. /**
  4832. * Sets shared key
  4833. * @param sKey the shared key
  4834. */
  4835. my.setSharedKey = function (sKey) {
  4836. sharedKey = sKey;
  4837. };
  4838. my.authenticateClicked = function () {
  4839. Authentication.focusAuthenticationWindow();
  4840. if (!APP.xmpp.isExternalAuthEnabled()) {
  4841. Authentication.xmppAuthenticate();
  4842. return;
  4843. }
  4844. // Get authentication URL
  4845. if (!APP.xmpp.getMUCJoined()) {
  4846. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4847. // If conference has not been started yet - redirect to login page
  4848. window.location.href = url;
  4849. });
  4850. } else {
  4851. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4852. // Otherwise - open popup with authentication URL
  4853. var authenticationWindow = Authentication.createAuthenticationWindow(
  4854. function () {
  4855. // On popup closed - retry room allocation
  4856. APP.xmpp.allocateConferenceFocus(
  4857. APP.UI.getRoomName(),
  4858. function () { console.info("AUTH DONE"); }
  4859. );
  4860. }, url);
  4861. if (!authenticationWindow) {
  4862. messageHandler.openMessageDialog(
  4863. null, "dialog.popupError");
  4864. }
  4865. });
  4866. }
  4867. };
  4868. /**
  4869. * Updates the room invite url.
  4870. */
  4871. my.updateRoomUrl = function (newRoomUrl) {
  4872. roomUrl = newRoomUrl;
  4873. // If the invite dialog has been already opened we update the information.
  4874. var inviteLink = document.getElementById('inviteLinkRef');
  4875. if (inviteLink) {
  4876. inviteLink.value = roomUrl;
  4877. inviteLink.select();
  4878. $('#inviteLinkRef').parent()
  4879. .find('button[value=true]').prop('disabled', false);
  4880. }
  4881. };
  4882. /**
  4883. * Disables and enables some of the buttons.
  4884. */
  4885. my.setupButtonsFromConfig = function () {
  4886. if (config.disablePrezi)
  4887. {
  4888. $("#prezi_button").css({display: "none"});
  4889. }
  4890. };
  4891. /**
  4892. * Opens the lock room dialog.
  4893. */
  4894. my.openLockDialog = function () {
  4895. // Only the focus is able to set a shared key.
  4896. if (!APP.xmpp.isModerator()) {
  4897. if (sharedKey) {
  4898. messageHandler.openMessageDialog(null,
  4899. "dialog.passwordError");
  4900. } else {
  4901. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  4902. }
  4903. } else {
  4904. if (sharedKey) {
  4905. messageHandler.openTwoButtonDialog(null, null,
  4906. "dialog.passwordCheck",
  4907. null,
  4908. false,
  4909. "dialog.Remove",
  4910. function (e, v) {
  4911. if (v) {
  4912. Toolbar.setSharedKey('');
  4913. lockRoom(false);
  4914. }
  4915. });
  4916. } else {
  4917. var msg = APP.translation.generateTranslatonHTML(
  4918. "dialog.passwordMsg");
  4919. var yourPassword = APP.translation.translateString(
  4920. "dialog.yourPassword");
  4921. messageHandler.openTwoButtonDialog(null, null, null,
  4922. '<h2>' + msg + '</h2>' +
  4923. '<input name="lockKey" type="text"' +
  4924. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  4925. 'placeholder="' + yourPassword + '" autofocus>',
  4926. false,
  4927. "dialog.Save",
  4928. function (e, v, m, f) {
  4929. if (v) {
  4930. var lockKey = f.lockKey;
  4931. if (lockKey) {
  4932. Toolbar.setSharedKey(
  4933. UIUtil.escapeHtml(lockKey));
  4934. lockRoom(true);
  4935. }
  4936. }
  4937. },
  4938. null, null, 'input:first'
  4939. );
  4940. }
  4941. }
  4942. };
  4943. /**
  4944. * Opens the invite link dialog.
  4945. */
  4946. my.openLinkDialog = function () {
  4947. var inviteAttreibutes;
  4948. if (roomUrl === null) {
  4949. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  4950. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  4951. } else {
  4952. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  4953. }
  4954. messageHandler.openTwoButtonDialog("dialog.shareLink",
  4955. null, null,
  4956. '<input id="inviteLinkRef" type="text" ' +
  4957. inviteAttreibutes + ' onclick="this.select();" readonly>',
  4958. false,
  4959. "dialog.Invite",
  4960. function (e, v) {
  4961. if (v) {
  4962. if (roomUrl) {
  4963. inviteParticipants();
  4964. }
  4965. }
  4966. },
  4967. function (event) {
  4968. if (roomUrl) {
  4969. document.getElementById('inviteLinkRef').select();
  4970. } else {
  4971. if (event && event.target)
  4972. $(event.target)
  4973. .find('button[value=true]').prop('disabled', true);
  4974. }
  4975. }
  4976. );
  4977. };
  4978. /**
  4979. * Opens the settings dialog.
  4980. * FIXME: not used ?
  4981. */
  4982. my.openSettingsDialog = function () {
  4983. var settings1 = APP.translation.generateTranslatonHTML(
  4984. "dialog.settings1");
  4985. var settings2 = APP.translation.generateTranslatonHTML(
  4986. "dialog.settings2");
  4987. var settings3 = APP.translation.generateTranslatonHTML(
  4988. "dialog.settings3");
  4989. var yourPassword = APP.translation.translateString(
  4990. "dialog.yourPassword");
  4991. messageHandler.openTwoButtonDialog(null,
  4992. '<h2>' + settings1 + '</h2>' +
  4993. '<input type="checkbox" id="initMuted">' +
  4994. settings2 + '<br/>' +
  4995. '<input type="checkbox" id="requireNicknames">' +
  4996. settings3 +
  4997. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  4998. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  4999. null,
  5000. null,
  5001. false,
  5002. "dialog.Save",
  5003. function () {
  5004. document.getElementById('lockKey').focus();
  5005. },
  5006. function (e, v) {
  5007. if (v) {
  5008. if ($('#initMuted').is(":checked")) {
  5009. // it is checked
  5010. }
  5011. if ($('#requireNicknames').is(":checked")) {
  5012. // it is checked
  5013. }
  5014. /*
  5015. var lockKey = document.getElementById('lockKey');
  5016. if (lockKey.value) {
  5017. setSharedKey(lockKey.value);
  5018. lockRoom(true);
  5019. }
  5020. */
  5021. }
  5022. }
  5023. );
  5024. };
  5025. /**
  5026. * Toggles the application in and out of full screen mode
  5027. * (a.k.a. presentation mode in Chrome).
  5028. */
  5029. my.toggleFullScreen = function () {
  5030. var fsElement = document.documentElement;
  5031. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  5032. //Enter Full Screen
  5033. if (fsElement.mozRequestFullScreen) {
  5034. fsElement.mozRequestFullScreen();
  5035. }
  5036. else {
  5037. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  5038. }
  5039. } else {
  5040. //Exit Full Screen
  5041. if (document.mozCancelFullScreen) {
  5042. document.mozCancelFullScreen();
  5043. } else {
  5044. document.webkitCancelFullScreen();
  5045. }
  5046. }
  5047. };
  5048. /**
  5049. * Unlocks the lock button state.
  5050. */
  5051. my.unlockLockButton = function () {
  5052. if ($("#lockIcon").hasClass("icon-security-locked"))
  5053. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  5054. };
  5055. /**
  5056. * Updates the lock button state to locked.
  5057. */
  5058. my.lockLockButton = function () {
  5059. if ($("#lockIcon").hasClass("icon-security"))
  5060. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  5061. };
  5062. /**
  5063. * Shows or hides authentication button
  5064. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  5065. */
  5066. my.showAuthenticateButton = function (show) {
  5067. if (show) {
  5068. $('#authentication').css({display: "inline"});
  5069. }
  5070. else {
  5071. $('#authentication').css({display: "none"});
  5072. }
  5073. };
  5074. // Shows or hides the 'recording' button.
  5075. my.showRecordingButton = function (show) {
  5076. if (!config.enableRecording) {
  5077. return;
  5078. }
  5079. if (show) {
  5080. $('#recording').css({display: "inline"});
  5081. }
  5082. else {
  5083. $('#recording').css({display: "none"});
  5084. }
  5085. };
  5086. // Sets the state of the recording button
  5087. my.setRecordingButtonState = function (isRecording) {
  5088. var selector = $('#recordButton');
  5089. if (isRecording) {
  5090. selector.removeClass("icon-recEnable");
  5091. selector.addClass("icon-recEnable active");
  5092. } else {
  5093. selector.removeClass("icon-recEnable active");
  5094. selector.addClass("icon-recEnable");
  5095. }
  5096. };
  5097. // Shows or hides SIP calls button
  5098. my.showSipCallButton = function (show) {
  5099. if (APP.xmpp.isSipGatewayEnabled() && show) {
  5100. $('#sipCallButton').css({display: "inline-block"});
  5101. } else {
  5102. $('#sipCallButton').css({display: "none"});
  5103. }
  5104. };
  5105. // Shows or hides the dialpad button
  5106. my.showDialPadButton = function (show) {
  5107. if (show) {
  5108. $('#dialPadButton').css({display: "inline-block"});
  5109. } else {
  5110. $('#dialPadButton').css({display: "none"});
  5111. }
  5112. };
  5113. /**
  5114. * Displays user authenticated identity name(login).
  5115. * @param authIdentity identity name to be displayed.
  5116. */
  5117. my.setAuthenticatedIdentity = function (authIdentity) {
  5118. if (authIdentity) {
  5119. var selector = $('#toolbar_auth_identity');
  5120. selector.css({display: "list-item"});
  5121. selector.text(authIdentity);
  5122. } else {
  5123. $('#toolbar_auth_identity').css({display: "none"});
  5124. }
  5125. };
  5126. /**
  5127. * Shows/hides login button.
  5128. * @param show <tt>true</tt> to show
  5129. */
  5130. my.showLoginButton = function (show) {
  5131. if (show) {
  5132. $('#toolbar_button_login').css({display: "list-item"});
  5133. } else {
  5134. $('#toolbar_button_login').css({display: "none"});
  5135. }
  5136. };
  5137. /**
  5138. * Shows/hides logout button.
  5139. * @param show <tt>true</tt> to show
  5140. */
  5141. my.showLogoutButton = function (show) {
  5142. if (show) {
  5143. $('#toolbar_button_logout').css({display: "list-item"});
  5144. } else {
  5145. $('#toolbar_button_logout').css({display: "none"});
  5146. }
  5147. };
  5148. /**
  5149. * Sets the state of the button. The button has blue glow if desktop
  5150. * streaming is active.
  5151. * @param active the state of the desktop streaming.
  5152. */
  5153. my.changeDesktopSharingButtonState = function (active) {
  5154. var button = $("#desktopsharing > a");
  5155. if (active)
  5156. {
  5157. button.addClass("glow");
  5158. }
  5159. else
  5160. {
  5161. button.removeClass("glow");
  5162. }
  5163. };
  5164. return my;
  5165. }(Toolbar || {}));
  5166. module.exports = Toolbar;
  5167. },{"../../../service/authentication/AuthenticationEvents":100,"../authentication/Authentication":12,"../etherpad/Etherpad":15,"../prezi/Prezi":16,"../side_pannels/SidePanelToggler":18,"../util/MessageHandler":29,"../util/UIUtil":31,"./BottomToolbar":25}],27:[function(require,module,exports){
  5168. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  5169. var toolbarTimeoutObject,
  5170. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  5171. function showDesktopSharingButton() {
  5172. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  5173. $('#desktopsharing').css({display: "inline"});
  5174. } else {
  5175. $('#desktopsharing').css({display: "none"});
  5176. }
  5177. }
  5178. /**
  5179. * Hides the toolbar.
  5180. */
  5181. function hideToolbar() {
  5182. if(config.alwaysVisibleToolbar)
  5183. return;
  5184. var header = $("#header"),
  5185. bottomToolbar = $("#bottomToolbar");
  5186. var isToolbarHover = false;
  5187. header.find('*').each(function () {
  5188. var id = $(this).attr('id');
  5189. if ($("#" + id + ":hover").length > 0) {
  5190. isToolbarHover = true;
  5191. }
  5192. });
  5193. if ($("#bottomToolbar:hover").length > 0) {
  5194. isToolbarHover = true;
  5195. }
  5196. clearTimeout(toolbarTimeoutObject);
  5197. toolbarTimeoutObject = null;
  5198. if (!isToolbarHover) {
  5199. header.hide("slide", { direction: "up", duration: 300});
  5200. $('#subject').animate({top: "-=40"}, 300);
  5201. if ($("#remoteVideos").hasClass("hidden")) {
  5202. bottomToolbar.hide(
  5203. "slide", {direction: "right", duration: 300});
  5204. }
  5205. }
  5206. else {
  5207. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5208. }
  5209. }
  5210. var ToolbarToggler = {
  5211. /**
  5212. * Shows the main toolbar.
  5213. */
  5214. showToolbar: function () {
  5215. var header = $("#header"),
  5216. bottomToolbar = $("#bottomToolbar");
  5217. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  5218. header.show("slide", { direction: "up", duration: 300});
  5219. $('#subject').animate({top: "+=40"}, 300);
  5220. if (!bottomToolbar.is(":visible")) {
  5221. bottomToolbar.show(
  5222. "slide", {direction: "right", duration: 300});
  5223. }
  5224. if (toolbarTimeoutObject) {
  5225. clearTimeout(toolbarTimeoutObject);
  5226. toolbarTimeoutObject = null;
  5227. }
  5228. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5229. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  5230. }
  5231. if (APP.xmpp.isModerator())
  5232. {
  5233. // TODO: Enable settings functionality.
  5234. // Need to uncomment the settings button in index.html.
  5235. // $('#settingsButton').css({visibility:"visible"});
  5236. }
  5237. // Show/hide desktop sharing button
  5238. showDesktopSharingButton();
  5239. },
  5240. /**
  5241. * Docks/undocks the toolbar.
  5242. *
  5243. * @param isDock indicates what operation to perform
  5244. */
  5245. dockToolbar: function (isDock) {
  5246. if (isDock) {
  5247. // First make sure the toolbar is shown.
  5248. if (!$('#header').is(':visible')) {
  5249. this.showToolbar();
  5250. }
  5251. // Then clear the time out, to dock the toolbar.
  5252. if (toolbarTimeoutObject) {
  5253. clearTimeout(toolbarTimeoutObject);
  5254. toolbarTimeoutObject = null;
  5255. }
  5256. }
  5257. else {
  5258. if (!$('#header').is(':visible')) {
  5259. this.showToolbar();
  5260. }
  5261. else {
  5262. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5263. }
  5264. }
  5265. },
  5266. showDesktopSharingButton: showDesktopSharingButton
  5267. };
  5268. module.exports = ToolbarToggler;
  5269. },{}],28:[function(require,module,exports){
  5270. var JitsiPopover = (function () {
  5271. /**
  5272. * Constructs new JitsiPopover and attaches it to the element
  5273. * @param element jquery selector
  5274. * @param options the options for the popover.
  5275. * @constructor
  5276. */
  5277. function JitsiPopover(element, options)
  5278. {
  5279. this.options = {
  5280. skin: "white",
  5281. content: ""
  5282. };
  5283. if(options)
  5284. {
  5285. if(options.skin)
  5286. this.options.skin = options.skin;
  5287. if(options.content)
  5288. this.options.content = options.content;
  5289. }
  5290. this.elementIsHovered = false;
  5291. this.popoverIsHovered = false;
  5292. this.popoverShown = false;
  5293. element.data("jitsi_popover", this);
  5294. this.element = element;
  5295. this.template = ' <div class="jitsipopover ' + this.options.skin +
  5296. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  5297. '<div class="jitsiPopupmenuPadding"></div></div>';
  5298. var self = this;
  5299. this.element.on("mouseenter", function () {
  5300. self.elementIsHovered = true;
  5301. self.show();
  5302. }).on("mouseleave", function () {
  5303. self.elementIsHovered = false;
  5304. setTimeout(function () {
  5305. self.hide();
  5306. }, 10);
  5307. });
  5308. }
  5309. /**
  5310. * Shows the popover
  5311. */
  5312. JitsiPopover.prototype.show = function () {
  5313. this.createPopover();
  5314. this.popoverShown = true;
  5315. };
  5316. /**
  5317. * Hides the popover
  5318. */
  5319. JitsiPopover.prototype.hide = function () {
  5320. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  5321. {
  5322. this.forceHide();
  5323. }
  5324. };
  5325. /**
  5326. * Hides the popover
  5327. */
  5328. JitsiPopover.prototype.forceHide = function () {
  5329. $(".jitsipopover").remove();
  5330. this.popoverShown = false;
  5331. };
  5332. /**
  5333. * Creates the popover html
  5334. */
  5335. JitsiPopover.prototype.createPopover = function () {
  5336. $("body").append(this.template);
  5337. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  5338. var self = this;
  5339. $(".jitsipopover").on("mouseenter", function () {
  5340. self.popoverIsHovered = true;
  5341. }).on("mouseleave", function () {
  5342. self.popoverIsHovered = false;
  5343. self.hide();
  5344. });
  5345. this.refreshPosition();
  5346. };
  5347. /**
  5348. * Refreshes the position of the popover
  5349. */
  5350. JitsiPopover.prototype.refreshPosition = function () {
  5351. $(".jitsipopover").position({
  5352. my: "bottom",
  5353. at: "top",
  5354. collision: "fit",
  5355. of: this.element,
  5356. using: function (position, elements) {
  5357. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  5358. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  5359. $(".jitsipopover > .arrow").css({left: calcLeft});
  5360. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  5361. }
  5362. });
  5363. };
  5364. /**
  5365. * Updates the content of popover.
  5366. * @param content new content
  5367. */
  5368. JitsiPopover.prototype.updateContent = function (content) {
  5369. this.options.content = content;
  5370. if(!this.popoverShown)
  5371. return;
  5372. $(".jitsipopover").remove();
  5373. this.createPopover();
  5374. };
  5375. return JitsiPopover;
  5376. })();
  5377. module.exports = JitsiPopover;
  5378. },{}],29:[function(require,module,exports){
  5379. /* global $, APP, jQuery, toastr */
  5380. var messageHandler = (function(my) {
  5381. /**
  5382. * Shows a message to the user.
  5383. *
  5384. * @param titleString the title of the message
  5385. * @param messageString the text of the message
  5386. */
  5387. my.openMessageDialog = function(titleKey, messageKey) {
  5388. var title = null;
  5389. if(titleKey)
  5390. {
  5391. title = APP.translation.generateTranslatonHTML(titleKey);
  5392. }
  5393. var message = APP.translation.generateTranslatonHTML(messageKey);
  5394. $.prompt(message,
  5395. {
  5396. title: title,
  5397. persistent: false
  5398. }
  5399. );
  5400. };
  5401. /**
  5402. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5403. *
  5404. * @param titleString the title of the message
  5405. * @param msgString the text of the message
  5406. * @param persistent boolean value which determines whether the message is persistent or not
  5407. * @param leftButton the fist button's text
  5408. * @param submitFunction function to be called on submit
  5409. * @param loadedFunction function to be called after the prompt is fully loaded
  5410. * @param closeFunction function to be called after the prompt is closed
  5411. * @param focus optional focus selector or button index to be focused after
  5412. * the dialog is opened
  5413. * @param defaultButton index of default button which will be activated when
  5414. * the user press 'enter'. Indexed from 0.
  5415. */
  5416. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  5417. persistent, leftButtonKey, submitFunction, loadedFunction,
  5418. closeFunction, focus, defaultButton)
  5419. {
  5420. var buttons = [];
  5421. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  5422. buttons.push({ title: leftButton, value: true});
  5423. var cancelButton
  5424. = APP.translation.generateTranslatonHTML("dialog.Cancel");
  5425. buttons.push({title: cancelButton, value: false});
  5426. var message = msgString, title = titleString;
  5427. if (titleKey)
  5428. {
  5429. title = APP.translation.generateTranslatonHTML(titleKey);
  5430. }
  5431. if (msgKey) {
  5432. message = APP.translation.generateTranslatonHTML(msgKey);
  5433. }
  5434. $.prompt(message, {
  5435. title: title,
  5436. persistent: false,
  5437. buttons: buttons,
  5438. defaultButton: defaultButton,
  5439. focus: focus,
  5440. loaded: loadedFunction,
  5441. submit: submitFunction,
  5442. close: closeFunction
  5443. });
  5444. };
  5445. /**
  5446. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5447. *
  5448. * @param titleString the title of the message
  5449. * @param msgString the text of the message
  5450. * @param persistent boolean value which determines whether the message is persistent or not
  5451. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  5452. * that will be passed to submitFunction
  5453. * @param submitFunction function to be called on submit
  5454. * @param loadedFunction function to be called after the prompt is fully loaded
  5455. */
  5456. my.openDialog = function (titleString, msgString, persistent, buttons,
  5457. submitFunction, loadedFunction) {
  5458. var args = {
  5459. title: titleString,
  5460. persistent: persistent,
  5461. buttons: buttons,
  5462. defaultButton: 1,
  5463. loaded: loadedFunction,
  5464. submit: submitFunction
  5465. };
  5466. if (persistent) {
  5467. args.closeText = '';
  5468. }
  5469. return new Impromptu(msgString, args);
  5470. };
  5471. /**
  5472. * Closes currently opened dialog.
  5473. */
  5474. my.closeDialog = function () {
  5475. $.prompt.close();
  5476. };
  5477. /**
  5478. * Shows a dialog with different states to the user.
  5479. *
  5480. * @param statesObject object containing all the states of the dialog
  5481. */
  5482. my.openDialogWithStates = function (statesObject, options) {
  5483. return new Impromptu(statesObject, options);
  5484. };
  5485. /**
  5486. * Opens new popup window for given <tt>url</tt> centered over current
  5487. * window.
  5488. *
  5489. * @param url the URL to be displayed in the popup window
  5490. * @param w the width of the popup window
  5491. * @param h the height of the popup window
  5492. * @param onPopupClosed optional callback function called when popup window
  5493. * has been closed.
  5494. *
  5495. * @returns popup window object if opened successfully or undefined
  5496. * in case we failed to open it(popup blocked)
  5497. */
  5498. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  5499. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  5500. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  5501. var popup = window.open(
  5502. url, '_blank',
  5503. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  5504. if (popup && onPopupClosed) {
  5505. var pollTimer = window.setInterval(function () {
  5506. if (popup.closed !== false) {
  5507. window.clearInterval(pollTimer);
  5508. onPopupClosed();
  5509. }
  5510. }, 200);
  5511. }
  5512. return popup;
  5513. };
  5514. /**
  5515. * Shows a dialog prompting the user to send an error report.
  5516. *
  5517. * @param titleString the title of the message
  5518. * @param msgString the text of the message
  5519. * @param error the error that is being reported
  5520. */
  5521. my.openReportDialog = function(titleKey, msgKey, error) {
  5522. my.openMessageDialog(titleKey, msgKey);
  5523. console.log(error);
  5524. //FIXME send the error to the server
  5525. };
  5526. /**
  5527. * Shows an error dialog to the user.
  5528. * @param title the title of the message
  5529. * @param message the text of the messafe
  5530. */
  5531. my.showError = function(titleKey, msgKey) {
  5532. if(!titleKey) {
  5533. titleKey = "dialog.oops";
  5534. }
  5535. if(!msgKey)
  5536. {
  5537. msgKey = "dialog.defaultError";
  5538. }
  5539. messageHandler.openMessageDialog(titleKey, msgKey);
  5540. };
  5541. my.notify = function(displayName, displayNameKey,
  5542. cls, messageKey, messageArguments, options) {
  5543. var displayNameSpan = '<span class="nickname" ';
  5544. if(displayName)
  5545. {
  5546. displayNameSpan += ">" + displayName;
  5547. }
  5548. else
  5549. {
  5550. displayNameSpan += "data-i18n='" + displayNameKey +
  5551. "'>" + APP.translation.translateString(displayNameKey);
  5552. }
  5553. displayNameSpan += "</span>";
  5554. toastr.info(
  5555. displayNameSpan + '<br>' +
  5556. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  5557. (messageArguments?
  5558. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  5559. : "") + ">" +
  5560. APP.translation.translateString(messageKey,
  5561. messageArguments) +
  5562. '</span>', null, options);
  5563. };
  5564. return my;
  5565. }(messageHandler || {}));
  5566. module.exports = messageHandler;
  5567. },{}],30:[function(require,module,exports){
  5568. var UIEvents = require("../../../service/UI/UIEvents");
  5569. var nickname = null;
  5570. var eventEmitter = null;
  5571. var NickanameHandler = {
  5572. init: function (emitter) {
  5573. eventEmitter = emitter;
  5574. var storedDisplayName = window.localStorage.displayname;
  5575. if (storedDisplayName) {
  5576. nickname = storedDisplayName;
  5577. }
  5578. },
  5579. setNickname: function (newNickname) {
  5580. if (!newNickname || nickname === newNickname)
  5581. return;
  5582. nickname = newNickname;
  5583. window.localStorage.displayname = nickname;
  5584. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  5585. },
  5586. getNickname: function () {
  5587. return nickname;
  5588. },
  5589. addListener: function (type, listener) {
  5590. eventEmitter.on(type, listener);
  5591. }
  5592. };
  5593. module.exports = NickanameHandler;
  5594. },{"../../../service/UI/UIEvents":99}],31:[function(require,module,exports){
  5595. /**
  5596. * Created by hristo on 12/22/14.
  5597. */
  5598. module.exports = {
  5599. /**
  5600. * Returns the available video width.
  5601. */
  5602. getAvailableVideoWidth: function () {
  5603. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5604. var rightPanelWidth
  5605. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5606. return window.innerWidth - rightPanelWidth;
  5607. },
  5608. /**
  5609. * Changes the style class of the element given by id.
  5610. */
  5611. buttonClick: function(id, classname) {
  5612. $(id).toggleClass(classname); // add the class to the clicked element
  5613. },
  5614. /**
  5615. * Returns the text width for the given element.
  5616. *
  5617. * @param el the element
  5618. */
  5619. getTextWidth: function (el) {
  5620. return (el.clientWidth + 1);
  5621. },
  5622. /**
  5623. * Returns the text height for the given element.
  5624. *
  5625. * @param el the element
  5626. */
  5627. getTextHeight: function (el) {
  5628. return (el.clientHeight + 1);
  5629. },
  5630. /**
  5631. * Plays the sound given by id.
  5632. *
  5633. * @param id the identifier of the audio element.
  5634. */
  5635. playSoundNotification: function (id) {
  5636. document.getElementById(id).play();
  5637. },
  5638. /**
  5639. * Escapes the given text.
  5640. */
  5641. escapeHtml: function (unsafeText) {
  5642. return $('<div/>').text(unsafeText).html();
  5643. },
  5644. imageToGrayScale: function (canvas) {
  5645. var context = canvas.getContext('2d');
  5646. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5647. var pixels = imgData.data;
  5648. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5649. var grayscale
  5650. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5651. pixels[i ] = grayscale; // red
  5652. pixels[i+1] = grayscale; // green
  5653. pixels[i+2] = grayscale; // blue
  5654. // pixels[i+3] is alpha
  5655. }
  5656. // redraw the image in black & white
  5657. context.putImageData(imgData, 0, 0);
  5658. },
  5659. setTooltip: function (element, key, position) {
  5660. element.setAttribute("data-i18n", "[data-content]" + key);
  5661. element.setAttribute("data-toggle", "popover");
  5662. element.setAttribute("data-placement", position);
  5663. element.setAttribute("data-html", true);
  5664. element.setAttribute("data-container", "body");
  5665. }
  5666. };
  5667. },{"../side_pannels/SidePanelToggler":18}],32:[function(require,module,exports){
  5668. var JitsiPopover = require("../util/JitsiPopover");
  5669. /**
  5670. * Constructs new connection indicator.
  5671. * @param videoContainer the video container associated with the indicator.
  5672. * @constructor
  5673. */
  5674. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5675. {
  5676. this.videoContainer = videoContainer;
  5677. this.bandwidth = null;
  5678. this.packetLoss = null;
  5679. this.bitrate = null;
  5680. this.showMoreValue = false;
  5681. this.resolution = null;
  5682. this.transport = [];
  5683. this.popover = null;
  5684. this.jid = jid;
  5685. this.create();
  5686. this.videoLayout = VideoLayout;
  5687. }
  5688. /**
  5689. * Values for the connection quality
  5690. * @type {{98: string,
  5691. * 81: string,
  5692. * 64: string,
  5693. * 47: string,
  5694. * 30: string,
  5695. * 0: string}}
  5696. */
  5697. ConnectionIndicator.connectionQualityValues = {
  5698. 98: "18px", //full
  5699. 81: "15px",//4 bars
  5700. 64: "11px",//3 bars
  5701. 47: "7px",//2 bars
  5702. 30: "3px",//1 bar
  5703. 0: "0px"//empty
  5704. };
  5705. ConnectionIndicator.getIP = function(value)
  5706. {
  5707. return value.substring(0, value.lastIndexOf(":"));
  5708. };
  5709. ConnectionIndicator.getPort = function(value)
  5710. {
  5711. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5712. };
  5713. ConnectionIndicator.getStringFromArray = function (array) {
  5714. var res = "";
  5715. for(var i = 0; i < array.length; i++)
  5716. {
  5717. res += (i === 0? "" : ", ") + array[i];
  5718. }
  5719. return res;
  5720. };
  5721. /**
  5722. * Generates the html content.
  5723. * @returns {string} the html content.
  5724. */
  5725. ConnectionIndicator.prototype.generateText = function () {
  5726. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5727. var translate = APP.translation.translateString;
  5728. if(this.bitrate === null)
  5729. {
  5730. downloadBitrate = "N/A";
  5731. uploadBitrate = "N/A";
  5732. }
  5733. else
  5734. {
  5735. downloadBitrate =
  5736. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5737. uploadBitrate =
  5738. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5739. }
  5740. if(this.packetLoss === null)
  5741. {
  5742. packetLoss = "N/A";
  5743. }
  5744. else
  5745. {
  5746. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5747. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5748. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5749. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5750. }
  5751. var resolutionValue = null;
  5752. if(this.resolution && this.jid != null)
  5753. {
  5754. var keys = Object.keys(this.resolution);
  5755. if(keys.length == 1)
  5756. {
  5757. for(var ssrc in this.resolution)
  5758. {
  5759. resolutionValue = this.resolution[ssrc];
  5760. }
  5761. }
  5762. else if(keys.length > 1)
  5763. {
  5764. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  5765. resolutionValue = this.resolution[displayedSsrc];
  5766. }
  5767. }
  5768. if(this.jid === null)
  5769. {
  5770. resolution = "";
  5771. if(this.resolution === null || !Object.keys(this.resolution) ||
  5772. Object.keys(this.resolution).length === 0)
  5773. {
  5774. resolution = "N/A";
  5775. }
  5776. else
  5777. for(i in this.resolution)
  5778. {
  5779. resolutionValue = this.resolution[i];
  5780. if(resolutionValue)
  5781. {
  5782. if(resolutionValue.height &&
  5783. resolutionValue.width)
  5784. {
  5785. resolution += (resolution === ""? "" : ", ") +
  5786. resolutionValue.width + "x" +
  5787. resolutionValue.height;
  5788. }
  5789. }
  5790. }
  5791. }
  5792. else if(!resolutionValue ||
  5793. !resolutionValue.height ||
  5794. !resolutionValue.width)
  5795. {
  5796. resolution = "N/A";
  5797. }
  5798. else
  5799. {
  5800. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5801. }
  5802. var result = "<table style='width:100%'>" +
  5803. "<tr>" +
  5804. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5805. translate("connectionindicator.bitrate") + "</span></td>" +
  5806. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5807. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5808. uploadBitrate + "</td>" +
  5809. "</tr><tr>" +
  5810. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5811. translate("connectionindicator.packetloss") + "</span></td>" +
  5812. "<td>" + packetLoss + "</td>" +
  5813. "</tr><tr>" +
  5814. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5815. translate("connectionindicator.resolution") + "</span></td>" +
  5816. "<td>" + resolution + "</td></tr></table>";
  5817. if(this.videoContainer.id == "localVideoContainer") {
  5818. result += "<div class=\"jitsipopover_showmore\" " +
  5819. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5820. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5821. (this.showMoreValue ? "less" : "more") + "'>" +
  5822. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5823. "</div><br />";
  5824. }
  5825. if(this.showMoreValue)
  5826. {
  5827. var downloadBandwidth, uploadBandwidth, transport;
  5828. if(this.bandwidth === null)
  5829. {
  5830. downloadBandwidth = "N/A";
  5831. uploadBandwidth = "N/A";
  5832. }
  5833. else
  5834. {
  5835. downloadBandwidth = this.bandwidth.download?
  5836. this.bandwidth.download + " Kbps" :
  5837. "N/A";
  5838. uploadBandwidth = this.bandwidth.upload?
  5839. this.bandwidth.upload + " Kbps" :
  5840. "N/A";
  5841. }
  5842. if(!this.transport || this.transport.length === 0)
  5843. {
  5844. transport = "<tr>" +
  5845. "<td><span class='jitsipopover_blue' " +
  5846. "data-i18n='connectionindicator.address'>" +
  5847. translate("connectionindicator.address") + "</span></td>" +
  5848. "<td> N/A</td></tr>";
  5849. }
  5850. else
  5851. {
  5852. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5853. for(i = 0; i < this.transport.length; i++)
  5854. {
  5855. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5856. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5857. var localIP =
  5858. ConnectionIndicator.getIP(this.transport[i].localip);
  5859. var localPort =
  5860. ConnectionIndicator.getPort(this.transport[i].localip);
  5861. if(data.remoteIP.indexOf(ip) == -1)
  5862. {
  5863. data.remoteIP.push(ip);
  5864. }
  5865. if(data.remotePort.indexOf(port) == -1)
  5866. {
  5867. data.remotePort.push(port);
  5868. }
  5869. if(data.localIP.indexOf(localIP) == -1)
  5870. {
  5871. data.localIP.push(localIP);
  5872. }
  5873. if(data.localPort.indexOf(localPort) == -1)
  5874. {
  5875. data.localPort.push(localPort);
  5876. }
  5877. }
  5878. var local_address_key = "connectionindicator.localaddress";
  5879. var remote_address_key = "connectionindicator.remoteaddress";
  5880. var localTransport =
  5881. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5882. local_address_key +"' data-i18n-options='" +
  5883. JSON.stringify({count: data.localIP.length}) + "'>" +
  5884. translate(local_address_key, {count: data.localIP.length}) +
  5885. "</span></td><td> " +
  5886. ConnectionIndicator.getStringFromArray(data.localIP) +
  5887. "</td></tr>";
  5888. transport =
  5889. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5890. remote_address_key + "' data-i18n-options='" +
  5891. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  5892. translate(remote_address_key,
  5893. {count: data.remoteIP.length}) +
  5894. "</span></td><td> " +
  5895. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5896. "</td></tr>";
  5897. var key_remote = "connectionindicator.remoteport",
  5898. key_local = "connectionindicator.localport";
  5899. transport += "<tr>" +
  5900. "<td>" +
  5901. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5902. "' data-i18n-options='" +
  5903. JSON.stringify({count: this.transport.length}) + "'>" +
  5904. translate(key_remote, {count: this.transport.length}) +
  5905. "</span></td><td>";
  5906. localTransport += "<tr>" +
  5907. "<td>" +
  5908. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5909. "' data-i18n-options='" +
  5910. JSON.stringify({count: this.transport.length}) + "'>" +
  5911. translate(key_local, {count: this.transport.length}) +
  5912. "</span></td><td>";
  5913. transport +=
  5914. ConnectionIndicator.getStringFromArray(data.remotePort);
  5915. localTransport +=
  5916. ConnectionIndicator.getStringFromArray(data.localPort);
  5917. transport += "</td></tr>";
  5918. transport += localTransport + "</td></tr>";
  5919. transport +="<tr>" +
  5920. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5921. translate("connectionindicator.transport") + "</span></td>" +
  5922. "<td>" + this.transport[0].type + "</td></tr>";
  5923. }
  5924. result += "<table style='width:100%'>" +
  5925. "<tr>" +
  5926. "<td>" +
  5927. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5928. translate("connectionindicator.bandwidth") + "</span>" +
  5929. "</td><td>" +
  5930. "<span class='jitsipopover_green'>&darr;</span>" +
  5931. downloadBandwidth +
  5932. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5933. uploadBandwidth + "</td></tr>";
  5934. result += transport + "</table>";
  5935. }
  5936. return result;
  5937. };
  5938. /**
  5939. * Shows or hide the additional information.
  5940. */
  5941. ConnectionIndicator.prototype.showMore = function () {
  5942. this.showMoreValue = !this.showMoreValue;
  5943. this.updatePopoverData();
  5944. };
  5945. function createIcon(classes)
  5946. {
  5947. var icon = document.createElement("span");
  5948. for(var i in classes)
  5949. {
  5950. icon.classList.add(classes[i]);
  5951. }
  5952. icon.appendChild(
  5953. document.createElement("i")).classList.add("icon-connection");
  5954. return icon;
  5955. }
  5956. /**
  5957. * Creates the indicator
  5958. */
  5959. ConnectionIndicator.prototype.create = function () {
  5960. this.connectionIndicatorContainer = document.createElement("div");
  5961. this.connectionIndicatorContainer.className = "connectionindicator";
  5962. this.connectionIndicatorContainer.style.display = "none";
  5963. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5964. this.popover = new JitsiPopover(
  5965. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5966. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5967. APP.translation.translateString("connectionindicator.na") + "</div>",
  5968. skin: "black"});
  5969. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5970. createIcon(["connection", "connection_empty"]));
  5971. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5972. createIcon(["connection", "connection_full"]));
  5973. };
  5974. /**
  5975. * Removes the indicator
  5976. */
  5977. ConnectionIndicator.prototype.remove = function()
  5978. {
  5979. this.connectionIndicatorContainer.remove();
  5980. this.popover.forceHide();
  5981. };
  5982. /**
  5983. * Updates the data of the indicator
  5984. * @param percent the percent of connection quality
  5985. * @param object the statistics data.
  5986. */
  5987. ConnectionIndicator.prototype.updateConnectionQuality =
  5988. function (percent, object) {
  5989. if(percent === null)
  5990. {
  5991. this.connectionIndicatorContainer.style.display = "none";
  5992. this.popover.forceHide();
  5993. return;
  5994. }
  5995. else
  5996. {
  5997. if(this.connectionIndicatorContainer.style.display == "none") {
  5998. this.connectionIndicatorContainer.style.display = "block";
  5999. this.videoLayout.updateMutePosition(this.videoContainer.id);
  6000. }
  6001. }
  6002. this.bandwidth = object.bandwidth;
  6003. this.bitrate = object.bitrate;
  6004. this.packetLoss = object.packetLoss;
  6005. this.transport = object.transport;
  6006. if(object.resolution)
  6007. {
  6008. this.resolution = object.resolution;
  6009. }
  6010. for(var quality in ConnectionIndicator.connectionQualityValues)
  6011. {
  6012. if(percent >= quality)
  6013. {
  6014. this.fullIcon.style.width =
  6015. ConnectionIndicator.connectionQualityValues[quality];
  6016. }
  6017. }
  6018. this.updatePopoverData();
  6019. };
  6020. /**
  6021. * Updates the resolution
  6022. * @param resolution the new resolution
  6023. */
  6024. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  6025. this.resolution = resolution;
  6026. this.updatePopoverData();
  6027. };
  6028. /**
  6029. * Updates the content of the popover
  6030. */
  6031. ConnectionIndicator.prototype.updatePopoverData = function () {
  6032. this.popover.updateContent(
  6033. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  6034. APP.translation.translateElement($(".connection_info"));
  6035. };
  6036. /**
  6037. * Hides the popover
  6038. */
  6039. ConnectionIndicator.prototype.hide = function () {
  6040. this.popover.forceHide();
  6041. };
  6042. /**
  6043. * Hides the indicator
  6044. */
  6045. ConnectionIndicator.prototype.hideIndicator = function () {
  6046. this.connectionIndicatorContainer.style.display = "none";
  6047. if(this.popover)
  6048. this.popover.forceHide();
  6049. };
  6050. module.exports = ConnectionIndicator;
  6051. },{"../util/JitsiPopover":28}],33:[function(require,module,exports){
  6052. var AudioLevels = require("../audio_levels/AudioLevels");
  6053. var Avatar = require("../avatar/Avatar");
  6054. var Chat = require("../side_pannels/chat/Chat");
  6055. var ContactList = require("../side_pannels/contactlist/ContactList");
  6056. var UIUtil = require("../util/UIUtil");
  6057. var ConnectionIndicator = require("./ConnectionIndicator");
  6058. var NicknameHandler = require("../util/NicknameHandler");
  6059. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  6060. var UIEvents = require("../../../service/UI/UIEvents");
  6061. var currentDominantSpeaker = null;
  6062. var lastNCount = config.channelLastN;
  6063. var localLastNCount = config.channelLastN;
  6064. var localLastNSet = [];
  6065. var lastNEndpointsCache = [];
  6066. var lastNPickupJid = null;
  6067. var largeVideoState = {
  6068. updateInProgress: false,
  6069. newSrc: ''
  6070. };
  6071. var eventEmitter = null;
  6072. /**
  6073. * Currently focused video "src"(displayed in large video).
  6074. * @type {String}
  6075. */
  6076. var focusedVideoInfo = null;
  6077. /**
  6078. * Indicates if we have muted our audio before the conference has started.
  6079. * @type {boolean}
  6080. */
  6081. var preMuted = false;
  6082. var mutedAudios = {};
  6083. var flipXLocalVideo = true;
  6084. var currentVideoWidth = null;
  6085. var currentVideoHeight = null;
  6086. var localVideoSrc = null;
  6087. function videoactive( videoelem) {
  6088. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  6089. // ignore mixedmslabela0 and v0
  6090. videoelem.show();
  6091. VideoLayout.resizeThumbnails();
  6092. var videoParent = videoelem.parent();
  6093. var parentResourceJid = null;
  6094. if (videoParent)
  6095. parentResourceJid
  6096. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  6097. // Update the large video to the last added video only if there's no
  6098. // current dominant, focused speaker or prezi playing or update it to
  6099. // the current dominant speaker.
  6100. if ((!focusedVideoInfo &&
  6101. !VideoLayout.getDominantSpeakerResourceJid() &&
  6102. !require("../prezi/Prezi").isPresentationVisible()) ||
  6103. (parentResourceJid &&
  6104. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  6105. VideoLayout.updateLargeVideo(
  6106. APP.RTC.getVideoSrc(videoelem[0]),
  6107. 1,
  6108. parentResourceJid);
  6109. }
  6110. VideoLayout.showModeratorIndicator();
  6111. }
  6112. }
  6113. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  6114. // XXX(gp) so, every call to this function is *always* preceded by a call
  6115. // to the RTC.attachMediaStream() function but that call is *not* followed
  6116. // by an update to the videoSrcToSsrc map!
  6117. //
  6118. // The above way of doing things results in video SRCs that don't correspond
  6119. // to any SSRC for a short period of time (to be more precise, for as long
  6120. // the waitForRemoteVideo takes to complete). This causes problems (see
  6121. // bellow).
  6122. //
  6123. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  6124. // a second time in here and only then update the videoSrcToSsrc map? Why
  6125. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  6126. // is called the first time? I actually do that in the lastN changed event
  6127. // handler because the "orphan" video SRC is causing troubles there. The
  6128. // purpose of this method would then be to fire the "videoactive.jingle".
  6129. //
  6130. // Food for though I guess :-)
  6131. if (selector.removed || !selector.parent().is(":visible")) {
  6132. console.warn("Media removed before had started", selector);
  6133. return;
  6134. }
  6135. if (stream.id === 'mixedmslabel') return;
  6136. if (selector[0].currentTime > 0) {
  6137. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6138. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  6139. videoactive(selector);
  6140. } else {
  6141. setTimeout(function () {
  6142. waitForRemoteVideo(selector, ssrc, stream, jid);
  6143. }, 250);
  6144. }
  6145. }
  6146. /**
  6147. * Returns an array of the video horizontal and vertical indents,
  6148. * so that if fits its parent.
  6149. *
  6150. * @return an array with 2 elements, the horizontal indent and the vertical
  6151. * indent
  6152. */
  6153. function getCameraVideoPosition(videoWidth,
  6154. videoHeight,
  6155. videoSpaceWidth,
  6156. videoSpaceHeight) {
  6157. // Parent height isn't completely calculated when we position the video in
  6158. // full screen mode and this is why we use the screen height in this case.
  6159. // Need to think it further at some point and implement it properly.
  6160. var isFullScreen = document.fullScreen ||
  6161. document.mozFullScreen ||
  6162. document.webkitIsFullScreen;
  6163. if (isFullScreen)
  6164. videoSpaceHeight = window.innerHeight;
  6165. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  6166. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  6167. return [horizontalIndent, verticalIndent];
  6168. }
  6169. /**
  6170. * Returns an array of the video horizontal and vertical indents.
  6171. * Centers horizontally and top aligns vertically.
  6172. *
  6173. * @return an array with 2 elements, the horizontal indent and the vertical
  6174. * indent
  6175. */
  6176. function getDesktopVideoPosition(videoWidth,
  6177. videoHeight,
  6178. videoSpaceWidth,
  6179. videoSpaceHeight) {
  6180. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  6181. var verticalIndent = 0;// Top aligned
  6182. return [horizontalIndent, verticalIndent];
  6183. }
  6184. /**
  6185. * Returns an array of the video dimensions, so that it covers the screen.
  6186. * It leaves no empty areas, but some parts of the video might not be visible.
  6187. *
  6188. * @return an array with 2 elements, the video width and the video height
  6189. */
  6190. function getCameraVideoSize(videoWidth,
  6191. videoHeight,
  6192. videoSpaceWidth,
  6193. videoSpaceHeight) {
  6194. if (!videoWidth)
  6195. videoWidth = currentVideoWidth;
  6196. if (!videoHeight)
  6197. videoHeight = currentVideoHeight;
  6198. var aspectRatio = videoWidth / videoHeight;
  6199. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6200. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6201. if (availableWidth / aspectRatio < videoSpaceHeight) {
  6202. availableHeight = videoSpaceHeight;
  6203. availableWidth = availableHeight * aspectRatio;
  6204. }
  6205. if (availableHeight * aspectRatio < videoSpaceWidth) {
  6206. availableWidth = videoSpaceWidth;
  6207. availableHeight = availableWidth / aspectRatio;
  6208. }
  6209. return [availableWidth, availableHeight];
  6210. }
  6211. /**
  6212. * Sets the display name for the given video span id.
  6213. */
  6214. function setDisplayName(videoSpanId, displayName, key) {
  6215. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  6216. var defaultLocalDisplayName = APP.translation.generateTranslatonHTML(
  6217. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6218. // If we already have a display name for this video.
  6219. if (nameSpan.length > 0) {
  6220. var nameSpanElement = nameSpan.get(0);
  6221. if (nameSpanElement.id === 'localDisplayName' &&
  6222. $('#localDisplayName').text() !== displayName) {
  6223. if (displayName && displayName.length > 0)
  6224. {
  6225. var meHTML = APP.translation.generateTranslatonHTML("me");
  6226. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  6227. }
  6228. else
  6229. $('#localDisplayName').html(defaultLocalDisplayName);
  6230. } else {
  6231. if (displayName && displayName.length > 0)
  6232. {
  6233. $('#' + videoSpanId + '_name').html(displayName);
  6234. }
  6235. else if (key && key.length > 0)
  6236. {
  6237. var nameHtml = APP.translation.generateTranslatonHTML(key);
  6238. $('#' + videoSpanId + '_name').html(nameHtml);
  6239. }
  6240. else
  6241. $('#' + videoSpanId + '_name').text(
  6242. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  6243. }
  6244. } else {
  6245. var editButton = null;
  6246. nameSpan = document.createElement('span');
  6247. nameSpan.className = 'displayname';
  6248. $('#' + videoSpanId)[0].appendChild(nameSpan);
  6249. if (videoSpanId === 'localVideoContainer') {
  6250. editButton = createEditDisplayNameButton();
  6251. if (displayName && displayName.length > 0) {
  6252. var meHTML = APP.translation.generateTranslatonHTML("me");
  6253. nameSpan.innerHTML = displayName + meHTML;
  6254. }
  6255. else
  6256. nameSpan.innerHTML = defaultLocalDisplayName;
  6257. }
  6258. else {
  6259. if (displayName && displayName.length > 0) {
  6260. nameSpan.innerText = displayName;
  6261. }
  6262. else
  6263. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  6264. }
  6265. if (!editButton) {
  6266. nameSpan.id = videoSpanId + '_name';
  6267. } else {
  6268. nameSpan.id = 'localDisplayName';
  6269. $('#' + videoSpanId)[0].appendChild(editButton);
  6270. //translates popover of edit button
  6271. APP.translation.translateElement($("a.displayname"));
  6272. var editableText = document.createElement('input');
  6273. editableText.className = 'displayname';
  6274. editableText.type = 'text';
  6275. editableText.id = 'editDisplayName';
  6276. if (displayName && displayName.length) {
  6277. editableText.value
  6278. = displayName;
  6279. }
  6280. var defaultNickname = APP.translation.translateString(
  6281. "defaultNickname", {name: "Jane Pink"});
  6282. editableText.setAttribute('style', 'display:none;');
  6283. editableText.setAttribute('data-18n',
  6284. '[placeholder]defaultNickname');
  6285. editableText.setAttribute("data-i18n-options",
  6286. JSON.stringify({name: "Jane Pink"}));
  6287. editableText.setAttribute("placeholder", defaultNickname);
  6288. $('#' + videoSpanId)[0].appendChild(editableText);
  6289. $('#localVideoContainer .displayname')
  6290. .bind("click", function (e) {
  6291. e.preventDefault();
  6292. e.stopPropagation();
  6293. $('#localDisplayName').hide();
  6294. $('#editDisplayName').show();
  6295. $('#editDisplayName').focus();
  6296. $('#editDisplayName').select();
  6297. $('#editDisplayName').one("focusout", function (e) {
  6298. VideoLayout.inputDisplayNameHandler(this.value);
  6299. });
  6300. $('#editDisplayName').on('keydown', function (e) {
  6301. if (e.keyCode === 13) {
  6302. e.preventDefault();
  6303. VideoLayout.inputDisplayNameHandler(this.value);
  6304. }
  6305. });
  6306. });
  6307. }
  6308. }
  6309. }
  6310. /**
  6311. * Gets the selector of video thumbnail container for the user identified by
  6312. * given <tt>userJid</tt>
  6313. * @param resourceJid user's Jid for whom we want to get the video container.
  6314. */
  6315. function getParticipantContainer(resourceJid)
  6316. {
  6317. if (!resourceJid)
  6318. return null;
  6319. if (resourceJid === APP.xmpp.myResource())
  6320. return $("#localVideoContainer");
  6321. else
  6322. return $("#participant_" + resourceJid);
  6323. }
  6324. /**
  6325. * Sets the size and position of the given video element.
  6326. *
  6327. * @param video the video element to position
  6328. * @param width the desired video width
  6329. * @param height the desired video height
  6330. * @param horizontalIndent the left and right indent
  6331. * @param verticalIndent the top and bottom indent
  6332. */
  6333. function positionVideo(video,
  6334. width,
  6335. height,
  6336. horizontalIndent,
  6337. verticalIndent) {
  6338. video.width(width);
  6339. video.height(height);
  6340. video.css({ top: verticalIndent + 'px',
  6341. bottom: verticalIndent + 'px',
  6342. left: horizontalIndent + 'px',
  6343. right: horizontalIndent + 'px'});
  6344. }
  6345. /**
  6346. * Adds the remote video menu element for the given <tt>jid</tt> in the
  6347. * given <tt>parentElement</tt>.
  6348. *
  6349. * @param jid the jid indicating the video for which we're adding a menu.
  6350. * @param parentElement the parent element where this menu will be added
  6351. */
  6352. function addRemoteVideoMenu(jid, parentElement) {
  6353. var spanElement = document.createElement('span');
  6354. spanElement.className = 'remotevideomenu';
  6355. parentElement.appendChild(spanElement);
  6356. var menuElement = document.createElement('i');
  6357. menuElement.className = 'fa fa-angle-down';
  6358. menuElement.title = 'Remote user controls';
  6359. spanElement.appendChild(menuElement);
  6360. // <ul class="popupmenu">
  6361. // <li><a href="#">Mute</a></li>
  6362. // <li><a href="#">Eject</a></li>
  6363. // </ul>
  6364. var popupmenuElement = document.createElement('ul');
  6365. popupmenuElement.className = 'popupmenu';
  6366. popupmenuElement.id
  6367. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  6368. spanElement.appendChild(popupmenuElement);
  6369. var muteMenuItem = document.createElement('li');
  6370. var muteLinkItem = document.createElement('a');
  6371. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  6372. if (!mutedAudios[jid]) {
  6373. muteLinkItem.innerHTML = mutedIndicator +
  6374. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6375. muteLinkItem.className = 'mutelink';
  6376. }
  6377. else {
  6378. muteLinkItem.innerHTML = mutedIndicator +
  6379. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6380. muteLinkItem.className = 'mutelink disabled';
  6381. }
  6382. muteLinkItem.onclick = function(){
  6383. if ($(this).attr('disabled') != undefined) {
  6384. event.preventDefault();
  6385. }
  6386. var isMute = mutedAudios[jid] == true;
  6387. APP.xmpp.setMute(jid, !isMute);
  6388. popupmenuElement.setAttribute('style', 'display:none;');
  6389. if (isMute) {
  6390. this.innerHTML = mutedIndicator +
  6391. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6392. this.className = 'mutelink disabled';
  6393. }
  6394. else {
  6395. this.innerHTML = mutedIndicator +
  6396. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6397. this.className = 'mutelink';
  6398. }
  6399. };
  6400. muteMenuItem.appendChild(muteLinkItem);
  6401. popupmenuElement.appendChild(muteMenuItem);
  6402. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  6403. var ejectMenuItem = document.createElement('li');
  6404. var ejectLinkItem = document.createElement('a');
  6405. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  6406. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  6407. ejectLinkItem.onclick = function(){
  6408. APP.xmpp.eject(jid);
  6409. popupmenuElement.setAttribute('style', 'display:none;');
  6410. };
  6411. ejectMenuItem.appendChild(ejectLinkItem);
  6412. popupmenuElement.appendChild(ejectMenuItem);
  6413. var paddingSpan = document.createElement('span');
  6414. paddingSpan.className = 'popupmenuPadding';
  6415. popupmenuElement.appendChild(paddingSpan);
  6416. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  6417. }
  6418. /**
  6419. * Removes remote video menu element from video element identified by
  6420. * given <tt>videoElementId</tt>.
  6421. *
  6422. * @param videoElementId the id of local or remote video element.
  6423. */
  6424. function removeRemoteVideoMenu(videoElementId) {
  6425. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  6426. if (menuSpan.length) {
  6427. menuSpan.remove();
  6428. }
  6429. }
  6430. /**
  6431. * Updates the data for the indicator
  6432. * @param id the id of the indicator
  6433. * @param percent the percent for connection quality
  6434. * @param object the data
  6435. */
  6436. function updateStatsIndicator(id, percent, object) {
  6437. if(VideoLayout.connectionIndicators[id])
  6438. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  6439. }
  6440. /**
  6441. * Returns an array of the video dimensions, so that it keeps it's aspect
  6442. * ratio and fits available area with it's larger dimension. This method
  6443. * ensures that whole video will be visible and can leave empty areas.
  6444. *
  6445. * @return an array with 2 elements, the video width and the video height
  6446. */
  6447. function getDesktopVideoSize(videoWidth,
  6448. videoHeight,
  6449. videoSpaceWidth,
  6450. videoSpaceHeight) {
  6451. if (!videoWidth)
  6452. videoWidth = currentVideoWidth;
  6453. if (!videoHeight)
  6454. videoHeight = currentVideoHeight;
  6455. var aspectRatio = videoWidth / videoHeight;
  6456. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6457. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6458. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  6459. if (availableWidth / aspectRatio >= videoSpaceHeight)
  6460. {
  6461. availableHeight = videoSpaceHeight;
  6462. availableWidth = availableHeight * aspectRatio;
  6463. }
  6464. if (availableHeight * aspectRatio >= videoSpaceWidth)
  6465. {
  6466. availableWidth = videoSpaceWidth;
  6467. availableHeight = availableWidth / aspectRatio;
  6468. }
  6469. return [availableWidth, availableHeight];
  6470. }
  6471. /**
  6472. * Creates the edit display name button.
  6473. *
  6474. * @returns the edit button
  6475. */
  6476. function createEditDisplayNameButton() {
  6477. var editButton = document.createElement('a');
  6478. editButton.className = 'displayname';
  6479. UIUtil.setTooltip(editButton,
  6480. "videothumbnail.editnickname",
  6481. "top");
  6482. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  6483. return editButton;
  6484. }
  6485. /**
  6486. * Creates the element indicating the moderator(owner) of the conference.
  6487. *
  6488. * @param parentElement the parent element where the owner indicator will
  6489. * be added
  6490. */
  6491. function createModeratorIndicatorElement(parentElement) {
  6492. var moderatorIndicator = document.createElement('i');
  6493. moderatorIndicator.className = 'fa fa-star';
  6494. parentElement.appendChild(moderatorIndicator);
  6495. UIUtil.setTooltip(parentElement,
  6496. "videothumbnail.moderator",
  6497. "top");
  6498. }
  6499. var VideoLayout = (function (my) {
  6500. my.connectionIndicators = {};
  6501. // By default we use camera
  6502. my.getVideoSize = getCameraVideoSize;
  6503. my.getVideoPosition = getCameraVideoPosition;
  6504. my.init = function (emitter) {
  6505. // Listen for large video size updates
  6506. document.getElementById('largeVideo')
  6507. .addEventListener('loadedmetadata', function (e) {
  6508. currentVideoWidth = this.videoWidth;
  6509. currentVideoHeight = this.videoHeight;
  6510. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6511. });
  6512. eventEmitter = emitter;
  6513. };
  6514. my.isInLastN = function(resource) {
  6515. return lastNCount < 0 // lastN is disabled, return true
  6516. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  6517. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  6518. };
  6519. my.changeLocalStream = function (stream, isMuted) {
  6520. VideoLayout.changeLocalVideo(stream, isMuted);
  6521. };
  6522. my.changeLocalAudio = function(stream, isMuted) {
  6523. if(isMuted)
  6524. APP.UI.setAudioMuted(true, true);
  6525. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  6526. document.getElementById('localAudio').autoplay = true;
  6527. document.getElementById('localAudio').volume = 0;
  6528. };
  6529. my.changeLocalVideo = function(stream, isMuted) {
  6530. // Set default display name.
  6531. setDisplayName('localVideoContainer');
  6532. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  6533. VideoLayout.connectionIndicators["localVideoContainer"]
  6534. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  6535. }
  6536. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  6537. var localVideo = null;
  6538. function localVideoClick(event) {
  6539. event.stopPropagation();
  6540. VideoLayout.handleVideoThumbClicked(
  6541. APP.RTC.getVideoSrc(localVideo),
  6542. false,
  6543. APP.xmpp.myResource());
  6544. }
  6545. $('#localVideoContainer').click(localVideoClick);
  6546. // Add hover handler
  6547. $('#localVideoContainer').hover(
  6548. function() {
  6549. VideoLayout.showDisplayName('localVideoContainer', true);
  6550. },
  6551. function() {
  6552. if (!VideoLayout.isLargeVideoVisible()
  6553. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6554. VideoLayout.showDisplayName('localVideoContainer', false);
  6555. }
  6556. );
  6557. if(isMuted)
  6558. {
  6559. APP.UI.setVideoMute(true);
  6560. return;
  6561. }
  6562. var flipX = true;
  6563. if(stream.videoType == "screen")
  6564. flipX = false;
  6565. var localVideo = document.createElement('video');
  6566. localVideo.id = 'localVideo_' +
  6567. APP.RTC.getStreamID(stream.getOriginalStream());
  6568. localVideo.autoplay = true;
  6569. localVideo.volume = 0; // is it required if audio is separated ?
  6570. localVideo.oncontextmenu = function () { return false; };
  6571. var localVideoContainer = document.getElementById('localVideoWrapper');
  6572. localVideoContainer.appendChild(localVideo);
  6573. var localVideoSelector = $('#' + localVideo.id);
  6574. // Add click handler to both video and video wrapper elements in case
  6575. // there's no video.
  6576. localVideoSelector.click(localVideoClick);
  6577. // Flip video x axis if needed
  6578. flipXLocalVideo = flipX;
  6579. if (flipX) {
  6580. localVideoSelector.addClass("flipVideoX");
  6581. }
  6582. // Attach WebRTC stream
  6583. var videoStream = APP.simulcast.getLocalVideoStream();
  6584. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  6585. // Add stream ended handler
  6586. stream.getOriginalStream().onended = function () {
  6587. localVideoContainer.removeChild(localVideo);
  6588. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  6589. };
  6590. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  6591. var myResourceJid = APP.xmpp.myResource();
  6592. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  6593. myResourceJid);
  6594. };
  6595. my.mucJoined = function () {
  6596. var myResourceJid = APP.xmpp.myResource();
  6597. if(!largeVideoState.userResourceJid)
  6598. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  6599. myResourceJid, true);
  6600. };
  6601. /**
  6602. * Adds or removes icons for not available camera and microphone.
  6603. * @param resourceJid the jid of user
  6604. * @param devices available devices
  6605. */
  6606. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  6607. if(!devices)
  6608. return;
  6609. var container = null
  6610. if(!resourceJid)
  6611. {
  6612. container = $("#localVideoContainer")[0];
  6613. }
  6614. else
  6615. {
  6616. container = $("#participant_" + resourceJid)[0];
  6617. }
  6618. if(!container)
  6619. return;
  6620. $("#" + container.id + " > .noMic").remove();
  6621. $("#" + container.id + " > .noVideo").remove();
  6622. if(!devices.audio)
  6623. {
  6624. container.appendChild(document.createElement("div")).setAttribute("class","noMic");
  6625. }
  6626. if(!devices.video)
  6627. {
  6628. container.appendChild(document.createElement("div")).setAttribute("class","noVideo");
  6629. }
  6630. if(!devices.audio && !devices.video)
  6631. {
  6632. $("#" + container.id + " > .noMic").css("background-position", "75%");
  6633. $("#" + container.id + " > .noVideo").css("background-position", "25%");
  6634. $("#" + container.id + " > .noVideo").css("background-color", "transparent");
  6635. }
  6636. }
  6637. /**
  6638. * Checks if removed video is currently displayed and tries to display
  6639. * another one instead.
  6640. * @param removedVideoSrc src stream identifier of the video.
  6641. */
  6642. my.updateRemovedVideo = function(removedVideoSrc) {
  6643. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  6644. // this is currently displayed as large
  6645. // pick the last visible video in the row
  6646. // if nobody else is left, this picks the local video
  6647. var pick
  6648. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  6649. .get(0);
  6650. if (!pick) {
  6651. console.info("Last visible video no longer exists");
  6652. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  6653. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  6654. // Try local video
  6655. console.info("Fallback to local video...");
  6656. pick = $('#remoteVideos>span>span>video').get(0);
  6657. }
  6658. }
  6659. var src = null, volume = null;
  6660. // mute if localvideo
  6661. if (pick) {
  6662. var container = pick.parentNode;
  6663. src = APP.RTC.getVideoSrc(pick);
  6664. volume = pick.volume;
  6665. } else {
  6666. console.warn("Failed to elect large video");
  6667. container = $('#remoteVideos>span[id!="mixedstream"]:visible:last').get(0);
  6668. }
  6669. var jid = null;
  6670. if(container)
  6671. {
  6672. if(container.id == "localVideoWrapper")
  6673. {
  6674. jid = APP.xmpp.myResource();
  6675. }
  6676. else
  6677. {
  6678. jid = VideoLayout.getPeerContainerResourceJid(container);
  6679. }
  6680. }
  6681. else
  6682. return;
  6683. VideoLayout.updateLargeVideo(src, volume, jid);
  6684. }
  6685. };
  6686. my.onRemoteStreamAdded = function (stream) {
  6687. var container;
  6688. var remotes = document.getElementById('remoteVideos');
  6689. if (stream.peerjid) {
  6690. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6691. container = document.getElementById(
  6692. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6693. } else {
  6694. var id = stream.getOriginalStream().id;
  6695. if (id !== 'mixedmslabel'
  6696. // FIXME: default stream is added always with new focus
  6697. // (to be investigated)
  6698. && id !== 'default') {
  6699. console.error('can not associate stream',
  6700. id,
  6701. 'with a participant');
  6702. // We don't want to add it here since it will cause troubles
  6703. return;
  6704. }
  6705. // FIXME: for the mixed ms we dont need a video -- currently
  6706. container = document.createElement('span');
  6707. container.id = 'mixedstream';
  6708. container.className = 'videocontainer';
  6709. remotes.appendChild(container);
  6710. if(!config.startAudioMuted ||
  6711. config.startAudioMuted > APP.members.size())
  6712. UIUtil.playSoundNotification('userJoined');
  6713. }
  6714. if (container) {
  6715. VideoLayout.addRemoteStreamElement( container,
  6716. stream.sid,
  6717. stream.getOriginalStream(),
  6718. stream.peerjid,
  6719. stream.ssrc);
  6720. }
  6721. }
  6722. my.getLargeVideoState = function () {
  6723. return largeVideoState;
  6724. };
  6725. /**
  6726. * Updates the large video with the given new video source.
  6727. */
  6728. my.updateLargeVideo = function(newSrc, vol, resourceJid, forceUpdate) {
  6729. console.log('hover in', newSrc, resourceJid);
  6730. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc || forceUpdate) {
  6731. $('#activeSpeaker').css('visibility', 'hidden');
  6732. // Due to the simulcast the localVideoSrc may have changed when the
  6733. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6734. // isVideoSrcDesktop methods will not function correctly.
  6735. //
  6736. // Also, again due to the simulcast, the updateLargeVideo method can
  6737. // be called multiple times almost simultaneously. Therefore, we
  6738. // store the state here and update only once.
  6739. largeVideoState.newSrc = newSrc;
  6740. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6741. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(
  6742. APP.xmpp.findJidFromResource(resourceJid));
  6743. if(largeVideoState.userResourceJid) {
  6744. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6745. } else {
  6746. largeVideoState.oldResourceJid = null;
  6747. }
  6748. largeVideoState.userResourceJid = resourceJid;
  6749. // Screen stream is already rotated
  6750. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6751. var userChanged = false;
  6752. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6753. userChanged = true;
  6754. // we want the notification to trigger even if userJid is undefined,
  6755. // or null.
  6756. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6757. largeVideoState.userResourceJid);
  6758. }
  6759. if (!largeVideoState.updateInProgress) {
  6760. largeVideoState.updateInProgress = true;
  6761. var doUpdate = function () {
  6762. Avatar.updateActiveSpeakerAvatarSrc(
  6763. APP.xmpp.findJidFromResource(
  6764. largeVideoState.userResourceJid));
  6765. if (!userChanged && largeVideoState.preload &&
  6766. largeVideoState.preload !== null &&
  6767. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  6768. {
  6769. console.info('Switching to preloaded video');
  6770. var attributes = $('#largeVideo').prop("attributes");
  6771. // loop through largeVideo attributes and apply them on
  6772. // preload.
  6773. $.each(attributes, function () {
  6774. if (this.name !== 'id' && this.name !== 'src') {
  6775. largeVideoState.preload.attr(this.name, this.value);
  6776. }
  6777. });
  6778. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  6779. $('#largeVideo').attr('id', 'previousLargeVideo');
  6780. largeVideoState.preload.attr('id', 'largeVideo');
  6781. $('#previousLargeVideo').remove();
  6782. largeVideoState.preload.on('loadedmetadata', function (e) {
  6783. currentVideoWidth = this.videoWidth;
  6784. currentVideoHeight = this.videoHeight;
  6785. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6786. });
  6787. largeVideoState.preload = null;
  6788. largeVideoState.preload_ssrc = 0;
  6789. } else {
  6790. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6791. }
  6792. var videoTransform = document.getElementById('largeVideo')
  6793. .style.webkitTransform;
  6794. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6795. document.getElementById('largeVideo').style.webkitTransform
  6796. = "scaleX(-1)";
  6797. }
  6798. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6799. document.getElementById('largeVideo').style.webkitTransform
  6800. = "none";
  6801. }
  6802. // Change the way we'll be measuring and positioning large video
  6803. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6804. ? getDesktopVideoSize
  6805. : getCameraVideoSize;
  6806. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6807. ? getDesktopVideoPosition
  6808. : getCameraVideoPosition;
  6809. // Only if the large video is currently visible.
  6810. // Disable previous dominant speaker video.
  6811. if (largeVideoState.oldResourceJid) {
  6812. VideoLayout.enableDominantSpeaker(
  6813. largeVideoState.oldResourceJid,
  6814. false);
  6815. }
  6816. // Enable new dominant speaker in the remote videos section.
  6817. if (largeVideoState.userResourceJid) {
  6818. VideoLayout.enableDominantSpeaker(
  6819. largeVideoState.userResourceJid,
  6820. true);
  6821. }
  6822. if (userChanged && largeVideoState.isVisible) {
  6823. // using "this" should be ok because we're called
  6824. // from within the fadeOut event.
  6825. $(this).fadeIn(300);
  6826. }
  6827. if(userChanged) {
  6828. Avatar.showUserAvatar(
  6829. APP.xmpp.findJidFromResource(
  6830. largeVideoState.oldResourceJid));
  6831. }
  6832. largeVideoState.updateInProgress = false;
  6833. };
  6834. if (userChanged) {
  6835. $('#largeVideo').fadeOut(300, doUpdate);
  6836. } else {
  6837. doUpdate();
  6838. }
  6839. }
  6840. } else {
  6841. Avatar.showUserAvatar(
  6842. APP.xmpp.findJidFromResource(
  6843. largeVideoState.userResourceJid));
  6844. }
  6845. };
  6846. my.handleVideoThumbClicked = function(videoSrc,
  6847. noPinnedEndpointChangedEvent,
  6848. resourceJid) {
  6849. // Restore style for previously focused video
  6850. var oldContainer = null;
  6851. if(focusedVideoInfo) {
  6852. var focusResourceJid = focusedVideoInfo.resourceJid;
  6853. oldContainer = getParticipantContainer(focusResourceJid);
  6854. }
  6855. if (oldContainer) {
  6856. oldContainer.removeClass("videoContainerFocused");
  6857. }
  6858. // Unlock current focused.
  6859. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6860. {
  6861. focusedVideoInfo = null;
  6862. var dominantSpeakerVideo = null;
  6863. // Enable the currently set dominant speaker.
  6864. if (currentDominantSpeaker) {
  6865. dominantSpeakerVideo
  6866. = $('#participant_' + currentDominantSpeaker + '>video')
  6867. .get(0);
  6868. if (dominantSpeakerVideo) {
  6869. VideoLayout.updateLargeVideo(
  6870. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6871. 1,
  6872. currentDominantSpeaker);
  6873. }
  6874. }
  6875. if (!noPinnedEndpointChangedEvent) {
  6876. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6877. }
  6878. return;
  6879. }
  6880. // Lock new video
  6881. focusedVideoInfo = {
  6882. src: videoSrc,
  6883. resourceJid: resourceJid
  6884. };
  6885. // Update focused/pinned interface.
  6886. if (resourceJid)
  6887. {
  6888. var container = getParticipantContainer(resourceJid);
  6889. container.addClass("videoContainerFocused");
  6890. if (!noPinnedEndpointChangedEvent) {
  6891. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6892. }
  6893. }
  6894. if ($('#largeVideo').attr('src') === videoSrc &&
  6895. VideoLayout.isLargeVideoOnTop()) {
  6896. return;
  6897. }
  6898. // Triggers a "video.selected" event. The "false" parameter indicates
  6899. // this isn't a prezi.
  6900. $(document).trigger("video.selected", [false]);
  6901. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6902. $('audio').each(function (idx, el) {
  6903. if (el.id.indexOf('mixedmslabel') !== -1) {
  6904. el.volume = 0;
  6905. el.volume = 1;
  6906. }
  6907. });
  6908. };
  6909. /**
  6910. * Positions the large video.
  6911. *
  6912. * @param videoWidth the stream video width
  6913. * @param videoHeight the stream video height
  6914. */
  6915. my.positionLarge = function (videoWidth, videoHeight) {
  6916. var videoSpaceWidth = $('#videospace').width();
  6917. var videoSpaceHeight = window.innerHeight;
  6918. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6919. videoHeight,
  6920. videoSpaceWidth,
  6921. videoSpaceHeight);
  6922. var largeVideoWidth = videoSize[0];
  6923. var largeVideoHeight = videoSize[1];
  6924. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6925. largeVideoHeight,
  6926. videoSpaceWidth,
  6927. videoSpaceHeight);
  6928. var horizontalIndent = videoPosition[0];
  6929. var verticalIndent = videoPosition[1];
  6930. positionVideo($('#largeVideo'),
  6931. largeVideoWidth,
  6932. largeVideoHeight,
  6933. horizontalIndent, verticalIndent);
  6934. };
  6935. /**
  6936. * Shows/hides the large video.
  6937. */
  6938. my.setLargeVideoVisible = function(isVisible) {
  6939. var resourceJid = largeVideoState.userResourceJid;
  6940. if (isVisible) {
  6941. $('#largeVideo').css({visibility: 'visible'});
  6942. $('.watermark').css({visibility: 'visible'});
  6943. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6944. }
  6945. else {
  6946. $('#largeVideo').css({visibility: 'hidden'});
  6947. $('#activeSpeaker').css('visibility', 'hidden');
  6948. $('.watermark').css({visibility: 'hidden'});
  6949. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6950. if(focusedVideoInfo) {
  6951. var focusResourceJid = focusedVideoInfo.resourceJid;
  6952. var oldContainer = getParticipantContainer(focusResourceJid);
  6953. if (oldContainer && oldContainer.length > 0) {
  6954. oldContainer.removeClass("videoContainerFocused");
  6955. }
  6956. focusedVideoInfo = null;
  6957. if(focusResourceJid) {
  6958. Avatar.showUserAvatar(
  6959. APP.xmpp.findJidFromResource(focusResourceJid));
  6960. }
  6961. }
  6962. }
  6963. };
  6964. /**
  6965. * Indicates if the large video is currently visible.
  6966. *
  6967. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6968. */
  6969. my.isLargeVideoVisible = function() {
  6970. return $('#largeVideo').is(':visible');
  6971. };
  6972. my.isLargeVideoOnTop = function () {
  6973. var Etherpad = require("../etherpad/Etherpad");
  6974. var Prezi = require("../prezi/Prezi");
  6975. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6976. };
  6977. /**
  6978. * Checks if container for participant identified by given peerJid exists
  6979. * in the document and creates it eventually.
  6980. *
  6981. * @param peerJid peer Jid to check.
  6982. * @param userId user email or id for setting the avatar
  6983. *
  6984. * @return Returns <tt>true</tt> if the peer container exists,
  6985. * <tt>false</tt> - otherwise
  6986. */
  6987. my.ensurePeerContainerExists = function(peerJid, userId) {
  6988. ContactList.ensureAddContact(peerJid, userId);
  6989. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6990. var videoSpanId = 'participant_' + resourceJid;
  6991. if (!$('#' + videoSpanId).length) {
  6992. var container =
  6993. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6994. Avatar.setUserAvatar(peerJid, userId);
  6995. // Set default display name.
  6996. setDisplayName(videoSpanId);
  6997. VideoLayout.connectionIndicators[videoSpanId] =
  6998. new ConnectionIndicator(container, peerJid, VideoLayout);
  6999. var nickfield = document.createElement('span');
  7000. nickfield.className = "nick";
  7001. nickfield.appendChild(document.createTextNode(resourceJid));
  7002. container.appendChild(nickfield);
  7003. // In case this is not currently in the last n we don't show it.
  7004. if (localLastNCount
  7005. && localLastNCount > 0
  7006. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  7007. showPeerContainer(resourceJid, 'hide');
  7008. }
  7009. else
  7010. VideoLayout.resizeThumbnails();
  7011. }
  7012. };
  7013. my.addRemoteVideoContainer = function(peerJid, spanId) {
  7014. var container = document.createElement('span');
  7015. container.id = spanId;
  7016. container.className = 'videocontainer';
  7017. var remotes = document.getElementById('remoteVideos');
  7018. remotes.appendChild(container);
  7019. // If the peerJid is null then this video span couldn't be directly
  7020. // associated with a participant (this could happen in the case of prezi).
  7021. if (APP.xmpp.isModerator() && peerJid !== null)
  7022. addRemoteVideoMenu(peerJid, container);
  7023. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  7024. return container;
  7025. };
  7026. /**
  7027. * Creates an audio or video stream element.
  7028. */
  7029. my.createStreamElement = function (sid, stream) {
  7030. var isVideo = stream.getVideoTracks().length > 0;
  7031. var element = isVideo
  7032. ? document.createElement('video')
  7033. : document.createElement('audio');
  7034. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  7035. + sid + '_' + APP.RTC.getStreamID(stream);
  7036. element.id = id;
  7037. element.autoplay = true;
  7038. element.oncontextmenu = function () { return false; };
  7039. return element;
  7040. };
  7041. my.addRemoteStreamElement
  7042. = function (container, sid, stream, peerJid, thessrc) {
  7043. var newElementId = null;
  7044. var isVideo = stream.getVideoTracks().length > 0;
  7045. if (container) {
  7046. var streamElement = VideoLayout.createStreamElement(sid, stream);
  7047. newElementId = streamElement.id;
  7048. container.appendChild(streamElement);
  7049. var sel = $('#' + newElementId);
  7050. sel.hide();
  7051. // If the container is currently visible we attach the stream.
  7052. if (!isVideo
  7053. || (container.offsetParent !== null && isVideo)) {
  7054. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  7055. APP.RTC.attachMediaStream(sel, videoStream);
  7056. if (isVideo)
  7057. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  7058. }
  7059. stream.onended = function () {
  7060. console.log('stream ended', this);
  7061. VideoLayout.removeRemoteStreamElement(
  7062. stream, isVideo, container, newElementId);
  7063. // NOTE(gp) it seems that under certain circumstances, the
  7064. // onended event is not fired and thus the contact list is not
  7065. // updated.
  7066. //
  7067. // The onended event of a stream should be fired when the SSRCs
  7068. // corresponding to that stream are removed from the SDP; but
  7069. // this doesn't seem to always be the case, resulting in ghost
  7070. // contacts.
  7071. //
  7072. // In an attempt to fix the ghost contacts problem, I'm moving
  7073. // the removeContact() method call in app.js, inside the
  7074. // 'muc.left' event handler.
  7075. //if (peerJid)
  7076. // ContactList.removeContact(peerJid);
  7077. };
  7078. // Add click handler.
  7079. container.onclick = function (event) {
  7080. /*
  7081. * FIXME It turns out that videoThumb may not exist (if there is
  7082. * no actual video).
  7083. */
  7084. var videoThumb = $('#' + container.id + '>video').get(0);
  7085. if (videoThumb) {
  7086. VideoLayout.handleVideoThumbClicked(
  7087. APP.RTC.getVideoSrc(videoThumb),
  7088. false,
  7089. Strophe.getResourceFromJid(peerJid));
  7090. }
  7091. event.stopPropagation();
  7092. event.preventDefault();
  7093. return false;
  7094. };
  7095. // Add hover handler
  7096. $(container).hover(
  7097. function() {
  7098. VideoLayout.showDisplayName(container.id, true);
  7099. },
  7100. function() {
  7101. var videoSrc = null;
  7102. if ($('#' + container.id + '>video')
  7103. && $('#' + container.id + '>video').length > 0) {
  7104. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  7105. }
  7106. // If the video has been "pinned" by the user we want to
  7107. // keep the display name on place.
  7108. if (!VideoLayout.isLargeVideoVisible()
  7109. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  7110. VideoLayout.showDisplayName(container.id, false);
  7111. }
  7112. );
  7113. }
  7114. return newElementId;
  7115. };
  7116. /**
  7117. * Removes the remote stream element corresponding to the given stream and
  7118. * parent container.
  7119. *
  7120. * @param stream the stream
  7121. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  7122. * @param container
  7123. */
  7124. my.removeRemoteStreamElement = function (stream, isVideo, container, id) {
  7125. if (!container)
  7126. return;
  7127. var select = null;
  7128. var removedVideoSrc = null;
  7129. if (isVideo) {
  7130. select = $('#' + id);
  7131. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  7132. }
  7133. else
  7134. select = $('#' + container.id + '>audio');
  7135. // Mark video as removed to cancel waiting loop(if video is removed
  7136. // before has started)
  7137. select.removed = true;
  7138. select.remove();
  7139. var audioCount = $('#' + container.id + '>audio').length;
  7140. var videoCount = $('#' + container.id + '>video').length;
  7141. if (!audioCount && !videoCount) {
  7142. console.log("Remove whole user", container.id);
  7143. if(VideoLayout.connectionIndicators[container.id])
  7144. VideoLayout.connectionIndicators[container.id].remove();
  7145. // Remove whole container
  7146. container.remove();
  7147. if(!config.startAudioMuted ||
  7148. config.startAudioMuted > APP.members.size())
  7149. UIUtil.playSoundNotification('userLeft');
  7150. VideoLayout.resizeThumbnails();
  7151. }
  7152. if (removedVideoSrc)
  7153. VideoLayout.updateRemovedVideo(removedVideoSrc);
  7154. };
  7155. /**
  7156. * Show/hide peer container for the given resourceJid.
  7157. */
  7158. function showPeerContainer(resourceJid, state) {
  7159. var peerContainer = $('#participant_' + resourceJid);
  7160. if (!peerContainer)
  7161. return;
  7162. var isHide = state === 'hide';
  7163. var resizeThumbnails = false;
  7164. if (!isHide) {
  7165. if (!peerContainer.is(':visible')) {
  7166. resizeThumbnails = true;
  7167. peerContainer.show();
  7168. }
  7169. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7170. if (state == 'show')
  7171. {
  7172. // peerContainer.css('-webkit-filter', '');
  7173. Avatar.showUserAvatar(jid, false);
  7174. }
  7175. else // if (state == 'avatar')
  7176. {
  7177. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  7178. Avatar.showUserAvatar(jid, true);
  7179. }
  7180. }
  7181. else if (peerContainer.is(':visible') && isHide)
  7182. {
  7183. resizeThumbnails = true;
  7184. peerContainer.hide();
  7185. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  7186. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  7187. }
  7188. if (resizeThumbnails) {
  7189. VideoLayout.resizeThumbnails();
  7190. }
  7191. // We want to be able to pin a participant from the contact list, even
  7192. // if he's not in the lastN set!
  7193. // ContactList.setClickable(resourceJid, !isHide);
  7194. };
  7195. my.inputDisplayNameHandler = function (name) {
  7196. NicknameHandler.setNickname(name);
  7197. if (!$('#localDisplayName').is(":visible")) {
  7198. if (NicknameHandler.getNickname())
  7199. {
  7200. var meHTML = APP.translation.generateTranslatonHTML("me");
  7201. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  7202. }
  7203. else
  7204. {
  7205. var defaultHTML = APP.translation.generateTranslatonHTML(
  7206. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7207. $('#localDisplayName')
  7208. .html(defaultHTML);
  7209. }
  7210. $('#localDisplayName').show();
  7211. }
  7212. $('#editDisplayName').hide();
  7213. };
  7214. /**
  7215. * Shows/hides the display name on the remote video.
  7216. * @param videoSpanId the identifier of the video span element
  7217. * @param isShow indicates if the display name should be shown or hidden
  7218. */
  7219. my.showDisplayName = function(videoSpanId, isShow) {
  7220. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  7221. if (isShow) {
  7222. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  7223. nameSpan.setAttribute("style", "display:inline-block;");
  7224. }
  7225. else {
  7226. if (nameSpan)
  7227. nameSpan.setAttribute("style", "display:none;");
  7228. }
  7229. };
  7230. /**
  7231. * Shows the presence status message for the given video.
  7232. */
  7233. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  7234. if (!$('#' + videoSpanId).length) {
  7235. // No container
  7236. return;
  7237. }
  7238. var statusSpan = $('#' + videoSpanId + '>span.status');
  7239. if (!statusSpan.length) {
  7240. //Add status span
  7241. statusSpan = document.createElement('span');
  7242. statusSpan.className = 'status';
  7243. statusSpan.id = videoSpanId + '_status';
  7244. $('#' + videoSpanId)[0].appendChild(statusSpan);
  7245. statusSpan = $('#' + videoSpanId + '>span.status');
  7246. }
  7247. // Display status
  7248. if (statusMsg && statusMsg.length) {
  7249. $('#' + videoSpanId + '_status').text(statusMsg);
  7250. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  7251. }
  7252. else {
  7253. // Hide
  7254. statusSpan.get(0).setAttribute("style", "display:none;");
  7255. }
  7256. };
  7257. /**
  7258. * Shows a visual indicator for the moderator of the conference.
  7259. */
  7260. my.showModeratorIndicator = function () {
  7261. var isModerator = APP.xmpp.isModerator();
  7262. if (isModerator) {
  7263. var indicatorSpan = $('#localVideoContainer .focusindicator');
  7264. if (indicatorSpan.children().length === 0)
  7265. {
  7266. createModeratorIndicatorElement(indicatorSpan[0]);
  7267. //translates text in focus indicator
  7268. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  7269. }
  7270. }
  7271. var members = APP.xmpp.getMembers();
  7272. Object.keys(members).forEach(function (jid) {
  7273. if (Strophe.getResourceFromJid(jid) === 'focus') {
  7274. // Skip server side focus
  7275. return;
  7276. }
  7277. var resourceJid = Strophe.getResourceFromJid(jid);
  7278. var videoSpanId = 'participant_' + resourceJid;
  7279. var videoContainer = document.getElementById(videoSpanId);
  7280. if (!videoContainer) {
  7281. console.error("No video container for " + jid);
  7282. return;
  7283. }
  7284. var member = members[jid];
  7285. if (member.role === 'moderator') {
  7286. // Remove menu if peer is moderator
  7287. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  7288. if (menuSpan.length) {
  7289. removeRemoteVideoMenu(videoSpanId);
  7290. }
  7291. // Show moderator indicator
  7292. var indicatorSpan
  7293. = $('#' + videoSpanId + ' .focusindicator');
  7294. if (!indicatorSpan || indicatorSpan.length === 0) {
  7295. indicatorSpan = document.createElement('span');
  7296. indicatorSpan.className = 'focusindicator';
  7297. videoContainer.appendChild(indicatorSpan);
  7298. createModeratorIndicatorElement(indicatorSpan);
  7299. //translates text in focus indicators
  7300. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  7301. }
  7302. } else if (isModerator) {
  7303. // We are moderator, but user is not - add menu
  7304. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  7305. addRemoteVideoMenu(
  7306. jid,
  7307. document.getElementById('participant_' + resourceJid));
  7308. }
  7309. }
  7310. });
  7311. };
  7312. /**
  7313. * Shows video muted indicator over small videos.
  7314. */
  7315. my.showVideoIndicator = function(videoSpanId, isMuted) {
  7316. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  7317. if (isMuted === 'false') {
  7318. if (videoMutedSpan.length > 0) {
  7319. videoMutedSpan.remove();
  7320. }
  7321. }
  7322. else {
  7323. if(videoMutedSpan.length == 0) {
  7324. videoMutedSpan = document.createElement('span');
  7325. videoMutedSpan.className = 'videoMuted';
  7326. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  7327. var mutedIndicator = document.createElement('i');
  7328. mutedIndicator.className = 'icon-camera-disabled';
  7329. UIUtil.setTooltip(mutedIndicator,
  7330. "videothumbnail.videomute",
  7331. "top");
  7332. videoMutedSpan.appendChild(mutedIndicator);
  7333. //translate texts for muted indicator
  7334. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  7335. }
  7336. VideoLayout.updateMutePosition(videoSpanId);
  7337. }
  7338. };
  7339. my.updateMutePosition = function (videoSpanId) {
  7340. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  7341. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  7342. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  7343. if(connectionIndicator.length > 0
  7344. && connectionIndicator[0].style.display != "none") {
  7345. audioMutedSpan.css({right: "23px"});
  7346. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  7347. }
  7348. else
  7349. {
  7350. audioMutedSpan.css({right: "0px"});
  7351. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  7352. }
  7353. }
  7354. /**
  7355. * Shows audio muted indicator over small videos.
  7356. * @param {string} isMuted
  7357. */
  7358. my.showAudioIndicator = function(videoSpanId, isMuted) {
  7359. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  7360. if (isMuted === 'false') {
  7361. if (audioMutedSpan.length > 0) {
  7362. audioMutedSpan.popover('hide');
  7363. audioMutedSpan.remove();
  7364. }
  7365. }
  7366. else {
  7367. if(audioMutedSpan.length == 0 ) {
  7368. audioMutedSpan = document.createElement('span');
  7369. audioMutedSpan.className = 'audioMuted';
  7370. UIUtil.setTooltip(audioMutedSpan,
  7371. "videothumbnail.mute",
  7372. "top");
  7373. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  7374. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  7375. var mutedIndicator = document.createElement('i');
  7376. mutedIndicator.className = 'icon-mic-disabled';
  7377. audioMutedSpan.appendChild(mutedIndicator);
  7378. }
  7379. VideoLayout.updateMutePosition(videoSpanId);
  7380. }
  7381. };
  7382. /*
  7383. * Shows or hides the audio muted indicator over the local thumbnail video.
  7384. * @param {boolean} isMuted
  7385. */
  7386. my.showLocalAudioIndicator = function(isMuted) {
  7387. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  7388. };
  7389. /**
  7390. * Resizes the large video container.
  7391. */
  7392. my.resizeLargeVideoContainer = function () {
  7393. Chat.resizeChat();
  7394. var availableHeight = window.innerHeight;
  7395. var availableWidth = UIUtil.getAvailableVideoWidth();
  7396. if (availableWidth < 0 || availableHeight < 0) return;
  7397. $('#videospace').width(availableWidth);
  7398. $('#videospace').height(availableHeight);
  7399. $('#largeVideoContainer').width(availableWidth);
  7400. $('#largeVideoContainer').height(availableHeight);
  7401. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7402. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7403. $('#activeSpeaker').css('top', top);
  7404. VideoLayout.resizeThumbnails();
  7405. };
  7406. /**
  7407. * Resizes thumbnails.
  7408. */
  7409. my.resizeThumbnails = function() {
  7410. var videoSpaceWidth = $('#remoteVideos').width();
  7411. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  7412. var width = thumbnailSize[0];
  7413. var height = thumbnailSize[1];
  7414. // size videos so that while keeping AR and max height, we have a
  7415. // nice fit
  7416. $('#remoteVideos').height(height);
  7417. $('#remoteVideos>span').width(width);
  7418. $('#remoteVideos>span').height(height);
  7419. $('.userAvatar').css('left', (width - height) / 2);
  7420. $(document).trigger("remotevideo.resized", [width, height]);
  7421. };
  7422. /**
  7423. * Enables the dominant speaker UI.
  7424. *
  7425. * @param resourceJid the jid indicating the video element to
  7426. * activate/deactivate
  7427. * @param isEnable indicates if the dominant speaker should be enabled or
  7428. * disabled
  7429. */
  7430. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  7431. var videoSpanId = null;
  7432. var videoContainerId = null;
  7433. if (resourceJid
  7434. === APP.xmpp.myResource()) {
  7435. videoSpanId = 'localVideoWrapper';
  7436. videoContainerId = 'localVideoContainer';
  7437. }
  7438. else {
  7439. videoSpanId = 'participant_' + resourceJid;
  7440. videoContainerId = videoSpanId;
  7441. }
  7442. var displayName = resourceJid;
  7443. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  7444. if (nameSpan.length > 0)
  7445. displayName = nameSpan.html();
  7446. console.log("UI enable dominant speaker",
  7447. displayName,
  7448. resourceJid,
  7449. isEnable);
  7450. videoSpan = document.getElementById(videoContainerId);
  7451. if (!videoSpan) {
  7452. return;
  7453. }
  7454. var video = $('#' + videoSpanId + '>video');
  7455. if (video && video.length > 0) {
  7456. if (isEnable) {
  7457. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  7458. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  7459. if (!videoSpan.classList.contains("dominantspeaker"))
  7460. videoSpan.classList.add("dominantspeaker");
  7461. }
  7462. else {
  7463. VideoLayout.showDisplayName(videoContainerId, false);
  7464. if (videoSpan.classList.contains("dominantspeaker"))
  7465. videoSpan.classList.remove("dominantspeaker");
  7466. }
  7467. }
  7468. Avatar.showUserAvatar(
  7469. APP.xmpp.findJidFromResource(resourceJid));
  7470. };
  7471. /**
  7472. * Calculates the thumbnail size.
  7473. *
  7474. * @param videoSpaceWidth the width of the video space
  7475. */
  7476. my.calculateThumbnailSize = function (videoSpaceWidth) {
  7477. // Calculate the available height, which is the inner window height minus
  7478. // 39px for the header minus 2px for the delimiter lines on the top and
  7479. // bottom of the large video, minus the 36px space inside the remoteVideos
  7480. // container used for highlighting shadow.
  7481. var availableHeight = 100;
  7482. var numvids = $('#remoteVideos>span:visible').length;
  7483. if (localLastNCount && localLastNCount > 0) {
  7484. numvids = Math.min(localLastNCount + 1, numvids);
  7485. }
  7486. // Remove the 3px borders arround videos and border around the remote
  7487. // videos area and the 4 pixels between the local video and the others
  7488. //TODO: Find out where the 4 pixels come from and remove them
  7489. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  7490. var availableWidth = availableWinWidth / numvids;
  7491. var aspectRatio = 16.0 / 9.0;
  7492. var maxHeight = Math.min(160, availableHeight);
  7493. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  7494. if (availableHeight < availableWidth / aspectRatio) {
  7495. availableWidth = Math.floor(availableHeight * aspectRatio);
  7496. }
  7497. return [availableWidth, availableHeight];
  7498. };
  7499. /**
  7500. * Updates the remote video menu.
  7501. *
  7502. * @param jid the jid indicating the video for which we're adding a menu.
  7503. * @param isMuted indicates the current mute state
  7504. */
  7505. my.updateRemoteVideoMenu = function(jid, isMuted) {
  7506. var muteMenuItem
  7507. = $('#remote_popupmenu_'
  7508. + Strophe.getResourceFromJid(jid)
  7509. + '>li>a.mutelink');
  7510. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  7511. if (muteMenuItem.length) {
  7512. var muteLink = muteMenuItem.get(0);
  7513. if (isMuted === 'true') {
  7514. muteLink.innerHTML = mutedIndicator + ' Muted';
  7515. muteLink.className = 'mutelink disabled';
  7516. }
  7517. else {
  7518. muteLink.innerHTML = mutedIndicator + ' Mute';
  7519. muteLink.className = 'mutelink';
  7520. }
  7521. }
  7522. };
  7523. /**
  7524. * Returns the current dominant speaker resource jid.
  7525. */
  7526. my.getDominantSpeakerResourceJid = function () {
  7527. return currentDominantSpeaker;
  7528. };
  7529. /**
  7530. * Returns the corresponding resource jid to the given peer container
  7531. * DOM element.
  7532. *
  7533. * @return the corresponding resource jid to the given peer container
  7534. * DOM element
  7535. */
  7536. my.getPeerContainerResourceJid = function (containerElement) {
  7537. var i = containerElement.id.indexOf('participant_');
  7538. if (i >= 0)
  7539. return containerElement.id.substring(i + 12);
  7540. };
  7541. /**
  7542. * On contact list item clicked.
  7543. */
  7544. $(ContactList).bind('contactclicked', function(event, jid) {
  7545. if (!jid) {
  7546. return;
  7547. }
  7548. var resource = Strophe.getResourceFromJid(jid);
  7549. var videoContainer = $("#participant_" + resource);
  7550. if (videoContainer.length > 0) {
  7551. var videoThumb = $('video', videoContainer).get(0);
  7552. // It is not always the case that a videoThumb exists (if there is
  7553. // no actual video).
  7554. if (videoThumb) {
  7555. if (videoThumb.src && videoThumb.src != '') {
  7556. // We have a video src, great! Let's update the large video
  7557. // now.
  7558. VideoLayout.handleVideoThumbClicked(
  7559. videoThumb.src,
  7560. false,
  7561. Strophe.getResourceFromJid(jid));
  7562. } else {
  7563. // If we don't have a video src for jid, there's absolutely
  7564. // no point in calling handleVideoThumbClicked; Quite
  7565. // simply, it won't work because it needs an src to attach
  7566. // to the large video.
  7567. //
  7568. // Instead, we trigger the pinned endpoint changed event to
  7569. // let the bridge adjust its lastN set for myjid and store
  7570. // the pinned user in the lastNPickupJid variable to be
  7571. // picked up later by the lastN changed event handler.
  7572. lastNPickupJid = jid;
  7573. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  7574. Strophe.getResourceFromJid(jid));
  7575. }
  7576. } else if (jid == APP.xmpp.myJid()) {
  7577. $("#localVideoContainer").click();
  7578. }
  7579. }
  7580. });
  7581. /**
  7582. * On audio muted event.
  7583. */
  7584. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  7585. /*
  7586. // FIXME: but focus can not mute in this case ? - check
  7587. if (jid === xmpp.myJid()) {
  7588. // The local mute indicator is controlled locally
  7589. return;
  7590. }*/
  7591. var videoSpanId = null;
  7592. if (jid === APP.xmpp.myJid()) {
  7593. videoSpanId = 'localVideoContainer';
  7594. } else {
  7595. VideoLayout.ensurePeerContainerExists(jid);
  7596. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7597. }
  7598. mutedAudios[jid] = isMuted;
  7599. if (APP.xmpp.isModerator()) {
  7600. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  7601. }
  7602. if (videoSpanId)
  7603. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  7604. });
  7605. /**
  7606. * On video muted event.
  7607. */
  7608. $(document).bind('videomuted.muc', function (event, jid, value) {
  7609. var isMuted = (value === "true");
  7610. if(jid !== APP.xmpp.myJid() && !APP.RTC.muteRemoteVideoStream(jid, isMuted))
  7611. return;
  7612. Avatar.showUserAvatar(jid, isMuted);
  7613. var videoSpanId = null;
  7614. if (jid === APP.xmpp.myJid()) {
  7615. videoSpanId = 'localVideoContainer';
  7616. } else {
  7617. VideoLayout.ensurePeerContainerExists(jid);
  7618. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7619. }
  7620. if (videoSpanId)
  7621. VideoLayout.showVideoIndicator(videoSpanId, value);
  7622. });
  7623. /**
  7624. * Display name changed.
  7625. */
  7626. my.onDisplayNameChanged =
  7627. function (jid, displayName, status) {
  7628. if (jid === 'localVideoContainer'
  7629. || jid === APP.xmpp.myJid()) {
  7630. setDisplayName('localVideoContainer',
  7631. displayName);
  7632. } else {
  7633. VideoLayout.ensurePeerContainerExists(jid);
  7634. setDisplayName(
  7635. 'participant_' + Strophe.getResourceFromJid(jid),
  7636. displayName,
  7637. status);
  7638. }
  7639. };
  7640. /**
  7641. * On dominant speaker changed event.
  7642. */
  7643. my.onDominantSpeakerChanged = function (resourceJid) {
  7644. // We ignore local user events.
  7645. if (resourceJid
  7646. === APP.xmpp.myResource())
  7647. return;
  7648. var members = APP.xmpp.getMembers();
  7649. // Update the current dominant speaker.
  7650. if (resourceJid !== currentDominantSpeaker) {
  7651. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  7652. newSpeakerVideoSpanId = "participant_" + resourceJid;
  7653. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  7654. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  7655. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  7656. !members[currentJID].displayName)) {
  7657. setDisplayName(oldSpeakerVideoSpanId, null);
  7658. }
  7659. if(resourceJid && (!members || !members[newJID] ||
  7660. !members[newJID].displayName)) {
  7661. setDisplayName(newSpeakerVideoSpanId, null,
  7662. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  7663. }
  7664. currentDominantSpeaker = resourceJid;
  7665. } else {
  7666. return;
  7667. }
  7668. // Obtain container for new dominant speaker.
  7669. var container = document.getElementById(
  7670. 'participant_' + resourceJid);
  7671. // Local video will not have container found, but that's ok
  7672. // since we don't want to switch to local video.
  7673. if (container && !focusedVideoInfo)
  7674. {
  7675. var video = container.getElementsByTagName("video");
  7676. // Update the large video if the video source is already available,
  7677. // otherwise wait for the "videoactive.jingle" event.
  7678. if (video.length && video[0].currentTime > 0)
  7679. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  7680. }
  7681. };
  7682. /**
  7683. * On last N change event.
  7684. *
  7685. * @param lastNEndpoints the list of last N endpoints
  7686. * @param endpointsEnteringLastN the list currently entering last N
  7687. * endpoints
  7688. */
  7689. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7690. endpointsEnteringLastN,
  7691. stream) {
  7692. if (lastNCount !== lastNEndpoints.length)
  7693. lastNCount = lastNEndpoints.length;
  7694. lastNEndpointsCache = lastNEndpoints;
  7695. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7696. //
  7697. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7698. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7699. // so E sees them. C is only in E's local LastN set.
  7700. //
  7701. // If F starts talking and LastN = 3, then E should see thumbnails for
  7702. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7703. // enters E's local LastN ejecting C.
  7704. // Increase the local LastN set size, if necessary.
  7705. if (lastNCount > localLastNCount) {
  7706. localLastNCount = lastNCount;
  7707. }
  7708. // Update the local LastN set preserving the order in which the
  7709. // endpoints appeared in the LastN/local LastN set.
  7710. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7711. for (var i = 0; i < localLastNSet.length; i++) {
  7712. if (nextLocalLastNSet.length >= localLastNCount) {
  7713. break;
  7714. }
  7715. var resourceJid = localLastNSet[i];
  7716. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7717. nextLocalLastNSet.push(resourceJid);
  7718. }
  7719. }
  7720. localLastNSet = nextLocalLastNSet;
  7721. var updateLargeVideo = false;
  7722. // Handle LastN/local LastN changes.
  7723. $('#remoteVideos>span').each(function( index, element ) {
  7724. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7725. var isReceived = true;
  7726. if (resourceJid
  7727. && lastNEndpoints.indexOf(resourceJid) < 0
  7728. && localLastNSet.indexOf(resourceJid) < 0) {
  7729. console.log("Remove from last N", resourceJid);
  7730. showPeerContainer(resourceJid, 'hide');
  7731. isReceived = false;
  7732. } else if (resourceJid
  7733. && $('#participant_' + resourceJid).is(':visible')
  7734. && lastNEndpoints.indexOf(resourceJid) < 0
  7735. && localLastNSet.indexOf(resourceJid) >= 0) {
  7736. showPeerContainer(resourceJid, 'avatar');
  7737. isReceived = false;
  7738. }
  7739. if (!isReceived) {
  7740. // resourceJid has dropped out of the server side lastN set, so
  7741. // it is no longer being received. If resourceJid was being
  7742. // displayed in the large video we have to switch to another
  7743. // user.
  7744. var largeVideoResource = largeVideoState.userResourceJid;
  7745. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7746. updateLargeVideo = true;
  7747. }
  7748. }
  7749. });
  7750. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7751. endpointsEnteringLastN = lastNEndpoints;
  7752. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7753. endpointsEnteringLastN.forEach(function (resourceJid) {
  7754. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7755. showPeerContainer(resourceJid, 'show');
  7756. if (!isVisible) {
  7757. console.log("Add to last N", resourceJid);
  7758. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7759. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7760. var sel = $('#participant_' + resourceJid + '>video');
  7761. var videoStream = APP.simulcast.getReceivingVideoStream(
  7762. mediaStream.stream);
  7763. APP.RTC.attachMediaStream(sel, videoStream);
  7764. if (lastNPickupJid == mediaStream.peerjid) {
  7765. // Clean up the lastN pickup jid.
  7766. lastNPickupJid = null;
  7767. // Don't fire the events again, they've already
  7768. // been fired in the contact list click handler.
  7769. VideoLayout.handleVideoThumbClicked(
  7770. $(sel).attr('src'),
  7771. false,
  7772. Strophe.getResourceFromJid(mediaStream.peerjid));
  7773. updateLargeVideo = false;
  7774. }
  7775. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7776. }
  7777. })
  7778. }
  7779. // The endpoint that was being shown in the large video has dropped out
  7780. // of the lastN set and there was no lastN pickup jid. We need to update
  7781. // the large video now.
  7782. if (updateLargeVideo) {
  7783. var resource, container, src;
  7784. var myResource
  7785. = APP.xmpp.myResource();
  7786. // Find out which endpoint to show in the large video.
  7787. for (var i = 0; i < lastNEndpoints.length; i++) {
  7788. resource = lastNEndpoints[i];
  7789. if (!resource || resource === myResource)
  7790. continue;
  7791. container = $("#participant_" + resource);
  7792. if (container.length == 0)
  7793. continue;
  7794. src = $('video', container).attr('src');
  7795. if (!src)
  7796. continue;
  7797. // videoSrcToSsrc needs to be update for this call to succeed.
  7798. VideoLayout.updateLargeVideo(src);
  7799. break;
  7800. }
  7801. }
  7802. };
  7803. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  7804. endpointSimulcastLayers.forEach(function (esl) {
  7805. var resource = esl.endpoint;
  7806. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7807. // then ignore the event (= do not preload anything).
  7808. //
  7809. // The bridge could probably stop sending this message if it's for
  7810. // an endpoint that's not in lastN.
  7811. if (lastNCount != -1
  7812. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7813. return;
  7814. }
  7815. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7816. // Get session and stream from primary ssrc.
  7817. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7818. var sid = res.sid;
  7819. var electedStream = res.stream;
  7820. if (sid && electedStream) {
  7821. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7822. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7823. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  7824. if (preload) {
  7825. if (largeVideoState.preload)
  7826. {
  7827. $(largeVideoState.preload).remove();
  7828. }
  7829. console.info('Preloading remote video');
  7830. largeVideoState.preload = $('<video autoplay></video>');
  7831. // ssrcs are unique in an rtp session
  7832. largeVideoState.preload_ssrc = primarySSRC;
  7833. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  7834. }
  7835. } else {
  7836. console.error('Could not find a stream or a session.', sid, electedStream);
  7837. }
  7838. });
  7839. };
  7840. /**
  7841. * On simulcast layers changed event.
  7842. */
  7843. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  7844. endpointSimulcastLayers.forEach(function (esl) {
  7845. var resource = esl.endpoint;
  7846. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7847. // then ignore the event (= do not change large video/thumbnail
  7848. // SRCs).
  7849. //
  7850. // Note that even if we ignore the "changed" event in this event
  7851. // handler, the bridge must continue sending these events because
  7852. // the simulcast code in simulcast.js uses it to know what's going
  7853. // to be streamed by the bridge when/if the endpoint gets back into
  7854. // the lastN set.
  7855. if (lastNCount != -1
  7856. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7857. return;
  7858. }
  7859. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7860. // Get session and stream from primary ssrc.
  7861. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7862. var sid = res.sid;
  7863. var electedStream = res.stream;
  7864. if (sid && electedStream) {
  7865. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7866. console.info('Switching simulcast substream.');
  7867. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7868. var msidParts = msid.split(' ');
  7869. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  7870. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  7871. == largeVideoState.userResourceJid);
  7872. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  7873. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  7874. var electedStreamUrl;
  7875. if (largeVideoState.preload_ssrc == primarySSRC)
  7876. {
  7877. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  7878. }
  7879. else
  7880. {
  7881. if (largeVideoState.preload
  7882. && largeVideoState.preload != null) {
  7883. $(largeVideoState.preload).remove();
  7884. }
  7885. largeVideoState.preload_ssrc = 0;
  7886. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  7887. }
  7888. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  7889. if (updateLargeVideo) {
  7890. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  7891. Strophe.getResourceFromJid(jid));
  7892. }
  7893. if (updateFocusedVideoSrc) {
  7894. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  7895. }
  7896. var videoId;
  7897. if(resource == APP.xmpp.myResource())
  7898. {
  7899. videoId = "localVideoContainer";
  7900. }
  7901. else
  7902. {
  7903. videoId = "participant_" + resource;
  7904. }
  7905. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  7906. if(connectionIndicator)
  7907. connectionIndicator.updatePopoverData();
  7908. } else {
  7909. console.error('Could not find a stream or a sid.', sid, electedStream);
  7910. }
  7911. });
  7912. };
  7913. /**
  7914. * Updates local stats
  7915. * @param percent
  7916. * @param object
  7917. */
  7918. my.updateLocalConnectionStats = function (percent, object) {
  7919. var resolution = null;
  7920. if(object.resolution !== null)
  7921. {
  7922. resolution = object.resolution;
  7923. object.resolution = resolution[APP.xmpp.myJid()];
  7924. delete resolution[APP.xmpp.myJid()];
  7925. }
  7926. updateStatsIndicator("localVideoContainer", percent, object);
  7927. for(var jid in resolution)
  7928. {
  7929. if(resolution[jid] === null)
  7930. continue;
  7931. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7932. if(VideoLayout.connectionIndicators[id])
  7933. {
  7934. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7935. }
  7936. }
  7937. };
  7938. /**
  7939. * Updates remote stats.
  7940. * @param jid the jid associated with the stats
  7941. * @param percent the connection quality percent
  7942. * @param object the stats data
  7943. */
  7944. my.updateConnectionStats = function (jid, percent, object) {
  7945. var resourceJid = Strophe.getResourceFromJid(jid);
  7946. var videoSpanId = 'participant_' + resourceJid;
  7947. updateStatsIndicator(videoSpanId, percent, object);
  7948. };
  7949. /**
  7950. * Removes the connection
  7951. * @param jid
  7952. */
  7953. my.removeConnectionIndicator = function (jid) {
  7954. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7955. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7956. };
  7957. /**
  7958. * Hides the connection indicator
  7959. * @param jid
  7960. */
  7961. my.hideConnectionIndicator = function (jid) {
  7962. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7963. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7964. };
  7965. /**
  7966. * Hides all the indicators
  7967. */
  7968. my.onStatsStop = function () {
  7969. for(var indicator in VideoLayout.connectionIndicators)
  7970. {
  7971. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7972. }
  7973. };
  7974. my.participantLeft = function (jid) {
  7975. // Unlock large video
  7976. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7977. {
  7978. console.info("Focused video owner has left the conference");
  7979. focusedVideoInfo = null;
  7980. }
  7981. }
  7982. my.onVideoTypeChanged = function (jid) {
  7983. if(jid &&
  7984. Strophe.getResourceFromJid(jid) === largeVideoState.userResourceJid)
  7985. {
  7986. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  7987. VideoLayout.getVideoSize = largeVideoState.isDesktop
  7988. ? getDesktopVideoSize
  7989. : getCameraVideoSize;
  7990. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  7991. ? getDesktopVideoPosition
  7992. : getCameraVideoPosition;
  7993. VideoLayout.positionLarge(null, null);
  7994. }
  7995. }
  7996. return my;
  7997. }(VideoLayout || {}));
  7998. module.exports = VideoLayout;
  7999. },{"../../../service/RTC/MediaStreamTypes":94,"../../../service/UI/UIEvents":99,"../audio_levels/AudioLevels":10,"../avatar/Avatar":14,"../etherpad/Etherpad":15,"../prezi/Prezi":16,"../side_pannels/chat/Chat":19,"../side_pannels/contactlist/ContactList":23,"../util/NicknameHandler":30,"../util/UIUtil":31,"./ConnectionIndicator":32}],34:[function(require,module,exports){
  8000. //var nouns = [
  8001. //];
  8002. var pluralNouns = [
  8003. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  8004. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  8005. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  8006. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  8007. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  8008. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  8009. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  8010. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  8011. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  8012. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  8013. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  8014. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  8015. ];
  8016. //var places = [
  8017. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  8018. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  8019. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  8020. // "Bridge"
  8021. //];
  8022. var verbs = [
  8023. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  8024. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  8025. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  8026. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  8027. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  8028. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  8029. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  8030. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  8031. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  8032. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  8033. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  8034. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  8035. ];
  8036. var adverbs = [
  8037. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  8038. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  8039. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  8040. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  8041. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  8042. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  8043. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  8044. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  8045. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  8046. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  8047. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  8048. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  8049. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  8050. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  8051. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  8052. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  8053. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  8054. ];
  8055. var adjectives = [
  8056. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  8057. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  8058. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  8059. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  8060. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  8061. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  8062. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  8063. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  8064. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  8065. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  8066. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  8067. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  8068. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  8069. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  8070. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  8071. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  8072. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  8073. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  8074. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  8075. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  8076. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  8077. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  8078. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  8079. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  8080. "Zealous"
  8081. ];
  8082. //var pronouns = [
  8083. //];
  8084. //var conjunctions = [
  8085. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  8086. //];
  8087. /*
  8088. * Maps a string (category name) to the array of words from that category.
  8089. */
  8090. var CATEGORIES =
  8091. {
  8092. //"_NOUN_": nouns,
  8093. "_PLURALNOUN_": pluralNouns,
  8094. //"_PLACE_": places,
  8095. "_VERB_": verbs,
  8096. "_ADVERB_": adverbs,
  8097. "_ADJECTIVE_": adjectives
  8098. //"_PRONOUN_": pronouns,
  8099. //"_CONJUNCTION_": conjunctions,
  8100. };
  8101. var PATTERNS = [
  8102. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  8103. // BeautifulFungiOrSpaghetti
  8104. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  8105. // AmazinglyScaryToy
  8106. //"_ADVERB__ADJECTIVE__NOUN_",
  8107. // NeitherTrashNorRifle
  8108. //"Neither_NOUN_Nor_NOUN_",
  8109. //"Either_NOUN_Or_NOUN_",
  8110. // EitherCopulateOrInvestigate
  8111. //"Either_VERB_Or_VERB_",
  8112. //"Neither_VERB_Nor_VERB_",
  8113. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  8114. //"The_ADVERB__ADJECTIVE__NOUN_",
  8115. //"The_ADVERB__ADJECTIVE__NOUN_s",
  8116. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  8117. // WolvesComputeBadly
  8118. //"_PLURALNOUN__VERB__ADVERB_",
  8119. // UniteFacilitateAndMerge
  8120. //"_VERB__VERB_And_VERB_",
  8121. //NastyWitchesAtThePub
  8122. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  8123. ];
  8124. /*
  8125. * Returns a random element from the array 'arr'
  8126. */
  8127. function randomElement(arr)
  8128. {
  8129. return arr[Math.floor(Math.random() * arr.length)];
  8130. }
  8131. /*
  8132. * Returns true if the string 's' contains one of the
  8133. * template strings.
  8134. */
  8135. function hasTemplate(s)
  8136. {
  8137. for (var template in CATEGORIES){
  8138. if (s.indexOf(template) >= 0){
  8139. return true;
  8140. }
  8141. }
  8142. }
  8143. /**
  8144. * Generates new room name.
  8145. */
  8146. var RoomNameGenerator = {
  8147. generateRoomWithoutSeparator: function()
  8148. {
  8149. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  8150. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  8151. var name = randomElement(PATTERNS);
  8152. var word;
  8153. while (hasTemplate(name)){
  8154. for (var template in CATEGORIES){
  8155. word = randomElement(CATEGORIES[template]);
  8156. name = name.replace(template, word);
  8157. }
  8158. }
  8159. return name;
  8160. }
  8161. }
  8162. module.exports = RoomNameGenerator;
  8163. },{}],35:[function(require,module,exports){
  8164. var animateTimeout, updateTimeout;
  8165. var RoomNameGenerator = require("./RoomnameGenerator");
  8166. function enter_room()
  8167. {
  8168. var val = $("#enter_room_field").val();
  8169. if(!val) {
  8170. val = $("#enter_room_field").attr("room_name");
  8171. }
  8172. if (val) {
  8173. window.location.pathname = "/" + val;
  8174. }
  8175. }
  8176. function animate(word) {
  8177. var currentVal = $("#enter_room_field").attr("placeholder");
  8178. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  8179. animateTimeout = setTimeout(function() {
  8180. animate(word.substring(1, word.length))
  8181. }, 70);
  8182. }
  8183. function update_roomname()
  8184. {
  8185. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  8186. $("#enter_room_field").attr("room_name", word);
  8187. $("#enter_room_field").attr("placeholder", "");
  8188. clearTimeout(animateTimeout);
  8189. animate(word);
  8190. updateTimeout = setTimeout(update_roomname, 10000);
  8191. }
  8192. function setupWelcomePage()
  8193. {
  8194. $("#videoconference_page").hide();
  8195. $("#domain_name").text(
  8196. window.location.protocol + "//" + window.location.host + "/");
  8197. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  8198. var leftWatermarkDiv
  8199. = $("#welcome_page_header div[class='watermark leftwatermark']");
  8200. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  8201. {
  8202. leftWatermarkDiv.css({display: 'block'});
  8203. leftWatermarkDiv.parent().get(0).href
  8204. = interfaceConfig.JITSI_WATERMARK_LINK;
  8205. }
  8206. }
  8207. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  8208. var rightWatermarkDiv
  8209. = $("#welcome_page_header div[class='watermark rightwatermark']");
  8210. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  8211. rightWatermarkDiv.css({display: 'block'});
  8212. rightWatermarkDiv.parent().get(0).href
  8213. = interfaceConfig.BRAND_WATERMARK_LINK;
  8214. rightWatermarkDiv.get(0).style.backgroundImage
  8215. = "url(images/rightwatermark.png)";
  8216. }
  8217. }
  8218. if (interfaceConfig.SHOW_POWERED_BY) {
  8219. $("#welcome_page_header>a[class='poweredby']")
  8220. .css({display: 'block'});
  8221. }
  8222. $("#enter_room_button").click(function()
  8223. {
  8224. enter_room();
  8225. });
  8226. $("#enter_room_field").keydown(function (event) {
  8227. if (event.keyCode === 13 /* enter */) {
  8228. enter_room();
  8229. }
  8230. });
  8231. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  8232. var updateTimeout;
  8233. var animateTimeout;
  8234. $("#reload_roomname").click(function () {
  8235. clearTimeout(updateTimeout);
  8236. clearTimeout(animateTimeout);
  8237. update_roomname();
  8238. });
  8239. $("#reload_roomname").show();
  8240. update_roomname();
  8241. }
  8242. $("#disable_welcome").click(function () {
  8243. window.localStorage.welcomePageDisabled
  8244. = $("#disable_welcome").is(":checked");
  8245. });
  8246. }
  8247. module.exports = setupWelcomePage;
  8248. },{"./RoomnameGenerator":34}],36:[function(require,module,exports){
  8249. var params = {};
  8250. function getConfigParamsFromUrl() {
  8251. if(!location.hash)
  8252. return {};
  8253. var hash = location.hash.substr(1);
  8254. var result = {};
  8255. hash.split("&").forEach(function(part) {
  8256. var item = part.split("=");
  8257. result[item[0]] = JSON.parse(
  8258. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  8259. });
  8260. return result;
  8261. }
  8262. params = getConfigParamsFromUrl();
  8263. var URLProcessor = {
  8264. setConfigParametersFromUrl: function () {
  8265. for(var k in params)
  8266. {
  8267. if(typeof k !== "string" || k.indexOf("config.") === -1)
  8268. continue;
  8269. var v = params[k];
  8270. var confKey = k.substr(7);
  8271. if(config[confKey] && typeof config[confKey] !== typeof v)
  8272. {
  8273. console.warn("The type of " + k +
  8274. " is wrong. That parameter won't be updated in config.js.");
  8275. continue;
  8276. }
  8277. config[confKey] = v;
  8278. }
  8279. }
  8280. };
  8281. module.exports = URLProcessor;
  8282. },{}],37:[function(require,module,exports){
  8283. var EventEmitter = require("events");
  8284. var eventEmitter = new EventEmitter();
  8285. var CQEvents = require("../../service/connectionquality/CQEvents");
  8286. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8287. /**
  8288. * local stats
  8289. * @type {{}}
  8290. */
  8291. var stats = {};
  8292. /**
  8293. * remote stats
  8294. * @type {{}}
  8295. */
  8296. var remoteStats = {};
  8297. /**
  8298. * Interval for sending statistics to other participants
  8299. * @type {null}
  8300. */
  8301. var sendIntervalId = null;
  8302. /**
  8303. * Start statistics sending.
  8304. */
  8305. function startSendingStats() {
  8306. sendStats();
  8307. sendIntervalId = setInterval(sendStats, 10000);
  8308. }
  8309. /**
  8310. * Sends statistics to other participants
  8311. */
  8312. function sendStats() {
  8313. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  8314. }
  8315. /**
  8316. * Converts statistics to format for sending through XMPP
  8317. * @param stats the statistics
  8318. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  8319. */
  8320. function convertToMUCStats(stats) {
  8321. return {
  8322. "bitrate_download": stats.bitrate.download,
  8323. "bitrate_upload": stats.bitrate.upload,
  8324. "packetLoss_total": stats.packetLoss.total,
  8325. "packetLoss_download": stats.packetLoss.download,
  8326. "packetLoss_upload": stats.packetLoss.upload
  8327. };
  8328. }
  8329. /**
  8330. * Converts statitistics to format used by VideoLayout
  8331. * @param stats
  8332. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  8333. */
  8334. function parseMUCStats(stats) {
  8335. return {
  8336. bitrate: {
  8337. download: stats.bitrate_download,
  8338. upload: stats.bitrate_upload
  8339. },
  8340. packetLoss: {
  8341. total: stats.packetLoss_total,
  8342. download: stats.packetLoss_download,
  8343. upload: stats.packetLoss_upload
  8344. }
  8345. };
  8346. }
  8347. var ConnectionQuality = {
  8348. init: function () {
  8349. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  8350. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  8351. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  8352. },
  8353. /**
  8354. * Updates the local statistics
  8355. * @param data new statistics
  8356. */
  8357. updateLocalStats: function (data) {
  8358. stats = data;
  8359. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  8360. if (sendIntervalId == null) {
  8361. startSendingStats();
  8362. }
  8363. },
  8364. /**
  8365. * Updates remote statistics
  8366. * @param jid the jid associated with the statistics
  8367. * @param data the statistics
  8368. */
  8369. updateRemoteStats: function (jid, data) {
  8370. if (data == null || data.packetLoss_total == null) {
  8371. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  8372. return;
  8373. }
  8374. remoteStats[jid] = parseMUCStats(data);
  8375. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  8376. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  8377. },
  8378. /**
  8379. * Stops statistics sending.
  8380. */
  8381. stopSendingStats: function () {
  8382. clearInterval(sendIntervalId);
  8383. sendIntervalId = null;
  8384. //notify UI about stopping statistics gathering
  8385. eventEmitter.emit(CQEvents.STOP);
  8386. },
  8387. /**
  8388. * Returns the local statistics.
  8389. */
  8390. getStats: function () {
  8391. return stats;
  8392. },
  8393. addListener: function (type, listener) {
  8394. eventEmitter.on(type, listener);
  8395. }
  8396. };
  8397. module.exports = ConnectionQuality;
  8398. },{"../../service/connectionquality/CQEvents":101,"../../service/xmpp/XMPPEvents":105,"events":106}],38:[function(require,module,exports){
  8399. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  8400. getUserMediaWithConstraints */
  8401. /**
  8402. * Indicates that desktop stream is currently in use(for toggle purpose).
  8403. * @type {boolean}
  8404. */
  8405. var isUsingScreenStream = false;
  8406. /**
  8407. * Indicates that switch stream operation is in progress and prevent from
  8408. * triggering new events.
  8409. * @type {boolean}
  8410. */
  8411. var switchInProgress = false;
  8412. /**
  8413. * Method used to get screen sharing stream.
  8414. *
  8415. * @type {function (stream_callback, failure_callback}
  8416. */
  8417. var obtainDesktopStream = null;
  8418. /**
  8419. * Indicates whether desktop sharing extension is installed.
  8420. * @type {boolean}
  8421. */
  8422. var extInstalled = false;
  8423. /**
  8424. * Indicates whether update of desktop sharing extension is required.
  8425. * @type {boolean}
  8426. */
  8427. var extUpdateRequired = false;
  8428. /**
  8429. * Flag used to cache desktop sharing enabled state. Do not use directly as
  8430. * it can be <tt>null</tt>.
  8431. *
  8432. * @type {null|boolean}
  8433. */
  8434. var _desktopSharingEnabled = null;
  8435. var EventEmitter = require("events");
  8436. var eventEmitter = new EventEmitter();
  8437. var DesktopSharingEventTypes
  8438. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  8439. /**
  8440. * Method obtains desktop stream from WebRTC 'screen' source.
  8441. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  8442. */
  8443. function obtainWebRTCScreen(streamCallback, failCallback) {
  8444. APP.RTC.getUserMediaWithConstraints(
  8445. ['screen'],
  8446. streamCallback,
  8447. failCallback
  8448. );
  8449. }
  8450. /**
  8451. * Constructs inline install URL for Chrome desktop streaming extension.
  8452. * The 'chromeExtensionId' must be defined in config.js.
  8453. * @returns {string}
  8454. */
  8455. function getWebStoreInstallUrl()
  8456. {
  8457. return "https://chrome.google.com/webstore/detail/" +
  8458. config.chromeExtensionId;
  8459. }
  8460. /**
  8461. * Checks whether extension update is required.
  8462. * @param minVersion minimal required version
  8463. * @param extVersion current extension version
  8464. * @returns {boolean}
  8465. */
  8466. function isUpdateRequired(minVersion, extVersion)
  8467. {
  8468. try
  8469. {
  8470. var s1 = minVersion.split('.');
  8471. var s2 = extVersion.split('.');
  8472. var len = Math.max(s1.length, s2.length);
  8473. for (var i = 0; i < len; i++)
  8474. {
  8475. var n1 = 0,
  8476. n2 = 0;
  8477. if (i < s1.length)
  8478. n1 = parseInt(s1[i]);
  8479. if (i < s2.length)
  8480. n2 = parseInt(s2[i]);
  8481. if (isNaN(n1) || isNaN(n2))
  8482. {
  8483. return true;
  8484. }
  8485. else if (n1 !== n2)
  8486. {
  8487. return n1 > n2;
  8488. }
  8489. }
  8490. // will happen if boths version has identical numbers in
  8491. // their components (even if one of them is longer, has more components)
  8492. return false;
  8493. }
  8494. catch (e)
  8495. {
  8496. console.error("Failed to parse extension version", e);
  8497. APP.UI.messageHandler.showError("dialog.error",
  8498. "dialog.detectext");
  8499. return true;
  8500. }
  8501. }
  8502. function checkExtInstalled(callback) {
  8503. if (!chrome.runtime) {
  8504. // No API, so no extension for sure
  8505. callback(false, false);
  8506. return;
  8507. }
  8508. chrome.runtime.sendMessage(
  8509. config.chromeExtensionId,
  8510. { getVersion: true },
  8511. function (response) {
  8512. if (!response || !response.version) {
  8513. // Communication failure - assume that no endpoint exists
  8514. console.warn(
  8515. "Extension not installed?: ", chrome.runtime.lastError);
  8516. callback(false, false);
  8517. return;
  8518. }
  8519. // Check installed extension version
  8520. var extVersion = response.version;
  8521. console.log('Extension version is: ' + extVersion);
  8522. var updateRequired
  8523. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  8524. callback(!updateRequired, updateRequired);
  8525. }
  8526. );
  8527. }
  8528. function doGetStreamFromExtension(streamCallback, failCallback) {
  8529. // Sends 'getStream' msg to the extension.
  8530. // Extension id must be defined in the config.
  8531. chrome.runtime.sendMessage(
  8532. config.chromeExtensionId,
  8533. { getStream: true, sources: config.desktopSharingSources },
  8534. function (response) {
  8535. if (!response) {
  8536. failCallback(chrome.runtime.lastError);
  8537. return;
  8538. }
  8539. console.log("Response from extension: " + response);
  8540. if (response.streamId) {
  8541. APP.RTC.getUserMediaWithConstraints(
  8542. ['desktop'],
  8543. function (stream) {
  8544. streamCallback(stream);
  8545. },
  8546. failCallback,
  8547. null, null, null,
  8548. response.streamId);
  8549. } else {
  8550. failCallback("Extension failed to get the stream");
  8551. }
  8552. }
  8553. );
  8554. }
  8555. /**
  8556. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  8557. * stream for returned stream token.
  8558. */
  8559. function obtainScreenFromExtension(streamCallback, failCallback) {
  8560. if (extInstalled) {
  8561. doGetStreamFromExtension(streamCallback, failCallback);
  8562. } else {
  8563. if (extUpdateRequired) {
  8564. alert(
  8565. 'Jitsi Desktop Streamer requires update. ' +
  8566. 'Changes will take effect after next Chrome restart.');
  8567. }
  8568. chrome.webstore.install(
  8569. getWebStoreInstallUrl(),
  8570. function (arg) {
  8571. console.log("Extension installed successfully", arg);
  8572. // We need to reload the page in order to get the access to
  8573. // chrome.runtime
  8574. window.location.reload(false);
  8575. },
  8576. function (arg) {
  8577. console.log("Failed to install the extension", arg);
  8578. failCallback(arg);
  8579. APP.UI.messageHandler.showError("dialog.error",
  8580. "dialog.failtoinstall");
  8581. }
  8582. );
  8583. }
  8584. }
  8585. /**
  8586. * Call this method to toggle desktop sharing feature.
  8587. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  8588. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  8589. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  8590. * enabled), pass any other string or nothing in order to disable this
  8591. * feature completely.
  8592. */
  8593. function setDesktopSharing(method) {
  8594. // Check if we are running chrome
  8595. if (!navigator.webkitGetUserMedia) {
  8596. obtainDesktopStream = null;
  8597. console.info("Desktop sharing disabled");
  8598. } else if (method == "ext") {
  8599. obtainDesktopStream = obtainScreenFromExtension;
  8600. console.info("Using Chrome extension for desktop sharing");
  8601. } else if (method == "webrtc") {
  8602. obtainDesktopStream = obtainWebRTCScreen;
  8603. console.info("Using Chrome WebRTC for desktop sharing");
  8604. }
  8605. // Reset enabled cache
  8606. _desktopSharingEnabled = null;
  8607. }
  8608. /**
  8609. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  8610. * config.js to support inline installs. Host site must be selected as main
  8611. * website of published extension.
  8612. */
  8613. function initInlineInstalls()
  8614. {
  8615. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  8616. }
  8617. function getVideoStreamFailed(error) {
  8618. console.error("Failed to obtain the stream to switch to", error);
  8619. switchInProgress = false;
  8620. isUsingScreenStream = false;
  8621. newStreamCreated(null);
  8622. }
  8623. function getDesktopStreamFailed(error) {
  8624. console.error("Failed to obtain the stream to switch to", error);
  8625. switchInProgress = false;
  8626. }
  8627. function streamSwitchDone() {
  8628. switchInProgress = false;
  8629. eventEmitter.emit(
  8630. DesktopSharingEventTypes.SWITCHING_DONE,
  8631. isUsingScreenStream);
  8632. }
  8633. function newStreamCreated(stream)
  8634. {
  8635. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  8636. stream, isUsingScreenStream, streamSwitchDone);
  8637. }
  8638. module.exports = {
  8639. isUsingScreenStream: function () {
  8640. return isUsingScreenStream;
  8641. },
  8642. /**
  8643. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  8644. * and enabled.
  8645. */
  8646. isDesktopSharingEnabled: function () {
  8647. if (_desktopSharingEnabled === null) {
  8648. if (obtainDesktopStream === obtainScreenFromExtension) {
  8649. // Parse chrome version
  8650. var userAgent = navigator.userAgent.toLowerCase();
  8651. // We can assume that user agent is chrome, because it's
  8652. // enforced when 'ext' streaming method is set
  8653. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  8654. console.log("Chrome version" + userAgent, ver);
  8655. _desktopSharingEnabled = ver >= 34;
  8656. } else {
  8657. _desktopSharingEnabled =
  8658. obtainDesktopStream === obtainWebRTCScreen;
  8659. }
  8660. }
  8661. return _desktopSharingEnabled;
  8662. },
  8663. init: function () {
  8664. setDesktopSharing(config.desktopSharing);
  8665. // Initialize Chrome extension inline installs
  8666. if (config.chromeExtensionId) {
  8667. initInlineInstalls();
  8668. // Check if extension is installed
  8669. checkExtInstalled(function (installed, updateRequired) {
  8670. extInstalled = installed;
  8671. extUpdateRequired = updateRequired;
  8672. console.info(
  8673. "Chrome extension installed: " + extInstalled +
  8674. " updateRequired: " + extUpdateRequired);
  8675. });
  8676. }
  8677. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  8678. },
  8679. addListener: function (listener, type)
  8680. {
  8681. eventEmitter.on(type, listener);
  8682. },
  8683. removeListener: function (listener, type) {
  8684. eventEmitter.removeListener(type, listener);
  8685. },
  8686. /*
  8687. * Toggles screen sharing.
  8688. */
  8689. toggleScreenSharing: function () {
  8690. if (switchInProgress || !obtainDesktopStream) {
  8691. console.warn("Switch in progress or no method defined");
  8692. return;
  8693. }
  8694. switchInProgress = true;
  8695. if (!isUsingScreenStream)
  8696. {
  8697. // Switch to desktop stream
  8698. obtainDesktopStream(
  8699. function (stream) {
  8700. // We now use screen stream
  8701. isUsingScreenStream = true;
  8702. // Hook 'ended' event to restore camera
  8703. // when screen stream stops
  8704. stream.addEventListener('ended',
  8705. function (e) {
  8706. if (!switchInProgress && isUsingScreenStream) {
  8707. APP.desktopsharing.toggleScreenSharing();
  8708. }
  8709. }
  8710. );
  8711. newStreamCreated(stream);
  8712. },
  8713. getDesktopStreamFailed);
  8714. } else {
  8715. // Disable screen stream
  8716. APP.RTC.getUserMediaWithConstraints(
  8717. ['video'],
  8718. function (stream) {
  8719. // We are now using camera stream
  8720. isUsingScreenStream = false;
  8721. newStreamCreated(stream);
  8722. },
  8723. getVideoStreamFailed, config.resolution || '360'
  8724. );
  8725. }
  8726. }
  8727. };
  8728. },{"../../service/desktopsharing/DesktopSharingEventTypes":102,"events":106}],39:[function(require,module,exports){
  8729. //maps keycode to character, id of popover for given function and function
  8730. var shortcuts = {
  8731. 67: {
  8732. character: "C",
  8733. id: "toggleChatPopover",
  8734. function: APP.UI.toggleChat
  8735. },
  8736. 70: {
  8737. character: "F",
  8738. id: "filmstripPopover",
  8739. function: APP.UI.toggleFilmStrip
  8740. },
  8741. 77: {
  8742. character: "M",
  8743. id: "mutePopover",
  8744. function: APP.UI.toggleAudio
  8745. },
  8746. 84: {
  8747. character: "T",
  8748. function: function() {
  8749. if(!APP.RTC.localAudio.isMuted()) {
  8750. APP.UI.toggleAudio();
  8751. }
  8752. }
  8753. },
  8754. 86: {
  8755. character: "V",
  8756. id: "toggleVideoPopover",
  8757. function: APP.UI.toggleVideo
  8758. }
  8759. };
  8760. var KeyboardShortcut = {
  8761. init: function () {
  8762. window.onkeyup = function(e) {
  8763. var keycode = e.which;
  8764. if(!($(":focus").is("input[type=text]") ||
  8765. $(":focus").is("input[type=password]") ||
  8766. $(":focus").is("textarea"))) {
  8767. if (typeof shortcuts[keycode] === "object") {
  8768. shortcuts[keycode].function();
  8769. }
  8770. else if (keycode >= "0".charCodeAt(0) &&
  8771. keycode <= "9".charCodeAt(0)) {
  8772. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8773. }
  8774. //esc while the smileys are visible hides them
  8775. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8776. APP.UI.toggleSmileys();
  8777. }
  8778. };
  8779. window.onkeydown = function(e) {
  8780. if(!($(":focus").is("input[type=text]") ||
  8781. $(":focus").is("input[type=password]") ||
  8782. $(":focus").is("textarea"))) {
  8783. if(e.which === "T".charCodeAt(0)) {
  8784. if(APP.RTC.localAudio.isMuted()) {
  8785. APP.UI.toggleAudio();
  8786. }
  8787. }
  8788. }
  8789. };
  8790. var self = this;
  8791. $('body').popover({ selector: '[data-toggle=popover]',
  8792. trigger: 'click hover',
  8793. content: function() {
  8794. return this.getAttribute("content") +
  8795. self.getShortcut(this.getAttribute("shortcut"));
  8796. }
  8797. });
  8798. },
  8799. /**
  8800. *
  8801. * @param id indicates the popover associated with the shortcut
  8802. * @returns {string} the keyboard shortcut used for the id given
  8803. */
  8804. getShortcut: function (id) {
  8805. for (var keycode in shortcuts) {
  8806. if (shortcuts.hasOwnProperty(keycode)) {
  8807. if (shortcuts[keycode].id === id) {
  8808. return " (" + shortcuts[keycode].character + ")";
  8809. }
  8810. }
  8811. }
  8812. return "";
  8813. }
  8814. };
  8815. module.exports = KeyboardShortcut;
  8816. },{}],40:[function(require,module,exports){
  8817. /* global APP */
  8818. /**
  8819. * This module is meant to (eventually) contain and manage all information
  8820. * about members/participants of the conference, so that other modules don't
  8821. * have to do it on their own, and so that other modules can access members'
  8822. * information from a single place.
  8823. *
  8824. * Currently this module only manages information about the support of jingle
  8825. * DTMF of the members. Other fields, as well as accessor methods are meant to
  8826. * be added as needed.
  8827. */
  8828. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8829. var Events = require("../../service/members/Events");
  8830. var EventEmitter = require("events");
  8831. var eventEmitter = new EventEmitter();
  8832. /**
  8833. * The actual container.
  8834. */
  8835. var members = {};
  8836. /**
  8837. * There is at least one member that supports DTMF (i.e. is jigasi).
  8838. */
  8839. var atLeastOneDtmf = false;
  8840. function registerListeners() {
  8841. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  8842. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  8843. }
  8844. /**
  8845. * Handles a new member joining the MUC.
  8846. */
  8847. function onMucMemberJoined(jid, id, displayName) {
  8848. var member = {
  8849. displayName: displayName
  8850. };
  8851. APP.xmpp.getConnection().disco.info(
  8852. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  8853. members[jid] = member;
  8854. }
  8855. /**
  8856. * Handles a member leaving the MUC.
  8857. */
  8858. function onMucMemberLeft(jid) {
  8859. delete members[jid];
  8860. updateAtLeastOneDtmf();
  8861. }
  8862. /**
  8863. * Handles the reception of a disco#info packet from a particular JID.
  8864. * @param jid the JID sending the packet.
  8865. * @param iq the packet.
  8866. */
  8867. function onDiscoInfoReceived(jid, iq) {
  8868. if (!members[jid])
  8869. return;
  8870. var supportsDtmf
  8871. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  8872. updateDtmf(jid, supportsDtmf);
  8873. }
  8874. /**
  8875. * Updates the 'supportsDtmf' field for a member.
  8876. * @param jid the jid of the member.
  8877. * @param newValue the new value for the 'supportsDtmf' field.
  8878. */
  8879. function updateDtmf(jid, newValue) {
  8880. var oldValue = members[jid].supportsDtmf;
  8881. members[jid].supportsDtmf = newValue;
  8882. if (newValue != oldValue) {
  8883. updateAtLeastOneDtmf();
  8884. }
  8885. }
  8886. /**
  8887. * Checks each member's 'supportsDtmf' field and updates
  8888. * 'atLastOneSupportsDtmf'.
  8889. */
  8890. function updateAtLeastOneDtmf(){
  8891. var newAtLeastOneDtmf = false;
  8892. for (var key in members) {
  8893. if (typeof members[key].supportsDtmf !== 'undefined'
  8894. && members[key].supportsDtmf) {
  8895. newAtLeastOneDtmf= true;
  8896. break;
  8897. }
  8898. }
  8899. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  8900. atLeastOneDtmf = newAtLeastOneDtmf;
  8901. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  8902. }
  8903. }
  8904. /**
  8905. * Exported interface.
  8906. */
  8907. var Members = {
  8908. start: function(){
  8909. registerListeners();
  8910. },
  8911. addListener: function(type, listener)
  8912. {
  8913. eventEmitter.on(type, listener);
  8914. },
  8915. removeListener: function (type, listener) {
  8916. eventEmitter.removeListener(type, listener);
  8917. },
  8918. size: function () {
  8919. return Object.keys(members).length;
  8920. },
  8921. getMembers: function () {
  8922. return members;
  8923. }
  8924. };
  8925. module.exports = Members;
  8926. },{"../../service/members/Events":103,"../../service/xmpp/XMPPEvents":105,"events":106}],41:[function(require,module,exports){
  8927. var email = '';
  8928. var displayName = '';
  8929. var userId;
  8930. var language = null;
  8931. function supportsLocalStorage() {
  8932. try {
  8933. return 'localStorage' in window && window.localStorage !== null;
  8934. } catch (e) {
  8935. console.log("localstorage is not supported");
  8936. return false;
  8937. }
  8938. }
  8939. function generateUniqueId() {
  8940. function _p8() {
  8941. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8942. }
  8943. return _p8() + _p8() + _p8() + _p8();
  8944. }
  8945. if (supportsLocalStorage()) {
  8946. if (!window.localStorage.jitsiMeetId) {
  8947. window.localStorage.jitsiMeetId = generateUniqueId();
  8948. console.log("generated id", window.localStorage.jitsiMeetId);
  8949. }
  8950. userId = window.localStorage.jitsiMeetId || '';
  8951. email = window.localStorage.email || '';
  8952. displayName = window.localStorage.displayname || '';
  8953. language = window.localStorage.language;
  8954. } else {
  8955. console.log("local storage is not supported");
  8956. userId = generateUniqueId();
  8957. }
  8958. var Settings =
  8959. {
  8960. setDisplayName: function (newDisplayName) {
  8961. displayName = newDisplayName;
  8962. window.localStorage.displayname = displayName;
  8963. return displayName;
  8964. },
  8965. setEmail: function (newEmail)
  8966. {
  8967. email = newEmail;
  8968. window.localStorage.email = newEmail;
  8969. return email;
  8970. },
  8971. getSettings: function () {
  8972. return {
  8973. email: email,
  8974. displayName: displayName,
  8975. uid: userId,
  8976. language: language
  8977. };
  8978. },
  8979. setLanguage: function (lang) {
  8980. language = lang;
  8981. window.localStorage.language = lang;
  8982. }
  8983. };
  8984. module.exports = Settings;
  8985. },{}],42:[function(require,module,exports){
  8986. /**
  8987. *
  8988. * @constructor
  8989. */
  8990. function SimulcastLogger(name, lvl) {
  8991. this.name = name;
  8992. this.lvl = lvl;
  8993. }
  8994. SimulcastLogger.prototype.log = function (text) {
  8995. if (this.lvl) {
  8996. console.log(text);
  8997. }
  8998. };
  8999. SimulcastLogger.prototype.info = function (text) {
  9000. if (this.lvl > 1) {
  9001. console.info(text);
  9002. }
  9003. };
  9004. SimulcastLogger.prototype.fine = function (text) {
  9005. if (this.lvl > 2) {
  9006. console.log(text);
  9007. }
  9008. };
  9009. SimulcastLogger.prototype.error = function (text) {
  9010. console.error(text);
  9011. };
  9012. module.exports = SimulcastLogger;
  9013. },{}],43:[function(require,module,exports){
  9014. var SimulcastLogger = require("./SimulcastLogger");
  9015. var SimulcastUtils = require("./SimulcastUtils");
  9016. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  9017. function SimulcastReceiver() {
  9018. this.simulcastUtils = new SimulcastUtils();
  9019. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  9020. }
  9021. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  9022. SimulcastReceiver.prototype._remoteMaps = {
  9023. msid2Quality: {},
  9024. ssrc2Msid: {},
  9025. msid2ssrc: {},
  9026. receivingVideoStreams: {}
  9027. };
  9028. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  9029. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  9030. };
  9031. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  9032. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  9033. };
  9034. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  9035. var sb;
  9036. this.logger.info('Ensuring x-google-conference flag...')
  9037. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  9038. // TODO(gp) do that for the audio as well as suggested by fippo.
  9039. // Add the google conference flag
  9040. sb = this.simulcastUtils._getVideoSources(lines);
  9041. sb = ['a=x-google-flag:conference'].concat(sb);
  9042. this.simulcastUtils._replaceVideoSources(lines, sb);
  9043. }
  9044. };
  9045. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  9046. this._restoreRemoteVideoSources(sb);
  9047. };
  9048. /**
  9049. * Restores the simulcast groups of the remote description. In
  9050. * transformRemoteDescription we remove those in order for the set remote
  9051. * description to succeed. The focus needs the signal the groups to new
  9052. * participants.
  9053. *
  9054. * @param desc
  9055. * @returns {*}
  9056. */
  9057. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  9058. var sb;
  9059. if (!this.simulcastUtils.isValidDescription(desc)) {
  9060. return desc;
  9061. }
  9062. if (config.enableSimulcast) {
  9063. sb = desc.sdp.split('\r\n');
  9064. this._restoreSimulcastGroups(sb);
  9065. desc = new RTCSessionDescription({
  9066. type: desc.type,
  9067. sdp: sb.join('\r\n')
  9068. });
  9069. }
  9070. return desc;
  9071. };
  9072. SimulcastUtils.prototype._ensureOrder = function (lines) {
  9073. var videoSources, sb;
  9074. videoSources = this.parseMedia(lines, ['video'])[0];
  9075. sb = this._compileVideoSources(videoSources);
  9076. this._replaceVideoSources(lines, sb);
  9077. };
  9078. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  9079. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  9080. videoSource, quality;
  9081. // (re) initialize the remote maps.
  9082. this._remoteMaps.msid2Quality = {};
  9083. this._remoteMaps.ssrc2Msid = {};
  9084. this._remoteMaps.msid2ssrc = {};
  9085. var self = this;
  9086. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  9087. remoteVideoSources.groups.forEach(function (group) {
  9088. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  9089. quality = 0;
  9090. group.ssrcs.forEach(function (ssrc) {
  9091. videoSource = remoteVideoSources.sources[ssrc];
  9092. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  9093. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  9094. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  9095. });
  9096. }
  9097. });
  9098. }
  9099. };
  9100. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  9101. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  9102. };
  9103. /**
  9104. * Returns a stream with single video track, the one currently being
  9105. * received by this endpoint.
  9106. *
  9107. * @param stream the remote simulcast stream.
  9108. * @returns {webkitMediaStream}
  9109. */
  9110. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  9111. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  9112. var self = this;
  9113. if (config.enableSimulcast) {
  9114. stream.getVideoTracks().some(function (track) {
  9115. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  9116. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  9117. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  9118. if (msid == [stream.id, track.id].join(' ')) {
  9119. electedTrack = track;
  9120. return true;
  9121. }
  9122. });
  9123. });
  9124. if (!electedTrack) {
  9125. // we don't have an elected track, choose by initial quality.
  9126. tracks = stream.getVideoTracks();
  9127. for (i = 0; i < tracks.length; i++) {
  9128. msid = [stream.id, tracks[i].id].join(' ');
  9129. if (this._remoteMaps.msid2Quality[msid] === quality) {
  9130. electedTrack = tracks[i];
  9131. break;
  9132. }
  9133. }
  9134. // TODO(gp) if the initialQuality could not be satisfied, lower
  9135. // the requirement and try again.
  9136. }
  9137. }
  9138. return (electedTrack)
  9139. ? new webkitMediaStream([electedTrack])
  9140. : stream;
  9141. };
  9142. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  9143. var resource = Strophe.getResourceFromJid(jid);
  9144. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  9145. // If we haven't receiving a "changed" event yet, then we must be receiving
  9146. // low quality (that the sender always streams).
  9147. if(!ssrc)
  9148. {
  9149. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9150. var remoteStream = remoteStreamObject.getOriginalStream();
  9151. var tracks = remoteStream.getVideoTracks();
  9152. if (tracks) {
  9153. for (var k = 0; k < tracks.length; k++) {
  9154. var track = tracks[k];
  9155. var msid = [remoteStream.id, track.id].join(' ');
  9156. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  9157. var quality = this._remoteMaps.msid2Quality[msid];
  9158. if (quality == 0) {
  9159. ssrc = _ssrc;
  9160. }
  9161. }
  9162. }
  9163. }
  9164. return ssrc;
  9165. };
  9166. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  9167. {
  9168. var sid, electedStream;
  9169. var i, j, k;
  9170. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9171. if(jid && APP.RTC.remoteStreams[jid])
  9172. {
  9173. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9174. var remoteStream = remoteStreamObject.getOriginalStream();
  9175. var tracks = remoteStream.getVideoTracks();
  9176. if (tracks) {
  9177. for (k = 0; k < tracks.length; k++) {
  9178. var track = tracks[k];
  9179. var msid = [remoteStream.id, track.id].join(' ');
  9180. var tmp = this._remoteMaps.msid2ssrc[msid];
  9181. if (tmp == ssrc) {
  9182. electedStream = new webkitMediaStream([track]);
  9183. sid = remoteStreamObject.sid;
  9184. // stream found, stop.
  9185. break;
  9186. }
  9187. }
  9188. }
  9189. }
  9190. else
  9191. {
  9192. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  9193. }
  9194. return {
  9195. sid: sid,
  9196. stream: electedStream
  9197. };
  9198. };
  9199. /**
  9200. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9201. * SSRC.
  9202. *
  9203. * @param ssrc
  9204. * @returns {*}
  9205. */
  9206. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9207. return this._remoteMaps.ssrc2Msid[ssrc];
  9208. };
  9209. /**
  9210. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9211. * either gets confused and thinks this is an FID group or, if an FID group
  9212. * is already present, it fails to set the remote description.
  9213. *
  9214. * @param desc
  9215. * @returns {*}
  9216. */
  9217. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  9218. if (desc && desc.sdp) {
  9219. var sb = desc.sdp.split('\r\n');
  9220. this._updateRemoteMaps(sb);
  9221. this._cacheRemoteVideoSources(sb);
  9222. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  9223. // need the simulcast group in the _updateRemoteMaps() method.
  9224. this.simulcastUtils._removeSimulcastGroup(sb);
  9225. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  9226. // We don't need the goog conference flag if we're not doing
  9227. // simulcast.
  9228. this._ensureGoogConference(sb);
  9229. }
  9230. desc = new RTCSessionDescription({
  9231. type: desc.type,
  9232. sdp: sb.join('\r\n')
  9233. });
  9234. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  9235. }
  9236. return desc;
  9237. };
  9238. module.exports = SimulcastReceiver;
  9239. },{"../../service/RTC/MediaStreamTypes":94,"./SimulcastLogger":42,"./SimulcastUtils":45}],44:[function(require,module,exports){
  9240. var SimulcastLogger = require("./SimulcastLogger");
  9241. var SimulcastUtils = require("./SimulcastUtils");
  9242. function SimulcastSender() {
  9243. this.simulcastUtils = new SimulcastUtils();
  9244. this.logger = new SimulcastLogger('SimulcastSender', 1);
  9245. }
  9246. SimulcastSender.prototype.displayedLocalVideoStream = null;
  9247. SimulcastSender.prototype._generateGuid = (function () {
  9248. function s4() {
  9249. return Math.floor((1 + Math.random()) * 0x10000)
  9250. .toString(16)
  9251. .substring(1);
  9252. }
  9253. return function () {
  9254. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  9255. s4() + '-' + s4() + s4() + s4();
  9256. };
  9257. }());
  9258. // Returns a random integer between min (included) and max (excluded)
  9259. // Using Math.round() gives a non-uniform distribution!
  9260. SimulcastSender.prototype._generateRandomSSRC = function () {
  9261. var min = 0, max = 0xffffffff;
  9262. return Math.floor(Math.random() * (max - min)) + min;
  9263. };
  9264. SimulcastSender.prototype.getLocalVideoStream = function () {
  9265. return (this.displayedLocalVideoStream != null)
  9266. ? this.displayedLocalVideoStream
  9267. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  9268. : APP.RTC.localVideo.getOriginalStream();
  9269. };
  9270. function NativeSimulcastSender() {
  9271. SimulcastSender.call(this); // call the super constructor.
  9272. }
  9273. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9274. NativeSimulcastSender.prototype._localExplosionMap = {};
  9275. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  9276. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  9277. NativeSimulcastSender.prototype.reset = function () {
  9278. this._localExplosionMap = {};
  9279. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  9280. };
  9281. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  9282. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  9283. };
  9284. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  9285. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  9286. };
  9287. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  9288. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  9289. this.logger.info('Appending simulcast group...');
  9290. // Get the primary SSRC information.
  9291. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  9292. // Start building the SIM SSRC group.
  9293. ssrcGroup = ['a=ssrc-group:SIM'];
  9294. // The video source buffer.
  9295. sb = [];
  9296. // Create the simulcast sub-streams.
  9297. for (i = 0; i < numOfSubs; i++) {
  9298. // TODO(gp) prevent SSRC collision.
  9299. simSSRC = this._generateRandomSSRC();
  9300. ssrcGroup.push(simSSRC);
  9301. if (videoSources.base) {
  9302. sb.splice.apply(sb, [sb.length, 0].concat(
  9303. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  9304. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  9305. ));
  9306. }
  9307. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  9308. }
  9309. // Add the group sim layers.
  9310. sb.splice(0, 0, ssrcGroup.join(' '))
  9311. this.simulcastUtils._replaceVideoSources(lines, sb);
  9312. };
  9313. // Does the actual patching.
  9314. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  9315. this.logger.info('Ensuring simulcast group...');
  9316. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  9317. this._appendSimulcastGroup(lines);
  9318. this._cacheLocalVideoSources(lines);
  9319. } else {
  9320. // verify that the ssrcs participating in the SIM group are present
  9321. // in the SDP (needed for presence).
  9322. this._restoreLocalVideoSources(lines);
  9323. }
  9324. };
  9325. /**
  9326. * Produces a single stream with multiple tracks for local video sources.
  9327. *
  9328. * @param lines
  9329. * @private
  9330. */
  9331. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  9332. var sb, msid, sid, tid, videoSources, self;
  9333. this.logger.info('Exploding local video sources...');
  9334. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  9335. self = this;
  9336. if (videoSources.groups && videoSources.groups.length !== 0) {
  9337. videoSources.groups.forEach(function (group) {
  9338. if (group.semantics === 'SIM') {
  9339. group.ssrcs.forEach(function (ssrc) {
  9340. // Get the msid for this ssrc..
  9341. if (self._localExplosionMap[ssrc]) {
  9342. // .. either from the explosion map..
  9343. msid = self._localExplosionMap[ssrc];
  9344. } else {
  9345. // .. or generate a new one (msid).
  9346. sid = videoSources.sources[ssrc].msid
  9347. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  9348. tid = self._generateGuid();
  9349. msid = [sid, tid].join(' ');
  9350. self._localExplosionMap[ssrc] = msid;
  9351. }
  9352. // Assign it to the source object.
  9353. videoSources.sources[ssrc].msid = msid;
  9354. // TODO(gp) Change the msid of associated sources.
  9355. });
  9356. }
  9357. });
  9358. }
  9359. sb = this.simulcastUtils._compileVideoSources(videoSources);
  9360. this.simulcastUtils._replaceVideoSources(lines, sb);
  9361. };
  9362. /**
  9363. * GUM for simulcast.
  9364. *
  9365. * @param constraints
  9366. * @param success
  9367. * @param err
  9368. */
  9369. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9370. // There's nothing special to do for native simulcast, so just do a normal GUM.
  9371. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9372. success(hqStream);
  9373. }, err);
  9374. };
  9375. /**
  9376. * Prepares the local description for public usage (i.e. to be signaled
  9377. * through Jingle to the focus).
  9378. *
  9379. * @param desc
  9380. * @returns {RTCSessionDescription}
  9381. */
  9382. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9383. var sb;
  9384. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  9385. return desc;
  9386. }
  9387. sb = desc.sdp.split('\r\n');
  9388. this._explodeSimulcastSenderSources(sb);
  9389. desc = new RTCSessionDescription({
  9390. type: desc.type,
  9391. sdp: sb.join('\r\n')
  9392. });
  9393. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  9394. return desc;
  9395. };
  9396. /**
  9397. * Ensures that the simulcast group is present in the answer, _if_ native
  9398. * simulcast is enabled,
  9399. *
  9400. * @param desc
  9401. * @returns {*}
  9402. */
  9403. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  9404. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  9405. return desc;
  9406. }
  9407. var sb = desc.sdp.split('\r\n');
  9408. // Even if we have enabled native simulcasting previously
  9409. // (with a call to SLD with an appropriate SDP, for example),
  9410. // createAnswer seems to consistently generate incomplete SDP
  9411. // with missing SSRCS.
  9412. //
  9413. // So, subsequent calls to SLD will have missing SSRCS and presence
  9414. // won't have the complete list of SRCs.
  9415. this._ensureSimulcastGroup(sb);
  9416. desc = new RTCSessionDescription({
  9417. type: desc.type,
  9418. sdp: sb.join('\r\n')
  9419. });
  9420. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  9421. return desc;
  9422. };
  9423. /**
  9424. *
  9425. *
  9426. * @param desc
  9427. * @returns {*}
  9428. */
  9429. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9430. return desc;
  9431. };
  9432. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9433. // Nothing to do here, native simulcast does that auto-magically.
  9434. };
  9435. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  9436. function SimpleSimulcastSender() {
  9437. SimulcastSender.call(this);
  9438. }
  9439. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9440. SimpleSimulcastSender.prototype.localStream = null;
  9441. SimpleSimulcastSender.prototype._localMaps = {
  9442. msids: [],
  9443. msid2ssrc: {}
  9444. };
  9445. /**
  9446. * Groups local video sources together in the ssrc-group:SIM group.
  9447. *
  9448. * @param lines
  9449. * @private
  9450. */
  9451. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  9452. var sb, videoSources, ssrcs = [], ssrc;
  9453. this.logger.info('Grouping local video sources...');
  9454. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  9455. for (ssrc in videoSources.sources) {
  9456. // jitsi-meet destroys/creates streams at various places causing
  9457. // the original local stream ids to change. The only thing that
  9458. // remains unchanged is the trackid.
  9459. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  9460. }
  9461. var self = this;
  9462. // TODO(gp) add only "free" sources.
  9463. this._localMaps.msids.forEach(function (msid) {
  9464. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  9465. });
  9466. if (!videoSources.groups) {
  9467. videoSources.groups = [];
  9468. }
  9469. videoSources.groups.push({
  9470. 'semantics': 'SIM',
  9471. 'ssrcs': ssrcs
  9472. });
  9473. sb = this.simulcastUtils._compileVideoSources(videoSources);
  9474. this.simulcastUtils._replaceVideoSources(lines, sb);
  9475. };
  9476. /**
  9477. * GUM for simulcast.
  9478. *
  9479. * @param constraints
  9480. * @param success
  9481. * @param err
  9482. */
  9483. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9484. // TODO(gp) what if we request a resolution not supported by the hardware?
  9485. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  9486. var lqConstraints = {
  9487. audio: false,
  9488. video: {
  9489. mandatory: {
  9490. maxWidth: 320,
  9491. maxHeight: 180,
  9492. maxFrameRate: 15
  9493. }
  9494. }
  9495. };
  9496. this.logger.info('HQ constraints: ', constraints);
  9497. this.logger.info('LQ constraints: ', lqConstraints);
  9498. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  9499. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  9500. // reason appears to be that Chrome only acquires the cam once and
  9501. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  9502. var self = this;
  9503. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9504. self.localStream = hqStream;
  9505. // reset local maps.
  9506. self._localMaps.msids = [];
  9507. self._localMaps.msid2ssrc = {};
  9508. // add hq trackid to local map
  9509. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  9510. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  9511. self.displayedLocalVideoStream = lqStream;
  9512. // NOTE(gp) The specification says Array.forEach() will visit
  9513. // the array elements in numeric order, and that it doesn't
  9514. // visit elements that don't exist.
  9515. // add lq trackid to local map
  9516. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  9517. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  9518. success(self.localStream);
  9519. }, err);
  9520. }, err);
  9521. };
  9522. /**
  9523. * Prepares the local description for public usage (i.e. to be signaled
  9524. * through Jingle to the focus).
  9525. *
  9526. * @param desc
  9527. * @returns {RTCSessionDescription}
  9528. */
  9529. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9530. var sb;
  9531. if (!this.simulcastUtils.isValidDescription(desc)) {
  9532. return desc;
  9533. }
  9534. sb = desc.sdp.split('\r\n');
  9535. this._groupLocalVideoSources(sb);
  9536. desc = new RTCSessionDescription({
  9537. type: desc.type,
  9538. sdp: sb.join('\r\n')
  9539. });
  9540. this.logger.fine('Grouped local video sources');
  9541. this.logger.fine(desc.sdp);
  9542. return desc;
  9543. };
  9544. /**
  9545. * Ensures that the simulcast group is present in the answer, _if_ native
  9546. * simulcast is enabled,
  9547. *
  9548. * @param desc
  9549. * @returns {*}
  9550. */
  9551. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  9552. return desc;
  9553. };
  9554. /**
  9555. *
  9556. *
  9557. * @param desc
  9558. * @returns {*}
  9559. */
  9560. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9561. var sb = desc.sdp.split('\r\n');
  9562. this.simulcastUtils._removeSimulcastGroup(sb);
  9563. desc = new RTCSessionDescription({
  9564. type: desc.type,
  9565. sdp: sb.join('\r\n')
  9566. });
  9567. this.logger.fine('Transformed local description');
  9568. this.logger.fine(desc.sdp);
  9569. return desc;
  9570. };
  9571. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9572. var trackid;
  9573. var self = this;
  9574. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  9575. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  9576. // Search for the track id that corresponds to the ssrc
  9577. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  9578. trackid = tid;
  9579. return true;
  9580. }
  9581. }) && self.localStream.getVideoTracks().some(function (track) {
  9582. // Start/stop the track that corresponds to the track id
  9583. if (track.id === trackid) {
  9584. track.enabled = enabled;
  9585. return true;
  9586. }
  9587. })) {
  9588. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  9589. $(document).trigger(enabled
  9590. ? 'simulcastlayerstarted'
  9591. : 'simulcastlayerstopped');
  9592. } else {
  9593. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  9594. }
  9595. };
  9596. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  9597. function NoSimulcastSender() {
  9598. SimulcastSender.call(this);
  9599. }
  9600. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9601. /**
  9602. * GUM for simulcast.
  9603. *
  9604. * @param constraints
  9605. * @param success
  9606. * @param err
  9607. */
  9608. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9609. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9610. success(hqStream);
  9611. }, err);
  9612. };
  9613. /**
  9614. * Prepares the local description for public usage (i.e. to be signaled
  9615. * through Jingle to the focus).
  9616. *
  9617. * @param desc
  9618. * @returns {RTCSessionDescription}
  9619. */
  9620. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9621. return desc;
  9622. };
  9623. /**
  9624. * Ensures that the simulcast group is present in the answer, _if_ native
  9625. * simulcast is enabled,
  9626. *
  9627. * @param desc
  9628. * @returns {*}
  9629. */
  9630. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  9631. return desc;
  9632. };
  9633. /**
  9634. *
  9635. *
  9636. * @param desc
  9637. * @returns {*}
  9638. */
  9639. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9640. return desc;
  9641. };
  9642. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9643. };
  9644. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  9645. module.exports = {
  9646. "native": NativeSimulcastSender,
  9647. "no": NoSimulcastSender
  9648. }
  9649. },{"./SimulcastLogger":42,"./SimulcastUtils":45}],45:[function(require,module,exports){
  9650. var SimulcastLogger = require("./SimulcastLogger");
  9651. /**
  9652. *
  9653. * @constructor
  9654. */
  9655. function SimulcastUtils() {
  9656. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  9657. }
  9658. /**
  9659. *
  9660. * @type {{}}
  9661. * @private
  9662. */
  9663. SimulcastUtils.prototype._emptyCompoundIndex = {};
  9664. /**
  9665. *
  9666. * @param lines
  9667. * @param videoSources
  9668. * @private
  9669. */
  9670. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  9671. var i, inVideo = false, index = -1, howMany = 0;
  9672. this.logger.info('Replacing video sources...');
  9673. for (i = 0; i < lines.length; i++) {
  9674. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9675. // Out of video.
  9676. break;
  9677. }
  9678. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9679. // In video.
  9680. inVideo = true;
  9681. }
  9682. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  9683. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  9684. if (index === -1) {
  9685. index = i;
  9686. }
  9687. howMany++;
  9688. }
  9689. }
  9690. // efficiency baby ;)
  9691. lines.splice.apply(lines,
  9692. [index, howMany].concat(videoSources));
  9693. };
  9694. SimulcastUtils.prototype.isValidDescription = function (desc)
  9695. {
  9696. return desc && desc != null
  9697. && desc.type && desc.type != ''
  9698. && desc.sdp && desc.sdp != '';
  9699. };
  9700. SimulcastUtils.prototype._getVideoSources = function (lines) {
  9701. var i, inVideo = false, sb = [];
  9702. this.logger.info('Getting video sources...');
  9703. for (i = 0; i < lines.length; i++) {
  9704. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9705. // Out of video.
  9706. break;
  9707. }
  9708. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9709. // In video.
  9710. inVideo = true;
  9711. }
  9712. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9713. // In SSRC.
  9714. sb.push(lines[i]);
  9715. }
  9716. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9717. sb.push(lines[i]);
  9718. }
  9719. }
  9720. return sb;
  9721. };
  9722. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  9723. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  9724. ssrc_attribute, group, semantics, skip = true;
  9725. this.logger.info('Parsing media sources...');
  9726. for (i = 0; i < lines.length; i++) {
  9727. if (lines[i].substring(0, 'm='.length) === 'm=') {
  9728. type = lines[i]
  9729. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  9730. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  9731. if (!skip) {
  9732. cur_media = {
  9733. 'type': type,
  9734. 'sources': {},
  9735. 'groups': []
  9736. };
  9737. res.push(cur_media);
  9738. }
  9739. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9740. idx = lines[i].indexOf(' ');
  9741. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  9742. if (cur_media.sources[ssrc] === undefined) {
  9743. cur_ssrc = {'ssrc': ssrc};
  9744. cur_media.sources[ssrc] = cur_ssrc;
  9745. }
  9746. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  9747. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  9748. if (cur_media.base === undefined) {
  9749. cur_media.base = cur_ssrc;
  9750. }
  9751. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9752. idx = lines[i].indexOf(' ');
  9753. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  9754. ssrcs = lines[i].substr(idx).trim().split(' ');
  9755. group = {
  9756. 'semantics': semantics,
  9757. 'ssrcs': ssrcs
  9758. };
  9759. cur_media.groups.push(group);
  9760. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  9761. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  9762. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  9763. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  9764. cur_media.direction = lines[i].substring('a='.length);
  9765. }
  9766. }
  9767. return res;
  9768. };
  9769. /**
  9770. * The _indexOfArray() method returns the first a CompoundIndex at which a
  9771. * given element can be found in the array, or _emptyCompoundIndex if it is
  9772. * not present.
  9773. *
  9774. * Example:
  9775. *
  9776. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  9777. *
  9778. * returns {row: 2, column: 14}
  9779. *
  9780. * @param needle
  9781. * @param haystack
  9782. * @param start
  9783. * @returns {}
  9784. * @private
  9785. */
  9786. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  9787. var length = haystack.length, idx, i;
  9788. if (!start) {
  9789. start = 0;
  9790. }
  9791. for (i = start; i < length; i++) {
  9792. idx = haystack[i].indexOf(needle);
  9793. if (idx !== -1) {
  9794. return {row: i, column: idx};
  9795. }
  9796. }
  9797. return this._emptyCompoundIndex;
  9798. };
  9799. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  9800. var i;
  9801. for (i = lines.length - 1; i >= 0; i--) {
  9802. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  9803. lines.splice(i, 1);
  9804. }
  9805. }
  9806. };
  9807. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  9808. var sb = [], ssrc, addedSSRCs = [];
  9809. this.logger.info('Compiling video sources...');
  9810. // Add the groups
  9811. if (videoSources.groups && videoSources.groups.length !== 0) {
  9812. videoSources.groups.forEach(function (group) {
  9813. if (group.ssrcs && group.ssrcs.length !== 0) {
  9814. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  9815. // if (group.semantics !== 'SIM') {
  9816. group.ssrcs.forEach(function (ssrc) {
  9817. addedSSRCs.push(ssrc);
  9818. sb.splice.apply(sb, [sb.length, 0].concat([
  9819. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9820. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9821. });
  9822. //}
  9823. }
  9824. });
  9825. }
  9826. // Then add any free sources.
  9827. if (videoSources.sources) {
  9828. for (ssrc in videoSources.sources) {
  9829. if (addedSSRCs.indexOf(ssrc) === -1) {
  9830. sb.splice.apply(sb, [sb.length, 0].concat([
  9831. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9832. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9833. }
  9834. }
  9835. }
  9836. return sb;
  9837. };
  9838. module.exports = SimulcastUtils;
  9839. },{"./SimulcastLogger":42}],46:[function(require,module,exports){
  9840. /*jslint plusplus: true */
  9841. /*jslint nomen: true*/
  9842. var SimulcastSender = require("./SimulcastSender");
  9843. var NoSimulcastSender = SimulcastSender["no"];
  9844. var NativeSimulcastSender = SimulcastSender["native"];
  9845. var SimulcastReceiver = require("./SimulcastReceiver");
  9846. var SimulcastUtils = require("./SimulcastUtils");
  9847. var RTCEvents = require("../../service/RTC/RTCEvents");
  9848. /**
  9849. *
  9850. * @constructor
  9851. */
  9852. function SimulcastManager() {
  9853. // Create the simulcast utilities.
  9854. this.simulcastUtils = new SimulcastUtils();
  9855. // Create remote simulcast.
  9856. this.simulcastReceiver = new SimulcastReceiver();
  9857. // Initialize local simulcast.
  9858. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  9859. // account constraints.
  9860. if (!config.enableSimulcast) {
  9861. this.simulcastSender = new NoSimulcastSender();
  9862. } else {
  9863. var isChromium = window.chrome,
  9864. vendorName = window.navigator.vendor;
  9865. if(isChromium !== null && isChromium !== undefined
  9866. /* skip opera */
  9867. && vendorName === "Google Inc."
  9868. /* skip Chromium as suggested by fippo */
  9869. && !window.navigator.appVersion.match(/Chromium\//) ) {
  9870. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  9871. if (ver > 37) {
  9872. this.simulcastSender = new NativeSimulcastSender();
  9873. } else {
  9874. this.simulcastSender = new NoSimulcastSender();
  9875. }
  9876. } else {
  9877. this.simulcastSender = new NoSimulcastSender();
  9878. }
  9879. }
  9880. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  9881. function (endpointSimulcastLayers) {
  9882. endpointSimulcastLayers.forEach(function (esl) {
  9883. var ssrc = esl.simulcastLayer.primarySSRC;
  9884. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  9885. });
  9886. });
  9887. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  9888. var ssrc = simulcastLayer.primarySSRC;
  9889. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  9890. });
  9891. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  9892. var ssrc = simulcastLayer.primarySSRC;
  9893. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  9894. });
  9895. }
  9896. /**
  9897. * Restores the simulcast groups of the remote description. In
  9898. * transformRemoteDescription we remove those in order for the set remote
  9899. * description to succeed. The focus needs the signal the groups to new
  9900. * participants.
  9901. *
  9902. * @param desc
  9903. * @returns {*}
  9904. */
  9905. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  9906. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  9907. };
  9908. /**
  9909. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9910. * either gets confused and thinks this is an FID group or, if an FID group
  9911. * is already present, it fails to set the remote description.
  9912. *
  9913. * @param desc
  9914. * @returns {*}
  9915. */
  9916. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  9917. return this.simulcastReceiver.transformRemoteDescription(desc);
  9918. };
  9919. /**
  9920. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9921. * SSRC.
  9922. *
  9923. * @param ssrc
  9924. * @returns {*}
  9925. */
  9926. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9927. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  9928. };
  9929. /**
  9930. * Returns a stream with single video track, the one currently being
  9931. * received by this endpoint.
  9932. *
  9933. * @param stream the remote simulcast stream.
  9934. * @returns {webkitMediaStream}
  9935. */
  9936. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  9937. return this.simulcastReceiver.getReceivingVideoStream(stream);
  9938. };
  9939. /**
  9940. *
  9941. *
  9942. * @param desc
  9943. * @returns {*}
  9944. */
  9945. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  9946. return this.simulcastSender.transformLocalDescription(desc);
  9947. };
  9948. /**
  9949. *
  9950. * @returns {*}
  9951. */
  9952. SimulcastManager.prototype.getLocalVideoStream = function() {
  9953. return this.simulcastSender.getLocalVideoStream();
  9954. };
  9955. /**
  9956. * GUM for simulcast.
  9957. *
  9958. * @param constraints
  9959. * @param success
  9960. * @param err
  9961. */
  9962. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  9963. this.simulcastSender.getUserMedia(constraints, success, err);
  9964. };
  9965. /**
  9966. * Prepares the local description for public usage (i.e. to be signaled
  9967. * through Jingle to the focus).
  9968. *
  9969. * @param desc
  9970. * @returns {RTCSessionDescription}
  9971. */
  9972. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  9973. return this.simulcastSender.reverseTransformLocalDescription(desc);
  9974. };
  9975. /**
  9976. * Ensures that the simulcast group is present in the answer, _if_ native
  9977. * simulcast is enabled,
  9978. *
  9979. * @param desc
  9980. * @returns {*}
  9981. */
  9982. SimulcastManager.prototype.transformAnswer = function (desc) {
  9983. return this.simulcastSender.transformAnswer(desc);
  9984. };
  9985. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  9986. return this.simulcastReceiver.getReceivingSSRC(jid);
  9987. };
  9988. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  9989. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  9990. };
  9991. /**
  9992. *
  9993. * @param lines
  9994. * @param mediatypes
  9995. * @returns {*}
  9996. */
  9997. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  9998. var sb = lines.sdp.split('\r\n');
  9999. return this.simulcastUtils.parseMedia(sb, mediatypes);
  10000. };
  10001. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  10002. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  10003. };
  10004. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  10005. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  10006. };
  10007. SimulcastManager.prototype.resetSender = function() {
  10008. if (typeof this.simulcastSender.reset === 'function'){
  10009. this.simulcastSender.reset();
  10010. }
  10011. };
  10012. var simulcast = new SimulcastManager();
  10013. module.exports = simulcast;
  10014. },{"../../service/RTC/RTCEvents":96,"./SimulcastReceiver":43,"./SimulcastSender":44,"./SimulcastUtils":45}],47:[function(require,module,exports){
  10015. /**
  10016. * Provides statistics for the local stream.
  10017. */
  10018. /**
  10019. * Size of the webaudio analizer buffer.
  10020. * @type {number}
  10021. */
  10022. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  10023. /**
  10024. * Value of the webaudio analizer smoothing time parameter.
  10025. * @type {number}
  10026. */
  10027. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  10028. /**
  10029. * Converts time domain data array to audio level.
  10030. * @param array the time domain data array.
  10031. * @returns {number} the audio level
  10032. */
  10033. function timeDomainDataToAudioLevel(samples) {
  10034. var maxVolume = 0;
  10035. var length = samples.length;
  10036. for (var i = 0; i < length; i++) {
  10037. if (maxVolume < samples[i])
  10038. maxVolume = samples[i];
  10039. }
  10040. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  10041. };
  10042. /**
  10043. * Animates audio level change
  10044. * @param newLevel the new audio level
  10045. * @param lastLevel the last audio level
  10046. * @returns {Number} the audio level to be set
  10047. */
  10048. function animateLevel(newLevel, lastLevel)
  10049. {
  10050. var value = 0;
  10051. var diff = lastLevel - newLevel;
  10052. if(diff > 0.2)
  10053. {
  10054. value = lastLevel - 0.2;
  10055. }
  10056. else if(diff < -0.4)
  10057. {
  10058. value = lastLevel + 0.4;
  10059. }
  10060. else
  10061. {
  10062. value = newLevel;
  10063. }
  10064. return parseFloat(value.toFixed(3));
  10065. }
  10066. /**
  10067. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  10068. *
  10069. * @param stream the local stream
  10070. * @param interval stats refresh interval given in ms.
  10071. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  10072. * update.
  10073. * @constructor
  10074. */
  10075. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  10076. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  10077. this.stream = stream;
  10078. this.intervalId = null;
  10079. this.intervalMilis = interval;
  10080. this.eventEmitter = eventEmitter;
  10081. this.audioLevel = 0;
  10082. this.statisticsService = statisticsService;
  10083. }
  10084. /**
  10085. * Starts the collecting the statistics.
  10086. */
  10087. LocalStatsCollector.prototype.start = function () {
  10088. if (config.disableAudioLevels || !window.AudioContext)
  10089. return;
  10090. var context = new AudioContext();
  10091. var analyser = context.createAnalyser();
  10092. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  10093. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  10094. var source = context.createMediaStreamSource(this.stream);
  10095. source.connect(analyser);
  10096. var self = this;
  10097. this.intervalId = setInterval(
  10098. function () {
  10099. var array = new Uint8Array(analyser.frequencyBinCount);
  10100. analyser.getByteTimeDomainData(array);
  10101. var audioLevel = timeDomainDataToAudioLevel(array);
  10102. if(audioLevel != self.audioLevel) {
  10103. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10104. self.eventEmitter.emit(
  10105. "statistics.audioLevel",
  10106. self.statisticsService.LOCAL_JID,
  10107. self.audioLevel);
  10108. }
  10109. },
  10110. this.intervalMilis
  10111. );
  10112. };
  10113. /**
  10114. * Stops collecting the statistics.
  10115. */
  10116. LocalStatsCollector.prototype.stop = function () {
  10117. if (this.intervalId) {
  10118. clearInterval(this.intervalId);
  10119. this.intervalId = null;
  10120. }
  10121. };
  10122. module.exports = LocalStatsCollector;
  10123. },{}],48:[function(require,module,exports){
  10124. /* global ssrc2jid */
  10125. /* jshint -W117 */
  10126. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10127. /**
  10128. * Calculates packet lost percent using the number of lost packets and the
  10129. * number of all packet.
  10130. * @param lostPackets the number of lost packets
  10131. * @param totalPackets the number of all packets.
  10132. * @returns {number} packet loss percent
  10133. */
  10134. function calculatePacketLoss(lostPackets, totalPackets) {
  10135. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  10136. return 0;
  10137. return Math.round((lostPackets/totalPackets)*100);
  10138. }
  10139. function getStatValue(item, name) {
  10140. if(!keyMap[APP.RTC.getBrowserType()][name])
  10141. throw "The property isn't supported!";
  10142. var key = keyMap[APP.RTC.getBrowserType()][name];
  10143. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  10144. }
  10145. /**
  10146. * Peer statistics data holder.
  10147. * @constructor
  10148. */
  10149. function PeerStats()
  10150. {
  10151. this.ssrc2Loss = {};
  10152. this.ssrc2AudioLevel = {};
  10153. this.ssrc2bitrate = {};
  10154. this.ssrc2resolution = {};
  10155. }
  10156. /**
  10157. * The bandwidth
  10158. * @type {{}}
  10159. */
  10160. PeerStats.bandwidth = {};
  10161. /**
  10162. * The bit rate
  10163. * @type {{}}
  10164. */
  10165. PeerStats.bitrate = {};
  10166. /**
  10167. * The packet loss rate
  10168. * @type {{}}
  10169. */
  10170. PeerStats.packetLoss = null;
  10171. /**
  10172. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  10173. * represented by this instance.
  10174. * @param ssrc audio or video RTP stream SSRC.
  10175. * @param lossRate new packet loss rate value to be set.
  10176. */
  10177. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  10178. {
  10179. this.ssrc2Loss[ssrc] = lossRate;
  10180. };
  10181. /**
  10182. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  10183. * represented by this instance.
  10184. * @param ssrc audio or video RTP stream SSRC.
  10185. * @param resolution new resolution value to be set.
  10186. */
  10187. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  10188. {
  10189. if(resolution === null && this.ssrc2resolution[ssrc])
  10190. {
  10191. delete this.ssrc2resolution[ssrc];
  10192. }
  10193. else if(resolution !== null)
  10194. this.ssrc2resolution[ssrc] = resolution;
  10195. };
  10196. /**
  10197. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  10198. * represented by this instance.
  10199. * @param ssrc audio or video RTP stream SSRC.
  10200. * @param bitrate new bitrate value to be set.
  10201. */
  10202. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  10203. {
  10204. if(this.ssrc2bitrate[ssrc])
  10205. {
  10206. this.ssrc2bitrate[ssrc].download += bitrate.download;
  10207. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  10208. }
  10209. else {
  10210. this.ssrc2bitrate[ssrc] = bitrate;
  10211. }
  10212. };
  10213. /**
  10214. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  10215. * the stream which belongs to the peer represented by this instance.
  10216. * @param ssrc RTP stream SSRC for which current audio level value will be
  10217. * updated.
  10218. * @param audioLevel the new audio level value to be set. Value is truncated to
  10219. * fit the range from 0 to 1.
  10220. */
  10221. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  10222. {
  10223. // Range limit 0 - 1
  10224. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  10225. };
  10226. function formatAudioLevel(audioLevel) {
  10227. return Math.min(Math.max(audioLevel, 0), 1);
  10228. }
  10229. /**
  10230. * Array with the transport information.
  10231. * @type {Array}
  10232. */
  10233. PeerStats.transport = [];
  10234. /**
  10235. * <tt>StatsCollector</tt> registers for stats updates of given
  10236. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  10237. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  10238. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  10239. * instance as an event source.
  10240. *
  10241. * @param peerconnection webRTC peer connection object.
  10242. * @param interval stats refresh interval given in ms.
  10243. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  10244. * called on stats update.
  10245. * @constructor
  10246. */
  10247. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  10248. {
  10249. this.peerconnection = peerconnection;
  10250. this.baselineAudioLevelsReport = null;
  10251. this.currentAudioLevelsReport = null;
  10252. this.currentStatsReport = null;
  10253. this.baselineStatsReport = null;
  10254. this.audioLevelsIntervalId = null;
  10255. this.eventEmitter = eventEmitter;
  10256. /**
  10257. * Gather PeerConnection stats once every this many milliseconds.
  10258. */
  10259. this.GATHER_INTERVAL = 15000;
  10260. /**
  10261. * Log stats via the focus once every this many milliseconds.
  10262. */
  10263. this.LOG_INTERVAL = 60000;
  10264. /**
  10265. * Gather stats and store them in this.statsToBeLogged.
  10266. */
  10267. this.gatherStatsIntervalId = null;
  10268. /**
  10269. * Send the stats already saved in this.statsToBeLogged to be logged via
  10270. * the focus.
  10271. */
  10272. this.logStatsIntervalId = null;
  10273. /**
  10274. * Stores the statistics which will be send to the focus to be logged.
  10275. */
  10276. this.statsToBeLogged =
  10277. {
  10278. timestamps: [],
  10279. stats: {}
  10280. };
  10281. // Updates stats interval
  10282. this.audioLevelsIntervalMilis = audioLevelsInterval;
  10283. this.statsIntervalId = null;
  10284. this.statsIntervalMilis = statsInterval;
  10285. // Map of jids to PeerStats
  10286. this.jid2stats = {};
  10287. }
  10288. module.exports = StatsCollector;
  10289. /**
  10290. * Stops stats updates.
  10291. */
  10292. StatsCollector.prototype.stop = function () {
  10293. if (this.audioLevelsIntervalId) {
  10294. clearInterval(this.audioLevelsIntervalId);
  10295. this.audioLevelsIntervalId = null;
  10296. }
  10297. if (this.statsIntervalId)
  10298. {
  10299. clearInterval(this.statsIntervalId);
  10300. this.statsIntervalId = null;
  10301. }
  10302. if(this.logStatsIntervalId)
  10303. {
  10304. clearInterval(this.logStatsIntervalId);
  10305. this.logStatsIntervalId = null;
  10306. }
  10307. if(this.gatherStatsIntervalId)
  10308. {
  10309. clearInterval(this.gatherStatsIntervalId);
  10310. this.gatherStatsIntervalId = null;
  10311. }
  10312. };
  10313. /**
  10314. * Callback passed to <tt>getStats</tt> method.
  10315. * @param error an error that occurred on <tt>getStats</tt> call.
  10316. */
  10317. StatsCollector.prototype.errorCallback = function (error)
  10318. {
  10319. console.error("Get stats error", error);
  10320. this.stop();
  10321. };
  10322. /**
  10323. * Starts stats updates.
  10324. */
  10325. StatsCollector.prototype.start = function ()
  10326. {
  10327. var self = this;
  10328. if(!config.disableAudioLevels) {
  10329. this.audioLevelsIntervalId = setInterval(
  10330. function () {
  10331. // Interval updates
  10332. self.peerconnection.getStats(
  10333. function (report) {
  10334. var results = null;
  10335. if (!report || !report.result ||
  10336. typeof report.result != 'function') {
  10337. results = report;
  10338. }
  10339. else {
  10340. results = report.result();
  10341. }
  10342. //console.error("Got interval report", results);
  10343. self.currentAudioLevelsReport = results;
  10344. self.processAudioLevelReport();
  10345. self.baselineAudioLevelsReport =
  10346. self.currentAudioLevelsReport;
  10347. },
  10348. self.errorCallback
  10349. );
  10350. },
  10351. self.audioLevelsIntervalMilis
  10352. );
  10353. }
  10354. if(!config.disableStats && !navigator.mozGetUserMedia) {
  10355. this.statsIntervalId = setInterval(
  10356. function () {
  10357. // Interval updates
  10358. self.peerconnection.getStats(
  10359. function (report) {
  10360. var results = null;
  10361. if (!report || !report.result ||
  10362. typeof report.result != 'function') {
  10363. //firefox
  10364. results = report;
  10365. }
  10366. else {
  10367. //chrome
  10368. results = report.result();
  10369. }
  10370. //console.error("Got interval report", results);
  10371. self.currentStatsReport = results;
  10372. try {
  10373. self.processStatsReport();
  10374. }
  10375. catch (e) {
  10376. console.error("Unsupported key:" + e, e);
  10377. }
  10378. self.baselineStatsReport = self.currentStatsReport;
  10379. },
  10380. self.errorCallback
  10381. );
  10382. },
  10383. self.statsIntervalMilis
  10384. );
  10385. }
  10386. if (config.logStats && !navigator.mozGetUserMedia) {
  10387. this.gatherStatsIntervalId = setInterval(
  10388. function () {
  10389. self.peerconnection.getStats(
  10390. function (report) {
  10391. self.addStatsToBeLogged(report.result());
  10392. },
  10393. function () {
  10394. }
  10395. );
  10396. },
  10397. this.GATHER_INTERVAL
  10398. );
  10399. this.logStatsIntervalId = setInterval(
  10400. function() { self.logStats(); },
  10401. this.LOG_INTERVAL);
  10402. }
  10403. };
  10404. /**
  10405. * Checks whether a certain record should be included in the logged statistics.
  10406. */
  10407. function acceptStat(reportId, reportType, statName) {
  10408. if (reportType == "googCandidatePair" && statName == "googChannelId")
  10409. return false;
  10410. if (reportType == "ssrc") {
  10411. if (statName == "googTrackId" ||
  10412. statName == "transportId" ||
  10413. statName == "ssrc")
  10414. return false;
  10415. }
  10416. return true;
  10417. }
  10418. /**
  10419. * Checks whether a certain record should be included in the logged statistics.
  10420. */
  10421. function acceptReport(id, type) {
  10422. if (id.substring(0, 15) == "googCertificate" ||
  10423. id.substring(0, 9) == "googTrack" ||
  10424. id.substring(0, 20) == "googLibjingleSession")
  10425. return false;
  10426. if (type == "googComponent")
  10427. return false;
  10428. return true;
  10429. }
  10430. /**
  10431. * Converts the stats to the format used for logging, and saves the data in
  10432. * this.statsToBeLogged.
  10433. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  10434. */
  10435. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  10436. var self = this;
  10437. var num_records = this.statsToBeLogged.timestamps.length;
  10438. this.statsToBeLogged.timestamps.push(new Date().getTime());
  10439. reports.map(function (report) {
  10440. if (!acceptReport(report.id, report.type))
  10441. return;
  10442. var stat = self.statsToBeLogged.stats[report.id];
  10443. if (!stat) {
  10444. stat = self.statsToBeLogged.stats[report.id] = {};
  10445. }
  10446. stat.type = report.type;
  10447. report.names().map(function (name) {
  10448. if (!acceptStat(report.id, report.type, name))
  10449. return;
  10450. var values = stat[name];
  10451. if (!values) {
  10452. values = stat[name] = [];
  10453. }
  10454. while (values.length < num_records) {
  10455. values.push(null);
  10456. }
  10457. values.push(report.stat(name));
  10458. });
  10459. });
  10460. };
  10461. StatsCollector.prototype.logStats = function () {
  10462. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  10463. return;
  10464. // Reset the stats
  10465. this.statsToBeLogged.stats = {};
  10466. this.statsToBeLogged.timestamps = [];
  10467. };
  10468. var keyMap = {};
  10469. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  10470. "ssrc": "ssrc",
  10471. "packetsReceived": "packetsReceived",
  10472. "packetsLost": "packetsLost",
  10473. "packetsSent": "packetsSent",
  10474. "bytesReceived": "bytesReceived",
  10475. "bytesSent": "bytesSent"
  10476. };
  10477. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  10478. "receiveBandwidth": "googAvailableReceiveBandwidth",
  10479. "sendBandwidth": "googAvailableSendBandwidth",
  10480. "remoteAddress": "googRemoteAddress",
  10481. "transportType": "googTransportType",
  10482. "localAddress": "googLocalAddress",
  10483. "activeConnection": "googActiveConnection",
  10484. "ssrc": "ssrc",
  10485. "packetsReceived": "packetsReceived",
  10486. "packetsSent": "packetsSent",
  10487. "packetsLost": "packetsLost",
  10488. "bytesReceived": "bytesReceived",
  10489. "bytesSent": "bytesSent",
  10490. "googFrameHeightReceived": "googFrameHeightReceived",
  10491. "googFrameWidthReceived": "googFrameWidthReceived",
  10492. "googFrameHeightSent": "googFrameHeightSent",
  10493. "googFrameWidthSent": "googFrameWidthSent",
  10494. "audioInputLevel": "audioInputLevel",
  10495. "audioOutputLevel": "audioOutputLevel"
  10496. };
  10497. /**
  10498. * Stats processing logic.
  10499. */
  10500. StatsCollector.prototype.processStatsReport = function () {
  10501. if (!this.baselineStatsReport) {
  10502. return;
  10503. }
  10504. for (var idx in this.currentStatsReport) {
  10505. var now = this.currentStatsReport[idx];
  10506. try {
  10507. if (getStatValue(now, 'receiveBandwidth') ||
  10508. getStatValue(now, 'sendBandwidth')) {
  10509. PeerStats.bandwidth = {
  10510. "download": Math.round(
  10511. (getStatValue(now, 'receiveBandwidth')) / 1000),
  10512. "upload": Math.round(
  10513. (getStatValue(now, 'sendBandwidth')) / 1000)
  10514. };
  10515. }
  10516. }
  10517. catch(e){/*not supported*/}
  10518. if(now.type == 'googCandidatePair')
  10519. {
  10520. var ip, type, localIP, active;
  10521. try {
  10522. ip = getStatValue(now, 'remoteAddress');
  10523. type = getStatValue(now, "transportType");
  10524. localIP = getStatValue(now, "localAddress");
  10525. active = getStatValue(now, "activeConnection");
  10526. }
  10527. catch(e){/*not supported*/}
  10528. if(!ip || !type || !localIP || active != "true")
  10529. continue;
  10530. var addressSaved = false;
  10531. for(var i = 0; i < PeerStats.transport.length; i++)
  10532. {
  10533. if(PeerStats.transport[i].ip == ip &&
  10534. PeerStats.transport[i].type == type &&
  10535. PeerStats.transport[i].localip == localIP)
  10536. {
  10537. addressSaved = true;
  10538. }
  10539. }
  10540. if(addressSaved)
  10541. continue;
  10542. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  10543. continue;
  10544. }
  10545. if(now.type == "candidatepair")
  10546. {
  10547. if(now.state == "succeeded")
  10548. continue;
  10549. var local = this.currentStatsReport[now.localCandidateId];
  10550. var remote = this.currentStatsReport[now.remoteCandidateId];
  10551. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  10552. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  10553. }
  10554. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  10555. now.type != "inboundrtp") {
  10556. continue;
  10557. }
  10558. var before = this.baselineStatsReport[idx];
  10559. if (!before) {
  10560. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10561. continue;
  10562. }
  10563. var ssrc = getStatValue(now, 'ssrc');
  10564. if(!ssrc)
  10565. continue;
  10566. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10567. if (!jid && (Date.now() - now.timestamp) < 3000) {
  10568. console.warn("No jid for ssrc: " + ssrc);
  10569. continue;
  10570. }
  10571. var jidStats = this.jid2stats[jid];
  10572. if (!jidStats) {
  10573. jidStats = new PeerStats();
  10574. this.jid2stats[jid] = jidStats;
  10575. }
  10576. var isDownloadStream = true;
  10577. var key = 'packetsReceived';
  10578. if (!getStatValue(now, key))
  10579. {
  10580. isDownloadStream = false;
  10581. key = 'packetsSent';
  10582. if (!getStatValue(now, key))
  10583. {
  10584. console.warn("No packetsReceived nor packetSent stat found");
  10585. continue;
  10586. }
  10587. }
  10588. var packetsNow = getStatValue(now, key);
  10589. if(!packetsNow || packetsNow < 0)
  10590. packetsNow = 0;
  10591. var packetsBefore = getStatValue(before, key);
  10592. if(!packetsBefore || packetsBefore < 0)
  10593. packetsBefore = 0;
  10594. var packetRate = packetsNow - packetsBefore;
  10595. if(!packetRate || packetRate < 0)
  10596. packetRate = 0;
  10597. var currentLoss = getStatValue(now, 'packetsLost');
  10598. if(!currentLoss || currentLoss < 0)
  10599. currentLoss = 0;
  10600. var previousLoss = getStatValue(before, 'packetsLost');
  10601. if(!previousLoss || previousLoss < 0)
  10602. previousLoss = 0;
  10603. var lossRate = currentLoss - previousLoss;
  10604. if(!lossRate || lossRate < 0)
  10605. lossRate = 0;
  10606. var packetsTotal = (packetRate + lossRate);
  10607. jidStats.setSsrcLoss(ssrc,
  10608. {"packetsTotal": packetsTotal,
  10609. "packetsLost": lossRate,
  10610. "isDownloadStream": isDownloadStream});
  10611. var bytesReceived = 0, bytesSent = 0;
  10612. if(getStatValue(now, "bytesReceived"))
  10613. {
  10614. bytesReceived = getStatValue(now, "bytesReceived") -
  10615. getStatValue(before, "bytesReceived");
  10616. }
  10617. if(getStatValue(now, "bytesSent"))
  10618. {
  10619. bytesSent = getStatValue(now, "bytesSent") -
  10620. getStatValue(before, "bytesSent");
  10621. }
  10622. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  10623. if(bytesReceived <= 0 || time <= 0)
  10624. {
  10625. bytesReceived = 0;
  10626. }
  10627. else
  10628. {
  10629. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  10630. }
  10631. if(bytesSent <= 0 || time <= 0)
  10632. {
  10633. bytesSent = 0;
  10634. }
  10635. else
  10636. {
  10637. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  10638. }
  10639. jidStats.setSsrcBitrate(ssrc, {
  10640. "download": bytesReceived,
  10641. "upload": bytesSent});
  10642. var resolution = {height: null, width: null};
  10643. try {
  10644. if (getStatValue(now, "googFrameHeightReceived") &&
  10645. getStatValue(now, "googFrameWidthReceived")) {
  10646. resolution.height = getStatValue(now, "googFrameHeightReceived");
  10647. resolution.width = getStatValue(now, "googFrameWidthReceived");
  10648. }
  10649. else if (getStatValue(now, "googFrameHeightSent") &&
  10650. getStatValue(now, "googFrameWidthSent")) {
  10651. resolution.height = getStatValue(now, "googFrameHeightSent");
  10652. resolution.width = getStatValue(now, "googFrameWidthSent");
  10653. }
  10654. }
  10655. catch(e){/*not supported*/}
  10656. if(resolution.height && resolution.width)
  10657. {
  10658. jidStats.setSsrcResolution(ssrc, resolution);
  10659. }
  10660. else
  10661. {
  10662. jidStats.setSsrcResolution(ssrc, null);
  10663. }
  10664. }
  10665. var self = this;
  10666. // Jid stats
  10667. var totalPackets = {download: 0, upload: 0};
  10668. var lostPackets = {download: 0, upload: 0};
  10669. var bitrateDownload = 0;
  10670. var bitrateUpload = 0;
  10671. var resolutions = {};
  10672. Object.keys(this.jid2stats).forEach(
  10673. function (jid)
  10674. {
  10675. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  10676. function (ssrc)
  10677. {
  10678. var type = "upload";
  10679. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  10680. type = "download";
  10681. totalPackets[type] +=
  10682. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  10683. lostPackets[type] +=
  10684. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  10685. }
  10686. );
  10687. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  10688. function (ssrc) {
  10689. bitrateDownload +=
  10690. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  10691. bitrateUpload +=
  10692. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  10693. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  10694. }
  10695. );
  10696. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  10697. }
  10698. );
  10699. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  10700. PeerStats.packetLoss = {
  10701. total:
  10702. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  10703. totalPackets.download + totalPackets.upload),
  10704. download:
  10705. calculatePacketLoss(lostPackets.download, totalPackets.download),
  10706. upload:
  10707. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  10708. };
  10709. this.eventEmitter.emit("statistics.connectionstats",
  10710. {
  10711. "bitrate": PeerStats.bitrate,
  10712. "packetLoss": PeerStats.packetLoss,
  10713. "bandwidth": PeerStats.bandwidth,
  10714. "resolution": resolutions,
  10715. "transport": PeerStats.transport
  10716. });
  10717. PeerStats.transport = [];
  10718. };
  10719. /**
  10720. * Stats processing logic.
  10721. */
  10722. StatsCollector.prototype.processAudioLevelReport = function ()
  10723. {
  10724. if (!this.baselineAudioLevelsReport)
  10725. {
  10726. return;
  10727. }
  10728. for (var idx in this.currentAudioLevelsReport)
  10729. {
  10730. var now = this.currentAudioLevelsReport[idx];
  10731. if (now.type != 'ssrc')
  10732. {
  10733. continue;
  10734. }
  10735. var before = this.baselineAudioLevelsReport[idx];
  10736. if (!before)
  10737. {
  10738. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10739. continue;
  10740. }
  10741. var ssrc = getStatValue(now, 'ssrc');
  10742. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10743. if (!jid && (Date.now() - now.timestamp) < 3000)
  10744. {
  10745. console.warn("No jid for ssrc: " + ssrc);
  10746. continue;
  10747. }
  10748. var jidStats = this.jid2stats[jid];
  10749. if (!jidStats)
  10750. {
  10751. jidStats = new PeerStats();
  10752. this.jid2stats[jid] = jidStats;
  10753. }
  10754. // Audio level
  10755. var audioLevel = null;
  10756. try {
  10757. audioLevel = getStatValue(now, 'audioInputLevel');
  10758. if (!audioLevel)
  10759. audioLevel = getStatValue(now, 'audioOutputLevel');
  10760. }
  10761. catch(e) {/*not supported*/
  10762. console.warn("Audio Levels are not available in the statistics.");
  10763. clearInterval(this.audioLevelsIntervalId);
  10764. return;
  10765. }
  10766. if (audioLevel)
  10767. {
  10768. // TODO: can't find specs about what this value really is,
  10769. // but it seems to vary between 0 and around 32k.
  10770. audioLevel = audioLevel / 32767;
  10771. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  10772. if(jid != APP.xmpp.myJid())
  10773. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  10774. }
  10775. }
  10776. };
  10777. },{"../../service/RTC/RTCBrowserType":95}],49:[function(require,module,exports){
  10778. /**
  10779. * Created by hristo on 8/4/14.
  10780. */
  10781. var LocalStats = require("./LocalStatsCollector.js");
  10782. var RTPStats = require("./RTPStatsCollector.js");
  10783. var EventEmitter = require("events");
  10784. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  10785. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10786. var eventEmitter = new EventEmitter();
  10787. var localStats = null;
  10788. var rtpStats = null;
  10789. function stopLocal()
  10790. {
  10791. if(localStats)
  10792. {
  10793. localStats.stop();
  10794. localStats = null;
  10795. }
  10796. }
  10797. function stopRemote()
  10798. {
  10799. if(rtpStats)
  10800. {
  10801. rtpStats.stop();
  10802. eventEmitter.emit("statistics.stop");
  10803. rtpStats = null;
  10804. }
  10805. }
  10806. function startRemoteStats (peerconnection) {
  10807. if(rtpStats)
  10808. {
  10809. rtpStats.stop();
  10810. rtpStats = null;
  10811. }
  10812. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  10813. rtpStats.start();
  10814. }
  10815. function onStreamCreated(stream)
  10816. {
  10817. if(stream.getOriginalStream().getAudioTracks().length === 0)
  10818. return;
  10819. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  10820. eventEmitter);
  10821. localStats.start();
  10822. }
  10823. function onDisposeConference(onUnload) {
  10824. stopRemote();
  10825. if(onUnload) {
  10826. stopLocal();
  10827. eventEmitter.removeAllListeners();
  10828. }
  10829. }
  10830. var statistics =
  10831. {
  10832. /**
  10833. * Indicates that this audio level is for local jid.
  10834. * @type {string}
  10835. */
  10836. LOCAL_JID: 'local',
  10837. addAudioLevelListener: function(listener)
  10838. {
  10839. eventEmitter.on("statistics.audioLevel", listener);
  10840. },
  10841. removeAudioLevelListener: function(listener)
  10842. {
  10843. eventEmitter.removeListener("statistics.audioLevel", listener);
  10844. },
  10845. addConnectionStatsListener: function(listener)
  10846. {
  10847. eventEmitter.on("statistics.connectionstats", listener);
  10848. },
  10849. removeConnectionStatsListener: function(listener)
  10850. {
  10851. eventEmitter.removeListener("statistics.connectionstats", listener);
  10852. },
  10853. addRemoteStatsStopListener: function(listener)
  10854. {
  10855. eventEmitter.on("statistics.stop", listener);
  10856. },
  10857. removeRemoteStatsStopListener: function(listener)
  10858. {
  10859. eventEmitter.removeListener("statistics.stop", listener);
  10860. },
  10861. stop: function () {
  10862. stopLocal();
  10863. stopRemote();
  10864. if(eventEmitter)
  10865. {
  10866. eventEmitter.removeAllListeners();
  10867. }
  10868. },
  10869. stopRemoteStatistics: function()
  10870. {
  10871. stopRemote();
  10872. },
  10873. start: function () {
  10874. APP.RTC.addStreamListener(onStreamCreated,
  10875. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10876. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10877. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10878. startRemoteStats(event.peerconnection);
  10879. });
  10880. }
  10881. };
  10882. module.exports = statistics;
  10883. },{"../../service/RTC/StreamEventTypes.js":98,"../../service/xmpp/XMPPEvents":105,"./LocalStatsCollector.js":47,"./RTPStatsCollector.js":48,"events":106}],50:[function(require,module,exports){
  10884. var i18n = require("i18next-client");
  10885. var languages = require("../../service/translation/languages");
  10886. var Settings = require("../settings/Settings");
  10887. var DEFAULT_LANG = languages.EN;
  10888. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10889. return value.replace("__app__", interfaceConfig.APP_NAME);
  10890. });
  10891. var defaultOptions = {
  10892. detectLngQS: "lang",
  10893. useCookie: false,
  10894. fallbackLng: DEFAULT_LANG,
  10895. load: "unspecific",
  10896. resGetPath: 'lang/__ns__-__lng__.json',
  10897. ns: {
  10898. namespaces: ['main', 'languages'],
  10899. defaultNs: 'main'
  10900. },
  10901. lngWhitelist : languages.getLanguages(),
  10902. fallbackOnNull: true,
  10903. fallbackOnEmpty: true,
  10904. useDataAttrOptions: true,
  10905. defaultValueFromContent: false,
  10906. app: interfaceConfig.APP_NAME,
  10907. getAsync: false,
  10908. defaultValueFromContent: false,
  10909. customLoad: function(lng, ns, options, done) {
  10910. var resPath = "lang/__ns__-__lng__.json";
  10911. if(lng === languages.EN)
  10912. resPath = "lang/__ns__.json";
  10913. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10914. i18n.functions.ajax({
  10915. url: url,
  10916. success: function(data, status, xhr) {
  10917. i18n.functions.log('loaded: ' + url);
  10918. done(null, data);
  10919. },
  10920. error : function(xhr, status, error) {
  10921. if ((status && status == 200) ||
  10922. (xhr && xhr.status && xhr.status == 200)) {
  10923. // file loaded but invalid json, stop waste time !
  10924. i18n.functions.error('There is a typo in: ' + url);
  10925. } else if ((status && status == 404) ||
  10926. (xhr && xhr.status && xhr.status == 404)) {
  10927. i18n.functions.log('Does not exist: ' + url);
  10928. } else {
  10929. var theStatus = status ? status :
  10930. ((xhr && xhr.status) ? xhr.status : null);
  10931. i18n.functions.log(theStatus + ' when loading ' + url);
  10932. }
  10933. done(error, {});
  10934. },
  10935. dataType: "json",
  10936. async : options.getAsync
  10937. });
  10938. }
  10939. // options for caching
  10940. // useLocalStorage: true,
  10941. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10942. };
  10943. function initCompleted(t)
  10944. {
  10945. $("[data-i18n]").i18n();
  10946. }
  10947. function checkForParameter() {
  10948. var query = window.location.search.substring(1);
  10949. var vars = query.split("&");
  10950. for (var i=0;i<vars.length;i++) {
  10951. var pair = vars[i].split("=");
  10952. if(pair[0] == "lang")
  10953. {
  10954. return pair[1];
  10955. }
  10956. }
  10957. return null;
  10958. }
  10959. module.exports = {
  10960. init: function (lang) {
  10961. var options = defaultOptions;
  10962. if(!lang)
  10963. {
  10964. lang = checkForParameter();
  10965. if(!lang)
  10966. {
  10967. var settings = Settings.getSettings();
  10968. if(settings)
  10969. lang = settings.language;
  10970. }
  10971. }
  10972. if(lang) {
  10973. options.lng = lang;
  10974. }
  10975. i18n.init(options, initCompleted);
  10976. },
  10977. translateString: function (key, options) {
  10978. return i18n.t(key, options);
  10979. },
  10980. setLanguage: function (lang) {
  10981. if(!lang)
  10982. lang = DEFAULT_LANG;
  10983. i18n.setLng(lang, defaultOptions, initCompleted);
  10984. },
  10985. getCurrentLanguage: function () {
  10986. return i18n.lng();
  10987. },
  10988. translateElement: function (selector) {
  10989. selector.i18n();
  10990. },
  10991. generateTranslatonHTML: function (key, options) {
  10992. var str = "<span data-i18n=\"" + key + "\"";
  10993. if(options)
  10994. {
  10995. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10996. }
  10997. str += ">";
  10998. str += this.translateString(key, options);
  10999. str += "</span>";
  11000. return str;
  11001. }
  11002. };
  11003. },{"../../service/translation/languages":104,"../settings/Settings":41,"i18next-client":66}],51:[function(require,module,exports){
  11004. /* jshint -W117 */
  11005. var TraceablePeerConnection = require("./TraceablePeerConnection");
  11006. var SDPDiffer = require("./SDPDiffer");
  11007. var SDPUtil = require("./SDPUtil");
  11008. var SDP = require("./SDP");
  11009. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  11010. var async = require("async");
  11011. // Jingle stuff
  11012. function JingleSession(me, sid, connection, service) {
  11013. this.me = me;
  11014. this.sid = sid;
  11015. this.connection = connection;
  11016. this.initiator = null;
  11017. this.responder = null;
  11018. this.isInitiator = null;
  11019. this.peerjid = null;
  11020. this.state = null;
  11021. this.localSDP = null;
  11022. this.remoteSDP = null;
  11023. this.relayedStreams = [];
  11024. this.startTime = null;
  11025. this.stopTime = null;
  11026. this.media_constraints = null;
  11027. this.pc_constraints = null;
  11028. this.ice_config = {};
  11029. this.drip_container = [];
  11030. this.service = service;
  11031. this.usetrickle = true;
  11032. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  11033. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  11034. this.hadstuncandidate = false;
  11035. this.hadturncandidate = false;
  11036. this.lasticecandidate = false;
  11037. this.statsinterval = null;
  11038. this.reason = null;
  11039. this.addssrc = [];
  11040. this.removessrc = [];
  11041. this.pendingop = null;
  11042. this.switchstreams = false;
  11043. this.wait = true;
  11044. this.localStreamsSSRC = null;
  11045. /**
  11046. * The indicator which determines whether the (local) video has been muted
  11047. * in response to a user command in contrast to an automatic decision made
  11048. * by the application logic.
  11049. */
  11050. this.videoMuteByUser = false;
  11051. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  11052. // We start with the queue paused. We resume it when the signaling state is
  11053. // stable and the ice connection state is connected.
  11054. this.modifySourcesQueue.pause();
  11055. }
  11056. JingleSession.prototype.updateModifySourcesQueue = function() {
  11057. var signalingState = this.peerconnection.signalingState;
  11058. var iceConnectionState = this.peerconnection.iceConnectionState;
  11059. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  11060. this.modifySourcesQueue.resume();
  11061. } else {
  11062. this.modifySourcesQueue.pause();
  11063. }
  11064. };
  11065. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  11066. var self = this;
  11067. if (this.state !== null) {
  11068. console.error('attempt to initiate on session ' + this.sid +
  11069. 'in state ' + this.state);
  11070. return;
  11071. }
  11072. this.isInitiator = isInitiator;
  11073. this.state = 'pending';
  11074. this.initiator = isInitiator ? this.me : peerjid;
  11075. this.responder = !isInitiator ? this.me : peerjid;
  11076. this.peerjid = peerjid;
  11077. this.hadstuncandidate = false;
  11078. this.hadturncandidate = false;
  11079. this.lasticecandidate = false;
  11080. this.peerconnection
  11081. = new TraceablePeerConnection(
  11082. this.connection.jingle.ice_config,
  11083. this.connection.jingle.pc_constraints );
  11084. this.peerconnection.onicecandidate = function (event) {
  11085. self.sendIceCandidate(event.candidate);
  11086. };
  11087. this.peerconnection.onaddstream = function (event) {
  11088. if (event.stream.id !== 'default') {
  11089. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  11090. self.remoteStreamAdded(event);
  11091. } else {
  11092. // This is a recvonly stream. Clients that implement Unified Plan,
  11093. // such as Firefox use recvonly "streams/channels/tracks" for
  11094. // receiving remote stream/tracks, as opposed to Plan B where there
  11095. // are only 3 channels: audio, video and data.
  11096. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  11097. }
  11098. };
  11099. this.peerconnection.onremovestream = function (event) {
  11100. // Remove the stream from remoteStreams
  11101. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  11102. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  11103. };
  11104. this.peerconnection.onsignalingstatechange = function (event) {
  11105. if (!(self && self.peerconnection)) return;
  11106. self.updateModifySourcesQueue();
  11107. };
  11108. this.peerconnection.oniceconnectionstatechange = function (event) {
  11109. if (!(self && self.peerconnection)) return;
  11110. self.updateModifySourcesQueue();
  11111. switch (self.peerconnection.iceConnectionState) {
  11112. case 'connected':
  11113. this.startTime = new Date();
  11114. break;
  11115. case 'disconnected':
  11116. this.stopTime = new Date();
  11117. break;
  11118. }
  11119. onIceConnectionStateChange(self.sid, self);
  11120. };
  11121. // add any local and relayed stream
  11122. APP.RTC.localStreams.forEach(function(stream) {
  11123. self.peerconnection.addStream(stream.getOriginalStream());
  11124. });
  11125. this.relayedStreams.forEach(function(stream) {
  11126. self.peerconnection.addStream(stream);
  11127. });
  11128. };
  11129. function onIceConnectionStateChange(sid, session) {
  11130. switch (session.peerconnection.iceConnectionState) {
  11131. case 'checking':
  11132. session.timeChecking = (new Date()).getTime();
  11133. session.firstconnect = true;
  11134. break;
  11135. case 'completed': // on caller side
  11136. case 'connected':
  11137. if (session.firstconnect) {
  11138. session.firstconnect = false;
  11139. var metadata = {};
  11140. metadata.setupTime
  11141. = (new Date()).getTime() - session.timeChecking;
  11142. session.peerconnection.getStats(function (res) {
  11143. if(res && res.result) {
  11144. res.result().forEach(function (report) {
  11145. if (report.type == 'googCandidatePair' &&
  11146. report.stat('googActiveConnection') == 'true') {
  11147. metadata.localCandidateType
  11148. = report.stat('googLocalCandidateType');
  11149. metadata.remoteCandidateType
  11150. = report.stat('googRemoteCandidateType');
  11151. // log pair as well so we can get nice pie
  11152. // charts
  11153. metadata.candidatePair
  11154. = report.stat('googLocalCandidateType') +
  11155. ';' +
  11156. report.stat('googRemoteCandidateType');
  11157. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  11158. {
  11159. metadata.ipv6 = true;
  11160. }
  11161. }
  11162. });
  11163. }
  11164. });
  11165. }
  11166. break;
  11167. }
  11168. }
  11169. JingleSession.prototype.accept = function () {
  11170. var self = this;
  11171. this.state = 'active';
  11172. var pranswer = this.peerconnection.localDescription;
  11173. if (!pranswer || pranswer.type != 'pranswer') {
  11174. return;
  11175. }
  11176. console.log('going from pranswer to answer');
  11177. if (this.usetrickle) {
  11178. // remove candidates already sent from session-accept
  11179. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  11180. for (var i = 0; i < lines.length; i++) {
  11181. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  11182. }
  11183. }
  11184. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  11185. // FIXME: change any inactive to sendrecv or whatever they were originally
  11186. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  11187. }
  11188. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  11189. var prsdp = new SDP(pranswer.sdp);
  11190. var accept = $iq({to: this.peerjid,
  11191. type: 'set'})
  11192. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11193. action: 'session-accept',
  11194. initiator: this.initiator,
  11195. responder: this.responder,
  11196. sid: this.sid });
  11197. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  11198. var sdp = this.peerconnection.localDescription.sdp;
  11199. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  11200. // FIXME: change any inactive to sendrecv or whatever they were originally
  11201. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  11202. }
  11203. var self = this;
  11204. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  11205. function () {
  11206. //console.log('setLocalDescription success');
  11207. self.setLocalDescription();
  11208. self.connection.sendIQ(accept,
  11209. function () {
  11210. var ack = {};
  11211. ack.source = 'answer';
  11212. $(document).trigger('ack.jingle', [self.sid, ack]);
  11213. },
  11214. function (stanza) {
  11215. var error = ($(stanza).find('error').length) ? {
  11216. code: $(stanza).find('error').attr('code'),
  11217. reason: $(stanza).find('error :first')[0].tagName
  11218. }:{};
  11219. error.source = 'answer';
  11220. JingleSession.onJingleError(self.sid, error);
  11221. },
  11222. 10000);
  11223. },
  11224. function (e) {
  11225. console.error('setLocalDescription failed', e);
  11226. }
  11227. );
  11228. };
  11229. JingleSession.prototype.terminate = function (reason) {
  11230. this.state = 'ended';
  11231. this.reason = reason;
  11232. this.peerconnection.close();
  11233. if (this.statsinterval !== null) {
  11234. window.clearInterval(this.statsinterval);
  11235. this.statsinterval = null;
  11236. }
  11237. };
  11238. JingleSession.prototype.active = function () {
  11239. return this.state == 'active';
  11240. };
  11241. JingleSession.prototype.sendIceCandidate = function (candidate) {
  11242. var self = this;
  11243. if (candidate && !this.lasticecandidate) {
  11244. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  11245. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  11246. if (!(ice && jcand)) {
  11247. console.error('failed to get ice && jcand');
  11248. return;
  11249. }
  11250. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11251. if (jcand.type === 'srflx') {
  11252. this.hadstuncandidate = true;
  11253. } else if (jcand.type === 'relay') {
  11254. this.hadturncandidate = true;
  11255. }
  11256. if (this.usetrickle) {
  11257. if (this.usedrip) {
  11258. if (this.drip_container.length === 0) {
  11259. // start 20ms callout
  11260. window.setTimeout(function () {
  11261. if (self.drip_container.length === 0) return;
  11262. self.sendIceCandidates(self.drip_container);
  11263. self.drip_container = [];
  11264. }, 20);
  11265. }
  11266. this.drip_container.push(candidate);
  11267. return;
  11268. } else {
  11269. self.sendIceCandidate([candidate]);
  11270. }
  11271. }
  11272. } else {
  11273. //console.log('sendIceCandidate: last candidate.');
  11274. if (!this.usetrickle) {
  11275. //console.log('should send full offer now...');
  11276. var init = $iq({to: this.peerjid,
  11277. type: 'set'})
  11278. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11279. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  11280. initiator: this.initiator,
  11281. sid: this.sid});
  11282. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  11283. var self = this;
  11284. var sendJingle = function (ssrc) {
  11285. if(!ssrc)
  11286. ssrc = {};
  11287. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  11288. self.connection.sendIQ(init,
  11289. function () {
  11290. //console.log('session initiate ack');
  11291. var ack = {};
  11292. ack.source = 'offer';
  11293. $(document).trigger('ack.jingle', [self.sid, ack]);
  11294. },
  11295. function (stanza) {
  11296. self.state = 'error';
  11297. self.peerconnection.close();
  11298. var error = ($(stanza).find('error').length) ? {
  11299. code: $(stanza).find('error').attr('code'),
  11300. reason: $(stanza).find('error :first')[0].tagName,
  11301. }:{};
  11302. error.source = 'offer';
  11303. JingleSession.onJingleError(self.sid, error);
  11304. },
  11305. 10000);
  11306. }
  11307. sendJingle();
  11308. }
  11309. this.lasticecandidate = true;
  11310. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  11311. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  11312. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  11313. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  11314. }
  11315. }
  11316. };
  11317. JingleSession.prototype.sendIceCandidates = function (candidates) {
  11318. console.log('sendIceCandidates', candidates);
  11319. var cand = $iq({to: this.peerjid, type: 'set'})
  11320. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11321. action: 'transport-info',
  11322. initiator: this.initiator,
  11323. sid: this.sid});
  11324. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  11325. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  11326. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  11327. if (cands.length > 0) {
  11328. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  11329. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11330. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  11331. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  11332. }).c('transport', ice);
  11333. for (var i = 0; i < cands.length; i++) {
  11334. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  11335. }
  11336. // add fingerprint
  11337. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  11338. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  11339. tmp.required = true;
  11340. cand.c(
  11341. 'fingerprint',
  11342. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  11343. .t(tmp.fingerprint);
  11344. delete tmp.fingerprint;
  11345. cand.attrs(tmp);
  11346. cand.up();
  11347. }
  11348. cand.up(); // transport
  11349. cand.up(); // content
  11350. }
  11351. }
  11352. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  11353. //console.log('was this the last candidate', this.lasticecandidate);
  11354. this.connection.sendIQ(cand,
  11355. function () {
  11356. var ack = {};
  11357. ack.source = 'transportinfo';
  11358. $(document).trigger('ack.jingle', [this.sid, ack]);
  11359. },
  11360. function (stanza) {
  11361. var error = ($(stanza).find('error').length) ? {
  11362. code: $(stanza).find('error').attr('code'),
  11363. reason: $(stanza).find('error :first')[0].tagName,
  11364. }:{};
  11365. error.source = 'transportinfo';
  11366. JingleSession.onJingleError(this.sid, error);
  11367. },
  11368. 10000);
  11369. };
  11370. JingleSession.prototype.sendOffer = function () {
  11371. //console.log('sendOffer...');
  11372. var self = this;
  11373. this.peerconnection.createOffer(function (sdp) {
  11374. self.createdOffer(sdp);
  11375. },
  11376. function (e) {
  11377. console.error('createOffer failed', e);
  11378. },
  11379. this.media_constraints
  11380. );
  11381. };
  11382. JingleSession.prototype.createdOffer = function (sdp) {
  11383. //console.log('createdOffer', sdp);
  11384. var self = this;
  11385. this.localSDP = new SDP(sdp.sdp);
  11386. //this.localSDP.mangle();
  11387. var sendJingle = function () {
  11388. var init = $iq({to: this.peerjid,
  11389. type: 'set'})
  11390. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11391. action: 'session-initiate',
  11392. initiator: this.initiator,
  11393. sid: this.sid});
  11394. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  11395. self.connection.sendIQ(init,
  11396. function () {
  11397. var ack = {};
  11398. ack.source = 'offer';
  11399. $(document).trigger('ack.jingle', [self.sid, ack]);
  11400. },
  11401. function (stanza) {
  11402. self.state = 'error';
  11403. self.peerconnection.close();
  11404. var error = ($(stanza).find('error').length) ? {
  11405. code: $(stanza).find('error').attr('code'),
  11406. reason: $(stanza).find('error :first')[0].tagName,
  11407. }:{};
  11408. error.source = 'offer';
  11409. JingleSession.onJingleError(self.sid, error);
  11410. },
  11411. 10000);
  11412. }
  11413. sdp.sdp = this.localSDP.raw;
  11414. this.peerconnection.setLocalDescription(sdp,
  11415. function () {
  11416. if(self.usetrickle)
  11417. {
  11418. sendJingle();
  11419. }
  11420. self.setLocalDescription();
  11421. //console.log('setLocalDescription success');
  11422. },
  11423. function (e) {
  11424. console.error('setLocalDescription failed', e);
  11425. }
  11426. );
  11427. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11428. for (var i = 0; i < cands.length; i++) {
  11429. var cand = SDPUtil.parse_icecandidate(cands[i]);
  11430. if (cand.type == 'srflx') {
  11431. this.hadstuncandidate = true;
  11432. } else if (cand.type == 'relay') {
  11433. this.hadturncandidate = true;
  11434. }
  11435. }
  11436. };
  11437. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  11438. //console.log('setting remote description... ', desctype);
  11439. this.remoteSDP = new SDP('');
  11440. this.remoteSDP.fromJingle(elem);
  11441. if (this.peerconnection.remoteDescription !== null) {
  11442. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  11443. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  11444. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  11445. for (var i = 0; i < pranswer.media.length; i++) {
  11446. // make sure we have ice ufrag and pwd
  11447. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  11448. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  11449. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  11450. } else {
  11451. console.warn('no ice ufrag?');
  11452. }
  11453. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  11454. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  11455. } else {
  11456. console.warn('no ice pwd?');
  11457. }
  11458. }
  11459. // copy over candidates
  11460. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  11461. for (var j = 0; j < lines.length; j++) {
  11462. this.remoteSDP.media[i] += lines[j] + '\r\n';
  11463. }
  11464. }
  11465. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11466. }
  11467. }
  11468. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  11469. this.peerconnection.setRemoteDescription(remotedesc,
  11470. function () {
  11471. //console.log('setRemoteDescription success');
  11472. },
  11473. function (e) {
  11474. console.error('setRemoteDescription error', e);
  11475. JingleSession.onJingleFatalError(self, e);
  11476. }
  11477. );
  11478. };
  11479. JingleSession.prototype.addIceCandidate = function (elem) {
  11480. var self = this;
  11481. if (this.peerconnection.signalingState == 'closed') {
  11482. return;
  11483. }
  11484. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  11485. console.log('trickle ice candidate arriving before session accept...');
  11486. // create a PRANSWER for setRemoteDescription
  11487. if (!this.remoteSDP) {
  11488. var cobbled = 'v=0\r\n' +
  11489. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11490. 's=-\r\n' +
  11491. 't=0 0\r\n';
  11492. // first, take some things from the local description
  11493. for (var i = 0; i < this.localSDP.media.length; i++) {
  11494. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  11495. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  11496. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  11497. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  11498. }
  11499. cobbled += 'a=inactive\r\n';
  11500. }
  11501. this.remoteSDP = new SDP(cobbled);
  11502. }
  11503. // then add things like ice and dtls from remote candidate
  11504. elem.each(function () {
  11505. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  11506. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11507. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11508. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  11509. var tmp = $(this).find('transport');
  11510. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  11511. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  11512. tmp = $(this).find('transport>fingerprint');
  11513. if (tmp.length) {
  11514. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  11515. } else {
  11516. console.log('no dtls fingerprint (webrtc issue #1718?)');
  11517. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  11518. }
  11519. break;
  11520. }
  11521. }
  11522. }
  11523. });
  11524. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11525. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  11526. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  11527. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  11528. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  11529. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  11530. }).length == this.remoteSDP.media.length;
  11531. if (iscomplete) {
  11532. console.log('setting pranswer');
  11533. try {
  11534. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  11535. function() {
  11536. },
  11537. function(e) {
  11538. console.log('setRemoteDescription pranswer failed', e.toString());
  11539. });
  11540. } catch (e) {
  11541. console.error('setting pranswer failed', e);
  11542. }
  11543. } else {
  11544. //console.log('not yet setting pranswer');
  11545. }
  11546. }
  11547. // operate on each content element
  11548. elem.each(function () {
  11549. // would love to deactivate this, but firefox still requires it
  11550. var idx = -1;
  11551. var i;
  11552. for (i = 0; i < self.remoteSDP.media.length; i++) {
  11553. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11554. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11555. idx = i;
  11556. break;
  11557. }
  11558. }
  11559. if (idx == -1) { // fall back to localdescription
  11560. for (i = 0; i < self.localSDP.media.length; i++) {
  11561. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11562. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11563. idx = i;
  11564. break;
  11565. }
  11566. }
  11567. }
  11568. var name = $(this).attr('name');
  11569. // TODO: check ice-pwd and ice-ufrag?
  11570. $(this).find('transport>candidate').each(function () {
  11571. var line, candidate;
  11572. line = SDPUtil.candidateFromJingle(this);
  11573. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  11574. sdpMid: name,
  11575. candidate: line});
  11576. try {
  11577. self.peerconnection.addIceCandidate(candidate);
  11578. } catch (e) {
  11579. console.error('addIceCandidate failed', e.toString(), line);
  11580. }
  11581. });
  11582. });
  11583. };
  11584. JingleSession.prototype.sendAnswer = function (provisional) {
  11585. //console.log('createAnswer', provisional);
  11586. var self = this;
  11587. this.peerconnection.createAnswer(
  11588. function (sdp) {
  11589. self.createdAnswer(sdp, provisional);
  11590. },
  11591. function (e) {
  11592. console.error('createAnswer failed', e);
  11593. },
  11594. this.media_constraints
  11595. );
  11596. };
  11597. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  11598. //console.log('createAnswer callback');
  11599. var self = this;
  11600. this.localSDP = new SDP(sdp.sdp);
  11601. //this.localSDP.mangle();
  11602. this.usepranswer = provisional === true;
  11603. if (this.usetrickle) {
  11604. if (this.usepranswer) {
  11605. sdp.type = 'pranswer';
  11606. for (var i = 0; i < this.localSDP.media.length; i++) {
  11607. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  11608. }
  11609. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  11610. }
  11611. }
  11612. var self = this;
  11613. var sendJingle = function (ssrcs) {
  11614. var accept = $iq({to: self.peerjid,
  11615. type: 'set'})
  11616. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11617. action: 'session-accept',
  11618. initiator: self.initiator,
  11619. responder: self.responder,
  11620. sid: self.sid });
  11621. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  11622. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  11623. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  11624. self.connection.sendIQ(accept,
  11625. function () {
  11626. var ack = {};
  11627. ack.source = 'answer';
  11628. $(document).trigger('ack.jingle', [self.sid, ack]);
  11629. },
  11630. function (stanza) {
  11631. var error = ($(stanza).find('error').length) ? {
  11632. code: $(stanza).find('error').attr('code'),
  11633. reason: $(stanza).find('error :first')[0].tagName,
  11634. }:{};
  11635. error.source = 'answer';
  11636. JingleSession.onJingleError(self.sid, error);
  11637. },
  11638. 10000);
  11639. }
  11640. sdp.sdp = this.localSDP.raw;
  11641. this.peerconnection.setLocalDescription(sdp,
  11642. function () {
  11643. //console.log('setLocalDescription success');
  11644. if (self.usetrickle && !self.usepranswer) {
  11645. sendJingle();
  11646. }
  11647. self.setLocalDescription();
  11648. },
  11649. function (e) {
  11650. console.error('setLocalDescription failed', e);
  11651. }
  11652. );
  11653. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11654. for (var j = 0; j < cands.length; j++) {
  11655. var cand = SDPUtil.parse_icecandidate(cands[j]);
  11656. if (cand.type == 'srflx') {
  11657. this.hadstuncandidate = true;
  11658. } else if (cand.type == 'relay') {
  11659. this.hadturncandidate = true;
  11660. }
  11661. }
  11662. };
  11663. JingleSession.prototype.sendTerminate = function (reason, text) {
  11664. var self = this,
  11665. term = $iq({to: this.peerjid,
  11666. type: 'set'})
  11667. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11668. action: 'session-terminate',
  11669. initiator: this.initiator,
  11670. sid: this.sid})
  11671. .c('reason')
  11672. .c(reason || 'success');
  11673. if (text) {
  11674. term.up().c('text').t(text);
  11675. }
  11676. this.connection.sendIQ(term,
  11677. function () {
  11678. self.peerconnection.close();
  11679. self.peerconnection = null;
  11680. self.terminate();
  11681. var ack = {};
  11682. ack.source = 'terminate';
  11683. $(document).trigger('ack.jingle', [self.sid, ack]);
  11684. },
  11685. function (stanza) {
  11686. var error = ($(stanza).find('error').length) ? {
  11687. code: $(stanza).find('error').attr('code'),
  11688. reason: $(stanza).find('error :first')[0].tagName,
  11689. }:{};
  11690. $(document).trigger('ack.jingle', [self.sid, error]);
  11691. },
  11692. 10000);
  11693. if (this.statsinterval !== null) {
  11694. window.clearInterval(this.statsinterval);
  11695. this.statsinterval = null;
  11696. }
  11697. };
  11698. JingleSession.prototype.addSource = function (elem, fromJid) {
  11699. var self = this;
  11700. // FIXME: dirty waiting
  11701. if (!this.peerconnection.localDescription)
  11702. {
  11703. console.warn("addSource - localDescription not ready yet")
  11704. setTimeout(function()
  11705. {
  11706. self.addSource(elem, fromJid);
  11707. },
  11708. 200
  11709. );
  11710. return;
  11711. }
  11712. console.log('addssrc', new Date().getTime());
  11713. console.log('ice', this.peerconnection.iceConnectionState);
  11714. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11715. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11716. $(elem).each(function (idx, content) {
  11717. var name = $(content).attr('name');
  11718. var lines = '';
  11719. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11720. var semantics = this.getAttribute('semantics');
  11721. var ssrcs = $(this).find('>source').map(function () {
  11722. return this.getAttribute('ssrc');
  11723. }).get();
  11724. if (ssrcs.length != 0) {
  11725. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11726. }
  11727. });
  11728. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11729. tmp.each(function () {
  11730. var ssrc = $(this).attr('ssrc');
  11731. if(mySdp.containsSSRC(ssrc)){
  11732. /**
  11733. * This happens when multiple participants change their streams at the same time and
  11734. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  11735. * addssrc are scheduled for update IQ. See
  11736. */
  11737. console.warn("Got add stream request for my own ssrc: "+ssrc);
  11738. return;
  11739. }
  11740. $(this).find('>parameter').each(function () {
  11741. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11742. if ($(this).attr('value') && $(this).attr('value').length)
  11743. lines += ':' + $(this).attr('value');
  11744. lines += '\r\n';
  11745. });
  11746. });
  11747. sdp.media.forEach(function(media, idx) {
  11748. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11749. return;
  11750. sdp.media[idx] += lines;
  11751. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  11752. self.addssrc[idx] += lines;
  11753. });
  11754. sdp.raw = sdp.session + sdp.media.join('');
  11755. });
  11756. this.modifySourcesQueue.push(function() {
  11757. // When a source is added and if this is FF, a new channel is allocated
  11758. // for receiving the added source. We need to diffuse the SSRC of this
  11759. // new recvonly channel to the rest of the peers.
  11760. console.log('modify sources done');
  11761. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11762. console.log("SDPs", mySdp, newSdp);
  11763. self.notifyMySSRCUpdate(mySdp, newSdp);
  11764. });
  11765. };
  11766. JingleSession.prototype.removeSource = function (elem, fromJid) {
  11767. var self = this;
  11768. // FIXME: dirty waiting
  11769. if (!this.peerconnection.localDescription)
  11770. {
  11771. console.warn("removeSource - localDescription not ready yet")
  11772. setTimeout(function()
  11773. {
  11774. self.removeSource(elem, fromJid);
  11775. },
  11776. 200
  11777. );
  11778. return;
  11779. }
  11780. console.log('removessrc', new Date().getTime());
  11781. console.log('ice', this.peerconnection.iceConnectionState);
  11782. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11783. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11784. $(elem).each(function (idx, content) {
  11785. var name = $(content).attr('name');
  11786. var lines = '';
  11787. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11788. var semantics = this.getAttribute('semantics');
  11789. var ssrcs = $(this).find('>source').map(function () {
  11790. return this.getAttribute('ssrc');
  11791. }).get();
  11792. if (ssrcs.length != 0) {
  11793. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11794. }
  11795. });
  11796. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11797. tmp.each(function () {
  11798. var ssrc = $(this).attr('ssrc');
  11799. // This should never happen, but can be useful for bug detection
  11800. if(mySdp.containsSSRC(ssrc)){
  11801. console.error("Got remove stream request for my own ssrc: "+ssrc);
  11802. return;
  11803. }
  11804. $(this).find('>parameter').each(function () {
  11805. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11806. if ($(this).attr('value') && $(this).attr('value').length)
  11807. lines += ':' + $(this).attr('value');
  11808. lines += '\r\n';
  11809. });
  11810. });
  11811. sdp.media.forEach(function(media, idx) {
  11812. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11813. return;
  11814. sdp.media[idx] += lines;
  11815. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  11816. self.removessrc[idx] += lines;
  11817. });
  11818. sdp.raw = sdp.session + sdp.media.join('');
  11819. });
  11820. this.modifySourcesQueue.push(function() {
  11821. // When a source is removed and if this is FF, the recvonly channel that
  11822. // receives the remote stream is deactivated . We need to diffuse the
  11823. // recvonly SSRC removal to the rest of the peers.
  11824. console.log('modify sources done');
  11825. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11826. console.log("SDPs", mySdp, newSdp);
  11827. self.notifyMySSRCUpdate(mySdp, newSdp);
  11828. });
  11829. };
  11830. JingleSession.prototype._modifySources = function (successCallback, queueCallback) {
  11831. var self = this;
  11832. if (this.peerconnection.signalingState == 'closed') return;
  11833. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  11834. // There is nothing to do since scheduled job might have been executed by another succeeding call
  11835. this.setLocalDescription();
  11836. if(successCallback){
  11837. successCallback();
  11838. }
  11839. queueCallback();
  11840. return;
  11841. }
  11842. // Reset switch streams flag
  11843. this.switchstreams = false;
  11844. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11845. // add sources
  11846. this.addssrc.forEach(function(lines, idx) {
  11847. sdp.media[idx] += lines;
  11848. });
  11849. this.addssrc = [];
  11850. // remove sources
  11851. this.removessrc.forEach(function(lines, idx) {
  11852. lines = lines.split('\r\n');
  11853. lines.pop(); // remove empty last element;
  11854. lines.forEach(function(line) {
  11855. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  11856. });
  11857. });
  11858. this.removessrc = [];
  11859. // FIXME:
  11860. // this was a hack for the situation when only one peer exists
  11861. // in the conference.
  11862. // check if still required and remove
  11863. if (sdp.media[0])
  11864. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  11865. if (sdp.media[1])
  11866. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11867. sdp.raw = sdp.session + sdp.media.join('');
  11868. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  11869. function() {
  11870. if(self.signalingState == 'closed') {
  11871. console.error("createAnswer attempt on closed state");
  11872. queueCallback("createAnswer attempt on closed state");
  11873. return;
  11874. }
  11875. self.peerconnection.createAnswer(
  11876. function(modifiedAnswer) {
  11877. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  11878. if (self.pendingop !== null) {
  11879. var sdp = new SDP(modifiedAnswer.sdp);
  11880. if (sdp.media.length > 1) {
  11881. switch(self.pendingop) {
  11882. case 'mute':
  11883. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  11884. break;
  11885. case 'unmute':
  11886. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11887. break;
  11888. }
  11889. sdp.raw = sdp.session + sdp.media.join('');
  11890. modifiedAnswer.sdp = sdp.raw;
  11891. }
  11892. self.pendingop = null;
  11893. }
  11894. // FIXME: pushing down an answer while ice connection state
  11895. // is still checking is bad...
  11896. //console.log(self.peerconnection.iceConnectionState);
  11897. // trying to work around another chrome bug
  11898. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11899. self.peerconnection.setLocalDescription(modifiedAnswer,
  11900. function() {
  11901. //console.log('modified setLocalDescription ok');
  11902. self.setLocalDescription();
  11903. if(successCallback){
  11904. successCallback();
  11905. }
  11906. queueCallback();
  11907. },
  11908. function(error) {
  11909. console.error('modified setLocalDescription failed', error);
  11910. queueCallback(error);
  11911. }
  11912. );
  11913. },
  11914. function(error) {
  11915. console.error('modified answer failed', error);
  11916. queueCallback(error);
  11917. }
  11918. );
  11919. },
  11920. function(error) {
  11921. console.error('modify failed', error);
  11922. queueCallback(error);
  11923. }
  11924. );
  11925. };
  11926. /**
  11927. * Switches video streams.
  11928. * @param new_stream new stream that will be used as video of this session.
  11929. * @param oldStream old video stream of this session.
  11930. * @param success_callback callback executed after successful stream switch.
  11931. */
  11932. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  11933. var self = this;
  11934. // Remember SDP to figure out added/removed SSRCs
  11935. var oldSdp = null;
  11936. if(self.peerconnection) {
  11937. if(self.peerconnection.localDescription) {
  11938. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11939. }
  11940. self.peerconnection.removeStream(oldStream, true);
  11941. if(new_stream)
  11942. self.peerconnection.addStream(new_stream);
  11943. }
  11944. if(!isAudio)
  11945. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11946. // Conference is not active
  11947. if(!oldSdp || !self.peerconnection) {
  11948. success_callback();
  11949. return;
  11950. }
  11951. self.switchstreams = true;
  11952. self.modifySourcesQueue.push(function() {
  11953. console.log('modify sources done');
  11954. success_callback();
  11955. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11956. console.log("SDPs", oldSdp, newSdp);
  11957. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11958. });
  11959. };
  11960. /**
  11961. * Figures out added/removed ssrcs and send update IQs.
  11962. * @param old_sdp SDP object for old description.
  11963. * @param new_sdp SDP object for new description.
  11964. */
  11965. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11966. if (!(this.peerconnection.signalingState == 'stable' &&
  11967. this.peerconnection.iceConnectionState == 'connected')){
  11968. console.log("Too early to send updates");
  11969. return;
  11970. }
  11971. // send source-remove IQ.
  11972. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11973. var remove = $iq({to: this.peerjid, type: 'set'})
  11974. .c('jingle', {
  11975. xmlns: 'urn:xmpp:jingle:1',
  11976. action: 'source-remove',
  11977. initiator: this.initiator,
  11978. sid: this.sid
  11979. }
  11980. );
  11981. var removed = sdpDiffer.toJingle(remove);
  11982. if (removed) {
  11983. this.connection.sendIQ(remove,
  11984. function (res) {
  11985. console.info('got remove result', res);
  11986. },
  11987. function (err) {
  11988. console.error('got remove error', err);
  11989. }
  11990. );
  11991. } else {
  11992. console.log('removal not necessary');
  11993. }
  11994. // send source-add IQ.
  11995. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11996. var add = $iq({to: this.peerjid, type: 'set'})
  11997. .c('jingle', {
  11998. xmlns: 'urn:xmpp:jingle:1',
  11999. action: 'source-add',
  12000. initiator: this.initiator,
  12001. sid: this.sid
  12002. }
  12003. );
  12004. var added = sdpDiffer.toJingle(add);
  12005. if (added) {
  12006. this.connection.sendIQ(add,
  12007. function (res) {
  12008. console.info('got add result', res);
  12009. },
  12010. function (err) {
  12011. console.error('got add error', err);
  12012. }
  12013. );
  12014. } else {
  12015. console.log('addition not necessary');
  12016. }
  12017. };
  12018. /**
  12019. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  12020. *
  12021. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  12022. * tracks; otherwise, <tt>false</tt>
  12023. * @param callback a function to be invoked with <tt>mute</tt> after all video
  12024. * tracks have been enabled/disabled. The function may, optionally, return
  12025. * another function which is to be invoked after the whole mute/unmute operation
  12026. * has completed successfully.
  12027. * @param options an object which specifies optional arguments such as the
  12028. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  12029. * specifies whether the method was initiated in response to a user command (in
  12030. * contrast to an automatic decision made by the application logic)
  12031. */
  12032. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  12033. var byUser;
  12034. if (options) {
  12035. byUser = options.byUser;
  12036. if (typeof byUser === 'undefined') {
  12037. byUser = true;
  12038. }
  12039. } else {
  12040. byUser = true;
  12041. }
  12042. // The user's command to mute the (local) video takes precedence over any
  12043. // automatic decision made by the application logic.
  12044. if (byUser) {
  12045. this.videoMuteByUser = mute;
  12046. } else if (this.videoMuteByUser) {
  12047. return;
  12048. }
  12049. this.hardMuteVideo(mute);
  12050. var self = this;
  12051. var oldSdp = null;
  12052. if(self.peerconnection) {
  12053. if(self.peerconnection.localDescription) {
  12054. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12055. }
  12056. }
  12057. this.modifySourcesQueue.push(function() {
  12058. console.log('modify sources done');
  12059. callback(mute);
  12060. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12061. console.log("SDPs", oldSdp, newSdp);
  12062. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12063. });
  12064. };
  12065. JingleSession.prototype.hardMuteVideo = function (muted) {
  12066. this.pendingop = muted ? 'mute' : 'unmute';
  12067. };
  12068. JingleSession.prototype.sendMute = function (muted, content) {
  12069. var info = $iq({to: this.peerjid,
  12070. type: 'set'})
  12071. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12072. action: 'session-info',
  12073. initiator: this.initiator,
  12074. sid: this.sid });
  12075. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12076. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  12077. if (content) {
  12078. info.attrs({'name': content});
  12079. }
  12080. this.connection.send(info);
  12081. };
  12082. JingleSession.prototype.sendRinging = function () {
  12083. var info = $iq({to: this.peerjid,
  12084. type: 'set'})
  12085. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12086. action: 'session-info',
  12087. initiator: this.initiator,
  12088. sid: this.sid });
  12089. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12090. this.connection.send(info);
  12091. };
  12092. JingleSession.prototype.getStats = function (interval) {
  12093. var self = this;
  12094. var recv = {audio: 0, video: 0};
  12095. var lost = {audio: 0, video: 0};
  12096. var lastrecv = {audio: 0, video: 0};
  12097. var lastlost = {audio: 0, video: 0};
  12098. var loss = {audio: 0, video: 0};
  12099. var delta = {audio: 0, video: 0};
  12100. this.statsinterval = window.setInterval(function () {
  12101. if (self && self.peerconnection && self.peerconnection.getStats) {
  12102. self.peerconnection.getStats(function (stats) {
  12103. var results = stats.result();
  12104. // TODO: there are so much statistics you can get from this..
  12105. for (var i = 0; i < results.length; ++i) {
  12106. if (results[i].type == 'ssrc') {
  12107. var packetsrecv = results[i].stat('packetsReceived');
  12108. var packetslost = results[i].stat('packetsLost');
  12109. if (packetsrecv && packetslost) {
  12110. packetsrecv = parseInt(packetsrecv, 10);
  12111. packetslost = parseInt(packetslost, 10);
  12112. if (results[i].stat('googFrameRateReceived')) {
  12113. lastlost.video = lost.video;
  12114. lastrecv.video = recv.video;
  12115. recv.video = packetsrecv;
  12116. lost.video = packetslost;
  12117. } else {
  12118. lastlost.audio = lost.audio;
  12119. lastrecv.audio = recv.audio;
  12120. recv.audio = packetsrecv;
  12121. lost.audio = packetslost;
  12122. }
  12123. }
  12124. }
  12125. }
  12126. delta.audio = recv.audio - lastrecv.audio;
  12127. delta.video = recv.video - lastrecv.video;
  12128. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  12129. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  12130. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  12131. });
  12132. }
  12133. }, interval || 3000);
  12134. return this.statsinterval;
  12135. };
  12136. JingleSession.onJingleError = function (session, error)
  12137. {
  12138. console.error("Jingle error", error);
  12139. }
  12140. JingleSession.onJingleFatalError = function (session, error)
  12141. {
  12142. this.service.sessionTerminated = true;
  12143. this.connection.emuc.doLeave();
  12144. APP.UI.messageHandler.showError("dialog.sorry",
  12145. "dialog.internalError");
  12146. }
  12147. JingleSession.prototype.setLocalDescription = function () {
  12148. // put our ssrcs into presence so other clients can identify our stream
  12149. var newssrcs = [];
  12150. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  12151. media.forEach(function (media) {
  12152. if(Object.keys(media.sources).length > 0) {
  12153. // TODO(gp) maybe exclude FID streams?
  12154. Object.keys(media.sources).forEach(function (ssrc) {
  12155. newssrcs.push({
  12156. 'ssrc': ssrc,
  12157. 'type': media.type,
  12158. 'direction': media.direction
  12159. });
  12160. });
  12161. }
  12162. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  12163. {
  12164. newssrcs.push({
  12165. 'ssrc': this.localStreamsSSRC[media.type],
  12166. 'type': media.type,
  12167. 'direction': media.direction
  12168. });
  12169. }
  12170. });
  12171. console.log('new ssrcs', newssrcs);
  12172. // Have to clear presence map to get rid of removed streams
  12173. this.connection.emuc.clearPresenceMedia();
  12174. if (newssrcs.length > 0) {
  12175. for (var i = 1; i <= newssrcs.length; i ++) {
  12176. // Change video type to screen
  12177. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  12178. newssrcs[i-1].type = 'screen';
  12179. }
  12180. this.connection.emuc.addMediaToPresence(i,
  12181. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  12182. }
  12183. this.connection.emuc.sendPresence();
  12184. }
  12185. }
  12186. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12187. function sendKeyframe(pc) {
  12188. console.log('sendkeyframe', pc.iceConnectionState);
  12189. if (pc.iceConnectionState !== 'connected') return; // safe...
  12190. pc.setRemoteDescription(
  12191. pc.remoteDescription,
  12192. function () {
  12193. pc.createAnswer(
  12194. function (modifiedAnswer) {
  12195. pc.setLocalDescription(
  12196. modifiedAnswer,
  12197. function () {
  12198. // noop
  12199. },
  12200. function (error) {
  12201. console.log('triggerKeyframe setLocalDescription failed', error);
  12202. APP.UI.messageHandler.showError();
  12203. }
  12204. );
  12205. },
  12206. function (error) {
  12207. console.log('triggerKeyframe createAnswer failed', error);
  12208. APP.UI.messageHandler.showError();
  12209. }
  12210. );
  12211. },
  12212. function (error) {
  12213. console.log('triggerKeyframe setRemoteDescription failed', error);
  12214. APP.UI.messageHandler.showError();
  12215. }
  12216. );
  12217. }
  12218. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  12219. var self = this;
  12220. var thessrc;
  12221. var ssrc2jid = this.connection.emuc.ssrc2jid;
  12222. // look up an associated JID for a stream id
  12223. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  12224. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  12225. var ssrclines
  12226. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  12227. ssrclines = ssrclines.filter(function (line) {
  12228. // NOTE(gp) previously we filtered on the mslabel, but that property
  12229. // is not always present.
  12230. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  12231. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  12232. });
  12233. if (ssrclines.length) {
  12234. thessrc = ssrclines[0].substring(7).split(' ')[0];
  12235. // We signal our streams (through Jingle to the focus) before we set
  12236. // our presence (through which peers associate remote streams to
  12237. // jids). So, it might arrive that a remote stream is added but
  12238. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  12239. // successfully set. Here we wait for up to a second for the
  12240. // presence to arrive.
  12241. if (!ssrc2jid[thessrc]) {
  12242. if (typeof times === 'undefined')
  12243. {
  12244. times = 0;
  12245. }
  12246. if (times > 10)
  12247. {
  12248. console.warning('Waiting for jid timed out', thessrc);
  12249. }
  12250. else
  12251. {
  12252. setTimeout(function(d) {
  12253. return function() {
  12254. self.remoteStreamAdded(d, times++);
  12255. }
  12256. }(data), 250);
  12257. }
  12258. return;
  12259. }
  12260. // ok to overwrite the one from focus? might save work in colibri.js
  12261. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  12262. if (ssrc2jid[thessrc]) {
  12263. data.peerjid = ssrc2jid[thessrc];
  12264. }
  12265. }
  12266. }
  12267. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  12268. var isVideo = data.stream.getVideoTracks().length > 0;
  12269. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12270. if (isVideo &&
  12271. data.peerjid && this.peerjid === data.peerjid &&
  12272. data.stream.getVideoTracks().length === 0 &&
  12273. APP.RTC.localVideo.getTracks().length > 0) {
  12274. window.setTimeout(function () {
  12275. sendKeyframe(self.peerconnection);
  12276. }, 3000);
  12277. }
  12278. }
  12279. module.exports = JingleSession;
  12280. },{"../../service/RTC/RTCBrowserType":95,"./SDP":52,"./SDPDiffer":53,"./SDPUtil":54,"./TraceablePeerConnection":55,"async":65}],52:[function(require,module,exports){
  12281. /* jshint -W117 */
  12282. var SDPUtil = require("./SDPUtil");
  12283. // SDP STUFF
  12284. function SDP(sdp) {
  12285. this.media = sdp.split('\r\nm=');
  12286. for (var i = 1; i < this.media.length; i++) {
  12287. this.media[i] = 'm=' + this.media[i];
  12288. if (i != this.media.length - 1) {
  12289. this.media[i] += '\r\n';
  12290. }
  12291. }
  12292. this.session = this.media.shift() + '\r\n';
  12293. this.raw = this.session + this.media.join('');
  12294. }
  12295. /**
  12296. * Returns map of MediaChannel mapped per channel idx.
  12297. */
  12298. SDP.prototype.getMediaSsrcMap = function() {
  12299. var self = this;
  12300. var media_ssrcs = {};
  12301. var tmp;
  12302. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  12303. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  12304. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  12305. var media = {
  12306. mediaindex: mediaindex,
  12307. mid: mid,
  12308. ssrcs: {},
  12309. ssrcGroups: []
  12310. };
  12311. media_ssrcs[mediaindex] = media;
  12312. tmp.forEach(function (line) {
  12313. var linessrc = line.substring(7).split(' ')[0];
  12314. // allocate new ChannelSsrc
  12315. if(!media.ssrcs[linessrc]) {
  12316. media.ssrcs[linessrc] = {
  12317. ssrc: linessrc,
  12318. lines: []
  12319. };
  12320. }
  12321. media.ssrcs[linessrc].lines.push(line);
  12322. });
  12323. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  12324. tmp.forEach(function(line){
  12325. var semantics = line.substr(0, idx).substr(13);
  12326. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12327. if (ssrcs.length != 0) {
  12328. media.ssrcGroups.push({
  12329. semantics: semantics,
  12330. ssrcs: ssrcs
  12331. });
  12332. }
  12333. });
  12334. }
  12335. return media_ssrcs;
  12336. };
  12337. /**
  12338. * Returns <tt>true</tt> if this SDP contains given SSRC.
  12339. * @param ssrc the ssrc to check.
  12340. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  12341. */
  12342. SDP.prototype.containsSSRC = function(ssrc) {
  12343. var medias = this.getMediaSsrcMap();
  12344. var contains = false;
  12345. Object.keys(medias).forEach(function(mediaindex){
  12346. var media = medias[mediaindex];
  12347. //console.log("Check", channel, ssrc);
  12348. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  12349. contains = true;
  12350. }
  12351. });
  12352. return contains;
  12353. };
  12354. // remove iSAC and CN from SDP
  12355. SDP.prototype.mangle = function () {
  12356. var i, j, mline, lines, rtpmap, newdesc;
  12357. for (i = 0; i < this.media.length; i++) {
  12358. lines = this.media[i].split('\r\n');
  12359. lines.pop(); // remove empty last element
  12360. mline = SDPUtil.parse_mline(lines.shift());
  12361. if (mline.media != 'audio')
  12362. continue;
  12363. newdesc = '';
  12364. mline.fmt.length = 0;
  12365. for (j = 0; j < lines.length; j++) {
  12366. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  12367. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  12368. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  12369. continue;
  12370. mline.fmt.push(rtpmap.id);
  12371. newdesc += lines[j] + '\r\n';
  12372. } else {
  12373. newdesc += lines[j] + '\r\n';
  12374. }
  12375. }
  12376. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  12377. this.media[i] += newdesc;
  12378. }
  12379. this.raw = this.session + this.media.join('');
  12380. };
  12381. // remove lines matching prefix from session section
  12382. SDP.prototype.removeSessionLines = function(prefix) {
  12383. var self = this;
  12384. var lines = SDPUtil.find_lines(this.session, prefix);
  12385. lines.forEach(function(line) {
  12386. self.session = self.session.replace(line + '\r\n', '');
  12387. });
  12388. this.raw = this.session + this.media.join('');
  12389. return lines;
  12390. }
  12391. // remove lines matching prefix from a media section specified by mediaindex
  12392. // TODO: non-numeric mediaindex could match mid
  12393. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  12394. var self = this;
  12395. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  12396. lines.forEach(function(line) {
  12397. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  12398. });
  12399. this.raw = this.session + this.media.join('');
  12400. return lines;
  12401. }
  12402. // add content's to a jingle element
  12403. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  12404. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  12405. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  12406. var self = this;
  12407. // new bundle plan
  12408. if (SDPUtil.find_line(this.session, 'a=group:')) {
  12409. lines = SDPUtil.find_lines(this.session, 'a=group:');
  12410. for (i = 0; i < lines.length; i++) {
  12411. tmp = lines[i].split(' ');
  12412. var semantics = tmp.shift().substr(8);
  12413. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  12414. for (j = 0; j < tmp.length; j++) {
  12415. elem.c('content', {name: tmp[j]}).up();
  12416. }
  12417. elem.up();
  12418. }
  12419. }
  12420. for (i = 0; i < this.media.length; i++) {
  12421. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  12422. if (!(mline.media === 'audio' ||
  12423. mline.media === 'video' ||
  12424. mline.media === 'application'))
  12425. {
  12426. continue;
  12427. }
  12428. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  12429. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  12430. } else {
  12431. if(ssrcs && ssrcs[mline.media])
  12432. {
  12433. ssrc = ssrcs[mline.media];
  12434. }
  12435. else
  12436. ssrc = false;
  12437. }
  12438. elem.c('content', {creator: thecreator, name: mline.media});
  12439. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  12440. // prefer identifier from a=mid if present
  12441. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  12442. elem.attrs({ name: mid });
  12443. }
  12444. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  12445. {
  12446. elem.c('description',
  12447. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  12448. media: mline.media });
  12449. if (ssrc) {
  12450. elem.attrs({ssrc: ssrc});
  12451. }
  12452. for (j = 0; j < mline.fmt.length; j++) {
  12453. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  12454. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  12455. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  12456. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  12457. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  12458. for (k = 0; k < tmp.length; k++) {
  12459. elem.c('parameter', tmp[k]).up();
  12460. }
  12461. }
  12462. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  12463. elem.up();
  12464. }
  12465. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  12466. elem.c('encryption', {required: 1});
  12467. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  12468. crypto.forEach(function(line) {
  12469. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  12470. });
  12471. elem.up(); // end of encryption
  12472. }
  12473. if (ssrc) {
  12474. // new style mapping
  12475. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12476. // FIXME: group by ssrc and support multiple different ssrcs
  12477. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  12478. if(ssrclines.length > 0) {
  12479. ssrclines.forEach(function (line) {
  12480. idx = line.indexOf(' ');
  12481. var linessrc = line.substr(0, idx).substr(7);
  12482. if (linessrc != ssrc) {
  12483. elem.up();
  12484. ssrc = linessrc;
  12485. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12486. }
  12487. var kv = line.substr(idx + 1);
  12488. elem.c('parameter');
  12489. if (kv.indexOf(':') == -1) {
  12490. elem.attrs({ name: kv });
  12491. } else {
  12492. elem.attrs({ name: kv.split(':', 2)[0] });
  12493. elem.attrs({ value: kv.split(':', 2)[1] });
  12494. }
  12495. elem.up();
  12496. });
  12497. elem.up();
  12498. }
  12499. else
  12500. {
  12501. elem.up();
  12502. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12503. elem.c('parameter');
  12504. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  12505. elem.up();
  12506. var msid = null;
  12507. if(mline.media == "audio")
  12508. {
  12509. msid = APP.RTC.localAudio.getId();
  12510. }
  12511. else
  12512. {
  12513. msid = APP.RTC.localVideo.getId();
  12514. }
  12515. if(msid != null)
  12516. {
  12517. msid = msid.replace(/[\{,\}]/g,"");
  12518. elem.c('parameter');
  12519. elem.attrs({name: "msid", value:msid});
  12520. elem.up();
  12521. elem.c('parameter');
  12522. elem.attrs({name: "mslabel", value:msid});
  12523. elem.up();
  12524. elem.c('parameter');
  12525. elem.attrs({name: "label", value:msid});
  12526. elem.up();
  12527. elem.up();
  12528. }
  12529. }
  12530. // XEP-0339 handle ssrc-group attributes
  12531. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  12532. ssrc_group_lines.forEach(function(line) {
  12533. idx = line.indexOf(' ');
  12534. var semantics = line.substr(0, idx).substr(13);
  12535. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12536. if (ssrcs.length != 0) {
  12537. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12538. ssrcs.forEach(function(ssrc) {
  12539. elem.c('source', { ssrc: ssrc })
  12540. .up();
  12541. });
  12542. elem.up();
  12543. }
  12544. });
  12545. }
  12546. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  12547. elem.c('rtcp-mux').up();
  12548. }
  12549. // XEP-0293 -- map a=rtcp-fb:*
  12550. this.RtcpFbToJingle(i, elem, '*');
  12551. // XEP-0294
  12552. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  12553. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  12554. for (j = 0; j < lines.length; j++) {
  12555. tmp = SDPUtil.parse_extmap(lines[j]);
  12556. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  12557. uri: tmp.uri,
  12558. id: tmp.value });
  12559. if (tmp.hasOwnProperty('direction')) {
  12560. switch (tmp.direction) {
  12561. case 'sendonly':
  12562. elem.attrs({senders: 'responder'});
  12563. break;
  12564. case 'recvonly':
  12565. elem.attrs({senders: 'initiator'});
  12566. break;
  12567. case 'sendrecv':
  12568. elem.attrs({senders: 'both'});
  12569. break;
  12570. case 'inactive':
  12571. elem.attrs({senders: 'none'});
  12572. break;
  12573. }
  12574. }
  12575. // TODO: handle params
  12576. elem.up();
  12577. }
  12578. }
  12579. elem.up(); // end of description
  12580. }
  12581. // map ice-ufrag/pwd, dtls fingerprint, candidates
  12582. this.TransportToJingle(i, elem);
  12583. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  12584. elem.attrs({senders: 'both'});
  12585. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  12586. elem.attrs({senders: 'initiator'});
  12587. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  12588. elem.attrs({senders: 'responder'});
  12589. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  12590. elem.attrs({senders: 'none'});
  12591. }
  12592. if (mline.port == '0') {
  12593. // estos hack to reject an m-line
  12594. elem.attrs({senders: 'rejected'});
  12595. }
  12596. elem.up(); // end of content
  12597. }
  12598. elem.up();
  12599. return elem;
  12600. };
  12601. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  12602. var i = mediaindex;
  12603. var tmp;
  12604. var self = this;
  12605. elem.c('transport');
  12606. // XEP-0343 DTLS/SCTP
  12607. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  12608. {
  12609. var sctpmap = SDPUtil.find_line(
  12610. this.media[i], 'a=sctpmap:', self.session);
  12611. if (sctpmap)
  12612. {
  12613. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  12614. elem.c('sctpmap',
  12615. {
  12616. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  12617. number: sctpAttrs[0], /* SCTP port */
  12618. protocol: sctpAttrs[1], /* protocol */
  12619. });
  12620. // Optional stream count attribute
  12621. if (sctpAttrs.length > 2)
  12622. elem.attrs({ streams: sctpAttrs[2]});
  12623. elem.up();
  12624. }
  12625. }
  12626. // XEP-0320
  12627. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  12628. fingerprints.forEach(function(line) {
  12629. tmp = SDPUtil.parse_fingerprint(line);
  12630. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  12631. elem.c('fingerprint').t(tmp.fingerprint);
  12632. delete tmp.fingerprint;
  12633. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  12634. if (line) {
  12635. tmp.setup = line.substr(8);
  12636. }
  12637. elem.attrs(tmp);
  12638. elem.up(); // end of fingerprint
  12639. });
  12640. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  12641. if (tmp) {
  12642. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12643. elem.attrs(tmp);
  12644. // XEP-0176
  12645. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  12646. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  12647. lines.forEach(function (line) {
  12648. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  12649. });
  12650. }
  12651. }
  12652. elem.up(); // end of transport
  12653. }
  12654. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  12655. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  12656. lines.forEach(function (line) {
  12657. var tmp = SDPUtil.parse_rtcpfb(line);
  12658. if (tmp.type == 'trr-int') {
  12659. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  12660. elem.up();
  12661. } else {
  12662. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  12663. if (tmp.params.length > 0) {
  12664. elem.attrs({'subtype': tmp.params[0]});
  12665. }
  12666. elem.up();
  12667. }
  12668. });
  12669. };
  12670. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  12671. var media = '';
  12672. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12673. if (tmp.length) {
  12674. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  12675. if (tmp.attr('value')) {
  12676. media += tmp.attr('value');
  12677. } else {
  12678. media += '0';
  12679. }
  12680. media += '\r\n';
  12681. }
  12682. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12683. tmp.each(function () {
  12684. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  12685. if ($(this).attr('subtype')) {
  12686. media += ' ' + $(this).attr('subtype');
  12687. }
  12688. media += '\r\n';
  12689. });
  12690. return media;
  12691. };
  12692. // construct an SDP from a jingle stanza
  12693. SDP.prototype.fromJingle = function (jingle) {
  12694. var self = this;
  12695. this.raw = 'v=0\r\n' +
  12696. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12697. 's=-\r\n' +
  12698. 't=0 0\r\n';
  12699. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  12700. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  12701. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  12702. var contents = $(group).find('>content').map(function (idx, content) {
  12703. return content.getAttribute('name');
  12704. }).get();
  12705. if (contents.length > 0) {
  12706. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  12707. }
  12708. });
  12709. }
  12710. this.session = this.raw;
  12711. jingle.find('>content').each(function () {
  12712. var m = self.jingle2media($(this));
  12713. self.media.push(m);
  12714. });
  12715. // reconstruct msid-semantic -- apparently not necessary
  12716. /*
  12717. var msid = SDPUtil.parse_ssrc(this.raw);
  12718. if (msid.hasOwnProperty('mslabel')) {
  12719. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  12720. }
  12721. */
  12722. this.raw = this.session + this.media.join('');
  12723. };
  12724. // translate a jingle content element into an an SDP media part
  12725. SDP.prototype.jingle2media = function (content) {
  12726. var media = '',
  12727. desc = content.find('description'),
  12728. ssrc = desc.attr('ssrc'),
  12729. self = this,
  12730. tmp;
  12731. var sctp = content.find(
  12732. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  12733. tmp = { media: desc.attr('media') };
  12734. tmp.port = '1';
  12735. if (content.attr('senders') == 'rejected') {
  12736. // estos hack to reject an m-line.
  12737. tmp.port = '0';
  12738. }
  12739. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  12740. if (sctp.length)
  12741. tmp.proto = 'DTLS/SCTP';
  12742. else
  12743. tmp.proto = 'RTP/SAVPF';
  12744. } else {
  12745. tmp.proto = 'RTP/AVPF';
  12746. }
  12747. if (!sctp.length)
  12748. {
  12749. tmp.fmt = desc.find('payload-type').map(
  12750. function () { return this.getAttribute('id'); }).get();
  12751. media += SDPUtil.build_mline(tmp) + '\r\n';
  12752. }
  12753. else
  12754. {
  12755. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  12756. media += 'a=sctpmap:' + sctp.attr('number') +
  12757. ' ' + sctp.attr('protocol');
  12758. var streamCount = sctp.attr('streams');
  12759. if (streamCount)
  12760. media += ' ' + streamCount + '\r\n';
  12761. else
  12762. media += '\r\n';
  12763. }
  12764. media += 'c=IN IP4 0.0.0.0\r\n';
  12765. if (!sctp.length)
  12766. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  12767. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  12768. if (tmp.length) {
  12769. if (tmp.attr('ufrag')) {
  12770. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  12771. }
  12772. if (tmp.attr('pwd')) {
  12773. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  12774. }
  12775. tmp.find('>fingerprint').each(function () {
  12776. // FIXME: check namespace at some point
  12777. media += 'a=fingerprint:' + this.getAttribute('hash');
  12778. media += ' ' + $(this).text();
  12779. media += '\r\n';
  12780. if (this.getAttribute('setup')) {
  12781. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  12782. }
  12783. });
  12784. }
  12785. switch (content.attr('senders')) {
  12786. case 'initiator':
  12787. media += 'a=sendonly\r\n';
  12788. break;
  12789. case 'responder':
  12790. media += 'a=recvonly\r\n';
  12791. break;
  12792. case 'none':
  12793. media += 'a=inactive\r\n';
  12794. break;
  12795. case 'both':
  12796. media += 'a=sendrecv\r\n';
  12797. break;
  12798. }
  12799. media += 'a=mid:' + content.attr('name') + '\r\n';
  12800. // <description><rtcp-mux/></description>
  12801. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  12802. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  12803. if (desc.find('rtcp-mux').length) {
  12804. media += 'a=rtcp-mux\r\n';
  12805. }
  12806. if (desc.find('encryption').length) {
  12807. desc.find('encryption>crypto').each(function () {
  12808. media += 'a=crypto:' + this.getAttribute('tag');
  12809. media += ' ' + this.getAttribute('crypto-suite');
  12810. media += ' ' + this.getAttribute('key-params');
  12811. if (this.getAttribute('session-params')) {
  12812. media += ' ' + this.getAttribute('session-params');
  12813. }
  12814. media += '\r\n';
  12815. });
  12816. }
  12817. desc.find('payload-type').each(function () {
  12818. media += SDPUtil.build_rtpmap(this) + '\r\n';
  12819. if ($(this).find('>parameter').length) {
  12820. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  12821. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  12822. media += '\r\n';
  12823. }
  12824. // xep-0293
  12825. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  12826. });
  12827. // xep-0293
  12828. media += self.RtcpFbFromJingle(desc, '*');
  12829. // xep-0294
  12830. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  12831. tmp.each(function () {
  12832. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  12833. });
  12834. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  12835. media += SDPUtil.candidateFromJingle(this);
  12836. });
  12837. // XEP-0339 handle ssrc-group attributes
  12838. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12839. var semantics = this.getAttribute('semantics');
  12840. var ssrcs = $(this).find('>source').map(function() {
  12841. return this.getAttribute('ssrc');
  12842. }).get();
  12843. if (ssrcs.length != 0) {
  12844. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12845. }
  12846. });
  12847. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12848. tmp.each(function () {
  12849. var ssrc = this.getAttribute('ssrc');
  12850. $(this).find('>parameter').each(function () {
  12851. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  12852. if (this.getAttribute('value') && this.getAttribute('value').length)
  12853. media += ':' + this.getAttribute('value');
  12854. media += '\r\n';
  12855. });
  12856. });
  12857. return media;
  12858. };
  12859. module.exports = SDP;
  12860. },{"./SDPUtil":54}],53:[function(require,module,exports){
  12861. function SDPDiffer(mySDP, otherSDP) {
  12862. this.mySDP = mySDP;
  12863. this.otherSDP = otherSDP;
  12864. }
  12865. /**
  12866. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  12867. * @param otherSdp the other SDP to check ssrc with.
  12868. */
  12869. SDPDiffer.prototype.getNewMedia = function() {
  12870. // this could be useful in Array.prototype.
  12871. function arrayEquals(array) {
  12872. // if the other array is a falsy value, return
  12873. if (!array)
  12874. return false;
  12875. // compare lengths - can save a lot of time
  12876. if (this.length != array.length)
  12877. return false;
  12878. for (var i = 0, l=this.length; i < l; i++) {
  12879. // Check if we have nested arrays
  12880. if (this[i] instanceof Array && array[i] instanceof Array) {
  12881. // recurse into the nested arrays
  12882. if (!this[i].equals(array[i]))
  12883. return false;
  12884. }
  12885. else if (this[i] != array[i]) {
  12886. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12887. return false;
  12888. }
  12889. }
  12890. return true;
  12891. }
  12892. var myMedias = this.mySDP.getMediaSsrcMap();
  12893. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12894. var newMedia = {};
  12895. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12896. var myMedia = myMedias[othersMediaIdx];
  12897. var othersMedia = othersMedias[othersMediaIdx];
  12898. if(!myMedia && othersMedia) {
  12899. // Add whole channel
  12900. newMedia[othersMediaIdx] = othersMedia;
  12901. return;
  12902. }
  12903. // Look for new ssrcs accross the channel
  12904. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12905. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12906. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12907. if(!newMedia[othersMediaIdx]){
  12908. newMedia[othersMediaIdx] = {
  12909. mediaindex: othersMedia.mediaindex,
  12910. mid: othersMedia.mid,
  12911. ssrcs: {},
  12912. ssrcGroups: []
  12913. };
  12914. }
  12915. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12916. }
  12917. });
  12918. // Look for new ssrc groups across the channels
  12919. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12920. // try to match the other ssrc-group with an ssrc-group of ours
  12921. var matched = false;
  12922. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12923. var mySsrcGroup = myMedia.ssrcGroups[i];
  12924. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12925. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12926. matched = true;
  12927. break;
  12928. }
  12929. }
  12930. if (!matched) {
  12931. // Allocate channel if we've found an ssrc-group that doesn't
  12932. // exist in our channel
  12933. if(!newMedia[othersMediaIdx]){
  12934. newMedia[othersMediaIdx] = {
  12935. mediaindex: othersMedia.mediaindex,
  12936. mid: othersMedia.mid,
  12937. ssrcs: {},
  12938. ssrcGroups: []
  12939. };
  12940. }
  12941. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12942. }
  12943. });
  12944. });
  12945. return newMedia;
  12946. };
  12947. /**
  12948. * Sends SSRC update IQ.
  12949. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12950. * @param sid session identifier that will be put into the IQ.
  12951. * @param initiator initiator identifier.
  12952. * @param toJid destination Jid
  12953. * @param isAdd indicates if this is remove or add operation.
  12954. */
  12955. SDPDiffer.prototype.toJingle = function(modify) {
  12956. var sdpMediaSsrcs = this.getNewMedia();
  12957. var self = this;
  12958. // FIXME: only announce video ssrcs since we mix audio and dont need
  12959. // the audio ssrcs therefore
  12960. var modified = false;
  12961. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12962. modified = true;
  12963. var media = sdpMediaSsrcs[mediaindex];
  12964. modify.c('content', {name: media.mid});
  12965. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12966. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12967. // generate sources from lines
  12968. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12969. var mediaSsrc = media.ssrcs[ssrcNum];
  12970. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12971. modify.attrs({ssrc: mediaSsrc.ssrc});
  12972. // iterate over ssrc lines
  12973. mediaSsrc.lines.forEach(function (line) {
  12974. var idx = line.indexOf(' ');
  12975. var kv = line.substr(idx + 1);
  12976. modify.c('parameter');
  12977. if (kv.indexOf(':') == -1) {
  12978. modify.attrs({ name: kv });
  12979. } else {
  12980. modify.attrs({ name: kv.split(':', 2)[0] });
  12981. modify.attrs({ value: kv.split(':', 2)[1] });
  12982. }
  12983. modify.up(); // end of parameter
  12984. });
  12985. modify.up(); // end of source
  12986. });
  12987. // generate source groups from lines
  12988. media.ssrcGroups.forEach(function(ssrcGroup) {
  12989. if (ssrcGroup.ssrcs.length != 0) {
  12990. modify.c('ssrc-group', {
  12991. semantics: ssrcGroup.semantics,
  12992. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12993. });
  12994. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12995. modify.c('source', { ssrc: ssrc })
  12996. .up(); // end of source
  12997. });
  12998. modify.up(); // end of ssrc-group
  12999. }
  13000. });
  13001. modify.up(); // end of description
  13002. modify.up(); // end of content
  13003. });
  13004. return modified;
  13005. };
  13006. module.exports = SDPDiffer;
  13007. },{}],54:[function(require,module,exports){
  13008. SDPUtil = {
  13009. iceparams: function (mediadesc, sessiondesc) {
  13010. var data = null;
  13011. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  13012. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  13013. data = {
  13014. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  13015. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  13016. };
  13017. }
  13018. return data;
  13019. },
  13020. parse_iceufrag: function (line) {
  13021. return line.substring(12);
  13022. },
  13023. build_iceufrag: function (frag) {
  13024. return 'a=ice-ufrag:' + frag;
  13025. },
  13026. parse_icepwd: function (line) {
  13027. return line.substring(10);
  13028. },
  13029. build_icepwd: function (pwd) {
  13030. return 'a=ice-pwd:' + pwd;
  13031. },
  13032. parse_mid: function (line) {
  13033. return line.substring(6);
  13034. },
  13035. parse_mline: function (line) {
  13036. var parts = line.substring(2).split(' '),
  13037. data = {};
  13038. data.media = parts.shift();
  13039. data.port = parts.shift();
  13040. data.proto = parts.shift();
  13041. if (parts[parts.length - 1] === '') { // trailing whitespace
  13042. parts.pop();
  13043. }
  13044. data.fmt = parts;
  13045. return data;
  13046. },
  13047. build_mline: function (mline) {
  13048. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  13049. },
  13050. parse_rtpmap: function (line) {
  13051. var parts = line.substring(9).split(' '),
  13052. data = {};
  13053. data.id = parts.shift();
  13054. parts = parts[0].split('/');
  13055. data.name = parts.shift();
  13056. data.clockrate = parts.shift();
  13057. data.channels = parts.length ? parts.shift() : '1';
  13058. return data;
  13059. },
  13060. /**
  13061. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  13062. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  13063. * @returns [SCTP port number, protocol, streams]
  13064. */
  13065. parse_sctpmap: function (line)
  13066. {
  13067. var parts = line.substring(10).split(' ');
  13068. var sctpPort = parts[0];
  13069. var protocol = parts[1];
  13070. // Stream count is optional
  13071. var streamCount = parts.length > 2 ? parts[2] : null;
  13072. return [sctpPort, protocol, streamCount];// SCTP port
  13073. },
  13074. build_rtpmap: function (el) {
  13075. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  13076. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  13077. line += '/' + el.getAttribute('channels');
  13078. }
  13079. return line;
  13080. },
  13081. parse_crypto: function (line) {
  13082. var parts = line.substring(9).split(' '),
  13083. data = {};
  13084. data.tag = parts.shift();
  13085. data['crypto-suite'] = parts.shift();
  13086. data['key-params'] = parts.shift();
  13087. if (parts.length) {
  13088. data['session-params'] = parts.join(' ');
  13089. }
  13090. return data;
  13091. },
  13092. parse_fingerprint: function (line) { // RFC 4572
  13093. var parts = line.substring(14).split(' '),
  13094. data = {};
  13095. data.hash = parts.shift();
  13096. data.fingerprint = parts.shift();
  13097. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  13098. return data;
  13099. },
  13100. parse_fmtp: function (line) {
  13101. var parts = line.split(' '),
  13102. i, key, value,
  13103. data = [];
  13104. parts.shift();
  13105. parts = parts.join(' ').split(';');
  13106. for (i = 0; i < parts.length; i++) {
  13107. key = parts[i].split('=')[0];
  13108. while (key.length && key[0] == ' ') {
  13109. key = key.substring(1);
  13110. }
  13111. value = parts[i].split('=')[1];
  13112. if (key && value) {
  13113. data.push({name: key, value: value});
  13114. } else if (key) {
  13115. // rfc 4733 (DTMF) style stuff
  13116. data.push({name: '', value: key});
  13117. }
  13118. }
  13119. return data;
  13120. },
  13121. parse_icecandidate: function (line) {
  13122. var candidate = {},
  13123. elems = line.split(' ');
  13124. candidate.foundation = elems[0].substring(12);
  13125. candidate.component = elems[1];
  13126. candidate.protocol = elems[2].toLowerCase();
  13127. candidate.priority = elems[3];
  13128. candidate.ip = elems[4];
  13129. candidate.port = elems[5];
  13130. // elems[6] => "typ"
  13131. candidate.type = elems[7];
  13132. candidate.generation = 0; // default value, may be overwritten below
  13133. for (var i = 8; i < elems.length; i += 2) {
  13134. switch (elems[i]) {
  13135. case 'raddr':
  13136. candidate['rel-addr'] = elems[i + 1];
  13137. break;
  13138. case 'rport':
  13139. candidate['rel-port'] = elems[i + 1];
  13140. break;
  13141. case 'generation':
  13142. candidate.generation = elems[i + 1];
  13143. break;
  13144. case 'tcptype':
  13145. candidate.tcptype = elems[i + 1];
  13146. break;
  13147. default: // TODO
  13148. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13149. }
  13150. }
  13151. candidate.network = '1';
  13152. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13153. return candidate;
  13154. },
  13155. build_icecandidate: function (cand) {
  13156. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  13157. line += ' ';
  13158. switch (cand.type) {
  13159. case 'srflx':
  13160. case 'prflx':
  13161. case 'relay':
  13162. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  13163. line += 'raddr';
  13164. line += ' ';
  13165. line += cand['rel-addr'];
  13166. line += ' ';
  13167. line += 'rport';
  13168. line += ' ';
  13169. line += cand['rel-port'];
  13170. line += ' ';
  13171. }
  13172. break;
  13173. }
  13174. if (cand.hasOwnAttribute('tcptype')) {
  13175. line += 'tcptype';
  13176. line += ' ';
  13177. line += cand.tcptype;
  13178. line += ' ';
  13179. }
  13180. line += 'generation';
  13181. line += ' ';
  13182. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  13183. return line;
  13184. },
  13185. parse_ssrc: function (desc) {
  13186. // proprietary mapping of a=ssrc lines
  13187. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  13188. // and parse according to that
  13189. var lines = desc.split('\r\n'),
  13190. data = {};
  13191. for (var i = 0; i < lines.length; i++) {
  13192. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  13193. var idx = lines[i].indexOf(' ');
  13194. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  13195. }
  13196. }
  13197. return data;
  13198. },
  13199. parse_rtcpfb: function (line) {
  13200. var parts = line.substr(10).split(' ');
  13201. var data = {};
  13202. data.pt = parts.shift();
  13203. data.type = parts.shift();
  13204. data.params = parts;
  13205. return data;
  13206. },
  13207. parse_extmap: function (line) {
  13208. var parts = line.substr(9).split(' ');
  13209. var data = {};
  13210. data.value = parts.shift();
  13211. if (data.value.indexOf('/') != -1) {
  13212. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  13213. data.value = data.value.substr(0, data.value.indexOf('/'));
  13214. } else {
  13215. data.direction = 'both';
  13216. }
  13217. data.uri = parts.shift();
  13218. data.params = parts;
  13219. return data;
  13220. },
  13221. find_line: function (haystack, needle, sessionpart) {
  13222. var lines = haystack.split('\r\n');
  13223. for (var i = 0; i < lines.length; i++) {
  13224. if (lines[i].substring(0, needle.length) == needle) {
  13225. return lines[i];
  13226. }
  13227. }
  13228. if (!sessionpart) {
  13229. return false;
  13230. }
  13231. // search session part
  13232. lines = sessionpart.split('\r\n');
  13233. for (var j = 0; j < lines.length; j++) {
  13234. if (lines[j].substring(0, needle.length) == needle) {
  13235. return lines[j];
  13236. }
  13237. }
  13238. return false;
  13239. },
  13240. find_lines: function (haystack, needle, sessionpart) {
  13241. var lines = haystack.split('\r\n'),
  13242. needles = [];
  13243. for (var i = 0; i < lines.length; i++) {
  13244. if (lines[i].substring(0, needle.length) == needle)
  13245. needles.push(lines[i]);
  13246. }
  13247. if (needles.length || !sessionpart) {
  13248. return needles;
  13249. }
  13250. // search session part
  13251. lines = sessionpart.split('\r\n');
  13252. for (var j = 0; j < lines.length; j++) {
  13253. if (lines[j].substring(0, needle.length) == needle) {
  13254. needles.push(lines[j]);
  13255. }
  13256. }
  13257. return needles;
  13258. },
  13259. candidateToJingle: function (line) {
  13260. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  13261. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  13262. if (line.indexOf('candidate:') === 0) {
  13263. line = 'a=' + line;
  13264. } else if (line.substring(0, 12) != 'a=candidate:') {
  13265. console.log('parseCandidate called with a line that is not a candidate line');
  13266. console.log(line);
  13267. return null;
  13268. }
  13269. if (line.substring(line.length - 2) == '\r\n') // chomp it
  13270. line = line.substring(0, line.length - 2);
  13271. var candidate = {},
  13272. elems = line.split(' '),
  13273. i;
  13274. if (elems[6] != 'typ') {
  13275. console.log('did not find typ in the right place');
  13276. console.log(line);
  13277. return null;
  13278. }
  13279. candidate.foundation = elems[0].substring(12);
  13280. candidate.component = elems[1];
  13281. candidate.protocol = elems[2].toLowerCase();
  13282. candidate.priority = elems[3];
  13283. candidate.ip = elems[4];
  13284. candidate.port = elems[5];
  13285. // elems[6] => "typ"
  13286. candidate.type = elems[7];
  13287. candidate.generation = '0'; // default, may be overwritten below
  13288. for (i = 8; i < elems.length; i += 2) {
  13289. switch (elems[i]) {
  13290. case 'raddr':
  13291. candidate['rel-addr'] = elems[i + 1];
  13292. break;
  13293. case 'rport':
  13294. candidate['rel-port'] = elems[i + 1];
  13295. break;
  13296. case 'generation':
  13297. candidate.generation = elems[i + 1];
  13298. break;
  13299. case 'tcptype':
  13300. candidate.tcptype = elems[i + 1];
  13301. break;
  13302. default: // TODO
  13303. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13304. }
  13305. }
  13306. candidate.network = '1';
  13307. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13308. return candidate;
  13309. },
  13310. candidateFromJingle: function (cand) {
  13311. var line = 'a=candidate:';
  13312. line += cand.getAttribute('foundation');
  13313. line += ' ';
  13314. line += cand.getAttribute('component');
  13315. line += ' ';
  13316. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  13317. line += ' ';
  13318. line += cand.getAttribute('priority');
  13319. line += ' ';
  13320. line += cand.getAttribute('ip');
  13321. line += ' ';
  13322. line += cand.getAttribute('port');
  13323. line += ' ';
  13324. line += 'typ';
  13325. line += ' ' + cand.getAttribute('type');
  13326. line += ' ';
  13327. switch (cand.getAttribute('type')) {
  13328. case 'srflx':
  13329. case 'prflx':
  13330. case 'relay':
  13331. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  13332. line += 'raddr';
  13333. line += ' ';
  13334. line += cand.getAttribute('rel-addr');
  13335. line += ' ';
  13336. line += 'rport';
  13337. line += ' ';
  13338. line += cand.getAttribute('rel-port');
  13339. line += ' ';
  13340. }
  13341. break;
  13342. }
  13343. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  13344. line += 'tcptype';
  13345. line += ' ';
  13346. line += cand.getAttribute('tcptype');
  13347. line += ' ';
  13348. }
  13349. line += 'generation';
  13350. line += ' ';
  13351. line += cand.getAttribute('generation') || '0';
  13352. return line + '\r\n';
  13353. }
  13354. };
  13355. module.exports = SDPUtil;
  13356. },{}],55:[function(require,module,exports){
  13357. function TraceablePeerConnection(ice_config, constraints) {
  13358. var self = this;
  13359. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  13360. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  13361. this.updateLog = [];
  13362. this.stats = {};
  13363. this.statsinterval = null;
  13364. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  13365. var Interop = require('sdp-interop').Interop;
  13366. this.interop = new Interop();
  13367. // override as desired
  13368. this.trace = function (what, info) {
  13369. //console.warn('WTRACE', what, info);
  13370. self.updateLog.push({
  13371. time: new Date(),
  13372. type: what,
  13373. value: info || ""
  13374. });
  13375. };
  13376. this.onicecandidate = null;
  13377. this.peerconnection.onicecandidate = function (event) {
  13378. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  13379. if (self.onicecandidate !== null) {
  13380. self.onicecandidate(event);
  13381. }
  13382. };
  13383. this.onaddstream = null;
  13384. this.peerconnection.onaddstream = function (event) {
  13385. self.trace('onaddstream', event.stream.id);
  13386. if (self.onaddstream !== null) {
  13387. self.onaddstream(event);
  13388. }
  13389. };
  13390. this.onremovestream = null;
  13391. this.peerconnection.onremovestream = function (event) {
  13392. self.trace('onremovestream', event.stream.id);
  13393. if (self.onremovestream !== null) {
  13394. self.onremovestream(event);
  13395. }
  13396. };
  13397. this.onsignalingstatechange = null;
  13398. this.peerconnection.onsignalingstatechange = function (event) {
  13399. self.trace('onsignalingstatechange', self.signalingState);
  13400. if (self.onsignalingstatechange !== null) {
  13401. self.onsignalingstatechange(event);
  13402. }
  13403. };
  13404. this.oniceconnectionstatechange = null;
  13405. this.peerconnection.oniceconnectionstatechange = function (event) {
  13406. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  13407. if (self.oniceconnectionstatechange !== null) {
  13408. self.oniceconnectionstatechange(event);
  13409. }
  13410. };
  13411. this.onnegotiationneeded = null;
  13412. this.peerconnection.onnegotiationneeded = function (event) {
  13413. self.trace('onnegotiationneeded');
  13414. if (self.onnegotiationneeded !== null) {
  13415. self.onnegotiationneeded(event);
  13416. }
  13417. };
  13418. self.ondatachannel = null;
  13419. this.peerconnection.ondatachannel = function (event) {
  13420. self.trace('ondatachannel', event);
  13421. if (self.ondatachannel !== null) {
  13422. self.ondatachannel(event);
  13423. }
  13424. };
  13425. if (!navigator.mozGetUserMedia && this.maxstats) {
  13426. this.statsinterval = window.setInterval(function() {
  13427. self.peerconnection.getStats(function(stats) {
  13428. var results = stats.result();
  13429. for (var i = 0; i < results.length; ++i) {
  13430. //console.log(results[i].type, results[i].id, results[i].names())
  13431. var now = new Date();
  13432. results[i].names().forEach(function (name) {
  13433. var id = results[i].id + '-' + name;
  13434. if (!self.stats[id]) {
  13435. self.stats[id] = {
  13436. startTime: now,
  13437. endTime: now,
  13438. values: [],
  13439. times: []
  13440. };
  13441. }
  13442. self.stats[id].values.push(results[i].stat(name));
  13443. self.stats[id].times.push(now.getTime());
  13444. if (self.stats[id].values.length > self.maxstats) {
  13445. self.stats[id].values.shift();
  13446. self.stats[id].times.shift();
  13447. }
  13448. self.stats[id].endTime = now;
  13449. });
  13450. }
  13451. });
  13452. }, 1000);
  13453. }
  13454. };
  13455. dumpSDP = function(description) {
  13456. if (typeof description === 'undefined' || description == null) {
  13457. return '';
  13458. }
  13459. return 'type: ' + description.type + '\r\n' + description.sdp;
  13460. };
  13461. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  13462. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  13463. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  13464. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  13465. this.trace('getLocalDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.localDescription));
  13466. // if we're running on FF, transform to Plan B first.
  13467. var desc = this.peerconnection.localDescription;
  13468. if (navigator.mozGetUserMedia) {
  13469. desc = this.interop.toPlanB(desc);
  13470. } else {
  13471. desc = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  13472. }
  13473. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  13474. return desc;
  13475. });
  13476. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  13477. this.trace('getRemoteDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.remoteDescription));
  13478. // if we're running on FF, transform to Plan B first.
  13479. var desc = this.peerconnection.remoteDescription;
  13480. if (navigator.mozGetUserMedia) {
  13481. desc = this.interop.toPlanB(desc);
  13482. } else {
  13483. desc = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  13484. }
  13485. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  13486. return desc;
  13487. });
  13488. }
  13489. TraceablePeerConnection.prototype.addStream = function (stream) {
  13490. this.trace('addStream', stream.id);
  13491. APP.simulcast.resetSender();
  13492. try
  13493. {
  13494. this.peerconnection.addStream(stream);
  13495. }
  13496. catch (e)
  13497. {
  13498. console.error(e);
  13499. return;
  13500. }
  13501. };
  13502. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  13503. this.trace('removeStream', stream.id);
  13504. APP.simulcast.resetSender();
  13505. if(stopStreams) {
  13506. stream.getAudioTracks().forEach(function (track) {
  13507. track.stop();
  13508. });
  13509. stream.getVideoTracks().forEach(function (track) {
  13510. track.stop();
  13511. });
  13512. }
  13513. try {
  13514. // FF doesn't support this yet.
  13515. this.peerconnection.removeStream(stream);
  13516. } catch (e) {
  13517. console.error(e);
  13518. }
  13519. };
  13520. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  13521. this.trace('createDataChannel', label, opts);
  13522. return this.peerconnection.createDataChannel(label, opts);
  13523. };
  13524. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  13525. this.trace('setLocalDescription::preTransform (Plan B)', dumpSDP(description));
  13526. // if we're running on FF, transform to Plan A first.
  13527. if (navigator.mozGetUserMedia) {
  13528. description = this.interop.toUnifiedPlan(description);
  13529. } else {
  13530. description = APP.simulcast.transformLocalDescription(description);
  13531. }
  13532. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  13533. var self = this;
  13534. this.peerconnection.setLocalDescription(description,
  13535. function () {
  13536. self.trace('setLocalDescriptionOnSuccess');
  13537. successCallback();
  13538. },
  13539. function (err) {
  13540. self.trace('setLocalDescriptionOnFailure', err);
  13541. failureCallback(err);
  13542. }
  13543. );
  13544. /*
  13545. if (this.statsinterval === null && this.maxstats > 0) {
  13546. // start gathering stats
  13547. }
  13548. */
  13549. };
  13550. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  13551. this.trace('setRemoteDescription::preTransform (Plan B)', dumpSDP(description));
  13552. // if we're running on FF, transform to Plan A first.
  13553. if (navigator.mozGetUserMedia) {
  13554. description = this.interop.toUnifiedPlan(description);
  13555. }
  13556. else {
  13557. description = APP.simulcast.transformRemoteDescription(description);
  13558. }
  13559. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  13560. var self = this;
  13561. this.peerconnection.setRemoteDescription(description,
  13562. function () {
  13563. self.trace('setRemoteDescriptionOnSuccess');
  13564. successCallback();
  13565. },
  13566. function (err) {
  13567. self.trace('setRemoteDescriptionOnFailure', err);
  13568. failureCallback(err);
  13569. }
  13570. );
  13571. /*
  13572. if (this.statsinterval === null && this.maxstats > 0) {
  13573. // start gathering stats
  13574. }
  13575. */
  13576. };
  13577. TraceablePeerConnection.prototype.close = function () {
  13578. this.trace('stop');
  13579. if (this.statsinterval !== null) {
  13580. window.clearInterval(this.statsinterval);
  13581. this.statsinterval = null;
  13582. }
  13583. this.peerconnection.close();
  13584. };
  13585. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  13586. var self = this;
  13587. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  13588. this.peerconnection.createOffer(
  13589. function (offer) {
  13590. self.trace('createOfferOnSuccess::preTransform (Plan A)', dumpSDP(offer));
  13591. // if we're running on FF, transform to Plan B first.
  13592. if (navigator.mozGetUserMedia) {
  13593. offer = self.interop.toPlanB(offer);
  13594. }
  13595. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  13596. successCallback(offer);
  13597. },
  13598. function(err) {
  13599. self.trace('createOfferOnFailure', err);
  13600. failureCallback(err);
  13601. },
  13602. constraints
  13603. );
  13604. };
  13605. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  13606. var self = this;
  13607. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  13608. this.peerconnection.createAnswer(
  13609. function (answer) {
  13610. self.trace('createAnswerOnSuccess::preTransfom (Plan A)', dumpSDP(answer));
  13611. // if we're running on FF, transform to Plan A first.
  13612. if (navigator.mozGetUserMedia) {
  13613. answer = self.interop.toPlanB(answer);
  13614. } else {
  13615. answer = APP.simulcast.transformAnswer(answer);
  13616. }
  13617. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  13618. successCallback(answer);
  13619. },
  13620. function(err) {
  13621. self.trace('createAnswerOnFailure', err);
  13622. failureCallback(err);
  13623. },
  13624. constraints
  13625. );
  13626. };
  13627. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  13628. var self = this;
  13629. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  13630. this.peerconnection.addIceCandidate(candidate);
  13631. /* maybe later
  13632. this.peerconnection.addIceCandidate(candidate,
  13633. function () {
  13634. self.trace('addIceCandidateOnSuccess');
  13635. successCallback();
  13636. },
  13637. function (err) {
  13638. self.trace('addIceCandidateOnFailure', err);
  13639. failureCallback(err);
  13640. }
  13641. );
  13642. */
  13643. };
  13644. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  13645. if (navigator.mozGetUserMedia) {
  13646. // ignore for now...
  13647. if(!errback)
  13648. errback = function () {
  13649. }
  13650. this.peerconnection.getStats(null,callback,errback);
  13651. } else {
  13652. this.peerconnection.getStats(callback);
  13653. }
  13654. };
  13655. module.exports = TraceablePeerConnection;
  13656. },{"sdp-interop":87}],56:[function(require,module,exports){
  13657. /* global $, $iq, APP, config, connection, UI, messageHandler,
  13658. roomName, sessionTerminated, Strophe, Util */
  13659. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13660. var Settings = require("../settings/Settings");
  13661. var AuthenticationEvents
  13662. = require("../../service/authentication/AuthenticationEvents");
  13663. /**
  13664. * Contains logic responsible for enabling/disabling functionality available
  13665. * only to moderator users.
  13666. */
  13667. var connection = null;
  13668. var focusUserJid;
  13669. function createExpBackoffTimer(step) {
  13670. var count = 1;
  13671. return function (reset) {
  13672. // Reset call
  13673. if (reset) {
  13674. count = 1;
  13675. return;
  13676. }
  13677. // Calculate next timeout
  13678. var timeout = Math.pow(2, count - 1);
  13679. count += 1;
  13680. return timeout * step;
  13681. };
  13682. }
  13683. var getNextTimeout = createExpBackoffTimer(1000);
  13684. var getNextErrorTimeout = createExpBackoffTimer(1000);
  13685. // External authentication stuff
  13686. var externalAuthEnabled = false;
  13687. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  13688. // it will be enabled automatically if focus detects the component through
  13689. // service discovery.
  13690. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  13691. var eventEmitter = null;
  13692. var Moderator = {
  13693. isModerator: function () {
  13694. return connection && connection.emuc.isModerator();
  13695. },
  13696. isPeerModerator: function (peerJid) {
  13697. return connection &&
  13698. connection.emuc.getMemberRole(peerJid) === 'moderator';
  13699. },
  13700. isExternalAuthEnabled: function () {
  13701. return externalAuthEnabled;
  13702. },
  13703. isSipGatewayEnabled: function () {
  13704. return sipGatewayEnabled;
  13705. },
  13706. setConnection: function (con) {
  13707. connection = con;
  13708. },
  13709. init: function (xmpp, emitter) {
  13710. this.xmppService = xmpp;
  13711. eventEmitter = emitter;
  13712. // Message listener that talks to POPUP window
  13713. function listener(event) {
  13714. if (event.data && event.data.sessionId) {
  13715. if (event.origin !== window.location.origin) {
  13716. console.warn(
  13717. "Ignoring sessionId from different origin: " + event.origin);
  13718. return;
  13719. }
  13720. localStorage.setItem('sessionId', event.data.sessionId);
  13721. // After popup is closed we will authenticate
  13722. }
  13723. }
  13724. // Register
  13725. if (window.addEventListener) {
  13726. window.addEventListener("message", listener, false);
  13727. } else {
  13728. window.attachEvent("onmessage", listener);
  13729. }
  13730. },
  13731. onMucMemberLeft: function (jid) {
  13732. console.info("Someone left is it focus ? " + jid);
  13733. var resource = Strophe.getResourceFromJid(jid);
  13734. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  13735. console.info(
  13736. "Focus has left the room - leaving conference");
  13737. //hangUp();
  13738. // We'd rather reload to have everything re-initialized
  13739. // FIXME: show some message before reload
  13740. location.reload();
  13741. }
  13742. },
  13743. setFocusUserJid: function (focusJid) {
  13744. if (!focusUserJid) {
  13745. focusUserJid = focusJid;
  13746. console.info("Focus jid set to: " + focusUserJid);
  13747. }
  13748. },
  13749. getFocusUserJid: function () {
  13750. return focusUserJid;
  13751. },
  13752. getFocusComponent: function () {
  13753. // Get focus component address
  13754. var focusComponent = config.hosts.focus;
  13755. // If not specified use default: 'focus.domain'
  13756. if (!focusComponent) {
  13757. focusComponent = 'focus.' + config.hosts.domain;
  13758. }
  13759. return focusComponent;
  13760. },
  13761. createConferenceIq: function (roomName) {
  13762. // Generate create conference IQ
  13763. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13764. // Session Id used for authentication
  13765. var sessionId = localStorage.getItem('sessionId');
  13766. var machineUID = Settings.getSettings().uid;
  13767. console.info(
  13768. "Session ID: " + sessionId + " machine UID: " + machineUID);
  13769. elem.c('conference', {
  13770. xmlns: 'http://jitsi.org/protocol/focus',
  13771. room: roomName,
  13772. 'machine-uid': machineUID
  13773. });
  13774. if (sessionId) {
  13775. elem.attrs({ 'session-id': sessionId});
  13776. }
  13777. if (config.hosts.bridge !== undefined) {
  13778. elem.c(
  13779. 'property',
  13780. { name: 'bridge', value: config.hosts.bridge})
  13781. .up();
  13782. }
  13783. // Tell the focus we have Jigasi configured
  13784. if (config.hosts.call_control !== undefined) {
  13785. elem.c(
  13786. 'property',
  13787. { name: 'call_control', value: config.hosts.call_control})
  13788. .up();
  13789. }
  13790. if (config.channelLastN !== undefined) {
  13791. elem.c(
  13792. 'property',
  13793. { name: 'channelLastN', value: config.channelLastN})
  13794. .up();
  13795. }
  13796. if (config.adaptiveLastN !== undefined) {
  13797. elem.c(
  13798. 'property',
  13799. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  13800. .up();
  13801. }
  13802. if (config.adaptiveSimulcast !== undefined) {
  13803. elem.c(
  13804. 'property',
  13805. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  13806. .up();
  13807. }
  13808. if (config.openSctp !== undefined) {
  13809. elem.c(
  13810. 'property',
  13811. { name: 'openSctp', value: config.openSctp})
  13812. .up();
  13813. }
  13814. if(config.startAudioMuted !== undefined)
  13815. {
  13816. elem.c(
  13817. 'property',
  13818. { name: 'startAudioMuted', value: config.startAudioMuted})
  13819. .up();
  13820. }
  13821. if(config.startVideoMuted !== undefined)
  13822. {
  13823. elem.c(
  13824. 'property',
  13825. { name: 'startVideoMuted', value: config.startVideoMuted})
  13826. .up();
  13827. }
  13828. elem.up();
  13829. return elem;
  13830. },
  13831. parseSessionId: function (resultIq) {
  13832. var sessionId = $(resultIq).find('conference').attr('session-id');
  13833. if (sessionId) {
  13834. console.info('Received sessionId: ' + sessionId);
  13835. localStorage.setItem('sessionId', sessionId);
  13836. }
  13837. },
  13838. parseConfigOptions: function (resultIq) {
  13839. Moderator.setFocusUserJid(
  13840. $(resultIq).find('conference').attr('focusjid'));
  13841. var authenticationEnabled
  13842. = $(resultIq).find(
  13843. '>conference>property' +
  13844. '[name=\'authentication\'][value=\'true\']').length > 0;
  13845. console.info("Authentication enabled: " + authenticationEnabled);
  13846. externalAuthEnabled
  13847. = $(resultIq).find(
  13848. '>conference>property' +
  13849. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  13850. console.info('External authentication enabled: ' + externalAuthEnabled);
  13851. if (!externalAuthEnabled) {
  13852. // We expect to receive sessionId in 'internal' authentication mode
  13853. Moderator.parseSessionId(resultIq);
  13854. }
  13855. var authIdentity = $(resultIq).find('>conference').attr('identity');
  13856. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  13857. authenticationEnabled, authIdentity);
  13858. // Check if focus has auto-detected Jigasi component(this will be also
  13859. // included if we have passed our host from the config)
  13860. if ($(resultIq).find(
  13861. '>conference>property' +
  13862. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  13863. sipGatewayEnabled = true;
  13864. }
  13865. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  13866. },
  13867. // FIXME: we need to show the fact that we're waiting for the focus
  13868. // to the user(or that focus is not available)
  13869. allocateConferenceFocus: function (roomName, callback) {
  13870. // Try to use focus user JID from the config
  13871. Moderator.setFocusUserJid(config.focusUserJid);
  13872. // Send create conference IQ
  13873. var iq = Moderator.createConferenceIq(roomName);
  13874. var self = this;
  13875. connection.sendIQ(
  13876. iq,
  13877. function (result) {
  13878. // Setup config options
  13879. Moderator.parseConfigOptions(result);
  13880. if ('true' === $(result).find('conference').attr('ready')) {
  13881. // Reset both timers
  13882. getNextTimeout(true);
  13883. getNextErrorTimeout(true);
  13884. // Exec callback
  13885. callback();
  13886. } else {
  13887. var waitMs = getNextTimeout();
  13888. console.info("Waiting for the focus... " + waitMs);
  13889. // Reset error timeout
  13890. getNextErrorTimeout(true);
  13891. window.setTimeout(
  13892. function () {
  13893. Moderator.allocateConferenceFocus(
  13894. roomName, callback);
  13895. }, waitMs);
  13896. }
  13897. },
  13898. function (error) {
  13899. // Invalid session ? remove and try again
  13900. // without session ID to get a new one
  13901. var invalidSession
  13902. = $(error).find('>error>session-invalid').length;
  13903. if (invalidSession) {
  13904. console.info("Session expired! - removing");
  13905. localStorage.removeItem("sessionId");
  13906. }
  13907. if ($(error).find('>error>graceful-shutdown').length) {
  13908. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  13909. return;
  13910. }
  13911. // Check for error returned by the reservation system
  13912. var reservationErr = $(error).find('>error>reservation-error');
  13913. if (reservationErr.length) {
  13914. // Trigger error event
  13915. var errorCode = reservationErr.attr('error-code');
  13916. var errorMsg;
  13917. if ($(error).find('>error>text')) {
  13918. errorMsg = $(error).find('>error>text').text();
  13919. }
  13920. eventEmitter.emit(
  13921. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  13922. return;
  13923. }
  13924. // Not authorized to create new room
  13925. if ($(error).find('>error>not-authorized').length) {
  13926. console.warn("Unauthorized to start the conference", error);
  13927. var toDomain
  13928. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13929. if (toDomain !== config.hosts.anonymousdomain) {
  13930. // FIXME: "is external" should come either from
  13931. // the focus or config.js
  13932. externalAuthEnabled = true;
  13933. }
  13934. eventEmitter.emit(
  13935. XMPPEvents.AUTHENTICATION_REQUIRED,
  13936. function () {
  13937. Moderator.allocateConferenceFocus(
  13938. roomName, callback);
  13939. });
  13940. return;
  13941. }
  13942. var waitMs = getNextErrorTimeout();
  13943. console.error("Focus error, retry after " + waitMs, error);
  13944. // Show message
  13945. var focusComponent = Moderator.getFocusComponent();
  13946. var retrySec = waitMs / 1000;
  13947. // FIXME: message is duplicated ?
  13948. // Do not show in case of session invalid
  13949. // which means just a retry
  13950. if (!invalidSession) {
  13951. APP.UI.messageHandler.notify(
  13952. null, "notify.focus",
  13953. 'disconnected', "notify.focusFail",
  13954. {component: focusComponent, ms: retrySec});
  13955. }
  13956. // Reset response timeout
  13957. getNextTimeout(true);
  13958. window.setTimeout(
  13959. function () {
  13960. Moderator.allocateConferenceFocus(roomName, callback);
  13961. }, waitMs);
  13962. }
  13963. );
  13964. },
  13965. getLoginUrl: function (roomName, urlCallback) {
  13966. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13967. iq.c('login-url', {
  13968. xmlns: 'http://jitsi.org/protocol/focus',
  13969. room: roomName,
  13970. 'machine-uid': Settings.getSettings().uid
  13971. });
  13972. connection.sendIQ(
  13973. iq,
  13974. function (result) {
  13975. var url = $(result).find('login-url').attr('url');
  13976. url = url = decodeURIComponent(url);
  13977. if (url) {
  13978. console.info("Got auth url: " + url);
  13979. urlCallback(url);
  13980. } else {
  13981. console.error(
  13982. "Failed to get auth url from the focus", result);
  13983. }
  13984. },
  13985. function (error) {
  13986. console.error("Get auth url error", error);
  13987. }
  13988. );
  13989. },
  13990. getPopupLoginUrl: function (roomName, urlCallback) {
  13991. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13992. iq.c('login-url', {
  13993. xmlns: 'http://jitsi.org/protocol/focus',
  13994. room: roomName,
  13995. 'machine-uid': Settings.getSettings().uid,
  13996. popup: true
  13997. });
  13998. connection.sendIQ(
  13999. iq,
  14000. function (result) {
  14001. var url = $(result).find('login-url').attr('url');
  14002. url = url = decodeURIComponent(url);
  14003. if (url) {
  14004. console.info("Got POPUP auth url: " + url);
  14005. urlCallback(url);
  14006. } else {
  14007. console.error(
  14008. "Failed to get POPUP auth url from the focus", result);
  14009. }
  14010. },
  14011. function (error) {
  14012. console.error('Get POPUP auth url error', error);
  14013. }
  14014. );
  14015. },
  14016. logout: function (callback) {
  14017. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14018. var sessionId = localStorage.getItem('sessionId');
  14019. if (!sessionId) {
  14020. callback();
  14021. return;
  14022. }
  14023. iq.c('logout', {
  14024. xmlns: 'http://jitsi.org/protocol/focus',
  14025. 'session-id': sessionId
  14026. });
  14027. connection.sendIQ(
  14028. iq,
  14029. function (result) {
  14030. var logoutUrl = $(result).find('logout').attr('logout-url');
  14031. if (logoutUrl) {
  14032. logoutUrl = decodeURIComponent(logoutUrl);
  14033. }
  14034. console.info("Log out OK, url: " + logoutUrl, result);
  14035. localStorage.removeItem('sessionId');
  14036. callback(logoutUrl);
  14037. },
  14038. function (error) {
  14039. console.error("Logout error", error);
  14040. }
  14041. );
  14042. }
  14043. };
  14044. module.exports = Moderator;
  14045. },{"../../service/authentication/AuthenticationEvents":100,"../../service/xmpp/XMPPEvents":105,"../settings/Settings":41}],57:[function(require,module,exports){
  14046. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  14047. Toolbar, Util */
  14048. var Moderator = require("./moderator");
  14049. var recordingToken = null;
  14050. var recordingEnabled;
  14051. /**
  14052. * Whether to use a jirecon component for recording, or use the videobridge
  14053. * through COLIBRI.
  14054. */
  14055. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  14056. /**
  14057. * The ID of the jirecon recording session. Jirecon generates it when we
  14058. * initially start recording, and it needs to be used in subsequent requests
  14059. * to jirecon.
  14060. */
  14061. var jireconRid = null;
  14062. function setRecordingToken(token) {
  14063. recordingToken = token;
  14064. }
  14065. function setRecording(state, token, callback, connection) {
  14066. if (useJirecon){
  14067. setRecordingJirecon(state, token, callback, connection);
  14068. } else {
  14069. setRecordingColibri(state, token, callback, connection);
  14070. }
  14071. }
  14072. function setRecordingJirecon(state, token, callback, connection) {
  14073. if (state == recordingEnabled){
  14074. return;
  14075. }
  14076. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  14077. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  14078. action: state ? 'start' : 'stop',
  14079. mucjid: connection.emuc.roomjid});
  14080. if (!state){
  14081. iq.attrs({rid: jireconRid});
  14082. }
  14083. console.log('Start recording');
  14084. connection.sendIQ(
  14085. iq,
  14086. function (result) {
  14087. // TODO wait for an IQ with the real status, since this is
  14088. // provisional?
  14089. jireconRid = $(result).find('recording').attr('rid');
  14090. console.log('Recording ' + (state ? 'started' : 'stopped') +
  14091. '(jirecon)' + result);
  14092. recordingEnabled = state;
  14093. if (!state){
  14094. jireconRid = null;
  14095. }
  14096. callback(state);
  14097. },
  14098. function (error) {
  14099. console.log('Failed to start recording, error: ', error);
  14100. callback(recordingEnabled);
  14101. });
  14102. }
  14103. // Sends a COLIBRI message which enables or disables (according to 'state')
  14104. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  14105. // with the new recording state, according to the IQ.
  14106. function setRecordingColibri(state, token, callback, connection) {
  14107. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  14108. elem.c('conference', {
  14109. xmlns: 'http://jitsi.org/protocol/colibri'
  14110. });
  14111. elem.c('recording', {state: state, token: token});
  14112. connection.sendIQ(elem,
  14113. function (result) {
  14114. console.log('Set recording "', state, '". Result:', result);
  14115. var recordingElem = $(result).find('>conference>recording');
  14116. var newState = ('true' === recordingElem.attr('state'));
  14117. recordingEnabled = newState;
  14118. callback(newState);
  14119. },
  14120. function (error) {
  14121. console.warn(error);
  14122. callback(recordingEnabled);
  14123. }
  14124. );
  14125. }
  14126. var Recording = {
  14127. toggleRecording: function (tokenEmptyCallback,
  14128. startingCallback, startedCallback, connection) {
  14129. if (!Moderator.isModerator()) {
  14130. console.log(
  14131. 'non-focus, or conference not yet organized:' +
  14132. ' not enabling recording');
  14133. return;
  14134. }
  14135. var self = this;
  14136. // Jirecon does not (currently) support a token.
  14137. if (!recordingToken && !useJirecon) {
  14138. tokenEmptyCallback(function (value) {
  14139. setRecordingToken(value);
  14140. self.toggleRecording(tokenEmptyCallback,
  14141. startingCallback, startedCallback, connection);
  14142. });
  14143. return;
  14144. }
  14145. var oldState = recordingEnabled;
  14146. startingCallback(!oldState);
  14147. setRecording(!oldState,
  14148. recordingToken,
  14149. function (state) {
  14150. console.log("New recording state: ", state);
  14151. if (state === oldState) {
  14152. // FIXME: new focus:
  14153. // this will not work when moderator changes
  14154. // during active session. Then it will assume that
  14155. // recording status has changed to true, but it might have
  14156. // been already true(and we only received actual status from
  14157. // the focus).
  14158. //
  14159. // SO we start with status null, so that it is initialized
  14160. // here and will fail only after second click, so if invalid
  14161. // token was used we have to press the button twice before
  14162. // current status will be fetched and token will be reset.
  14163. //
  14164. // Reliable way would be to return authentication error.
  14165. // Or status update when moderator connects.
  14166. // Or we have to stop recording session when current
  14167. // moderator leaves the room.
  14168. // Failed to change, reset the token because it might
  14169. // have been wrong
  14170. setRecordingToken(null);
  14171. }
  14172. startedCallback(state);
  14173. },
  14174. connection
  14175. );
  14176. }
  14177. }
  14178. module.exports = Recording;
  14179. },{"./moderator":56}],58:[function(require,module,exports){
  14180. /* jshint -W117 */
  14181. /* a simple MUC connection plugin
  14182. * can only handle a single MUC room
  14183. */
  14184. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14185. var Moderator = require("./moderator");
  14186. var JingleSession = require("./JingleSession");
  14187. var bridgeIsDown = false;
  14188. module.exports = function(XMPP, eventEmitter) {
  14189. Strophe.addConnectionPlugin('emuc', {
  14190. connection: null,
  14191. roomjid: null,
  14192. myroomjid: null,
  14193. members: {},
  14194. list_members: [], // so we can elect a new focus
  14195. presMap: {},
  14196. preziMap: {},
  14197. joined: false,
  14198. isOwner: false,
  14199. role: null,
  14200. focusMucJid: null,
  14201. ssrc2jid: {},
  14202. init: function (conn) {
  14203. this.connection = conn;
  14204. },
  14205. initPresenceMap: function (myroomjid) {
  14206. this.presMap['to'] = myroomjid;
  14207. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  14208. if(APP.RTC.localAudio.isMuted())
  14209. {
  14210. this.addAudioInfoToPresence(true);
  14211. }
  14212. if(APP.RTC.localVideo.isMuted())
  14213. {
  14214. this.addVideoInfoToPresence(true);
  14215. }
  14216. },
  14217. doJoin: function (jid, password) {
  14218. this.myroomjid = jid;
  14219. console.info("Joined MUC as " + this.myroomjid);
  14220. this.initPresenceMap(this.myroomjid);
  14221. if (!this.roomjid) {
  14222. this.roomjid = Strophe.getBareJidFromJid(jid);
  14223. // add handlers (just once)
  14224. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  14225. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  14226. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  14227. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  14228. }
  14229. if (password !== undefined) {
  14230. this.presMap['password'] = password;
  14231. }
  14232. this.sendPresence();
  14233. },
  14234. doLeave: function () {
  14235. console.log("do leave", this.myroomjid);
  14236. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  14237. this.presMap.length = 0;
  14238. this.connection.send(pres);
  14239. },
  14240. createNonAnonymousRoom: function () {
  14241. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  14242. var getForm = $iq({type: 'get', to: this.roomjid})
  14243. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  14244. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14245. var self = this;
  14246. this.connection.sendIQ(getForm, function (form) {
  14247. if (!$(form).find(
  14248. '>query>x[xmlns="jabber:x:data"]' +
  14249. '>field[var="muc#roomconfig_whois"]').length) {
  14250. console.error('non-anonymous rooms not supported');
  14251. return;
  14252. }
  14253. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  14254. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  14255. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14256. formSubmit.c('field', {'var': 'FORM_TYPE'})
  14257. .c('value')
  14258. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  14259. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  14260. .c('value').t('anyone').up().up();
  14261. self.connection.sendIQ(formSubmit);
  14262. }, function (error) {
  14263. console.error("Error getting room configuration form");
  14264. });
  14265. },
  14266. onPresence: function (pres) {
  14267. var from = pres.getAttribute('from');
  14268. // What is this for? A workaround for something?
  14269. if (pres.getAttribute('type')) {
  14270. return true;
  14271. }
  14272. // Parse etherpad tag.
  14273. var etherpad = $(pres).find('>etherpad');
  14274. if (etherpad.length) {
  14275. if (config.etherpad_base && !Moderator.isModerator()) {
  14276. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  14277. }
  14278. }
  14279. // Parse prezi tag.
  14280. var presentation = $(pres).find('>prezi');
  14281. if (presentation.length) {
  14282. var url = presentation.attr('url');
  14283. var current = presentation.find('>current').text();
  14284. console.log('presentation info received from', from, url);
  14285. if (this.preziMap[from] == null) {
  14286. this.preziMap[from] = url;
  14287. $(document).trigger('presentationadded.muc', [from, url, current]);
  14288. }
  14289. else {
  14290. $(document).trigger('gotoslide.muc', [from, url, current]);
  14291. }
  14292. }
  14293. else if (this.preziMap[from] != null) {
  14294. var url = this.preziMap[from];
  14295. delete this.preziMap[from];
  14296. $(document).trigger('presentationremoved.muc', [from, url]);
  14297. }
  14298. // Parse audio info tag.
  14299. var audioMuted = $(pres).find('>audiomuted');
  14300. if (audioMuted.length) {
  14301. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  14302. }
  14303. // Parse video info tag.
  14304. var videoMuted = $(pres).find('>videomuted');
  14305. if (videoMuted.length) {
  14306. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  14307. }
  14308. var startMuted = $(pres).find('>startmuted');
  14309. if (startMuted.length)
  14310. {
  14311. eventEmitter.emit(XMPPEvents.START_MUTED,
  14312. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  14313. }
  14314. var devices = $(pres).find('>devices');
  14315. if(devices.length)
  14316. {
  14317. var audio = devices.find('>audio');
  14318. var video = devices.find('>video');
  14319. var devicesValues = {audio: false, video: false};
  14320. if(audio.length && audio.text() === "true")
  14321. {
  14322. devicesValues.audio = true;
  14323. }
  14324. if(video.length && video.text() === "true")
  14325. {
  14326. devicesValues.video = true;
  14327. }
  14328. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  14329. Strophe.getResourceFromJid(from), devicesValues);
  14330. }
  14331. var stats = $(pres).find('>stats');
  14332. if (stats.length) {
  14333. var statsObj = {};
  14334. Strophe.forEachChild(stats[0], "stat", function (el) {
  14335. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  14336. });
  14337. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  14338. }
  14339. // Parse status.
  14340. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  14341. this.isOwner = true;
  14342. this.createNonAnonymousRoom();
  14343. }
  14344. // Parse roles.
  14345. var member = {};
  14346. member.show = $(pres).find('>show').text();
  14347. member.status = $(pres).find('>status').text();
  14348. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  14349. member.affiliation = tmp.attr('affiliation');
  14350. member.role = tmp.attr('role');
  14351. // Focus recognition
  14352. member.jid = tmp.attr('jid');
  14353. member.isFocus = false;
  14354. if (member.jid
  14355. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  14356. member.isFocus = true;
  14357. }
  14358. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  14359. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  14360. if (from == this.myroomjid) {
  14361. if (member.affiliation == 'owner') this.isOwner = true;
  14362. if (this.role !== member.role) {
  14363. this.role = member.role;
  14364. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  14365. from, member, pres, Moderator.isModerator());
  14366. }
  14367. if (!this.joined) {
  14368. this.joined = true;
  14369. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  14370. this.list_members.push(from);
  14371. }
  14372. } else if (this.members[from] === undefined) {
  14373. // new participant
  14374. this.members[from] = member;
  14375. this.list_members.push(from);
  14376. console.log('entered', from, member);
  14377. if (member.isFocus) {
  14378. this.focusMucJid = from;
  14379. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  14380. }
  14381. else {
  14382. var id = $(pres).find('>userId').text();
  14383. var email = $(pres).find('>email');
  14384. if (email.length > 0) {
  14385. id = email.text();
  14386. }
  14387. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  14388. }
  14389. } else {
  14390. // Presence update for existing participant
  14391. // Watch role change:
  14392. if (this.members[from].role != member.role) {
  14393. this.members[from].role = member.role;
  14394. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  14395. member.role, member.displayName);
  14396. }
  14397. }
  14398. // Always trigger presence to update bindings
  14399. this.parsePresence(from, member, pres);
  14400. // Trigger status message update
  14401. if (member.status) {
  14402. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  14403. }
  14404. return true;
  14405. },
  14406. onPresenceUnavailable: function (pres) {
  14407. var from = pres.getAttribute('from');
  14408. // room destroyed ?
  14409. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  14410. '>destroy').length) {
  14411. var reason;
  14412. var reasonSelect = $(pres).find(
  14413. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  14414. '>destroy>reason');
  14415. if (reasonSelect.length) {
  14416. reason = reasonSelect.text();
  14417. }
  14418. XMPP.disposeConference(false);
  14419. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  14420. return true;
  14421. }
  14422. // Status code 110 indicates that this notification is "self-presence".
  14423. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  14424. delete this.members[from];
  14425. this.list_members.splice(this.list_members.indexOf(from), 1);
  14426. this.onParticipantLeft(from);
  14427. }
  14428. // If the status code is 110 this means we're leaving and we would like
  14429. // to remove everyone else from our view, so we trigger the event.
  14430. else if (this.list_members.length > 1) {
  14431. for (var i = 0; i < this.list_members.length; i++) {
  14432. var member = this.list_members[i];
  14433. delete this.members[i];
  14434. this.list_members.splice(i, 1);
  14435. this.onParticipantLeft(member);
  14436. }
  14437. }
  14438. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  14439. $(document).trigger('kicked.muc', [from]);
  14440. if (this.myroomjid === from) {
  14441. XMPP.disposeConference(false);
  14442. eventEmitter.emit(XMPPEvents.KICKED);
  14443. }
  14444. }
  14445. return true;
  14446. },
  14447. onPresenceError: function (pres) {
  14448. var from = pres.getAttribute('from');
  14449. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  14450. console.log('on password required', from);
  14451. var self = this;
  14452. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  14453. self.doJoin(from, value);
  14454. });
  14455. } else if ($(pres).find(
  14456. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  14457. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  14458. if (toDomain === config.hosts.anonymousdomain) {
  14459. // enter the room by replying with 'not-authorized'. This would
  14460. // result in reconnection from authorized domain.
  14461. // We're either missing Jicofo/Prosody config for anonymous
  14462. // domains or something is wrong.
  14463. // XMPP.promptLogin();
  14464. APP.UI.messageHandler.openReportDialog(null,
  14465. "dialog.joinError", pres);
  14466. } else {
  14467. console.warn('onPresError ', pres);
  14468. APP.UI.messageHandler.openReportDialog(null,
  14469. "dialog.connectError",
  14470. pres);
  14471. }
  14472. } else {
  14473. console.warn('onPresError ', pres);
  14474. APP.UI.messageHandler.openReportDialog(null,
  14475. "dialog.connectError",
  14476. pres);
  14477. }
  14478. return true;
  14479. },
  14480. sendMessage: function (body, nickname) {
  14481. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  14482. msg.c('body', body).up();
  14483. if (nickname) {
  14484. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  14485. }
  14486. this.connection.send(msg);
  14487. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  14488. },
  14489. setSubject: function (subject) {
  14490. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  14491. msg.c('subject', subject);
  14492. this.connection.send(msg);
  14493. console.log("topic changed to " + subject);
  14494. },
  14495. onMessage: function (msg) {
  14496. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  14497. var from = msg.getAttribute('from');
  14498. var nick =
  14499. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  14500. .text() ||
  14501. Strophe.getResourceFromJid(from);
  14502. var txt = $(msg).find('>body').text();
  14503. var type = msg.getAttribute("type");
  14504. if (type == "error") {
  14505. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  14506. $(msg).find('>text').text(), txt);
  14507. return true;
  14508. }
  14509. var subject = $(msg).find('>subject');
  14510. if (subject.length) {
  14511. var subjectText = subject.text();
  14512. if (subjectText || subjectText == "") {
  14513. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  14514. console.log("Subject is changed to " + subjectText);
  14515. }
  14516. }
  14517. if (txt) {
  14518. console.log('chat', nick, txt);
  14519. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  14520. from, nick, txt, this.myroomjid);
  14521. }
  14522. return true;
  14523. },
  14524. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14525. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  14526. var ob = this;
  14527. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  14528. function (res) {
  14529. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  14530. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  14531. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14532. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  14533. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  14534. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  14535. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  14536. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  14537. ob.connection.sendIQ(formsubmit,
  14538. onSuccess,
  14539. onError);
  14540. } else {
  14541. onNotSupported();
  14542. }
  14543. }, onError);
  14544. },
  14545. kick: function (jid) {
  14546. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  14547. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  14548. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  14549. .c('reason').t('You have been kicked.').up().up().up();
  14550. this.connection.sendIQ(
  14551. kickIQ,
  14552. function (result) {
  14553. console.log('Kick participant with jid: ', jid, result);
  14554. },
  14555. function (error) {
  14556. console.log('Kick participant error: ', error);
  14557. });
  14558. },
  14559. sendPresence: function () {
  14560. if (!this.presMap['to']) {
  14561. // Too early to send presence - not initialized
  14562. return;
  14563. }
  14564. var pres = $pres({to: this.presMap['to'] });
  14565. pres.c('x', {xmlns: this.presMap['xns']});
  14566. if (this.presMap['password']) {
  14567. pres.c('password').t(this.presMap['password']).up();
  14568. }
  14569. pres.up();
  14570. // Send XEP-0115 'c' stanza that contains our capabilities info
  14571. if (this.connection.caps) {
  14572. this.connection.caps.node = config.clientNode;
  14573. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  14574. }
  14575. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  14576. .t(navigator.userAgent).up();
  14577. if (this.presMap['bridgeIsDown']) {
  14578. pres.c('bridgeIsDown').up();
  14579. }
  14580. if (this.presMap['email']) {
  14581. pres.c('email').t(this.presMap['email']).up();
  14582. }
  14583. if (this.presMap['userId']) {
  14584. pres.c('userId').t(this.presMap['userId']).up();
  14585. }
  14586. if (this.presMap['displayName']) {
  14587. // XEP-0172
  14588. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  14589. .t(this.presMap['displayName']).up();
  14590. }
  14591. if(this.presMap["devices"])
  14592. {
  14593. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  14594. .c('video').t(this.presMap['devices'].video).up().up();
  14595. }
  14596. if (this.presMap['audions']) {
  14597. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  14598. .t(this.presMap['audiomuted']).up();
  14599. }
  14600. if (this.presMap['videons']) {
  14601. pres.c('videomuted', {xmlns: this.presMap['videons']})
  14602. .t(this.presMap['videomuted']).up();
  14603. }
  14604. if (this.presMap['statsns']) {
  14605. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  14606. for (var stat in this.presMap["stats"])
  14607. if (this.presMap["stats"][stat] != null)
  14608. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  14609. pres.up();
  14610. }
  14611. if (this.presMap['prezins']) {
  14612. pres.c('prezi',
  14613. {xmlns: this.presMap['prezins'],
  14614. 'url': this.presMap['preziurl']})
  14615. .c('current').t(this.presMap['prezicurrent']).up().up();
  14616. }
  14617. if (this.presMap['etherpadns']) {
  14618. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  14619. .t(this.presMap['etherpadname']).up();
  14620. }
  14621. if (this.presMap['medians']) {
  14622. pres.c('media', {xmlns: this.presMap['medians']});
  14623. var sourceNumber = 0;
  14624. Object.keys(this.presMap).forEach(function (key) {
  14625. if (key.indexOf('source') >= 0) {
  14626. sourceNumber++;
  14627. }
  14628. });
  14629. if (sourceNumber > 0)
  14630. for (var i = 1; i <= sourceNumber / 3; i++) {
  14631. pres.c('source',
  14632. {type: this.presMap['source' + i + '_type'],
  14633. ssrc: this.presMap['source' + i + '_ssrc'],
  14634. direction: this.presMap['source' + i + '_direction']
  14635. || 'sendrecv' }
  14636. ).up();
  14637. }
  14638. pres.up();
  14639. }
  14640. if(this.presMap["startMuted"] !== undefined)
  14641. {
  14642. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  14643. video: this.presMap["startMuted"].video,
  14644. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  14645. delete this.presMap["startMuted"];
  14646. }
  14647. pres.up();
  14648. this.connection.send(pres);
  14649. },
  14650. addDisplayNameToPresence: function (displayName) {
  14651. this.presMap['displayName'] = displayName;
  14652. },
  14653. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  14654. if (!this.presMap['medians'])
  14655. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  14656. this.presMap['source' + sourceNumber + '_type'] = mtype;
  14657. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  14658. this.presMap['source' + sourceNumber + '_direction'] = direction;
  14659. },
  14660. addDevicesToPresence: function (devices) {
  14661. this.presMap['devices'] = devices;
  14662. },
  14663. clearPresenceMedia: function () {
  14664. var self = this;
  14665. Object.keys(this.presMap).forEach(function (key) {
  14666. if (key.indexOf('source') != -1) {
  14667. delete self.presMap[key];
  14668. }
  14669. });
  14670. },
  14671. addPreziToPresence: function (url, currentSlide) {
  14672. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  14673. this.presMap['preziurl'] = url;
  14674. this.presMap['prezicurrent'] = currentSlide;
  14675. },
  14676. removePreziFromPresence: function () {
  14677. delete this.presMap['prezins'];
  14678. delete this.presMap['preziurl'];
  14679. delete this.presMap['prezicurrent'];
  14680. },
  14681. addCurrentSlideToPresence: function (currentSlide) {
  14682. this.presMap['prezicurrent'] = currentSlide;
  14683. },
  14684. getPrezi: function (roomjid) {
  14685. return this.preziMap[roomjid];
  14686. },
  14687. addEtherpadToPresence: function (etherpadName) {
  14688. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  14689. this.presMap['etherpadname'] = etherpadName;
  14690. },
  14691. addAudioInfoToPresence: function (isMuted) {
  14692. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  14693. this.presMap['audiomuted'] = isMuted.toString();
  14694. },
  14695. addVideoInfoToPresence: function (isMuted) {
  14696. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  14697. this.presMap['videomuted'] = isMuted.toString();
  14698. },
  14699. addConnectionInfoToPresence: function (stats) {
  14700. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  14701. this.presMap['stats'] = stats;
  14702. },
  14703. findJidFromResource: function (resourceJid) {
  14704. if (resourceJid &&
  14705. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  14706. return this.myroomjid;
  14707. }
  14708. var peerJid = null;
  14709. Object.keys(this.members).some(function (jid) {
  14710. peerJid = jid;
  14711. return Strophe.getResourceFromJid(jid) === resourceJid;
  14712. });
  14713. return peerJid;
  14714. },
  14715. addBridgeIsDownToPresence: function () {
  14716. this.presMap['bridgeIsDown'] = true;
  14717. },
  14718. addEmailToPresence: function (email) {
  14719. this.presMap['email'] = email;
  14720. },
  14721. addUserIdToPresence: function (userId) {
  14722. this.presMap['userId'] = userId;
  14723. },
  14724. addStartMutedToPresence: function (audio, video) {
  14725. this.presMap["startMuted"] = {audio: audio, video: video};
  14726. },
  14727. isModerator: function () {
  14728. return this.role === 'moderator';
  14729. },
  14730. getMemberRole: function (peerJid) {
  14731. if (this.members[peerJid]) {
  14732. return this.members[peerJid].role;
  14733. }
  14734. return null;
  14735. },
  14736. onParticipantLeft: function (jid) {
  14737. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  14738. this.connection.jingle.terminateByJid(jid);
  14739. if (this.getPrezi(jid)) {
  14740. $(document).trigger('presentationremoved.muc',
  14741. [jid, this.getPrezi(jid)]);
  14742. }
  14743. Moderator.onMucMemberLeft(jid);
  14744. },
  14745. parsePresence: function (from, memeber, pres) {
  14746. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  14747. bridgeIsDown = true;
  14748. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  14749. }
  14750. if(memeber.isFocus)
  14751. return;
  14752. var self = this;
  14753. // Remove old ssrcs coming from the jid
  14754. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  14755. if (self.ssrc2jid[ssrc] == from) {
  14756. delete self.ssrc2jid[ssrc];
  14757. }
  14758. });
  14759. var changedStreams = [];
  14760. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  14761. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  14762. var ssrcV = ssrc.getAttribute('ssrc');
  14763. self.ssrc2jid[ssrcV] = from;
  14764. var type = ssrc.getAttribute('type');
  14765. var direction = ssrc.getAttribute('direction');
  14766. changedStreams.push({type: type, direction: direction});
  14767. });
  14768. eventEmitter.emit(XMPPEvents.STREAMS_CHANGED, from, changedStreams);
  14769. var displayName = !config.displayJids
  14770. ? memeber.displayName : Strophe.getResourceFromJid(from);
  14771. if (displayName && displayName.length > 0)
  14772. {
  14773. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  14774. }
  14775. var id = $(pres).find('>userID').text();
  14776. var email = $(pres).find('>email');
  14777. if(email.length > 0) {
  14778. id = email.text();
  14779. }
  14780. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  14781. }
  14782. });
  14783. };
  14784. },{"../../service/xmpp/XMPPEvents":105,"./JingleSession":51,"./moderator":56}],59:[function(require,module,exports){
  14785. /* jshint -W117 */
  14786. var JingleSession = require("./JingleSession");
  14787. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14788. module.exports = function(XMPP, eventEmitter)
  14789. {
  14790. function CallIncomingJingle(sid, connection) {
  14791. var sess = connection.jingle.sessions[sid];
  14792. // TODO: do we check activecall == null?
  14793. connection.jingle.activecall = sess;
  14794. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  14795. // TODO: check affiliation and/or role
  14796. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  14797. sess.usedrip = true; // not-so-naive trickle ice
  14798. sess.sendAnswer();
  14799. sess.accept();
  14800. };
  14801. Strophe.addConnectionPlugin('jingle', {
  14802. connection: null,
  14803. sessions: {},
  14804. jid2session: {},
  14805. ice_config: {iceServers: []},
  14806. pc_constraints: {},
  14807. activecall: null,
  14808. media_constraints: {
  14809. mandatory: {
  14810. 'OfferToReceiveAudio': true,
  14811. 'OfferToReceiveVideo': true
  14812. }
  14813. // MozDontOfferDataChannel: true when this is firefox
  14814. },
  14815. init: function (conn) {
  14816. this.connection = conn;
  14817. if (this.connection.disco) {
  14818. // http://xmpp.org/extensions/xep-0167.html#support
  14819. // http://xmpp.org/extensions/xep-0176.html#support
  14820. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  14821. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  14822. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  14823. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  14824. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  14825. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  14826. // this is dealt with by SDP O/A so we don't need to annouce this
  14827. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  14828. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  14829. if (config.useRtcpMux) {
  14830. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  14831. }
  14832. if (config.useBundle) {
  14833. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  14834. }
  14835. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  14836. }
  14837. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  14838. },
  14839. onJingle: function (iq) {
  14840. var sid = $(iq).find('jingle').attr('sid');
  14841. var action = $(iq).find('jingle').attr('action');
  14842. var fromJid = iq.getAttribute('from');
  14843. // send ack first
  14844. var ack = $iq({type: 'result',
  14845. to: fromJid,
  14846. id: iq.getAttribute('id')
  14847. });
  14848. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  14849. var sess = this.sessions[sid];
  14850. if ('session-initiate' != action) {
  14851. if (sess === null) {
  14852. ack.type = 'error';
  14853. ack.c('error', {type: 'cancel'})
  14854. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14855. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14856. this.connection.send(ack);
  14857. return true;
  14858. }
  14859. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  14860. // local jid is not checked
  14861. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  14862. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  14863. ack.type = 'error';
  14864. ack.c('error', {type: 'cancel'})
  14865. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14866. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14867. this.connection.send(ack);
  14868. return true;
  14869. }
  14870. } else if (sess !== undefined) {
  14871. // existing session with same session id
  14872. // this might be out-of-order if the sess.peerjid is the same as from
  14873. ack.type = 'error';
  14874. ack.c('error', {type: 'cancel'})
  14875. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  14876. console.warn('duplicate session id', sid);
  14877. this.connection.send(ack);
  14878. return true;
  14879. }
  14880. // FIXME: check for a defined action
  14881. this.connection.send(ack);
  14882. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  14883. switch (action) {
  14884. case 'session-initiate':
  14885. var startMuted = $(iq).find('jingle>startmuted');
  14886. if(startMuted && startMuted.length > 0)
  14887. {
  14888. var audioMuted = startMuted.attr("audio");
  14889. var videoMuted = startMuted.attr("video");
  14890. APP.UI.setInitialMuteFromFocus((audioMuted === "true"),
  14891. (videoMuted === "true"));
  14892. }
  14893. sess = new JingleSession(
  14894. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  14895. this.connection, XMPP);
  14896. // configure session
  14897. sess.media_constraints = this.media_constraints;
  14898. sess.pc_constraints = this.pc_constraints;
  14899. sess.ice_config = this.ice_config;
  14900. sess.initiate(fromJid, false);
  14901. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  14902. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  14903. this.sessions[sess.sid] = sess;
  14904. this.jid2session[sess.peerjid] = sess;
  14905. // the callback should either
  14906. // .sendAnswer and .accept
  14907. // or .sendTerminate -- not necessarily synchronus
  14908. CallIncomingJingle(sess.sid, this.connection);
  14909. break;
  14910. case 'session-accept':
  14911. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  14912. sess.accept();
  14913. $(document).trigger('callaccepted.jingle', [sess.sid]);
  14914. break;
  14915. case 'session-terminate':
  14916. // If this is not the focus sending the terminate, we have
  14917. // nothing more to do here.
  14918. if (Object.keys(this.sessions).length < 1
  14919. || !(this.sessions[Object.keys(this.sessions)[0]]
  14920. instanceof JingleSession))
  14921. {
  14922. break;
  14923. }
  14924. console.log('terminating...', sess.sid);
  14925. sess.terminate();
  14926. this.terminate(sess.sid);
  14927. if ($(iq).find('>jingle>reason').length) {
  14928. $(document).trigger('callterminated.jingle', [
  14929. sess.sid,
  14930. sess.peerjid,
  14931. $(iq).find('>jingle>reason>:first')[0].tagName,
  14932. $(iq).find('>jingle>reason>text').text()
  14933. ]);
  14934. } else {
  14935. $(document).trigger('callterminated.jingle',
  14936. [sess.sid, sess.peerjid]);
  14937. }
  14938. break;
  14939. case 'transport-info':
  14940. sess.addIceCandidate($(iq).find('>jingle>content'));
  14941. break;
  14942. case 'session-info':
  14943. var affected;
  14944. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14945. $(document).trigger('ringing.jingle', [sess.sid]);
  14946. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14947. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14948. $(document).trigger('mute.jingle', [sess.sid, affected]);
  14949. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14950. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14951. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  14952. }
  14953. break;
  14954. case 'addsource': // FIXME: proprietary, un-jingleish
  14955. case 'source-add': // FIXME: proprietary
  14956. sess.addSource($(iq).find('>jingle>content'), fromJid);
  14957. break;
  14958. case 'removesource': // FIXME: proprietary, un-jingleish
  14959. case 'source-remove': // FIXME: proprietary
  14960. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  14961. break;
  14962. default:
  14963. console.warn('jingle action not implemented', action);
  14964. break;
  14965. }
  14966. return true;
  14967. },
  14968. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  14969. var sess = new JingleSession(myjid || this.connection.jid,
  14970. Math.random().toString(36).substr(2, 12), // random string
  14971. this.connection, XMPP);
  14972. // configure session
  14973. sess.media_constraints = this.media_constraints;
  14974. sess.pc_constraints = this.pc_constraints;
  14975. sess.ice_config = this.ice_config;
  14976. sess.initiate(peerjid, true);
  14977. this.sessions[sess.sid] = sess;
  14978. this.jid2session[sess.peerjid] = sess;
  14979. sess.sendOffer();
  14980. return sess;
  14981. },
  14982. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  14983. if (sid === null || sid === undefined) {
  14984. for (sid in this.sessions) {
  14985. if (this.sessions[sid].state != 'ended') {
  14986. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14987. this.sessions[sid].terminate();
  14988. }
  14989. delete this.jid2session[this.sessions[sid].peerjid];
  14990. delete this.sessions[sid];
  14991. }
  14992. } else if (this.sessions.hasOwnProperty(sid)) {
  14993. if (this.sessions[sid].state != 'ended') {
  14994. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14995. this.sessions[sid].terminate();
  14996. }
  14997. delete this.jid2session[this.sessions[sid].peerjid];
  14998. delete this.sessions[sid];
  14999. }
  15000. },
  15001. // Used to terminate a session when an unavailable presence is received.
  15002. terminateByJid: function (jid) {
  15003. if (this.jid2session.hasOwnProperty(jid)) {
  15004. var sess = this.jid2session[jid];
  15005. if (sess) {
  15006. sess.terminate();
  15007. console.log('peer went away silently', jid);
  15008. delete this.sessions[sess.sid];
  15009. delete this.jid2session[jid];
  15010. $(document).trigger('callterminated.jingle',
  15011. [sess.sid, jid], 'gone');
  15012. }
  15013. }
  15014. },
  15015. terminateRemoteByJid: function (jid, reason) {
  15016. if (this.jid2session.hasOwnProperty(jid)) {
  15017. var sess = this.jid2session[jid];
  15018. if (sess) {
  15019. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  15020. sess.terminate();
  15021. console.log('terminate peer with jid', sess.sid, jid);
  15022. delete this.sessions[sess.sid];
  15023. delete this.jid2session[jid];
  15024. $(document).trigger('callterminated.jingle',
  15025. [sess.sid, jid, 'kicked']);
  15026. }
  15027. }
  15028. },
  15029. getStunAndTurnCredentials: function () {
  15030. // get stun and turn configuration from server via xep-0215
  15031. // uses time-limited credentials as described in
  15032. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  15033. //
  15034. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  15035. // for a prosody module which implements this
  15036. //
  15037. // currently, this doesn't work with updateIce and therefore credentials with a long
  15038. // validity have to be fetched before creating the peerconnection
  15039. // TODO: implement refresh via updateIce as described in
  15040. // https://code.google.com/p/webrtc/issues/detail?id=1650
  15041. var self = this;
  15042. this.connection.sendIQ(
  15043. $iq({type: 'get', to: this.connection.domain})
  15044. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  15045. function (res) {
  15046. var iceservers = [];
  15047. $(res).find('>services>service').each(function (idx, el) {
  15048. el = $(el);
  15049. var dict = {};
  15050. var type = el.attr('type');
  15051. switch (type) {
  15052. case 'stun':
  15053. dict.url = 'stun:' + el.attr('host');
  15054. if (el.attr('port')) {
  15055. dict.url += ':' + el.attr('port');
  15056. }
  15057. iceservers.push(dict);
  15058. break;
  15059. case 'turn':
  15060. case 'turns':
  15061. dict.url = type + ':';
  15062. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  15063. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  15064. dict.url += el.attr('username') + '@';
  15065. } else {
  15066. dict.username = el.attr('username'); // only works in M28
  15067. }
  15068. }
  15069. dict.url += el.attr('host');
  15070. if (el.attr('port') && el.attr('port') != '3478') {
  15071. dict.url += ':' + el.attr('port');
  15072. }
  15073. if (el.attr('transport') && el.attr('transport') != 'udp') {
  15074. dict.url += '?transport=' + el.attr('transport');
  15075. }
  15076. if (el.attr('password')) {
  15077. dict.credential = el.attr('password');
  15078. }
  15079. iceservers.push(dict);
  15080. break;
  15081. }
  15082. });
  15083. self.ice_config.iceServers = iceservers;
  15084. },
  15085. function (err) {
  15086. console.warn('getting turn credentials failed', err);
  15087. console.warn('is mod_turncredentials or similar installed?');
  15088. }
  15089. );
  15090. // implement push?
  15091. },
  15092. /**
  15093. * Populates the log data
  15094. */
  15095. populateData: function () {
  15096. var data = {};
  15097. Object.keys(this.sessions).forEach(function (sid) {
  15098. var session = this.sessions[sid];
  15099. if (session.peerconnection && session.peerconnection.updateLog) {
  15100. // FIXME: should probably be a .dump call
  15101. data["jingle_" + session.sid] = {
  15102. updateLog: session.peerconnection.updateLog,
  15103. stats: session.peerconnection.stats,
  15104. url: window.location.href
  15105. };
  15106. }
  15107. });
  15108. return data;
  15109. }
  15110. });
  15111. };
  15112. },{"../../service/xmpp/XMPPEvents":105,"./JingleSession":51}],60:[function(require,module,exports){
  15113. /* global Strophe */
  15114. module.exports = function () {
  15115. Strophe.addConnectionPlugin('logger', {
  15116. // logs raw stanzas and makes them available for download as JSON
  15117. connection: null,
  15118. log: [],
  15119. init: function (conn) {
  15120. this.connection = conn;
  15121. this.connection.rawInput = this.log_incoming.bind(this);
  15122. this.connection.rawOutput = this.log_outgoing.bind(this);
  15123. },
  15124. log_incoming: function (stanza) {
  15125. this.log.push([new Date().getTime(), 'incoming', stanza]);
  15126. },
  15127. log_outgoing: function (stanza) {
  15128. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  15129. }
  15130. });
  15131. };
  15132. },{}],61:[function(require,module,exports){
  15133. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  15134. setAudioMuted, Strophe */
  15135. /**
  15136. * Moderate connection plugin.
  15137. */
  15138. module.exports = function (XMPP) {
  15139. Strophe.addConnectionPlugin('moderate', {
  15140. connection: null,
  15141. init: function (conn) {
  15142. this.connection = conn;
  15143. this.connection.addHandler(this.onMute.bind(this),
  15144. 'http://jitsi.org/jitmeet/audio',
  15145. 'iq',
  15146. 'set',
  15147. null,
  15148. null);
  15149. },
  15150. setMute: function (jid, mute) {
  15151. console.info("set mute", mute);
  15152. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  15153. .c('mute', {
  15154. xmlns: 'http://jitsi.org/jitmeet/audio',
  15155. jid: jid
  15156. })
  15157. .t(mute.toString())
  15158. .up();
  15159. this.connection.sendIQ(
  15160. iqToFocus,
  15161. function (result) {
  15162. console.log('set mute', result);
  15163. },
  15164. function (error) {
  15165. console.log('set mute error', error);
  15166. });
  15167. },
  15168. onMute: function (iq) {
  15169. var from = iq.getAttribute('from');
  15170. if (from !== this.connection.emuc.focusMucJid) {
  15171. console.warn("Ignored mute from non focus peer");
  15172. return false;
  15173. }
  15174. var mute = $(iq).find('mute');
  15175. if (mute.length) {
  15176. var doMuteAudio = mute.text() === "true";
  15177. APP.UI.setAudioMuted(doMuteAudio);
  15178. XMPP.forceMuted = doMuteAudio;
  15179. }
  15180. return true;
  15181. },
  15182. eject: function (jid) {
  15183. // We're not the focus, so can't terminate
  15184. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  15185. this.connection.emuc.kick(jid);
  15186. }
  15187. });
  15188. }
  15189. },{}],62:[function(require,module,exports){
  15190. /* jshint -W117 */
  15191. module.exports = function() {
  15192. Strophe.addConnectionPlugin('rayo',
  15193. {
  15194. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  15195. connection: null,
  15196. init: function (conn) {
  15197. this.connection = conn;
  15198. if (this.connection.disco) {
  15199. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  15200. }
  15201. this.connection.addHandler(
  15202. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  15203. },
  15204. onRayo: function (iq) {
  15205. console.info("Rayo IQ", iq);
  15206. },
  15207. dial: function (to, from, roomName, roomPass) {
  15208. var self = this;
  15209. var req = $iq(
  15210. {
  15211. type: 'set',
  15212. to: this.connection.emuc.focusMucJid
  15213. }
  15214. );
  15215. req.c('dial',
  15216. {
  15217. xmlns: this.RAYO_XMLNS,
  15218. to: to,
  15219. from: from
  15220. });
  15221. req.c('header',
  15222. {
  15223. name: 'JvbRoomName',
  15224. value: roomName
  15225. }).up();
  15226. if (roomPass !== null && roomPass.length) {
  15227. req.c('header',
  15228. {
  15229. name: 'JvbRoomPassword',
  15230. value: roomPass
  15231. }).up();
  15232. }
  15233. this.connection.sendIQ(
  15234. req,
  15235. function (result) {
  15236. console.info('Dial result ', result);
  15237. var resource = $(result).find('ref').attr('uri');
  15238. this.call_resource = resource.substr('xmpp:'.length);
  15239. console.info(
  15240. "Received call resource: " + this.call_resource);
  15241. },
  15242. function (error) {
  15243. console.info('Dial error ', error);
  15244. }
  15245. );
  15246. },
  15247. hang_up: function () {
  15248. if (!this.call_resource) {
  15249. console.warn("No call in progress");
  15250. return;
  15251. }
  15252. var self = this;
  15253. var req = $iq(
  15254. {
  15255. type: 'set',
  15256. to: this.call_resource
  15257. }
  15258. );
  15259. req.c('hangup',
  15260. {
  15261. xmlns: this.RAYO_XMLNS
  15262. });
  15263. this.connection.sendIQ(
  15264. req,
  15265. function (result) {
  15266. console.info('Hangup result ', result);
  15267. self.call_resource = null;
  15268. },
  15269. function (error) {
  15270. console.info('Hangup error ', error);
  15271. self.call_resource = null;
  15272. }
  15273. );
  15274. }
  15275. }
  15276. );
  15277. };
  15278. },{}],63:[function(require,module,exports){
  15279. /**
  15280. * Strophe logger implementation. Logs from level WARN and above.
  15281. */
  15282. module.exports = function () {
  15283. Strophe.log = function (level, msg) {
  15284. switch (level) {
  15285. case Strophe.LogLevel.WARN:
  15286. console.warn("Strophe: " + msg);
  15287. break;
  15288. case Strophe.LogLevel.ERROR:
  15289. case Strophe.LogLevel.FATAL:
  15290. console.error("Strophe: " + msg);
  15291. break;
  15292. }
  15293. };
  15294. Strophe.getStatusString = function (status) {
  15295. switch (status) {
  15296. case Strophe.Status.ERROR:
  15297. return "ERROR";
  15298. case Strophe.Status.CONNECTING:
  15299. return "CONNECTING";
  15300. case Strophe.Status.CONNFAIL:
  15301. return "CONNFAIL";
  15302. case Strophe.Status.AUTHENTICATING:
  15303. return "AUTHENTICATING";
  15304. case Strophe.Status.AUTHFAIL:
  15305. return "AUTHFAIL";
  15306. case Strophe.Status.CONNECTED:
  15307. return "CONNECTED";
  15308. case Strophe.Status.DISCONNECTED:
  15309. return "DISCONNECTED";
  15310. case Strophe.Status.DISCONNECTING:
  15311. return "DISCONNECTING";
  15312. case Strophe.Status.ATTACHED:
  15313. return "ATTACHED";
  15314. default:
  15315. return "unknown";
  15316. }
  15317. };
  15318. };
  15319. },{}],64:[function(require,module,exports){
  15320. /* global $, APP, config, Strophe*/
  15321. var Moderator = require("./moderator");
  15322. var EventEmitter = require("events");
  15323. var Recording = require("./recording");
  15324. var SDP = require("./SDP");
  15325. var Settings = require("../settings/Settings");
  15326. var Pako = require("pako");
  15327. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  15328. var RTCEvents = require("../../service/RTC/RTCEvents");
  15329. var UIEvents = require("../../service/UI/UIEvents");
  15330. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15331. var retry = require('retry');
  15332. var eventEmitter = new EventEmitter();
  15333. var connection = null;
  15334. var authenticatedUser = false;
  15335. function connect(jid, password) {
  15336. var faultTolerantConnect = retry.operation({
  15337. retries: 3
  15338. });
  15339. // fault tolerant connect
  15340. faultTolerantConnect.attempt(function () {
  15341. connection = XMPP.createConnection();
  15342. Moderator.setConnection(connection);
  15343. if (connection.disco) {
  15344. // for chrome, add multistream cap
  15345. }
  15346. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  15347. if (config.useIPv6) {
  15348. // https://code.google.com/p/webrtc/issues/detail?id=2828
  15349. if (!connection.jingle.pc_constraints.optional)
  15350. connection.jingle.pc_constraints.optional = [];
  15351. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  15352. }
  15353. // Include user info in MUC presence
  15354. var settings = Settings.getSettings();
  15355. if (settings.email) {
  15356. connection.emuc.addEmailToPresence(settings.email);
  15357. }
  15358. if (settings.uid) {
  15359. connection.emuc.addUserIdToPresence(settings.uid);
  15360. }
  15361. if (settings.displayName) {
  15362. connection.emuc.addDisplayNameToPresence(settings.displayName);
  15363. }
  15364. // connection.connect() starts the connection process.
  15365. //
  15366. // As the connection process proceeds, the user supplied callback will
  15367. // be triggered multiple times with status updates. The callback should
  15368. // take two arguments - the status code and the error condition.
  15369. //
  15370. // The status code will be one of the values in the Strophe.Status
  15371. // constants. The error condition will be one of the conditions defined
  15372. // in RFC 3920 or the condition ‘strophe-parsererror’.
  15373. //
  15374. // The Parameters wait, hold and route are optional and only relevant
  15375. // for BOSH connections. Please see XEP 124 for a more detailed
  15376. // explanation of the optional parameters.
  15377. //
  15378. // Connection status constants for use by the connection handler
  15379. // callback.
  15380. //
  15381. // Status.ERROR - An error has occurred (websockets specific)
  15382. // Status.CONNECTING - The connection is currently being made
  15383. // Status.CONNFAIL - The connection attempt failed
  15384. // Status.AUTHENTICATING - The connection is authenticating
  15385. // Status.AUTHFAIL - The authentication attempt failed
  15386. // Status.CONNECTED - The connection has succeeded
  15387. // Status.DISCONNECTED - The connection has been terminated
  15388. // Status.DISCONNECTING - The connection is currently being terminated
  15389. // Status.ATTACHED - The connection has been attached
  15390. var anonymousConnectionFailed = false;
  15391. var connectionFailed = false;
  15392. var lastErrorMsg;
  15393. connection.connect(jid, password, function (status, msg) {
  15394. console.log('Strophe status changed to',
  15395. Strophe.getStatusString(status), msg);
  15396. if (status === Strophe.Status.CONNECTED) {
  15397. if (config.useStunTurn) {
  15398. connection.jingle.getStunAndTurnCredentials();
  15399. }
  15400. console.info("My Jabber ID: " + connection.jid);
  15401. if (password)
  15402. authenticatedUser = true;
  15403. maybeDoJoin();
  15404. } else if (status === Strophe.Status.CONNFAIL) {
  15405. if (msg === 'x-strophe-bad-non-anon-jid') {
  15406. anonymousConnectionFailed = true;
  15407. } else {
  15408. connectionFailed = true;
  15409. }
  15410. lastErrorMsg = msg;
  15411. } else if (status === Strophe.Status.DISCONNECTED) {
  15412. if (anonymousConnectionFailed) {
  15413. // prompt user for username and password
  15414. XMPP.promptLogin();
  15415. } else {
  15416. // Strophe already has built-in HTTP/BOSH error handling and
  15417. // request retry logic. Requests are resent automatically
  15418. // until their error count reaches 5. Strophe.js disconnects
  15419. // if the error count is > 5. We are not replicating this
  15420. // here.
  15421. //
  15422. // The "problem" is that failed HTTP/BOSH requests don't
  15423. // trigger a callback with a status update, so when a
  15424. // callback with status Strophe.Status.DISCONNECTED arrives,
  15425. // we can't be sure if it's a graceful disconnect or if it's
  15426. // triggered by some HTTP/BOSH error.
  15427. //
  15428. // But that's a minor issue in Jitsi Meet as we never
  15429. // disconnect anyway, not even when the user closes the
  15430. // browser window (which is kind of wrong, but the point is
  15431. // that we should never ever get disconnected).
  15432. //
  15433. // On the other hand, failed connections due to XMPP layer
  15434. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  15435. //
  15436. // Here we implement retry logic for failed connections due
  15437. // to XMPP layer errors and we display an error to the user
  15438. // if we get disconnected from the XMPP server permanently.
  15439. // If the connection failed, retry.
  15440. if (connectionFailed
  15441. && faultTolerantConnect.retry("connection-failed")) {
  15442. return;
  15443. }
  15444. // If we failed to connect to the XMPP server, fire an event
  15445. // to let all the interested module now about it.
  15446. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  15447. msg ? msg : lastErrorMsg);
  15448. }
  15449. } else if (status === Strophe.Status.AUTHFAIL) {
  15450. // wrong password or username, prompt user
  15451. XMPP.promptLogin();
  15452. }
  15453. });
  15454. });
  15455. }
  15456. function maybeDoJoin() {
  15457. if (connection && connection.connected &&
  15458. Strophe.getResourceFromJid(connection.jid)
  15459. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  15460. // .connected is true while connecting?
  15461. doJoin();
  15462. }
  15463. }
  15464. function doJoin() {
  15465. var roomName = APP.UI.generateRoomName();
  15466. Moderator.allocateConferenceFocus(
  15467. roomName, APP.UI.checkForNicknameAndJoin);
  15468. }
  15469. function initStrophePlugins()
  15470. {
  15471. require("./strophe.emuc")(XMPP, eventEmitter);
  15472. require("./strophe.jingle")(XMPP, eventEmitter);
  15473. require("./strophe.moderate")(XMPP);
  15474. require("./strophe.util")();
  15475. require("./strophe.rayo")();
  15476. require("./strophe.logger")();
  15477. }
  15478. function registerListeners() {
  15479. APP.RTC.addStreamListener(maybeDoJoin,
  15480. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  15481. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  15482. XMPP.addToPresence("devices", devices);
  15483. })
  15484. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  15485. XMPP.addToPresence("displayName", nickname);
  15486. });
  15487. }
  15488. var unload = (function () {
  15489. var unloaded = false;
  15490. return function () {
  15491. if (unloaded) { return; }
  15492. unloaded = true;
  15493. if (connection && connection.connected) {
  15494. // ensure signout
  15495. $.ajax({
  15496. type: 'POST',
  15497. url: config.bosh,
  15498. async: false,
  15499. cache: false,
  15500. contentType: 'application/xml',
  15501. data: "<body rid='" + (connection.rid || connection._proto.rid) +
  15502. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  15503. (connection.sid || connection._proto.sid) +
  15504. "' type='terminate'>" +
  15505. "<presence xmlns='jabber:client' type='unavailable'/>" +
  15506. "</body>",
  15507. success: function (data) {
  15508. console.log('signed out');
  15509. console.log(data);
  15510. },
  15511. error: function (XMLHttpRequest, textStatus, errorThrown) {
  15512. console.log('signout error',
  15513. textStatus + ' (' + errorThrown + ')');
  15514. }
  15515. });
  15516. }
  15517. XMPP.disposeConference(true);
  15518. };
  15519. })();
  15520. function setupEvents() {
  15521. // In recent versions of FF the 'beforeunload' event is not fired when the
  15522. // window or the tab is closed. It is only fired when we leave the page
  15523. // (change URL). If this participant doesn't unload properly, then it
  15524. // becomes a ghost for the rest of the participants that stay in the
  15525. // conference. Thankfully handling the 'unload' event in addition to the
  15526. // 'beforeunload' event seems to garante the execution of the 'unload'
  15527. // method at least once.
  15528. //
  15529. // The 'unload' method can safely be run multiple times, it will actually do
  15530. // something only the first time that it's run, so we're don't have to worry
  15531. // about browsers that fire both events.
  15532. $(window).bind('beforeunload', unload);
  15533. $(window).bind('unload', unload);
  15534. }
  15535. var XMPP = {
  15536. getConnection: function(){ return connection; },
  15537. sessionTerminated: false,
  15538. /**
  15539. * XMPP connection status
  15540. */
  15541. Status: Strophe.Status,
  15542. /**
  15543. * Remembers if we were muted by the focus.
  15544. * @type {boolean}
  15545. */
  15546. forceMuted: false,
  15547. start: function () {
  15548. setupEvents();
  15549. initStrophePlugins();
  15550. registerListeners();
  15551. Moderator.init(this, eventEmitter);
  15552. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  15553. // Force authenticated domain if room is appended with '?login=true'
  15554. if (config.hosts.anonymousdomain &&
  15555. window.location.search.indexOf("login=true") !== -1) {
  15556. configDomain = config.hosts.domain;
  15557. }
  15558. var jid = configDomain || window.location.hostname;
  15559. connect(jid, null);
  15560. },
  15561. createConnection: function () {
  15562. var bosh = config.bosh || '/http-bind';
  15563. return new Strophe.Connection(bosh);
  15564. },
  15565. getStatusString: function (status) {
  15566. return Strophe.getStatusString(status);
  15567. },
  15568. promptLogin: function () {
  15569. // FIXME: re-use LoginDialog which supports retries
  15570. APP.UI.showLoginPopup(connect);
  15571. },
  15572. joinRoom: function(roomName, useNicks, nick)
  15573. {
  15574. var roomjid;
  15575. roomjid = roomName;
  15576. if (useNicks) {
  15577. if (nick) {
  15578. roomjid += '/' + nick;
  15579. } else {
  15580. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  15581. }
  15582. } else {
  15583. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  15584. if(!authenticatedUser)
  15585. tmpJid = tmpJid.substr(0, 8);
  15586. roomjid += '/' + tmpJid;
  15587. }
  15588. connection.emuc.doJoin(roomjid);
  15589. },
  15590. myJid: function () {
  15591. if(!connection)
  15592. return null;
  15593. return connection.emuc.myroomjid;
  15594. },
  15595. myResource: function () {
  15596. if(!connection || ! connection.emuc.myroomjid)
  15597. return null;
  15598. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  15599. },
  15600. disposeConference: function (onUnload) {
  15601. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  15602. var handler = connection.jingle.activecall;
  15603. if (handler && handler.peerconnection) {
  15604. // FIXME: probably removing streams is not required and close() should
  15605. // be enough
  15606. if (APP.RTC.localAudio) {
  15607. handler.peerconnection.removeStream(
  15608. APP.RTC.localAudio.getOriginalStream(), onUnload);
  15609. }
  15610. if (APP.RTC.localVideo) {
  15611. handler.peerconnection.removeStream(
  15612. APP.RTC.localVideo.getOriginalStream(), onUnload);
  15613. }
  15614. handler.peerconnection.close();
  15615. }
  15616. connection.jingle.activecall = null;
  15617. if(!onUnload)
  15618. {
  15619. this.sessionTerminated = true;
  15620. connection.emuc.doLeave();
  15621. }
  15622. },
  15623. addListener: function(type, listener)
  15624. {
  15625. eventEmitter.on(type, listener);
  15626. },
  15627. removeListener: function (type, listener) {
  15628. eventEmitter.removeListener(type, listener);
  15629. },
  15630. allocateConferenceFocus: function(roomName, callback) {
  15631. Moderator.allocateConferenceFocus(roomName, callback);
  15632. },
  15633. getLoginUrl: function (roomName, callback) {
  15634. Moderator.getLoginUrl(roomName, callback);
  15635. },
  15636. getPopupLoginUrl: function (roomName, callback) {
  15637. Moderator.getPopupLoginUrl(roomName, callback);
  15638. },
  15639. isModerator: function () {
  15640. return Moderator.isModerator();
  15641. },
  15642. isSipGatewayEnabled: function () {
  15643. return Moderator.isSipGatewayEnabled();
  15644. },
  15645. isExternalAuthEnabled: function () {
  15646. return Moderator.isExternalAuthEnabled();
  15647. },
  15648. switchStreams: function (stream, oldStream, callback, isAudio) {
  15649. if (connection && connection.jingle.activecall) {
  15650. // FIXME: will block switchInProgress on true value in case of exception
  15651. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  15652. } else {
  15653. // We are done immediately
  15654. console.warn("No conference handler or conference not started yet");
  15655. callback();
  15656. }
  15657. },
  15658. sendVideoInfoPresence: function (mute) {
  15659. if(!connection)
  15660. return;
  15661. connection.emuc.addVideoInfoToPresence(mute);
  15662. connection.emuc.sendPresence();
  15663. },
  15664. setVideoMute: function (mute, callback, options) {
  15665. if(!connection)
  15666. return;
  15667. var self = this;
  15668. var localCallback = function (mute) {
  15669. self.sendVideoInfoPresence(mute);
  15670. return callback(mute);
  15671. };
  15672. if(connection.jingle.activecall)
  15673. {
  15674. connection.jingle.activecall.setVideoMute(
  15675. mute, localCallback, options);
  15676. }
  15677. else {
  15678. localCallback(mute);
  15679. }
  15680. },
  15681. setAudioMute: function (mute, callback) {
  15682. if (!(connection && APP.RTC.localAudio)) {
  15683. return false;
  15684. }
  15685. if (this.forceMuted && !mute) {
  15686. console.info("Asking focus for unmute");
  15687. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  15688. // FIXME: wait for result before resetting muted status
  15689. this.forceMuted = false;
  15690. }
  15691. if (mute == APP.RTC.localAudio.isMuted()) {
  15692. // Nothing to do
  15693. return true;
  15694. }
  15695. // It is not clear what is the right way to handle multiple tracks.
  15696. // So at least make sure that they are all muted or all unmuted and
  15697. // that we send presence just once.
  15698. APP.RTC.localAudio.setMute(!mute);
  15699. // isMuted is the opposite of audioEnabled
  15700. this.sendAudioInfoPresence(mute, callback);
  15701. return true;
  15702. },
  15703. sendAudioInfoPresence: function(mute, callback)
  15704. {
  15705. if(connection) {
  15706. connection.emuc.addAudioInfoToPresence(mute);
  15707. connection.emuc.sendPresence();
  15708. }
  15709. callback();
  15710. return true;
  15711. },
  15712. // Really mute video, i.e. dont even send black frames
  15713. muteVideo: function (pc, unmute) {
  15714. // FIXME: this probably needs another of those lovely state safeguards...
  15715. // which checks for iceconn == connected and sigstate == stable
  15716. pc.setRemoteDescription(pc.remoteDescription,
  15717. function () {
  15718. pc.createAnswer(
  15719. function (answer) {
  15720. var sdp = new SDP(answer.sdp);
  15721. if (sdp.media.length > 1) {
  15722. if (unmute)
  15723. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  15724. else
  15725. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  15726. sdp.raw = sdp.session + sdp.media.join('');
  15727. answer.sdp = sdp.raw;
  15728. }
  15729. pc.setLocalDescription(answer,
  15730. function () {
  15731. console.log('mute SLD ok');
  15732. },
  15733. function (error) {
  15734. console.log('mute SLD error');
  15735. APP.UI.messageHandler.showError("dialog.error",
  15736. "dialog.SLDFailure");
  15737. }
  15738. );
  15739. },
  15740. function (error) {
  15741. console.log(error);
  15742. APP.UI.messageHandler.showError();
  15743. }
  15744. );
  15745. },
  15746. function (error) {
  15747. console.log('muteVideo SRD error');
  15748. APP.UI.messageHandler.showError("dialog.error",
  15749. "dialog.SRDFailure");
  15750. }
  15751. );
  15752. },
  15753. toggleRecording: function (tokenEmptyCallback,
  15754. startingCallback, startedCallback) {
  15755. Recording.toggleRecording(tokenEmptyCallback,
  15756. startingCallback, startedCallback, connection);
  15757. },
  15758. addToPresence: function (name, value, dontSend) {
  15759. switch (name)
  15760. {
  15761. case "displayName":
  15762. connection.emuc.addDisplayNameToPresence(value);
  15763. break;
  15764. case "etherpad":
  15765. connection.emuc.addEtherpadToPresence(value);
  15766. break;
  15767. case "prezi":
  15768. connection.emuc.addPreziToPresence(value, 0);
  15769. break;
  15770. case "preziSlide":
  15771. connection.emuc.addCurrentSlideToPresence(value);
  15772. break;
  15773. case "connectionQuality":
  15774. connection.emuc.addConnectionInfoToPresence(value);
  15775. break;
  15776. case "email":
  15777. connection.emuc.addEmailToPresence(value);
  15778. break;
  15779. case "devices":
  15780. connection.emuc.addDevicesToPresence(value);
  15781. break;
  15782. case "startMuted":
  15783. if(!Moderator.isModerator())
  15784. return;
  15785. connection.emuc.addStartMutedToPresence(value[0],
  15786. value[1]);
  15787. break;
  15788. default :
  15789. console.log("Unknown tag for presence: " + name);
  15790. return;
  15791. }
  15792. if (!dontSend)
  15793. connection.emuc.sendPresence();
  15794. },
  15795. /**
  15796. * Sends 'data' as a log message to the focus. Returns true iff a message
  15797. * was sent.
  15798. * @param data
  15799. * @returns {boolean} true iff a message was sent.
  15800. */
  15801. sendLogs: function (data) {
  15802. if(!connection.emuc.focusMucJid)
  15803. return false;
  15804. var deflate = true;
  15805. var content = JSON.stringify(data);
  15806. if (deflate) {
  15807. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  15808. }
  15809. content = Base64.encode(content);
  15810. // XEP-0337-ish
  15811. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  15812. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  15813. id: 'PeerConnectionStats'});
  15814. message.c('message').t(content).up();
  15815. if (deflate) {
  15816. message.c('tag', {name: "deflated", value: "true"}).up();
  15817. }
  15818. message.up();
  15819. connection.send(message);
  15820. return true;
  15821. },
  15822. populateData: function () {
  15823. var data = {};
  15824. if (connection.jingle) {
  15825. data = connection.jingle.populateData();
  15826. }
  15827. return data;
  15828. },
  15829. getLogger: function () {
  15830. if(connection.logger)
  15831. return connection.logger.log;
  15832. return null;
  15833. },
  15834. getPrezi: function () {
  15835. return connection.emuc.getPrezi(this.myJid());
  15836. },
  15837. removePreziFromPresence: function () {
  15838. connection.emuc.removePreziFromPresence();
  15839. connection.emuc.sendPresence();
  15840. },
  15841. sendChatMessage: function (message, nickname) {
  15842. connection.emuc.sendMessage(message, nickname);
  15843. },
  15844. setSubject: function (topic) {
  15845. connection.emuc.setSubject(topic);
  15846. },
  15847. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15848. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  15849. },
  15850. dial: function (to, from, roomName,roomPass) {
  15851. connection.rayo.dial(to, from, roomName,roomPass);
  15852. },
  15853. setMute: function (jid, mute) {
  15854. connection.moderate.setMute(jid, mute);
  15855. },
  15856. eject: function (jid) {
  15857. connection.moderate.eject(jid);
  15858. },
  15859. logout: function (callback) {
  15860. Moderator.logout(callback);
  15861. },
  15862. findJidFromResource: function (resource) {
  15863. return connection.emuc.findJidFromResource(resource);
  15864. },
  15865. getMembers: function () {
  15866. return connection.emuc.members;
  15867. },
  15868. getJidFromSSRC: function (ssrc) {
  15869. if(!connection)
  15870. return null;
  15871. return connection.emuc.ssrc2jid[ssrc];
  15872. },
  15873. getMUCJoined: function () {
  15874. return connection.emuc.joined;
  15875. },
  15876. getSessions: function () {
  15877. return connection.jingle.sessions;
  15878. },
  15879. removeStream: function (stream) {
  15880. if(!connection || !connection.jingle.activecall ||
  15881. !connection.jingle.activecall.peerconnection)
  15882. return;
  15883. connection.jingle.activecall.peerconnection.removeStream(stream);
  15884. }
  15885. };
  15886. module.exports = XMPP;
  15887. },{"../../service/RTC/RTCEvents":96,"../../service/RTC/StreamEventTypes":98,"../../service/UI/UIEvents":99,"../../service/xmpp/XMPPEvents":105,"../settings/Settings":41,"./SDP":52,"./moderator":56,"./recording":57,"./strophe.emuc":58,"./strophe.jingle":59,"./strophe.logger":60,"./strophe.moderate":61,"./strophe.rayo":62,"./strophe.util":63,"events":106,"pako":67,"retry":83}],65:[function(require,module,exports){
  15888. (function (process){
  15889. /*!
  15890. * async
  15891. * https://github.com/caolan/async
  15892. *
  15893. * Copyright 2010-2014 Caolan McMahon
  15894. * Released under the MIT license
  15895. */
  15896. /*jshint onevar: false, indent:4 */
  15897. /*global setImmediate: false, setTimeout: false, console: false */
  15898. (function () {
  15899. var async = {};
  15900. // global on the server, window in the browser
  15901. var root, previous_async;
  15902. root = this;
  15903. if (root != null) {
  15904. previous_async = root.async;
  15905. }
  15906. async.noConflict = function () {
  15907. root.async = previous_async;
  15908. return async;
  15909. };
  15910. function only_once(fn) {
  15911. var called = false;
  15912. return function() {
  15913. if (called) throw new Error("Callback was already called.");
  15914. called = true;
  15915. fn.apply(root, arguments);
  15916. }
  15917. }
  15918. //// cross-browser compatiblity functions ////
  15919. var _toString = Object.prototype.toString;
  15920. var _isArray = Array.isArray || function (obj) {
  15921. return _toString.call(obj) === '[object Array]';
  15922. };
  15923. var _each = function (arr, iterator) {
  15924. if (arr.forEach) {
  15925. return arr.forEach(iterator);
  15926. }
  15927. for (var i = 0; i < arr.length; i += 1) {
  15928. iterator(arr[i], i, arr);
  15929. }
  15930. };
  15931. var _map = function (arr, iterator) {
  15932. if (arr.map) {
  15933. return arr.map(iterator);
  15934. }
  15935. var results = [];
  15936. _each(arr, function (x, i, a) {
  15937. results.push(iterator(x, i, a));
  15938. });
  15939. return results;
  15940. };
  15941. var _reduce = function (arr, iterator, memo) {
  15942. if (arr.reduce) {
  15943. return arr.reduce(iterator, memo);
  15944. }
  15945. _each(arr, function (x, i, a) {
  15946. memo = iterator(memo, x, i, a);
  15947. });
  15948. return memo;
  15949. };
  15950. var _keys = function (obj) {
  15951. if (Object.keys) {
  15952. return Object.keys(obj);
  15953. }
  15954. var keys = [];
  15955. for (var k in obj) {
  15956. if (obj.hasOwnProperty(k)) {
  15957. keys.push(k);
  15958. }
  15959. }
  15960. return keys;
  15961. };
  15962. //// exported async module functions ////
  15963. //// nextTick implementation with browser-compatible fallback ////
  15964. if (typeof process === 'undefined' || !(process.nextTick)) {
  15965. if (typeof setImmediate === 'function') {
  15966. async.nextTick = function (fn) {
  15967. // not a direct alias for IE10 compatibility
  15968. setImmediate(fn);
  15969. };
  15970. async.setImmediate = async.nextTick;
  15971. }
  15972. else {
  15973. async.nextTick = function (fn) {
  15974. setTimeout(fn, 0);
  15975. };
  15976. async.setImmediate = async.nextTick;
  15977. }
  15978. }
  15979. else {
  15980. async.nextTick = process.nextTick;
  15981. if (typeof setImmediate !== 'undefined') {
  15982. async.setImmediate = function (fn) {
  15983. // not a direct alias for IE10 compatibility
  15984. setImmediate(fn);
  15985. };
  15986. }
  15987. else {
  15988. async.setImmediate = async.nextTick;
  15989. }
  15990. }
  15991. async.each = function (arr, iterator, callback) {
  15992. callback = callback || function () {};
  15993. if (!arr.length) {
  15994. return callback();
  15995. }
  15996. var completed = 0;
  15997. _each(arr, function (x) {
  15998. iterator(x, only_once(done) );
  15999. });
  16000. function done(err) {
  16001. if (err) {
  16002. callback(err);
  16003. callback = function () {};
  16004. }
  16005. else {
  16006. completed += 1;
  16007. if (completed >= arr.length) {
  16008. callback();
  16009. }
  16010. }
  16011. }
  16012. };
  16013. async.forEach = async.each;
  16014. async.eachSeries = function (arr, iterator, callback) {
  16015. callback = callback || function () {};
  16016. if (!arr.length) {
  16017. return callback();
  16018. }
  16019. var completed = 0;
  16020. var iterate = function () {
  16021. iterator(arr[completed], function (err) {
  16022. if (err) {
  16023. callback(err);
  16024. callback = function () {};
  16025. }
  16026. else {
  16027. completed += 1;
  16028. if (completed >= arr.length) {
  16029. callback();
  16030. }
  16031. else {
  16032. iterate();
  16033. }
  16034. }
  16035. });
  16036. };
  16037. iterate();
  16038. };
  16039. async.forEachSeries = async.eachSeries;
  16040. async.eachLimit = function (arr, limit, iterator, callback) {
  16041. var fn = _eachLimit(limit);
  16042. fn.apply(null, [arr, iterator, callback]);
  16043. };
  16044. async.forEachLimit = async.eachLimit;
  16045. var _eachLimit = function (limit) {
  16046. return function (arr, iterator, callback) {
  16047. callback = callback || function () {};
  16048. if (!arr.length || limit <= 0) {
  16049. return callback();
  16050. }
  16051. var completed = 0;
  16052. var started = 0;
  16053. var running = 0;
  16054. (function replenish () {
  16055. if (completed >= arr.length) {
  16056. return callback();
  16057. }
  16058. while (running < limit && started < arr.length) {
  16059. started += 1;
  16060. running += 1;
  16061. iterator(arr[started - 1], function (err) {
  16062. if (err) {
  16063. callback(err);
  16064. callback = function () {};
  16065. }
  16066. else {
  16067. completed += 1;
  16068. running -= 1;
  16069. if (completed >= arr.length) {
  16070. callback();
  16071. }
  16072. else {
  16073. replenish();
  16074. }
  16075. }
  16076. });
  16077. }
  16078. })();
  16079. };
  16080. };
  16081. var doParallel = function (fn) {
  16082. return function () {
  16083. var args = Array.prototype.slice.call(arguments);
  16084. return fn.apply(null, [async.each].concat(args));
  16085. };
  16086. };
  16087. var doParallelLimit = function(limit, fn) {
  16088. return function () {
  16089. var args = Array.prototype.slice.call(arguments);
  16090. return fn.apply(null, [_eachLimit(limit)].concat(args));
  16091. };
  16092. };
  16093. var doSeries = function (fn) {
  16094. return function () {
  16095. var args = Array.prototype.slice.call(arguments);
  16096. return fn.apply(null, [async.eachSeries].concat(args));
  16097. };
  16098. };
  16099. var _asyncMap = function (eachfn, arr, iterator, callback) {
  16100. arr = _map(arr, function (x, i) {
  16101. return {index: i, value: x};
  16102. });
  16103. if (!callback) {
  16104. eachfn(arr, function (x, callback) {
  16105. iterator(x.value, function (err) {
  16106. callback(err);
  16107. });
  16108. });
  16109. } else {
  16110. var results = [];
  16111. eachfn(arr, function (x, callback) {
  16112. iterator(x.value, function (err, v) {
  16113. results[x.index] = v;
  16114. callback(err);
  16115. });
  16116. }, function (err) {
  16117. callback(err, results);
  16118. });
  16119. }
  16120. };
  16121. async.map = doParallel(_asyncMap);
  16122. async.mapSeries = doSeries(_asyncMap);
  16123. async.mapLimit = function (arr, limit, iterator, callback) {
  16124. return _mapLimit(limit)(arr, iterator, callback);
  16125. };
  16126. var _mapLimit = function(limit) {
  16127. return doParallelLimit(limit, _asyncMap);
  16128. };
  16129. // reduce only has a series version, as doing reduce in parallel won't
  16130. // work in many situations.
  16131. async.reduce = function (arr, memo, iterator, callback) {
  16132. async.eachSeries(arr, function (x, callback) {
  16133. iterator(memo, x, function (err, v) {
  16134. memo = v;
  16135. callback(err);
  16136. });
  16137. }, function (err) {
  16138. callback(err, memo);
  16139. });
  16140. };
  16141. // inject alias
  16142. async.inject = async.reduce;
  16143. // foldl alias
  16144. async.foldl = async.reduce;
  16145. async.reduceRight = function (arr, memo, iterator, callback) {
  16146. var reversed = _map(arr, function (x) {
  16147. return x;
  16148. }).reverse();
  16149. async.reduce(reversed, memo, iterator, callback);
  16150. };
  16151. // foldr alias
  16152. async.foldr = async.reduceRight;
  16153. var _filter = function (eachfn, arr, iterator, callback) {
  16154. var results = [];
  16155. arr = _map(arr, function (x, i) {
  16156. return {index: i, value: x};
  16157. });
  16158. eachfn(arr, function (x, callback) {
  16159. iterator(x.value, function (v) {
  16160. if (v) {
  16161. results.push(x);
  16162. }
  16163. callback();
  16164. });
  16165. }, function (err) {
  16166. callback(_map(results.sort(function (a, b) {
  16167. return a.index - b.index;
  16168. }), function (x) {
  16169. return x.value;
  16170. }));
  16171. });
  16172. };
  16173. async.filter = doParallel(_filter);
  16174. async.filterSeries = doSeries(_filter);
  16175. // select alias
  16176. async.select = async.filter;
  16177. async.selectSeries = async.filterSeries;
  16178. var _reject = function (eachfn, arr, iterator, callback) {
  16179. var results = [];
  16180. arr = _map(arr, function (x, i) {
  16181. return {index: i, value: x};
  16182. });
  16183. eachfn(arr, function (x, callback) {
  16184. iterator(x.value, function (v) {
  16185. if (!v) {
  16186. results.push(x);
  16187. }
  16188. callback();
  16189. });
  16190. }, function (err) {
  16191. callback(_map(results.sort(function (a, b) {
  16192. return a.index - b.index;
  16193. }), function (x) {
  16194. return x.value;
  16195. }));
  16196. });
  16197. };
  16198. async.reject = doParallel(_reject);
  16199. async.rejectSeries = doSeries(_reject);
  16200. var _detect = function (eachfn, arr, iterator, main_callback) {
  16201. eachfn(arr, function (x, callback) {
  16202. iterator(x, function (result) {
  16203. if (result) {
  16204. main_callback(x);
  16205. main_callback = function () {};
  16206. }
  16207. else {
  16208. callback();
  16209. }
  16210. });
  16211. }, function (err) {
  16212. main_callback();
  16213. });
  16214. };
  16215. async.detect = doParallel(_detect);
  16216. async.detectSeries = doSeries(_detect);
  16217. async.some = function (arr, iterator, main_callback) {
  16218. async.each(arr, function (x, callback) {
  16219. iterator(x, function (v) {
  16220. if (v) {
  16221. main_callback(true);
  16222. main_callback = function () {};
  16223. }
  16224. callback();
  16225. });
  16226. }, function (err) {
  16227. main_callback(false);
  16228. });
  16229. };
  16230. // any alias
  16231. async.any = async.some;
  16232. async.every = function (arr, iterator, main_callback) {
  16233. async.each(arr, function (x, callback) {
  16234. iterator(x, function (v) {
  16235. if (!v) {
  16236. main_callback(false);
  16237. main_callback = function () {};
  16238. }
  16239. callback();
  16240. });
  16241. }, function (err) {
  16242. main_callback(true);
  16243. });
  16244. };
  16245. // all alias
  16246. async.all = async.every;
  16247. async.sortBy = function (arr, iterator, callback) {
  16248. async.map(arr, function (x, callback) {
  16249. iterator(x, function (err, criteria) {
  16250. if (err) {
  16251. callback(err);
  16252. }
  16253. else {
  16254. callback(null, {value: x, criteria: criteria});
  16255. }
  16256. });
  16257. }, function (err, results) {
  16258. if (err) {
  16259. return callback(err);
  16260. }
  16261. else {
  16262. var fn = function (left, right) {
  16263. var a = left.criteria, b = right.criteria;
  16264. return a < b ? -1 : a > b ? 1 : 0;
  16265. };
  16266. callback(null, _map(results.sort(fn), function (x) {
  16267. return x.value;
  16268. }));
  16269. }
  16270. });
  16271. };
  16272. async.auto = function (tasks, callback) {
  16273. callback = callback || function () {};
  16274. var keys = _keys(tasks);
  16275. var remainingTasks = keys.length
  16276. if (!remainingTasks) {
  16277. return callback();
  16278. }
  16279. var results = {};
  16280. var listeners = [];
  16281. var addListener = function (fn) {
  16282. listeners.unshift(fn);
  16283. };
  16284. var removeListener = function (fn) {
  16285. for (var i = 0; i < listeners.length; i += 1) {
  16286. if (listeners[i] === fn) {
  16287. listeners.splice(i, 1);
  16288. return;
  16289. }
  16290. }
  16291. };
  16292. var taskComplete = function () {
  16293. remainingTasks--
  16294. _each(listeners.slice(0), function (fn) {
  16295. fn();
  16296. });
  16297. };
  16298. addListener(function () {
  16299. if (!remainingTasks) {
  16300. var theCallback = callback;
  16301. // prevent final callback from calling itself if it errors
  16302. callback = function () {};
  16303. theCallback(null, results);
  16304. }
  16305. });
  16306. _each(keys, function (k) {
  16307. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  16308. var taskCallback = function (err) {
  16309. var args = Array.prototype.slice.call(arguments, 1);
  16310. if (args.length <= 1) {
  16311. args = args[0];
  16312. }
  16313. if (err) {
  16314. var safeResults = {};
  16315. _each(_keys(results), function(rkey) {
  16316. safeResults[rkey] = results[rkey];
  16317. });
  16318. safeResults[k] = args;
  16319. callback(err, safeResults);
  16320. // stop subsequent errors hitting callback multiple times
  16321. callback = function () {};
  16322. }
  16323. else {
  16324. results[k] = args;
  16325. async.setImmediate(taskComplete);
  16326. }
  16327. };
  16328. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  16329. var ready = function () {
  16330. return _reduce(requires, function (a, x) {
  16331. return (a && results.hasOwnProperty(x));
  16332. }, true) && !results.hasOwnProperty(k);
  16333. };
  16334. if (ready()) {
  16335. task[task.length - 1](taskCallback, results);
  16336. }
  16337. else {
  16338. var listener = function () {
  16339. if (ready()) {
  16340. removeListener(listener);
  16341. task[task.length - 1](taskCallback, results);
  16342. }
  16343. };
  16344. addListener(listener);
  16345. }
  16346. });
  16347. };
  16348. async.retry = function(times, task, callback) {
  16349. var DEFAULT_TIMES = 5;
  16350. var attempts = [];
  16351. // Use defaults if times not passed
  16352. if (typeof times === 'function') {
  16353. callback = task;
  16354. task = times;
  16355. times = DEFAULT_TIMES;
  16356. }
  16357. // Make sure times is a number
  16358. times = parseInt(times, 10) || DEFAULT_TIMES;
  16359. var wrappedTask = function(wrappedCallback, wrappedResults) {
  16360. var retryAttempt = function(task, finalAttempt) {
  16361. return function(seriesCallback) {
  16362. task(function(err, result){
  16363. seriesCallback(!err || finalAttempt, {err: err, result: result});
  16364. }, wrappedResults);
  16365. };
  16366. };
  16367. while (times) {
  16368. attempts.push(retryAttempt(task, !(times-=1)));
  16369. }
  16370. async.series(attempts, function(done, data){
  16371. data = data[data.length - 1];
  16372. (wrappedCallback || callback)(data.err, data.result);
  16373. });
  16374. }
  16375. // If a callback is passed, run this as a controll flow
  16376. return callback ? wrappedTask() : wrappedTask
  16377. };
  16378. async.waterfall = function (tasks, callback) {
  16379. callback = callback || function () {};
  16380. if (!_isArray(tasks)) {
  16381. var err = new Error('First argument to waterfall must be an array of functions');
  16382. return callback(err);
  16383. }
  16384. if (!tasks.length) {
  16385. return callback();
  16386. }
  16387. var wrapIterator = function (iterator) {
  16388. return function (err) {
  16389. if (err) {
  16390. callback.apply(null, arguments);
  16391. callback = function () {};
  16392. }
  16393. else {
  16394. var args = Array.prototype.slice.call(arguments, 1);
  16395. var next = iterator.next();
  16396. if (next) {
  16397. args.push(wrapIterator(next));
  16398. }
  16399. else {
  16400. args.push(callback);
  16401. }
  16402. async.setImmediate(function () {
  16403. iterator.apply(null, args);
  16404. });
  16405. }
  16406. };
  16407. };
  16408. wrapIterator(async.iterator(tasks))();
  16409. };
  16410. var _parallel = function(eachfn, tasks, callback) {
  16411. callback = callback || function () {};
  16412. if (_isArray(tasks)) {
  16413. eachfn.map(tasks, function (fn, callback) {
  16414. if (fn) {
  16415. fn(function (err) {
  16416. var args = Array.prototype.slice.call(arguments, 1);
  16417. if (args.length <= 1) {
  16418. args = args[0];
  16419. }
  16420. callback.call(null, err, args);
  16421. });
  16422. }
  16423. }, callback);
  16424. }
  16425. else {
  16426. var results = {};
  16427. eachfn.each(_keys(tasks), function (k, callback) {
  16428. tasks[k](function (err) {
  16429. var args = Array.prototype.slice.call(arguments, 1);
  16430. if (args.length <= 1) {
  16431. args = args[0];
  16432. }
  16433. results[k] = args;
  16434. callback(err);
  16435. });
  16436. }, function (err) {
  16437. callback(err, results);
  16438. });
  16439. }
  16440. };
  16441. async.parallel = function (tasks, callback) {
  16442. _parallel({ map: async.map, each: async.each }, tasks, callback);
  16443. };
  16444. async.parallelLimit = function(tasks, limit, callback) {
  16445. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  16446. };
  16447. async.series = function (tasks, callback) {
  16448. callback = callback || function () {};
  16449. if (_isArray(tasks)) {
  16450. async.mapSeries(tasks, function (fn, callback) {
  16451. if (fn) {
  16452. fn(function (err) {
  16453. var args = Array.prototype.slice.call(arguments, 1);
  16454. if (args.length <= 1) {
  16455. args = args[0];
  16456. }
  16457. callback.call(null, err, args);
  16458. });
  16459. }
  16460. }, callback);
  16461. }
  16462. else {
  16463. var results = {};
  16464. async.eachSeries(_keys(tasks), function (k, callback) {
  16465. tasks[k](function (err) {
  16466. var args = Array.prototype.slice.call(arguments, 1);
  16467. if (args.length <= 1) {
  16468. args = args[0];
  16469. }
  16470. results[k] = args;
  16471. callback(err);
  16472. });
  16473. }, function (err) {
  16474. callback(err, results);
  16475. });
  16476. }
  16477. };
  16478. async.iterator = function (tasks) {
  16479. var makeCallback = function (index) {
  16480. var fn = function () {
  16481. if (tasks.length) {
  16482. tasks[index].apply(null, arguments);
  16483. }
  16484. return fn.next();
  16485. };
  16486. fn.next = function () {
  16487. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  16488. };
  16489. return fn;
  16490. };
  16491. return makeCallback(0);
  16492. };
  16493. async.apply = function (fn) {
  16494. var args = Array.prototype.slice.call(arguments, 1);
  16495. return function () {
  16496. return fn.apply(
  16497. null, args.concat(Array.prototype.slice.call(arguments))
  16498. );
  16499. };
  16500. };
  16501. var _concat = function (eachfn, arr, fn, callback) {
  16502. var r = [];
  16503. eachfn(arr, function (x, cb) {
  16504. fn(x, function (err, y) {
  16505. r = r.concat(y || []);
  16506. cb(err);
  16507. });
  16508. }, function (err) {
  16509. callback(err, r);
  16510. });
  16511. };
  16512. async.concat = doParallel(_concat);
  16513. async.concatSeries = doSeries(_concat);
  16514. async.whilst = function (test, iterator, callback) {
  16515. if (test()) {
  16516. iterator(function (err) {
  16517. if (err) {
  16518. return callback(err);
  16519. }
  16520. async.whilst(test, iterator, callback);
  16521. });
  16522. }
  16523. else {
  16524. callback();
  16525. }
  16526. };
  16527. async.doWhilst = function (iterator, test, callback) {
  16528. iterator(function (err) {
  16529. if (err) {
  16530. return callback(err);
  16531. }
  16532. var args = Array.prototype.slice.call(arguments, 1);
  16533. if (test.apply(null, args)) {
  16534. async.doWhilst(iterator, test, callback);
  16535. }
  16536. else {
  16537. callback();
  16538. }
  16539. });
  16540. };
  16541. async.until = function (test, iterator, callback) {
  16542. if (!test()) {
  16543. iterator(function (err) {
  16544. if (err) {
  16545. return callback(err);
  16546. }
  16547. async.until(test, iterator, callback);
  16548. });
  16549. }
  16550. else {
  16551. callback();
  16552. }
  16553. };
  16554. async.doUntil = function (iterator, test, callback) {
  16555. iterator(function (err) {
  16556. if (err) {
  16557. return callback(err);
  16558. }
  16559. var args = Array.prototype.slice.call(arguments, 1);
  16560. if (!test.apply(null, args)) {
  16561. async.doUntil(iterator, test, callback);
  16562. }
  16563. else {
  16564. callback();
  16565. }
  16566. });
  16567. };
  16568. async.queue = function (worker, concurrency) {
  16569. if (concurrency === undefined) {
  16570. concurrency = 1;
  16571. }
  16572. function _insert(q, data, pos, callback) {
  16573. if (!q.started){
  16574. q.started = true;
  16575. }
  16576. if (!_isArray(data)) {
  16577. data = [data];
  16578. }
  16579. if(data.length == 0) {
  16580. // call drain immediately if there are no tasks
  16581. return async.setImmediate(function() {
  16582. if (q.drain) {
  16583. q.drain();
  16584. }
  16585. });
  16586. }
  16587. _each(data, function(task) {
  16588. var item = {
  16589. data: task,
  16590. callback: typeof callback === 'function' ? callback : null
  16591. };
  16592. if (pos) {
  16593. q.tasks.unshift(item);
  16594. } else {
  16595. q.tasks.push(item);
  16596. }
  16597. if (q.saturated && q.tasks.length === q.concurrency) {
  16598. q.saturated();
  16599. }
  16600. async.setImmediate(q.process);
  16601. });
  16602. }
  16603. var workers = 0;
  16604. var q = {
  16605. tasks: [],
  16606. concurrency: concurrency,
  16607. saturated: null,
  16608. empty: null,
  16609. drain: null,
  16610. started: false,
  16611. paused: false,
  16612. push: function (data, callback) {
  16613. _insert(q, data, false, callback);
  16614. },
  16615. kill: function () {
  16616. q.drain = null;
  16617. q.tasks = [];
  16618. },
  16619. unshift: function (data, callback) {
  16620. _insert(q, data, true, callback);
  16621. },
  16622. process: function () {
  16623. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  16624. var task = q.tasks.shift();
  16625. if (q.empty && q.tasks.length === 0) {
  16626. q.empty();
  16627. }
  16628. workers += 1;
  16629. var next = function () {
  16630. workers -= 1;
  16631. if (task.callback) {
  16632. task.callback.apply(task, arguments);
  16633. }
  16634. if (q.drain && q.tasks.length + workers === 0) {
  16635. q.drain();
  16636. }
  16637. q.process();
  16638. };
  16639. var cb = only_once(next);
  16640. worker(task.data, cb);
  16641. }
  16642. },
  16643. length: function () {
  16644. return q.tasks.length;
  16645. },
  16646. running: function () {
  16647. return workers;
  16648. },
  16649. idle: function() {
  16650. return q.tasks.length + workers === 0;
  16651. },
  16652. pause: function () {
  16653. if (q.paused === true) { return; }
  16654. q.paused = true;
  16655. q.process();
  16656. },
  16657. resume: function () {
  16658. if (q.paused === false) { return; }
  16659. q.paused = false;
  16660. q.process();
  16661. }
  16662. };
  16663. return q;
  16664. };
  16665. async.priorityQueue = function (worker, concurrency) {
  16666. function _compareTasks(a, b){
  16667. return a.priority - b.priority;
  16668. };
  16669. function _binarySearch(sequence, item, compare) {
  16670. var beg = -1,
  16671. end = sequence.length - 1;
  16672. while (beg < end) {
  16673. var mid = beg + ((end - beg + 1) >>> 1);
  16674. if (compare(item, sequence[mid]) >= 0) {
  16675. beg = mid;
  16676. } else {
  16677. end = mid - 1;
  16678. }
  16679. }
  16680. return beg;
  16681. }
  16682. function _insert(q, data, priority, callback) {
  16683. if (!q.started){
  16684. q.started = true;
  16685. }
  16686. if (!_isArray(data)) {
  16687. data = [data];
  16688. }
  16689. if(data.length == 0) {
  16690. // call drain immediately if there are no tasks
  16691. return async.setImmediate(function() {
  16692. if (q.drain) {
  16693. q.drain();
  16694. }
  16695. });
  16696. }
  16697. _each(data, function(task) {
  16698. var item = {
  16699. data: task,
  16700. priority: priority,
  16701. callback: typeof callback === 'function' ? callback : null
  16702. };
  16703. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  16704. if (q.saturated && q.tasks.length === q.concurrency) {
  16705. q.saturated();
  16706. }
  16707. async.setImmediate(q.process);
  16708. });
  16709. }
  16710. // Start with a normal queue
  16711. var q = async.queue(worker, concurrency);
  16712. // Override push to accept second parameter representing priority
  16713. q.push = function (data, priority, callback) {
  16714. _insert(q, data, priority, callback);
  16715. };
  16716. // Remove unshift function
  16717. delete q.unshift;
  16718. return q;
  16719. };
  16720. async.cargo = function (worker, payload) {
  16721. var working = false,
  16722. tasks = [];
  16723. var cargo = {
  16724. tasks: tasks,
  16725. payload: payload,
  16726. saturated: null,
  16727. empty: null,
  16728. drain: null,
  16729. drained: true,
  16730. push: function (data, callback) {
  16731. if (!_isArray(data)) {
  16732. data = [data];
  16733. }
  16734. _each(data, function(task) {
  16735. tasks.push({
  16736. data: task,
  16737. callback: typeof callback === 'function' ? callback : null
  16738. });
  16739. cargo.drained = false;
  16740. if (cargo.saturated && tasks.length === payload) {
  16741. cargo.saturated();
  16742. }
  16743. });
  16744. async.setImmediate(cargo.process);
  16745. },
  16746. process: function process() {
  16747. if (working) return;
  16748. if (tasks.length === 0) {
  16749. if(cargo.drain && !cargo.drained) cargo.drain();
  16750. cargo.drained = true;
  16751. return;
  16752. }
  16753. var ts = typeof payload === 'number'
  16754. ? tasks.splice(0, payload)
  16755. : tasks.splice(0, tasks.length);
  16756. var ds = _map(ts, function (task) {
  16757. return task.data;
  16758. });
  16759. if(cargo.empty) cargo.empty();
  16760. working = true;
  16761. worker(ds, function () {
  16762. working = false;
  16763. var args = arguments;
  16764. _each(ts, function (data) {
  16765. if (data.callback) {
  16766. data.callback.apply(null, args);
  16767. }
  16768. });
  16769. process();
  16770. });
  16771. },
  16772. length: function () {
  16773. return tasks.length;
  16774. },
  16775. running: function () {
  16776. return working;
  16777. }
  16778. };
  16779. return cargo;
  16780. };
  16781. var _console_fn = function (name) {
  16782. return function (fn) {
  16783. var args = Array.prototype.slice.call(arguments, 1);
  16784. fn.apply(null, args.concat([function (err) {
  16785. var args = Array.prototype.slice.call(arguments, 1);
  16786. if (typeof console !== 'undefined') {
  16787. if (err) {
  16788. if (console.error) {
  16789. console.error(err);
  16790. }
  16791. }
  16792. else if (console[name]) {
  16793. _each(args, function (x) {
  16794. console[name](x);
  16795. });
  16796. }
  16797. }
  16798. }]));
  16799. };
  16800. };
  16801. async.log = _console_fn('log');
  16802. async.dir = _console_fn('dir');
  16803. /*async.info = _console_fn('info');
  16804. async.warn = _console_fn('warn');
  16805. async.error = _console_fn('error');*/
  16806. async.memoize = function (fn, hasher) {
  16807. var memo = {};
  16808. var queues = {};
  16809. hasher = hasher || function (x) {
  16810. return x;
  16811. };
  16812. var memoized = function () {
  16813. var args = Array.prototype.slice.call(arguments);
  16814. var callback = args.pop();
  16815. var key = hasher.apply(null, args);
  16816. if (key in memo) {
  16817. async.nextTick(function () {
  16818. callback.apply(null, memo[key]);
  16819. });
  16820. }
  16821. else if (key in queues) {
  16822. queues[key].push(callback);
  16823. }
  16824. else {
  16825. queues[key] = [callback];
  16826. fn.apply(null, args.concat([function () {
  16827. memo[key] = arguments;
  16828. var q = queues[key];
  16829. delete queues[key];
  16830. for (var i = 0, l = q.length; i < l; i++) {
  16831. q[i].apply(null, arguments);
  16832. }
  16833. }]));
  16834. }
  16835. };
  16836. memoized.memo = memo;
  16837. memoized.unmemoized = fn;
  16838. return memoized;
  16839. };
  16840. async.unmemoize = function (fn) {
  16841. return function () {
  16842. return (fn.unmemoized || fn).apply(null, arguments);
  16843. };
  16844. };
  16845. async.times = function (count, iterator, callback) {
  16846. var counter = [];
  16847. for (var i = 0; i < count; i++) {
  16848. counter.push(i);
  16849. }
  16850. return async.map(counter, iterator, callback);
  16851. };
  16852. async.timesSeries = function (count, iterator, callback) {
  16853. var counter = [];
  16854. for (var i = 0; i < count; i++) {
  16855. counter.push(i);
  16856. }
  16857. return async.mapSeries(counter, iterator, callback);
  16858. };
  16859. async.seq = function (/* functions... */) {
  16860. var fns = arguments;
  16861. return function () {
  16862. var that = this;
  16863. var args = Array.prototype.slice.call(arguments);
  16864. var callback = args.pop();
  16865. async.reduce(fns, args, function (newargs, fn, cb) {
  16866. fn.apply(that, newargs.concat([function () {
  16867. var err = arguments[0];
  16868. var nextargs = Array.prototype.slice.call(arguments, 1);
  16869. cb(err, nextargs);
  16870. }]))
  16871. },
  16872. function (err, results) {
  16873. callback.apply(that, [err].concat(results));
  16874. });
  16875. };
  16876. };
  16877. async.compose = function (/* functions... */) {
  16878. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  16879. };
  16880. var _applyEach = function (eachfn, fns /*args...*/) {
  16881. var go = function () {
  16882. var that = this;
  16883. var args = Array.prototype.slice.call(arguments);
  16884. var callback = args.pop();
  16885. return eachfn(fns, function (fn, cb) {
  16886. fn.apply(that, args.concat([cb]));
  16887. },
  16888. callback);
  16889. };
  16890. if (arguments.length > 2) {
  16891. var args = Array.prototype.slice.call(arguments, 2);
  16892. return go.apply(this, args);
  16893. }
  16894. else {
  16895. return go;
  16896. }
  16897. };
  16898. async.applyEach = doParallel(_applyEach);
  16899. async.applyEachSeries = doSeries(_applyEach);
  16900. async.forever = function (fn, callback) {
  16901. function next(err) {
  16902. if (err) {
  16903. if (callback) {
  16904. return callback(err);
  16905. }
  16906. throw err;
  16907. }
  16908. fn(next);
  16909. }
  16910. next();
  16911. };
  16912. // Node.js
  16913. if (typeof module !== 'undefined' && module.exports) {
  16914. module.exports = async;
  16915. }
  16916. // AMD / RequireJS
  16917. else if (typeof define !== 'undefined' && define.amd) {
  16918. define([], function () {
  16919. return async;
  16920. });
  16921. }
  16922. // included directly via <script> tag
  16923. else {
  16924. root.async = async;
  16925. }
  16926. }());
  16927. }).call(this,require('_process'))
  16928. },{"_process":107}],66:[function(require,module,exports){
  16929. // i18next, v1.7.7
  16930. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  16931. // Distributed under MIT license
  16932. // http://i18next.com
  16933. (function() {
  16934. // add indexOf to non ECMA-262 standard compliant browsers
  16935. if (!Array.prototype.indexOf) {
  16936. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  16937. "use strict";
  16938. if (this == null) {
  16939. throw new TypeError();
  16940. }
  16941. var t = Object(this);
  16942. var len = t.length >>> 0;
  16943. if (len === 0) {
  16944. return -1;
  16945. }
  16946. var n = 0;
  16947. if (arguments.length > 0) {
  16948. n = Number(arguments[1]);
  16949. if (n != n) { // shortcut for verifying if it's NaN
  16950. n = 0;
  16951. } else if (n != 0 && n != Infinity && n != -Infinity) {
  16952. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  16953. }
  16954. }
  16955. if (n >= len) {
  16956. return -1;
  16957. }
  16958. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  16959. for (; k < len; k++) {
  16960. if (k in t && t[k] === searchElement) {
  16961. return k;
  16962. }
  16963. }
  16964. return -1;
  16965. }
  16966. }
  16967. // add lastIndexOf to non ECMA-262 standard compliant browsers
  16968. if (!Array.prototype.lastIndexOf) {
  16969. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  16970. "use strict";
  16971. if (this == null) {
  16972. throw new TypeError();
  16973. }
  16974. var t = Object(this);
  16975. var len = t.length >>> 0;
  16976. if (len === 0) {
  16977. return -1;
  16978. }
  16979. var n = len;
  16980. if (arguments.length > 1) {
  16981. n = Number(arguments[1]);
  16982. if (n != n) {
  16983. n = 0;
  16984. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  16985. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  16986. }
  16987. }
  16988. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  16989. for (; k >= 0; k--) {
  16990. if (k in t && t[k] === searchElement) {
  16991. return k;
  16992. }
  16993. }
  16994. return -1;
  16995. };
  16996. }
  16997. // Add string trim for IE8.
  16998. if (typeof String.prototype.trim !== 'function') {
  16999. String.prototype.trim = function() {
  17000. return this.replace(/^\s+|\s+$/g, '');
  17001. }
  17002. }
  17003. var root = this
  17004. , $ = root.jQuery || root.Zepto
  17005. , i18n = {}
  17006. , resStore = {}
  17007. , currentLng
  17008. , replacementCounter = 0
  17009. , languages = []
  17010. , initialized = false
  17011. , sync = {};
  17012. // Export the i18next object for **CommonJS**.
  17013. // If we're not in CommonJS, add `i18n` to the
  17014. // global object or to jquery.
  17015. if (typeof module !== 'undefined' && module.exports) {
  17016. if (!$) {
  17017. try {
  17018. $ = require('jquery');
  17019. } catch(e) {
  17020. // just ignore
  17021. }
  17022. }
  17023. if ($) {
  17024. $.i18n = $.i18n || i18n;
  17025. }
  17026. module.exports = i18n;
  17027. } else {
  17028. if ($) {
  17029. $.i18n = $.i18n || i18n;
  17030. }
  17031. root.i18n = root.i18n || i18n;
  17032. }
  17033. sync = {
  17034. load: function(lngs, options, cb) {
  17035. if (options.useLocalStorage) {
  17036. sync._loadLocal(lngs, options, function(err, store) {
  17037. var missingLngs = [];
  17038. for (var i = 0, len = lngs.length; i < len; i++) {
  17039. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  17040. }
  17041. if (missingLngs.length > 0) {
  17042. sync._fetch(missingLngs, options, function(err, fetched) {
  17043. f.extend(store, fetched);
  17044. sync._storeLocal(fetched);
  17045. cb(null, store);
  17046. });
  17047. } else {
  17048. cb(null, store);
  17049. }
  17050. });
  17051. } else {
  17052. sync._fetch(lngs, options, function(err, store){
  17053. cb(null, store);
  17054. });
  17055. }
  17056. },
  17057. _loadLocal: function(lngs, options, cb) {
  17058. var store = {}
  17059. , nowMS = new Date().getTime();
  17060. if(window.localStorage) {
  17061. var todo = lngs.length;
  17062. f.each(lngs, function(key, lng) {
  17063. var local = window.localStorage.getItem('res_' + lng);
  17064. if (local) {
  17065. local = JSON.parse(local);
  17066. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  17067. store[lng] = local;
  17068. }
  17069. }
  17070. todo--; // wait for all done befor callback
  17071. if (todo === 0) cb(null, store);
  17072. });
  17073. }
  17074. },
  17075. _storeLocal: function(store) {
  17076. if(window.localStorage) {
  17077. for (var m in store) {
  17078. store[m].i18nStamp = new Date().getTime();
  17079. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  17080. }
  17081. }
  17082. return;
  17083. },
  17084. _fetch: function(lngs, options, cb) {
  17085. var ns = options.ns
  17086. , store = {};
  17087. if (!options.dynamicLoad) {
  17088. var todo = ns.namespaces.length * lngs.length
  17089. , errors;
  17090. // load each file individual
  17091. f.each(ns.namespaces, function(nsIndex, nsValue) {
  17092. f.each(lngs, function(lngIndex, lngValue) {
  17093. // Call this once our translation has returned.
  17094. var loadComplete = function(err, data) {
  17095. if (err) {
  17096. errors = errors || [];
  17097. errors.push(err);
  17098. }
  17099. store[lngValue] = store[lngValue] || {};
  17100. store[lngValue][nsValue] = data;
  17101. todo--; // wait for all done befor callback
  17102. if (todo === 0) cb(errors, store);
  17103. };
  17104. if(typeof options.customLoad == 'function'){
  17105. // Use the specified custom callback.
  17106. options.customLoad(lngValue, nsValue, options, loadComplete);
  17107. } else {
  17108. //~ // Use our inbuilt sync.
  17109. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  17110. }
  17111. });
  17112. });
  17113. } else {
  17114. // Call this once our translation has returned.
  17115. var loadComplete = function(err, data) {
  17116. cb(null, data);
  17117. };
  17118. if(typeof options.customLoad == 'function'){
  17119. // Use the specified custom callback.
  17120. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  17121. } else {
  17122. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  17123. // load all needed stuff once
  17124. f.ajax({
  17125. url: url,
  17126. success: function(data, status, xhr) {
  17127. f.log('loaded: ' + url);
  17128. loadComplete(null, data);
  17129. },
  17130. error : function(xhr, status, error) {
  17131. f.log('failed loading: ' + url);
  17132. loadComplete('failed loading resource.json error: ' + error);
  17133. },
  17134. dataType: "json",
  17135. async : options.getAsync
  17136. });
  17137. }
  17138. }
  17139. },
  17140. _fetchOne: function(lng, ns, options, done) {
  17141. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  17142. f.ajax({
  17143. url: url,
  17144. success: function(data, status, xhr) {
  17145. f.log('loaded: ' + url);
  17146. done(null, data);
  17147. },
  17148. error : function(xhr, status, error) {
  17149. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  17150. // file loaded but invalid json, stop waste time !
  17151. f.error('There is a typo in: ' + url);
  17152. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  17153. f.log('Does not exist: ' + url);
  17154. } else {
  17155. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  17156. f.log(theStatus + ' when loading ' + url);
  17157. }
  17158. done(error, {});
  17159. },
  17160. dataType: "json",
  17161. async : options.getAsync
  17162. });
  17163. },
  17164. postMissing: function(lng, ns, key, defaultValue, lngs) {
  17165. var payload = {};
  17166. payload[key] = defaultValue;
  17167. var urls = [];
  17168. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  17169. for (var i = 0; i < o.fallbackLng.length; i++) {
  17170. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  17171. }
  17172. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  17173. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  17174. } else if (o.sendMissingTo === 'all') {
  17175. for (var i = 0, l = lngs.length; i < l; i++) {
  17176. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  17177. }
  17178. }
  17179. for (var y = 0, len = urls.length; y < len; y++) {
  17180. var item = urls[y];
  17181. f.ajax({
  17182. url: item.url,
  17183. type: o.sendType,
  17184. data: payload,
  17185. success: function(data, status, xhr) {
  17186. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  17187. // add key to resStore
  17188. var keys = key.split('.');
  17189. var x = 0;
  17190. var value = resStore[item.lng][ns];
  17191. while (keys[x]) {
  17192. if (x === keys.length - 1) {
  17193. value = value[keys[x]] = defaultValue;
  17194. } else {
  17195. value = value[keys[x]] = value[keys[x]] || {};
  17196. }
  17197. x++;
  17198. }
  17199. },
  17200. error : function(xhr, status, error) {
  17201. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  17202. },
  17203. dataType: "json",
  17204. async : o.postAsync
  17205. });
  17206. }
  17207. },
  17208. reload: reload
  17209. };
  17210. // defaults
  17211. var o = {
  17212. lng: undefined,
  17213. load: 'all',
  17214. preload: [],
  17215. lowerCaseLng: false,
  17216. returnObjectTrees: false,
  17217. fallbackLng: ['dev'],
  17218. fallbackNS: [],
  17219. detectLngQS: 'setLng',
  17220. detectLngFromLocalStorage: false,
  17221. ns: 'translation',
  17222. fallbackOnNull: true,
  17223. fallbackOnEmpty: false,
  17224. fallbackToDefaultNS: false,
  17225. nsseparator: ':',
  17226. keyseparator: '.',
  17227. selectorAttr: 'data-i18n',
  17228. debug: false,
  17229. resGetPath: 'locales/__lng__/__ns__.json',
  17230. resPostPath: 'locales/add/__lng__/__ns__',
  17231. getAsync: true,
  17232. postAsync: true,
  17233. resStore: undefined,
  17234. useLocalStorage: false,
  17235. localStorageExpirationTime: 7*24*60*60*1000,
  17236. dynamicLoad: false,
  17237. sendMissing: false,
  17238. sendMissingTo: 'fallback', // current | all
  17239. sendType: 'POST',
  17240. interpolationPrefix: '__',
  17241. interpolationSuffix: '__',
  17242. defaultVariables: false,
  17243. reusePrefix: '$t(',
  17244. reuseSuffix: ')',
  17245. pluralSuffix: '_plural',
  17246. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  17247. contextNotFound: ['context_not_found', Math.random()].join(''),
  17248. escapeInterpolation: false,
  17249. indefiniteSuffix: '_indefinite',
  17250. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  17251. setJqueryExt: true,
  17252. defaultValueFromContent: true,
  17253. useDataAttrOptions: false,
  17254. cookieExpirationTime: undefined,
  17255. useCookie: true,
  17256. cookieName: 'i18next',
  17257. cookieDomain: undefined,
  17258. objectTreeKeyHandler: undefined,
  17259. postProcess: undefined,
  17260. parseMissingKey: undefined,
  17261. missingKeyHandler: sync.postMissing,
  17262. shortcutFunction: 'sprintf' // or: defaultValue
  17263. };
  17264. function _extend(target, source) {
  17265. if (!source || typeof source === 'function') {
  17266. return target;
  17267. }
  17268. for (var attr in source) { target[attr] = source[attr]; }
  17269. return target;
  17270. }
  17271. function _deepExtend(target, source) {
  17272. for (var prop in source)
  17273. if (prop in target)
  17274. _deepExtend(target[prop], source[prop]);
  17275. else
  17276. target[prop] = source[prop];
  17277. return target;
  17278. }
  17279. function _each(object, callback, args) {
  17280. var name, i = 0,
  17281. length = object.length,
  17282. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  17283. if (args) {
  17284. if (isObj) {
  17285. for (name in object) {
  17286. if (callback.apply(object[name], args) === false) {
  17287. break;
  17288. }
  17289. }
  17290. } else {
  17291. for ( ; i < length; ) {
  17292. if (callback.apply(object[i++], args) === false) {
  17293. break;
  17294. }
  17295. }
  17296. }
  17297. // A special, fast, case for the most common use of each
  17298. } else {
  17299. if (isObj) {
  17300. for (name in object) {
  17301. if (callback.call(object[name], name, object[name]) === false) {
  17302. break;
  17303. }
  17304. }
  17305. } else {
  17306. for ( ; i < length; ) {
  17307. if (callback.call(object[i], i, object[i++]) === false) {
  17308. break;
  17309. }
  17310. }
  17311. }
  17312. }
  17313. return object;
  17314. }
  17315. var _entityMap = {
  17316. "&": "&amp;",
  17317. "<": "&lt;",
  17318. ">": "&gt;",
  17319. '"': '&quot;',
  17320. "'": '&#39;',
  17321. "/": '&#x2F;'
  17322. };
  17323. function _escape(data) {
  17324. if (typeof data === 'string') {
  17325. return data.replace(/[&<>"'\/]/g, function (s) {
  17326. return _entityMap[s];
  17327. });
  17328. }else{
  17329. return data;
  17330. }
  17331. }
  17332. function _ajax(options) {
  17333. // v0.5.0 of https://github.com/goloroden/http.js
  17334. var getXhr = function (callback) {
  17335. // Use the native XHR object if the browser supports it.
  17336. if (window.XMLHttpRequest) {
  17337. return callback(null, new XMLHttpRequest());
  17338. } else if (window.ActiveXObject) {
  17339. // In Internet Explorer check for ActiveX versions of the XHR object.
  17340. try {
  17341. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  17342. } catch (e) {
  17343. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  17344. }
  17345. }
  17346. // If no XHR support was found, throw an error.
  17347. return callback(new Error());
  17348. };
  17349. var encodeUsingUrlEncoding = function (data) {
  17350. if(typeof data === 'string') {
  17351. return data;
  17352. }
  17353. var result = [];
  17354. for(var dataItem in data) {
  17355. if(data.hasOwnProperty(dataItem)) {
  17356. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  17357. }
  17358. }
  17359. return result.join('&');
  17360. };
  17361. var utf8 = function (text) {
  17362. text = text.replace(/\r\n/g, '\n');
  17363. var result = '';
  17364. for(var i = 0; i < text.length; i++) {
  17365. var c = text.charCodeAt(i);
  17366. if(c < 128) {
  17367. result += String.fromCharCode(c);
  17368. } else if((c > 127) && (c < 2048)) {
  17369. result += String.fromCharCode((c >> 6) | 192);
  17370. result += String.fromCharCode((c & 63) | 128);
  17371. } else {
  17372. result += String.fromCharCode((c >> 12) | 224);
  17373. result += String.fromCharCode(((c >> 6) & 63) | 128);
  17374. result += String.fromCharCode((c & 63) | 128);
  17375. }
  17376. }
  17377. return result;
  17378. };
  17379. var base64 = function (text) {
  17380. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  17381. text = utf8(text);
  17382. var result = '',
  17383. chr1, chr2, chr3,
  17384. enc1, enc2, enc3, enc4,
  17385. i = 0;
  17386. do {
  17387. chr1 = text.charCodeAt(i++);
  17388. chr2 = text.charCodeAt(i++);
  17389. chr3 = text.charCodeAt(i++);
  17390. enc1 = chr1 >> 2;
  17391. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  17392. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  17393. enc4 = chr3 & 63;
  17394. if(isNaN(chr2)) {
  17395. enc3 = enc4 = 64;
  17396. } else if(isNaN(chr3)) {
  17397. enc4 = 64;
  17398. }
  17399. result +=
  17400. keyStr.charAt(enc1) +
  17401. keyStr.charAt(enc2) +
  17402. keyStr.charAt(enc3) +
  17403. keyStr.charAt(enc4);
  17404. chr1 = chr2 = chr3 = '';
  17405. enc1 = enc2 = enc3 = enc4 = '';
  17406. } while(i < text.length);
  17407. return result;
  17408. };
  17409. var mergeHeaders = function () {
  17410. // Use the first header object as base.
  17411. var result = arguments[0];
  17412. // Iterate through the remaining header objects and add them.
  17413. for(var i = 1; i < arguments.length; i++) {
  17414. var currentHeaders = arguments[i];
  17415. for(var header in currentHeaders) {
  17416. if(currentHeaders.hasOwnProperty(header)) {
  17417. result[header] = currentHeaders[header];
  17418. }
  17419. }
  17420. }
  17421. // Return the merged headers.
  17422. return result;
  17423. };
  17424. var ajax = function (method, url, options, callback) {
  17425. // Adjust parameters.
  17426. if(typeof options === 'function') {
  17427. callback = options;
  17428. options = {};
  17429. }
  17430. // Set default parameter values.
  17431. options.cache = options.cache || false;
  17432. options.data = options.data || {};
  17433. options.headers = options.headers || {};
  17434. options.jsonp = options.jsonp || false;
  17435. options.async = options.async === undefined ? true : options.async;
  17436. // Merge the various header objects.
  17437. var headers = mergeHeaders({
  17438. 'accept': '*/*',
  17439. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  17440. }, ajax.headers, options.headers);
  17441. // Encode the data according to the content-type.
  17442. var payload;
  17443. if (headers['content-type'] === 'application/json') {
  17444. payload = JSON.stringify(options.data);
  17445. } else {
  17446. payload = encodeUsingUrlEncoding(options.data);
  17447. }
  17448. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  17449. // if neccessary.
  17450. if(method === 'GET') {
  17451. // Setup the query string.
  17452. var queryString = [];
  17453. if(payload) {
  17454. queryString.push(payload);
  17455. payload = null;
  17456. }
  17457. // Handle caching.
  17458. if(!options.cache) {
  17459. queryString.push('_=' + (new Date()).getTime());
  17460. }
  17461. // If neccessary prepare the query string for a JSONP call.
  17462. if(options.jsonp) {
  17463. queryString.push('callback=' + options.jsonp);
  17464. queryString.push('jsonp=' + options.jsonp);
  17465. }
  17466. // Merge the query string and attach it to the url.
  17467. queryString = queryString.join('&');
  17468. if (queryString.length > 1) {
  17469. if (url.indexOf('?') > -1) {
  17470. url += '&' + queryString;
  17471. } else {
  17472. url += '?' + queryString;
  17473. }
  17474. }
  17475. // Make a JSONP call if neccessary.
  17476. if(options.jsonp) {
  17477. var head = document.getElementsByTagName('head')[0];
  17478. var script = document.createElement('script');
  17479. script.type = 'text/javascript';
  17480. script.src = url;
  17481. head.appendChild(script);
  17482. return;
  17483. }
  17484. }
  17485. // Since we got here, it is no JSONP request, so make a normal XHR request.
  17486. getXhr(function (err, xhr) {
  17487. if(err) return callback(err);
  17488. // Open the request.
  17489. xhr.open(method, url, options.async);
  17490. // Set the request headers.
  17491. for(var header in headers) {
  17492. if(headers.hasOwnProperty(header)) {
  17493. xhr.setRequestHeader(header, headers[header]);
  17494. }
  17495. }
  17496. // Handle the request events.
  17497. xhr.onreadystatechange = function () {
  17498. if(xhr.readyState === 4) {
  17499. var data = xhr.responseText || '';
  17500. // If no callback is given, return.
  17501. if(!callback) {
  17502. return;
  17503. }
  17504. // Return an object that provides access to the data as text and JSON.
  17505. callback(xhr.status, {
  17506. text: function () {
  17507. return data;
  17508. },
  17509. json: function () {
  17510. try {
  17511. return JSON.parse(data)
  17512. } catch (e) {
  17513. f.error('Can not parse JSON. URL: ' + url);
  17514. return {};
  17515. }
  17516. }
  17517. });
  17518. }
  17519. };
  17520. // Actually send the XHR request.
  17521. xhr.send(payload);
  17522. });
  17523. };
  17524. // Define the external interface.
  17525. var http = {
  17526. authBasic: function (username, password) {
  17527. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  17528. },
  17529. connect: function (url, options, callback) {
  17530. return ajax('CONNECT', url, options, callback);
  17531. },
  17532. del: function (url, options, callback) {
  17533. return ajax('DELETE', url, options, callback);
  17534. },
  17535. get: function (url, options, callback) {
  17536. return ajax('GET', url, options, callback);
  17537. },
  17538. head: function (url, options, callback) {
  17539. return ajax('HEAD', url, options, callback);
  17540. },
  17541. headers: function (headers) {
  17542. ajax.headers = headers || {};
  17543. },
  17544. isAllowed: function (url, verb, callback) {
  17545. this.options(url, function (status, data) {
  17546. callback(data.text().indexOf(verb) !== -1);
  17547. });
  17548. },
  17549. options: function (url, options, callback) {
  17550. return ajax('OPTIONS', url, options, callback);
  17551. },
  17552. patch: function (url, options, callback) {
  17553. return ajax('PATCH', url, options, callback);
  17554. },
  17555. post: function (url, options, callback) {
  17556. return ajax('POST', url, options, callback);
  17557. },
  17558. put: function (url, options, callback) {
  17559. return ajax('PUT', url, options, callback);
  17560. },
  17561. trace: function (url, options, callback) {
  17562. return ajax('TRACE', url, options, callback);
  17563. }
  17564. };
  17565. var methode = options.type ? options.type.toLowerCase() : 'get';
  17566. http[methode](options.url, options, function (status, data) {
  17567. // file: protocol always gives status code 0, so check for data
  17568. if (status === 200 || (status === 0 && data.text())) {
  17569. options.success(data.json(), status, null);
  17570. } else {
  17571. options.error(data.text(), status, null);
  17572. }
  17573. });
  17574. }
  17575. var _cookie = {
  17576. create: function(name,value,minutes,domain) {
  17577. var expires;
  17578. if (minutes) {
  17579. var date = new Date();
  17580. date.setTime(date.getTime()+(minutes*60*1000));
  17581. expires = "; expires="+date.toGMTString();
  17582. }
  17583. else expires = "";
  17584. domain = (domain)? "domain="+domain+";" : "";
  17585. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  17586. },
  17587. read: function(name) {
  17588. var nameEQ = name + "=";
  17589. var ca = document.cookie.split(';');
  17590. for(var i=0;i < ca.length;i++) {
  17591. var c = ca[i];
  17592. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  17593. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  17594. }
  17595. return null;
  17596. },
  17597. remove: function(name) {
  17598. this.create(name,"",-1);
  17599. }
  17600. };
  17601. var cookie_noop = {
  17602. create: function(name,value,minutes,domain) {},
  17603. read: function(name) { return null; },
  17604. remove: function(name) {}
  17605. };
  17606. // move dependent functions to a container so that
  17607. // they can be overriden easier in no jquery environment (node.js)
  17608. var f = {
  17609. extend: $ ? $.extend : _extend,
  17610. deepExtend: _deepExtend,
  17611. each: $ ? $.each : _each,
  17612. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  17613. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  17614. detectLanguage: detectLanguage,
  17615. escape: _escape,
  17616. log: function(str) {
  17617. if (o.debug && typeof console !== "undefined") console.log(str);
  17618. },
  17619. error: function(str) {
  17620. if (typeof console !== "undefined") console.error(str);
  17621. },
  17622. getCountyIndexOfLng: function(lng) {
  17623. var lng_index = 0;
  17624. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  17625. return lng_index;
  17626. },
  17627. toLanguages: function(lng) {
  17628. var log = this.log;
  17629. function applyCase(l) {
  17630. var ret = l;
  17631. if (typeof l === 'string' && l.indexOf('-') > -1) {
  17632. var parts = l.split('-');
  17633. ret = o.lowerCaseLng ?
  17634. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  17635. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  17636. } else {
  17637. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  17638. }
  17639. return ret;
  17640. }
  17641. var languages = [];
  17642. var whitelist = o.lngWhitelist || false;
  17643. var addLanguage = function(language){
  17644. //reject langs not whitelisted
  17645. if(!whitelist || whitelist.indexOf(language) > -1){
  17646. languages.push(language);
  17647. }else{
  17648. log('rejecting non-whitelisted language: ' + language);
  17649. }
  17650. };
  17651. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  17652. var parts = lng.split('-');
  17653. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  17654. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  17655. } else {
  17656. addLanguage(applyCase(lng));
  17657. }
  17658. for (var i = 0; i < o.fallbackLng.length; i++) {
  17659. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  17660. }
  17661. return languages;
  17662. },
  17663. regexEscape: function(str) {
  17664. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  17665. },
  17666. regexReplacementEscape: function(strOrFn) {
  17667. if (typeof strOrFn === 'string') {
  17668. return strOrFn.replace(/\$/g, "$$$$");
  17669. } else {
  17670. return strOrFn;
  17671. }
  17672. },
  17673. localStorage: {
  17674. setItem: function(key, value) {
  17675. if (window.localStorage) {
  17676. try {
  17677. window.localStorage.setItem(key, value);
  17678. } catch (e) {
  17679. f.log('failed to set value for key "' + key + '" to localStorage.');
  17680. }
  17681. }
  17682. }
  17683. }
  17684. };
  17685. function init(options, cb) {
  17686. if (typeof options === 'function') {
  17687. cb = options;
  17688. options = {};
  17689. }
  17690. options = options || {};
  17691. // override defaults with passed in options
  17692. f.extend(o, options);
  17693. delete o.fixLng; /* passed in each time */
  17694. // override functions: .log(), .detectLanguage(), etc
  17695. if (o.functions) {
  17696. delete o.functions;
  17697. f.extend(f, options.functions);
  17698. }
  17699. // create namespace object if namespace is passed in as string
  17700. if (typeof o.ns == 'string') {
  17701. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  17702. }
  17703. // fallback namespaces
  17704. if (typeof o.fallbackNS == 'string') {
  17705. o.fallbackNS = [o.fallbackNS];
  17706. }
  17707. // fallback languages
  17708. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  17709. o.fallbackLng = [o.fallbackLng];
  17710. }
  17711. // escape prefix/suffix
  17712. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  17713. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  17714. if (!o.lng) o.lng = f.detectLanguage();
  17715. languages = f.toLanguages(o.lng);
  17716. currentLng = languages[0];
  17717. f.log('currentLng set to: ' + currentLng);
  17718. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  17719. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  17720. }
  17721. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  17722. f.localStorage.setItem('i18next_lng', currentLng);
  17723. }
  17724. var lngTranslate = translate;
  17725. if (options.fixLng) {
  17726. lngTranslate = function(key, options) {
  17727. options = options || {};
  17728. options.lng = options.lng || lngTranslate.lng;
  17729. return translate(key, options);
  17730. };
  17731. lngTranslate.lng = currentLng;
  17732. }
  17733. pluralExtensions.setCurrentLng(currentLng);
  17734. // add JQuery extensions
  17735. if ($ && o.setJqueryExt) addJqueryFunct();
  17736. // jQuery deferred
  17737. var deferred;
  17738. if ($ && $.Deferred) {
  17739. deferred = $.Deferred();
  17740. }
  17741. // return immidiatly if res are passed in
  17742. if (o.resStore) {
  17743. resStore = o.resStore;
  17744. initialized = true;
  17745. if (cb) cb(lngTranslate);
  17746. if (deferred) deferred.resolve(lngTranslate);
  17747. if (deferred) return deferred.promise();
  17748. return;
  17749. }
  17750. // languages to load
  17751. var lngsToLoad = f.toLanguages(o.lng);
  17752. if (typeof o.preload === 'string') o.preload = [o.preload];
  17753. for (var i = 0, l = o.preload.length; i < l; i++) {
  17754. var pres = f.toLanguages(o.preload[i]);
  17755. for (var y = 0, len = pres.length; y < len; y++) {
  17756. if (lngsToLoad.indexOf(pres[y]) < 0) {
  17757. lngsToLoad.push(pres[y]);
  17758. }
  17759. }
  17760. }
  17761. // else load them
  17762. i18n.sync.load(lngsToLoad, o, function(err, store) {
  17763. resStore = store;
  17764. initialized = true;
  17765. if (cb) cb(lngTranslate);
  17766. if (deferred) deferred.resolve(lngTranslate);
  17767. });
  17768. if (deferred) return deferred.promise();
  17769. }
  17770. function preload(lngs, cb) {
  17771. if (typeof lngs === 'string') lngs = [lngs];
  17772. for (var i = 0, l = lngs.length; i < l; i++) {
  17773. if (o.preload.indexOf(lngs[i]) < 0) {
  17774. o.preload.push(lngs[i]);
  17775. }
  17776. }
  17777. return init(cb);
  17778. }
  17779. function addResourceBundle(lng, ns, resources, deep) {
  17780. if (typeof ns !== 'string') {
  17781. resources = ns;
  17782. ns = o.ns.defaultNs;
  17783. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  17784. o.ns.namespaces.push(ns);
  17785. }
  17786. resStore[lng] = resStore[lng] || {};
  17787. resStore[lng][ns] = resStore[lng][ns] || {};
  17788. if (deep) {
  17789. f.deepExtend(resStore[lng][ns], resources);
  17790. } else {
  17791. f.extend(resStore[lng][ns], resources);
  17792. }
  17793. }
  17794. function hasResourceBundle(lng, ns) {
  17795. if (typeof ns !== 'string') {
  17796. ns = o.ns.defaultNs;
  17797. }
  17798. resStore[lng] = resStore[lng] || {};
  17799. var res = resStore[lng][ns] || {};
  17800. var hasValues = false;
  17801. for(var prop in res) {
  17802. if (res.hasOwnProperty(prop)) {
  17803. hasValues = true;
  17804. }
  17805. }
  17806. return hasValues;
  17807. }
  17808. function removeResourceBundle(lng, ns) {
  17809. if (typeof ns !== 'string') {
  17810. ns = o.ns.defaultNs;
  17811. }
  17812. resStore[lng] = resStore[lng] || {};
  17813. resStore[lng][ns] = {};
  17814. }
  17815. function addResource(lng, ns, key, value) {
  17816. if (typeof ns !== 'string') {
  17817. resource = ns;
  17818. ns = o.ns.defaultNs;
  17819. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  17820. o.ns.namespaces.push(ns);
  17821. }
  17822. resStore[lng] = resStore[lng] || {};
  17823. resStore[lng][ns] = resStore[lng][ns] || {};
  17824. var keys = key.split(o.keyseparator);
  17825. var x = 0;
  17826. var node = resStore[lng][ns];
  17827. var origRef = node;
  17828. while (keys[x]) {
  17829. if (x == keys.length - 1)
  17830. node[keys[x]] = value;
  17831. else {
  17832. if (node[keys[x]] == null)
  17833. node[keys[x]] = {};
  17834. node = node[keys[x]];
  17835. }
  17836. x++;
  17837. }
  17838. }
  17839. function addResources(lng, ns, resources) {
  17840. if (typeof ns !== 'string') {
  17841. resource = ns;
  17842. ns = o.ns.defaultNs;
  17843. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  17844. o.ns.namespaces.push(ns);
  17845. }
  17846. for (var m in resources) {
  17847. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  17848. }
  17849. }
  17850. function setDefaultNamespace(ns) {
  17851. o.ns.defaultNs = ns;
  17852. }
  17853. function loadNamespace(namespace, cb) {
  17854. loadNamespaces([namespace], cb);
  17855. }
  17856. function loadNamespaces(namespaces, cb) {
  17857. var opts = {
  17858. dynamicLoad: o.dynamicLoad,
  17859. resGetPath: o.resGetPath,
  17860. getAsync: o.getAsync,
  17861. customLoad: o.customLoad,
  17862. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  17863. };
  17864. // languages to load
  17865. var lngsToLoad = f.toLanguages(o.lng);
  17866. if (typeof o.preload === 'string') o.preload = [o.preload];
  17867. for (var i = 0, l = o.preload.length; i < l; i++) {
  17868. var pres = f.toLanguages(o.preload[i]);
  17869. for (var y = 0, len = pres.length; y < len; y++) {
  17870. if (lngsToLoad.indexOf(pres[y]) < 0) {
  17871. lngsToLoad.push(pres[y]);
  17872. }
  17873. }
  17874. }
  17875. // check if we have to load
  17876. var lngNeedLoad = [];
  17877. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  17878. var needLoad = false;
  17879. var resSet = resStore[lngsToLoad[a]];
  17880. if (resSet) {
  17881. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  17882. if (!resSet[namespaces[b]]) needLoad = true;
  17883. }
  17884. } else {
  17885. needLoad = true;
  17886. }
  17887. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  17888. }
  17889. if (lngNeedLoad.length) {
  17890. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  17891. var todo = namespaces.length * lngNeedLoad.length;
  17892. // load each file individual
  17893. f.each(namespaces, function(nsIndex, nsValue) {
  17894. // append namespace to namespace array
  17895. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  17896. o.ns.namespaces.push(nsValue);
  17897. }
  17898. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  17899. resStore[lngValue] = resStore[lngValue] || {};
  17900. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  17901. todo--; // wait for all done befor callback
  17902. if (todo === 0 && cb) {
  17903. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  17904. cb();
  17905. }
  17906. });
  17907. });
  17908. });
  17909. } else {
  17910. if (cb) cb();
  17911. }
  17912. }
  17913. function setLng(lng, options, cb) {
  17914. if (typeof options === 'function') {
  17915. cb = options;
  17916. options = {};
  17917. } else if (!options) {
  17918. options = {};
  17919. }
  17920. options.lng = lng;
  17921. return init(options, cb);
  17922. }
  17923. function lng() {
  17924. return currentLng;
  17925. }
  17926. function reload(cb) {
  17927. resStore = {};
  17928. setLng(currentLng, cb);
  17929. }
  17930. function addJqueryFunct() {
  17931. // $.t shortcut
  17932. $.t = $.t || translate;
  17933. function parse(ele, key, options) {
  17934. if (key.length === 0) return;
  17935. var attr = 'text';
  17936. if (key.indexOf('[') === 0) {
  17937. var parts = key.split(']');
  17938. key = parts[1];
  17939. attr = parts[0].substr(1, parts[0].length-1);
  17940. }
  17941. if (key.indexOf(';') === key.length-1) {
  17942. key = key.substr(0, key.length-2);
  17943. }
  17944. var optionsToUse;
  17945. if (attr === 'html') {
  17946. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  17947. ele.html($.t(key, optionsToUse));
  17948. } else if (attr === 'text') {
  17949. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  17950. ele.text($.t(key, optionsToUse));
  17951. } else if (attr === 'prepend') {
  17952. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  17953. ele.prepend($.t(key, optionsToUse));
  17954. } else if (attr === 'append') {
  17955. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  17956. ele.append($.t(key, optionsToUse));
  17957. } else if (attr.indexOf("data-") === 0) {
  17958. var dataAttr = attr.substr(("data-").length);
  17959. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  17960. var translated = $.t(key, optionsToUse);
  17961. //we change into the data cache
  17962. ele.data(dataAttr, translated);
  17963. //we change into the dom
  17964. ele.attr(attr, translated);
  17965. } else {
  17966. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  17967. ele.attr(attr, $.t(key, optionsToUse));
  17968. }
  17969. }
  17970. function localize(ele, options) {
  17971. var key = ele.attr(o.selectorAttr);
  17972. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  17973. if (!key) return;
  17974. var target = ele
  17975. , targetSelector = ele.data("i18n-target");
  17976. if (targetSelector) {
  17977. target = ele.find(targetSelector) || ele;
  17978. }
  17979. if (!options && o.useDataAttrOptions === true) {
  17980. options = ele.data("i18n-options");
  17981. }
  17982. options = options || {};
  17983. if (key.indexOf(';') >= 0) {
  17984. var keys = key.split(';');
  17985. $.each(keys, function(m, k) {
  17986. if (k !== '') parse(target, k, options);
  17987. });
  17988. } else {
  17989. parse(target, key, options);
  17990. }
  17991. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  17992. }
  17993. // fn
  17994. $.fn.i18n = function (options) {
  17995. return this.each(function() {
  17996. // localize element itself
  17997. localize($(this), options);
  17998. // localize childs
  17999. var elements = $(this).find('[' + o.selectorAttr + ']');
  18000. elements.each(function() {
  18001. localize($(this), options);
  18002. });
  18003. });
  18004. };
  18005. }
  18006. function applyReplacement(str, replacementHash, nestedKey, options) {
  18007. if (!str) return str;
  18008. options = options || replacementHash; // first call uses replacement hash combined with options
  18009. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  18010. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  18011. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  18012. , unEscapingSuffix = 'HTML'+suffix;
  18013. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  18014. f.each(hash, function(key, value) {
  18015. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  18016. if (typeof value === 'object' && value !== null) {
  18017. str = applyReplacement(str, value, nextKey, options);
  18018. } else {
  18019. if (options.escapeInterpolation || o.escapeInterpolation) {
  18020. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  18021. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  18022. } else {
  18023. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  18024. }
  18025. // str = options.escapeInterpolation;
  18026. }
  18027. });
  18028. return str;
  18029. }
  18030. // append it to functions
  18031. f.applyReplacement = applyReplacement;
  18032. function applyReuse(translated, options) {
  18033. var comma = ',';
  18034. var options_open = '{';
  18035. var options_close = '}';
  18036. var opts = f.extend({}, options);
  18037. delete opts.postProcess;
  18038. while (translated.indexOf(o.reusePrefix) != -1) {
  18039. replacementCounter++;
  18040. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  18041. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  18042. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  18043. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  18044. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  18045. if (index_of_end_of_closing <= index_of_opening) {
  18046. f.error('there is an missing closing in following translation value', translated);
  18047. return '';
  18048. }
  18049. if (token_without_symbols.indexOf(comma) != -1) {
  18050. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  18051. 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) {
  18052. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  18053. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  18054. try {
  18055. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  18056. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  18057. } catch (e) {
  18058. }
  18059. }
  18060. }
  18061. var translated_token = _translate(token_without_symbols, opts);
  18062. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  18063. }
  18064. return translated;
  18065. }
  18066. function hasContext(options) {
  18067. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  18068. }
  18069. function needsPlural(options, lng) {
  18070. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  18071. }
  18072. function needsIndefiniteArticle(options) {
  18073. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  18074. }
  18075. function exists(key, options) {
  18076. options = options || {};
  18077. var notFound = _getDefaultValue(key, options)
  18078. , found = _find(key, options);
  18079. return found !== undefined || found === notFound;
  18080. }
  18081. function translate(key, options) {
  18082. options = options || {};
  18083. if (!initialized) {
  18084. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  18085. return options.defaultValue || '';
  18086. };
  18087. replacementCounter = 0;
  18088. return _translate.apply(null, arguments);
  18089. }
  18090. function _getDefaultValue(key, options) {
  18091. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  18092. }
  18093. function _injectSprintfProcessor() {
  18094. var values = [];
  18095. // mh: build array from second argument onwards
  18096. for (var i = 1; i < arguments.length; i++) {
  18097. values.push(arguments[i]);
  18098. }
  18099. return {
  18100. postProcess: 'sprintf',
  18101. sprintf: values
  18102. };
  18103. }
  18104. function _translate(potentialKeys, options) {
  18105. if (options && typeof options !== 'object') {
  18106. if (o.shortcutFunction === 'sprintf') {
  18107. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  18108. options = _injectSprintfProcessor.apply(null, arguments);
  18109. } else if (o.shortcutFunction === 'defaultValue') {
  18110. options = {
  18111. defaultValue: options
  18112. }
  18113. }
  18114. } else {
  18115. options = options || {};
  18116. }
  18117. if (typeof o.defaultVariables === 'object') {
  18118. options = f.extend({}, o.defaultVariables, options);
  18119. }
  18120. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  18121. if (typeof potentialKeys === 'string') {
  18122. potentialKeys = [potentialKeys];
  18123. }
  18124. var key = potentialKeys[0];
  18125. if (potentialKeys.length > 1) {
  18126. for (var i = 0; i < potentialKeys.length; i++) {
  18127. key = potentialKeys[i];
  18128. if (exists(key, options)) {
  18129. break;
  18130. }
  18131. }
  18132. }
  18133. var notFound = _getDefaultValue(key, options)
  18134. , found = _find(key, options)
  18135. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  18136. , ns = options.ns || o.ns.defaultNs
  18137. , parts;
  18138. // split ns and key
  18139. if (key.indexOf(o.nsseparator) > -1) {
  18140. parts = key.split(o.nsseparator);
  18141. ns = parts[0];
  18142. key = parts[1];
  18143. }
  18144. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  18145. if (options.lng) {
  18146. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  18147. } else {
  18148. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  18149. }
  18150. }
  18151. var postProcessor = options.postProcess || o.postProcess;
  18152. if (found !== undefined && postProcessor) {
  18153. if (postProcessors[postProcessor]) {
  18154. found = postProcessors[postProcessor](found, key, options);
  18155. }
  18156. }
  18157. // process notFound if function exists
  18158. var splitNotFound = notFound;
  18159. if (notFound.indexOf(o.nsseparator) > -1) {
  18160. parts = notFound.split(o.nsseparator);
  18161. splitNotFound = parts[1];
  18162. }
  18163. if (splitNotFound === key && o.parseMissingKey) {
  18164. notFound = o.parseMissingKey(notFound);
  18165. }
  18166. if (found === undefined) {
  18167. notFound = applyReplacement(notFound, options);
  18168. notFound = applyReuse(notFound, options);
  18169. if (postProcessor && postProcessors[postProcessor]) {
  18170. var val = _getDefaultValue(key, options);
  18171. found = postProcessors[postProcessor](val, key, options);
  18172. }
  18173. }
  18174. return (found !== undefined) ? found : notFound;
  18175. }
  18176. function _find(key, options) {
  18177. options = options || {};
  18178. var optionWithoutCount, translated
  18179. , notFound = _getDefaultValue(key, options)
  18180. , lngs = languages;
  18181. if (!resStore) { return notFound; } // no resStore to translate from
  18182. // CI mode
  18183. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  18184. // passed in lng
  18185. if (options.lngs) lngs = options.lngs;
  18186. if (options.lng) {
  18187. lngs = f.toLanguages(options.lng, options.fallbackLng);
  18188. if (!resStore[lngs[0]]) {
  18189. var oldAsync = o.getAsync;
  18190. o.getAsync = false;
  18191. i18n.sync.load(lngs, o, function(err, store) {
  18192. f.extend(resStore, store);
  18193. o.getAsync = oldAsync;
  18194. });
  18195. }
  18196. }
  18197. var ns = options.ns || o.ns.defaultNs;
  18198. if (key.indexOf(o.nsseparator) > -1) {
  18199. var parts = key.split(o.nsseparator);
  18200. ns = parts[0];
  18201. key = parts[1];
  18202. }
  18203. if (hasContext(options)) {
  18204. optionWithoutCount = f.extend({}, options);
  18205. delete optionWithoutCount.context;
  18206. optionWithoutCount.defaultValue = o.contextNotFound;
  18207. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  18208. translated = translate(contextKey, optionWithoutCount);
  18209. if (translated != o.contextNotFound) {
  18210. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  18211. } // else continue translation with original/nonContext key
  18212. }
  18213. if (needsPlural(options, lngs[0])) {
  18214. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  18215. delete optionWithoutCount.count;
  18216. delete optionWithoutCount.lng;
  18217. optionWithoutCount.defaultValue = o.pluralNotFound;
  18218. var pluralKey;
  18219. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  18220. pluralKey = ns + o.nsseparator + key;
  18221. } else {
  18222. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  18223. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  18224. if (pluralExtension >= 0) {
  18225. pluralKey = pluralKey + '_' + pluralExtension;
  18226. } else if (pluralExtension === 1) {
  18227. pluralKey = ns + o.nsseparator + key; // singular
  18228. }
  18229. }
  18230. translated = translate(pluralKey, optionWithoutCount);
  18231. if (translated != o.pluralNotFound) {
  18232. return applyReplacement(translated, {
  18233. count: options.count,
  18234. interpolationPrefix: options.interpolationPrefix,
  18235. interpolationSuffix: options.interpolationSuffix
  18236. }); // apply replacement for count only
  18237. } else if (lngs.length > 1) {
  18238. // remove failed lng
  18239. var clone = lngs.slice();
  18240. clone.shift();
  18241. options = f.extend(options, { lngs: clone });
  18242. delete options.lng;
  18243. // retry with fallbacks
  18244. translated = translate(ns + o.nsseparator + key, options);
  18245. if (translated != o.pluralNotFound) return translated;
  18246. } else {
  18247. return translated;
  18248. }
  18249. }
  18250. if (needsIndefiniteArticle(options)) {
  18251. var optionsWithoutIndef = f.extend({}, options);
  18252. delete optionsWithoutIndef.indefinite_article;
  18253. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  18254. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  18255. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  18256. translated = translate(indefiniteKey, optionsWithoutIndef);
  18257. if (translated != o.indefiniteNotFound) {
  18258. return translated;
  18259. }
  18260. }
  18261. var found;
  18262. var keys = key.split(o.keyseparator);
  18263. for (var i = 0, len = lngs.length; i < len; i++ ) {
  18264. if (found !== undefined) break;
  18265. var l = lngs[i];
  18266. var x = 0;
  18267. var value = resStore[l] && resStore[l][ns];
  18268. while (keys[x]) {
  18269. value = value && value[keys[x]];
  18270. x++;
  18271. }
  18272. if (value !== undefined) {
  18273. var valueType = Object.prototype.toString.apply(value);
  18274. if (typeof value === 'string') {
  18275. value = applyReplacement(value, options);
  18276. value = applyReuse(value, options);
  18277. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  18278. value = value.join('\n');
  18279. value = applyReplacement(value, options);
  18280. value = applyReuse(value, options);
  18281. } else if (value === null && o.fallbackOnNull === true) {
  18282. value = undefined;
  18283. } else if (value !== null) {
  18284. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  18285. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  18286. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  18287. } else {
  18288. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  18289. 'returned an object instead of string.';
  18290. f.log(value);
  18291. }
  18292. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  18293. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  18294. f.each(value, function(m) {
  18295. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  18296. });
  18297. value = copy;
  18298. }
  18299. }
  18300. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  18301. value = undefined;
  18302. found = value;
  18303. }
  18304. }
  18305. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  18306. // set flag for fallback lookup - avoid recursion
  18307. options.isFallbackLookup = true;
  18308. if (o.fallbackNS.length) {
  18309. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  18310. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  18311. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  18312. /* compare value without namespace */
  18313. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  18314. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  18315. if (foundValue !== notFoundValue) break;
  18316. }
  18317. }
  18318. } else {
  18319. found = _find(key, options); // fallback to default NS
  18320. }
  18321. options.isFallbackLookup = false;
  18322. }
  18323. return found;
  18324. }
  18325. function detectLanguage() {
  18326. var detectedLng;
  18327. var whitelist = o.lngWhitelist || [];
  18328. var userLngChoices = [];
  18329. // get from qs
  18330. var qsParm = [];
  18331. if (typeof window !== 'undefined') {
  18332. (function() {
  18333. var query = window.location.search.substring(1);
  18334. var params = query.split('&');
  18335. for (var i=0; i<params.length; i++) {
  18336. var pos = params[i].indexOf('=');
  18337. if (pos > 0) {
  18338. var key = params[i].substring(0,pos);
  18339. if (key == o.detectLngQS) {
  18340. userLngChoices.push(params[i].substring(pos+1));
  18341. }
  18342. }
  18343. }
  18344. })();
  18345. }
  18346. // get from cookie
  18347. if (o.useCookie && typeof document !== 'undefined') {
  18348. var c = f.cookie.read(o.cookieName);
  18349. if (c) userLngChoices.push(c);
  18350. }
  18351. // get from localStorage
  18352. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  18353. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  18354. }
  18355. // get from navigator
  18356. if (typeof navigator !== 'undefined') {
  18357. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  18358. for (var i=0;i<navigator.languages.length;i++) {
  18359. userLngChoices.push(navigator.languages[i]);
  18360. }
  18361. }
  18362. if (navigator.userLanguage) {
  18363. userLngChoices.push(navigator.userLanguage);
  18364. }
  18365. if (navigator.language) {
  18366. userLngChoices.push(navigator.language);
  18367. }
  18368. }
  18369. (function() {
  18370. for (var i=0;i<userLngChoices.length;i++) {
  18371. var lng = userLngChoices[i];
  18372. if (lng.indexOf('-') > -1) {
  18373. var parts = lng.split('-');
  18374. lng = o.lowerCaseLng ?
  18375. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18376. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18377. }
  18378. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  18379. detectedLng = lng;
  18380. break;
  18381. }
  18382. }
  18383. })();
  18384. //fallback
  18385. if (!detectedLng){
  18386. detectedLng = o.fallbackLng[0];
  18387. }
  18388. return detectedLng;
  18389. }
  18390. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  18391. /* [code, name, numbers, pluralsType] */
  18392. var _rules = [
  18393. ["ach", "Acholi", [1,2], 1],
  18394. ["af", "Afrikaans",[1,2], 2],
  18395. ["ak", "Akan", [1,2], 1],
  18396. ["am", "Amharic", [1,2], 1],
  18397. ["an", "Aragonese",[1,2], 2],
  18398. ["ar", "Arabic", [0,1,2,3,11,100],5],
  18399. ["arn", "Mapudungun",[1,2], 1],
  18400. ["ast", "Asturian", [1,2], 2],
  18401. ["ay", "Aymará", [1], 3],
  18402. ["az", "Azerbaijani",[1,2],2],
  18403. ["be", "Belarusian",[1,2,5],4],
  18404. ["bg", "Bulgarian",[1,2], 2],
  18405. ["bn", "Bengali", [1,2], 2],
  18406. ["bo", "Tibetan", [1], 3],
  18407. ["br", "Breton", [1,2], 1],
  18408. ["bs", "Bosnian", [1,2,5],4],
  18409. ["ca", "Catalan", [1,2], 2],
  18410. ["cgg", "Chiga", [1], 3],
  18411. ["cs", "Czech", [1,2,5],6],
  18412. ["csb", "Kashubian",[1,2,5],7],
  18413. ["cy", "Welsh", [1,2,3,8],8],
  18414. ["da", "Danish", [1,2], 2],
  18415. ["de", "German", [1,2], 2],
  18416. ["dev", "Development Fallback", [1,2], 2],
  18417. ["dz", "Dzongkha", [1], 3],
  18418. ["el", "Greek", [1,2], 2],
  18419. ["en", "English", [1,2], 2],
  18420. ["eo", "Esperanto",[1,2], 2],
  18421. ["es", "Spanish", [1,2], 2],
  18422. ["es_ar","Argentinean Spanish", [1,2], 2],
  18423. ["et", "Estonian", [1,2], 2],
  18424. ["eu", "Basque", [1,2], 2],
  18425. ["fa", "Persian", [1], 3],
  18426. ["fi", "Finnish", [1,2], 2],
  18427. ["fil", "Filipino", [1,2], 1],
  18428. ["fo", "Faroese", [1,2], 2],
  18429. ["fr", "French", [1,2], 9],
  18430. ["fur", "Friulian", [1,2], 2],
  18431. ["fy", "Frisian", [1,2], 2],
  18432. ["ga", "Irish", [1,2,3,7,11],10],
  18433. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  18434. ["gl", "Galician", [1,2], 2],
  18435. ["gu", "Gujarati", [1,2], 2],
  18436. ["gun", "Gun", [1,2], 1],
  18437. ["ha", "Hausa", [1,2], 2],
  18438. ["he", "Hebrew", [1,2], 2],
  18439. ["hi", "Hindi", [1,2], 2],
  18440. ["hr", "Croatian", [1,2,5],4],
  18441. ["hu", "Hungarian",[1,2], 2],
  18442. ["hy", "Armenian", [1,2], 2],
  18443. ["ia", "Interlingua",[1,2],2],
  18444. ["id", "Indonesian",[1], 3],
  18445. ["is", "Icelandic",[1,2], 12],
  18446. ["it", "Italian", [1,2], 2],
  18447. ["ja", "Japanese", [1], 3],
  18448. ["jbo", "Lojban", [1], 3],
  18449. ["jv", "Javanese", [0,1], 13],
  18450. ["ka", "Georgian", [1], 3],
  18451. ["kk", "Kazakh", [1], 3],
  18452. ["km", "Khmer", [1], 3],
  18453. ["kn", "Kannada", [1,2], 2],
  18454. ["ko", "Korean", [1], 3],
  18455. ["ku", "Kurdish", [1,2], 2],
  18456. ["kw", "Cornish", [1,2,3,4],14],
  18457. ["ky", "Kyrgyz", [1], 3],
  18458. ["lb", "Letzeburgesch",[1,2],2],
  18459. ["ln", "Lingala", [1,2], 1],
  18460. ["lo", "Lao", [1], 3],
  18461. ["lt", "Lithuanian",[1,2,10],15],
  18462. ["lv", "Latvian", [1,2,0],16],
  18463. ["mai", "Maithili", [1,2], 2],
  18464. ["mfe", "Mauritian Creole",[1,2],1],
  18465. ["mg", "Malagasy", [1,2], 1],
  18466. ["mi", "Maori", [1,2], 1],
  18467. ["mk", "Macedonian",[1,2],17],
  18468. ["ml", "Malayalam",[1,2], 2],
  18469. ["mn", "Mongolian",[1,2], 2],
  18470. ["mnk", "Mandinka", [0,1,2],18],
  18471. ["mr", "Marathi", [1,2], 2],
  18472. ["ms", "Malay", [1], 3],
  18473. ["mt", "Maltese", [1,2,11,20],19],
  18474. ["nah", "Nahuatl", [1,2], 2],
  18475. ["nap", "Neapolitan",[1,2], 2],
  18476. ["nb", "Norwegian Bokmal",[1,2],2],
  18477. ["ne", "Nepali", [1,2], 2],
  18478. ["nl", "Dutch", [1,2], 2],
  18479. ["nn", "Norwegian Nynorsk",[1,2],2],
  18480. ["no", "Norwegian",[1,2], 2],
  18481. ["nso", "Northern Sotho",[1,2],2],
  18482. ["oc", "Occitan", [1,2], 1],
  18483. ["or", "Oriya", [2,1], 2],
  18484. ["pa", "Punjabi", [1,2], 2],
  18485. ["pap", "Papiamento",[1,2], 2],
  18486. ["pl", "Polish", [1,2,5],7],
  18487. ["pms", "Piemontese",[1,2], 2],
  18488. ["ps", "Pashto", [1,2], 2],
  18489. ["pt", "Portuguese",[1,2], 2],
  18490. ["pt_br","Brazilian Portuguese",[1,2], 2],
  18491. ["rm", "Romansh", [1,2], 2],
  18492. ["ro", "Romanian", [1,2,20],20],
  18493. ["ru", "Russian", [1,2,5],4],
  18494. ["sah", "Yakut", [1], 3],
  18495. ["sco", "Scots", [1,2], 2],
  18496. ["se", "Northern Sami",[1,2], 2],
  18497. ["si", "Sinhala", [1,2], 2],
  18498. ["sk", "Slovak", [1,2,5],6],
  18499. ["sl", "Slovenian",[5,1,2,3],21],
  18500. ["so", "Somali", [1,2], 2],
  18501. ["son", "Songhay", [1,2], 2],
  18502. ["sq", "Albanian", [1,2], 2],
  18503. ["sr", "Serbian", [1,2,5],4],
  18504. ["su", "Sundanese",[1], 3],
  18505. ["sv", "Swedish", [1,2], 2],
  18506. ["sw", "Swahili", [1,2], 2],
  18507. ["ta", "Tamil", [1,2], 2],
  18508. ["te", "Telugu", [1,2], 2],
  18509. ["tg", "Tajik", [1,2], 1],
  18510. ["th", "Thai", [1], 3],
  18511. ["ti", "Tigrinya", [1,2], 1],
  18512. ["tk", "Turkmen", [1,2], 2],
  18513. ["tr", "Turkish", [1,2], 1],
  18514. ["tt", "Tatar", [1], 3],
  18515. ["ug", "Uyghur", [1], 3],
  18516. ["uk", "Ukrainian",[1,2,5],4],
  18517. ["ur", "Urdu", [1,2], 2],
  18518. ["uz", "Uzbek", [1,2], 1],
  18519. ["vi", "Vietnamese",[1], 3],
  18520. ["wa", "Walloon", [1,2], 1],
  18521. ["wo", "Wolof", [1], 3],
  18522. ["yo", "Yoruba", [1,2], 2],
  18523. ["zh", "Chinese", [1], 3]
  18524. ];
  18525. var _rulesPluralsTypes = {
  18526. 1: function(n) {return Number(n > 1);},
  18527. 2: function(n) {return Number(n != 1);},
  18528. 3: function(n) {return 0;},
  18529. 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);},
  18530. 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);},
  18531. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  18532. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  18533. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  18534. 9: function(n) {return Number(n >= 2);},
  18535. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  18536. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  18537. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  18538. 13: function(n) {return Number(n !== 0);},
  18539. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  18540. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  18541. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  18542. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  18543. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  18544. 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);},
  18545. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  18546. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  18547. };
  18548. var pluralExtensions = {
  18549. rules: (function () {
  18550. var l, rules = {};
  18551. for (l=_rules.length; l-- ;) {
  18552. rules[_rules[l][0]] = {
  18553. name: _rules[l][1],
  18554. numbers: _rules[l][2],
  18555. plurals: _rulesPluralsTypes[_rules[l][3]]
  18556. }
  18557. }
  18558. return rules;
  18559. }()),
  18560. // you can add your own pluralExtensions
  18561. addRule: function(lng, obj) {
  18562. pluralExtensions.rules[lng] = obj;
  18563. },
  18564. setCurrentLng: function(lng) {
  18565. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  18566. var parts = lng.split('-');
  18567. pluralExtensions.currentRule = {
  18568. lng: lng,
  18569. rule: pluralExtensions.rules[parts[0]]
  18570. };
  18571. }
  18572. },
  18573. needsPlural: function(lng, count) {
  18574. var parts = lng.split('-');
  18575. var ext;
  18576. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  18577. ext = pluralExtensions.currentRule.rule;
  18578. } else {
  18579. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  18580. }
  18581. if (ext && ext.numbers.length <= 1) {
  18582. return false;
  18583. } else {
  18584. return this.get(lng, count) !== 1;
  18585. }
  18586. },
  18587. get: function(lng, count) {
  18588. var parts = lng.split('-');
  18589. function getResult(l, c) {
  18590. var ext;
  18591. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  18592. ext = pluralExtensions.currentRule.rule;
  18593. } else {
  18594. ext = pluralExtensions.rules[l];
  18595. }
  18596. if (ext) {
  18597. var i;
  18598. if (ext.noAbs) {
  18599. i = ext.plurals(c);
  18600. } else {
  18601. i = ext.plurals(Math.abs(c));
  18602. }
  18603. var number = ext.numbers[i];
  18604. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  18605. if (number === 2) {
  18606. number = -1; // regular plural
  18607. } else if (number === 1) {
  18608. number = 1; // singular
  18609. }
  18610. }//console.log(count + '-' + number);
  18611. return number;
  18612. } else {
  18613. return c === 1 ? '1' : '-1';
  18614. }
  18615. }
  18616. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  18617. }
  18618. };
  18619. var postProcessors = {};
  18620. var addPostProcessor = function(name, fc) {
  18621. postProcessors[name] = fc;
  18622. };
  18623. // sprintf support
  18624. var sprintf = (function() {
  18625. function get_type(variable) {
  18626. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  18627. }
  18628. function str_repeat(input, multiplier) {
  18629. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  18630. return output.join('');
  18631. }
  18632. var str_format = function() {
  18633. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  18634. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  18635. }
  18636. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  18637. };
  18638. str_format.format = function(parse_tree, argv) {
  18639. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  18640. for (i = 0; i < tree_length; i++) {
  18641. node_type = get_type(parse_tree[i]);
  18642. if (node_type === 'string') {
  18643. output.push(parse_tree[i]);
  18644. }
  18645. else if (node_type === 'array') {
  18646. match = parse_tree[i]; // convenience purposes only
  18647. if (match[2]) { // keyword argument
  18648. arg = argv[cursor];
  18649. for (k = 0; k < match[2].length; k++) {
  18650. if (!arg.hasOwnProperty(match[2][k])) {
  18651. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  18652. }
  18653. arg = arg[match[2][k]];
  18654. }
  18655. }
  18656. else if (match[1]) { // positional argument (explicit)
  18657. arg = argv[match[1]];
  18658. }
  18659. else { // positional argument (implicit)
  18660. arg = argv[cursor++];
  18661. }
  18662. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  18663. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  18664. }
  18665. switch (match[8]) {
  18666. case 'b': arg = arg.toString(2); break;
  18667. case 'c': arg = String.fromCharCode(arg); break;
  18668. case 'd': arg = parseInt(arg, 10); break;
  18669. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  18670. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  18671. case 'o': arg = arg.toString(8); break;
  18672. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  18673. case 'u': arg = Math.abs(arg); break;
  18674. case 'x': arg = arg.toString(16); break;
  18675. case 'X': arg = arg.toString(16).toUpperCase(); break;
  18676. }
  18677. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  18678. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  18679. pad_length = match[6] - String(arg).length;
  18680. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  18681. output.push(match[5] ? arg + pad : pad + arg);
  18682. }
  18683. }
  18684. return output.join('');
  18685. };
  18686. str_format.cache = {};
  18687. str_format.parse = function(fmt) {
  18688. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  18689. while (_fmt) {
  18690. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  18691. parse_tree.push(match[0]);
  18692. }
  18693. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  18694. parse_tree.push('%');
  18695. }
  18696. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  18697. if (match[2]) {
  18698. arg_names |= 1;
  18699. var field_list = [], replacement_field = match[2], field_match = [];
  18700. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  18701. field_list.push(field_match[1]);
  18702. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  18703. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  18704. field_list.push(field_match[1]);
  18705. }
  18706. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  18707. field_list.push(field_match[1]);
  18708. }
  18709. else {
  18710. throw('[sprintf] huh?');
  18711. }
  18712. }
  18713. }
  18714. else {
  18715. throw('[sprintf] huh?');
  18716. }
  18717. match[2] = field_list;
  18718. }
  18719. else {
  18720. arg_names |= 2;
  18721. }
  18722. if (arg_names === 3) {
  18723. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  18724. }
  18725. parse_tree.push(match);
  18726. }
  18727. else {
  18728. throw('[sprintf] huh?');
  18729. }
  18730. _fmt = _fmt.substring(match[0].length);
  18731. }
  18732. return parse_tree;
  18733. };
  18734. return str_format;
  18735. })();
  18736. var vsprintf = function(fmt, argv) {
  18737. argv.unshift(fmt);
  18738. return sprintf.apply(null, argv);
  18739. };
  18740. addPostProcessor("sprintf", function(val, key, opts) {
  18741. if (!opts.sprintf) return val;
  18742. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  18743. return vsprintf(val, opts.sprintf);
  18744. } else if (typeof opts.sprintf === 'object') {
  18745. return sprintf(val, opts.sprintf);
  18746. }
  18747. return val;
  18748. });
  18749. // public api interface
  18750. i18n.init = init;
  18751. i18n.setLng = setLng;
  18752. i18n.preload = preload;
  18753. i18n.addResourceBundle = addResourceBundle;
  18754. i18n.hasResourceBundle = hasResourceBundle;
  18755. i18n.addResource = addResource;
  18756. i18n.addResources = addResources;
  18757. i18n.removeResourceBundle = removeResourceBundle;
  18758. i18n.loadNamespace = loadNamespace;
  18759. i18n.loadNamespaces = loadNamespaces;
  18760. i18n.setDefaultNamespace = setDefaultNamespace;
  18761. i18n.t = translate;
  18762. i18n.translate = translate;
  18763. i18n.exists = exists;
  18764. i18n.detectLanguage = f.detectLanguage;
  18765. i18n.pluralExtensions = pluralExtensions;
  18766. i18n.sync = sync;
  18767. i18n.functions = f;
  18768. i18n.lng = lng;
  18769. i18n.addPostProcessor = addPostProcessor;
  18770. i18n.options = o;
  18771. })();
  18772. },{"jquery":"jquery"}],67:[function(require,module,exports){
  18773. // Top level file is just a mixin of submodules & constants
  18774. 'use strict';
  18775. var assign = require('./lib/utils/common').assign;
  18776. var deflate = require('./lib/deflate');
  18777. var inflate = require('./lib/inflate');
  18778. var constants = require('./lib/zlib/constants');
  18779. var pako = {};
  18780. assign(pako, deflate, inflate, constants);
  18781. module.exports = pako;
  18782. },{"./lib/deflate":68,"./lib/inflate":69,"./lib/utils/common":70,"./lib/zlib/constants":73}],68:[function(require,module,exports){
  18783. 'use strict';
  18784. var zlib_deflate = require('./zlib/deflate.js');
  18785. var utils = require('./utils/common');
  18786. var strings = require('./utils/strings');
  18787. var msg = require('./zlib/messages');
  18788. var zstream = require('./zlib/zstream');
  18789. var toString = Object.prototype.toString;
  18790. /* Public constants ==========================================================*/
  18791. /* ===========================================================================*/
  18792. var Z_NO_FLUSH = 0;
  18793. var Z_FINISH = 4;
  18794. var Z_OK = 0;
  18795. var Z_STREAM_END = 1;
  18796. var Z_DEFAULT_COMPRESSION = -1;
  18797. var Z_DEFAULT_STRATEGY = 0;
  18798. var Z_DEFLATED = 8;
  18799. /* ===========================================================================*/
  18800. /**
  18801. * class Deflate
  18802. *
  18803. * Generic JS-style wrapper for zlib calls. If you don't need
  18804. * streaming behaviour - use more simple functions: [[deflate]],
  18805. * [[deflateRaw]] and [[gzip]].
  18806. **/
  18807. /* internal
  18808. * Deflate.chunks -> Array
  18809. *
  18810. * Chunks of output data, if [[Deflate#onData]] not overriden.
  18811. **/
  18812. /**
  18813. * Deflate.result -> Uint8Array|Array
  18814. *
  18815. * Compressed result, generated by default [[Deflate#onData]]
  18816. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  18817. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  18818. **/
  18819. /**
  18820. * Deflate.err -> Number
  18821. *
  18822. * Error code after deflate finished. 0 (Z_OK) on success.
  18823. * You will not need it in real life, because deflate errors
  18824. * are possible only on wrong options or bad `onData` / `onEnd`
  18825. * custom handlers.
  18826. **/
  18827. /**
  18828. * Deflate.msg -> String
  18829. *
  18830. * Error message, if [[Deflate.err]] != 0
  18831. **/
  18832. /**
  18833. * new Deflate(options)
  18834. * - options (Object): zlib deflate options.
  18835. *
  18836. * Creates new deflator instance with specified params. Throws exception
  18837. * on bad params. Supported options:
  18838. *
  18839. * - `level`
  18840. * - `windowBits`
  18841. * - `memLevel`
  18842. * - `strategy`
  18843. *
  18844. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  18845. * for more information on these.
  18846. *
  18847. * Additional options, for internal needs:
  18848. *
  18849. * - `chunkSize` - size of generated data chunks (16K by default)
  18850. * - `raw` (Boolean) - do raw deflate
  18851. * - `gzip` (Boolean) - create gzip wrapper
  18852. * - `to` (String) - if equal to 'string', then result will be "binary string"
  18853. * (each char code [0..255])
  18854. * - `header` (Object) - custom header for gzip
  18855. * - `text` (Boolean) - true if compressed data believed to be text
  18856. * - `time` (Number) - modification time, unix timestamp
  18857. * - `os` (Number) - operation system code
  18858. * - `extra` (Array) - array of bytes with extra data (max 65536)
  18859. * - `name` (String) - file name (binary string)
  18860. * - `comment` (String) - comment (binary string)
  18861. * - `hcrc` (Boolean) - true if header crc should be added
  18862. *
  18863. * ##### Example:
  18864. *
  18865. * ```javascript
  18866. * var pako = require('pako')
  18867. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  18868. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  18869. *
  18870. * var deflate = new pako.Deflate({ level: 3});
  18871. *
  18872. * deflate.push(chunk1, false);
  18873. * deflate.push(chunk2, true); // true -> last chunk
  18874. *
  18875. * if (deflate.err) { throw new Error(deflate.err); }
  18876. *
  18877. * console.log(deflate.result);
  18878. * ```
  18879. **/
  18880. var Deflate = function(options) {
  18881. this.options = utils.assign({
  18882. level: Z_DEFAULT_COMPRESSION,
  18883. method: Z_DEFLATED,
  18884. chunkSize: 16384,
  18885. windowBits: 15,
  18886. memLevel: 8,
  18887. strategy: Z_DEFAULT_STRATEGY,
  18888. to: ''
  18889. }, options || {});
  18890. var opt = this.options;
  18891. if (opt.raw && (opt.windowBits > 0)) {
  18892. opt.windowBits = -opt.windowBits;
  18893. }
  18894. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  18895. opt.windowBits += 16;
  18896. }
  18897. this.err = 0; // error code, if happens (0 = Z_OK)
  18898. this.msg = ''; // error message
  18899. this.ended = false; // used to avoid multiple onEnd() calls
  18900. this.chunks = []; // chunks of compressed data
  18901. this.strm = new zstream();
  18902. this.strm.avail_out = 0;
  18903. var status = zlib_deflate.deflateInit2(
  18904. this.strm,
  18905. opt.level,
  18906. opt.method,
  18907. opt.windowBits,
  18908. opt.memLevel,
  18909. opt.strategy
  18910. );
  18911. if (status !== Z_OK) {
  18912. throw new Error(msg[status]);
  18913. }
  18914. if (opt.header) {
  18915. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  18916. }
  18917. };
  18918. /**
  18919. * Deflate#push(data[, mode]) -> Boolean
  18920. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  18921. * converted to utf8 byte sequence.
  18922. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  18923. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  18924. *
  18925. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  18926. * new compressed chunks. Returns `true` on success. The last data block must have
  18927. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  18928. * [[Deflate#onEnd]].
  18929. *
  18930. * On fail call [[Deflate#onEnd]] with error code and return false.
  18931. *
  18932. * We strongly recommend to use `Uint8Array` on input for best speed (output
  18933. * array format is detected automatically). Also, don't skip last param and always
  18934. * use the same type in your code (boolean or number). That will improve JS speed.
  18935. *
  18936. * For regular `Array`-s make sure all elements are [0..255].
  18937. *
  18938. * ##### Example
  18939. *
  18940. * ```javascript
  18941. * push(chunk, false); // push one of data chunks
  18942. * ...
  18943. * push(chunk, true); // push last chunk
  18944. * ```
  18945. **/
  18946. Deflate.prototype.push = function(data, mode) {
  18947. var strm = this.strm;
  18948. var chunkSize = this.options.chunkSize;
  18949. var status, _mode;
  18950. if (this.ended) { return false; }
  18951. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  18952. // Convert data if needed
  18953. if (typeof data === 'string') {
  18954. // If we need to compress text, change encoding to utf8.
  18955. strm.input = strings.string2buf(data);
  18956. } else if (toString.call(data) === '[object ArrayBuffer]') {
  18957. strm.input = new Uint8Array(data);
  18958. } else {
  18959. strm.input = data;
  18960. }
  18961. strm.next_in = 0;
  18962. strm.avail_in = strm.input.length;
  18963. do {
  18964. if (strm.avail_out === 0) {
  18965. strm.output = new utils.Buf8(chunkSize);
  18966. strm.next_out = 0;
  18967. strm.avail_out = chunkSize;
  18968. }
  18969. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  18970. if (status !== Z_STREAM_END && status !== Z_OK) {
  18971. this.onEnd(status);
  18972. this.ended = true;
  18973. return false;
  18974. }
  18975. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  18976. if (this.options.to === 'string') {
  18977. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  18978. } else {
  18979. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  18980. }
  18981. }
  18982. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  18983. // Finalize on the last chunk.
  18984. if (_mode === Z_FINISH) {
  18985. status = zlib_deflate.deflateEnd(this.strm);
  18986. this.onEnd(status);
  18987. this.ended = true;
  18988. return status === Z_OK;
  18989. }
  18990. return true;
  18991. };
  18992. /**
  18993. * Deflate#onData(chunk) -> Void
  18994. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  18995. * on js engine support. When string output requested, each chunk
  18996. * will be string.
  18997. *
  18998. * By default, stores data blocks in `chunks[]` property and glue
  18999. * those in `onEnd`. Override this handler, if you need another behaviour.
  19000. **/
  19001. Deflate.prototype.onData = function(chunk) {
  19002. this.chunks.push(chunk);
  19003. };
  19004. /**
  19005. * Deflate#onEnd(status) -> Void
  19006. * - status (Number): deflate status. 0 (Z_OK) on success,
  19007. * other if not.
  19008. *
  19009. * Called once after you tell deflate that input stream complete
  19010. * or error happenned. By default - join collected chunks,
  19011. * free memory and fill `results` / `err` properties.
  19012. **/
  19013. Deflate.prototype.onEnd = function(status) {
  19014. // On success - join
  19015. if (status === Z_OK) {
  19016. if (this.options.to === 'string') {
  19017. this.result = this.chunks.join('');
  19018. } else {
  19019. this.result = utils.flattenChunks(this.chunks);
  19020. }
  19021. }
  19022. this.chunks = [];
  19023. this.err = status;
  19024. this.msg = this.strm.msg;
  19025. };
  19026. /**
  19027. * deflate(data[, options]) -> Uint8Array|Array|String
  19028. * - data (Uint8Array|Array|String): input data to compress.
  19029. * - options (Object): zlib deflate options.
  19030. *
  19031. * Compress `data` with deflate alrorythm and `options`.
  19032. *
  19033. * Supported options are:
  19034. *
  19035. * - level
  19036. * - windowBits
  19037. * - memLevel
  19038. * - strategy
  19039. *
  19040. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19041. * for more information on these.
  19042. *
  19043. * Sugar (options):
  19044. *
  19045. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19046. * negative windowBits implicitly.
  19047. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19048. * (each char code [0..255])
  19049. *
  19050. * ##### Example:
  19051. *
  19052. * ```javascript
  19053. * var pako = require('pako')
  19054. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  19055. *
  19056. * console.log(pako.deflate(data));
  19057. * ```
  19058. **/
  19059. function deflate(input, options) {
  19060. var deflator = new Deflate(options);
  19061. deflator.push(input, true);
  19062. // That will never happens, if you don't cheat with options :)
  19063. if (deflator.err) { throw deflator.msg; }
  19064. return deflator.result;
  19065. }
  19066. /**
  19067. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  19068. * - data (Uint8Array|Array|String): input data to compress.
  19069. * - options (Object): zlib deflate options.
  19070. *
  19071. * The same as [[deflate]], but creates raw data, without wrapper
  19072. * (header and adler32 crc).
  19073. **/
  19074. function deflateRaw(input, options) {
  19075. options = options || {};
  19076. options.raw = true;
  19077. return deflate(input, options);
  19078. }
  19079. /**
  19080. * gzip(data[, options]) -> Uint8Array|Array|String
  19081. * - data (Uint8Array|Array|String): input data to compress.
  19082. * - options (Object): zlib deflate options.
  19083. *
  19084. * The same as [[deflate]], but create gzip wrapper instead of
  19085. * deflate one.
  19086. **/
  19087. function gzip(input, options) {
  19088. options = options || {};
  19089. options.gzip = true;
  19090. return deflate(input, options);
  19091. }
  19092. exports.Deflate = Deflate;
  19093. exports.deflate = deflate;
  19094. exports.deflateRaw = deflateRaw;
  19095. exports.gzip = gzip;
  19096. },{"./utils/common":70,"./utils/strings":71,"./zlib/deflate.js":75,"./zlib/messages":80,"./zlib/zstream":82}],69:[function(require,module,exports){
  19097. 'use strict';
  19098. var zlib_inflate = require('./zlib/inflate.js');
  19099. var utils = require('./utils/common');
  19100. var strings = require('./utils/strings');
  19101. var c = require('./zlib/constants');
  19102. var msg = require('./zlib/messages');
  19103. var zstream = require('./zlib/zstream');
  19104. var gzheader = require('./zlib/gzheader');
  19105. var toString = Object.prototype.toString;
  19106. /**
  19107. * class Inflate
  19108. *
  19109. * Generic JS-style wrapper for zlib calls. If you don't need
  19110. * streaming behaviour - use more simple functions: [[inflate]]
  19111. * and [[inflateRaw]].
  19112. **/
  19113. /* internal
  19114. * inflate.chunks -> Array
  19115. *
  19116. * Chunks of output data, if [[Inflate#onData]] not overriden.
  19117. **/
  19118. /**
  19119. * Inflate.result -> Uint8Array|Array|String
  19120. *
  19121. * Uncompressed result, generated by default [[Inflate#onData]]
  19122. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  19123. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  19124. **/
  19125. /**
  19126. * Inflate.err -> Number
  19127. *
  19128. * Error code after inflate finished. 0 (Z_OK) on success.
  19129. * Should be checked if broken data possible.
  19130. **/
  19131. /**
  19132. * Inflate.msg -> String
  19133. *
  19134. * Error message, if [[Inflate.err]] != 0
  19135. **/
  19136. /**
  19137. * new Inflate(options)
  19138. * - options (Object): zlib inflate options.
  19139. *
  19140. * Creates new inflator instance with specified params. Throws exception
  19141. * on bad params. Supported options:
  19142. *
  19143. * - `windowBits`
  19144. *
  19145. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19146. * for more information on these.
  19147. *
  19148. * Additional options, for internal needs:
  19149. *
  19150. * - `chunkSize` - size of generated data chunks (16K by default)
  19151. * - `raw` (Boolean) - do raw inflate
  19152. * - `to` (String) - if equal to 'string', then result will be converted
  19153. * from utf8 to utf16 (javascript) string. When string output requested,
  19154. * chunk length can differ from `chunkSize`, depending on content.
  19155. *
  19156. * By default, when no options set, autodetect deflate/gzip data format via
  19157. * wrapper header.
  19158. *
  19159. * ##### Example:
  19160. *
  19161. * ```javascript
  19162. * var pako = require('pako')
  19163. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19164. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19165. *
  19166. * var inflate = new pako.Inflate({ level: 3});
  19167. *
  19168. * inflate.push(chunk1, false);
  19169. * inflate.push(chunk2, true); // true -> last chunk
  19170. *
  19171. * if (inflate.err) { throw new Error(inflate.err); }
  19172. *
  19173. * console.log(inflate.result);
  19174. * ```
  19175. **/
  19176. var Inflate = function(options) {
  19177. this.options = utils.assign({
  19178. chunkSize: 16384,
  19179. windowBits: 0,
  19180. to: ''
  19181. }, options || {});
  19182. var opt = this.options;
  19183. // Force window size for `raw` data, if not set directly,
  19184. // because we have no header for autodetect.
  19185. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  19186. opt.windowBits = -opt.windowBits;
  19187. if (opt.windowBits === 0) { opt.windowBits = -15; }
  19188. }
  19189. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  19190. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  19191. !(options && options.windowBits)) {
  19192. opt.windowBits += 32;
  19193. }
  19194. // Gzip header has no info about windows size, we can do autodetect only
  19195. // for deflate. So, if window size not set, force it to max when gzip possible
  19196. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  19197. // bit 3 (16) -> gzipped data
  19198. // bit 4 (32) -> autodetect gzip/deflate
  19199. if ((opt.windowBits & 15) === 0) {
  19200. opt.windowBits |= 15;
  19201. }
  19202. }
  19203. this.err = 0; // error code, if happens (0 = Z_OK)
  19204. this.msg = ''; // error message
  19205. this.ended = false; // used to avoid multiple onEnd() calls
  19206. this.chunks = []; // chunks of compressed data
  19207. this.strm = new zstream();
  19208. this.strm.avail_out = 0;
  19209. var status = zlib_inflate.inflateInit2(
  19210. this.strm,
  19211. opt.windowBits
  19212. );
  19213. if (status !== c.Z_OK) {
  19214. throw new Error(msg[status]);
  19215. }
  19216. this.header = new gzheader();
  19217. zlib_inflate.inflateGetHeader(this.strm, this.header);
  19218. };
  19219. /**
  19220. * Inflate#push(data[, mode]) -> Boolean
  19221. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  19222. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19223. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19224. *
  19225. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  19226. * new output chunks. Returns `true` on success. The last data block must have
  19227. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  19228. * [[Inflate#onEnd]].
  19229. *
  19230. * On fail call [[Inflate#onEnd]] with error code and return false.
  19231. *
  19232. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19233. * format is detected automatically). Also, don't skip last param and always
  19234. * use the same type in your code (boolean or number). That will improve JS speed.
  19235. *
  19236. * For regular `Array`-s make sure all elements are [0..255].
  19237. *
  19238. * ##### Example
  19239. *
  19240. * ```javascript
  19241. * push(chunk, false); // push one of data chunks
  19242. * ...
  19243. * push(chunk, true); // push last chunk
  19244. * ```
  19245. **/
  19246. Inflate.prototype.push = function(data, mode) {
  19247. var strm = this.strm;
  19248. var chunkSize = this.options.chunkSize;
  19249. var status, _mode;
  19250. var next_out_utf8, tail, utf8str;
  19251. if (this.ended) { return false; }
  19252. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  19253. // Convert data if needed
  19254. if (typeof data === 'string') {
  19255. // Only binary strings can be decompressed on practice
  19256. strm.input = strings.binstring2buf(data);
  19257. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19258. strm.input = new Uint8Array(data);
  19259. } else {
  19260. strm.input = data;
  19261. }
  19262. strm.next_in = 0;
  19263. strm.avail_in = strm.input.length;
  19264. do {
  19265. if (strm.avail_out === 0) {
  19266. strm.output = new utils.Buf8(chunkSize);
  19267. strm.next_out = 0;
  19268. strm.avail_out = chunkSize;
  19269. }
  19270. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  19271. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  19272. this.onEnd(status);
  19273. this.ended = true;
  19274. return false;
  19275. }
  19276. if (strm.next_out) {
  19277. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  19278. if (this.options.to === 'string') {
  19279. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  19280. tail = strm.next_out - next_out_utf8;
  19281. utf8str = strings.buf2string(strm.output, next_out_utf8);
  19282. // move tail
  19283. strm.next_out = tail;
  19284. strm.avail_out = chunkSize - tail;
  19285. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  19286. this.onData(utf8str);
  19287. } else {
  19288. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19289. }
  19290. }
  19291. }
  19292. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  19293. if (status === c.Z_STREAM_END) {
  19294. _mode = c.Z_FINISH;
  19295. }
  19296. // Finalize on the last chunk.
  19297. if (_mode === c.Z_FINISH) {
  19298. status = zlib_inflate.inflateEnd(this.strm);
  19299. this.onEnd(status);
  19300. this.ended = true;
  19301. return status === c.Z_OK;
  19302. }
  19303. return true;
  19304. };
  19305. /**
  19306. * Inflate#onData(chunk) -> Void
  19307. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19308. * on js engine support. When string output requested, each chunk
  19309. * will be string.
  19310. *
  19311. * By default, stores data blocks in `chunks[]` property and glue
  19312. * those in `onEnd`. Override this handler, if you need another behaviour.
  19313. **/
  19314. Inflate.prototype.onData = function(chunk) {
  19315. this.chunks.push(chunk);
  19316. };
  19317. /**
  19318. * Inflate#onEnd(status) -> Void
  19319. * - status (Number): inflate status. 0 (Z_OK) on success,
  19320. * other if not.
  19321. *
  19322. * Called once after you tell inflate that input stream complete
  19323. * or error happenned. By default - join collected chunks,
  19324. * free memory and fill `results` / `err` properties.
  19325. **/
  19326. Inflate.prototype.onEnd = function(status) {
  19327. // On success - join
  19328. if (status === c.Z_OK) {
  19329. if (this.options.to === 'string') {
  19330. // Glue & convert here, until we teach pako to send
  19331. // utf8 alligned strings to onData
  19332. this.result = this.chunks.join('');
  19333. } else {
  19334. this.result = utils.flattenChunks(this.chunks);
  19335. }
  19336. }
  19337. this.chunks = [];
  19338. this.err = status;
  19339. this.msg = this.strm.msg;
  19340. };
  19341. /**
  19342. * inflate(data[, options]) -> Uint8Array|Array|String
  19343. * - data (Uint8Array|Array|String): input data to decompress.
  19344. * - options (Object): zlib inflate options.
  19345. *
  19346. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  19347. * format via wrapper header by default. That's why we don't provide
  19348. * separate `ungzip` method.
  19349. *
  19350. * Supported options are:
  19351. *
  19352. * - windowBits
  19353. *
  19354. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19355. * for more information.
  19356. *
  19357. * Sugar (options):
  19358. *
  19359. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19360. * negative windowBits implicitly.
  19361. * - `to` (String) - if equal to 'string', then result will be converted
  19362. * from utf8 to utf16 (javascript) string. When string output requested,
  19363. * chunk length can differ from `chunkSize`, depending on content.
  19364. *
  19365. *
  19366. * ##### Example:
  19367. *
  19368. * ```javascript
  19369. * var pako = require('pako')
  19370. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  19371. * , output;
  19372. *
  19373. * try {
  19374. * output = pako.inflate(input);
  19375. * } catch (err)
  19376. * console.log(err);
  19377. * }
  19378. * ```
  19379. **/
  19380. function inflate(input, options) {
  19381. var inflator = new Inflate(options);
  19382. inflator.push(input, true);
  19383. // That will never happens, if you don't cheat with options :)
  19384. if (inflator.err) { throw inflator.msg; }
  19385. return inflator.result;
  19386. }
  19387. /**
  19388. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  19389. * - data (Uint8Array|Array|String): input data to decompress.
  19390. * - options (Object): zlib inflate options.
  19391. *
  19392. * The same as [[inflate]], but creates raw data, without wrapper
  19393. * (header and adler32 crc).
  19394. **/
  19395. function inflateRaw(input, options) {
  19396. options = options || {};
  19397. options.raw = true;
  19398. return inflate(input, options);
  19399. }
  19400. /**
  19401. * ungzip(data[, options]) -> Uint8Array|Array|String
  19402. * - data (Uint8Array|Array|String): input data to decompress.
  19403. * - options (Object): zlib inflate options.
  19404. *
  19405. * Just shortcut to [[inflate]], because it autodetects format
  19406. * by header.content. Done for convenience.
  19407. **/
  19408. exports.Inflate = Inflate;
  19409. exports.inflate = inflate;
  19410. exports.inflateRaw = inflateRaw;
  19411. exports.ungzip = inflate;
  19412. },{"./utils/common":70,"./utils/strings":71,"./zlib/constants":73,"./zlib/gzheader":76,"./zlib/inflate.js":78,"./zlib/messages":80,"./zlib/zstream":82}],70:[function(require,module,exports){
  19413. 'use strict';
  19414. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  19415. (typeof Uint16Array !== 'undefined') &&
  19416. (typeof Int32Array !== 'undefined');
  19417. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  19418. var sources = Array.prototype.slice.call(arguments, 1);
  19419. while (sources.length) {
  19420. var source = sources.shift();
  19421. if (!source) { continue; }
  19422. if (typeof(source) !== 'object') {
  19423. throw new TypeError(source + 'must be non-object');
  19424. }
  19425. for (var p in source) {
  19426. if (source.hasOwnProperty(p)) {
  19427. obj[p] = source[p];
  19428. }
  19429. }
  19430. }
  19431. return obj;
  19432. };
  19433. // reduce buffer size, avoiding mem copy
  19434. exports.shrinkBuf = function (buf, size) {
  19435. if (buf.length === size) { return buf; }
  19436. if (buf.subarray) { return buf.subarray(0, size); }
  19437. buf.length = size;
  19438. return buf;
  19439. };
  19440. var fnTyped = {
  19441. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19442. if (src.subarray && dest.subarray) {
  19443. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  19444. return;
  19445. }
  19446. // Fallback to ordinary array
  19447. for(var i=0; i<len; i++) {
  19448. dest[dest_offs + i] = src[src_offs + i];
  19449. }
  19450. },
  19451. // Join array of chunks to single array.
  19452. flattenChunks: function(chunks) {
  19453. var i, l, len, pos, chunk, result;
  19454. // calculate data length
  19455. len = 0;
  19456. for (i=0, l=chunks.length; i<l; i++) {
  19457. len += chunks[i].length;
  19458. }
  19459. // join chunks
  19460. result = new Uint8Array(len);
  19461. pos = 0;
  19462. for (i=0, l=chunks.length; i<l; i++) {
  19463. chunk = chunks[i];
  19464. result.set(chunk, pos);
  19465. pos += chunk.length;
  19466. }
  19467. return result;
  19468. }
  19469. };
  19470. var fnUntyped = {
  19471. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19472. for(var i=0; i<len; i++) {
  19473. dest[dest_offs + i] = src[src_offs + i];
  19474. }
  19475. },
  19476. // Join array of chunks to single array.
  19477. flattenChunks: function(chunks) {
  19478. return [].concat.apply([], chunks);
  19479. }
  19480. };
  19481. // Enable/Disable typed arrays use, for testing
  19482. //
  19483. exports.setTyped = function (on) {
  19484. if (on) {
  19485. exports.Buf8 = Uint8Array;
  19486. exports.Buf16 = Uint16Array;
  19487. exports.Buf32 = Int32Array;
  19488. exports.assign(exports, fnTyped);
  19489. } else {
  19490. exports.Buf8 = Array;
  19491. exports.Buf16 = Array;
  19492. exports.Buf32 = Array;
  19493. exports.assign(exports, fnUntyped);
  19494. }
  19495. };
  19496. exports.setTyped(TYPED_OK);
  19497. },{}],71:[function(require,module,exports){
  19498. // String encode/decode helpers
  19499. 'use strict';
  19500. var utils = require('./common');
  19501. // Quick check if we can use fast array to bin string conversion
  19502. //
  19503. // - apply(Array) can fail on Android 2.2
  19504. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  19505. //
  19506. var STR_APPLY_OK = true;
  19507. var STR_APPLY_UIA_OK = true;
  19508. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  19509. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  19510. // Table with utf8 lengths (calculated by first byte of sequence)
  19511. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  19512. // because max possible codepoint is 0x10ffff
  19513. var _utf8len = new utils.Buf8(256);
  19514. for (var i=0; i<256; i++) {
  19515. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  19516. }
  19517. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  19518. // convert string to array (typed, when possible)
  19519. exports.string2buf = function (str) {
  19520. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  19521. // count binary size
  19522. for (m_pos = 0; m_pos < str_len; m_pos++) {
  19523. c = str.charCodeAt(m_pos);
  19524. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  19525. c2 = str.charCodeAt(m_pos+1);
  19526. if ((c2 & 0xfc00) === 0xdc00) {
  19527. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  19528. m_pos++;
  19529. }
  19530. }
  19531. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  19532. }
  19533. // allocate buffer
  19534. buf = new utils.Buf8(buf_len);
  19535. // convert
  19536. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  19537. c = str.charCodeAt(m_pos);
  19538. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  19539. c2 = str.charCodeAt(m_pos+1);
  19540. if ((c2 & 0xfc00) === 0xdc00) {
  19541. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  19542. m_pos++;
  19543. }
  19544. }
  19545. if (c < 0x80) {
  19546. /* one byte */
  19547. buf[i++] = c;
  19548. } else if (c < 0x800) {
  19549. /* two bytes */
  19550. buf[i++] = 0xC0 | (c >>> 6);
  19551. buf[i++] = 0x80 | (c & 0x3f);
  19552. } else if (c < 0x10000) {
  19553. /* three bytes */
  19554. buf[i++] = 0xE0 | (c >>> 12);
  19555. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  19556. buf[i++] = 0x80 | (c & 0x3f);
  19557. } else {
  19558. /* four bytes */
  19559. buf[i++] = 0xf0 | (c >>> 18);
  19560. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  19561. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  19562. buf[i++] = 0x80 | (c & 0x3f);
  19563. }
  19564. }
  19565. return buf;
  19566. };
  19567. // Helper (used in 2 places)
  19568. function buf2binstring(buf, len) {
  19569. // use fallback for big arrays to avoid stack overflow
  19570. if (len < 65537) {
  19571. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  19572. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  19573. }
  19574. }
  19575. var result = '';
  19576. for(var i=0; i < len; i++) {
  19577. result += String.fromCharCode(buf[i]);
  19578. }
  19579. return result;
  19580. }
  19581. // Convert byte array to binary string
  19582. exports.buf2binstring = function(buf) {
  19583. return buf2binstring(buf, buf.length);
  19584. };
  19585. // Convert binary string (typed, when possible)
  19586. exports.binstring2buf = function(str) {
  19587. var buf = new utils.Buf8(str.length);
  19588. for(var i=0, len=buf.length; i < len; i++) {
  19589. buf[i] = str.charCodeAt(i);
  19590. }
  19591. return buf;
  19592. };
  19593. // convert array to string
  19594. exports.buf2string = function (buf, max) {
  19595. var i, out, c, c_len;
  19596. var len = max || buf.length;
  19597. // Reserve max possible length (2 words per char)
  19598. // NB: by unknown reasons, Array is significantly faster for
  19599. // String.fromCharCode.apply than Uint16Array.
  19600. var utf16buf = new Array(len*2);
  19601. for (out=0, i=0; i<len;) {
  19602. c = buf[i++];
  19603. // quick process ascii
  19604. if (c < 0x80) { utf16buf[out++] = c; continue; }
  19605. c_len = _utf8len[c];
  19606. // skip 5 & 6 byte codes
  19607. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  19608. // apply mask on first byte
  19609. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  19610. // join the rest
  19611. while (c_len > 1 && i < len) {
  19612. c = (c << 6) | (buf[i++] & 0x3f);
  19613. c_len--;
  19614. }
  19615. // terminated by end of string?
  19616. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  19617. if (c < 0x10000) {
  19618. utf16buf[out++] = c;
  19619. } else {
  19620. c -= 0x10000;
  19621. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  19622. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  19623. }
  19624. }
  19625. return buf2binstring(utf16buf, out);
  19626. };
  19627. // Calculate max possible position in utf8 buffer,
  19628. // that will not break sequence. If that's not possible
  19629. // - (very small limits) return max size as is.
  19630. //
  19631. // buf[] - utf8 bytes array
  19632. // max - length limit (mandatory);
  19633. exports.utf8border = function(buf, max) {
  19634. var pos;
  19635. max = max || buf.length;
  19636. if (max > buf.length) { max = buf.length; }
  19637. // go back from last position, until start of sequence found
  19638. pos = max-1;
  19639. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  19640. // Fuckup - very small and broken sequence,
  19641. // return max, because we should return something anyway.
  19642. if (pos < 0) { return max; }
  19643. // If we came to start of buffer - that means vuffer is too small,
  19644. // return max too.
  19645. if (pos === 0) { return max; }
  19646. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  19647. };
  19648. },{"./common":70}],72:[function(require,module,exports){
  19649. 'use strict';
  19650. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  19651. // It doesn't worth to make additional optimizationa as in original.
  19652. // Small size is preferable.
  19653. function adler32(adler, buf, len, pos) {
  19654. var s1 = (adler & 0xffff) |0
  19655. , s2 = ((adler >>> 16) & 0xffff) |0
  19656. , n = 0;
  19657. while (len !== 0) {
  19658. // Set limit ~ twice less than 5552, to keep
  19659. // s2 in 31-bits, because we force signed ints.
  19660. // in other case %= will fail.
  19661. n = len > 2000 ? 2000 : len;
  19662. len -= n;
  19663. do {
  19664. s1 = (s1 + buf[pos++]) |0;
  19665. s2 = (s2 + s1) |0;
  19666. } while (--n);
  19667. s1 %= 65521;
  19668. s2 %= 65521;
  19669. }
  19670. return (s1 | (s2 << 16)) |0;
  19671. }
  19672. module.exports = adler32;
  19673. },{}],73:[function(require,module,exports){
  19674. module.exports = {
  19675. /* Allowed flush values; see deflate() and inflate() below for details */
  19676. Z_NO_FLUSH: 0,
  19677. Z_PARTIAL_FLUSH: 1,
  19678. Z_SYNC_FLUSH: 2,
  19679. Z_FULL_FLUSH: 3,
  19680. Z_FINISH: 4,
  19681. Z_BLOCK: 5,
  19682. Z_TREES: 6,
  19683. /* Return codes for the compression/decompression functions. Negative values
  19684. * are errors, positive values are used for special but normal events.
  19685. */
  19686. Z_OK: 0,
  19687. Z_STREAM_END: 1,
  19688. Z_NEED_DICT: 2,
  19689. Z_ERRNO: -1,
  19690. Z_STREAM_ERROR: -2,
  19691. Z_DATA_ERROR: -3,
  19692. //Z_MEM_ERROR: -4,
  19693. Z_BUF_ERROR: -5,
  19694. //Z_VERSION_ERROR: -6,
  19695. /* compression levels */
  19696. Z_NO_COMPRESSION: 0,
  19697. Z_BEST_SPEED: 1,
  19698. Z_BEST_COMPRESSION: 9,
  19699. Z_DEFAULT_COMPRESSION: -1,
  19700. Z_FILTERED: 1,
  19701. Z_HUFFMAN_ONLY: 2,
  19702. Z_RLE: 3,
  19703. Z_FIXED: 4,
  19704. Z_DEFAULT_STRATEGY: 0,
  19705. /* Possible values of the data_type field (though see inflate()) */
  19706. Z_BINARY: 0,
  19707. Z_TEXT: 1,
  19708. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  19709. Z_UNKNOWN: 2,
  19710. /* The deflate compression method */
  19711. Z_DEFLATED: 8
  19712. //Z_NULL: null // Use -1 or null inline, depending on var type
  19713. };
  19714. },{}],74:[function(require,module,exports){
  19715. 'use strict';
  19716. // Note: we can't get significant speed boost here.
  19717. // So write code to minimize size - no pregenerated tables
  19718. // and array tools dependencies.
  19719. // Use ordinary array, since untyped makes no boost here
  19720. function makeTable() {
  19721. var c, table = [];
  19722. for(var n =0; n < 256; n++){
  19723. c = n;
  19724. for(var k =0; k < 8; k++){
  19725. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  19726. }
  19727. table[n] = c;
  19728. }
  19729. return table;
  19730. }
  19731. // Create table on load. Just 255 signed longs. Not a problem.
  19732. var crcTable = makeTable();
  19733. function crc32(crc, buf, len, pos) {
  19734. var t = crcTable
  19735. , end = pos + len;
  19736. crc = crc ^ (-1);
  19737. for (var i = pos; i < end; i++ ) {
  19738. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  19739. }
  19740. return (crc ^ (-1)); // >>> 0;
  19741. }
  19742. module.exports = crc32;
  19743. },{}],75:[function(require,module,exports){
  19744. 'use strict';
  19745. var utils = require('../utils/common');
  19746. var trees = require('./trees');
  19747. var adler32 = require('./adler32');
  19748. var crc32 = require('./crc32');
  19749. var msg = require('./messages');
  19750. /* Public constants ==========================================================*/
  19751. /* ===========================================================================*/
  19752. /* Allowed flush values; see deflate() and inflate() below for details */
  19753. var Z_NO_FLUSH = 0;
  19754. var Z_PARTIAL_FLUSH = 1;
  19755. //var Z_SYNC_FLUSH = 2;
  19756. var Z_FULL_FLUSH = 3;
  19757. var Z_FINISH = 4;
  19758. var Z_BLOCK = 5;
  19759. //var Z_TREES = 6;
  19760. /* Return codes for the compression/decompression functions. Negative values
  19761. * are errors, positive values are used for special but normal events.
  19762. */
  19763. var Z_OK = 0;
  19764. var Z_STREAM_END = 1;
  19765. //var Z_NEED_DICT = 2;
  19766. //var Z_ERRNO = -1;
  19767. var Z_STREAM_ERROR = -2;
  19768. var Z_DATA_ERROR = -3;
  19769. //var Z_MEM_ERROR = -4;
  19770. var Z_BUF_ERROR = -5;
  19771. //var Z_VERSION_ERROR = -6;
  19772. /* compression levels */
  19773. //var Z_NO_COMPRESSION = 0;
  19774. //var Z_BEST_SPEED = 1;
  19775. //var Z_BEST_COMPRESSION = 9;
  19776. var Z_DEFAULT_COMPRESSION = -1;
  19777. var Z_FILTERED = 1;
  19778. var Z_HUFFMAN_ONLY = 2;
  19779. var Z_RLE = 3;
  19780. var Z_FIXED = 4;
  19781. var Z_DEFAULT_STRATEGY = 0;
  19782. /* Possible values of the data_type field (though see inflate()) */
  19783. //var Z_BINARY = 0;
  19784. //var Z_TEXT = 1;
  19785. //var Z_ASCII = 1; // = Z_TEXT
  19786. var Z_UNKNOWN = 2;
  19787. /* The deflate compression method */
  19788. var Z_DEFLATED = 8;
  19789. /*============================================================================*/
  19790. var MAX_MEM_LEVEL = 9;
  19791. /* Maximum value for memLevel in deflateInit2 */
  19792. var MAX_WBITS = 15;
  19793. /* 32K LZ77 window */
  19794. var DEF_MEM_LEVEL = 8;
  19795. var LENGTH_CODES = 29;
  19796. /* number of length codes, not counting the special END_BLOCK code */
  19797. var LITERALS = 256;
  19798. /* number of literal bytes 0..255 */
  19799. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  19800. /* number of Literal or Length codes, including the END_BLOCK code */
  19801. var D_CODES = 30;
  19802. /* number of distance codes */
  19803. var BL_CODES = 19;
  19804. /* number of codes used to transfer the bit lengths */
  19805. var HEAP_SIZE = 2*L_CODES + 1;
  19806. /* maximum heap size */
  19807. var MAX_BITS = 15;
  19808. /* All codes must not exceed MAX_BITS bits */
  19809. var MIN_MATCH = 3;
  19810. var MAX_MATCH = 258;
  19811. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  19812. var PRESET_DICT = 0x20;
  19813. var INIT_STATE = 42;
  19814. var EXTRA_STATE = 69;
  19815. var NAME_STATE = 73;
  19816. var COMMENT_STATE = 91;
  19817. var HCRC_STATE = 103;
  19818. var BUSY_STATE = 113;
  19819. var FINISH_STATE = 666;
  19820. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  19821. var BS_BLOCK_DONE = 2; /* block flush performed */
  19822. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  19823. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  19824. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  19825. function err(strm, errorCode) {
  19826. strm.msg = msg[errorCode];
  19827. return errorCode;
  19828. }
  19829. function rank(f) {
  19830. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  19831. }
  19832. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  19833. /* =========================================================================
  19834. * Flush as much pending output as possible. All deflate() output goes
  19835. * through this function so some applications may wish to modify it
  19836. * to avoid allocating a large strm->output buffer and copying into it.
  19837. * (See also read_buf()).
  19838. */
  19839. function flush_pending(strm) {
  19840. var s = strm.state;
  19841. //_tr_flush_bits(s);
  19842. var len = s.pending;
  19843. if (len > strm.avail_out) {
  19844. len = strm.avail_out;
  19845. }
  19846. if (len === 0) { return; }
  19847. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  19848. strm.next_out += len;
  19849. s.pending_out += len;
  19850. strm.total_out += len;
  19851. strm.avail_out -= len;
  19852. s.pending -= len;
  19853. if (s.pending === 0) {
  19854. s.pending_out = 0;
  19855. }
  19856. }
  19857. function flush_block_only (s, last) {
  19858. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  19859. s.block_start = s.strstart;
  19860. flush_pending(s.strm);
  19861. }
  19862. function put_byte(s, b) {
  19863. s.pending_buf[s.pending++] = b;
  19864. }
  19865. /* =========================================================================
  19866. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  19867. * IN assertion: the stream state is correct and there is enough room in
  19868. * pending_buf.
  19869. */
  19870. function putShortMSB(s, b) {
  19871. // put_byte(s, (Byte)(b >> 8));
  19872. // put_byte(s, (Byte)(b & 0xff));
  19873. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  19874. s.pending_buf[s.pending++] = b & 0xff;
  19875. }
  19876. /* ===========================================================================
  19877. * Read a new buffer from the current input stream, update the adler32
  19878. * and total number of bytes read. All deflate() input goes through
  19879. * this function so some applications may wish to modify it to avoid
  19880. * allocating a large strm->input buffer and copying from it.
  19881. * (See also flush_pending()).
  19882. */
  19883. function read_buf(strm, buf, start, size) {
  19884. var len = strm.avail_in;
  19885. if (len > size) { len = size; }
  19886. if (len === 0) { return 0; }
  19887. strm.avail_in -= len;
  19888. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  19889. if (strm.state.wrap === 1) {
  19890. strm.adler = adler32(strm.adler, buf, len, start);
  19891. }
  19892. else if (strm.state.wrap === 2) {
  19893. strm.adler = crc32(strm.adler, buf, len, start);
  19894. }
  19895. strm.next_in += len;
  19896. strm.total_in += len;
  19897. return len;
  19898. }
  19899. /* ===========================================================================
  19900. * Set match_start to the longest match starting at the given string and
  19901. * return its length. Matches shorter or equal to prev_length are discarded,
  19902. * in which case the result is equal to prev_length and match_start is
  19903. * garbage.
  19904. * IN assertions: cur_match is the head of the hash chain for the current
  19905. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  19906. * OUT assertion: the match length is not greater than s->lookahead.
  19907. */
  19908. function longest_match(s, cur_match) {
  19909. var chain_length = s.max_chain_length; /* max hash chain length */
  19910. var scan = s.strstart; /* current string */
  19911. var match; /* matched string */
  19912. var len; /* length of current match */
  19913. var best_len = s.prev_length; /* best match length so far */
  19914. var nice_match = s.nice_match; /* stop if match long enough */
  19915. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  19916. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  19917. var _win = s.window; // shortcut
  19918. var wmask = s.w_mask;
  19919. var prev = s.prev;
  19920. /* Stop when cur_match becomes <= limit. To simplify the code,
  19921. * we prevent matches with the string of window index 0.
  19922. */
  19923. var strend = s.strstart + MAX_MATCH;
  19924. var scan_end1 = _win[scan + best_len - 1];
  19925. var scan_end = _win[scan + best_len];
  19926. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  19927. * It is easy to get rid of this optimization if necessary.
  19928. */
  19929. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  19930. /* Do not waste too much time if we already have a good match: */
  19931. if (s.prev_length >= s.good_match) {
  19932. chain_length >>= 2;
  19933. }
  19934. /* Do not look for matches beyond the end of the input. This is necessary
  19935. * to make deflate deterministic.
  19936. */
  19937. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  19938. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  19939. do {
  19940. // Assert(cur_match < s->strstart, "no future");
  19941. match = cur_match;
  19942. /* Skip to next match if the match length cannot increase
  19943. * or if the match length is less than 2. Note that the checks below
  19944. * for insufficient lookahead only occur occasionally for performance
  19945. * reasons. Therefore uninitialized memory will be accessed, and
  19946. * conditional jumps will be made that depend on those values.
  19947. * However the length of the match is limited to the lookahead, so
  19948. * the output of deflate is not affected by the uninitialized values.
  19949. */
  19950. if (_win[match + best_len] !== scan_end ||
  19951. _win[match + best_len - 1] !== scan_end1 ||
  19952. _win[match] !== _win[scan] ||
  19953. _win[++match] !== _win[scan + 1]) {
  19954. continue;
  19955. }
  19956. /* The check at best_len-1 can be removed because it will be made
  19957. * again later. (This heuristic is not always a win.)
  19958. * It is not necessary to compare scan[2] and match[2] since they
  19959. * are always equal when the other bytes match, given that
  19960. * the hash keys are equal and that HASH_BITS >= 8.
  19961. */
  19962. scan += 2;
  19963. match++;
  19964. // Assert(*scan == *match, "match[2]?");
  19965. /* We check for insufficient lookahead only every 8th comparison;
  19966. * the 256th check will be made at strstart+258.
  19967. */
  19968. do {
  19969. /*jshint noempty:false*/
  19970. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19971. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19972. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19973. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19974. scan < strend);
  19975. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  19976. len = MAX_MATCH - (strend - scan);
  19977. scan = strend - MAX_MATCH;
  19978. if (len > best_len) {
  19979. s.match_start = cur_match;
  19980. best_len = len;
  19981. if (len >= nice_match) {
  19982. break;
  19983. }
  19984. scan_end1 = _win[scan + best_len - 1];
  19985. scan_end = _win[scan + best_len];
  19986. }
  19987. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  19988. if (best_len <= s.lookahead) {
  19989. return best_len;
  19990. }
  19991. return s.lookahead;
  19992. }
  19993. /* ===========================================================================
  19994. * Fill the window when the lookahead becomes insufficient.
  19995. * Updates strstart and lookahead.
  19996. *
  19997. * IN assertion: lookahead < MIN_LOOKAHEAD
  19998. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  19999. * At least one byte has been read, or avail_in == 0; reads are
  20000. * performed for at least two bytes (required for the zip translate_eol
  20001. * option -- not supported here).
  20002. */
  20003. function fill_window(s) {
  20004. var _w_size = s.w_size;
  20005. var p, n, m, more, str;
  20006. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  20007. do {
  20008. more = s.window_size - s.lookahead - s.strstart;
  20009. // JS ints have 32 bit, block below not needed
  20010. /* Deal with !@#$% 64K limit: */
  20011. //if (sizeof(int) <= 2) {
  20012. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  20013. // more = wsize;
  20014. //
  20015. // } else if (more == (unsigned)(-1)) {
  20016. // /* Very unlikely, but possible on 16 bit machine if
  20017. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  20018. // */
  20019. // more--;
  20020. // }
  20021. //}
  20022. /* If the window is almost full and there is insufficient lookahead,
  20023. * move the upper half to the lower one to make room in the upper half.
  20024. */
  20025. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  20026. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  20027. s.match_start -= _w_size;
  20028. s.strstart -= _w_size;
  20029. /* we now have strstart >= MAX_DIST */
  20030. s.block_start -= _w_size;
  20031. /* Slide the hash table (could be avoided with 32 bit values
  20032. at the expense of memory usage). We slide even when level == 0
  20033. to keep the hash table consistent if we switch back to level > 0
  20034. later. (Using level 0 permanently is not an optimal usage of
  20035. zlib, so we don't care about this pathological case.)
  20036. */
  20037. n = s.hash_size;
  20038. p = n;
  20039. do {
  20040. m = s.head[--p];
  20041. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  20042. } while (--n);
  20043. n = _w_size;
  20044. p = n;
  20045. do {
  20046. m = s.prev[--p];
  20047. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  20048. /* If n is not on any hash chain, prev[n] is garbage but
  20049. * its value will never be used.
  20050. */
  20051. } while (--n);
  20052. more += _w_size;
  20053. }
  20054. if (s.strm.avail_in === 0) {
  20055. break;
  20056. }
  20057. /* If there was no sliding:
  20058. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  20059. * more == window_size - lookahead - strstart
  20060. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  20061. * => more >= window_size - 2*WSIZE + 2
  20062. * In the BIG_MEM or MMAP case (not yet supported),
  20063. * window_size == input_size + MIN_LOOKAHEAD &&
  20064. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  20065. * Otherwise, window_size == 2*WSIZE so more >= 2.
  20066. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  20067. */
  20068. //Assert(more >= 2, "more < 2");
  20069. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  20070. s.lookahead += n;
  20071. /* Initialize the hash value now that we have some input: */
  20072. if (s.lookahead + s.insert >= MIN_MATCH) {
  20073. str = s.strstart - s.insert;
  20074. s.ins_h = s.window[str];
  20075. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  20076. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  20077. //#if MIN_MATCH != 3
  20078. // Call update_hash() MIN_MATCH-3 more times
  20079. //#endif
  20080. while (s.insert) {
  20081. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  20082. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  20083. s.prev[str & s.w_mask] = s.head[s.ins_h];
  20084. s.head[s.ins_h] = str;
  20085. str++;
  20086. s.insert--;
  20087. if (s.lookahead + s.insert < MIN_MATCH) {
  20088. break;
  20089. }
  20090. }
  20091. }
  20092. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  20093. * but this is not important since only literal bytes will be emitted.
  20094. */
  20095. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  20096. /* If the WIN_INIT bytes after the end of the current data have never been
  20097. * written, then zero those bytes in order to avoid memory check reports of
  20098. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  20099. * the longest match routines. Update the high water mark for the next
  20100. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  20101. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  20102. */
  20103. // if (s.high_water < s.window_size) {
  20104. // var curr = s.strstart + s.lookahead;
  20105. // var init = 0;
  20106. //
  20107. // if (s.high_water < curr) {
  20108. // /* Previous high water mark below current data -- zero WIN_INIT
  20109. // * bytes or up to end of window, whichever is less.
  20110. // */
  20111. // init = s.window_size - curr;
  20112. // if (init > WIN_INIT)
  20113. // init = WIN_INIT;
  20114. // zmemzero(s->window + curr, (unsigned)init);
  20115. // s->high_water = curr + init;
  20116. // }
  20117. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  20118. // /* High water mark at or above current data, but below current data
  20119. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  20120. // * to end of window, whichever is less.
  20121. // */
  20122. // init = (ulg)curr + WIN_INIT - s->high_water;
  20123. // if (init > s->window_size - s->high_water)
  20124. // init = s->window_size - s->high_water;
  20125. // zmemzero(s->window + s->high_water, (unsigned)init);
  20126. // s->high_water += init;
  20127. // }
  20128. // }
  20129. //
  20130. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  20131. // "not enough room for search");
  20132. }
  20133. /* ===========================================================================
  20134. * Copy without compression as much as possible from the input stream, return
  20135. * the current block state.
  20136. * This function does not insert new strings in the dictionary since
  20137. * uncompressible data is probably not useful. This function is used
  20138. * only for the level=0 compression option.
  20139. * NOTE: this function should be optimized to avoid extra copying from
  20140. * window to pending_buf.
  20141. */
  20142. function deflate_stored(s, flush) {
  20143. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  20144. * to pending_buf_size, and each stored block has a 5 byte header:
  20145. */
  20146. var max_block_size = 0xffff;
  20147. if (max_block_size > s.pending_buf_size - 5) {
  20148. max_block_size = s.pending_buf_size - 5;
  20149. }
  20150. /* Copy as much as possible from input to output: */
  20151. for (;;) {
  20152. /* Fill the window as much as possible: */
  20153. if (s.lookahead <= 1) {
  20154. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  20155. // s->block_start >= (long)s->w_size, "slide too late");
  20156. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  20157. // s.block_start >= s.w_size)) {
  20158. // throw new Error("slide too late");
  20159. // }
  20160. fill_window(s);
  20161. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  20162. return BS_NEED_MORE;
  20163. }
  20164. if (s.lookahead === 0) {
  20165. break;
  20166. }
  20167. /* flush the current block */
  20168. }
  20169. //Assert(s->block_start >= 0L, "block gone");
  20170. // if (s.block_start < 0) throw new Error("block gone");
  20171. s.strstart += s.lookahead;
  20172. s.lookahead = 0;
  20173. /* Emit a stored block if pending_buf will be full: */
  20174. var max_start = s.block_start + max_block_size;
  20175. if (s.strstart === 0 || s.strstart >= max_start) {
  20176. /* strstart == 0 is possible when wraparound on 16-bit machine */
  20177. s.lookahead = s.strstart - max_start;
  20178. s.strstart = max_start;
  20179. /*** FLUSH_BLOCK(s, 0); ***/
  20180. flush_block_only(s, false);
  20181. if (s.strm.avail_out === 0) {
  20182. return BS_NEED_MORE;
  20183. }
  20184. /***/
  20185. }
  20186. /* Flush if we may have to slide, otherwise block_start may become
  20187. * negative and the data will be gone:
  20188. */
  20189. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  20190. /*** FLUSH_BLOCK(s, 0); ***/
  20191. flush_block_only(s, false);
  20192. if (s.strm.avail_out === 0) {
  20193. return BS_NEED_MORE;
  20194. }
  20195. /***/
  20196. }
  20197. }
  20198. s.insert = 0;
  20199. if (flush === Z_FINISH) {
  20200. /*** FLUSH_BLOCK(s, 1); ***/
  20201. flush_block_only(s, true);
  20202. if (s.strm.avail_out === 0) {
  20203. return BS_FINISH_STARTED;
  20204. }
  20205. /***/
  20206. return BS_FINISH_DONE;
  20207. }
  20208. if (s.strstart > s.block_start) {
  20209. /*** FLUSH_BLOCK(s, 0); ***/
  20210. flush_block_only(s, false);
  20211. if (s.strm.avail_out === 0) {
  20212. return BS_NEED_MORE;
  20213. }
  20214. /***/
  20215. }
  20216. return BS_NEED_MORE;
  20217. }
  20218. /* ===========================================================================
  20219. * Compress as much as possible from the input stream, return the current
  20220. * block state.
  20221. * This function does not perform lazy evaluation of matches and inserts
  20222. * new strings in the dictionary only for unmatched strings or for short
  20223. * matches. It is used only for the fast compression options.
  20224. */
  20225. function deflate_fast(s, flush) {
  20226. var hash_head; /* head of the hash chain */
  20227. var bflush; /* set if current block must be flushed */
  20228. for (;;) {
  20229. /* Make sure that we always have enough lookahead, except
  20230. * at the end of the input file. We need MAX_MATCH bytes
  20231. * for the next match, plus MIN_MATCH bytes to insert the
  20232. * string following the next match.
  20233. */
  20234. if (s.lookahead < MIN_LOOKAHEAD) {
  20235. fill_window(s);
  20236. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20237. return BS_NEED_MORE;
  20238. }
  20239. if (s.lookahead === 0) {
  20240. break; /* flush the current block */
  20241. }
  20242. }
  20243. /* Insert the string window[strstart .. strstart+2] in the
  20244. * dictionary, and set hash_head to the head of the hash chain:
  20245. */
  20246. hash_head = 0/*NIL*/;
  20247. if (s.lookahead >= MIN_MATCH) {
  20248. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20249. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20250. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20251. s.head[s.ins_h] = s.strstart;
  20252. /***/
  20253. }
  20254. /* Find the longest match, discarding those <= prev_length.
  20255. * At this point we have always match_length < MIN_MATCH
  20256. */
  20257. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  20258. /* To simplify the code, we prevent matches with the string
  20259. * of window index 0 (in particular we have to avoid a match
  20260. * of the string with itself at the start of the input file).
  20261. */
  20262. s.match_length = longest_match(s, hash_head);
  20263. /* longest_match() sets match_start */
  20264. }
  20265. if (s.match_length >= MIN_MATCH) {
  20266. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  20267. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  20268. s.match_length - MIN_MATCH, bflush); ***/
  20269. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  20270. s.lookahead -= s.match_length;
  20271. /* Insert new strings in the hash table only if the match length
  20272. * is not too large. This saves time but degrades compression.
  20273. */
  20274. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  20275. s.match_length--; /* string at strstart already in table */
  20276. do {
  20277. s.strstart++;
  20278. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20279. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20280. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20281. s.head[s.ins_h] = s.strstart;
  20282. /***/
  20283. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  20284. * always MIN_MATCH bytes ahead.
  20285. */
  20286. } while (--s.match_length !== 0);
  20287. s.strstart++;
  20288. } else
  20289. {
  20290. s.strstart += s.match_length;
  20291. s.match_length = 0;
  20292. s.ins_h = s.window[s.strstart];
  20293. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  20294. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  20295. //#if MIN_MATCH != 3
  20296. // Call UPDATE_HASH() MIN_MATCH-3 more times
  20297. //#endif
  20298. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  20299. * matter since it will be recomputed at next deflate call.
  20300. */
  20301. }
  20302. } else {
  20303. /* No match, output a literal byte */
  20304. //Tracevv((stderr,"%c", s.window[s.strstart]));
  20305. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20306. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20307. s.lookahead--;
  20308. s.strstart++;
  20309. }
  20310. if (bflush) {
  20311. /*** FLUSH_BLOCK(s, 0); ***/
  20312. flush_block_only(s, false);
  20313. if (s.strm.avail_out === 0) {
  20314. return BS_NEED_MORE;
  20315. }
  20316. /***/
  20317. }
  20318. }
  20319. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  20320. if (flush === Z_FINISH) {
  20321. /*** FLUSH_BLOCK(s, 1); ***/
  20322. flush_block_only(s, true);
  20323. if (s.strm.avail_out === 0) {
  20324. return BS_FINISH_STARTED;
  20325. }
  20326. /***/
  20327. return BS_FINISH_DONE;
  20328. }
  20329. if (s.last_lit) {
  20330. /*** FLUSH_BLOCK(s, 0); ***/
  20331. flush_block_only(s, false);
  20332. if (s.strm.avail_out === 0) {
  20333. return BS_NEED_MORE;
  20334. }
  20335. /***/
  20336. }
  20337. return BS_BLOCK_DONE;
  20338. }
  20339. /* ===========================================================================
  20340. * Same as above, but achieves better compression. We use a lazy
  20341. * evaluation for matches: a match is finally adopted only if there is
  20342. * no better match at the next window position.
  20343. */
  20344. function deflate_slow(s, flush) {
  20345. var hash_head; /* head of hash chain */
  20346. var bflush; /* set if current block must be flushed */
  20347. var max_insert;
  20348. /* Process the input block. */
  20349. for (;;) {
  20350. /* Make sure that we always have enough lookahead, except
  20351. * at the end of the input file. We need MAX_MATCH bytes
  20352. * for the next match, plus MIN_MATCH bytes to insert the
  20353. * string following the next match.
  20354. */
  20355. if (s.lookahead < MIN_LOOKAHEAD) {
  20356. fill_window(s);
  20357. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20358. return BS_NEED_MORE;
  20359. }
  20360. if (s.lookahead === 0) { break; } /* flush the current block */
  20361. }
  20362. /* Insert the string window[strstart .. strstart+2] in the
  20363. * dictionary, and set hash_head to the head of the hash chain:
  20364. */
  20365. hash_head = 0/*NIL*/;
  20366. if (s.lookahead >= MIN_MATCH) {
  20367. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20368. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20369. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20370. s.head[s.ins_h] = s.strstart;
  20371. /***/
  20372. }
  20373. /* Find the longest match, discarding those <= prev_length.
  20374. */
  20375. s.prev_length = s.match_length;
  20376. s.prev_match = s.match_start;
  20377. s.match_length = MIN_MATCH-1;
  20378. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  20379. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  20380. /* To simplify the code, we prevent matches with the string
  20381. * of window index 0 (in particular we have to avoid a match
  20382. * of the string with itself at the start of the input file).
  20383. */
  20384. s.match_length = longest_match(s, hash_head);
  20385. /* longest_match() sets match_start */
  20386. if (s.match_length <= 5 &&
  20387. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  20388. /* If prev_match is also MIN_MATCH, match_start is garbage
  20389. * but we will ignore the current match anyway.
  20390. */
  20391. s.match_length = MIN_MATCH-1;
  20392. }
  20393. }
  20394. /* If there was a match at the previous step and the current
  20395. * match is not better, output the previous match:
  20396. */
  20397. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  20398. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  20399. /* Do not insert strings in hash table beyond this. */
  20400. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  20401. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  20402. s.prev_length - MIN_MATCH, bflush);***/
  20403. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  20404. /* Insert in hash table all strings up to the end of the match.
  20405. * strstart-1 and strstart are already inserted. If there is not
  20406. * enough lookahead, the last two strings are not inserted in
  20407. * the hash table.
  20408. */
  20409. s.lookahead -= s.prev_length-1;
  20410. s.prev_length -= 2;
  20411. do {
  20412. if (++s.strstart <= max_insert) {
  20413. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20414. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20415. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20416. s.head[s.ins_h] = s.strstart;
  20417. /***/
  20418. }
  20419. } while (--s.prev_length !== 0);
  20420. s.match_available = 0;
  20421. s.match_length = MIN_MATCH-1;
  20422. s.strstart++;
  20423. if (bflush) {
  20424. /*** FLUSH_BLOCK(s, 0); ***/
  20425. flush_block_only(s, false);
  20426. if (s.strm.avail_out === 0) {
  20427. return BS_NEED_MORE;
  20428. }
  20429. /***/
  20430. }
  20431. } else if (s.match_available) {
  20432. /* If there was no match at the previous position, output a
  20433. * single literal. If there was a match but the current match
  20434. * is longer, truncate the previous match to a single literal.
  20435. */
  20436. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20437. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20438. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20439. if (bflush) {
  20440. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  20441. flush_block_only(s, false);
  20442. /***/
  20443. }
  20444. s.strstart++;
  20445. s.lookahead--;
  20446. if (s.strm.avail_out === 0) {
  20447. return BS_NEED_MORE;
  20448. }
  20449. } else {
  20450. /* There is no previous match to compare with, wait for
  20451. * the next step to decide.
  20452. */
  20453. s.match_available = 1;
  20454. s.strstart++;
  20455. s.lookahead--;
  20456. }
  20457. }
  20458. //Assert (flush != Z_NO_FLUSH, "no flush?");
  20459. if (s.match_available) {
  20460. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20461. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20462. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20463. s.match_available = 0;
  20464. }
  20465. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  20466. if (flush === Z_FINISH) {
  20467. /*** FLUSH_BLOCK(s, 1); ***/
  20468. flush_block_only(s, true);
  20469. if (s.strm.avail_out === 0) {
  20470. return BS_FINISH_STARTED;
  20471. }
  20472. /***/
  20473. return BS_FINISH_DONE;
  20474. }
  20475. if (s.last_lit) {
  20476. /*** FLUSH_BLOCK(s, 0); ***/
  20477. flush_block_only(s, false);
  20478. if (s.strm.avail_out === 0) {
  20479. return BS_NEED_MORE;
  20480. }
  20481. /***/
  20482. }
  20483. return BS_BLOCK_DONE;
  20484. }
  20485. /* ===========================================================================
  20486. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  20487. * one. Do not maintain a hash table. (It will be regenerated if this run of
  20488. * deflate switches away from Z_RLE.)
  20489. */
  20490. function deflate_rle(s, flush) {
  20491. var bflush; /* set if current block must be flushed */
  20492. var prev; /* byte at distance one to match */
  20493. var scan, strend; /* scan goes up to strend for length of run */
  20494. var _win = s.window;
  20495. for (;;) {
  20496. /* Make sure that we always have enough lookahead, except
  20497. * at the end of the input file. We need MAX_MATCH bytes
  20498. * for the longest run, plus one for the unrolled loop.
  20499. */
  20500. if (s.lookahead <= MAX_MATCH) {
  20501. fill_window(s);
  20502. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  20503. return BS_NEED_MORE;
  20504. }
  20505. if (s.lookahead === 0) { break; } /* flush the current block */
  20506. }
  20507. /* See how many times the previous byte repeats */
  20508. s.match_length = 0;
  20509. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  20510. scan = s.strstart - 1;
  20511. prev = _win[scan];
  20512. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  20513. strend = s.strstart + MAX_MATCH;
  20514. do {
  20515. /*jshint noempty:false*/
  20516. } while (prev === _win[++scan] && prev === _win[++scan] &&
  20517. prev === _win[++scan] && prev === _win[++scan] &&
  20518. prev === _win[++scan] && prev === _win[++scan] &&
  20519. prev === _win[++scan] && prev === _win[++scan] &&
  20520. scan < strend);
  20521. s.match_length = MAX_MATCH - (strend - scan);
  20522. if (s.match_length > s.lookahead) {
  20523. s.match_length = s.lookahead;
  20524. }
  20525. }
  20526. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  20527. }
  20528. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  20529. if (s.match_length >= MIN_MATCH) {
  20530. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  20531. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  20532. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  20533. s.lookahead -= s.match_length;
  20534. s.strstart += s.match_length;
  20535. s.match_length = 0;
  20536. } else {
  20537. /* No match, output a literal byte */
  20538. //Tracevv((stderr,"%c", s->window[s->strstart]));
  20539. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20540. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20541. s.lookahead--;
  20542. s.strstart++;
  20543. }
  20544. if (bflush) {
  20545. /*** FLUSH_BLOCK(s, 0); ***/
  20546. flush_block_only(s, false);
  20547. if (s.strm.avail_out === 0) {
  20548. return BS_NEED_MORE;
  20549. }
  20550. /***/
  20551. }
  20552. }
  20553. s.insert = 0;
  20554. if (flush === Z_FINISH) {
  20555. /*** FLUSH_BLOCK(s, 1); ***/
  20556. flush_block_only(s, true);
  20557. if (s.strm.avail_out === 0) {
  20558. return BS_FINISH_STARTED;
  20559. }
  20560. /***/
  20561. return BS_FINISH_DONE;
  20562. }
  20563. if (s.last_lit) {
  20564. /*** FLUSH_BLOCK(s, 0); ***/
  20565. flush_block_only(s, false);
  20566. if (s.strm.avail_out === 0) {
  20567. return BS_NEED_MORE;
  20568. }
  20569. /***/
  20570. }
  20571. return BS_BLOCK_DONE;
  20572. }
  20573. /* ===========================================================================
  20574. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  20575. * (It will be regenerated if this run of deflate switches away from Huffman.)
  20576. */
  20577. function deflate_huff(s, flush) {
  20578. var bflush; /* set if current block must be flushed */
  20579. for (;;) {
  20580. /* Make sure that we have a literal to write. */
  20581. if (s.lookahead === 0) {
  20582. fill_window(s);
  20583. if (s.lookahead === 0) {
  20584. if (flush === Z_NO_FLUSH) {
  20585. return BS_NEED_MORE;
  20586. }
  20587. break; /* flush the current block */
  20588. }
  20589. }
  20590. /* Output a literal byte */
  20591. s.match_length = 0;
  20592. //Tracevv((stderr,"%c", s->window[s->strstart]));
  20593. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20594. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20595. s.lookahead--;
  20596. s.strstart++;
  20597. if (bflush) {
  20598. /*** FLUSH_BLOCK(s, 0); ***/
  20599. flush_block_only(s, false);
  20600. if (s.strm.avail_out === 0) {
  20601. return BS_NEED_MORE;
  20602. }
  20603. /***/
  20604. }
  20605. }
  20606. s.insert = 0;
  20607. if (flush === Z_FINISH) {
  20608. /*** FLUSH_BLOCK(s, 1); ***/
  20609. flush_block_only(s, true);
  20610. if (s.strm.avail_out === 0) {
  20611. return BS_FINISH_STARTED;
  20612. }
  20613. /***/
  20614. return BS_FINISH_DONE;
  20615. }
  20616. if (s.last_lit) {
  20617. /*** FLUSH_BLOCK(s, 0); ***/
  20618. flush_block_only(s, false);
  20619. if (s.strm.avail_out === 0) {
  20620. return BS_NEED_MORE;
  20621. }
  20622. /***/
  20623. }
  20624. return BS_BLOCK_DONE;
  20625. }
  20626. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  20627. * the desired pack level (0..9). The values given below have been tuned to
  20628. * exclude worst case performance for pathological files. Better values may be
  20629. * found for specific files.
  20630. */
  20631. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  20632. this.good_length = good_length;
  20633. this.max_lazy = max_lazy;
  20634. this.nice_length = nice_length;
  20635. this.max_chain = max_chain;
  20636. this.func = func;
  20637. };
  20638. var configuration_table;
  20639. configuration_table = [
  20640. /* good lazy nice chain */
  20641. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  20642. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  20643. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  20644. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  20645. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  20646. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  20647. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  20648. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  20649. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  20650. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  20651. ];
  20652. /* ===========================================================================
  20653. * Initialize the "longest match" routines for a new zlib stream
  20654. */
  20655. function lm_init(s) {
  20656. s.window_size = 2 * s.w_size;
  20657. /*** CLEAR_HASH(s); ***/
  20658. zero(s.head); // Fill with NIL (= 0);
  20659. /* Set the default configuration parameters:
  20660. */
  20661. s.max_lazy_match = configuration_table[s.level].max_lazy;
  20662. s.good_match = configuration_table[s.level].good_length;
  20663. s.nice_match = configuration_table[s.level].nice_length;
  20664. s.max_chain_length = configuration_table[s.level].max_chain;
  20665. s.strstart = 0;
  20666. s.block_start = 0;
  20667. s.lookahead = 0;
  20668. s.insert = 0;
  20669. s.match_length = s.prev_length = MIN_MATCH - 1;
  20670. s.match_available = 0;
  20671. s.ins_h = 0;
  20672. }
  20673. function DeflateState() {
  20674. this.strm = null; /* pointer back to this zlib stream */
  20675. this.status = 0; /* as the name implies */
  20676. this.pending_buf = null; /* output still pending */
  20677. this.pending_buf_size = 0; /* size of pending_buf */
  20678. this.pending_out = 0; /* next pending byte to output to the stream */
  20679. this.pending = 0; /* nb of bytes in the pending buffer */
  20680. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  20681. this.gzhead = null; /* gzip header information to write */
  20682. this.gzindex = 0; /* where in extra, name, or comment */
  20683. this.method = Z_DEFLATED; /* can only be DEFLATED */
  20684. this.last_flush = -1; /* value of flush param for previous deflate call */
  20685. this.w_size = 0; /* LZ77 window size (32K by default) */
  20686. this.w_bits = 0; /* log2(w_size) (8..16) */
  20687. this.w_mask = 0; /* w_size - 1 */
  20688. this.window = null;
  20689. /* Sliding window. Input bytes are read into the second half of the window,
  20690. * and move to the first half later to keep a dictionary of at least wSize
  20691. * bytes. With this organization, matches are limited to a distance of
  20692. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  20693. * performed with a length multiple of the block size.
  20694. */
  20695. this.window_size = 0;
  20696. /* Actual size of window: 2*wSize, except when the user input buffer
  20697. * is directly used as sliding window.
  20698. */
  20699. this.prev = null;
  20700. /* Link to older string with same hash index. To limit the size of this
  20701. * array to 64K, this link is maintained only for the last 32K strings.
  20702. * An index in this array is thus a window index modulo 32K.
  20703. */
  20704. this.head = null; /* Heads of the hash chains or NIL. */
  20705. this.ins_h = 0; /* hash index of string to be inserted */
  20706. this.hash_size = 0; /* number of elements in hash table */
  20707. this.hash_bits = 0; /* log2(hash_size) */
  20708. this.hash_mask = 0; /* hash_size-1 */
  20709. this.hash_shift = 0;
  20710. /* Number of bits by which ins_h must be shifted at each input
  20711. * step. It must be such that after MIN_MATCH steps, the oldest
  20712. * byte no longer takes part in the hash key, that is:
  20713. * hash_shift * MIN_MATCH >= hash_bits
  20714. */
  20715. this.block_start = 0;
  20716. /* Window position at the beginning of the current output block. Gets
  20717. * negative when the window is moved backwards.
  20718. */
  20719. this.match_length = 0; /* length of best match */
  20720. this.prev_match = 0; /* previous match */
  20721. this.match_available = 0; /* set if previous match exists */
  20722. this.strstart = 0; /* start of string to insert */
  20723. this.match_start = 0; /* start of matching string */
  20724. this.lookahead = 0; /* number of valid bytes ahead in window */
  20725. this.prev_length = 0;
  20726. /* Length of the best match at previous step. Matches not greater than this
  20727. * are discarded. This is used in the lazy match evaluation.
  20728. */
  20729. this.max_chain_length = 0;
  20730. /* To speed up deflation, hash chains are never searched beyond this
  20731. * length. A higher limit improves compression ratio but degrades the
  20732. * speed.
  20733. */
  20734. this.max_lazy_match = 0;
  20735. /* Attempt to find a better match only when the current match is strictly
  20736. * smaller than this value. This mechanism is used only for compression
  20737. * levels >= 4.
  20738. */
  20739. // That's alias to max_lazy_match, don't use directly
  20740. //this.max_insert_length = 0;
  20741. /* Insert new strings in the hash table only if the match length is not
  20742. * greater than this length. This saves time but degrades compression.
  20743. * max_insert_length is used only for compression levels <= 3.
  20744. */
  20745. this.level = 0; /* compression level (1..9) */
  20746. this.strategy = 0; /* favor or force Huffman coding*/
  20747. this.good_match = 0;
  20748. /* Use a faster search when the previous match is longer than this */
  20749. this.nice_match = 0; /* Stop searching when current match exceeds this */
  20750. /* used by trees.c: */
  20751. /* Didn't use ct_data typedef below to suppress compiler warning */
  20752. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  20753. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  20754. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  20755. // Use flat array of DOUBLE size, with interleaved fata,
  20756. // because JS does not support effective
  20757. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  20758. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  20759. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  20760. zero(this.dyn_ltree);
  20761. zero(this.dyn_dtree);
  20762. zero(this.bl_tree);
  20763. this.l_desc = null; /* desc. for literal tree */
  20764. this.d_desc = null; /* desc. for distance tree */
  20765. this.bl_desc = null; /* desc. for bit length tree */
  20766. //ush bl_count[MAX_BITS+1];
  20767. this.bl_count = new utils.Buf16(MAX_BITS+1);
  20768. /* number of codes at each bit length for an optimal tree */
  20769. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  20770. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  20771. zero(this.heap);
  20772. this.heap_len = 0; /* number of elements in the heap */
  20773. this.heap_max = 0; /* element of largest frequency */
  20774. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  20775. * The same heap array is used to build all trees.
  20776. */
  20777. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  20778. zero(this.depth);
  20779. /* Depth of each subtree used as tie breaker for trees of equal frequency
  20780. */
  20781. this.l_buf = 0; /* buffer index for literals or lengths */
  20782. this.lit_bufsize = 0;
  20783. /* Size of match buffer for literals/lengths. There are 4 reasons for
  20784. * limiting lit_bufsize to 64K:
  20785. * - frequencies can be kept in 16 bit counters
  20786. * - if compression is not successful for the first block, all input
  20787. * data is still in the window so we can still emit a stored block even
  20788. * when input comes from standard input. (This can also be done for
  20789. * all blocks if lit_bufsize is not greater than 32K.)
  20790. * - if compression is not successful for a file smaller than 64K, we can
  20791. * even emit a stored file instead of a stored block (saving 5 bytes).
  20792. * This is applicable only for zip (not gzip or zlib).
  20793. * - creating new Huffman trees less frequently may not provide fast
  20794. * adaptation to changes in the input data statistics. (Take for
  20795. * example a binary file with poorly compressible code followed by
  20796. * a highly compressible string table.) Smaller buffer sizes give
  20797. * fast adaptation but have of course the overhead of transmitting
  20798. * trees more frequently.
  20799. * - I can't count above 4
  20800. */
  20801. this.last_lit = 0; /* running index in l_buf */
  20802. this.d_buf = 0;
  20803. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  20804. * the same number of elements. To use different lengths, an extra flag
  20805. * array would be necessary.
  20806. */
  20807. this.opt_len = 0; /* bit length of current block with optimal trees */
  20808. this.static_len = 0; /* bit length of current block with static trees */
  20809. this.matches = 0; /* number of string matches in current block */
  20810. this.insert = 0; /* bytes at end of window left to insert */
  20811. this.bi_buf = 0;
  20812. /* Output buffer. bits are inserted starting at the bottom (least
  20813. * significant bits).
  20814. */
  20815. this.bi_valid = 0;
  20816. /* Number of valid bits in bi_buf. All bits above the last valid bit
  20817. * are always zero.
  20818. */
  20819. // Used for window memory init. We safely ignore it for JS. That makes
  20820. // sense only for pointers and memory check tools.
  20821. //this.high_water = 0;
  20822. /* High water mark offset in window for initialized bytes -- bytes above
  20823. * this are set to zero in order to avoid memory check warnings when
  20824. * longest match routines access bytes past the input. This is then
  20825. * updated to the new high water mark.
  20826. */
  20827. }
  20828. function deflateResetKeep(strm) {
  20829. var s;
  20830. if (!strm || !strm.state) {
  20831. return err(strm, Z_STREAM_ERROR);
  20832. }
  20833. strm.total_in = strm.total_out = 0;
  20834. strm.data_type = Z_UNKNOWN;
  20835. s = strm.state;
  20836. s.pending = 0;
  20837. s.pending_out = 0;
  20838. if (s.wrap < 0) {
  20839. s.wrap = -s.wrap;
  20840. /* was made negative by deflate(..., Z_FINISH); */
  20841. }
  20842. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  20843. strm.adler = (s.wrap === 2) ?
  20844. 0 // crc32(0, Z_NULL, 0)
  20845. :
  20846. 1; // adler32(0, Z_NULL, 0)
  20847. s.last_flush = Z_NO_FLUSH;
  20848. trees._tr_init(s);
  20849. return Z_OK;
  20850. }
  20851. function deflateReset(strm) {
  20852. var ret = deflateResetKeep(strm);
  20853. if (ret === Z_OK) {
  20854. lm_init(strm.state);
  20855. }
  20856. return ret;
  20857. }
  20858. function deflateSetHeader(strm, head) {
  20859. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20860. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  20861. strm.state.gzhead = head;
  20862. return Z_OK;
  20863. }
  20864. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  20865. if (!strm) { // === Z_NULL
  20866. return Z_STREAM_ERROR;
  20867. }
  20868. var wrap = 1;
  20869. if (level === Z_DEFAULT_COMPRESSION) {
  20870. level = 6;
  20871. }
  20872. if (windowBits < 0) { /* suppress zlib wrapper */
  20873. wrap = 0;
  20874. windowBits = -windowBits;
  20875. }
  20876. else if (windowBits > 15) {
  20877. wrap = 2; /* write gzip wrapper instead */
  20878. windowBits -= 16;
  20879. }
  20880. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  20881. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  20882. strategy < 0 || strategy > Z_FIXED) {
  20883. return err(strm, Z_STREAM_ERROR);
  20884. }
  20885. if (windowBits === 8) {
  20886. windowBits = 9;
  20887. }
  20888. /* until 256-byte window bug fixed */
  20889. var s = new DeflateState();
  20890. strm.state = s;
  20891. s.strm = strm;
  20892. s.wrap = wrap;
  20893. s.gzhead = null;
  20894. s.w_bits = windowBits;
  20895. s.w_size = 1 << s.w_bits;
  20896. s.w_mask = s.w_size - 1;
  20897. s.hash_bits = memLevel + 7;
  20898. s.hash_size = 1 << s.hash_bits;
  20899. s.hash_mask = s.hash_size - 1;
  20900. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  20901. s.window = new utils.Buf8(s.w_size * 2);
  20902. s.head = new utils.Buf16(s.hash_size);
  20903. s.prev = new utils.Buf16(s.w_size);
  20904. // Don't need mem init magic for JS.
  20905. //s.high_water = 0; /* nothing written to s->window yet */
  20906. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  20907. s.pending_buf_size = s.lit_bufsize * 4;
  20908. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  20909. s.d_buf = s.lit_bufsize >> 1;
  20910. s.l_buf = (1 + 2) * s.lit_bufsize;
  20911. s.level = level;
  20912. s.strategy = strategy;
  20913. s.method = method;
  20914. return deflateReset(strm);
  20915. }
  20916. function deflateInit(strm, level) {
  20917. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  20918. }
  20919. function deflate(strm, flush) {
  20920. var old_flush, s;
  20921. var beg, val; // for gzip header write only
  20922. if (!strm || !strm.state ||
  20923. flush > Z_BLOCK || flush < 0) {
  20924. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  20925. }
  20926. s = strm.state;
  20927. if (!strm.output ||
  20928. (!strm.input && strm.avail_in !== 0) ||
  20929. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  20930. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  20931. }
  20932. s.strm = strm; /* just in case */
  20933. old_flush = s.last_flush;
  20934. s.last_flush = flush;
  20935. /* Write the header */
  20936. if (s.status === INIT_STATE) {
  20937. if (s.wrap === 2) { // GZIP header
  20938. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  20939. put_byte(s, 31);
  20940. put_byte(s, 139);
  20941. put_byte(s, 8);
  20942. if (!s.gzhead) { // s->gzhead == Z_NULL
  20943. put_byte(s, 0);
  20944. put_byte(s, 0);
  20945. put_byte(s, 0);
  20946. put_byte(s, 0);
  20947. put_byte(s, 0);
  20948. put_byte(s, s.level === 9 ? 2 :
  20949. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  20950. 4 : 0));
  20951. put_byte(s, OS_CODE);
  20952. s.status = BUSY_STATE;
  20953. }
  20954. else {
  20955. put_byte(s, (s.gzhead.text ? 1 : 0) +
  20956. (s.gzhead.hcrc ? 2 : 0) +
  20957. (!s.gzhead.extra ? 0 : 4) +
  20958. (!s.gzhead.name ? 0 : 8) +
  20959. (!s.gzhead.comment ? 0 : 16)
  20960. );
  20961. put_byte(s, s.gzhead.time & 0xff);
  20962. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  20963. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  20964. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  20965. put_byte(s, s.level === 9 ? 2 :
  20966. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  20967. 4 : 0));
  20968. put_byte(s, s.gzhead.os & 0xff);
  20969. if (s.gzhead.extra && s.gzhead.extra.length) {
  20970. put_byte(s, s.gzhead.extra.length & 0xff);
  20971. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  20972. }
  20973. if (s.gzhead.hcrc) {
  20974. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  20975. }
  20976. s.gzindex = 0;
  20977. s.status = EXTRA_STATE;
  20978. }
  20979. }
  20980. else // DEFLATE header
  20981. {
  20982. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  20983. var level_flags = -1;
  20984. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  20985. level_flags = 0;
  20986. } else if (s.level < 6) {
  20987. level_flags = 1;
  20988. } else if (s.level === 6) {
  20989. level_flags = 2;
  20990. } else {
  20991. level_flags = 3;
  20992. }
  20993. header |= (level_flags << 6);
  20994. if (s.strstart !== 0) { header |= PRESET_DICT; }
  20995. header += 31 - (header % 31);
  20996. s.status = BUSY_STATE;
  20997. putShortMSB(s, header);
  20998. /* Save the adler32 of the preset dictionary: */
  20999. if (s.strstart !== 0) {
  21000. putShortMSB(s, strm.adler >>> 16);
  21001. putShortMSB(s, strm.adler & 0xffff);
  21002. }
  21003. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  21004. }
  21005. }
  21006. //#ifdef GZIP
  21007. if (s.status === EXTRA_STATE) {
  21008. if (s.gzhead.extra/* != Z_NULL*/) {
  21009. beg = s.pending; /* start of bytes to update crc */
  21010. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  21011. if (s.pending === s.pending_buf_size) {
  21012. if (s.gzhead.hcrc && s.pending > beg) {
  21013. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21014. }
  21015. flush_pending(strm);
  21016. beg = s.pending;
  21017. if (s.pending === s.pending_buf_size) {
  21018. break;
  21019. }
  21020. }
  21021. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  21022. s.gzindex++;
  21023. }
  21024. if (s.gzhead.hcrc && s.pending > beg) {
  21025. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21026. }
  21027. if (s.gzindex === s.gzhead.extra.length) {
  21028. s.gzindex = 0;
  21029. s.status = NAME_STATE;
  21030. }
  21031. }
  21032. else {
  21033. s.status = NAME_STATE;
  21034. }
  21035. }
  21036. if (s.status === NAME_STATE) {
  21037. if (s.gzhead.name/* != Z_NULL*/) {
  21038. beg = s.pending; /* start of bytes to update crc */
  21039. //int val;
  21040. do {
  21041. if (s.pending === s.pending_buf_size) {
  21042. if (s.gzhead.hcrc && s.pending > beg) {
  21043. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21044. }
  21045. flush_pending(strm);
  21046. beg = s.pending;
  21047. if (s.pending === s.pending_buf_size) {
  21048. val = 1;
  21049. break;
  21050. }
  21051. }
  21052. // JS specific: little magic to add zero terminator to end of string
  21053. if (s.gzindex < s.gzhead.name.length) {
  21054. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  21055. } else {
  21056. val = 0;
  21057. }
  21058. put_byte(s, val);
  21059. } while (val !== 0);
  21060. if (s.gzhead.hcrc && s.pending > beg){
  21061. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21062. }
  21063. if (val === 0) {
  21064. s.gzindex = 0;
  21065. s.status = COMMENT_STATE;
  21066. }
  21067. }
  21068. else {
  21069. s.status = COMMENT_STATE;
  21070. }
  21071. }
  21072. if (s.status === COMMENT_STATE) {
  21073. if (s.gzhead.comment/* != Z_NULL*/) {
  21074. beg = s.pending; /* start of bytes to update crc */
  21075. //int val;
  21076. do {
  21077. if (s.pending === s.pending_buf_size) {
  21078. if (s.gzhead.hcrc && s.pending > beg) {
  21079. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21080. }
  21081. flush_pending(strm);
  21082. beg = s.pending;
  21083. if (s.pending === s.pending_buf_size) {
  21084. val = 1;
  21085. break;
  21086. }
  21087. }
  21088. // JS specific: little magic to add zero terminator to end of string
  21089. if (s.gzindex < s.gzhead.comment.length) {
  21090. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  21091. } else {
  21092. val = 0;
  21093. }
  21094. put_byte(s, val);
  21095. } while (val !== 0);
  21096. if (s.gzhead.hcrc && s.pending > beg) {
  21097. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21098. }
  21099. if (val === 0) {
  21100. s.status = HCRC_STATE;
  21101. }
  21102. }
  21103. else {
  21104. s.status = HCRC_STATE;
  21105. }
  21106. }
  21107. if (s.status === HCRC_STATE) {
  21108. if (s.gzhead.hcrc) {
  21109. if (s.pending + 2 > s.pending_buf_size) {
  21110. flush_pending(strm);
  21111. }
  21112. if (s.pending + 2 <= s.pending_buf_size) {
  21113. put_byte(s, strm.adler & 0xff);
  21114. put_byte(s, (strm.adler >> 8) & 0xff);
  21115. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21116. s.status = BUSY_STATE;
  21117. }
  21118. }
  21119. else {
  21120. s.status = BUSY_STATE;
  21121. }
  21122. }
  21123. //#endif
  21124. /* Flush as much pending output as possible */
  21125. if (s.pending !== 0) {
  21126. flush_pending(strm);
  21127. if (strm.avail_out === 0) {
  21128. /* Since avail_out is 0, deflate will be called again with
  21129. * more output space, but possibly with both pending and
  21130. * avail_in equal to zero. There won't be anything to do,
  21131. * but this is not an error situation so make sure we
  21132. * return OK instead of BUF_ERROR at next call of deflate:
  21133. */
  21134. s.last_flush = -1;
  21135. return Z_OK;
  21136. }
  21137. /* Make sure there is something to do and avoid duplicate consecutive
  21138. * flushes. For repeated and useless calls with Z_FINISH, we keep
  21139. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  21140. */
  21141. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  21142. flush !== Z_FINISH) {
  21143. return err(strm, Z_BUF_ERROR);
  21144. }
  21145. /* User must not provide more input after the first FINISH: */
  21146. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  21147. return err(strm, Z_BUF_ERROR);
  21148. }
  21149. /* Start a new block or continue the current one.
  21150. */
  21151. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  21152. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  21153. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  21154. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  21155. configuration_table[s.level].func(s, flush));
  21156. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  21157. s.status = FINISH_STATE;
  21158. }
  21159. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  21160. if (strm.avail_out === 0) {
  21161. s.last_flush = -1;
  21162. /* avoid BUF_ERROR next call, see above */
  21163. }
  21164. return Z_OK;
  21165. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  21166. * of deflate should use the same flush parameter to make sure
  21167. * that the flush is complete. So we don't have to output an
  21168. * empty block here, this will be done at next call. This also
  21169. * ensures that for a very small output buffer, we emit at most
  21170. * one empty block.
  21171. */
  21172. }
  21173. if (bstate === BS_BLOCK_DONE) {
  21174. if (flush === Z_PARTIAL_FLUSH) {
  21175. trees._tr_align(s);
  21176. }
  21177. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  21178. trees._tr_stored_block(s, 0, 0, false);
  21179. /* For a full flush, this empty block will be recognized
  21180. * as a special marker by inflate_sync().
  21181. */
  21182. if (flush === Z_FULL_FLUSH) {
  21183. /*** CLEAR_HASH(s); ***/ /* forget history */
  21184. zero(s.head); // Fill with NIL (= 0);
  21185. if (s.lookahead === 0) {
  21186. s.strstart = 0;
  21187. s.block_start = 0;
  21188. s.insert = 0;
  21189. }
  21190. }
  21191. }
  21192. flush_pending(strm);
  21193. if (strm.avail_out === 0) {
  21194. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  21195. return Z_OK;
  21196. }
  21197. }
  21198. }
  21199. //Assert(strm->avail_out > 0, "bug2");
  21200. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  21201. if (flush !== Z_FINISH) { return Z_OK; }
  21202. if (s.wrap <= 0) { return Z_STREAM_END; }
  21203. /* Write the trailer */
  21204. if (s.wrap === 2) {
  21205. put_byte(s, strm.adler & 0xff);
  21206. put_byte(s, (strm.adler >> 8) & 0xff);
  21207. put_byte(s, (strm.adler >> 16) & 0xff);
  21208. put_byte(s, (strm.adler >> 24) & 0xff);
  21209. put_byte(s, strm.total_in & 0xff);
  21210. put_byte(s, (strm.total_in >> 8) & 0xff);
  21211. put_byte(s, (strm.total_in >> 16) & 0xff);
  21212. put_byte(s, (strm.total_in >> 24) & 0xff);
  21213. }
  21214. else
  21215. {
  21216. putShortMSB(s, strm.adler >>> 16);
  21217. putShortMSB(s, strm.adler & 0xffff);
  21218. }
  21219. flush_pending(strm);
  21220. /* If avail_out is zero, the application will call deflate again
  21221. * to flush the rest.
  21222. */
  21223. if (s.wrap > 0) { s.wrap = -s.wrap; }
  21224. /* write the trailer only once! */
  21225. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  21226. }
  21227. function deflateEnd(strm) {
  21228. var status;
  21229. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  21230. return Z_STREAM_ERROR;
  21231. }
  21232. status = strm.state.status;
  21233. if (status !== INIT_STATE &&
  21234. status !== EXTRA_STATE &&
  21235. status !== NAME_STATE &&
  21236. status !== COMMENT_STATE &&
  21237. status !== HCRC_STATE &&
  21238. status !== BUSY_STATE &&
  21239. status !== FINISH_STATE
  21240. ) {
  21241. return err(strm, Z_STREAM_ERROR);
  21242. }
  21243. strm.state = null;
  21244. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  21245. }
  21246. /* =========================================================================
  21247. * Copy the source state to the destination state
  21248. */
  21249. //function deflateCopy(dest, source) {
  21250. //
  21251. //}
  21252. exports.deflateInit = deflateInit;
  21253. exports.deflateInit2 = deflateInit2;
  21254. exports.deflateReset = deflateReset;
  21255. exports.deflateResetKeep = deflateResetKeep;
  21256. exports.deflateSetHeader = deflateSetHeader;
  21257. exports.deflate = deflate;
  21258. exports.deflateEnd = deflateEnd;
  21259. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  21260. /* Not implemented
  21261. exports.deflateBound = deflateBound;
  21262. exports.deflateCopy = deflateCopy;
  21263. exports.deflateSetDictionary = deflateSetDictionary;
  21264. exports.deflateParams = deflateParams;
  21265. exports.deflatePending = deflatePending;
  21266. exports.deflatePrime = deflatePrime;
  21267. exports.deflateTune = deflateTune;
  21268. */
  21269. },{"../utils/common":70,"./adler32":72,"./crc32":74,"./messages":80,"./trees":81}],76:[function(require,module,exports){
  21270. 'use strict';
  21271. function GZheader() {
  21272. /* true if compressed data believed to be text */
  21273. this.text = 0;
  21274. /* modification time */
  21275. this.time = 0;
  21276. /* extra flags (not used when writing a gzip file) */
  21277. this.xflags = 0;
  21278. /* operating system */
  21279. this.os = 0;
  21280. /* pointer to extra field or Z_NULL if none */
  21281. this.extra = null;
  21282. /* extra field length (valid if extra != Z_NULL) */
  21283. this.extra_len = 0; // Actually, we don't need it in JS,
  21284. // but leave for few code modifications
  21285. //
  21286. // Setup limits is not necessary because in js we should not preallocate memory
  21287. // for inflate use constant limit in 65536 bytes
  21288. //
  21289. /* space at extra (only when reading header) */
  21290. // this.extra_max = 0;
  21291. /* pointer to zero-terminated file name or Z_NULL */
  21292. this.name = '';
  21293. /* space at name (only when reading header) */
  21294. // this.name_max = 0;
  21295. /* pointer to zero-terminated comment or Z_NULL */
  21296. this.comment = '';
  21297. /* space at comment (only when reading header) */
  21298. // this.comm_max = 0;
  21299. /* true if there was or will be a header crc */
  21300. this.hcrc = 0;
  21301. /* true when done reading gzip header (not used when writing a gzip file) */
  21302. this.done = false;
  21303. }
  21304. module.exports = GZheader;
  21305. },{}],77:[function(require,module,exports){
  21306. 'use strict';
  21307. // See state defs from inflate.js
  21308. var BAD = 30; /* got a data error -- remain here until reset */
  21309. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  21310. /*
  21311. Decode literal, length, and distance codes and write out the resulting
  21312. literal and match bytes until either not enough input or output is
  21313. available, an end-of-block is encountered, or a data error is encountered.
  21314. When large enough input and output buffers are supplied to inflate(), for
  21315. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  21316. inflate execution time is spent in this routine.
  21317. Entry assumptions:
  21318. state.mode === LEN
  21319. strm.avail_in >= 6
  21320. strm.avail_out >= 258
  21321. start >= strm.avail_out
  21322. state.bits < 8
  21323. On return, state.mode is one of:
  21324. LEN -- ran out of enough output space or enough available input
  21325. TYPE -- reached end of block code, inflate() to interpret next block
  21326. BAD -- error in block data
  21327. Notes:
  21328. - The maximum input bits used by a length/distance pair is 15 bits for the
  21329. length code, 5 bits for the length extra, 15 bits for the distance code,
  21330. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  21331. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  21332. checking for available input while decoding.
  21333. - The maximum bytes that a single length/distance pair can output is 258
  21334. bytes, which is the maximum length that can be coded. inflate_fast()
  21335. requires strm.avail_out >= 258 for each loop to avoid checking for
  21336. output space.
  21337. */
  21338. module.exports = function inflate_fast(strm, start) {
  21339. var state;
  21340. var _in; /* local strm.input */
  21341. var last; /* have enough input while in < last */
  21342. var _out; /* local strm.output */
  21343. var beg; /* inflate()'s initial strm.output */
  21344. var end; /* while out < end, enough space available */
  21345. //#ifdef INFLATE_STRICT
  21346. var dmax; /* maximum distance from zlib header */
  21347. //#endif
  21348. var wsize; /* window size or zero if not using window */
  21349. var whave; /* valid bytes in the window */
  21350. var wnext; /* window write index */
  21351. var window; /* allocated sliding window, if wsize != 0 */
  21352. var hold; /* local strm.hold */
  21353. var bits; /* local strm.bits */
  21354. var lcode; /* local strm.lencode */
  21355. var dcode; /* local strm.distcode */
  21356. var lmask; /* mask for first level of length codes */
  21357. var dmask; /* mask for first level of distance codes */
  21358. var here; /* retrieved table entry */
  21359. var op; /* code bits, operation, extra bits, or */
  21360. /* window position, window bytes to copy */
  21361. var len; /* match length, unused bytes */
  21362. var dist; /* match distance */
  21363. var from; /* where to copy match from */
  21364. var from_source;
  21365. var input, output; // JS specific, because we have no pointers
  21366. /* copy state to local variables */
  21367. state = strm.state;
  21368. //here = state.here;
  21369. _in = strm.next_in;
  21370. input = strm.input;
  21371. last = _in + (strm.avail_in - 5);
  21372. _out = strm.next_out;
  21373. output = strm.output;
  21374. beg = _out - (start - strm.avail_out);
  21375. end = _out + (strm.avail_out - 257);
  21376. //#ifdef INFLATE_STRICT
  21377. dmax = state.dmax;
  21378. //#endif
  21379. wsize = state.wsize;
  21380. whave = state.whave;
  21381. wnext = state.wnext;
  21382. window = state.window;
  21383. hold = state.hold;
  21384. bits = state.bits;
  21385. lcode = state.lencode;
  21386. dcode = state.distcode;
  21387. lmask = (1 << state.lenbits) - 1;
  21388. dmask = (1 << state.distbits) - 1;
  21389. /* decode literals and length/distances until end-of-block or not enough
  21390. input data or output space */
  21391. top:
  21392. do {
  21393. if (bits < 15) {
  21394. hold += input[_in++] << bits;
  21395. bits += 8;
  21396. hold += input[_in++] << bits;
  21397. bits += 8;
  21398. }
  21399. here = lcode[hold & lmask];
  21400. dolen:
  21401. for (;;) { // Goto emulation
  21402. op = here >>> 24/*here.bits*/;
  21403. hold >>>= op;
  21404. bits -= op;
  21405. op = (here >>> 16) & 0xff/*here.op*/;
  21406. if (op === 0) { /* literal */
  21407. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  21408. // "inflate: literal '%c'\n" :
  21409. // "inflate: literal 0x%02x\n", here.val));
  21410. output[_out++] = here & 0xffff/*here.val*/;
  21411. }
  21412. else if (op & 16) { /* length base */
  21413. len = here & 0xffff/*here.val*/;
  21414. op &= 15; /* number of extra bits */
  21415. if (op) {
  21416. if (bits < op) {
  21417. hold += input[_in++] << bits;
  21418. bits += 8;
  21419. }
  21420. len += hold & ((1 << op) - 1);
  21421. hold >>>= op;
  21422. bits -= op;
  21423. }
  21424. //Tracevv((stderr, "inflate: length %u\n", len));
  21425. if (bits < 15) {
  21426. hold += input[_in++] << bits;
  21427. bits += 8;
  21428. hold += input[_in++] << bits;
  21429. bits += 8;
  21430. }
  21431. here = dcode[hold & dmask];
  21432. dodist:
  21433. for (;;) { // goto emulation
  21434. op = here >>> 24/*here.bits*/;
  21435. hold >>>= op;
  21436. bits -= op;
  21437. op = (here >>> 16) & 0xff/*here.op*/;
  21438. if (op & 16) { /* distance base */
  21439. dist = here & 0xffff/*here.val*/;
  21440. op &= 15; /* number of extra bits */
  21441. if (bits < op) {
  21442. hold += input[_in++] << bits;
  21443. bits += 8;
  21444. if (bits < op) {
  21445. hold += input[_in++] << bits;
  21446. bits += 8;
  21447. }
  21448. }
  21449. dist += hold & ((1 << op) - 1);
  21450. //#ifdef INFLATE_STRICT
  21451. if (dist > dmax) {
  21452. strm.msg = 'invalid distance too far back';
  21453. state.mode = BAD;
  21454. break top;
  21455. }
  21456. //#endif
  21457. hold >>>= op;
  21458. bits -= op;
  21459. //Tracevv((stderr, "inflate: distance %u\n", dist));
  21460. op = _out - beg; /* max distance in output */
  21461. if (dist > op) { /* see if copy from window */
  21462. op = dist - op; /* distance back in window */
  21463. if (op > whave) {
  21464. if (state.sane) {
  21465. strm.msg = 'invalid distance too far back';
  21466. state.mode = BAD;
  21467. break top;
  21468. }
  21469. // (!) This block is disabled in zlib defailts,
  21470. // don't enable it for binary compatibility
  21471. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  21472. // if (len <= op - whave) {
  21473. // do {
  21474. // output[_out++] = 0;
  21475. // } while (--len);
  21476. // continue top;
  21477. // }
  21478. // len -= op - whave;
  21479. // do {
  21480. // output[_out++] = 0;
  21481. // } while (--op > whave);
  21482. // if (op === 0) {
  21483. // from = _out - dist;
  21484. // do {
  21485. // output[_out++] = output[from++];
  21486. // } while (--len);
  21487. // continue top;
  21488. // }
  21489. //#endif
  21490. }
  21491. from = 0; // window index
  21492. from_source = window;
  21493. if (wnext === 0) { /* very common case */
  21494. from += wsize - op;
  21495. if (op < len) { /* some from window */
  21496. len -= op;
  21497. do {
  21498. output[_out++] = window[from++];
  21499. } while (--op);
  21500. from = _out - dist; /* rest from output */
  21501. from_source = output;
  21502. }
  21503. }
  21504. else if (wnext < op) { /* wrap around window */
  21505. from += wsize + wnext - op;
  21506. op -= wnext;
  21507. if (op < len) { /* some from end of window */
  21508. len -= op;
  21509. do {
  21510. output[_out++] = window[from++];
  21511. } while (--op);
  21512. from = 0;
  21513. if (wnext < len) { /* some from start of window */
  21514. op = wnext;
  21515. len -= op;
  21516. do {
  21517. output[_out++] = window[from++];
  21518. } while (--op);
  21519. from = _out - dist; /* rest from output */
  21520. from_source = output;
  21521. }
  21522. }
  21523. }
  21524. else { /* contiguous in window */
  21525. from += wnext - op;
  21526. if (op < len) { /* some from window */
  21527. len -= op;
  21528. do {
  21529. output[_out++] = window[from++];
  21530. } while (--op);
  21531. from = _out - dist; /* rest from output */
  21532. from_source = output;
  21533. }
  21534. }
  21535. while (len > 2) {
  21536. output[_out++] = from_source[from++];
  21537. output[_out++] = from_source[from++];
  21538. output[_out++] = from_source[from++];
  21539. len -= 3;
  21540. }
  21541. if (len) {
  21542. output[_out++] = from_source[from++];
  21543. if (len > 1) {
  21544. output[_out++] = from_source[from++];
  21545. }
  21546. }
  21547. }
  21548. else {
  21549. from = _out - dist; /* copy direct from output */
  21550. do { /* minimum length is three */
  21551. output[_out++] = output[from++];
  21552. output[_out++] = output[from++];
  21553. output[_out++] = output[from++];
  21554. len -= 3;
  21555. } while (len > 2);
  21556. if (len) {
  21557. output[_out++] = output[from++];
  21558. if (len > 1) {
  21559. output[_out++] = output[from++];
  21560. }
  21561. }
  21562. }
  21563. }
  21564. else if ((op & 64) === 0) { /* 2nd level distance code */
  21565. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  21566. continue dodist;
  21567. }
  21568. else {
  21569. strm.msg = 'invalid distance code';
  21570. state.mode = BAD;
  21571. break top;
  21572. }
  21573. break; // need to emulate goto via "continue"
  21574. }
  21575. }
  21576. else if ((op & 64) === 0) { /* 2nd level length code */
  21577. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  21578. continue dolen;
  21579. }
  21580. else if (op & 32) { /* end-of-block */
  21581. //Tracevv((stderr, "inflate: end of block\n"));
  21582. state.mode = TYPE;
  21583. break top;
  21584. }
  21585. else {
  21586. strm.msg = 'invalid literal/length code';
  21587. state.mode = BAD;
  21588. break top;
  21589. }
  21590. break; // need to emulate goto via "continue"
  21591. }
  21592. } while (_in < last && _out < end);
  21593. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  21594. len = bits >> 3;
  21595. _in -= len;
  21596. bits -= len << 3;
  21597. hold &= (1 << bits) - 1;
  21598. /* update state and return */
  21599. strm.next_in = _in;
  21600. strm.next_out = _out;
  21601. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  21602. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  21603. state.hold = hold;
  21604. state.bits = bits;
  21605. return;
  21606. };
  21607. },{}],78:[function(require,module,exports){
  21608. 'use strict';
  21609. var utils = require('../utils/common');
  21610. var adler32 = require('./adler32');
  21611. var crc32 = require('./crc32');
  21612. var inflate_fast = require('./inffast');
  21613. var inflate_table = require('./inftrees');
  21614. var CODES = 0;
  21615. var LENS = 1;
  21616. var DISTS = 2;
  21617. /* Public constants ==========================================================*/
  21618. /* ===========================================================================*/
  21619. /* Allowed flush values; see deflate() and inflate() below for details */
  21620. //var Z_NO_FLUSH = 0;
  21621. //var Z_PARTIAL_FLUSH = 1;
  21622. //var Z_SYNC_FLUSH = 2;
  21623. //var Z_FULL_FLUSH = 3;
  21624. var Z_FINISH = 4;
  21625. var Z_BLOCK = 5;
  21626. var Z_TREES = 6;
  21627. /* Return codes for the compression/decompression functions. Negative values
  21628. * are errors, positive values are used for special but normal events.
  21629. */
  21630. var Z_OK = 0;
  21631. var Z_STREAM_END = 1;
  21632. var Z_NEED_DICT = 2;
  21633. //var Z_ERRNO = -1;
  21634. var Z_STREAM_ERROR = -2;
  21635. var Z_DATA_ERROR = -3;
  21636. var Z_MEM_ERROR = -4;
  21637. var Z_BUF_ERROR = -5;
  21638. //var Z_VERSION_ERROR = -6;
  21639. /* The deflate compression method */
  21640. var Z_DEFLATED = 8;
  21641. /* STATES ====================================================================*/
  21642. /* ===========================================================================*/
  21643. var HEAD = 1; /* i: waiting for magic header */
  21644. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  21645. var TIME = 3; /* i: waiting for modification time (gzip) */
  21646. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  21647. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  21648. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  21649. var NAME = 7; /* i: waiting for end of file name (gzip) */
  21650. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  21651. var HCRC = 9; /* i: waiting for header crc (gzip) */
  21652. var DICTID = 10; /* i: waiting for dictionary check value */
  21653. var DICT = 11; /* waiting for inflateSetDictionary() call */
  21654. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  21655. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  21656. var STORED = 14; /* i: waiting for stored size (length and complement) */
  21657. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  21658. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  21659. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  21660. var LENLENS = 18; /* i: waiting for code length code lengths */
  21661. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  21662. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  21663. var LEN = 21; /* i: waiting for length/lit/eob code */
  21664. var LENEXT = 22; /* i: waiting for length extra bits */
  21665. var DIST = 23; /* i: waiting for distance code */
  21666. var DISTEXT = 24; /* i: waiting for distance extra bits */
  21667. var MATCH = 25; /* o: waiting for output space to copy string */
  21668. var LIT = 26; /* o: waiting for output space to write literal */
  21669. var CHECK = 27; /* i: waiting for 32-bit check value */
  21670. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  21671. var DONE = 29; /* finished check, done -- remain here until reset */
  21672. var BAD = 30; /* got a data error -- remain here until reset */
  21673. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  21674. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  21675. /* ===========================================================================*/
  21676. var ENOUGH_LENS = 852;
  21677. var ENOUGH_DISTS = 592;
  21678. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  21679. var MAX_WBITS = 15;
  21680. /* 32K LZ77 window */
  21681. var DEF_WBITS = MAX_WBITS;
  21682. function ZSWAP32(q) {
  21683. return (((q >>> 24) & 0xff) +
  21684. ((q >>> 8) & 0xff00) +
  21685. ((q & 0xff00) << 8) +
  21686. ((q & 0xff) << 24));
  21687. }
  21688. function InflateState() {
  21689. this.mode = 0; /* current inflate mode */
  21690. this.last = false; /* true if processing last block */
  21691. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21692. this.havedict = false; /* true if dictionary provided */
  21693. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  21694. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  21695. this.check = 0; /* protected copy of check value */
  21696. this.total = 0; /* protected copy of output count */
  21697. // TODO: may be {}
  21698. this.head = null; /* where to save gzip header information */
  21699. /* sliding window */
  21700. this.wbits = 0; /* log base 2 of requested window size */
  21701. this.wsize = 0; /* window size or zero if not using window */
  21702. this.whave = 0; /* valid bytes in the window */
  21703. this.wnext = 0; /* window write index */
  21704. this.window = null; /* allocated sliding window, if needed */
  21705. /* bit accumulator */
  21706. this.hold = 0; /* input bit accumulator */
  21707. this.bits = 0; /* number of bits in "in" */
  21708. /* for string and stored block copying */
  21709. this.length = 0; /* literal or length of data to copy */
  21710. this.offset = 0; /* distance back to copy string from */
  21711. /* for table and code decoding */
  21712. this.extra = 0; /* extra bits needed */
  21713. /* fixed and dynamic code tables */
  21714. this.lencode = null; /* starting table for length/literal codes */
  21715. this.distcode = null; /* starting table for distance codes */
  21716. this.lenbits = 0; /* index bits for lencode */
  21717. this.distbits = 0; /* index bits for distcode */
  21718. /* dynamic table building */
  21719. this.ncode = 0; /* number of code length code lengths */
  21720. this.nlen = 0; /* number of length code lengths */
  21721. this.ndist = 0; /* number of distance code lengths */
  21722. this.have = 0; /* number of code lengths in lens[] */
  21723. this.next = null; /* next available space in codes[] */
  21724. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  21725. this.work = new utils.Buf16(288); /* work area for code table building */
  21726. /*
  21727. because we don't have pointers in js, we use lencode and distcode directly
  21728. as buffers so we don't need codes
  21729. */
  21730. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  21731. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  21732. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  21733. this.sane = 0; /* if false, allow invalid distance too far */
  21734. this.back = 0; /* bits back of last unprocessed length/lit */
  21735. this.was = 0; /* initial length of match */
  21736. }
  21737. function inflateResetKeep(strm) {
  21738. var state;
  21739. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21740. state = strm.state;
  21741. strm.total_in = strm.total_out = state.total = 0;
  21742. strm.msg = ''; /*Z_NULL*/
  21743. if (state.wrap) { /* to support ill-conceived Java test suite */
  21744. strm.adler = state.wrap & 1;
  21745. }
  21746. state.mode = HEAD;
  21747. state.last = 0;
  21748. state.havedict = 0;
  21749. state.dmax = 32768;
  21750. state.head = null/*Z_NULL*/;
  21751. state.hold = 0;
  21752. state.bits = 0;
  21753. //state.lencode = state.distcode = state.next = state.codes;
  21754. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  21755. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  21756. state.sane = 1;
  21757. state.back = -1;
  21758. //Tracev((stderr, "inflate: reset\n"));
  21759. return Z_OK;
  21760. }
  21761. function inflateReset(strm) {
  21762. var state;
  21763. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21764. state = strm.state;
  21765. state.wsize = 0;
  21766. state.whave = 0;
  21767. state.wnext = 0;
  21768. return inflateResetKeep(strm);
  21769. }
  21770. function inflateReset2(strm, windowBits) {
  21771. var wrap;
  21772. var state;
  21773. /* get the state */
  21774. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21775. state = strm.state;
  21776. /* extract wrap request from windowBits parameter */
  21777. if (windowBits < 0) {
  21778. wrap = 0;
  21779. windowBits = -windowBits;
  21780. }
  21781. else {
  21782. wrap = (windowBits >> 4) + 1;
  21783. if (windowBits < 48) {
  21784. windowBits &= 15;
  21785. }
  21786. }
  21787. /* set number of window bits, free window if different */
  21788. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  21789. return Z_STREAM_ERROR;
  21790. }
  21791. if (state.window !== null && state.wbits !== windowBits) {
  21792. state.window = null;
  21793. }
  21794. /* update state and reset the rest of it */
  21795. state.wrap = wrap;
  21796. state.wbits = windowBits;
  21797. return inflateReset(strm);
  21798. }
  21799. function inflateInit2(strm, windowBits) {
  21800. var ret;
  21801. var state;
  21802. if (!strm) { return Z_STREAM_ERROR; }
  21803. //strm.msg = Z_NULL; /* in case we return an error */
  21804. state = new InflateState();
  21805. //if (state === Z_NULL) return Z_MEM_ERROR;
  21806. //Tracev((stderr, "inflate: allocated\n"));
  21807. strm.state = state;
  21808. state.window = null/*Z_NULL*/;
  21809. ret = inflateReset2(strm, windowBits);
  21810. if (ret !== Z_OK) {
  21811. strm.state = null/*Z_NULL*/;
  21812. }
  21813. return ret;
  21814. }
  21815. function inflateInit(strm) {
  21816. return inflateInit2(strm, DEF_WBITS);
  21817. }
  21818. /*
  21819. Return state with length and distance decoding tables and index sizes set to
  21820. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  21821. If BUILDFIXED is defined, then instead this routine builds the tables the
  21822. first time it's called, and returns those tables the first time and
  21823. thereafter. This reduces the size of the code by about 2K bytes, in
  21824. exchange for a little execution time. However, BUILDFIXED should not be
  21825. used for threaded applications, since the rewriting of the tables and virgin
  21826. may not be thread-safe.
  21827. */
  21828. var virgin = true;
  21829. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  21830. function fixedtables(state) {
  21831. /* build fixed huffman tables if first call (may not be thread safe) */
  21832. if (virgin) {
  21833. var sym;
  21834. lenfix = new utils.Buf32(512);
  21835. distfix = new utils.Buf32(32);
  21836. /* literal/length table */
  21837. sym = 0;
  21838. while (sym < 144) { state.lens[sym++] = 8; }
  21839. while (sym < 256) { state.lens[sym++] = 9; }
  21840. while (sym < 280) { state.lens[sym++] = 7; }
  21841. while (sym < 288) { state.lens[sym++] = 8; }
  21842. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  21843. /* distance table */
  21844. sym = 0;
  21845. while (sym < 32) { state.lens[sym++] = 5; }
  21846. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  21847. /* do this just once */
  21848. virgin = false;
  21849. }
  21850. state.lencode = lenfix;
  21851. state.lenbits = 9;
  21852. state.distcode = distfix;
  21853. state.distbits = 5;
  21854. }
  21855. /*
  21856. Update the window with the last wsize (normally 32K) bytes written before
  21857. returning. If window does not exist yet, create it. This is only called
  21858. when a window is already in use, or when output has been written during this
  21859. inflate call, but the end of the deflate stream has not been reached yet.
  21860. It is also called to create a window for dictionary data when a dictionary
  21861. is loaded.
  21862. Providing output buffers larger than 32K to inflate() should provide a speed
  21863. advantage, since only the last 32K of output is copied to the sliding window
  21864. upon return from inflate(), and since all distances after the first 32K of
  21865. output will fall in the output data, making match copies simpler and faster.
  21866. The advantage may be dependent on the size of the processor's data caches.
  21867. */
  21868. function updatewindow(strm, src, end, copy) {
  21869. var dist;
  21870. var state = strm.state;
  21871. /* if it hasn't been done already, allocate space for the window */
  21872. if (state.window === null) {
  21873. state.wsize = 1 << state.wbits;
  21874. state.wnext = 0;
  21875. state.whave = 0;
  21876. state.window = new utils.Buf8(state.wsize);
  21877. }
  21878. /* copy state->wsize or less output bytes into the circular window */
  21879. if (copy >= state.wsize) {
  21880. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  21881. state.wnext = 0;
  21882. state.whave = state.wsize;
  21883. }
  21884. else {
  21885. dist = state.wsize - state.wnext;
  21886. if (dist > copy) {
  21887. dist = copy;
  21888. }
  21889. //zmemcpy(state->window + state->wnext, end - copy, dist);
  21890. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  21891. copy -= dist;
  21892. if (copy) {
  21893. //zmemcpy(state->window, end - copy, copy);
  21894. utils.arraySet(state.window,src, end - copy, copy, 0);
  21895. state.wnext = copy;
  21896. state.whave = state.wsize;
  21897. }
  21898. else {
  21899. state.wnext += dist;
  21900. if (state.wnext === state.wsize) { state.wnext = 0; }
  21901. if (state.whave < state.wsize) { state.whave += dist; }
  21902. }
  21903. }
  21904. return 0;
  21905. }
  21906. function inflate(strm, flush) {
  21907. var state;
  21908. var input, output; // input/output buffers
  21909. var next; /* next input INDEX */
  21910. var put; /* next output INDEX */
  21911. var have, left; /* available input and output */
  21912. var hold; /* bit buffer */
  21913. var bits; /* bits in bit buffer */
  21914. var _in, _out; /* save starting available input and output */
  21915. var copy; /* number of stored or match bytes to copy */
  21916. var from; /* where to copy match bytes from */
  21917. var from_source;
  21918. var here = 0; /* current decoding table entry */
  21919. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  21920. //var last; /* parent table entry */
  21921. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  21922. var len; /* length to copy for repeats, bits to drop */
  21923. var ret; /* return code */
  21924. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  21925. var opts;
  21926. var n; // temporary var for NEED_BITS
  21927. var order = /* permutation of code lengths */
  21928. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  21929. if (!strm || !strm.state || !strm.output ||
  21930. (!strm.input && strm.avail_in !== 0)) {
  21931. return Z_STREAM_ERROR;
  21932. }
  21933. state = strm.state;
  21934. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  21935. //--- LOAD() ---
  21936. put = strm.next_out;
  21937. output = strm.output;
  21938. left = strm.avail_out;
  21939. next = strm.next_in;
  21940. input = strm.input;
  21941. have = strm.avail_in;
  21942. hold = state.hold;
  21943. bits = state.bits;
  21944. //---
  21945. _in = have;
  21946. _out = left;
  21947. ret = Z_OK;
  21948. inf_leave: // goto emulation
  21949. for (;;) {
  21950. switch (state.mode) {
  21951. case HEAD:
  21952. if (state.wrap === 0) {
  21953. state.mode = TYPEDO;
  21954. break;
  21955. }
  21956. //=== NEEDBITS(16);
  21957. while (bits < 16) {
  21958. if (have === 0) { break inf_leave; }
  21959. have--;
  21960. hold += input[next++] << bits;
  21961. bits += 8;
  21962. }
  21963. //===//
  21964. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  21965. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  21966. //=== CRC2(state.check, hold);
  21967. hbuf[0] = hold & 0xff;
  21968. hbuf[1] = (hold >>> 8) & 0xff;
  21969. state.check = crc32(state.check, hbuf, 2, 0);
  21970. //===//
  21971. //=== INITBITS();
  21972. hold = 0;
  21973. bits = 0;
  21974. //===//
  21975. state.mode = FLAGS;
  21976. break;
  21977. }
  21978. state.flags = 0; /* expect zlib header */
  21979. if (state.head) {
  21980. state.head.done = false;
  21981. }
  21982. if (!(state.wrap & 1) || /* check if zlib header allowed */
  21983. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  21984. strm.msg = 'incorrect header check';
  21985. state.mode = BAD;
  21986. break;
  21987. }
  21988. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  21989. strm.msg = 'unknown compression method';
  21990. state.mode = BAD;
  21991. break;
  21992. }
  21993. //--- DROPBITS(4) ---//
  21994. hold >>>= 4;
  21995. bits -= 4;
  21996. //---//
  21997. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  21998. if (state.wbits === 0) {
  21999. state.wbits = len;
  22000. }
  22001. else if (len > state.wbits) {
  22002. strm.msg = 'invalid window size';
  22003. state.mode = BAD;
  22004. break;
  22005. }
  22006. state.dmax = 1 << len;
  22007. //Tracev((stderr, "inflate: zlib header ok\n"));
  22008. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22009. state.mode = hold & 0x200 ? DICTID : TYPE;
  22010. //=== INITBITS();
  22011. hold = 0;
  22012. bits = 0;
  22013. //===//
  22014. break;
  22015. case FLAGS:
  22016. //=== NEEDBITS(16); */
  22017. while (bits < 16) {
  22018. if (have === 0) { break inf_leave; }
  22019. have--;
  22020. hold += input[next++] << bits;
  22021. bits += 8;
  22022. }
  22023. //===//
  22024. state.flags = hold;
  22025. if ((state.flags & 0xff) !== Z_DEFLATED) {
  22026. strm.msg = 'unknown compression method';
  22027. state.mode = BAD;
  22028. break;
  22029. }
  22030. if (state.flags & 0xe000) {
  22031. strm.msg = 'unknown header flags set';
  22032. state.mode = BAD;
  22033. break;
  22034. }
  22035. if (state.head) {
  22036. state.head.text = ((hold >> 8) & 1);
  22037. }
  22038. if (state.flags & 0x0200) {
  22039. //=== CRC2(state.check, hold);
  22040. hbuf[0] = hold & 0xff;
  22041. hbuf[1] = (hold >>> 8) & 0xff;
  22042. state.check = crc32(state.check, hbuf, 2, 0);
  22043. //===//
  22044. }
  22045. //=== INITBITS();
  22046. hold = 0;
  22047. bits = 0;
  22048. //===//
  22049. state.mode = TIME;
  22050. /* falls through */
  22051. case TIME:
  22052. //=== NEEDBITS(32); */
  22053. while (bits < 32) {
  22054. if (have === 0) { break inf_leave; }
  22055. have--;
  22056. hold += input[next++] << bits;
  22057. bits += 8;
  22058. }
  22059. //===//
  22060. if (state.head) {
  22061. state.head.time = hold;
  22062. }
  22063. if (state.flags & 0x0200) {
  22064. //=== CRC4(state.check, hold)
  22065. hbuf[0] = hold & 0xff;
  22066. hbuf[1] = (hold >>> 8) & 0xff;
  22067. hbuf[2] = (hold >>> 16) & 0xff;
  22068. hbuf[3] = (hold >>> 24) & 0xff;
  22069. state.check = crc32(state.check, hbuf, 4, 0);
  22070. //===
  22071. }
  22072. //=== INITBITS();
  22073. hold = 0;
  22074. bits = 0;
  22075. //===//
  22076. state.mode = OS;
  22077. /* falls through */
  22078. case OS:
  22079. //=== NEEDBITS(16); */
  22080. while (bits < 16) {
  22081. if (have === 0) { break inf_leave; }
  22082. have--;
  22083. hold += input[next++] << bits;
  22084. bits += 8;
  22085. }
  22086. //===//
  22087. if (state.head) {
  22088. state.head.xflags = (hold & 0xff);
  22089. state.head.os = (hold >> 8);
  22090. }
  22091. if (state.flags & 0x0200) {
  22092. //=== CRC2(state.check, hold);
  22093. hbuf[0] = hold & 0xff;
  22094. hbuf[1] = (hold >>> 8) & 0xff;
  22095. state.check = crc32(state.check, hbuf, 2, 0);
  22096. //===//
  22097. }
  22098. //=== INITBITS();
  22099. hold = 0;
  22100. bits = 0;
  22101. //===//
  22102. state.mode = EXLEN;
  22103. /* falls through */
  22104. case EXLEN:
  22105. if (state.flags & 0x0400) {
  22106. //=== NEEDBITS(16); */
  22107. while (bits < 16) {
  22108. if (have === 0) { break inf_leave; }
  22109. have--;
  22110. hold += input[next++] << bits;
  22111. bits += 8;
  22112. }
  22113. //===//
  22114. state.length = hold;
  22115. if (state.head) {
  22116. state.head.extra_len = hold;
  22117. }
  22118. if (state.flags & 0x0200) {
  22119. //=== CRC2(state.check, hold);
  22120. hbuf[0] = hold & 0xff;
  22121. hbuf[1] = (hold >>> 8) & 0xff;
  22122. state.check = crc32(state.check, hbuf, 2, 0);
  22123. //===//
  22124. }
  22125. //=== INITBITS();
  22126. hold = 0;
  22127. bits = 0;
  22128. //===//
  22129. }
  22130. else if (state.head) {
  22131. state.head.extra = null/*Z_NULL*/;
  22132. }
  22133. state.mode = EXTRA;
  22134. /* falls through */
  22135. case EXTRA:
  22136. if (state.flags & 0x0400) {
  22137. copy = state.length;
  22138. if (copy > have) { copy = have; }
  22139. if (copy) {
  22140. if (state.head) {
  22141. len = state.head.extra_len - state.length;
  22142. if (!state.head.extra) {
  22143. // Use untyped array for more conveniend processing later
  22144. state.head.extra = new Array(state.head.extra_len);
  22145. }
  22146. utils.arraySet(
  22147. state.head.extra,
  22148. input,
  22149. next,
  22150. // extra field is limited to 65536 bytes
  22151. // - no need for additional size check
  22152. copy,
  22153. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  22154. len
  22155. );
  22156. //zmemcpy(state.head.extra + len, next,
  22157. // len + copy > state.head.extra_max ?
  22158. // state.head.extra_max - len : copy);
  22159. }
  22160. if (state.flags & 0x0200) {
  22161. state.check = crc32(state.check, input, copy, next);
  22162. }
  22163. have -= copy;
  22164. next += copy;
  22165. state.length -= copy;
  22166. }
  22167. if (state.length) { break inf_leave; }
  22168. }
  22169. state.length = 0;
  22170. state.mode = NAME;
  22171. /* falls through */
  22172. case NAME:
  22173. if (state.flags & 0x0800) {
  22174. if (have === 0) { break inf_leave; }
  22175. copy = 0;
  22176. do {
  22177. // TODO: 2 or 1 bytes?
  22178. len = input[next + copy++];
  22179. /* use constant limit because in js we should not preallocate memory */
  22180. if (state.head && len &&
  22181. (state.length < 65536 /*state.head.name_max*/)) {
  22182. state.head.name += String.fromCharCode(len);
  22183. }
  22184. } while (len && copy < have);
  22185. if (state.flags & 0x0200) {
  22186. state.check = crc32(state.check, input, copy, next);
  22187. }
  22188. have -= copy;
  22189. next += copy;
  22190. if (len) { break inf_leave; }
  22191. }
  22192. else if (state.head) {
  22193. state.head.name = null;
  22194. }
  22195. state.length = 0;
  22196. state.mode = COMMENT;
  22197. /* falls through */
  22198. case COMMENT:
  22199. if (state.flags & 0x1000) {
  22200. if (have === 0) { break inf_leave; }
  22201. copy = 0;
  22202. do {
  22203. len = input[next + copy++];
  22204. /* use constant limit because in js we should not preallocate memory */
  22205. if (state.head && len &&
  22206. (state.length < 65536 /*state.head.comm_max*/)) {
  22207. state.head.comment += String.fromCharCode(len);
  22208. }
  22209. } while (len && copy < have);
  22210. if (state.flags & 0x0200) {
  22211. state.check = crc32(state.check, input, copy, next);
  22212. }
  22213. have -= copy;
  22214. next += copy;
  22215. if (len) { break inf_leave; }
  22216. }
  22217. else if (state.head) {
  22218. state.head.comment = null;
  22219. }
  22220. state.mode = HCRC;
  22221. /* falls through */
  22222. case HCRC:
  22223. if (state.flags & 0x0200) {
  22224. //=== NEEDBITS(16); */
  22225. while (bits < 16) {
  22226. if (have === 0) { break inf_leave; }
  22227. have--;
  22228. hold += input[next++] << bits;
  22229. bits += 8;
  22230. }
  22231. //===//
  22232. if (hold !== (state.check & 0xffff)) {
  22233. strm.msg = 'header crc mismatch';
  22234. state.mode = BAD;
  22235. break;
  22236. }
  22237. //=== INITBITS();
  22238. hold = 0;
  22239. bits = 0;
  22240. //===//
  22241. }
  22242. if (state.head) {
  22243. state.head.hcrc = ((state.flags >> 9) & 1);
  22244. state.head.done = true;
  22245. }
  22246. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  22247. state.mode = TYPE;
  22248. break;
  22249. case DICTID:
  22250. //=== NEEDBITS(32); */
  22251. while (bits < 32) {
  22252. if (have === 0) { break inf_leave; }
  22253. have--;
  22254. hold += input[next++] << bits;
  22255. bits += 8;
  22256. }
  22257. //===//
  22258. strm.adler = state.check = ZSWAP32(hold);
  22259. //=== INITBITS();
  22260. hold = 0;
  22261. bits = 0;
  22262. //===//
  22263. state.mode = DICT;
  22264. /* falls through */
  22265. case DICT:
  22266. if (state.havedict === 0) {
  22267. //--- RESTORE() ---
  22268. strm.next_out = put;
  22269. strm.avail_out = left;
  22270. strm.next_in = next;
  22271. strm.avail_in = have;
  22272. state.hold = hold;
  22273. state.bits = bits;
  22274. //---
  22275. return Z_NEED_DICT;
  22276. }
  22277. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22278. state.mode = TYPE;
  22279. /* falls through */
  22280. case TYPE:
  22281. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  22282. /* falls through */
  22283. case TYPEDO:
  22284. if (state.last) {
  22285. //--- BYTEBITS() ---//
  22286. hold >>>= bits & 7;
  22287. bits -= bits & 7;
  22288. //---//
  22289. state.mode = CHECK;
  22290. break;
  22291. }
  22292. //=== NEEDBITS(3); */
  22293. while (bits < 3) {
  22294. if (have === 0) { break inf_leave; }
  22295. have--;
  22296. hold += input[next++] << bits;
  22297. bits += 8;
  22298. }
  22299. //===//
  22300. state.last = (hold & 0x01)/*BITS(1)*/;
  22301. //--- DROPBITS(1) ---//
  22302. hold >>>= 1;
  22303. bits -= 1;
  22304. //---//
  22305. switch ((hold & 0x03)/*BITS(2)*/) {
  22306. case 0: /* stored block */
  22307. //Tracev((stderr, "inflate: stored block%s\n",
  22308. // state.last ? " (last)" : ""));
  22309. state.mode = STORED;
  22310. break;
  22311. case 1: /* fixed block */
  22312. fixedtables(state);
  22313. //Tracev((stderr, "inflate: fixed codes block%s\n",
  22314. // state.last ? " (last)" : ""));
  22315. state.mode = LEN_; /* decode codes */
  22316. if (flush === Z_TREES) {
  22317. //--- DROPBITS(2) ---//
  22318. hold >>>= 2;
  22319. bits -= 2;
  22320. //---//
  22321. break inf_leave;
  22322. }
  22323. break;
  22324. case 2: /* dynamic block */
  22325. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  22326. // state.last ? " (last)" : ""));
  22327. state.mode = TABLE;
  22328. break;
  22329. case 3:
  22330. strm.msg = 'invalid block type';
  22331. state.mode = BAD;
  22332. }
  22333. //--- DROPBITS(2) ---//
  22334. hold >>>= 2;
  22335. bits -= 2;
  22336. //---//
  22337. break;
  22338. case STORED:
  22339. //--- BYTEBITS() ---// /* go to byte boundary */
  22340. hold >>>= bits & 7;
  22341. bits -= bits & 7;
  22342. //---//
  22343. //=== NEEDBITS(32); */
  22344. while (bits < 32) {
  22345. if (have === 0) { break inf_leave; }
  22346. have--;
  22347. hold += input[next++] << bits;
  22348. bits += 8;
  22349. }
  22350. //===//
  22351. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  22352. strm.msg = 'invalid stored block lengths';
  22353. state.mode = BAD;
  22354. break;
  22355. }
  22356. state.length = hold & 0xffff;
  22357. //Tracev((stderr, "inflate: stored length %u\n",
  22358. // state.length));
  22359. //=== INITBITS();
  22360. hold = 0;
  22361. bits = 0;
  22362. //===//
  22363. state.mode = COPY_;
  22364. if (flush === Z_TREES) { break inf_leave; }
  22365. /* falls through */
  22366. case COPY_:
  22367. state.mode = COPY;
  22368. /* falls through */
  22369. case COPY:
  22370. copy = state.length;
  22371. if (copy) {
  22372. if (copy > have) { copy = have; }
  22373. if (copy > left) { copy = left; }
  22374. if (copy === 0) { break inf_leave; }
  22375. //--- zmemcpy(put, next, copy); ---
  22376. utils.arraySet(output, input, next, copy, put);
  22377. //---//
  22378. have -= copy;
  22379. next += copy;
  22380. left -= copy;
  22381. put += copy;
  22382. state.length -= copy;
  22383. break;
  22384. }
  22385. //Tracev((stderr, "inflate: stored end\n"));
  22386. state.mode = TYPE;
  22387. break;
  22388. case TABLE:
  22389. //=== NEEDBITS(14); */
  22390. while (bits < 14) {
  22391. if (have === 0) { break inf_leave; }
  22392. have--;
  22393. hold += input[next++] << bits;
  22394. bits += 8;
  22395. }
  22396. //===//
  22397. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  22398. //--- DROPBITS(5) ---//
  22399. hold >>>= 5;
  22400. bits -= 5;
  22401. //---//
  22402. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  22403. //--- DROPBITS(5) ---//
  22404. hold >>>= 5;
  22405. bits -= 5;
  22406. //---//
  22407. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  22408. //--- DROPBITS(4) ---//
  22409. hold >>>= 4;
  22410. bits -= 4;
  22411. //---//
  22412. //#ifndef PKZIP_BUG_WORKAROUND
  22413. if (state.nlen > 286 || state.ndist > 30) {
  22414. strm.msg = 'too many length or distance symbols';
  22415. state.mode = BAD;
  22416. break;
  22417. }
  22418. //#endif
  22419. //Tracev((stderr, "inflate: table sizes ok\n"));
  22420. state.have = 0;
  22421. state.mode = LENLENS;
  22422. /* falls through */
  22423. case LENLENS:
  22424. while (state.have < state.ncode) {
  22425. //=== NEEDBITS(3);
  22426. while (bits < 3) {
  22427. if (have === 0) { break inf_leave; }
  22428. have--;
  22429. hold += input[next++] << bits;
  22430. bits += 8;
  22431. }
  22432. //===//
  22433. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  22434. //--- DROPBITS(3) ---//
  22435. hold >>>= 3;
  22436. bits -= 3;
  22437. //---//
  22438. }
  22439. while (state.have < 19) {
  22440. state.lens[order[state.have++]] = 0;
  22441. }
  22442. // We have separate tables & no pointers. 2 commented lines below not needed.
  22443. //state.next = state.codes;
  22444. //state.lencode = state.next;
  22445. // Switch to use dynamic table
  22446. state.lencode = state.lendyn;
  22447. state.lenbits = 7;
  22448. opts = {bits: state.lenbits};
  22449. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  22450. state.lenbits = opts.bits;
  22451. if (ret) {
  22452. strm.msg = 'invalid code lengths set';
  22453. state.mode = BAD;
  22454. break;
  22455. }
  22456. //Tracev((stderr, "inflate: code lengths ok\n"));
  22457. state.have = 0;
  22458. state.mode = CODELENS;
  22459. /* falls through */
  22460. case CODELENS:
  22461. while (state.have < state.nlen + state.ndist) {
  22462. for (;;) {
  22463. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  22464. here_bits = here >>> 24;
  22465. here_op = (here >>> 16) & 0xff;
  22466. here_val = here & 0xffff;
  22467. if ((here_bits) <= bits) { break; }
  22468. //--- PULLBYTE() ---//
  22469. if (have === 0) { break inf_leave; }
  22470. have--;
  22471. hold += input[next++] << bits;
  22472. bits += 8;
  22473. //---//
  22474. }
  22475. if (here_val < 16) {
  22476. //--- DROPBITS(here.bits) ---//
  22477. hold >>>= here_bits;
  22478. bits -= here_bits;
  22479. //---//
  22480. state.lens[state.have++] = here_val;
  22481. }
  22482. else {
  22483. if (here_val === 16) {
  22484. //=== NEEDBITS(here.bits + 2);
  22485. n = here_bits + 2;
  22486. while (bits < n) {
  22487. if (have === 0) { break inf_leave; }
  22488. have--;
  22489. hold += input[next++] << bits;
  22490. bits += 8;
  22491. }
  22492. //===//
  22493. //--- DROPBITS(here.bits) ---//
  22494. hold >>>= here_bits;
  22495. bits -= here_bits;
  22496. //---//
  22497. if (state.have === 0) {
  22498. strm.msg = 'invalid bit length repeat';
  22499. state.mode = BAD;
  22500. break;
  22501. }
  22502. len = state.lens[state.have - 1];
  22503. copy = 3 + (hold & 0x03);//BITS(2);
  22504. //--- DROPBITS(2) ---//
  22505. hold >>>= 2;
  22506. bits -= 2;
  22507. //---//
  22508. }
  22509. else if (here_val === 17) {
  22510. //=== NEEDBITS(here.bits + 3);
  22511. n = here_bits + 3;
  22512. while (bits < n) {
  22513. if (have === 0) { break inf_leave; }
  22514. have--;
  22515. hold += input[next++] << bits;
  22516. bits += 8;
  22517. }
  22518. //===//
  22519. //--- DROPBITS(here.bits) ---//
  22520. hold >>>= here_bits;
  22521. bits -= here_bits;
  22522. //---//
  22523. len = 0;
  22524. copy = 3 + (hold & 0x07);//BITS(3);
  22525. //--- DROPBITS(3) ---//
  22526. hold >>>= 3;
  22527. bits -= 3;
  22528. //---//
  22529. }
  22530. else {
  22531. //=== NEEDBITS(here.bits + 7);
  22532. n = here_bits + 7;
  22533. while (bits < n) {
  22534. if (have === 0) { break inf_leave; }
  22535. have--;
  22536. hold += input[next++] << bits;
  22537. bits += 8;
  22538. }
  22539. //===//
  22540. //--- DROPBITS(here.bits) ---//
  22541. hold >>>= here_bits;
  22542. bits -= here_bits;
  22543. //---//
  22544. len = 0;
  22545. copy = 11 + (hold & 0x7f);//BITS(7);
  22546. //--- DROPBITS(7) ---//
  22547. hold >>>= 7;
  22548. bits -= 7;
  22549. //---//
  22550. }
  22551. if (state.have + copy > state.nlen + state.ndist) {
  22552. strm.msg = 'invalid bit length repeat';
  22553. state.mode = BAD;
  22554. break;
  22555. }
  22556. while (copy--) {
  22557. state.lens[state.have++] = len;
  22558. }
  22559. }
  22560. }
  22561. /* handle error breaks in while */
  22562. if (state.mode === BAD) { break; }
  22563. /* check for end-of-block code (better have one) */
  22564. if (state.lens[256] === 0) {
  22565. strm.msg = 'invalid code -- missing end-of-block';
  22566. state.mode = BAD;
  22567. break;
  22568. }
  22569. /* build code tables -- note: do not change the lenbits or distbits
  22570. values here (9 and 6) without reading the comments in inftrees.h
  22571. concerning the ENOUGH constants, which depend on those values */
  22572. state.lenbits = 9;
  22573. opts = {bits: state.lenbits};
  22574. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  22575. // We have separate tables & no pointers. 2 commented lines below not needed.
  22576. // state.next_index = opts.table_index;
  22577. state.lenbits = opts.bits;
  22578. // state.lencode = state.next;
  22579. if (ret) {
  22580. strm.msg = 'invalid literal/lengths set';
  22581. state.mode = BAD;
  22582. break;
  22583. }
  22584. state.distbits = 6;
  22585. //state.distcode.copy(state.codes);
  22586. // Switch to use dynamic table
  22587. state.distcode = state.distdyn;
  22588. opts = {bits: state.distbits};
  22589. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  22590. // We have separate tables & no pointers. 2 commented lines below not needed.
  22591. // state.next_index = opts.table_index;
  22592. state.distbits = opts.bits;
  22593. // state.distcode = state.next;
  22594. if (ret) {
  22595. strm.msg = 'invalid distances set';
  22596. state.mode = BAD;
  22597. break;
  22598. }
  22599. //Tracev((stderr, 'inflate: codes ok\n'));
  22600. state.mode = LEN_;
  22601. if (flush === Z_TREES) { break inf_leave; }
  22602. /* falls through */
  22603. case LEN_:
  22604. state.mode = LEN;
  22605. /* falls through */
  22606. case LEN:
  22607. if (have >= 6 && left >= 258) {
  22608. //--- RESTORE() ---
  22609. strm.next_out = put;
  22610. strm.avail_out = left;
  22611. strm.next_in = next;
  22612. strm.avail_in = have;
  22613. state.hold = hold;
  22614. state.bits = bits;
  22615. //---
  22616. inflate_fast(strm, _out);
  22617. //--- LOAD() ---
  22618. put = strm.next_out;
  22619. output = strm.output;
  22620. left = strm.avail_out;
  22621. next = strm.next_in;
  22622. input = strm.input;
  22623. have = strm.avail_in;
  22624. hold = state.hold;
  22625. bits = state.bits;
  22626. //---
  22627. if (state.mode === TYPE) {
  22628. state.back = -1;
  22629. }
  22630. break;
  22631. }
  22632. state.back = 0;
  22633. for (;;) {
  22634. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  22635. here_bits = here >>> 24;
  22636. here_op = (here >>> 16) & 0xff;
  22637. here_val = here & 0xffff;
  22638. if (here_bits <= bits) { break; }
  22639. //--- PULLBYTE() ---//
  22640. if (have === 0) { break inf_leave; }
  22641. have--;
  22642. hold += input[next++] << bits;
  22643. bits += 8;
  22644. //---//
  22645. }
  22646. if (here_op && (here_op & 0xf0) === 0) {
  22647. last_bits = here_bits;
  22648. last_op = here_op;
  22649. last_val = here_val;
  22650. for (;;) {
  22651. here = state.lencode[last_val +
  22652. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  22653. here_bits = here >>> 24;
  22654. here_op = (here >>> 16) & 0xff;
  22655. here_val = here & 0xffff;
  22656. if ((last_bits + here_bits) <= bits) { break; }
  22657. //--- PULLBYTE() ---//
  22658. if (have === 0) { break inf_leave; }
  22659. have--;
  22660. hold += input[next++] << bits;
  22661. bits += 8;
  22662. //---//
  22663. }
  22664. //--- DROPBITS(last.bits) ---//
  22665. hold >>>= last_bits;
  22666. bits -= last_bits;
  22667. //---//
  22668. state.back += last_bits;
  22669. }
  22670. //--- DROPBITS(here.bits) ---//
  22671. hold >>>= here_bits;
  22672. bits -= here_bits;
  22673. //---//
  22674. state.back += here_bits;
  22675. state.length = here_val;
  22676. if (here_op === 0) {
  22677. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  22678. // "inflate: literal '%c'\n" :
  22679. // "inflate: literal 0x%02x\n", here.val));
  22680. state.mode = LIT;
  22681. break;
  22682. }
  22683. if (here_op & 32) {
  22684. //Tracevv((stderr, "inflate: end of block\n"));
  22685. state.back = -1;
  22686. state.mode = TYPE;
  22687. break;
  22688. }
  22689. if (here_op & 64) {
  22690. strm.msg = 'invalid literal/length code';
  22691. state.mode = BAD;
  22692. break;
  22693. }
  22694. state.extra = here_op & 15;
  22695. state.mode = LENEXT;
  22696. /* falls through */
  22697. case LENEXT:
  22698. if (state.extra) {
  22699. //=== NEEDBITS(state.extra);
  22700. n = state.extra;
  22701. while (bits < n) {
  22702. if (have === 0) { break inf_leave; }
  22703. have--;
  22704. hold += input[next++] << bits;
  22705. bits += 8;
  22706. }
  22707. //===//
  22708. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  22709. //--- DROPBITS(state.extra) ---//
  22710. hold >>>= state.extra;
  22711. bits -= state.extra;
  22712. //---//
  22713. state.back += state.extra;
  22714. }
  22715. //Tracevv((stderr, "inflate: length %u\n", state.length));
  22716. state.was = state.length;
  22717. state.mode = DIST;
  22718. /* falls through */
  22719. case DIST:
  22720. for (;;) {
  22721. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  22722. here_bits = here >>> 24;
  22723. here_op = (here >>> 16) & 0xff;
  22724. here_val = here & 0xffff;
  22725. if ((here_bits) <= bits) { break; }
  22726. //--- PULLBYTE() ---//
  22727. if (have === 0) { break inf_leave; }
  22728. have--;
  22729. hold += input[next++] << bits;
  22730. bits += 8;
  22731. //---//
  22732. }
  22733. if ((here_op & 0xf0) === 0) {
  22734. last_bits = here_bits;
  22735. last_op = here_op;
  22736. last_val = here_val;
  22737. for (;;) {
  22738. here = state.distcode[last_val +
  22739. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  22740. here_bits = here >>> 24;
  22741. here_op = (here >>> 16) & 0xff;
  22742. here_val = here & 0xffff;
  22743. if ((last_bits + here_bits) <= bits) { break; }
  22744. //--- PULLBYTE() ---//
  22745. if (have === 0) { break inf_leave; }
  22746. have--;
  22747. hold += input[next++] << bits;
  22748. bits += 8;
  22749. //---//
  22750. }
  22751. //--- DROPBITS(last.bits) ---//
  22752. hold >>>= last_bits;
  22753. bits -= last_bits;
  22754. //---//
  22755. state.back += last_bits;
  22756. }
  22757. //--- DROPBITS(here.bits) ---//
  22758. hold >>>= here_bits;
  22759. bits -= here_bits;
  22760. //---//
  22761. state.back += here_bits;
  22762. if (here_op & 64) {
  22763. strm.msg = 'invalid distance code';
  22764. state.mode = BAD;
  22765. break;
  22766. }
  22767. state.offset = here_val;
  22768. state.extra = (here_op) & 15;
  22769. state.mode = DISTEXT;
  22770. /* falls through */
  22771. case DISTEXT:
  22772. if (state.extra) {
  22773. //=== NEEDBITS(state.extra);
  22774. n = state.extra;
  22775. while (bits < n) {
  22776. if (have === 0) { break inf_leave; }
  22777. have--;
  22778. hold += input[next++] << bits;
  22779. bits += 8;
  22780. }
  22781. //===//
  22782. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  22783. //--- DROPBITS(state.extra) ---//
  22784. hold >>>= state.extra;
  22785. bits -= state.extra;
  22786. //---//
  22787. state.back += state.extra;
  22788. }
  22789. //#ifdef INFLATE_STRICT
  22790. if (state.offset > state.dmax) {
  22791. strm.msg = 'invalid distance too far back';
  22792. state.mode = BAD;
  22793. break;
  22794. }
  22795. //#endif
  22796. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  22797. state.mode = MATCH;
  22798. /* falls through */
  22799. case MATCH:
  22800. if (left === 0) { break inf_leave; }
  22801. copy = _out - left;
  22802. if (state.offset > copy) { /* copy from window */
  22803. copy = state.offset - copy;
  22804. if (copy > state.whave) {
  22805. if (state.sane) {
  22806. strm.msg = 'invalid distance too far back';
  22807. state.mode = BAD;
  22808. break;
  22809. }
  22810. // (!) This block is disabled in zlib defailts,
  22811. // don't enable it for binary compatibility
  22812. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  22813. // Trace((stderr, "inflate.c too far\n"));
  22814. // copy -= state.whave;
  22815. // if (copy > state.length) { copy = state.length; }
  22816. // if (copy > left) { copy = left; }
  22817. // left -= copy;
  22818. // state.length -= copy;
  22819. // do {
  22820. // output[put++] = 0;
  22821. // } while (--copy);
  22822. // if (state.length === 0) { state.mode = LEN; }
  22823. // break;
  22824. //#endif
  22825. }
  22826. if (copy > state.wnext) {
  22827. copy -= state.wnext;
  22828. from = state.wsize - copy;
  22829. }
  22830. else {
  22831. from = state.wnext - copy;
  22832. }
  22833. if (copy > state.length) { copy = state.length; }
  22834. from_source = state.window;
  22835. }
  22836. else { /* copy from output */
  22837. from_source = output;
  22838. from = put - state.offset;
  22839. copy = state.length;
  22840. }
  22841. if (copy > left) { copy = left; }
  22842. left -= copy;
  22843. state.length -= copy;
  22844. do {
  22845. output[put++] = from_source[from++];
  22846. } while (--copy);
  22847. if (state.length === 0) { state.mode = LEN; }
  22848. break;
  22849. case LIT:
  22850. if (left === 0) { break inf_leave; }
  22851. output[put++] = state.length;
  22852. left--;
  22853. state.mode = LEN;
  22854. break;
  22855. case CHECK:
  22856. if (state.wrap) {
  22857. //=== NEEDBITS(32);
  22858. while (bits < 32) {
  22859. if (have === 0) { break inf_leave; }
  22860. have--;
  22861. // Use '|' insdead of '+' to make sure that result is signed
  22862. hold |= input[next++] << bits;
  22863. bits += 8;
  22864. }
  22865. //===//
  22866. _out -= left;
  22867. strm.total_out += _out;
  22868. state.total += _out;
  22869. if (_out) {
  22870. strm.adler = state.check =
  22871. /*UPDATE(state.check, put - _out, _out);*/
  22872. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  22873. }
  22874. _out = left;
  22875. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  22876. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  22877. strm.msg = 'incorrect data check';
  22878. state.mode = BAD;
  22879. break;
  22880. }
  22881. //=== INITBITS();
  22882. hold = 0;
  22883. bits = 0;
  22884. //===//
  22885. //Tracev((stderr, "inflate: check matches trailer\n"));
  22886. }
  22887. state.mode = LENGTH;
  22888. /* falls through */
  22889. case LENGTH:
  22890. if (state.wrap && state.flags) {
  22891. //=== NEEDBITS(32);
  22892. while (bits < 32) {
  22893. if (have === 0) { break inf_leave; }
  22894. have--;
  22895. hold += input[next++] << bits;
  22896. bits += 8;
  22897. }
  22898. //===//
  22899. if (hold !== (state.total & 0xffffffff)) {
  22900. strm.msg = 'incorrect length check';
  22901. state.mode = BAD;
  22902. break;
  22903. }
  22904. //=== INITBITS();
  22905. hold = 0;
  22906. bits = 0;
  22907. //===//
  22908. //Tracev((stderr, "inflate: length matches trailer\n"));
  22909. }
  22910. state.mode = DONE;
  22911. /* falls through */
  22912. case DONE:
  22913. ret = Z_STREAM_END;
  22914. break inf_leave;
  22915. case BAD:
  22916. ret = Z_DATA_ERROR;
  22917. break inf_leave;
  22918. case MEM:
  22919. return Z_MEM_ERROR;
  22920. case SYNC:
  22921. /* falls through */
  22922. default:
  22923. return Z_STREAM_ERROR;
  22924. }
  22925. }
  22926. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  22927. /*
  22928. Return from inflate(), updating the total counts and the check value.
  22929. If there was no progress during the inflate() call, return a buffer
  22930. error. Call updatewindow() to create and/or update the window state.
  22931. Note: a memory error from inflate() is non-recoverable.
  22932. */
  22933. //--- RESTORE() ---
  22934. strm.next_out = put;
  22935. strm.avail_out = left;
  22936. strm.next_in = next;
  22937. strm.avail_in = have;
  22938. state.hold = hold;
  22939. state.bits = bits;
  22940. //---
  22941. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  22942. (state.mode < CHECK || flush !== Z_FINISH))) {
  22943. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  22944. state.mode = MEM;
  22945. return Z_MEM_ERROR;
  22946. }
  22947. }
  22948. _in -= strm.avail_in;
  22949. _out -= strm.avail_out;
  22950. strm.total_in += _in;
  22951. strm.total_out += _out;
  22952. state.total += _out;
  22953. if (state.wrap && _out) {
  22954. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  22955. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  22956. }
  22957. strm.data_type = state.bits + (state.last ? 64 : 0) +
  22958. (state.mode === TYPE ? 128 : 0) +
  22959. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  22960. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  22961. ret = Z_BUF_ERROR;
  22962. }
  22963. return ret;
  22964. }
  22965. function inflateEnd(strm) {
  22966. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  22967. return Z_STREAM_ERROR;
  22968. }
  22969. var state = strm.state;
  22970. if (state.window) {
  22971. state.window = null;
  22972. }
  22973. strm.state = null;
  22974. return Z_OK;
  22975. }
  22976. function inflateGetHeader(strm, head) {
  22977. var state;
  22978. /* check state */
  22979. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22980. state = strm.state;
  22981. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  22982. /* save header structure */
  22983. state.head = head;
  22984. head.done = false;
  22985. return Z_OK;
  22986. }
  22987. exports.inflateReset = inflateReset;
  22988. exports.inflateReset2 = inflateReset2;
  22989. exports.inflateResetKeep = inflateResetKeep;
  22990. exports.inflateInit = inflateInit;
  22991. exports.inflateInit2 = inflateInit2;
  22992. exports.inflate = inflate;
  22993. exports.inflateEnd = inflateEnd;
  22994. exports.inflateGetHeader = inflateGetHeader;
  22995. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  22996. /* Not implemented
  22997. exports.inflateCopy = inflateCopy;
  22998. exports.inflateGetDictionary = inflateGetDictionary;
  22999. exports.inflateMark = inflateMark;
  23000. exports.inflatePrime = inflatePrime;
  23001. exports.inflateSetDictionary = inflateSetDictionary;
  23002. exports.inflateSync = inflateSync;
  23003. exports.inflateSyncPoint = inflateSyncPoint;
  23004. exports.inflateUndermine = inflateUndermine;
  23005. */
  23006. },{"../utils/common":70,"./adler32":72,"./crc32":74,"./inffast":77,"./inftrees":79}],79:[function(require,module,exports){
  23007. 'use strict';
  23008. var utils = require('../utils/common');
  23009. var MAXBITS = 15;
  23010. var ENOUGH_LENS = 852;
  23011. var ENOUGH_DISTS = 592;
  23012. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  23013. var CODES = 0;
  23014. var LENS = 1;
  23015. var DISTS = 2;
  23016. var lbase = [ /* Length codes 257..285 base */
  23017. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  23018. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  23019. ];
  23020. var lext = [ /* Length codes 257..285 extra */
  23021. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  23022. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  23023. ];
  23024. var dbase = [ /* Distance codes 0..29 base */
  23025. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  23026. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  23027. 8193, 12289, 16385, 24577, 0, 0
  23028. ];
  23029. var dext = [ /* Distance codes 0..29 extra */
  23030. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  23031. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  23032. 28, 28, 29, 29, 64, 64
  23033. ];
  23034. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  23035. {
  23036. var bits = opts.bits;
  23037. //here = opts.here; /* table entry for duplication */
  23038. var len = 0; /* a code's length in bits */
  23039. var sym = 0; /* index of code symbols */
  23040. var min = 0, max = 0; /* minimum and maximum code lengths */
  23041. var root = 0; /* number of index bits for root table */
  23042. var curr = 0; /* number of index bits for current table */
  23043. var drop = 0; /* code bits to drop for sub-table */
  23044. var left = 0; /* number of prefix codes available */
  23045. var used = 0; /* code entries in table used */
  23046. var huff = 0; /* Huffman code */
  23047. var incr; /* for incrementing code, index */
  23048. var fill; /* index for replicating entries */
  23049. var low; /* low bits for current root entry */
  23050. var mask; /* mask for low root bits */
  23051. var next; /* next available space in table */
  23052. var base = null; /* base value table to use */
  23053. var base_index = 0;
  23054. // var shoextra; /* extra bits table to use */
  23055. var end; /* use base and extra for symbol > end */
  23056. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  23057. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  23058. var extra = null;
  23059. var extra_index = 0;
  23060. var here_bits, here_op, here_val;
  23061. /*
  23062. Process a set of code lengths to create a canonical Huffman code. The
  23063. code lengths are lens[0..codes-1]. Each length corresponds to the
  23064. symbols 0..codes-1. The Huffman code is generated by first sorting the
  23065. symbols by length from short to long, and retaining the symbol order
  23066. for codes with equal lengths. Then the code starts with all zero bits
  23067. for the first code of the shortest length, and the codes are integer
  23068. increments for the same length, and zeros are appended as the length
  23069. increases. For the deflate format, these bits are stored backwards
  23070. from their more natural integer increment ordering, and so when the
  23071. decoding tables are built in the large loop below, the integer codes
  23072. are incremented backwards.
  23073. This routine assumes, but does not check, that all of the entries in
  23074. lens[] are in the range 0..MAXBITS. The caller must assure this.
  23075. 1..MAXBITS is interpreted as that code length. zero means that that
  23076. symbol does not occur in this code.
  23077. The codes are sorted by computing a count of codes for each length,
  23078. creating from that a table of starting indices for each length in the
  23079. sorted table, and then entering the symbols in order in the sorted
  23080. table. The sorted table is work[], with that space being provided by
  23081. the caller.
  23082. The length counts are used for other purposes as well, i.e. finding
  23083. the minimum and maximum length codes, determining if there are any
  23084. codes at all, checking for a valid set of lengths, and looking ahead
  23085. at length counts to determine sub-table sizes when building the
  23086. decoding tables.
  23087. */
  23088. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  23089. for (len = 0; len <= MAXBITS; len++) {
  23090. count[len] = 0;
  23091. }
  23092. for (sym = 0; sym < codes; sym++) {
  23093. count[lens[lens_index + sym]]++;
  23094. }
  23095. /* bound code lengths, force root to be within code lengths */
  23096. root = bits;
  23097. for (max = MAXBITS; max >= 1; max--) {
  23098. if (count[max] !== 0) { break; }
  23099. }
  23100. if (root > max) {
  23101. root = max;
  23102. }
  23103. if (max === 0) { /* no symbols to code at all */
  23104. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  23105. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  23106. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  23107. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23108. //table.op[opts.table_index] = 64;
  23109. //table.bits[opts.table_index] = 1;
  23110. //table.val[opts.table_index++] = 0;
  23111. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23112. opts.bits = 1;
  23113. return 0; /* no symbols, but wait for decoding to report error */
  23114. }
  23115. for (min = 1; min < max; min++) {
  23116. if (count[min] !== 0) { break; }
  23117. }
  23118. if (root < min) {
  23119. root = min;
  23120. }
  23121. /* check for an over-subscribed or incomplete set of lengths */
  23122. left = 1;
  23123. for (len = 1; len <= MAXBITS; len++) {
  23124. left <<= 1;
  23125. left -= count[len];
  23126. if (left < 0) {
  23127. return -1;
  23128. } /* over-subscribed */
  23129. }
  23130. if (left > 0 && (type === CODES || max !== 1)) {
  23131. return -1; /* incomplete set */
  23132. }
  23133. /* generate offsets into symbol table for each length for sorting */
  23134. offs[1] = 0;
  23135. for (len = 1; len < MAXBITS; len++) {
  23136. offs[len + 1] = offs[len] + count[len];
  23137. }
  23138. /* sort symbols by length, by symbol order within each length */
  23139. for (sym = 0; sym < codes; sym++) {
  23140. if (lens[lens_index + sym] !== 0) {
  23141. work[offs[lens[lens_index + sym]]++] = sym;
  23142. }
  23143. }
  23144. /*
  23145. Create and fill in decoding tables. In this loop, the table being
  23146. filled is at next and has curr index bits. The code being used is huff
  23147. with length len. That code is converted to an index by dropping drop
  23148. bits off of the bottom. For codes where len is less than drop + curr,
  23149. those top drop + curr - len bits are incremented through all values to
  23150. fill the table with replicated entries.
  23151. root is the number of index bits for the root table. When len exceeds
  23152. root, sub-tables are created pointed to by the root entry with an index
  23153. of the low root bits of huff. This is saved in low to check for when a
  23154. new sub-table should be started. drop is zero when the root table is
  23155. being filled, and drop is root when sub-tables are being filled.
  23156. When a new sub-table is needed, it is necessary to look ahead in the
  23157. code lengths to determine what size sub-table is needed. The length
  23158. counts are used for this, and so count[] is decremented as codes are
  23159. entered in the tables.
  23160. used keeps track of how many table entries have been allocated from the
  23161. provided *table space. It is checked for LENS and DIST tables against
  23162. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  23163. the initial root table size constants. See the comments in inftrees.h
  23164. for more information.
  23165. sym increments through all symbols, and the loop terminates when
  23166. all codes of length max, i.e. all codes, have been processed. This
  23167. routine permits incomplete codes, so another loop after this one fills
  23168. in the rest of the decoding tables with invalid code markers.
  23169. */
  23170. /* set up for code type */
  23171. // poor man optimization - use if-else instead of switch,
  23172. // to avoid deopts in old v8
  23173. if (type === CODES) {
  23174. base = extra = work; /* dummy value--not used */
  23175. end = 19;
  23176. } else if (type === LENS) {
  23177. base = lbase;
  23178. base_index -= 257;
  23179. extra = lext;
  23180. extra_index -= 257;
  23181. end = 256;
  23182. } else { /* DISTS */
  23183. base = dbase;
  23184. extra = dext;
  23185. end = -1;
  23186. }
  23187. /* initialize opts for loop */
  23188. huff = 0; /* starting code */
  23189. sym = 0; /* starting code symbol */
  23190. len = min; /* starting code length */
  23191. next = table_index; /* current table to fill in */
  23192. curr = root; /* current table index bits */
  23193. drop = 0; /* current bits to drop from code for index */
  23194. low = -1; /* trigger new sub-table when len > root */
  23195. used = 1 << root; /* use root table entries */
  23196. mask = used - 1; /* mask for comparing low */
  23197. /* check available table space */
  23198. if ((type === LENS && used > ENOUGH_LENS) ||
  23199. (type === DISTS && used > ENOUGH_DISTS)) {
  23200. return 1;
  23201. }
  23202. var i=0;
  23203. /* process all codes and make table entries */
  23204. for (;;) {
  23205. i++;
  23206. /* create table entry */
  23207. here_bits = len - drop;
  23208. if (work[sym] < end) {
  23209. here_op = 0;
  23210. here_val = work[sym];
  23211. }
  23212. else if (work[sym] > end) {
  23213. here_op = extra[extra_index + work[sym]];
  23214. here_val = base[base_index + work[sym]];
  23215. }
  23216. else {
  23217. here_op = 32 + 64; /* end of block */
  23218. here_val = 0;
  23219. }
  23220. /* replicate for those indices with low len bits equal to huff */
  23221. incr = 1 << (len - drop);
  23222. fill = 1 << curr;
  23223. min = fill; /* save offset to next table */
  23224. do {
  23225. fill -= incr;
  23226. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  23227. } while (fill !== 0);
  23228. /* backwards increment the len-bit code huff */
  23229. incr = 1 << (len - 1);
  23230. while (huff & incr) {
  23231. incr >>= 1;
  23232. }
  23233. if (incr !== 0) {
  23234. huff &= incr - 1;
  23235. huff += incr;
  23236. } else {
  23237. huff = 0;
  23238. }
  23239. /* go to next symbol, update count, len */
  23240. sym++;
  23241. if (--count[len] === 0) {
  23242. if (len === max) { break; }
  23243. len = lens[lens_index + work[sym]];
  23244. }
  23245. /* create new sub-table if needed */
  23246. if (len > root && (huff & mask) !== low) {
  23247. /* if first time, transition to sub-tables */
  23248. if (drop === 0) {
  23249. drop = root;
  23250. }
  23251. /* increment past last table */
  23252. next += min; /* here min is 1 << curr */
  23253. /* determine length of next table */
  23254. curr = len - drop;
  23255. left = 1 << curr;
  23256. while (curr + drop < max) {
  23257. left -= count[curr + drop];
  23258. if (left <= 0) { break; }
  23259. curr++;
  23260. left <<= 1;
  23261. }
  23262. /* check for enough space */
  23263. used += 1 << curr;
  23264. if ((type === LENS && used > ENOUGH_LENS) ||
  23265. (type === DISTS && used > ENOUGH_DISTS)) {
  23266. return 1;
  23267. }
  23268. /* point entry in root table to sub-table */
  23269. low = huff & mask;
  23270. /*table.op[low] = curr;
  23271. table.bits[low] = root;
  23272. table.val[low] = next - opts.table_index;*/
  23273. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  23274. }
  23275. }
  23276. /* fill in remaining table entry if code is incomplete (guaranteed to have
  23277. at most one remaining entry, since if the code is incomplete, the
  23278. maximum code length that was allowed to get this far is one bit) */
  23279. if (huff !== 0) {
  23280. //table.op[next + huff] = 64; /* invalid code marker */
  23281. //table.bits[next + huff] = len - drop;
  23282. //table.val[next + huff] = 0;
  23283. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  23284. }
  23285. /* set return parameters */
  23286. //opts.table_index += used;
  23287. opts.bits = root;
  23288. return 0;
  23289. };
  23290. },{"../utils/common":70}],80:[function(require,module,exports){
  23291. 'use strict';
  23292. module.exports = {
  23293. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  23294. '1': 'stream end', /* Z_STREAM_END 1 */
  23295. '0': '', /* Z_OK 0 */
  23296. '-1': 'file error', /* Z_ERRNO (-1) */
  23297. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  23298. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  23299. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  23300. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  23301. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  23302. };
  23303. },{}],81:[function(require,module,exports){
  23304. 'use strict';
  23305. var utils = require('../utils/common');
  23306. /* Public constants ==========================================================*/
  23307. /* ===========================================================================*/
  23308. //var Z_FILTERED = 1;
  23309. //var Z_HUFFMAN_ONLY = 2;
  23310. //var Z_RLE = 3;
  23311. var Z_FIXED = 4;
  23312. //var Z_DEFAULT_STRATEGY = 0;
  23313. /* Possible values of the data_type field (though see inflate()) */
  23314. var Z_BINARY = 0;
  23315. var Z_TEXT = 1;
  23316. //var Z_ASCII = 1; // = Z_TEXT
  23317. var Z_UNKNOWN = 2;
  23318. /*============================================================================*/
  23319. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  23320. // From zutil.h
  23321. var STORED_BLOCK = 0;
  23322. var STATIC_TREES = 1;
  23323. var DYN_TREES = 2;
  23324. /* The three kinds of block type */
  23325. var MIN_MATCH = 3;
  23326. var MAX_MATCH = 258;
  23327. /* The minimum and maximum match lengths */
  23328. // From deflate.h
  23329. /* ===========================================================================
  23330. * Internal compression state.
  23331. */
  23332. var LENGTH_CODES = 29;
  23333. /* number of length codes, not counting the special END_BLOCK code */
  23334. var LITERALS = 256;
  23335. /* number of literal bytes 0..255 */
  23336. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  23337. /* number of Literal or Length codes, including the END_BLOCK code */
  23338. var D_CODES = 30;
  23339. /* number of distance codes */
  23340. var BL_CODES = 19;
  23341. /* number of codes used to transfer the bit lengths */
  23342. var HEAP_SIZE = 2*L_CODES + 1;
  23343. /* maximum heap size */
  23344. var MAX_BITS = 15;
  23345. /* All codes must not exceed MAX_BITS bits */
  23346. var Buf_size = 16;
  23347. /* size of bit buffer in bi_buf */
  23348. /* ===========================================================================
  23349. * Constants
  23350. */
  23351. var MAX_BL_BITS = 7;
  23352. /* Bit length codes must not exceed MAX_BL_BITS bits */
  23353. var END_BLOCK = 256;
  23354. /* end of block literal code */
  23355. var REP_3_6 = 16;
  23356. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  23357. var REPZ_3_10 = 17;
  23358. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  23359. var REPZ_11_138 = 18;
  23360. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  23361. var extra_lbits = /* extra bits for each length code */
  23362. [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];
  23363. var extra_dbits = /* extra bits for each distance code */
  23364. [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];
  23365. var extra_blbits = /* extra bits for each bit length code */
  23366. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  23367. var bl_order =
  23368. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  23369. /* The lengths of the bit length codes are sent in order of decreasing
  23370. * probability, to avoid transmitting the lengths for unused bit length codes.
  23371. */
  23372. /* ===========================================================================
  23373. * Local data. These are initialized only once.
  23374. */
  23375. // We pre-fill arrays with 0 to avoid uninitialized gaps
  23376. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  23377. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  23378. var static_ltree = new Array((L_CODES+2) * 2);
  23379. zero(static_ltree);
  23380. /* The static literal tree. Since the bit lengths are imposed, there is no
  23381. * need for the L_CODES extra codes used during heap construction. However
  23382. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  23383. * below).
  23384. */
  23385. var static_dtree = new Array(D_CODES * 2);
  23386. zero(static_dtree);
  23387. /* The static distance tree. (Actually a trivial tree since all codes use
  23388. * 5 bits.)
  23389. */
  23390. var _dist_code = new Array(DIST_CODE_LEN);
  23391. zero(_dist_code);
  23392. /* Distance codes. The first 256 values correspond to the distances
  23393. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  23394. * the 15 bit distances.
  23395. */
  23396. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  23397. zero(_length_code);
  23398. /* length code for each normalized match length (0 == MIN_MATCH) */
  23399. var base_length = new Array(LENGTH_CODES);
  23400. zero(base_length);
  23401. /* First normalized length for each code (0 = MIN_MATCH) */
  23402. var base_dist = new Array(D_CODES);
  23403. zero(base_dist);
  23404. /* First normalized distance for each code (0 = distance of 1) */
  23405. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  23406. this.static_tree = static_tree; /* static tree or NULL */
  23407. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  23408. this.extra_base = extra_base; /* base index for extra_bits */
  23409. this.elems = elems; /* max number of elements in the tree */
  23410. this.max_length = max_length; /* max bit length for the codes */
  23411. // show if `static_tree` has data or dummy - needed for monomorphic objects
  23412. this.has_stree = static_tree && static_tree.length;
  23413. };
  23414. var static_l_desc;
  23415. var static_d_desc;
  23416. var static_bl_desc;
  23417. var TreeDesc = function(dyn_tree, stat_desc) {
  23418. this.dyn_tree = dyn_tree; /* the dynamic tree */
  23419. this.max_code = 0; /* largest code with non zero frequency */
  23420. this.stat_desc = stat_desc; /* the corresponding static tree */
  23421. };
  23422. function d_code(dist) {
  23423. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  23424. }
  23425. /* ===========================================================================
  23426. * Output a short LSB first on the stream.
  23427. * IN assertion: there is enough room in pendingBuf.
  23428. */
  23429. function put_short (s, w) {
  23430. // put_byte(s, (uch)((w) & 0xff));
  23431. // put_byte(s, (uch)((ush)(w) >> 8));
  23432. s.pending_buf[s.pending++] = (w) & 0xff;
  23433. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  23434. }
  23435. /* ===========================================================================
  23436. * Send a value on a given number of bits.
  23437. * IN assertion: length <= 16 and value fits in length bits.
  23438. */
  23439. function send_bits(s, value, length) {
  23440. if (s.bi_valid > (Buf_size - length)) {
  23441. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23442. put_short(s, s.bi_buf);
  23443. s.bi_buf = value >> (Buf_size - s.bi_valid);
  23444. s.bi_valid += length - Buf_size;
  23445. } else {
  23446. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23447. s.bi_valid += length;
  23448. }
  23449. }
  23450. function send_code(s, c, tree) {
  23451. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  23452. }
  23453. /* ===========================================================================
  23454. * Reverse the first len bits of a code, using straightforward code (a faster
  23455. * method would use a table)
  23456. * IN assertion: 1 <= len <= 15
  23457. */
  23458. function bi_reverse(code, len) {
  23459. var res = 0;
  23460. do {
  23461. res |= code & 1;
  23462. code >>>= 1;
  23463. res <<= 1;
  23464. } while (--len > 0);
  23465. return res >>> 1;
  23466. }
  23467. /* ===========================================================================
  23468. * Flush the bit buffer, keeping at most 7 bits in it.
  23469. */
  23470. function bi_flush(s) {
  23471. if (s.bi_valid === 16) {
  23472. put_short(s, s.bi_buf);
  23473. s.bi_buf = 0;
  23474. s.bi_valid = 0;
  23475. } else if (s.bi_valid >= 8) {
  23476. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  23477. s.bi_buf >>= 8;
  23478. s.bi_valid -= 8;
  23479. }
  23480. }
  23481. /* ===========================================================================
  23482. * Compute the optimal bit lengths for a tree and update the total bit length
  23483. * for the current block.
  23484. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  23485. * above are the tree nodes sorted by increasing frequency.
  23486. * OUT assertions: the field len is set to the optimal bit length, the
  23487. * array bl_count contains the frequencies for each bit length.
  23488. * The length opt_len is updated; static_len is also updated if stree is
  23489. * not null.
  23490. */
  23491. function gen_bitlen(s, desc)
  23492. // deflate_state *s;
  23493. // tree_desc *desc; /* the tree descriptor */
  23494. {
  23495. var tree = desc.dyn_tree;
  23496. var max_code = desc.max_code;
  23497. var stree = desc.stat_desc.static_tree;
  23498. var has_stree = desc.stat_desc.has_stree;
  23499. var extra = desc.stat_desc.extra_bits;
  23500. var base = desc.stat_desc.extra_base;
  23501. var max_length = desc.stat_desc.max_length;
  23502. var h; /* heap index */
  23503. var n, m; /* iterate over the tree elements */
  23504. var bits; /* bit length */
  23505. var xbits; /* extra bits */
  23506. var f; /* frequency */
  23507. var overflow = 0; /* number of elements with bit length too large */
  23508. for (bits = 0; bits <= MAX_BITS; bits++) {
  23509. s.bl_count[bits] = 0;
  23510. }
  23511. /* In a first pass, compute the optimal bit lengths (which may
  23512. * overflow in the case of the bit length tree).
  23513. */
  23514. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  23515. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  23516. n = s.heap[h];
  23517. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  23518. if (bits > max_length) {
  23519. bits = max_length;
  23520. overflow++;
  23521. }
  23522. tree[n*2 + 1]/*.Len*/ = bits;
  23523. /* We overwrite tree[n].Dad which is no longer needed */
  23524. if (n > max_code) { continue; } /* not a leaf node */
  23525. s.bl_count[bits]++;
  23526. xbits = 0;
  23527. if (n >= base) {
  23528. xbits = extra[n-base];
  23529. }
  23530. f = tree[n * 2]/*.Freq*/;
  23531. s.opt_len += f * (bits + xbits);
  23532. if (has_stree) {
  23533. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  23534. }
  23535. }
  23536. if (overflow === 0) { return; }
  23537. // Trace((stderr,"\nbit length overflow\n"));
  23538. /* This happens for example on obj2 and pic of the Calgary corpus */
  23539. /* Find the first bit length which could increase: */
  23540. do {
  23541. bits = max_length-1;
  23542. while (s.bl_count[bits] === 0) { bits--; }
  23543. s.bl_count[bits]--; /* move one leaf down the tree */
  23544. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  23545. s.bl_count[max_length]--;
  23546. /* The brother of the overflow item also moves one step up,
  23547. * but this does not affect bl_count[max_length]
  23548. */
  23549. overflow -= 2;
  23550. } while (overflow > 0);
  23551. /* Now recompute all bit lengths, scanning in increasing frequency.
  23552. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  23553. * lengths instead of fixing only the wrong ones. This idea is taken
  23554. * from 'ar' written by Haruhiko Okumura.)
  23555. */
  23556. for (bits = max_length; bits !== 0; bits--) {
  23557. n = s.bl_count[bits];
  23558. while (n !== 0) {
  23559. m = s.heap[--h];
  23560. if (m > max_code) { continue; }
  23561. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  23562. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  23563. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  23564. tree[m*2 + 1]/*.Len*/ = bits;
  23565. }
  23566. n--;
  23567. }
  23568. }
  23569. }
  23570. /* ===========================================================================
  23571. * Generate the codes for a given tree and bit counts (which need not be
  23572. * optimal).
  23573. * IN assertion: the array bl_count contains the bit length statistics for
  23574. * the given tree and the field len is set for all tree elements.
  23575. * OUT assertion: the field code is set for all tree elements of non
  23576. * zero code length.
  23577. */
  23578. function gen_codes(tree, max_code, bl_count)
  23579. // ct_data *tree; /* the tree to decorate */
  23580. // int max_code; /* largest code with non zero frequency */
  23581. // ushf *bl_count; /* number of codes at each bit length */
  23582. {
  23583. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  23584. var code = 0; /* running code value */
  23585. var bits; /* bit index */
  23586. var n; /* code index */
  23587. /* The distribution counts are first used to generate the code values
  23588. * without bit reversal.
  23589. */
  23590. for (bits = 1; bits <= MAX_BITS; bits++) {
  23591. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  23592. }
  23593. /* Check that the bit counts in bl_count are consistent. The last code
  23594. * must be all ones.
  23595. */
  23596. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  23597. // "inconsistent bit counts");
  23598. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  23599. for (n = 0; n <= max_code; n++) {
  23600. var len = tree[n*2 + 1]/*.Len*/;
  23601. if (len === 0) { continue; }
  23602. /* Now reverse the bits */
  23603. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  23604. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  23605. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  23606. }
  23607. }
  23608. /* ===========================================================================
  23609. * Initialize the various 'constant' tables.
  23610. */
  23611. function tr_static_init() {
  23612. var n; /* iterates over tree elements */
  23613. var bits; /* bit counter */
  23614. var length; /* length value */
  23615. var code; /* code value */
  23616. var dist; /* distance index */
  23617. var bl_count = new Array(MAX_BITS+1);
  23618. /* number of codes at each bit length for an optimal tree */
  23619. // do check in _tr_init()
  23620. //if (static_init_done) return;
  23621. /* For some embedded targets, global variables are not initialized: */
  23622. /*#ifdef NO_INIT_GLOBAL_POINTERS
  23623. static_l_desc.static_tree = static_ltree;
  23624. static_l_desc.extra_bits = extra_lbits;
  23625. static_d_desc.static_tree = static_dtree;
  23626. static_d_desc.extra_bits = extra_dbits;
  23627. static_bl_desc.extra_bits = extra_blbits;
  23628. #endif*/
  23629. /* Initialize the mapping length (0..255) -> length code (0..28) */
  23630. length = 0;
  23631. for (code = 0; code < LENGTH_CODES-1; code++) {
  23632. base_length[code] = length;
  23633. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  23634. _length_code[length++] = code;
  23635. }
  23636. }
  23637. //Assert (length == 256, "tr_static_init: length != 256");
  23638. /* Note that the length 255 (match length 258) can be represented
  23639. * in two different ways: code 284 + 5 bits or code 285, so we
  23640. * overwrite length_code[255] to use the best encoding:
  23641. */
  23642. _length_code[length-1] = code;
  23643. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  23644. dist = 0;
  23645. for (code = 0 ; code < 16; code++) {
  23646. base_dist[code] = dist;
  23647. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  23648. _dist_code[dist++] = code;
  23649. }
  23650. }
  23651. //Assert (dist == 256, "tr_static_init: dist != 256");
  23652. dist >>= 7; /* from now on, all distances are divided by 128 */
  23653. for ( ; code < D_CODES; code++) {
  23654. base_dist[code] = dist << 7;
  23655. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  23656. _dist_code[256 + dist++] = code;
  23657. }
  23658. }
  23659. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  23660. /* Construct the codes of the static literal tree */
  23661. for (bits = 0; bits <= MAX_BITS; bits++) {
  23662. bl_count[bits] = 0;
  23663. }
  23664. n = 0;
  23665. while (n <= 143) {
  23666. static_ltree[n*2 + 1]/*.Len*/ = 8;
  23667. n++;
  23668. bl_count[8]++;
  23669. }
  23670. while (n <= 255) {
  23671. static_ltree[n*2 + 1]/*.Len*/ = 9;
  23672. n++;
  23673. bl_count[9]++;
  23674. }
  23675. while (n <= 279) {
  23676. static_ltree[n*2 + 1]/*.Len*/ = 7;
  23677. n++;
  23678. bl_count[7]++;
  23679. }
  23680. while (n <= 287) {
  23681. static_ltree[n*2 + 1]/*.Len*/ = 8;
  23682. n++;
  23683. bl_count[8]++;
  23684. }
  23685. /* Codes 286 and 287 do not exist, but we must include them in the
  23686. * tree construction to get a canonical Huffman tree (longest code
  23687. * all ones)
  23688. */
  23689. gen_codes(static_ltree, L_CODES+1, bl_count);
  23690. /* The static distance tree is trivial: */
  23691. for (n = 0; n < D_CODES; n++) {
  23692. static_dtree[n*2 + 1]/*.Len*/ = 5;
  23693. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  23694. }
  23695. // Now data ready and we can init static trees
  23696. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  23697. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  23698. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  23699. //static_init_done = true;
  23700. }
  23701. /* ===========================================================================
  23702. * Initialize a new block.
  23703. */
  23704. function init_block(s) {
  23705. var n; /* iterates over tree elements */
  23706. /* Initialize the trees. */
  23707. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  23708. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  23709. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  23710. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  23711. s.opt_len = s.static_len = 0;
  23712. s.last_lit = s.matches = 0;
  23713. }
  23714. /* ===========================================================================
  23715. * Flush the bit buffer and align the output on a byte boundary
  23716. */
  23717. function bi_windup(s)
  23718. {
  23719. if (s.bi_valid > 8) {
  23720. put_short(s, s.bi_buf);
  23721. } else if (s.bi_valid > 0) {
  23722. //put_byte(s, (Byte)s->bi_buf);
  23723. s.pending_buf[s.pending++] = s.bi_buf;
  23724. }
  23725. s.bi_buf = 0;
  23726. s.bi_valid = 0;
  23727. }
  23728. /* ===========================================================================
  23729. * Copy a stored block, storing first the length and its
  23730. * one's complement if requested.
  23731. */
  23732. function copy_block(s, buf, len, header)
  23733. //DeflateState *s;
  23734. //charf *buf; /* the input data */
  23735. //unsigned len; /* its length */
  23736. //int header; /* true if block header must be written */
  23737. {
  23738. bi_windup(s); /* align on byte boundary */
  23739. if (header) {
  23740. put_short(s, len);
  23741. put_short(s, ~len);
  23742. }
  23743. // while (len--) {
  23744. // put_byte(s, *buf++);
  23745. // }
  23746. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  23747. s.pending += len;
  23748. }
  23749. /* ===========================================================================
  23750. * Compares to subtrees, using the tree depth as tie breaker when
  23751. * the subtrees have equal frequency. This minimizes the worst case length.
  23752. */
  23753. function smaller(tree, n, m, depth) {
  23754. var _n2 = n*2;
  23755. var _m2 = m*2;
  23756. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  23757. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  23758. }
  23759. /* ===========================================================================
  23760. * Restore the heap property by moving down the tree starting at node k,
  23761. * exchanging a node with the smallest of its two sons if necessary, stopping
  23762. * when the heap property is re-established (each father smaller than its
  23763. * two sons).
  23764. */
  23765. function pqdownheap(s, tree, k)
  23766. // deflate_state *s;
  23767. // ct_data *tree; /* the tree to restore */
  23768. // int k; /* node to move down */
  23769. {
  23770. var v = s.heap[k];
  23771. var j = k << 1; /* left son of k */
  23772. while (j <= s.heap_len) {
  23773. /* Set j to the smallest of the two sons: */
  23774. if (j < s.heap_len &&
  23775. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  23776. j++;
  23777. }
  23778. /* Exit if v is smaller than both sons */
  23779. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  23780. /* Exchange v with the smallest son */
  23781. s.heap[k] = s.heap[j];
  23782. k = j;
  23783. /* And continue down the tree, setting j to the left son of k */
  23784. j <<= 1;
  23785. }
  23786. s.heap[k] = v;
  23787. }
  23788. // inlined manually
  23789. // var SMALLEST = 1;
  23790. /* ===========================================================================
  23791. * Send the block data compressed using the given Huffman trees
  23792. */
  23793. function compress_block(s, ltree, dtree)
  23794. // deflate_state *s;
  23795. // const ct_data *ltree; /* literal tree */
  23796. // const ct_data *dtree; /* distance tree */
  23797. {
  23798. var dist; /* distance of matched string */
  23799. var lc; /* match length or unmatched char (if dist == 0) */
  23800. var lx = 0; /* running index in l_buf */
  23801. var code; /* the code to send */
  23802. var extra; /* number of extra bits to send */
  23803. if (s.last_lit !== 0) {
  23804. do {
  23805. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  23806. lc = s.pending_buf[s.l_buf + lx];
  23807. lx++;
  23808. if (dist === 0) {
  23809. send_code(s, lc, ltree); /* send a literal byte */
  23810. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  23811. } else {
  23812. /* Here, lc is the match length - MIN_MATCH */
  23813. code = _length_code[lc];
  23814. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  23815. extra = extra_lbits[code];
  23816. if (extra !== 0) {
  23817. lc -= base_length[code];
  23818. send_bits(s, lc, extra); /* send the extra length bits */
  23819. }
  23820. dist--; /* dist is now the match distance - 1 */
  23821. code = d_code(dist);
  23822. //Assert (code < D_CODES, "bad d_code");
  23823. send_code(s, code, dtree); /* send the distance code */
  23824. extra = extra_dbits[code];
  23825. if (extra !== 0) {
  23826. dist -= base_dist[code];
  23827. send_bits(s, dist, extra); /* send the extra distance bits */
  23828. }
  23829. } /* literal or match pair ? */
  23830. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  23831. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  23832. // "pendingBuf overflow");
  23833. } while (lx < s.last_lit);
  23834. }
  23835. send_code(s, END_BLOCK, ltree);
  23836. }
  23837. /* ===========================================================================
  23838. * Construct one Huffman tree and assigns the code bit strings and lengths.
  23839. * Update the total bit length for the current block.
  23840. * IN assertion: the field freq is set for all tree elements.
  23841. * OUT assertions: the fields len and code are set to the optimal bit length
  23842. * and corresponding code. The length opt_len is updated; static_len is
  23843. * also updated if stree is not null. The field max_code is set.
  23844. */
  23845. function build_tree(s, desc)
  23846. // deflate_state *s;
  23847. // tree_desc *desc; /* the tree descriptor */
  23848. {
  23849. var tree = desc.dyn_tree;
  23850. var stree = desc.stat_desc.static_tree;
  23851. var has_stree = desc.stat_desc.has_stree;
  23852. var elems = desc.stat_desc.elems;
  23853. var n, m; /* iterate over heap elements */
  23854. var max_code = -1; /* largest code with non zero frequency */
  23855. var node; /* new node being created */
  23856. /* Construct the initial heap, with least frequent element in
  23857. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  23858. * heap[0] is not used.
  23859. */
  23860. s.heap_len = 0;
  23861. s.heap_max = HEAP_SIZE;
  23862. for (n = 0; n < elems; n++) {
  23863. if (tree[n * 2]/*.Freq*/ !== 0) {
  23864. s.heap[++s.heap_len] = max_code = n;
  23865. s.depth[n] = 0;
  23866. } else {
  23867. tree[n*2 + 1]/*.Len*/ = 0;
  23868. }
  23869. }
  23870. /* The pkzip format requires that at least one distance code exists,
  23871. * and that at least one bit should be sent even if there is only one
  23872. * possible code. So to avoid special checks later on we force at least
  23873. * two codes of non zero frequency.
  23874. */
  23875. while (s.heap_len < 2) {
  23876. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  23877. tree[node * 2]/*.Freq*/ = 1;
  23878. s.depth[node] = 0;
  23879. s.opt_len--;
  23880. if (has_stree) {
  23881. s.static_len -= stree[node*2 + 1]/*.Len*/;
  23882. }
  23883. /* node is 0 or 1 so it does not have extra bits */
  23884. }
  23885. desc.max_code = max_code;
  23886. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  23887. * establish sub-heaps of increasing lengths:
  23888. */
  23889. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  23890. /* Construct the Huffman tree by repeatedly combining the least two
  23891. * frequent nodes.
  23892. */
  23893. node = elems; /* next internal node of the tree */
  23894. do {
  23895. //pqremove(s, tree, n); /* n = node of least frequency */
  23896. /*** pqremove ***/
  23897. n = s.heap[1/*SMALLEST*/];
  23898. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  23899. pqdownheap(s, tree, 1/*SMALLEST*/);
  23900. /***/
  23901. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  23902. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  23903. s.heap[--s.heap_max] = m;
  23904. /* Create a new node father of n and m */
  23905. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  23906. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  23907. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  23908. /* and insert the new node in the heap */
  23909. s.heap[1/*SMALLEST*/] = node++;
  23910. pqdownheap(s, tree, 1/*SMALLEST*/);
  23911. } while (s.heap_len >= 2);
  23912. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  23913. /* At this point, the fields freq and dad are set. We can now
  23914. * generate the bit lengths.
  23915. */
  23916. gen_bitlen(s, desc);
  23917. /* The field len is now set, we can generate the bit codes */
  23918. gen_codes(tree, max_code, s.bl_count);
  23919. }
  23920. /* ===========================================================================
  23921. * Scan a literal or distance tree to determine the frequencies of the codes
  23922. * in the bit length tree.
  23923. */
  23924. function scan_tree(s, tree, max_code)
  23925. // deflate_state *s;
  23926. // ct_data *tree; /* the tree to be scanned */
  23927. // int max_code; /* and its largest code of non zero frequency */
  23928. {
  23929. var n; /* iterates over all tree elements */
  23930. var prevlen = -1; /* last emitted length */
  23931. var curlen; /* length of current code */
  23932. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  23933. var count = 0; /* repeat count of the current code */
  23934. var max_count = 7; /* max repeat count */
  23935. var min_count = 4; /* min repeat count */
  23936. if (nextlen === 0) {
  23937. max_count = 138;
  23938. min_count = 3;
  23939. }
  23940. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  23941. for (n = 0; n <= max_code; n++) {
  23942. curlen = nextlen;
  23943. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  23944. if (++count < max_count && curlen === nextlen) {
  23945. continue;
  23946. } else if (count < min_count) {
  23947. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  23948. } else if (curlen !== 0) {
  23949. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  23950. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  23951. } else if (count <= 10) {
  23952. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  23953. } else {
  23954. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  23955. }
  23956. count = 0;
  23957. prevlen = curlen;
  23958. if (nextlen === 0) {
  23959. max_count = 138;
  23960. min_count = 3;
  23961. } else if (curlen === nextlen) {
  23962. max_count = 6;
  23963. min_count = 3;
  23964. } else {
  23965. max_count = 7;
  23966. min_count = 4;
  23967. }
  23968. }
  23969. }
  23970. /* ===========================================================================
  23971. * Send a literal or distance tree in compressed form, using the codes in
  23972. * bl_tree.
  23973. */
  23974. function send_tree(s, tree, max_code)
  23975. // deflate_state *s;
  23976. // ct_data *tree; /* the tree to be scanned */
  23977. // int max_code; /* and its largest code of non zero frequency */
  23978. {
  23979. var n; /* iterates over all tree elements */
  23980. var prevlen = -1; /* last emitted length */
  23981. var curlen; /* length of current code */
  23982. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  23983. var count = 0; /* repeat count of the current code */
  23984. var max_count = 7; /* max repeat count */
  23985. var min_count = 4; /* min repeat count */
  23986. /* tree[max_code+1].Len = -1; */ /* guard already set */
  23987. if (nextlen === 0) {
  23988. max_count = 138;
  23989. min_count = 3;
  23990. }
  23991. for (n = 0; n <= max_code; n++) {
  23992. curlen = nextlen;
  23993. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  23994. if (++count < max_count && curlen === nextlen) {
  23995. continue;
  23996. } else if (count < min_count) {
  23997. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  23998. } else if (curlen !== 0) {
  23999. if (curlen !== prevlen) {
  24000. send_code(s, curlen, s.bl_tree);
  24001. count--;
  24002. }
  24003. //Assert(count >= 3 && count <= 6, " 3_6?");
  24004. send_code(s, REP_3_6, s.bl_tree);
  24005. send_bits(s, count-3, 2);
  24006. } else if (count <= 10) {
  24007. send_code(s, REPZ_3_10, s.bl_tree);
  24008. send_bits(s, count-3, 3);
  24009. } else {
  24010. send_code(s, REPZ_11_138, s.bl_tree);
  24011. send_bits(s, count-11, 7);
  24012. }
  24013. count = 0;
  24014. prevlen = curlen;
  24015. if (nextlen === 0) {
  24016. max_count = 138;
  24017. min_count = 3;
  24018. } else if (curlen === nextlen) {
  24019. max_count = 6;
  24020. min_count = 3;
  24021. } else {
  24022. max_count = 7;
  24023. min_count = 4;
  24024. }
  24025. }
  24026. }
  24027. /* ===========================================================================
  24028. * Construct the Huffman tree for the bit lengths and return the index in
  24029. * bl_order of the last bit length code to send.
  24030. */
  24031. function build_bl_tree(s) {
  24032. var max_blindex; /* index of last bit length code of non zero freq */
  24033. /* Determine the bit length frequencies for literal and distance trees */
  24034. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  24035. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  24036. /* Build the bit length tree: */
  24037. build_tree(s, s.bl_desc);
  24038. /* opt_len now includes the length of the tree representations, except
  24039. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  24040. */
  24041. /* Determine the number of bit length codes to send. The pkzip format
  24042. * requires that at least 4 bit length codes be sent. (appnote.txt says
  24043. * 3 but the actual value used is 4.)
  24044. */
  24045. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  24046. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  24047. break;
  24048. }
  24049. }
  24050. /* Update opt_len to include the bit length tree and counts */
  24051. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  24052. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  24053. // s->opt_len, s->static_len));
  24054. return max_blindex;
  24055. }
  24056. /* ===========================================================================
  24057. * Send the header for a block using dynamic Huffman trees: the counts, the
  24058. * lengths of the bit length codes, the literal tree and the distance tree.
  24059. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  24060. */
  24061. function send_all_trees(s, lcodes, dcodes, blcodes)
  24062. // deflate_state *s;
  24063. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  24064. {
  24065. var rank; /* index in bl_order */
  24066. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  24067. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  24068. // "too many codes");
  24069. //Tracev((stderr, "\nbl counts: "));
  24070. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  24071. send_bits(s, dcodes-1, 5);
  24072. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  24073. for (rank = 0; rank < blcodes; rank++) {
  24074. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  24075. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  24076. }
  24077. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  24078. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  24079. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  24080. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  24081. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  24082. }
  24083. /* ===========================================================================
  24084. * Check if the data type is TEXT or BINARY, using the following algorithm:
  24085. * - TEXT if the two conditions below are satisfied:
  24086. * a) There are no non-portable control characters belonging to the
  24087. * "black list" (0..6, 14..25, 28..31).
  24088. * b) There is at least one printable character belonging to the
  24089. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  24090. * - BINARY otherwise.
  24091. * - The following partially-portable control characters form a
  24092. * "gray list" that is ignored in this detection algorithm:
  24093. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  24094. * IN assertion: the fields Freq of dyn_ltree are set.
  24095. */
  24096. function detect_data_type(s) {
  24097. /* black_mask is the bit mask of black-listed bytes
  24098. * set bits 0..6, 14..25, and 28..31
  24099. * 0xf3ffc07f = binary 11110011111111111100000001111111
  24100. */
  24101. var black_mask = 0xf3ffc07f;
  24102. var n;
  24103. /* Check for non-textual ("black-listed") bytes. */
  24104. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  24105. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  24106. return Z_BINARY;
  24107. }
  24108. }
  24109. /* Check for textual ("white-listed") bytes. */
  24110. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  24111. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  24112. return Z_TEXT;
  24113. }
  24114. for (n = 32; n < LITERALS; n++) {
  24115. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  24116. return Z_TEXT;
  24117. }
  24118. }
  24119. /* There are no "black-listed" or "white-listed" bytes:
  24120. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  24121. */
  24122. return Z_BINARY;
  24123. }
  24124. var static_init_done = false;
  24125. /* ===========================================================================
  24126. * Initialize the tree data structures for a new zlib stream.
  24127. */
  24128. function _tr_init(s)
  24129. {
  24130. if (!static_init_done) {
  24131. tr_static_init();
  24132. static_init_done = true;
  24133. }
  24134. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  24135. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  24136. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  24137. s.bi_buf = 0;
  24138. s.bi_valid = 0;
  24139. /* Initialize the first block of the first file: */
  24140. init_block(s);
  24141. }
  24142. /* ===========================================================================
  24143. * Send a stored block
  24144. */
  24145. function _tr_stored_block(s, buf, stored_len, last)
  24146. //DeflateState *s;
  24147. //charf *buf; /* input block */
  24148. //ulg stored_len; /* length of input block */
  24149. //int last; /* one if this is the last block for a file */
  24150. {
  24151. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  24152. copy_block(s, buf, stored_len, true); /* with header */
  24153. }
  24154. /* ===========================================================================
  24155. * Send one empty static block to give enough lookahead for inflate.
  24156. * This takes 10 bits, of which 7 may remain in the bit buffer.
  24157. */
  24158. function _tr_align(s) {
  24159. send_bits(s, STATIC_TREES<<1, 3);
  24160. send_code(s, END_BLOCK, static_ltree);
  24161. bi_flush(s);
  24162. }
  24163. /* ===========================================================================
  24164. * Determine the best encoding for the current block: dynamic trees, static
  24165. * trees or store, and output the encoded block to the zip file.
  24166. */
  24167. function _tr_flush_block(s, buf, stored_len, last)
  24168. //DeflateState *s;
  24169. //charf *buf; /* input block, or NULL if too old */
  24170. //ulg stored_len; /* length of input block */
  24171. //int last; /* one if this is the last block for a file */
  24172. {
  24173. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  24174. var max_blindex = 0; /* index of last bit length code of non zero freq */
  24175. /* Build the Huffman trees unless a stored block is forced */
  24176. if (s.level > 0) {
  24177. /* Check if the file is binary or text */
  24178. if (s.strm.data_type === Z_UNKNOWN) {
  24179. s.strm.data_type = detect_data_type(s);
  24180. }
  24181. /* Construct the literal and distance trees */
  24182. build_tree(s, s.l_desc);
  24183. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  24184. // s->static_len));
  24185. build_tree(s, s.d_desc);
  24186. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  24187. // s->static_len));
  24188. /* At this point, opt_len and static_len are the total bit lengths of
  24189. * the compressed block data, excluding the tree representations.
  24190. */
  24191. /* Build the bit length tree for the above two trees, and get the index
  24192. * in bl_order of the last bit length code to send.
  24193. */
  24194. max_blindex = build_bl_tree(s);
  24195. /* Determine the best encoding. Compute the block lengths in bytes. */
  24196. opt_lenb = (s.opt_len+3+7) >>> 3;
  24197. static_lenb = (s.static_len+3+7) >>> 3;
  24198. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  24199. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  24200. // s->last_lit));
  24201. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  24202. } else {
  24203. // Assert(buf != (char*)0, "lost buf");
  24204. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  24205. }
  24206. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  24207. /* 4: two words for the lengths */
  24208. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  24209. * Otherwise we can't have processed more than WSIZE input bytes since
  24210. * the last block flush, because compression would have been
  24211. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  24212. * transform a block into a stored block.
  24213. */
  24214. _tr_stored_block(s, buf, stored_len, last);
  24215. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  24216. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  24217. compress_block(s, static_ltree, static_dtree);
  24218. } else {
  24219. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  24220. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  24221. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  24222. }
  24223. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  24224. /* The above check is made mod 2^32, for files larger than 512 MB
  24225. * and uLong implemented on 32 bits.
  24226. */
  24227. init_block(s);
  24228. if (last) {
  24229. bi_windup(s);
  24230. }
  24231. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  24232. // s->compressed_len-7*last));
  24233. }
  24234. /* ===========================================================================
  24235. * Save the match info and tally the frequency counts. Return true if
  24236. * the current block must be flushed.
  24237. */
  24238. function _tr_tally(s, dist, lc)
  24239. // deflate_state *s;
  24240. // unsigned dist; /* distance of matched string */
  24241. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  24242. {
  24243. //var out_length, in_length, dcode;
  24244. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  24245. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  24246. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  24247. s.last_lit++;
  24248. if (dist === 0) {
  24249. /* lc is the unmatched char */
  24250. s.dyn_ltree[lc*2]/*.Freq*/++;
  24251. } else {
  24252. s.matches++;
  24253. /* Here, lc is the match length - MIN_MATCH */
  24254. dist--; /* dist = match distance - 1 */
  24255. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  24256. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  24257. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  24258. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  24259. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  24260. }
  24261. // (!) This block is disabled in zlib defailts,
  24262. // don't enable it for binary compatibility
  24263. //#ifdef TRUNCATE_BLOCK
  24264. // /* Try to guess if it is profitable to stop the current block here */
  24265. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  24266. // /* Compute an upper bound for the compressed length */
  24267. // out_length = s.last_lit*8;
  24268. // in_length = s.strstart - s.block_start;
  24269. //
  24270. // for (dcode = 0; dcode < D_CODES; dcode++) {
  24271. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  24272. // }
  24273. // out_length >>>= 3;
  24274. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  24275. // // s->last_lit, in_length, out_length,
  24276. // // 100L - out_length*100L/in_length));
  24277. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  24278. // return true;
  24279. // }
  24280. // }
  24281. //#endif
  24282. return (s.last_lit === s.lit_bufsize-1);
  24283. /* We avoid equality with lit_bufsize because of wraparound at 64K
  24284. * on 16 bit machines and because stored blocks are restricted to
  24285. * 64K-1 bytes.
  24286. */
  24287. }
  24288. exports._tr_init = _tr_init;
  24289. exports._tr_stored_block = _tr_stored_block;
  24290. exports._tr_flush_block = _tr_flush_block;
  24291. exports._tr_tally = _tr_tally;
  24292. exports._tr_align = _tr_align;
  24293. },{"../utils/common":70}],82:[function(require,module,exports){
  24294. 'use strict';
  24295. function ZStream() {
  24296. /* next input byte */
  24297. this.input = null; // JS specific, because we have no pointers
  24298. this.next_in = 0;
  24299. /* number of bytes available at input */
  24300. this.avail_in = 0;
  24301. /* total number of input bytes read so far */
  24302. this.total_in = 0;
  24303. /* next output byte should be put there */
  24304. this.output = null; // JS specific, because we have no pointers
  24305. this.next_out = 0;
  24306. /* remaining free space at output */
  24307. this.avail_out = 0;
  24308. /* total number of bytes output so far */
  24309. this.total_out = 0;
  24310. /* last error message, NULL if no error */
  24311. this.msg = ''/*Z_NULL*/;
  24312. /* not visible by applications */
  24313. this.state = null;
  24314. /* best guess about the data type: binary or text */
  24315. this.data_type = 2/*Z_UNKNOWN*/;
  24316. /* adler32 value of the uncompressed data */
  24317. this.adler = 0;
  24318. }
  24319. module.exports = ZStream;
  24320. },{}],83:[function(require,module,exports){
  24321. module.exports = require('./lib/retry');
  24322. },{"./lib/retry":84}],84:[function(require,module,exports){
  24323. var RetryOperation = require('./retry_operation');
  24324. exports.operation = function(options) {
  24325. var timeouts = exports.timeouts(options);
  24326. return new RetryOperation(timeouts);
  24327. };
  24328. exports.timeouts = function(options) {
  24329. if (options instanceof Array) {
  24330. return [].concat(options);
  24331. }
  24332. var opts = {
  24333. retries: 10,
  24334. factor: 2,
  24335. minTimeout: 1 * 1000,
  24336. maxTimeout: Infinity,
  24337. randomize: false
  24338. };
  24339. for (var key in options) {
  24340. opts[key] = options[key];
  24341. }
  24342. if (opts.minTimeout > opts.maxTimeout) {
  24343. throw new Error('minTimeout is greater than maxTimeout');
  24344. }
  24345. var timeouts = [];
  24346. for (var i = 0; i < opts.retries; i++) {
  24347. timeouts.push(this._createTimeout(i, opts));
  24348. }
  24349. // sort the array numerically ascending
  24350. timeouts.sort(function(a,b) {
  24351. return a - b;
  24352. });
  24353. return timeouts;
  24354. };
  24355. exports._createTimeout = function(attempt, opts) {
  24356. var random = (opts.randomize)
  24357. ? (Math.random() + 1)
  24358. : 1;
  24359. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  24360. timeout = Math.min(timeout, opts.maxTimeout);
  24361. return timeout;
  24362. };
  24363. },{"./retry_operation":85}],85:[function(require,module,exports){
  24364. function RetryOperation(timeouts) {
  24365. this._timeouts = timeouts;
  24366. this._fn = null;
  24367. this._errors = [];
  24368. this._attempts = 1;
  24369. this._operationTimeout = null;
  24370. this._operationTimeoutCb = null;
  24371. this._timeout = null;
  24372. }
  24373. module.exports = RetryOperation;
  24374. RetryOperation.prototype.retry = function(err) {
  24375. if (this._timeout) {
  24376. clearTimeout(this._timeout);
  24377. }
  24378. if (!err) {
  24379. return false;
  24380. }
  24381. this._errors.push(err);
  24382. var timeout = this._timeouts.shift();
  24383. if (timeout === undefined) {
  24384. return false;
  24385. }
  24386. this._attempts++;
  24387. var self = this;
  24388. setTimeout(function() {
  24389. self._fn(self._attempts);
  24390. if (self._operationTimeoutCb) {
  24391. self._timeout = setTimeout(function() {
  24392. self._operationTimeoutCb(self._attempts);
  24393. }, self._operationTimeout);
  24394. }
  24395. }, timeout);
  24396. return true;
  24397. };
  24398. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  24399. this._fn = fn;
  24400. if (timeoutOps) {
  24401. if (timeoutOps.timeout) {
  24402. this._operationTimeout = timeoutOps.timeout;
  24403. }
  24404. if (timeoutOps.cb) {
  24405. this._operationTimeoutCb = timeoutOps.cb;
  24406. }
  24407. }
  24408. this._fn(this._attempts);
  24409. var self = this;
  24410. if (this._operationTimeoutCb) {
  24411. this._timeout = setTimeout(function() {
  24412. self._operationTimeoutCb();
  24413. }, self._operationTimeout);
  24414. }
  24415. };
  24416. RetryOperation.prototype.try = function(fn) {
  24417. console.log('Using RetryOperation.try() is deprecated');
  24418. this.attempt(fn);
  24419. };
  24420. RetryOperation.prototype.start = function(fn) {
  24421. console.log('Using RetryOperation.start() is deprecated');
  24422. this.attempt(fn);
  24423. };
  24424. RetryOperation.prototype.start = RetryOperation.prototype.try;
  24425. RetryOperation.prototype.errors = function() {
  24426. return this._errors;
  24427. };
  24428. RetryOperation.prototype.attempts = function() {
  24429. return this._attempts;
  24430. };
  24431. RetryOperation.prototype.mainError = function() {
  24432. if (this._errors.length === 0) {
  24433. return null;
  24434. }
  24435. var counts = {};
  24436. var mainError = null;
  24437. var mainErrorCount = 0;
  24438. for (var i = 0; i < this._errors.length; i++) {
  24439. var error = this._errors[i];
  24440. var message = error.message;
  24441. var count = (counts[message] || 0) + 1;
  24442. counts[message] = count;
  24443. if (count >= mainErrorCount) {
  24444. mainError = error;
  24445. mainErrorCount = count;
  24446. }
  24447. }
  24448. return mainError;
  24449. };
  24450. },{}],86:[function(require,module,exports){
  24451. module.exports = function arrayEquals(array) {
  24452. // if the other array is a falsy value, return
  24453. if (!array)
  24454. return false;
  24455. // compare lengths - can save a lot of time
  24456. if (this.length != array.length)
  24457. return false;
  24458. for (var i = 0, l = this.length; i < l; i++) {
  24459. // Check if we have nested arrays
  24460. if (this[i] instanceof Array && array[i] instanceof Array) {
  24461. // recurse into the nested arrays
  24462. if (!arrayEquals.apply(this[i], [array[i]]))
  24463. return false;
  24464. } else if (this[i] != array[i]) {
  24465. // Warning - two different object instances will never be equal:
  24466. // {x:20} != {x:20}
  24467. return false;
  24468. }
  24469. }
  24470. return true;
  24471. }
  24472. },{}],87:[function(require,module,exports){
  24473. exports.Interop = require('./interop');
  24474. },{"./interop":88}],88:[function(require,module,exports){
  24475. "use strict";
  24476. var transform = require('./transform');
  24477. var arrayEquals = require('./array-equals');
  24478. function Interop() {
  24479. /**
  24480. * This map holds the most recent Unified Plan offer/answer SDP that was
  24481. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  24482. * the SDP string as values.
  24483. *
  24484. * @type {{}}
  24485. */
  24486. this.cache = {};
  24487. }
  24488. module.exports = Interop;
  24489. /**
  24490. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  24491. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  24492. * application.
  24493. *
  24494. * @param desc
  24495. * @returns {*}
  24496. */
  24497. Interop.prototype.toPlanB = function(desc) {
  24498. //#region Preliminary input validation.
  24499. if (typeof desc !== 'object' || desc === null ||
  24500. typeof desc.sdp !== 'string') {
  24501. console.warn('An empty description was passed as an argument.');
  24502. return desc;
  24503. }
  24504. // Objectify the SDP for easier manipulation.
  24505. var session = transform.parse(desc.sdp);
  24506. // If the SDP contains no media, there's nothing to transform.
  24507. if (typeof session.media === 'undefined' ||
  24508. !Array.isArray(session.media) || session.media.length === 0) {
  24509. console.warn('The description has no media.');
  24510. return desc;
  24511. }
  24512. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  24513. // SDP has a video, an audio and a data "channel" at most.
  24514. if (session.media.length <= 3 && session.media.every(function(m) {
  24515. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  24516. })) {
  24517. console.warn('This description does not look like Unified Plan.');
  24518. return desc;
  24519. }
  24520. //#endregion
  24521. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  24522. // -> Unified Plan transformation.
  24523. this.cache[desc.type] = desc.sdp;
  24524. //#region Convert from Unified Plan to Plan B.
  24525. // We rebuild the session.media array.
  24526. var media = session.media;
  24527. session.media = [];
  24528. // Associative array that maps channel types to channel objects for fast
  24529. // access to channel objects by their type, e.g. type2bl['audio']->channel
  24530. // obj.
  24531. var type2bl = {};
  24532. // Used to build the group:BUNDLE value after the channels construction
  24533. // loop.
  24534. var types = [];
  24535. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  24536. media.forEach(function(unifiedLine) {
  24537. // rtcp-mux is required in the Plan B SDP.
  24538. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  24539. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  24540. unifiedLine.direction !== 'inactive') {
  24541. throw new Error('Cannot convert to Plan B because m-lines ' +
  24542. 'without the rtcp-mux attribute were found.');
  24543. }
  24544. if (unifiedLine.type === 'application') {
  24545. session.media.push(unifiedLine);
  24546. types.push(unifiedLine.mid);
  24547. return;
  24548. }
  24549. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  24550. // as the channel basis.
  24551. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  24552. type2bl[unifiedLine.type] = unifiedLine;
  24553. }
  24554. // Add sources to the channel and handle a=msid.
  24555. if (typeof unifiedLine.sources === 'object') {
  24556. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  24557. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  24558. type2bl[unifiedLine.type].sources = {};
  24559. // Assign the sources to the channel.
  24560. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  24561. if (typeof unifiedLine.msid !== 'undefined') {
  24562. // In Plan B the msid is an SSRC attribute. Also, we don't
  24563. // care about the obsolete label and mslabel attributes.
  24564. //
  24565. // Note that it is not guaranteed that the unifiedLine will have
  24566. // an msid. recvonly channels in particular don't have one.
  24567. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  24568. }
  24569. // NOTE ssrcs in ssrc groups will share msids, as
  24570. // draft-uberti-rtcweb-plan-00 mandates.
  24571. });
  24572. }
  24573. // Add ssrc groups to the channel.
  24574. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  24575. Array.isArray(unifiedLine.ssrcGroups)) {
  24576. // Create the ssrcGroups array, if it's not defined.
  24577. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  24578. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  24579. type2bl[unifiedLine.type].ssrcGroups = [];
  24580. }
  24581. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  24582. }
  24583. if (type2bl[unifiedLine.type] === unifiedLine) {
  24584. // Copy ICE related stuff from the principal media line.
  24585. unifiedLine.candidates = media[0].candidates;
  24586. unifiedLine.iceUfrag = media[0].iceUfrag;
  24587. unifiedLine.icePwd = media[0].icePwd;
  24588. unifiedLine.fingerprint = media[0].fingerprint;
  24589. // Plan B mids are in ['audio', 'video', 'data']
  24590. unifiedLine.mid = unifiedLine.type;
  24591. // Plan B doesn't support/need the bundle-only attribute.
  24592. delete unifiedLine.bundleOnly;
  24593. // In Plan B the msid is an SSRC attribute.
  24594. delete unifiedLine.msid;
  24595. // Used to build the group:BUNDLE value after this loop.
  24596. types.push(unifiedLine.type);
  24597. // Add the channel to the new media array.
  24598. session.media.push(unifiedLine);
  24599. }
  24600. });
  24601. // We regenerate the BUNDLE group with the new mids.
  24602. session.groups.some(function(group) {
  24603. if (group.type === 'BUNDLE') {
  24604. group.mids = types.join(' ');
  24605. return true;
  24606. }
  24607. });
  24608. // msid semantic
  24609. session.msidSemantic = {
  24610. semantic: 'WMS',
  24611. token: '*'
  24612. };
  24613. var resStr = transform.write(session);
  24614. return new RTCSessionDescription({
  24615. type: desc.type,
  24616. sdp: resStr
  24617. });
  24618. //#endregion
  24619. };
  24620. /**
  24621. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  24622. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  24623. * to FF.
  24624. *
  24625. * @param desc
  24626. * @returns {*}
  24627. */
  24628. Interop.prototype.toUnifiedPlan = function(desc) {
  24629. //#region Preliminary input validation.
  24630. if (typeof desc !== 'object' || desc === null ||
  24631. typeof desc.sdp !== 'string') {
  24632. console.warn('An empty description was passed as an argument.');
  24633. return desc;
  24634. }
  24635. var session = transform.parse(desc.sdp);
  24636. // If the SDP contains no media, there's nothing to transform.
  24637. if (typeof session.media === 'undefined' ||
  24638. !Array.isArray(session.media) || session.media.length === 0) {
  24639. console.warn('The description has no media.');
  24640. return desc;
  24641. }
  24642. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  24643. // a video, an audio and a data "channel" at most.
  24644. if (session.media.length > 3 || !session.media.every(function(m) {
  24645. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  24646. })) {
  24647. console.warn('This description does not look like Plan B.');
  24648. return desc;
  24649. }
  24650. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  24651. var mids = [];
  24652. session.media.forEach(function(m) {
  24653. mids.push(m.mid);
  24654. });
  24655. var hasBundle = false;
  24656. if (typeof session.groups !== 'undefined' &&
  24657. Array.isArray(session.groups)) {
  24658. hasBundle = session.groups.every(function(g) {
  24659. return g.type !== 'BUNDLE' ||
  24660. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  24661. });
  24662. }
  24663. if (!hasBundle) {
  24664. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  24665. " are not bundled were found.");
  24666. }
  24667. //#endregion
  24668. //#region Convert from Plan B to Unified Plan.
  24669. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  24670. // rebuild an equivalent Unified Plan offer/answer.
  24671. //
  24672. // For example, if this is a local answer (in Unified Plan style) that we
  24673. // convert to Plan B prior to handing it over to the application (the
  24674. // PeerConnection wrapper called us, for instance, after a successful
  24675. // createAnswer), we want to remember the m-line at which we've seen the
  24676. // (local) SSRC. That's because when the application wants to do call the
  24677. // SLD method, forcing us to do the inverse transformation (from Plan B to
  24678. // Unified Plan), we need to know to which m-line to assign the (local)
  24679. // SSRC. We also need to know all the other m-lines that the original
  24680. // answer had and include them in the transformed answer as well.
  24681. //
  24682. // Another example is if this is a remote offer that we convert to Plan B
  24683. // prior to giving it to the application, we want to remember the mid at
  24684. // which we've seen the (remote) SSRC.
  24685. //
  24686. // In the iteration that follows, we use the cached Unified Plan (if it
  24687. // exists) to assign mids to ssrcs.
  24688. var cached;
  24689. if (typeof this.cache[desc.type] !== 'undefined') {
  24690. cached = transform.parse(this.cache[desc.type]);
  24691. }
  24692. // A helper map that sends mids to m-line objects. We use it later to
  24693. // rebuild the Unified Plan style session.media array.
  24694. var mid2ul = {};
  24695. session.media.forEach(function(bLine) {
  24696. if ((typeof bLine.rtcpMux !== 'string' ||
  24697. bLine.rtcpMux !== 'rtcp-mux') &&
  24698. bLine.direction !== 'inactive') {
  24699. throw new Error("Cannot convert to Unified Plan because m-lines " +
  24700. "without the rtcp-mux attribute were found.");
  24701. }
  24702. if (bLine.type === 'application') {
  24703. mid2ul[bLine.mid] = bLine;
  24704. return;
  24705. }
  24706. // With rtcp-mux and bundle all the channels should have the same ICE
  24707. // stuff.
  24708. var sources = bLine.sources;
  24709. var ssrcGroups = bLine.ssrcGroups;
  24710. var candidates = bLine.candidates;
  24711. var iceUfrag = bLine.iceUfrag;
  24712. var icePwd = bLine.icePwd;
  24713. var fingerprint = bLine.fingerprint;
  24714. var port = bLine.port;
  24715. // We'll use the "bLine" object as a prototype for each new "mLine"
  24716. // that we create, but first we need to clean it up a bit.
  24717. delete bLine.sources;
  24718. delete bLine.ssrcGroups;
  24719. delete bLine.candidates;
  24720. delete bLine.iceUfrag;
  24721. delete bLine.icePwd;
  24722. delete bLine.fingerprint;
  24723. delete bLine.port;
  24724. delete bLine.mid;
  24725. // inverted ssrc group map
  24726. var ssrc2group = {};
  24727. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  24728. ssrcGroups.forEach(function (ssrcGroup) {
  24729. // TODO(gp) find out how to receive simulcast with FF. For the
  24730. // time being, hide it.
  24731. if (ssrcGroup.semantics === 'SIM') {
  24732. return;
  24733. }
  24734. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  24735. Array.isArray(ssrcGroup.ssrcs)) {
  24736. ssrcGroup.ssrcs.forEach(function (ssrc) {
  24737. if (typeof ssrc2group[ssrc] === 'undefined') {
  24738. ssrc2group[ssrc] = [];
  24739. }
  24740. ssrc2group[ssrc].push(ssrcGroup);
  24741. });
  24742. }
  24743. });
  24744. }
  24745. // ssrc to m-line index.
  24746. var ssrc2ml = {};
  24747. if (typeof sources === 'object') {
  24748. // Explode the Plan B channel sources with one m-line per source.
  24749. Object.keys(sources).forEach(function(ssrc) {
  24750. // The (unified) m-line for this SSRC. We either create it from
  24751. // scratch or, if it's a grouped SSRC, we re-use a related
  24752. // mline. In other words, if the source is grouped with another
  24753. // source, put the two together in the same m-line.
  24754. var unifiedLine;
  24755. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  24756. Array.isArray(ssrc2group[ssrc])) {
  24757. ssrc2group[ssrc].some(function (ssrcGroup) {
  24758. // ssrcGroup.ssrcs *is* an Array, no need to check
  24759. // again here.
  24760. return ssrcGroup.ssrcs.some(function (related) {
  24761. if (typeof ssrc2ml[related] === 'object') {
  24762. unifiedLine = ssrc2ml[related];
  24763. return true;
  24764. }
  24765. });
  24766. });
  24767. }
  24768. if (typeof unifiedLine === 'object') {
  24769. // the m-line already exists. Just add the source.
  24770. unifiedLine.sources[ssrc] = sources[ssrc];
  24771. delete sources[ssrc].msid;
  24772. } else {
  24773. // Use the "bLine" as a prototype for the "unifiedLine".
  24774. unifiedLine = Object.create(bLine);
  24775. ssrc2ml[ssrc] = unifiedLine;
  24776. if (typeof sources[ssrc].msid !== 'undefined') {
  24777. // Assign the msid of the source to the m-line. Note
  24778. // that it is not guaranteed that the source will have
  24779. // msid. In particular "recvonly" sources don't have an
  24780. // msid. Note that "recvonly" is a term only defined
  24781. // for m-lines.
  24782. unifiedLine.msid = sources[ssrc].msid;
  24783. delete sources[ssrc].msid;
  24784. }
  24785. // We assign one SSRC per media line.
  24786. unifiedLine.sources = {};
  24787. unifiedLine.sources[ssrc] = sources[ssrc];
  24788. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  24789. // Use the cached Unified Plan SDP (if it exists) to assign
  24790. // SSRCs to mids.
  24791. if (typeof cached !== 'undefined' &&
  24792. typeof cached.media !== 'undefined' &&
  24793. Array.isArray(cached.media)) {
  24794. cached.media.forEach(function (m) {
  24795. if (typeof m.sources === 'object') {
  24796. Object.keys(m.sources).forEach(function (s) {
  24797. if (s === ssrc) {
  24798. unifiedLine.mid = m.mid;
  24799. }
  24800. });
  24801. }
  24802. });
  24803. }
  24804. if (typeof unifiedLine.mid === 'undefined') {
  24805. // If this is an SSRC that we see for the first time
  24806. // assign it a new mid. This is typically the case when
  24807. // this method is called to transform a remote
  24808. // description for the first time or when there is a
  24809. // new SSRC in the remote description because a new
  24810. // peer has joined the conference. Local SSRCs should
  24811. // have already been added to the map in the toPlanB
  24812. // method.
  24813. //
  24814. // Because FF generates answers in Unified Plan style,
  24815. // we MUST already have a cached answer with all the
  24816. // local SSRCs mapped to some m-line/mid.
  24817. if (desc.type === 'answer') {
  24818. throw new Error("An unmapped SSRC was found.");
  24819. }
  24820. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  24821. }
  24822. // Include the candidates in the 1st media line.
  24823. unifiedLine.candidates = candidates;
  24824. unifiedLine.iceUfrag = iceUfrag;
  24825. unifiedLine.icePwd = icePwd;
  24826. unifiedLine.fingerprint = fingerprint;
  24827. unifiedLine.port = port;
  24828. mid2ul[unifiedLine.mid] = unifiedLine;
  24829. }
  24830. });
  24831. }
  24832. });
  24833. // Rebuild the media array in the right order and add the missing mLines
  24834. // (missing from the Plan B SDP).
  24835. session.media = [];
  24836. mids = []; // reuse
  24837. if (desc.type === 'answer') {
  24838. // The media lines in the answer must match the media lines in the
  24839. // offer. The order is important too. Here we assume that Firefox is the
  24840. // answerer, so we merely have to use the reconstructed (unified) answer
  24841. // to update the cached (unified) answer accordingly.
  24842. //
  24843. // In the general case, one would have to use the cached (unified) offer
  24844. // to find the m-lines that are missing from the reconstructed answer,
  24845. // potentially grabbing them from the cached (unified) answer. One has
  24846. // to be carefull with this approach because inactive m-lines do not
  24847. // always have an mid, making it tricky (impossible?) to find where
  24848. // exactly and which m-lines are missing from the reconstructed answer.
  24849. for (var i = 0; i < cached.media.length; i++) {
  24850. var unifiedLine = cached.media[i];
  24851. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  24852. // The mid isn't in the reconstructed (unified) answer.
  24853. // This is either a (unified) m-line containing a remote
  24854. // track only, or a (unified) m-line containing a remote
  24855. // track and a local track that has been removed.
  24856. // In either case, it MUST exist in the cached
  24857. // (unified) answer.
  24858. //
  24859. // In case this is a removed local track, clean-up
  24860. // the (unified) m-line and make sure it's 'recvonly' or
  24861. // 'inactive'.
  24862. delete unifiedLine.msid;
  24863. delete unifiedLine.sources;
  24864. delete unifiedLine.ssrcGroups;
  24865. if (!unifiedLine.direction
  24866. || unifiedLine.direction === 'sendrecv')
  24867. unifiedLine.direction = 'recvonly';
  24868. if (!unifiedLine.direction
  24869. || unifiedLine.direction === 'sendonly')
  24870. unifiedLine.direction = 'inactive';
  24871. } else {
  24872. // This is an (unified) m-line/channel that contains a local
  24873. // track (sendrecv or sendonly channel) or it's a unified
  24874. // recvonly m-line/channel. In either case, since we're
  24875. // going from PlanB -> Unified Plan this m-line MUST
  24876. // exist in the cached answer.
  24877. }
  24878. session.media.push(unifiedLine);
  24879. if (typeof unifiedLine.mid === 'string') {
  24880. // inactive lines don't/may not have an mid.
  24881. mids.push(unifiedLine.mid);
  24882. }
  24883. }
  24884. } else {
  24885. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  24886. // under any circumstances. If we are no longer interested in sending a
  24887. // track, we just remove the msid and ssrc attributes and set it to
  24888. // either a=recvonly (as the reofferer, we must use recvonly if the
  24889. // other side was previously sending on the m-section, but we can also
  24890. // leave the possibility open if it wasn't previously in use), or
  24891. // a=inacive.
  24892. if (typeof cached !== 'undefined' &&
  24893. typeof cached.media !== 'undefined' &&
  24894. Array.isArray(cached.media)) {
  24895. cached.media.forEach(function(unifiedLine) {
  24896. mids.push(unifiedLine.mid);
  24897. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  24898. session.media.push(mid2ul[unifiedLine.mid]);
  24899. } else {
  24900. delete unifiedLine.msid;
  24901. delete unifiedLine.sources;
  24902. delete unifiedLine.ssrcGroups;
  24903. if (!unifiedLine.direction
  24904. || unifiedLine.direction === 'sendrecv')
  24905. unifiedLine.direction = 'recvonly';
  24906. if (!unifiedLine.direction
  24907. || unifiedLine.direction === 'sendonly')
  24908. unifiedLine.direction = 'inactive';
  24909. session.media.push(unifiedLine);
  24910. }
  24911. });
  24912. }
  24913. // Add all the remaining (new) m-lines of the transformed SDP.
  24914. Object.keys(mid2ul).forEach(function(mid) {
  24915. if (mids.indexOf(mid) === -1) {
  24916. mids.push(mid);
  24917. if (typeof mid2ul[mid].direction === 'recvonly') {
  24918. // This is a remote recvonly channel. Add its SSRC to the
  24919. // appropriate sendrecv or sendonly channel.
  24920. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  24921. session.media.some(function (unifiedLine) {
  24922. if ((unifiedLine.direction === 'sendrecv' ||
  24923. unifiedLine.direction === 'sendonly') &&
  24924. unifiedLine.type === mid2ul[mid].type) {
  24925. // mid2ul[mid] shouldn't have any ssrc-groups
  24926. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  24927. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  24928. });
  24929. return true;
  24930. }
  24931. });
  24932. } else {
  24933. session.media.push(mid2ul[mid]);
  24934. }
  24935. }
  24936. });
  24937. }
  24938. // We regenerate the BUNDLE group (since we regenerated the mids)
  24939. session.groups.some(function(group) {
  24940. if (group.type === 'BUNDLE') {
  24941. group.mids = mids.join(' ');
  24942. return true;
  24943. }
  24944. });
  24945. // msid semantic
  24946. session.msidSemantic = {
  24947. semantic: 'WMS',
  24948. token: '*'
  24949. };
  24950. var resStr = transform.write(session);
  24951. // Cache the transformed SDP (Unified Plan) for later re-use in this
  24952. // function.
  24953. this.cache[desc.type] = resStr;
  24954. return new RTCSessionDescription({
  24955. type: desc.type,
  24956. sdp: resStr
  24957. });
  24958. //#endregion
  24959. };
  24960. },{"./array-equals":86,"./transform":89}],89:[function(require,module,exports){
  24961. var transform = require('sdp-transform');
  24962. exports.write = function(session, opts) {
  24963. if (typeof session !== 'undefined' &&
  24964. typeof session.media !== 'undefined' &&
  24965. Array.isArray(session.media)) {
  24966. session.media.forEach(function (mLine) {
  24967. // expand sources to ssrcs
  24968. if (typeof mLine.sources !== 'undefined' &&
  24969. Object.keys(mLine.sources).length !== 0) {
  24970. mLine.ssrcs = [];
  24971. Object.keys(mLine.sources).forEach(function (ssrc) {
  24972. var source = mLine.sources[ssrc];
  24973. Object.keys(source).forEach(function (attribute) {
  24974. mLine.ssrcs.push({
  24975. id: ssrc,
  24976. attribute: attribute,
  24977. value: source[attribute]
  24978. });
  24979. });
  24980. });
  24981. delete mLine.sources;
  24982. }
  24983. // join ssrcs in ssrc groups
  24984. if (typeof mLine.ssrcGroups !== 'undefined' &&
  24985. Array.isArray(mLine.ssrcGroups)) {
  24986. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  24987. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  24988. Array.isArray(ssrcGroup.ssrcs)) {
  24989. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  24990. }
  24991. });
  24992. }
  24993. });
  24994. }
  24995. // join group mids
  24996. if (typeof session !== 'undefined' &&
  24997. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  24998. session.groups.forEach(function (g) {
  24999. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  25000. g.mids = g.mids.join(' ');
  25001. }
  25002. });
  25003. }
  25004. return transform.write(session, opts);
  25005. };
  25006. exports.parse = function(sdp) {
  25007. var session = transform.parse(sdp);
  25008. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  25009. Array.isArray(session.media)) {
  25010. session.media.forEach(function (mLine) {
  25011. // group sources attributes by ssrc
  25012. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  25013. mLine.sources = {};
  25014. mLine.ssrcs.forEach(function (ssrc) {
  25015. if (!mLine.sources[ssrc.id])
  25016. mLine.sources[ssrc.id] = {};
  25017. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25018. });
  25019. delete mLine.ssrcs;
  25020. }
  25021. // split ssrcs in ssrc groups
  25022. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25023. Array.isArray(mLine.ssrcGroups)) {
  25024. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25025. if (typeof ssrcGroup.ssrcs === 'string') {
  25026. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  25027. }
  25028. });
  25029. }
  25030. });
  25031. }
  25032. // split group mids
  25033. if (typeof session !== 'undefined' &&
  25034. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25035. session.groups.forEach(function (g) {
  25036. if (typeof g.mids === 'string') {
  25037. g.mids = g.mids.split(' ');
  25038. }
  25039. });
  25040. }
  25041. return session;
  25042. };
  25043. },{"sdp-transform":91}],90:[function(require,module,exports){
  25044. var grammar = module.exports = {
  25045. v: [{
  25046. name: 'version',
  25047. reg: /^(\d*)$/
  25048. }],
  25049. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  25050. // NB: sessionId will be a String in most cases because it is huge
  25051. name: 'origin',
  25052. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  25053. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  25054. format: "%s %s %d %s IP%d %s"
  25055. }],
  25056. // default parsing of these only (though some of these feel outdated)
  25057. s: [{ name: 'name' }],
  25058. i: [{ name: 'description' }],
  25059. u: [{ name: 'uri' }],
  25060. e: [{ name: 'email' }],
  25061. p: [{ name: 'phone' }],
  25062. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  25063. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  25064. //k: [{}], // outdated thing ignored
  25065. t: [{ //t=0 0
  25066. name: 'timing',
  25067. reg: /^(\d*) (\d*)/,
  25068. names: ['start', 'stop'],
  25069. format: "%d %d"
  25070. }],
  25071. c: [{ //c=IN IP4 10.47.197.26
  25072. name: 'connection',
  25073. reg: /^IN IP(\d) (\S*)/,
  25074. names: ['version', 'ip'],
  25075. format: "IN IP%d %s"
  25076. }],
  25077. b: [{ //b=AS:4000
  25078. push: 'bandwidth',
  25079. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  25080. names: ['type', 'limit'],
  25081. format: "%s:%s"
  25082. }],
  25083. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  25084. // NB: special - pushes to session
  25085. // TODO: rtp/fmtp should be filtered by the payloads found here?
  25086. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  25087. names: ['type', 'port', 'protocol', 'payloads'],
  25088. format: "%s %d %s %s"
  25089. }],
  25090. a: [
  25091. { //a=rtpmap:110 opus/48000/2
  25092. push: 'rtp',
  25093. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  25094. names: ['payload', 'codec', 'rate', 'encoding'],
  25095. format: function (o) {
  25096. return (o.encoding) ?
  25097. "rtpmap:%d %s/%s/%s":
  25098. "rtpmap:%d %s/%s";
  25099. }
  25100. },
  25101. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  25102. push: 'fmtp',
  25103. reg: /^fmtp:(\d*) (\S*)/,
  25104. names: ['payload', 'config'],
  25105. format: "fmtp:%d %s"
  25106. },
  25107. { //a=control:streamid=0
  25108. name: 'control',
  25109. reg: /^control:(.*)/,
  25110. format: "control:%s"
  25111. },
  25112. { //a=rtcp:65179 IN IP4 193.84.77.194
  25113. name: 'rtcp',
  25114. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  25115. names: ['port', 'netType', 'ipVer', 'address'],
  25116. format: function (o) {
  25117. return (o.address != null) ?
  25118. "rtcp:%d %s IP%d %s":
  25119. "rtcp:%d";
  25120. }
  25121. },
  25122. { //a=rtcp-fb:98 trr-int 100
  25123. push: 'rtcpFbTrrInt',
  25124. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  25125. names: ['payload', 'value'],
  25126. format: "rtcp-fb:%d trr-int %d"
  25127. },
  25128. { //a=rtcp-fb:98 nack rpsi
  25129. push: 'rtcpFb',
  25130. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  25131. names: ['payload', 'type', 'subtype'],
  25132. format: function (o) {
  25133. return (o.subtype != null) ?
  25134. "rtcp-fb:%s %s %s":
  25135. "rtcp-fb:%s %s";
  25136. }
  25137. },
  25138. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  25139. //a=extmap:1/recvonly URI-gps-string
  25140. push: 'ext',
  25141. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  25142. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  25143. format: function (o) {
  25144. return (o.config != null) ?
  25145. "extmap:%s %s %s":
  25146. "extmap:%s %s";
  25147. }
  25148. },
  25149. {
  25150. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  25151. push: 'crypto',
  25152. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  25153. names: ['id', 'suite', 'config', 'sessionConfig'],
  25154. format: function (o) {
  25155. return (o.sessionConfig != null) ?
  25156. "crypto:%d %s %s %s":
  25157. "crypto:%d %s %s";
  25158. }
  25159. },
  25160. { //a=setup:actpass
  25161. name: 'setup',
  25162. reg: /^setup:(\w*)/,
  25163. format: "setup:%s"
  25164. },
  25165. { //a=mid:1
  25166. name: 'mid',
  25167. reg: /^mid:([^\s]*)/,
  25168. format: "mid:%s"
  25169. },
  25170. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  25171. name: 'msid',
  25172. reg: /^msid:(.*)/,
  25173. format: "msid:%s"
  25174. },
  25175. { //a=ptime:20
  25176. name: 'ptime',
  25177. reg: /^ptime:(\d*)/,
  25178. format: "ptime:%d"
  25179. },
  25180. { //a=maxptime:60
  25181. name: 'maxptime',
  25182. reg: /^maxptime:(\d*)/,
  25183. format: "maxptime:%d"
  25184. },
  25185. { //a=sendrecv
  25186. name: 'direction',
  25187. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  25188. },
  25189. { //a=ice-lite
  25190. name: 'icelite',
  25191. reg: /^(ice-lite)/
  25192. },
  25193. { //a=ice-ufrag:F7gI
  25194. name: 'iceUfrag',
  25195. reg: /^ice-ufrag:(\S*)/,
  25196. format: "ice-ufrag:%s"
  25197. },
  25198. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  25199. name: 'icePwd',
  25200. reg: /^ice-pwd:(\S*)/,
  25201. format: "ice-pwd:%s"
  25202. },
  25203. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  25204. name: 'fingerprint',
  25205. reg: /^fingerprint:(\S*) (\S*)/,
  25206. names: ['type', 'hash'],
  25207. format: "fingerprint:%s %s"
  25208. },
  25209. {
  25210. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  25211. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  25212. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  25213. push:'candidates',
  25214. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  25215. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  25216. format: function (o) {
  25217. var str = "candidate:%s %d %s %d %s %d typ %s";
  25218. // NB: candidate has two optional chunks, so %void middle one if it's missing
  25219. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  25220. if (o.generation != null) {
  25221. str += " generation %d";
  25222. }
  25223. return str;
  25224. }
  25225. },
  25226. { //a=end-of-candidates (keep after the candidates line for readability)
  25227. name: 'endOfCandidates',
  25228. reg: /^(end-of-candidates)/
  25229. },
  25230. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  25231. name: 'remoteCandidates',
  25232. reg: /^remote-candidates:(.*)/,
  25233. format: "remote-candidates:%s"
  25234. },
  25235. { //a=ice-options:google-ice
  25236. name: 'iceOptions',
  25237. reg: /^ice-options:(\S*)/,
  25238. format: "ice-options:%s"
  25239. },
  25240. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  25241. push: "ssrcs",
  25242. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  25243. names: ['id', 'attribute', 'value'],
  25244. format: "ssrc:%d %s:%s"
  25245. },
  25246. { //a=ssrc-group:FEC 1 2
  25247. push: "ssrcGroups",
  25248. reg: /^ssrc-group:(\w*) (.*)/,
  25249. names: ['semantics', 'ssrcs'],
  25250. format: "ssrc-group:%s %s"
  25251. },
  25252. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  25253. name: "msidSemantic",
  25254. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  25255. names: ['semantic', 'token'],
  25256. format: "msid-semantic: %s %s" // space after ":" is not accidental
  25257. },
  25258. { //a=group:BUNDLE audio video
  25259. push: 'groups',
  25260. reg: /^group:(\w*) (.*)/,
  25261. names: ['type', 'mids'],
  25262. format: "group:%s %s"
  25263. },
  25264. { //a=rtcp-mux
  25265. name: 'rtcpMux',
  25266. reg: /^(rtcp-mux)/
  25267. },
  25268. { //a=rtcp-rsize
  25269. name: 'rtcpRsize',
  25270. reg: /^(rtcp-rsize)/
  25271. },
  25272. { // any a= that we don't understand is kepts verbatim on media.invalid
  25273. push: 'invalid',
  25274. names: ["value"]
  25275. }
  25276. ]
  25277. };
  25278. // set sensible defaults to avoid polluting the grammar with boring details
  25279. Object.keys(grammar).forEach(function (key) {
  25280. var objs = grammar[key];
  25281. objs.forEach(function (obj) {
  25282. if (!obj.reg) {
  25283. obj.reg = /(.*)/;
  25284. }
  25285. if (!obj.format) {
  25286. obj.format = "%s";
  25287. }
  25288. });
  25289. });
  25290. },{}],91:[function(require,module,exports){
  25291. var parser = require('./parser');
  25292. var writer = require('./writer');
  25293. exports.write = writer;
  25294. exports.parse = parser.parse;
  25295. exports.parseFmtpConfig = parser.parseFmtpConfig;
  25296. exports.parsePayloads = parser.parsePayloads;
  25297. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  25298. },{"./parser":92,"./writer":93}],92:[function(require,module,exports){
  25299. var toIntIfInt = function (v) {
  25300. return String(Number(v)) === v ? Number(v) : v;
  25301. };
  25302. var attachProperties = function (match, location, names, rawName) {
  25303. if (rawName && !names) {
  25304. location[rawName] = toIntIfInt(match[1]);
  25305. }
  25306. else {
  25307. for (var i = 0; i < names.length; i += 1) {
  25308. if (match[i+1] != null) {
  25309. location[names[i]] = toIntIfInt(match[i+1]);
  25310. }
  25311. }
  25312. }
  25313. };
  25314. var parseReg = function (obj, location, content) {
  25315. var needsBlank = obj.name && obj.names;
  25316. if (obj.push && !location[obj.push]) {
  25317. location[obj.push] = [];
  25318. }
  25319. else if (needsBlank && !location[obj.name]) {
  25320. location[obj.name] = {};
  25321. }
  25322. var keyLocation = obj.push ?
  25323. {} : // blank object that will be pushed
  25324. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  25325. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  25326. if (obj.push) {
  25327. location[obj.push].push(keyLocation);
  25328. }
  25329. };
  25330. var grammar = require('./grammar');
  25331. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  25332. exports.parse = function (sdp) {
  25333. var session = {}
  25334. , media = []
  25335. , location = session; // points at where properties go under (one of the above)
  25336. // parse lines we understand
  25337. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  25338. var type = l[0];
  25339. var content = l.slice(2);
  25340. if (type === 'm') {
  25341. media.push({rtp: [], fmtp: []});
  25342. location = media[media.length-1]; // point at latest media line
  25343. }
  25344. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  25345. var obj = grammar[type][j];
  25346. if (obj.reg.test(content)) {
  25347. return parseReg(obj, location, content);
  25348. }
  25349. }
  25350. });
  25351. session.media = media; // link it up
  25352. return session;
  25353. };
  25354. var fmtpReducer = function (acc, expr) {
  25355. var s = expr.split('=');
  25356. if (s.length === 2) {
  25357. acc[s[0]] = toIntIfInt(s[1]);
  25358. }
  25359. return acc;
  25360. };
  25361. exports.parseFmtpConfig = function (str) {
  25362. return str.split(';').reduce(fmtpReducer, {});
  25363. };
  25364. exports.parsePayloads = function (str) {
  25365. return str.split(' ').map(Number);
  25366. };
  25367. exports.parseRemoteCandidates = function (str) {
  25368. var candidates = [];
  25369. var parts = str.split(' ').map(toIntIfInt);
  25370. for (var i = 0; i < parts.length; i += 3) {
  25371. candidates.push({
  25372. component: parts[i],
  25373. ip: parts[i + 1],
  25374. port: parts[i + 2]
  25375. });
  25376. }
  25377. return candidates;
  25378. };
  25379. },{"./grammar":90}],93:[function(require,module,exports){
  25380. var grammar = require('./grammar');
  25381. // customized util.format - discards excess arguments and can void middle ones
  25382. var formatRegExp = /%[sdv%]/g;
  25383. var format = function (formatStr) {
  25384. var i = 1;
  25385. var args = arguments;
  25386. var len = args.length;
  25387. return formatStr.replace(formatRegExp, function (x) {
  25388. if (i >= len) {
  25389. return x; // missing argument
  25390. }
  25391. var arg = args[i];
  25392. i += 1;
  25393. switch (x) {
  25394. case '%%':
  25395. return '%';
  25396. case '%s':
  25397. return String(arg);
  25398. case '%d':
  25399. return Number(arg);
  25400. case '%v':
  25401. return '';
  25402. }
  25403. });
  25404. // NB: we discard excess arguments - they are typically undefined from makeLine
  25405. };
  25406. var makeLine = function (type, obj, location) {
  25407. var str = obj.format instanceof Function ?
  25408. (obj.format(obj.push ? location : location[obj.name])) :
  25409. obj.format;
  25410. var args = [type + '=' + str];
  25411. if (obj.names) {
  25412. for (var i = 0; i < obj.names.length; i += 1) {
  25413. var n = obj.names[i];
  25414. if (obj.name) {
  25415. args.push(location[obj.name][n]);
  25416. }
  25417. else { // for mLine and push attributes
  25418. args.push(location[obj.names[i]]);
  25419. }
  25420. }
  25421. }
  25422. else {
  25423. args.push(location[obj.name]);
  25424. }
  25425. return format.apply(null, args);
  25426. };
  25427. // RFC specified order
  25428. // TODO: extend this with all the rest
  25429. var defaultOuterOrder = [
  25430. 'v', 'o', 's', 'i',
  25431. 'u', 'e', 'p', 'c',
  25432. 'b', 't', 'r', 'z', 'a'
  25433. ];
  25434. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  25435. module.exports = function (session, opts) {
  25436. opts = opts || {};
  25437. // ensure certain properties exist
  25438. if (session.version == null) {
  25439. session.version = 0; // "v=0" must be there (only defined version atm)
  25440. }
  25441. if (session.name == null) {
  25442. session.name = " "; // "s= " must be there if no meaningful name set
  25443. }
  25444. session.media.forEach(function (mLine) {
  25445. if (mLine.payloads == null) {
  25446. mLine.payloads = "";
  25447. }
  25448. });
  25449. var outerOrder = opts.outerOrder || defaultOuterOrder;
  25450. var innerOrder = opts.innerOrder || defaultInnerOrder;
  25451. var sdp = [];
  25452. // loop through outerOrder for matching properties on session
  25453. outerOrder.forEach(function (type) {
  25454. grammar[type].forEach(function (obj) {
  25455. if (obj.name in session && session[obj.name] != null) {
  25456. sdp.push(makeLine(type, obj, session));
  25457. }
  25458. else if (obj.push in session && session[obj.push] != null) {
  25459. session[obj.push].forEach(function (el) {
  25460. sdp.push(makeLine(type, obj, el));
  25461. });
  25462. }
  25463. });
  25464. });
  25465. // then for each media line, follow the innerOrder
  25466. session.media.forEach(function (mLine) {
  25467. sdp.push(makeLine('m', grammar.m[0], mLine));
  25468. innerOrder.forEach(function (type) {
  25469. grammar[type].forEach(function (obj) {
  25470. if (obj.name in mLine && mLine[obj.name] != null) {
  25471. sdp.push(makeLine(type, obj, mLine));
  25472. }
  25473. else if (obj.push in mLine && mLine[obj.push] != null) {
  25474. mLine[obj.push].forEach(function (el) {
  25475. sdp.push(makeLine(type, obj, el));
  25476. });
  25477. }
  25478. });
  25479. });
  25480. });
  25481. return sdp.join('\r\n') + '\r\n';
  25482. };
  25483. },{"./grammar":90}],94:[function(require,module,exports){
  25484. var MediaStreamType = {
  25485. VIDEO_TYPE: "Video",
  25486. AUDIO_TYPE: "Audio"
  25487. };
  25488. module.exports = MediaStreamType;
  25489. },{}],95:[function(require,module,exports){
  25490. var RTCBrowserType = {
  25491. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  25492. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  25493. };
  25494. module.exports = RTCBrowserType;
  25495. },{}],96:[function(require,module,exports){
  25496. var RTCEvents = {
  25497. LASTN_CHANGED: "rtc.lastn_changed",
  25498. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  25499. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  25500. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  25501. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  25502. SIMULCAST_START: "rtc.simlcast_start",
  25503. SIMULCAST_STOP: "rtc.simlcast_stop",
  25504. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  25505. };
  25506. module.exports = RTCEvents;
  25507. },{}],97:[function(require,module,exports){
  25508. var Resolutions = {
  25509. "1080": {
  25510. width: 1920,
  25511. height: 1080,
  25512. order: 7
  25513. },
  25514. "fullhd": {
  25515. width: 1920,
  25516. height: 1080,
  25517. order: 7
  25518. },
  25519. "720": {
  25520. width: 1280,
  25521. height: 720,
  25522. order: 6
  25523. },
  25524. "hd": {
  25525. width: 1280,
  25526. height: 720,
  25527. order: 6
  25528. },
  25529. "960": {
  25530. width: 960,
  25531. height: 720,
  25532. order: 5
  25533. },
  25534. "640": {
  25535. width: 640,
  25536. height: 480,
  25537. order: 4
  25538. },
  25539. "vga": {
  25540. width: 640,
  25541. height: 480,
  25542. order: 4
  25543. },
  25544. "360": {
  25545. width: 640,
  25546. height: 360,
  25547. order: 3
  25548. },
  25549. "320": {
  25550. width: 320,
  25551. height: 240,
  25552. order: 2
  25553. },
  25554. "180": {
  25555. width: 320,
  25556. height: 180,
  25557. order: 1
  25558. }
  25559. };
  25560. module.exports = Resolutions;
  25561. },{}],98:[function(require,module,exports){
  25562. var StreamEventTypes = {
  25563. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  25564. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  25565. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  25566. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  25567. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  25568. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  25569. };
  25570. module.exports = StreamEventTypes;
  25571. },{}],99:[function(require,module,exports){
  25572. var UIEvents = {
  25573. NICKNAME_CHANGED: "UI.nickname_changed",
  25574. SELECTED_ENDPOINT: "UI.selected_endpoint",
  25575. PINNED_ENDPOINT: "UI.pinned_endpoint"
  25576. };
  25577. module.exports = UIEvents;
  25578. },{}],100:[function(require,module,exports){
  25579. var AuthenticationEvents = {
  25580. /**
  25581. * Event callback arguments:
  25582. * function(authenticationEnabled, userIdentity)
  25583. * authenticationEnabled - indicates whether authentication has been enabled
  25584. * in this session
  25585. * userIdentity - if user has been logged in then it contains user name. If
  25586. * contains 'null' or 'undefined' then user is not logged in.
  25587. */
  25588. IDENTITY_UPDATED: "authentication.identity_updated"
  25589. };
  25590. module.exports = AuthenticationEvents;
  25591. },{}],101:[function(require,module,exports){
  25592. var CQEvents = {
  25593. LOCALSTATS_UPDATED: "cq.localstats_updated",
  25594. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  25595. STOP: "cq.stop"
  25596. };
  25597. module.exports = CQEvents;
  25598. },{}],102:[function(require,module,exports){
  25599. var DesktopSharingEventTypes = {
  25600. INIT: "ds.init",
  25601. SWITCHING_DONE: "ds.switching_done",
  25602. NEW_STREAM_CREATED: "ds.new_stream_created"
  25603. };
  25604. module.exports = DesktopSharingEventTypes;
  25605. },{}],103:[function(require,module,exports){
  25606. var Events = {
  25607. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  25608. };
  25609. module.exports = Events;
  25610. },{}],104:[function(require,module,exports){
  25611. module.exports = {
  25612. getLanguages : function () {
  25613. var languages = [];
  25614. for(var lang in this)
  25615. {
  25616. if(typeof this[lang] === "string")
  25617. languages.push(this[lang]);
  25618. }
  25619. return languages;
  25620. },
  25621. EN: "en",
  25622. BG: "bg",
  25623. DE: "de",
  25624. TR: "tr"
  25625. }
  25626. },{}],105:[function(require,module,exports){
  25627. var XMPPEvents = {
  25628. CONNECTION_FAILED: "xmpp.connection.failed",
  25629. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  25630. CALL_TERMINATED: "xmpp.callterminated.jingle",
  25631. CALL_INCOMING: "xmpp.callincoming.jingle",
  25632. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  25633. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  25634. KICKED: "xmpp.kicked",
  25635. BRIDGE_DOWN: "xmpp.bridge_down",
  25636. USER_ID_CHANGED: "xmpp.user_id_changed",
  25637. STREAMS_CHANGED: "xmpp.streams_changed",
  25638. // We joined the MUC
  25639. MUC_JOINED: "xmpp.muc_joined",
  25640. // A member joined the MUC
  25641. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  25642. // A member left the MUC
  25643. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  25644. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  25645. MUC_DESTROYED: "xmpp.muc_destroyed",
  25646. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  25647. REMOTE_STATS: "xmpp.remote_stats",
  25648. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  25649. PRESENCE_STATUS: "xmpp.presence_status",
  25650. RESERVATION_ERROR: "xmpp.room_reservation_error",
  25651. SUBJECT_CHANGED: "xmpp.subject_changed",
  25652. MESSAGE_RECEIVED: "xmpp.message_received",
  25653. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  25654. PASSWORD_REQUIRED: "xmpp.password_required",
  25655. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  25656. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  25657. ETHERPAD: "xmpp.etherpad",
  25658. DEVICE_AVAILABLE: "xmpp.device_available",
  25659. START_MUTED: "xmpp.start_muted"
  25660. };
  25661. module.exports = XMPPEvents;
  25662. },{}],106:[function(require,module,exports){
  25663. // Copyright Joyent, Inc. and other Node contributors.
  25664. //
  25665. // Permission is hereby granted, free of charge, to any person obtaining a
  25666. // copy of this software and associated documentation files (the
  25667. // "Software"), to deal in the Software without restriction, including
  25668. // without limitation the rights to use, copy, modify, merge, publish,
  25669. // distribute, sublicense, and/or sell copies of the Software, and to permit
  25670. // persons to whom the Software is furnished to do so, subject to the
  25671. // following conditions:
  25672. //
  25673. // The above copyright notice and this permission notice shall be included
  25674. // in all copies or substantial portions of the Software.
  25675. //
  25676. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  25677. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25678. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  25679. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  25680. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  25681. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  25682. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  25683. function EventEmitter() {
  25684. this._events = this._events || {};
  25685. this._maxListeners = this._maxListeners || undefined;
  25686. }
  25687. module.exports = EventEmitter;
  25688. // Backwards-compat with node 0.10.x
  25689. EventEmitter.EventEmitter = EventEmitter;
  25690. EventEmitter.prototype._events = undefined;
  25691. EventEmitter.prototype._maxListeners = undefined;
  25692. // By default EventEmitters will print a warning if more than 10 listeners are
  25693. // added to it. This is a useful default which helps finding memory leaks.
  25694. EventEmitter.defaultMaxListeners = 10;
  25695. // Obviously not all Emitters should be limited to 10. This function allows
  25696. // that to be increased. Set to zero for unlimited.
  25697. EventEmitter.prototype.setMaxListeners = function(n) {
  25698. if (!isNumber(n) || n < 0 || isNaN(n))
  25699. throw TypeError('n must be a positive number');
  25700. this._maxListeners = n;
  25701. return this;
  25702. };
  25703. EventEmitter.prototype.emit = function(type) {
  25704. var er, handler, len, args, i, listeners;
  25705. if (!this._events)
  25706. this._events = {};
  25707. // If there is no 'error' event listener then throw.
  25708. if (type === 'error') {
  25709. if (!this._events.error ||
  25710. (isObject(this._events.error) && !this._events.error.length)) {
  25711. er = arguments[1];
  25712. if (er instanceof Error) {
  25713. throw er; // Unhandled 'error' event
  25714. }
  25715. throw TypeError('Uncaught, unspecified "error" event.');
  25716. }
  25717. }
  25718. handler = this._events[type];
  25719. if (isUndefined(handler))
  25720. return false;
  25721. if (isFunction(handler)) {
  25722. switch (arguments.length) {
  25723. // fast cases
  25724. case 1:
  25725. handler.call(this);
  25726. break;
  25727. case 2:
  25728. handler.call(this, arguments[1]);
  25729. break;
  25730. case 3:
  25731. handler.call(this, arguments[1], arguments[2]);
  25732. break;
  25733. // slower
  25734. default:
  25735. len = arguments.length;
  25736. args = new Array(len - 1);
  25737. for (i = 1; i < len; i++)
  25738. args[i - 1] = arguments[i];
  25739. handler.apply(this, args);
  25740. }
  25741. } else if (isObject(handler)) {
  25742. len = arguments.length;
  25743. args = new Array(len - 1);
  25744. for (i = 1; i < len; i++)
  25745. args[i - 1] = arguments[i];
  25746. listeners = handler.slice();
  25747. len = listeners.length;
  25748. for (i = 0; i < len; i++)
  25749. listeners[i].apply(this, args);
  25750. }
  25751. return true;
  25752. };
  25753. EventEmitter.prototype.addListener = function(type, listener) {
  25754. var m;
  25755. if (!isFunction(listener))
  25756. throw TypeError('listener must be a function');
  25757. if (!this._events)
  25758. this._events = {};
  25759. // To avoid recursion in the case that type === "newListener"! Before
  25760. // adding it to the listeners, first emit "newListener".
  25761. if (this._events.newListener)
  25762. this.emit('newListener', type,
  25763. isFunction(listener.listener) ?
  25764. listener.listener : listener);
  25765. if (!this._events[type])
  25766. // Optimize the case of one listener. Don't need the extra array object.
  25767. this._events[type] = listener;
  25768. else if (isObject(this._events[type]))
  25769. // If we've already got an array, just append.
  25770. this._events[type].push(listener);
  25771. else
  25772. // Adding the second element, need to change to array.
  25773. this._events[type] = [this._events[type], listener];
  25774. // Check for listener leak
  25775. if (isObject(this._events[type]) && !this._events[type].warned) {
  25776. var m;
  25777. if (!isUndefined(this._maxListeners)) {
  25778. m = this._maxListeners;
  25779. } else {
  25780. m = EventEmitter.defaultMaxListeners;
  25781. }
  25782. if (m && m > 0 && this._events[type].length > m) {
  25783. this._events[type].warned = true;
  25784. console.error('(node) warning: possible EventEmitter memory ' +
  25785. 'leak detected. %d listeners added. ' +
  25786. 'Use emitter.setMaxListeners() to increase limit.',
  25787. this._events[type].length);
  25788. if (typeof console.trace === 'function') {
  25789. // not supported in IE 10
  25790. console.trace();
  25791. }
  25792. }
  25793. }
  25794. return this;
  25795. };
  25796. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  25797. EventEmitter.prototype.once = function(type, listener) {
  25798. if (!isFunction(listener))
  25799. throw TypeError('listener must be a function');
  25800. var fired = false;
  25801. function g() {
  25802. this.removeListener(type, g);
  25803. if (!fired) {
  25804. fired = true;
  25805. listener.apply(this, arguments);
  25806. }
  25807. }
  25808. g.listener = listener;
  25809. this.on(type, g);
  25810. return this;
  25811. };
  25812. // emits a 'removeListener' event iff the listener was removed
  25813. EventEmitter.prototype.removeListener = function(type, listener) {
  25814. var list, position, length, i;
  25815. if (!isFunction(listener))
  25816. throw TypeError('listener must be a function');
  25817. if (!this._events || !this._events[type])
  25818. return this;
  25819. list = this._events[type];
  25820. length = list.length;
  25821. position = -1;
  25822. if (list === listener ||
  25823. (isFunction(list.listener) && list.listener === listener)) {
  25824. delete this._events[type];
  25825. if (this._events.removeListener)
  25826. this.emit('removeListener', type, listener);
  25827. } else if (isObject(list)) {
  25828. for (i = length; i-- > 0;) {
  25829. if (list[i] === listener ||
  25830. (list[i].listener && list[i].listener === listener)) {
  25831. position = i;
  25832. break;
  25833. }
  25834. }
  25835. if (position < 0)
  25836. return this;
  25837. if (list.length === 1) {
  25838. list.length = 0;
  25839. delete this._events[type];
  25840. } else {
  25841. list.splice(position, 1);
  25842. }
  25843. if (this._events.removeListener)
  25844. this.emit('removeListener', type, listener);
  25845. }
  25846. return this;
  25847. };
  25848. EventEmitter.prototype.removeAllListeners = function(type) {
  25849. var key, listeners;
  25850. if (!this._events)
  25851. return this;
  25852. // not listening for removeListener, no need to emit
  25853. if (!this._events.removeListener) {
  25854. if (arguments.length === 0)
  25855. this._events = {};
  25856. else if (this._events[type])
  25857. delete this._events[type];
  25858. return this;
  25859. }
  25860. // emit removeListener for all listeners on all events
  25861. if (arguments.length === 0) {
  25862. for (key in this._events) {
  25863. if (key === 'removeListener') continue;
  25864. this.removeAllListeners(key);
  25865. }
  25866. this.removeAllListeners('removeListener');
  25867. this._events = {};
  25868. return this;
  25869. }
  25870. listeners = this._events[type];
  25871. if (isFunction(listeners)) {
  25872. this.removeListener(type, listeners);
  25873. } else {
  25874. // LIFO order
  25875. while (listeners.length)
  25876. this.removeListener(type, listeners[listeners.length - 1]);
  25877. }
  25878. delete this._events[type];
  25879. return this;
  25880. };
  25881. EventEmitter.prototype.listeners = function(type) {
  25882. var ret;
  25883. if (!this._events || !this._events[type])
  25884. ret = [];
  25885. else if (isFunction(this._events[type]))
  25886. ret = [this._events[type]];
  25887. else
  25888. ret = this._events[type].slice();
  25889. return ret;
  25890. };
  25891. EventEmitter.listenerCount = function(emitter, type) {
  25892. var ret;
  25893. if (!emitter._events || !emitter._events[type])
  25894. ret = 0;
  25895. else if (isFunction(emitter._events[type]))
  25896. ret = 1;
  25897. else
  25898. ret = emitter._events[type].length;
  25899. return ret;
  25900. };
  25901. function isFunction(arg) {
  25902. return typeof arg === 'function';
  25903. }
  25904. function isNumber(arg) {
  25905. return typeof arg === 'number';
  25906. }
  25907. function isObject(arg) {
  25908. return typeof arg === 'object' && arg !== null;
  25909. }
  25910. function isUndefined(arg) {
  25911. return arg === void 0;
  25912. }
  25913. },{}],107:[function(require,module,exports){
  25914. // shim for using process in browser
  25915. var process = module.exports = {};
  25916. var queue = [];
  25917. var draining = false;
  25918. function drainQueue() {
  25919. if (draining) {
  25920. return;
  25921. }
  25922. draining = true;
  25923. var currentQueue;
  25924. var len = queue.length;
  25925. while(len) {
  25926. currentQueue = queue;
  25927. queue = [];
  25928. var i = -1;
  25929. while (++i < len) {
  25930. currentQueue[i]();
  25931. }
  25932. len = queue.length;
  25933. }
  25934. draining = false;
  25935. }
  25936. process.nextTick = function (fun) {
  25937. queue.push(fun);
  25938. if (!draining) {
  25939. setTimeout(drainQueue, 0);
  25940. }
  25941. };
  25942. process.title = 'browser';
  25943. process.browser = true;
  25944. process.env = {};
  25945. process.argv = [];
  25946. process.version = ''; // empty string to avoid regexp issues
  25947. function noop() {}
  25948. process.on = noop;
  25949. process.addListener = noop;
  25950. process.once = noop;
  25951. process.off = noop;
  25952. process.removeListener = noop;
  25953. process.removeAllListeners = noop;
  25954. process.emit = noop;
  25955. process.binding = function (name) {
  25956. throw new Error('process.binding is not supported');
  25957. };
  25958. // TODO(shtylman)
  25959. process.cwd = function () { return '/' };
  25960. process.chdir = function (dir) {
  25961. throw new Error('process.chdir is not supported');
  25962. };
  25963. process.umask = function() { return 0; };
  25964. },{}]},{},[1])(1)
  25965. });