You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

app.bundle.js 904KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.APP=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /* jshint -W117 */
  3. /* application specific logic */
  4. var APP =
  5. {
  6. init: function () {
  7. this.UI = require("./modules/UI/UI");
  8. this.API = require("./modules/API/API");
  9. this.connectionquality = require("./modules/connectionquality/connectionquality");
  10. this.statistics = require("./modules/statistics/statistics");
  11. this.RTC = require("./modules/RTC/RTC");
  12. this.simulcast = require("./modules/simulcast/simulcast");
  13. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  14. this.xmpp = require("./modules/xmpp/xmpp");
  15. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  16. this.translation = require("./modules/translation/translation");
  17. this.settings = require("./modules/settings/Settings");
  18. }
  19. };
  20. function init() {
  21. APP.RTC.start();
  22. APP.xmpp.start();
  23. APP.statistics.start();
  24. APP.connectionquality.init();
  25. // Set default desktop sharing method
  26. APP.desktopsharing.init();
  27. APP.keyboardshortcut.init();
  28. }
  29. $(document).ready(function () {
  30. APP.init();
  31. APP.translation.init();
  32. if(APP.API.isEnabled())
  33. APP.API.init();
  34. APP.UI.start(init);
  35. });
  36. $(window).bind('beforeunload', function () {
  37. if(APP.API.isEnabled())
  38. APP.API.dispose();
  39. });
  40. module.exports = APP;
  41. },{"./modules/API/API":2,"./modules/RTC/RTC":6,"./modules/UI/UI":8,"./modules/connectionquality/connectionquality":35,"./modules/desktopsharing/desktopsharing":36,"./modules/keyboardshortcut/keyboardshortcut":37,"./modules/settings/Settings":38,"./modules/simulcast/simulcast":43,"./modules/statistics/statistics":46,"./modules/translation/translation":47,"./modules/xmpp/xmpp":61}],2:[function(require,module,exports){
  42. /**
  43. * Implements API class that communicates with external api class
  44. * and provides interface to access Jitsi Meet features by external
  45. * applications that embed Jitsi Meet
  46. */
  47. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  48. /**
  49. * List of the available commands.
  50. * @type {{
  51. * displayName: inputDisplayNameHandler,
  52. * muteAudio: toggleAudio,
  53. * muteVideo: toggleVideo,
  54. * filmStrip: toggleFilmStrip
  55. * }}
  56. */
  57. var commands =
  58. {
  59. displayName: APP.UI.inputDisplayNameHandler,
  60. muteAudio: APP.UI.toggleAudio,
  61. muteVideo: APP.UI.toggleVideo,
  62. toggleFilmStrip: APP.UI.toggleFilmStrip,
  63. toggleChat: APP.UI.toggleChat,
  64. toggleContactList: APP.UI.toggleContactList
  65. };
  66. /**
  67. * Maps the supported events and their status
  68. * (true it the event is enabled and false if it is disabled)
  69. * @type {{
  70. * incomingMessage: boolean,
  71. * outgoingMessage: boolean,
  72. * displayNameChange: boolean,
  73. * participantJoined: boolean,
  74. * participantLeft: boolean
  75. * }}
  76. */
  77. var events =
  78. {
  79. incomingMessage: false,
  80. outgoingMessage:false,
  81. displayNameChange: false,
  82. participantJoined: false,
  83. participantLeft: false
  84. };
  85. var displayName = {};
  86. /**
  87. * Processes commands from external applicaiton.
  88. * @param message the object with the command
  89. */
  90. function processCommand(message)
  91. {
  92. if(message.action != "execute")
  93. {
  94. console.error("Unknown action of the message");
  95. return;
  96. }
  97. for(var key in message)
  98. {
  99. if(commands[key])
  100. commands[key].apply(null, message[key]);
  101. }
  102. }
  103. /**
  104. * Processes events objects from external applications
  105. * @param event the event
  106. */
  107. function processEvent(event) {
  108. if(!event.action)
  109. {
  110. console.error("Event with no action is received.");
  111. return;
  112. }
  113. var i = 0;
  114. switch(event.action)
  115. {
  116. case "add":
  117. for(; i < event.events.length; i++)
  118. {
  119. events[event.events[i]] = true;
  120. }
  121. break;
  122. case "remove":
  123. for(; i < event.events.length; i++)
  124. {
  125. events[event.events[i]] = false;
  126. }
  127. break;
  128. default:
  129. console.error("Unknown action for event.");
  130. }
  131. }
  132. /**
  133. * Sends message to the external application.
  134. * @param object
  135. */
  136. function sendMessage(object) {
  137. window.parent.postMessage(JSON.stringify(object), "*");
  138. }
  139. /**
  140. * Processes a message event from the external application
  141. * @param event the message event
  142. */
  143. function processMessage(event)
  144. {
  145. var message;
  146. try {
  147. message = JSON.parse(event.data);
  148. } catch (e) {}
  149. if(!message.type)
  150. return;
  151. switch (message.type)
  152. {
  153. case "command":
  154. processCommand(message);
  155. break;
  156. case "event":
  157. processEvent(message);
  158. break;
  159. default:
  160. console.error("Unknown type of the message");
  161. return;
  162. }
  163. }
  164. function setupListeners() {
  165. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, function (from) {
  166. API.triggerEvent("participantJoined", {jid: from});
  167. });
  168. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid) {
  169. if (from != myjid)
  170. API.triggerEvent("incomingMessage",
  171. {"from": from, "nick": nick, "message": txt});
  172. });
  173. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, function (jid) {
  174. API.triggerEvent("participantLeft", {jid: jid});
  175. });
  176. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  177. name = displayName[jid];
  178. if(!name || name != newDisplayName) {
  179. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  180. displayName[jid] = newDisplayName;
  181. }
  182. });
  183. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  184. APP.API.triggerEvent("outgoingMessage", {"message": body});
  185. });
  186. }
  187. var API = {
  188. /**
  189. * Check whether the API should be enabled or not.
  190. * @returns {boolean}
  191. */
  192. isEnabled: function () {
  193. var hash = location.hash;
  194. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  195. return true;
  196. return false;
  197. },
  198. /**
  199. * Initializes the APIConnector. Setups message event listeners that will
  200. * receive information from external applications that embed Jitsi Meet.
  201. * It also sends a message to the external application that APIConnector
  202. * is initialized.
  203. */
  204. init: function () {
  205. if (window.addEventListener)
  206. {
  207. window.addEventListener('message',
  208. processMessage, false);
  209. }
  210. else
  211. {
  212. window.attachEvent('onmessage', processMessage);
  213. }
  214. sendMessage({type: "system", loaded: true});
  215. setupListeners();
  216. },
  217. /**
  218. * Checks whether the event is enabled ot not.
  219. * @param name the name of the event.
  220. * @returns {*}
  221. */
  222. isEventEnabled: function (name) {
  223. return events[name];
  224. },
  225. /**
  226. * Sends event object to the external application that has been subscribed
  227. * for that event.
  228. * @param name the name event
  229. * @param object data associated with the event
  230. */
  231. triggerEvent: function (name, object) {
  232. if(this.isEnabled() && this.isEventEnabled(name))
  233. sendMessage({
  234. type: "event", action: "result", event: name, result: object});
  235. },
  236. /**
  237. * Removes the listeners.
  238. */
  239. dispose: function () {
  240. if(window.removeEventListener)
  241. {
  242. window.removeEventListener("message",
  243. processMessage, false);
  244. }
  245. else
  246. {
  247. window.detachEvent('onmessage', processMessage);
  248. }
  249. }
  250. };
  251. module.exports = API;
  252. },{"../../service/xmpp/XMPPEvents":97}],3:[function(require,module,exports){
  253. /* global Strophe, focusedVideoSrc*/
  254. // cache datachannels to avoid garbage collection
  255. // https://code.google.com/p/chromium/issues/detail?id=405545
  256. var RTCEvents = require("../../service/RTC/RTCEvents");
  257. var _dataChannels = [];
  258. var eventEmitter = null;
  259. var DataChannels =
  260. {
  261. /**
  262. * Callback triggered by PeerConnection when new data channel is opened
  263. * on the bridge.
  264. * @param event the event info object.
  265. */
  266. onDataChannel: function (event)
  267. {
  268. var dataChannel = event.channel;
  269. dataChannel.onopen = function () {
  270. console.info("Data channel opened by the Videobridge!", dataChannel);
  271. // Code sample for sending string and/or binary data
  272. // Sends String message to the bridge
  273. //dataChannel.send("Hello bridge!");
  274. // Sends 12 bytes binary message to the bridge
  275. //dataChannel.send(new ArrayBuffer(12));
  276. // when the data channel becomes available, tell the bridge about video
  277. // selections so that it can do adaptive simulcast,
  278. // we want the notification to trigger even if userJid is undefined,
  279. // or null.
  280. var userJid = APP.UI.getLargeVideoState().userResourceJid;
  281. // we want the notification to trigger even if userJid is undefined,
  282. // or null.
  283. onSelectedEndpointChanged(userJid);
  284. };
  285. dataChannel.onerror = function (error) {
  286. console.error("Data Channel Error:", error, dataChannel);
  287. };
  288. dataChannel.onmessage = function (event) {
  289. var data = event.data;
  290. // JSON
  291. var obj;
  292. try {
  293. obj = JSON.parse(data);
  294. }
  295. catch (e) {
  296. console.error(
  297. "Failed to parse data channel message as JSON: ",
  298. data,
  299. dataChannel);
  300. }
  301. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  302. var colibriClass = obj.colibriClass;
  303. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  304. // Endpoint ID from the Videobridge.
  305. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  306. console.info(
  307. "Data channel new dominant speaker event: ",
  308. dominantSpeakerEndpoint);
  309. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  310. }
  311. else if ("InLastNChangeEvent" === colibriClass)
  312. {
  313. var oldValue = obj.oldValue;
  314. var newValue = obj.newValue;
  315. // Make sure that oldValue and newValue are of type boolean.
  316. var type;
  317. if ((type = typeof oldValue) !== 'boolean') {
  318. if (type === 'string') {
  319. oldValue = (oldValue == "true");
  320. } else {
  321. oldValue = new Boolean(oldValue).valueOf();
  322. }
  323. }
  324. if ((type = typeof newValue) !== 'boolean') {
  325. if (type === 'string') {
  326. newValue = (newValue == "true");
  327. } else {
  328. newValue = new Boolean(newValue).valueOf();
  329. }
  330. }
  331. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  332. }
  333. else if ("LastNEndpointsChangeEvent" === colibriClass)
  334. {
  335. // The new/latest list of last-n endpoint IDs.
  336. var lastNEndpoints = obj.lastNEndpoints;
  337. // The list of endpoint IDs which are entering the list of
  338. // last-n at this time i.e. were not in the old list of last-n
  339. // endpoint IDs.
  340. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  341. var stream = obj.stream;
  342. console.log(
  343. "Data channel new last-n event: ",
  344. lastNEndpoints, endpointsEnteringLastN, obj);
  345. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  346. lastNEndpoints, endpointsEnteringLastN, obj);
  347. }
  348. else if ("SimulcastLayersChangedEvent" === colibriClass)
  349. {
  350. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGED,
  351. obj.endpointSimulcastLayers);
  352. }
  353. else if ("SimulcastLayersChangingEvent" === colibriClass)
  354. {
  355. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGING,
  356. obj.endpointSimulcastLayers);
  357. }
  358. else if ("StartSimulcastLayerEvent" === colibriClass)
  359. {
  360. eventEmitter.emit(RTCEvents.SIMULCAST_START, obj.simulcastLayer);
  361. }
  362. else if ("StopSimulcastLayerEvent" === colibriClass)
  363. {
  364. eventEmitter.emit(RTCEvents.SIMULCAST_STOP, obj.simulcastLayer);
  365. }
  366. else
  367. {
  368. console.debug("Data channel JSON-formatted message: ", obj);
  369. }
  370. }
  371. };
  372. dataChannel.onclose = function ()
  373. {
  374. console.info("The Data Channel closed", dataChannel);
  375. var idx = _dataChannels.indexOf(dataChannel);
  376. if (idx > -1)
  377. _dataChannels = _dataChannels.splice(idx, 1);
  378. };
  379. _dataChannels.push(dataChannel);
  380. },
  381. /**
  382. * Binds "ondatachannel" event listener to given PeerConnection instance.
  383. * @param peerConnection WebRTC peer connection instance.
  384. */
  385. init: function (peerConnection, emitter) {
  386. if(!config.openSctp)
  387. return;
  388. peerConnection.ondatachannel = this.onDataChannel;
  389. eventEmitter = emitter;
  390. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  391. // Although it's not a requirement to open separate channels from both bridge
  392. // and peer as single channel can be used for sending and receiving data.
  393. // So either channel opened by the bridge or the one opened here is enough
  394. // for communication with the bridge.
  395. /*var dataChannelOptions =
  396. {
  397. reliable: true
  398. };
  399. var dataChannel
  400. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  401. // Can be used only when is in open state
  402. dataChannel.onopen = function ()
  403. {
  404. dataChannel.send("My channel !!!");
  405. };
  406. dataChannel.onmessage = function (event)
  407. {
  408. var msgData = event.data;
  409. console.info("Got My Data Channel Message:", msgData, dataChannel);
  410. };*/
  411. },
  412. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  413. handlePinnedEndpointEvent: onPinnedEndpointChanged
  414. };
  415. function onSelectedEndpointChanged(userResource)
  416. {
  417. console.log('selected endpoint changed: ', userResource);
  418. if (_dataChannels && _dataChannels.length != 0)
  419. {
  420. _dataChannels.some(function (dataChannel) {
  421. if (dataChannel.readyState == 'open')
  422. {
  423. console.log('sending selected endpoint changed '
  424. + 'notification to the bridge: ', userResource);
  425. dataChannel.send(JSON.stringify({
  426. 'colibriClass': 'SelectedEndpointChangedEvent',
  427. 'selectedEndpoint':
  428. (!userResource || userResource === null)?
  429. null : userResource
  430. }));
  431. return true;
  432. }
  433. });
  434. }
  435. }
  436. function onPinnedEndpointChanged(userResource)
  437. {
  438. console.log('pinned endpoint changed: ', userResource);
  439. if (_dataChannels && _dataChannels.length != 0)
  440. {
  441. _dataChannels.some(function (dataChannel) {
  442. if (dataChannel.readyState == 'open')
  443. {
  444. dataChannel.send(JSON.stringify({
  445. 'colibriClass': 'PinnedEndpointChangedEvent',
  446. 'pinnedEndpoint':
  447. (!userResource || userResource == null)?
  448. null : userResource
  449. }));
  450. return true;
  451. }
  452. });
  453. }
  454. }
  455. module.exports = DataChannels;
  456. },{"../../service/RTC/RTCEvents":89}],4:[function(require,module,exports){
  457. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  458. function LocalStream(stream, type, eventEmitter, videoType)
  459. {
  460. this.stream = stream;
  461. this.eventEmitter = eventEmitter;
  462. this.type = type;
  463. this.videoType = videoType;
  464. var self = this;
  465. if(type == "audio")
  466. {
  467. this.getTracks = function () {
  468. return self.stream.getAudioTracks();
  469. };
  470. }
  471. else
  472. {
  473. this.getTracks = function () {
  474. return self.stream.getVideoTracks();
  475. };
  476. }
  477. this.stream.onended = function()
  478. {
  479. self.streamEnded();
  480. };
  481. }
  482. LocalStream.prototype.streamEnded = function () {
  483. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  484. }
  485. LocalStream.prototype.getOriginalStream = function()
  486. {
  487. return this.stream;
  488. }
  489. LocalStream.prototype.isAudioStream = function () {
  490. return (this.stream.getAudioTracks() && this.stream.getAudioTracks().length > 0);
  491. };
  492. LocalStream.prototype.mute = function()
  493. {
  494. var ismuted = false;
  495. var tracks = this.getTracks();
  496. for (var idx = 0; idx < tracks.length; idx++) {
  497. ismuted = !tracks[idx].enabled;
  498. tracks[idx].enabled = ismuted;
  499. }
  500. return ismuted;
  501. };
  502. LocalStream.prototype.setMute = function(mute)
  503. {
  504. if(window.location.protocol != "https:" ||
  505. this.isAudioStream() || this.videoType === "screen")
  506. {
  507. var tracks = this.getTracks();
  508. for (var idx = 0; idx < tracks.length; idx++) {
  509. tracks[idx].enabled = mute;
  510. }
  511. }
  512. else
  513. {
  514. if(mute === false) {
  515. APP.xmpp.removeStream(this.stream);
  516. this.stream.stop();
  517. }
  518. else
  519. {
  520. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(["video"],
  521. function (stream) {
  522. APP.RTC.changeLocalVideo(stream, false, function () {});
  523. });
  524. }
  525. }
  526. };
  527. LocalStream.prototype.isMuted = function () {
  528. var tracks = [];
  529. if(this.type == "audio")
  530. {
  531. tracks = this.stream.getAudioTracks();
  532. }
  533. else
  534. {
  535. if(this.stream.ended)
  536. return true;
  537. tracks = this.stream.getVideoTracks();
  538. }
  539. for (var idx = 0; idx < tracks.length; idx++) {
  540. if(tracks[idx].enabled)
  541. return false;
  542. }
  543. return true;
  544. }
  545. LocalStream.prototype.getId = function () {
  546. return this.stream.getTracks()[0].id;
  547. }
  548. module.exports = LocalStream;
  549. },{"../../service/RTC/StreamEventTypes.js":91}],5:[function(require,module,exports){
  550. ////These lines should be uncommented when require works in app.js
  551. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  552. var StreamEventType = require("../../service/RTC/StreamEventTypes");
  553. /**
  554. * Creates a MediaStream object for the given data, session id and ssrc.
  555. * It is a wrapper class for the MediaStream.
  556. *
  557. * @param data the data object from which we obtain the stream,
  558. * the peerjid, etc.
  559. * @param sid the session id
  560. * @param ssrc the ssrc corresponding to this MediaStream
  561. *
  562. * @constructor
  563. */
  564. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  565. // XXX(gp) to minimize headaches in the future, we should build our
  566. // abstractions around tracks and not streams. ORTC is track based API.
  567. // Mozilla expects m-lines to represent media tracks.
  568. //
  569. // Practically, what I'm saying is that we should have a MediaTrack class
  570. // and not a MediaStream class.
  571. //
  572. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  573. // a track might have an associated RTX and FEC sources.
  574. this.sid = sid;
  575. this.stream = data.stream;
  576. this.peerjid = data.peerjid;
  577. this.ssrc = ssrc;
  578. this.type = (this.stream.getVideoTracks().length > 0)?
  579. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  580. this.videoType = null;
  581. this.muted = false;
  582. this.eventEmitter = eventEmitter;
  583. }
  584. MediaStream.prototype.getOriginalStream = function()
  585. {
  586. return this.stream;
  587. };
  588. MediaStream.prototype.setMute = function (value)
  589. {
  590. this.stream.muted = value;
  591. this.muted = value;
  592. };
  593. MediaStream.prototype.setVideoType = function (value) {
  594. if(this.videoType === value)
  595. return;
  596. this.videoType = value;
  597. this.eventEmitter.emit(StreamEventType.EVENT_TYPE_REMOTE_CHANGED,
  598. this.peerjid);
  599. };
  600. module.exports = MediaStream;
  601. },{"../../service/RTC/MediaStreamTypes":87,"../../service/RTC/StreamEventTypes":91}],6:[function(require,module,exports){
  602. var EventEmitter = require("events");
  603. var RTCUtils = require("./RTCUtils.js");
  604. var LocalStream = require("./LocalStream.js");
  605. var DataChannels = require("./DataChannels");
  606. var MediaStream = require("./MediaStream.js");
  607. var DesktopSharingEventTypes
  608. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  609. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  610. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  611. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  612. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  613. var UIEvents = require("../../service/UI/UIEvents");
  614. var eventEmitter = new EventEmitter();
  615. var RTC = {
  616. rtcUtils: null,
  617. devices: {
  618. audio: false,
  619. video: false
  620. },
  621. localStreams: [],
  622. remoteStreams: {},
  623. localAudio: null,
  624. localVideo: null,
  625. addStreamListener: function (listener, eventType) {
  626. eventEmitter.on(eventType, listener);
  627. },
  628. addListener: function (type, listener) {
  629. eventEmitter.on(type, listener);
  630. },
  631. removeStreamListener: function (listener, eventType) {
  632. if(!(eventType instanceof StreamEventTypes))
  633. throw "Illegal argument";
  634. eventEmitter.removeListener(eventType, listener);
  635. },
  636. createLocalStream: function (stream, type, change, videoType) {
  637. var localStream = new LocalStream(stream, type, eventEmitter, videoType);
  638. //in firefox we have only one stream object
  639. if(this.localStreams.length == 0 ||
  640. this.localStreams[0].getOriginalStream() != stream)
  641. this.localStreams.push(localStream);
  642. if(type == "audio")
  643. {
  644. this.localAudio = localStream;
  645. }
  646. else
  647. {
  648. this.localVideo = localStream;
  649. }
  650. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  651. if(change)
  652. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  653. eventEmitter.emit(eventType, localStream);
  654. return localStream;
  655. },
  656. removeLocalStream: function (stream) {
  657. for(var i = 0; i < this.localStreams.length; i++)
  658. {
  659. if(this.localStreams[i].getOriginalStream() === stream) {
  660. delete this.localStreams[i];
  661. return;
  662. }
  663. }
  664. },
  665. createRemoteStream: function (data, sid, thessrc) {
  666. var remoteStream = new MediaStream(data, sid, thessrc,
  667. this.getBrowserType(), eventEmitter);
  668. var jid = data.peerjid || APP.xmpp.myJid();
  669. if(!this.remoteStreams[jid]) {
  670. this.remoteStreams[jid] = {};
  671. }
  672. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  673. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  674. return remoteStream;
  675. },
  676. getBrowserType: function () {
  677. return this.rtcUtils.browser;
  678. },
  679. getPCConstraints: function () {
  680. return this.rtcUtils.pc_constraints;
  681. },
  682. getUserMediaWithConstraints:function(um, success_callback,
  683. failure_callback, resolution,
  684. bandwidth, fps, desktopStream)
  685. {
  686. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  687. failure_callback, resolution, bandwidth, fps, desktopStream);
  688. },
  689. attachMediaStream: function (element, stream) {
  690. this.rtcUtils.attachMediaStream(element, stream);
  691. },
  692. getStreamID: function (stream) {
  693. return this.rtcUtils.getStreamID(stream);
  694. },
  695. getVideoSrc: function (element) {
  696. return this.rtcUtils.getVideoSrc(element);
  697. },
  698. setVideoSrc: function (element, src) {
  699. this.rtcUtils.setVideoSrc(element, src);
  700. },
  701. dispose: function() {
  702. if (this.rtcUtils) {
  703. this.rtcUtils = null;
  704. }
  705. },
  706. stop: function () {
  707. this.dispose();
  708. },
  709. start: function () {
  710. var self = this;
  711. APP.desktopsharing.addListener(
  712. function (stream, isUsingScreenStream, callback) {
  713. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  714. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  715. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  716. for(var i = 0; i < changedStreams.length; i++) {
  717. var type = changedStreams[i].type;
  718. if (type != "audio") {
  719. var peerStreams = self.remoteStreams[jid];
  720. if(!peerStreams)
  721. continue;
  722. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  723. if(!videoStream)
  724. continue;
  725. videoStream.setVideoType(changedStreams[i].type);
  726. }
  727. }
  728. });
  729. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  730. DataChannels.init(event.peerconnection, eventEmitter);
  731. });
  732. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  733. DataChannels.handleSelectedEndpointEvent);
  734. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  735. DataChannels.handlePinnedEndpointEvent);
  736. this.rtcUtils = new RTCUtils(this);
  737. this.rtcUtils.obtainAudioAndVideoPermissions();
  738. },
  739. muteRemoteVideoStream: function (jid, value) {
  740. var stream;
  741. if(this.remoteStreams[jid] &&
  742. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  743. {
  744. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  745. }
  746. if(!stream)
  747. return false;
  748. if (value != stream.muted) {
  749. stream.setMute(value);
  750. return true;
  751. }
  752. return false;
  753. },
  754. switchVideoStreams: function (new_stream) {
  755. this.localVideo.stream = new_stream;
  756. this.localStreams = [];
  757. //in firefox we have only one stream object
  758. if (this.localAudio.getOriginalStream() != new_stream)
  759. this.localStreams.push(this.localAudio);
  760. this.localStreams.push(this.localVideo);
  761. },
  762. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  763. var oldStream = this.localVideo.getOriginalStream();
  764. var type = (isUsingScreenStream? "screen" : "video");
  765. var localCallback = callback;
  766. if(this.localVideo.isMuted() && this.localVideo.videoType !== type)
  767. {
  768. localCallback = function() {
  769. APP.xmpp.setVideoMute(false, APP.UI.setVideoMuteButtonsState);
  770. callback();
  771. };
  772. }
  773. var videoStream = this.rtcUtils.createVideoStream(stream);
  774. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  775. // Stop the stream to trigger onended event for old stream
  776. oldStream.stop();
  777. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  778. },
  779. /**
  780. * Checks if video identified by given src is desktop stream.
  781. * @param videoSrc eg.
  782. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  783. * @returns {boolean}
  784. */
  785. isVideoSrcDesktop: function (jid) {
  786. if(!jid)
  787. return false;
  788. var isDesktop = false;
  789. var stream = null;
  790. if (APP.xmpp.myJid() === jid) {
  791. // local video
  792. stream = this.localVideo;
  793. } else {
  794. var peerStreams = this.remoteStreams[jid];
  795. if(!peerStreams)
  796. return false;
  797. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  798. }
  799. if(stream)
  800. isDesktop = (stream.videoType === "screen");
  801. return isDesktop;
  802. },
  803. setVideoMute: function(mute, callback, options) {
  804. if(!this.localVideo)
  805. return;
  806. if (mute == APP.RTC.localVideo.isMuted())
  807. {
  808. APP.xmpp.sendVideoInfoPresence(mute);
  809. if(callback)
  810. callback();
  811. }
  812. else
  813. {
  814. APP.RTC.localVideo.setMute(!mute);
  815. APP.xmpp.setVideoMute(
  816. mute,
  817. callback,
  818. options);
  819. }
  820. },
  821. setDeviceAvailability: function (devices) {
  822. this.devices.audio = (devices && devices.audio === true);
  823. this.devices.video = (devices && devices.video === true);
  824. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  825. }
  826. };
  827. module.exports = RTC;
  828. },{"../../service/RTC/MediaStreamTypes":87,"../../service/RTC/RTCEvents.js":89,"../../service/RTC/StreamEventTypes.js":91,"../../service/UI/UIEvents":92,"../../service/desktopsharing/DesktopSharingEventTypes":95,"../../service/xmpp/XMPPEvents":97,"./DataChannels":3,"./LocalStream.js":4,"./MediaStream.js":5,"./RTCUtils.js":7,"events":98}],7:[function(require,module,exports){
  829. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  830. var Resolutions = require("../../service/RTC/Resolutions");
  831. var currentResolution = null;
  832. function getPreviousResolution(resolution) {
  833. if(!Resolutions[resolution])
  834. return null;
  835. var order = Resolutions[resolution].order;
  836. var res = null;
  837. var resName = null;
  838. for(var i in Resolutions)
  839. {
  840. var tmp = Resolutions[i];
  841. if(res == null || (res.order < tmp.order && tmp.order < order))
  842. {
  843. resName = i;
  844. res = tmp;
  845. }
  846. }
  847. return resName;
  848. }
  849. function setResolutionConstraints(constraints, resolution, isAndroid)
  850. {
  851. if (resolution && !constraints.video || isAndroid) {
  852. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  853. }
  854. if(Resolutions[resolution])
  855. {
  856. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  857. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  858. }
  859. else
  860. {
  861. if (isAndroid) {
  862. constraints.video.mandatory.minWidth = 320;
  863. constraints.video.mandatory.minHeight = 240;
  864. constraints.video.mandatory.maxFrameRate = 15;
  865. }
  866. }
  867. if (constraints.video.mandatory.minWidth)
  868. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  869. if (constraints.video.mandatory.minHeight)
  870. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  871. }
  872. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  873. {
  874. var constraints = {audio: false, video: false};
  875. if (um.indexOf('video') >= 0) {
  876. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  877. }
  878. if (um.indexOf('audio') >= 0) {
  879. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  880. }
  881. if (um.indexOf('screen') >= 0) {
  882. constraints.video = {
  883. mandatory: {
  884. chromeMediaSource: "screen",
  885. googLeakyBucket: true,
  886. maxWidth: window.screen.width,
  887. maxHeight: window.screen.height,
  888. maxFrameRate: 3
  889. },
  890. optional: []
  891. };
  892. }
  893. if (um.indexOf('desktop') >= 0) {
  894. constraints.video = {
  895. mandatory: {
  896. chromeMediaSource: "desktop",
  897. chromeMediaSourceId: desktopStream,
  898. googLeakyBucket: true,
  899. maxWidth: window.screen.width,
  900. maxHeight: window.screen.height,
  901. maxFrameRate: 3
  902. },
  903. optional: []
  904. };
  905. }
  906. if (constraints.audio) {
  907. // if it is good enough for hangouts...
  908. constraints.audio.optional.push(
  909. {googEchoCancellation: true},
  910. {googAutoGainControl: true},
  911. {googNoiseSupression: true},
  912. {googHighpassFilter: true},
  913. {googNoisesuppression2: true},
  914. {googEchoCancellation2: true},
  915. {googAutoGainControl2: true}
  916. );
  917. }
  918. if (constraints.video) {
  919. constraints.video.optional.push(
  920. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  921. );
  922. if (um.indexOf('video') >= 0) {
  923. constraints.video.optional.push(
  924. {googLeakyBucket: true}
  925. );
  926. }
  927. }
  928. if (um.indexOf('video') >= 0) {
  929. setResolutionConstraints(constraints, resolution, isAndroid);
  930. }
  931. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  932. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  933. constraints.video.optional.push({bandwidth: bandwidth});
  934. }
  935. if (fps) { // for some cameras it might be necessary to request 30fps
  936. // so they choose 30fps mjpg over 10fps yuy2
  937. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  938. constraints.video.mandatory.minFrameRate = fps;
  939. }
  940. return constraints;
  941. }
  942. function RTCUtils(RTCService)
  943. {
  944. this.service = RTCService;
  945. if (navigator.mozGetUserMedia) {
  946. console.log('This appears to be Firefox');
  947. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  948. if (version >= 39) {
  949. this.peerconnection = mozRTCPeerConnection;
  950. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  951. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  952. this.pc_constraints = {};
  953. this.attachMediaStream = function (element, stream) {
  954. // srcObject is being standardized and FF will eventually
  955. // support that unprefixed. FF also supports the
  956. // "element.src = URL.createObjectURL(...)" combo, but that
  957. // will be deprecated in favour of srcObject.
  958. //
  959. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  960. // https://github.com/webrtc/samples/issues/302
  961. element[0].mozSrcObject = stream;
  962. element[0].play();
  963. };
  964. this.getStreamID = function (stream) {
  965. var tracks = stream.getVideoTracks();
  966. if(!tracks || tracks.length == 0)
  967. {
  968. tracks = stream.getAudioTracks();
  969. }
  970. return tracks[0].id.replace(/[\{,\}]/g,"");
  971. };
  972. this.getVideoSrc = function (element) {
  973. return element.mozSrcObject;
  974. };
  975. this.setVideoSrc = function (element, src) {
  976. element.mozSrcObject = src;
  977. };
  978. RTCSessionDescription = mozRTCSessionDescription;
  979. RTCIceCandidate = mozRTCIceCandidate;
  980. } else {
  981. window.location.href = 'unsupported_browser.html';
  982. return;
  983. }
  984. } else if (navigator.webkitGetUserMedia) {
  985. console.log('This appears to be Chrome');
  986. this.peerconnection = webkitRTCPeerConnection;
  987. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  988. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  989. this.attachMediaStream = function (element, stream) {
  990. element.attr('src', webkitURL.createObjectURL(stream));
  991. };
  992. this.getStreamID = function (stream) {
  993. // streams from FF endpoints have the characters '{' and '}'
  994. // that make jQuery choke.
  995. return stream.id.replace(/[\{,\}]/g,"");
  996. };
  997. this.getVideoSrc = function (element) {
  998. return element.getAttribute("src");
  999. };
  1000. this.setVideoSrc = function (element, src) {
  1001. element.setAttribute("src", src);
  1002. };
  1003. // DTLS should now be enabled by default but..
  1004. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1005. if (navigator.userAgent.indexOf('Android') != -1) {
  1006. this.pc_constraints = {}; // disable DTLS on Android
  1007. }
  1008. if (!webkitMediaStream.prototype.getVideoTracks) {
  1009. webkitMediaStream.prototype.getVideoTracks = function () {
  1010. return this.videoTracks;
  1011. };
  1012. }
  1013. if (!webkitMediaStream.prototype.getAudioTracks) {
  1014. webkitMediaStream.prototype.getAudioTracks = function () {
  1015. return this.audioTracks;
  1016. };
  1017. }
  1018. }
  1019. else
  1020. {
  1021. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  1022. window.location.href = 'unsupported_browser.html';
  1023. return;
  1024. }
  1025. }
  1026. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1027. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1028. desktopStream)
  1029. {
  1030. currentResolution = resolution;
  1031. // Check if we are running on Android device
  1032. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1033. var constraints = getConstraints(
  1034. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1035. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  1036. var self = this;
  1037. try {
  1038. if (config.enableSimulcast
  1039. && constraints.video
  1040. && constraints.video.chromeMediaSource !== 'screen'
  1041. && constraints.video.chromeMediaSource !== 'desktop'
  1042. && !isAndroid
  1043. // We currently do not support FF, as it doesn't have multistream support.
  1044. && !isFF) {
  1045. APP.simulcast.getUserMedia(constraints, function (stream) {
  1046. console.log('onUserMediaSuccess');
  1047. self.setAvailableDevices(um, true);
  1048. success_callback(stream);
  1049. },
  1050. function (error) {
  1051. console.warn('Failed to get access to local media. Error ', error);
  1052. self.setAvailableDevices(um, false);
  1053. if (failure_callback) {
  1054. failure_callback(error);
  1055. }
  1056. });
  1057. } else {
  1058. this.getUserMedia(constraints,
  1059. function (stream) {
  1060. console.log('onUserMediaSuccess');
  1061. self.setAvailableDevices(um, true);
  1062. success_callback(stream);
  1063. },
  1064. function (error) {
  1065. self.setAvailableDevices(um, false);
  1066. console.warn('Failed to get access to local media. Error ',
  1067. error, constraints);
  1068. if (failure_callback) {
  1069. failure_callback(error);
  1070. }
  1071. });
  1072. }
  1073. } catch (e) {
  1074. console.error('GUM failed: ', e);
  1075. if(failure_callback) {
  1076. failure_callback(e);
  1077. }
  1078. }
  1079. };
  1080. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1081. var devices = {};
  1082. if(um.indexOf("video") != -1)
  1083. {
  1084. devices.video = available;
  1085. }
  1086. if(um.indexOf("audio") != -1)
  1087. {
  1088. devices.audio = available;
  1089. }
  1090. this.service.setDeviceAvailability(devices);
  1091. }
  1092. /**
  1093. * We ask for audio and video combined stream in order to get permissions and
  1094. * not to ask twice.
  1095. */
  1096. RTCUtils.prototype.obtainAudioAndVideoPermissions = function(devices, callback) {
  1097. var self = this;
  1098. // Get AV
  1099. if(!devices)
  1100. devices = ['audio', 'video'];
  1101. this.getUserMediaWithConstraints(
  1102. devices,
  1103. function (stream) {
  1104. if(callback)
  1105. callback(stream);
  1106. else
  1107. self.successCallback(stream);
  1108. },
  1109. function (error) {
  1110. self.errorCallback(error);
  1111. },
  1112. config.resolution || '360');
  1113. }
  1114. RTCUtils.prototype.successCallback = function (stream) {
  1115. if(stream)
  1116. console.log('got', stream, stream.getAudioTracks().length,
  1117. stream.getVideoTracks().length);
  1118. this.handleLocalStream(stream);
  1119. };
  1120. RTCUtils.prototype.errorCallback = function (error) {
  1121. var self = this;
  1122. console.error('failed to obtain audio/video stream - trying audio only', error);
  1123. var resolution = getPreviousResolution(currentResolution);
  1124. if(typeof error == "object" && error.constraintName && error.name
  1125. && (error.name == "ConstraintNotSatisfiedError" ||
  1126. error.name == "OverconstrainedError") &&
  1127. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1128. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1129. && resolution != null)
  1130. {
  1131. self.getUserMediaWithConstraints(['audio', 'video'],
  1132. function (stream) {
  1133. return self.successCallback(stream);
  1134. }, function (error) {
  1135. return self.errorCallback(error);
  1136. }, resolution);
  1137. }
  1138. else
  1139. {
  1140. self.getUserMediaWithConstraints(
  1141. ['audio'],
  1142. function (stream) {
  1143. return self.successCallback(stream);
  1144. },
  1145. function (error) {
  1146. console.error('failed to obtain audio/video stream - stop',
  1147. error);
  1148. return self.successCallback(null);
  1149. }
  1150. );
  1151. }
  1152. }
  1153. RTCUtils.prototype.handleLocalStream = function(stream)
  1154. {
  1155. if(window.webkitMediaStream)
  1156. {
  1157. var audioStream = new webkitMediaStream();
  1158. var videoStream = new webkitMediaStream();
  1159. if(stream) {
  1160. var audioTracks = stream.getAudioTracks();
  1161. for (var i = 0; i < audioTracks.length; i++) {
  1162. audioStream.addTrack(audioTracks[i]);
  1163. }
  1164. var videoTracks = stream.getVideoTracks();
  1165. for (i = 0; i < videoTracks.length; i++) {
  1166. videoStream.addTrack(videoTracks[i]);
  1167. }
  1168. }
  1169. this.service.createLocalStream(audioStream, "audio");
  1170. this.service.createLocalStream(videoStream, "video");
  1171. }
  1172. else
  1173. {//firefox
  1174. this.service.createLocalStream(stream, "stream");
  1175. }
  1176. };
  1177. RTCUtils.prototype.createVideoStream = function(stream)
  1178. {
  1179. var videoStream = null;
  1180. if(window.webkitMediaStream)
  1181. {
  1182. videoStream = new webkitMediaStream();
  1183. if(stream)
  1184. {
  1185. var videoTracks = stream.getVideoTracks();
  1186. for (i = 0; i < videoTracks.length; i++) {
  1187. videoStream.addTrack(videoTracks[i]);
  1188. }
  1189. }
  1190. }
  1191. else
  1192. videoStream = stream;
  1193. return videoStream;
  1194. };
  1195. module.exports = RTCUtils;
  1196. },{"../../service/RTC/RTCBrowserType.js":88,"../../service/RTC/Resolutions":90}],8:[function(require,module,exports){
  1197. var UI = {};
  1198. var VideoLayout = require("./videolayout/VideoLayout.js");
  1199. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1200. var Prezi = require("./prezi/Prezi.js");
  1201. var Etherpad = require("./etherpad/Etherpad.js");
  1202. var Chat = require("./side_pannels/chat/Chat.js");
  1203. var Toolbar = require("./toolbars/Toolbar");
  1204. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1205. var BottomToolbar = require("./toolbars/BottomToolbar");
  1206. var ContactList = require("./side_pannels/contactlist/ContactList");
  1207. var Avatar = require("./avatar/Avatar");
  1208. var EventEmitter = require("events");
  1209. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1210. var Settings = require("./../settings/Settings");
  1211. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1212. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1213. UI.messageHandler = require("./util/MessageHandler");
  1214. var messageHandler = UI.messageHandler;
  1215. var Authentication = require("./authentication/Authentication");
  1216. var UIUtil = require("./util/UIUtil");
  1217. var NicknameHandler = require("./util/NicknameHandler");
  1218. var CQEvents = require("../../service/connectionquality/CQEvents");
  1219. var DesktopSharingEventTypes
  1220. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1221. var RTCEvents = require("../../service/RTC/RTCEvents");
  1222. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1223. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1224. var eventEmitter = new EventEmitter();
  1225. var roomName = null;
  1226. function setupPrezi()
  1227. {
  1228. $("#reloadPresentationLink").click(function()
  1229. {
  1230. Prezi.reloadPresentation();
  1231. });
  1232. }
  1233. function setupChat()
  1234. {
  1235. Chat.init();
  1236. $("#toggle_smileys").click(function() {
  1237. Chat.toggleSmileys();
  1238. });
  1239. }
  1240. function setupToolbars() {
  1241. Toolbar.init(UI);
  1242. Toolbar.setupButtonsFromConfig();
  1243. BottomToolbar.init();
  1244. }
  1245. function streamHandler(stream) {
  1246. switch (stream.type)
  1247. {
  1248. case "audio":
  1249. VideoLayout.changeLocalAudio(stream);
  1250. break;
  1251. case "video":
  1252. VideoLayout.changeLocalVideo(stream);
  1253. break;
  1254. case "stream":
  1255. VideoLayout.changeLocalStream(stream);
  1256. break;
  1257. }
  1258. }
  1259. function onDisposeConference(unload) {
  1260. Toolbar.showAuthenticateButton(false);
  1261. };
  1262. function onDisplayNameChanged(jid, displayName) {
  1263. ContactList.onDisplayNameChange(jid, displayName);
  1264. SettingsMenu.onDisplayNameChange(jid, displayName);
  1265. VideoLayout.onDisplayNameChanged(jid, displayName);
  1266. }
  1267. function registerListeners() {
  1268. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1269. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1270. APP.RTC.addStreamListener(function (stream) {
  1271. VideoLayout.onRemoteStreamAdded(stream);
  1272. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1273. APP.RTC.addStreamListener(function (jid) {
  1274. VideoLayout.onVideoTypeChanged(jid);
  1275. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  1276. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1277. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1278. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1279. });
  1280. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1281. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1282. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1283. endpointsEnteringLastN, stream);
  1284. });
  1285. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  1286. function (endpointSimulcastLayers) {
  1287. VideoLayout.onSimulcastLayersChanged(endpointSimulcastLayers);
  1288. });
  1289. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGING,
  1290. function (endpointSimulcastLayers) {
  1291. VideoLayout.onSimulcastLayersChanging(endpointSimulcastLayers);
  1292. });
  1293. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  1294. function (devices) {
  1295. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  1296. })
  1297. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1298. {
  1299. var resourceJid;
  1300. if(jid === APP.statistics.LOCAL_JID)
  1301. {
  1302. resourceJid = AudioLevels.LOCAL_LEVEL;
  1303. if(APP.RTC.localAudio.isMuted())
  1304. {
  1305. audioLevel = 0;
  1306. }
  1307. }
  1308. else
  1309. {
  1310. resourceJid = Strophe.getResourceFromJid(jid);
  1311. }
  1312. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1313. UI.getLargeVideoState().userResourceJid);
  1314. });
  1315. APP.desktopsharing.addListener(function () {
  1316. ToolbarToggler.showDesktopSharingButton();
  1317. }, DesktopSharingEventTypes.INIT);
  1318. APP.desktopsharing.addListener(
  1319. Toolbar.changeDesktopSharingButtonState,
  1320. DesktopSharingEventTypes.SWITCHING_DONE);
  1321. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1322. VideoLayout.updateLocalConnectionStats);
  1323. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1324. VideoLayout.updateConnectionStats);
  1325. APP.connectionquality.addListener(CQEvents.STOP,
  1326. VideoLayout.onStatsStop);
  1327. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1328. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  1329. messageHandler.openMessageDialog(
  1330. 'dialog.serviceUnavailable',
  1331. 'dialog.gracefulShutdown'
  1332. );
  1333. });
  1334. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  1335. var title = APP.translation.generateTranslatonHTML(
  1336. "dialog.reservationError");
  1337. var message = APP.translation.generateTranslatonHTML(
  1338. "dialog.reservationErrorMsg", {code: code, msg: msg});
  1339. messageHandler.openDialog(
  1340. title,
  1341. message,
  1342. true, {},
  1343. function (event, value, message, formVals)
  1344. {
  1345. return false;
  1346. }
  1347. );
  1348. });
  1349. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1350. messageHandler.openMessageDialog("dialog.sessTerminated",
  1351. "dialog.kickMessage");
  1352. });
  1353. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1354. //FIXME: use Session Terminated from translation, but
  1355. // 'reason' text comes from XMPP packet and is not translated
  1356. var title = APP.translation.generateTranslatonHTML("dialog.sessTerminated");
  1357. messageHandler.openDialog(
  1358. title, reason, true, {},
  1359. function (event, value, message, formVals)
  1360. {
  1361. return false;
  1362. }
  1363. );
  1364. });
  1365. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1366. messageHandler.showError("dialog.error",
  1367. "dialog.bridgeUnavailable");
  1368. });
  1369. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1370. Avatar.setUserAvatar(from, id);
  1371. });
  1372. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  1373. for(stream in changedStreams)
  1374. {
  1375. // might need to update the direction if participant just went from sendrecv to recvonly
  1376. if (stream.type === 'video' || stream.type === 'screen') {
  1377. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1378. switch (stream.direction) {
  1379. case 'sendrecv':
  1380. el.show();
  1381. break;
  1382. case 'recvonly':
  1383. el.hide();
  1384. // FIXME: Check if we have to change large video
  1385. //VideoLayout.updateLargeVideo(el);
  1386. break;
  1387. }
  1388. }
  1389. }
  1390. });
  1391. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1392. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1393. APP.xmpp.addListener(XMPPEvents.LOCALROLE_CHANGED, onLocalRoleChange);
  1394. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, onMucEntered);
  1395. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1396. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1397. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1398. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1399. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1400. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordReqiured);
  1401. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1402. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1403. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  1404. onAuthenticationRequired);
  1405. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  1406. function (resource, devices) {
  1407. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  1408. });
  1409. }
  1410. /**
  1411. * Mutes/unmutes the local video.
  1412. *
  1413. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1414. * @param options an object which specifies optional arguments such as the
  1415. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1416. * specifies whether the method was initiated in response to a user command (in
  1417. * contrast to an automatic decision taken by the application logic)
  1418. */
  1419. function setVideoMute(mute, options) {
  1420. APP.RTC.setVideoMute(mute,
  1421. UI.setVideoMuteButtonsState,
  1422. options);
  1423. }
  1424. function bindEvents()
  1425. {
  1426. /**
  1427. * Resizes and repositions videos in full screen mode.
  1428. */
  1429. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1430. function () {
  1431. VideoLayout.resizeLargeVideoContainer();
  1432. VideoLayout.positionLarge();
  1433. }
  1434. );
  1435. $(window).resize(function () {
  1436. VideoLayout.resizeLargeVideoContainer();
  1437. VideoLayout.positionLarge();
  1438. });
  1439. }
  1440. UI.start = function (init) {
  1441. document.title = interfaceConfig.APP_NAME;
  1442. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1443. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1444. {
  1445. $("#videoconference_page").hide();
  1446. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1447. setupWelcomePage();
  1448. return;
  1449. }
  1450. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1451. var leftWatermarkDiv
  1452. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1453. leftWatermarkDiv.css({display: 'block'});
  1454. leftWatermarkDiv.parent().get(0).href
  1455. = interfaceConfig.JITSI_WATERMARK_LINK;
  1456. }
  1457. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1458. var rightWatermarkDiv
  1459. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1460. rightWatermarkDiv.css({display: 'block'});
  1461. rightWatermarkDiv.parent().get(0).href
  1462. = interfaceConfig.BRAND_WATERMARK_LINK;
  1463. rightWatermarkDiv.get(0).style.backgroundImage
  1464. = "url(images/rightwatermark.png)";
  1465. }
  1466. if (interfaceConfig.SHOW_POWERED_BY) {
  1467. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1468. }
  1469. $("#welcome_page").hide();
  1470. VideoLayout.resizeLargeVideoContainer();
  1471. $("#videospace").mousemove(function () {
  1472. return ToolbarToggler.showToolbar();
  1473. });
  1474. // Set the defaults for prompt dialogs.
  1475. jQuery.prompt.setDefaults({persistent: false});
  1476. VideoLayout.init(eventEmitter);
  1477. AudioLevels.init();
  1478. NicknameHandler.init(eventEmitter);
  1479. registerListeners();
  1480. bindEvents();
  1481. setupPrezi();
  1482. setupToolbars();
  1483. setupChat();
  1484. document.title = interfaceConfig.APP_NAME;
  1485. $("#downloadlog").click(function (event) {
  1486. dump(event.target);
  1487. });
  1488. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1489. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1490. {
  1491. $("#videoconference_page").hide();
  1492. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1493. setupWelcomePage();
  1494. return;
  1495. }
  1496. $("#welcome_page").hide();
  1497. // Display notice message at the top of the toolbar
  1498. if (config.noticeMessage) {
  1499. $('#noticeText').text(config.noticeMessage);
  1500. $('#notice').css({display: 'block'});
  1501. }
  1502. document.getElementById('largeVideo').volume = 0;
  1503. if (!$('#settings').is(':visible')) {
  1504. console.log('init');
  1505. init();
  1506. } else {
  1507. loginInfo.onsubmit = function (e) {
  1508. if (e.preventDefault) e.preventDefault();
  1509. $('#settings').hide();
  1510. init();
  1511. };
  1512. }
  1513. toastr.options = {
  1514. "closeButton": true,
  1515. "debug": false,
  1516. "positionClass": "notification-bottom-right",
  1517. "onclick": null,
  1518. "showDuration": "300",
  1519. "hideDuration": "1000",
  1520. "timeOut": "2000",
  1521. "extendedTimeOut": "1000",
  1522. "showEasing": "swing",
  1523. "hideEasing": "linear",
  1524. "showMethod": "fadeIn",
  1525. "hideMethod": "fadeOut",
  1526. "reposition": function() {
  1527. if(PanelToggler.isVisible()) {
  1528. $("#toast-container").addClass("notification-bottom-right-center");
  1529. } else {
  1530. $("#toast-container").removeClass("notification-bottom-right-center");
  1531. }
  1532. },
  1533. "newestOnTop": false
  1534. };
  1535. SettingsMenu.init();
  1536. };
  1537. function chatAddError(errorMessage, originalText)
  1538. {
  1539. return Chat.chatAddError(errorMessage, originalText);
  1540. };
  1541. function chatSetSubject(text)
  1542. {
  1543. return Chat.chatSetSubject(text);
  1544. };
  1545. function updateChatConversation(from, displayName, message) {
  1546. return Chat.updateChatConversation(from, displayName, message);
  1547. };
  1548. function onMucJoined(jid, info) {
  1549. Toolbar.updateRoomUrl(window.location.href);
  1550. var meHTML = APP.translation.generateTranslatonHTML("me");
  1551. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  1552. var settings = Settings.getSettings();
  1553. // Add myself to the contact list.
  1554. ContactList.addContact(jid, settings.email || settings.uid);
  1555. // Once we've joined the muc show the toolbar
  1556. ToolbarToggler.showToolbar();
  1557. var displayName = !config.displayJids
  1558. ? info.displayName : Strophe.getResourceFromJid(jid);
  1559. if (displayName)
  1560. onDisplayNameChanged('localVideoContainer', displayName);
  1561. }
  1562. function initEtherpad(name) {
  1563. Etherpad.init(name);
  1564. };
  1565. function onMucLeft(jid) {
  1566. console.log('left.muc', jid);
  1567. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1568. '>.displayname').html();
  1569. messageHandler.notify(displayName,'notify.somebody',
  1570. 'disconnected',
  1571. 'notify.disconnected');
  1572. // Need to call this with a slight delay, otherwise the element couldn't be
  1573. // found for some reason.
  1574. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1575. window.setTimeout(function () {
  1576. var container = document.getElementById(
  1577. 'participant_' + Strophe.getResourceFromJid(jid));
  1578. if (container) {
  1579. ContactList.removeContact(jid);
  1580. VideoLayout.removeConnectionIndicator(jid);
  1581. // hide here, wait for video to close before removing
  1582. $(container).hide();
  1583. VideoLayout.resizeThumbnails();
  1584. }
  1585. }, 10);
  1586. VideoLayout.participantLeft(jid);
  1587. };
  1588. function onLocalRoleChange(jid, info, pres, isModerator)
  1589. {
  1590. console.info("My role changed, new role: " + info.role);
  1591. onModeratorStatusChanged(isModerator);
  1592. VideoLayout.showModeratorIndicator();
  1593. if (isModerator) {
  1594. Authentication.closeAuthenticationWindow();
  1595. messageHandler.notify(null, "notify.me",
  1596. 'connected', "notify.moderator");
  1597. }
  1598. }
  1599. function onModeratorStatusChanged(isModerator) {
  1600. Toolbar.showSipCallButton(isModerator);
  1601. Toolbar.showRecordingButton(
  1602. isModerator); //&&
  1603. // FIXME:
  1604. // Recording visible if
  1605. // there are at least 2(+ 1 focus) participants
  1606. //Object.keys(connection.emuc.members).length >= 3);
  1607. if (isModerator && config.etherpad_base) {
  1608. Etherpad.init();
  1609. }
  1610. };
  1611. function onPasswordReqiured(callback) {
  1612. // password is required
  1613. Toolbar.lockLockButton();
  1614. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1615. message += APP.translation.translateString(
  1616. "dialog.passwordRequired");
  1617. message += '</h2>' +
  1618. '<input name="lockKey" type="text" data-i18n=' +
  1619. '"[placeholder]dialog.password" placeholder="' +
  1620. APP.translation.translateString("dialog.password") +
  1621. '" autofocus>';
  1622. messageHandler.openTwoButtonDialog(null, null, null, message,
  1623. true,
  1624. "dialog.Ok",
  1625. function (e, v, m, f) {},
  1626. null,
  1627. function (e, v, m, f) {
  1628. if (v) {
  1629. var lockKey = f.lockKey;
  1630. if (lockKey) {
  1631. Toolbar.setSharedKey(lockKey);
  1632. callback(lockKey);
  1633. }
  1634. }
  1635. },
  1636. ':input:first'
  1637. );
  1638. }
  1639. function onMucEntered(jid, id, displayName) {
  1640. messageHandler.notify(displayName,'notify.somebody',
  1641. 'connected',
  1642. 'notify.connected');
  1643. // Add Peer's container
  1644. VideoLayout.ensurePeerContainerExists(jid,id);
  1645. }
  1646. function onMucPresenceStatus( jid, info) {
  1647. VideoLayout.setPresenceStatus(
  1648. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1649. }
  1650. function onMucRoleChanged(role, displayName) {
  1651. VideoLayout.showModeratorIndicator();
  1652. if (role === 'moderator') {
  1653. var messageKey, messageOptions = {};
  1654. if (!displayName) {
  1655. messageKey = "notify.grantedToUnknown";
  1656. }
  1657. else
  1658. {
  1659. messageKey = "notify.grantedTo";
  1660. messageOptions = {to: displayName};
  1661. }
  1662. messageHandler.notify(
  1663. displayName,'notify.somebody',
  1664. 'connected', messageKey,
  1665. messageOptions);
  1666. }
  1667. }
  1668. function onAuthenticationRequired(intervalCallback) {
  1669. Authentication.openAuthenticationDialog(
  1670. roomName, intervalCallback, function () {
  1671. Toolbar.authenticateClicked();
  1672. });
  1673. };
  1674. function onLastNChanged(oldValue, newValue) {
  1675. if (config.muteLocalVideoIfNotInLastN) {
  1676. setVideoMute(!newValue, { 'byUser': false });
  1677. }
  1678. }
  1679. UI.toggleSmileys = function () {
  1680. Chat.toggleSmileys();
  1681. };
  1682. UI.getSettings = function () {
  1683. return Settings.getSettings();
  1684. };
  1685. UI.toggleFilmStrip = function () {
  1686. return BottomToolbar.toggleFilmStrip();
  1687. };
  1688. UI.toggleChat = function () {
  1689. return BottomToolbar.toggleChat();
  1690. };
  1691. UI.toggleContactList = function () {
  1692. return BottomToolbar.toggleContactList();
  1693. };
  1694. UI.inputDisplayNameHandler = function (value) {
  1695. VideoLayout.inputDisplayNameHandler(value);
  1696. };
  1697. UI.getLargeVideoState = function()
  1698. {
  1699. return VideoLayout.getLargeVideoState();
  1700. };
  1701. UI.generateRoomName = function() {
  1702. if(roomName)
  1703. return roomName;
  1704. var roomnode = null;
  1705. var path = window.location.pathname;
  1706. // determinde the room node from the url
  1707. // TODO: just the roomnode or the whole bare jid?
  1708. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1709. // custom function might be responsible for doing the pushstate
  1710. roomnode = config.getroomnode(path);
  1711. } else {
  1712. /* fall back to default strategy
  1713. * this is making assumptions about how the URL->room mapping happens.
  1714. * It currently assumes deployment at root, with a rewrite like the
  1715. * following one (for nginx):
  1716. location ~ ^/([a-zA-Z0-9]+)$ {
  1717. rewrite ^/(.*)$ / break;
  1718. }
  1719. */
  1720. if (path.length > 1) {
  1721. roomnode = path.substr(1).toLowerCase();
  1722. } else {
  1723. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1724. roomnode = word.toLowerCase();
  1725. window.history.pushState('VideoChat',
  1726. 'Room: ' + word, window.location.pathname + word);
  1727. }
  1728. }
  1729. roomName = roomnode + '@' + config.hosts.muc;
  1730. return roomName;
  1731. };
  1732. UI.connectionIndicatorShowMore = function(id)
  1733. {
  1734. return VideoLayout.connectionIndicators[id].showMore();
  1735. };
  1736. UI.showLoginPopup = function(callback)
  1737. {
  1738. console.log('password is required');
  1739. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1740. message += APP.translation.translateString(
  1741. "dialog.passwordRequired");
  1742. message += '</h2>' +
  1743. '<input name="username" type="text" ' +
  1744. 'placeholder="user@domain.net" autofocus>' +
  1745. '<input name="password" ' +
  1746. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  1747. ' placeholder="user password">';
  1748. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  1749. true,
  1750. "dialog.Ok",
  1751. function (e, v, m, f) {
  1752. if (v) {
  1753. if (f.username !== null && f.password != null) {
  1754. callback(f.username, f.password);
  1755. }
  1756. }
  1757. },
  1758. null, null, ':input:first'
  1759. );
  1760. }
  1761. UI.checkForNicknameAndJoin = function () {
  1762. Authentication.closeAuthenticationDialog();
  1763. Authentication.stopInterval();
  1764. var nick = null;
  1765. if (config.useNicks) {
  1766. nick = window.prompt('Your nickname (optional)');
  1767. }
  1768. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1769. };
  1770. function dump(elem, filename) {
  1771. elem = elem.parentNode;
  1772. elem.download = filename || 'meetlog.json';
  1773. elem.href = 'data:application/json;charset=utf-8,\n';
  1774. var data = APP.xmpp.populateData();
  1775. var metadata = {};
  1776. metadata.time = new Date();
  1777. metadata.url = window.location.href;
  1778. metadata.ua = navigator.userAgent;
  1779. var log = APP.xmpp.getLogger();
  1780. if (log) {
  1781. metadata.xmpp = log;
  1782. }
  1783. data.metadata = metadata;
  1784. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1785. return false;
  1786. }
  1787. UI.getRoomName = function () {
  1788. return roomName;
  1789. };
  1790. /**
  1791. * Mutes/unmutes the local video.
  1792. */
  1793. UI.toggleVideo = function () {
  1794. setVideoMute(!APP.RTC.localVideo.isMuted());
  1795. };
  1796. /**
  1797. * Mutes / unmutes audio for the local participant.
  1798. */
  1799. UI.toggleAudio = function() {
  1800. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  1801. };
  1802. /**
  1803. * Sets muted audio state for the local participant.
  1804. */
  1805. UI.setAudioMuted = function (mute) {
  1806. if(!APP.xmpp.setAudioMute(mute, function () {
  1807. VideoLayout.showLocalAudioIndicator(mute);
  1808. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1809. }))
  1810. {
  1811. // We still click the button.
  1812. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1813. return;
  1814. }
  1815. }
  1816. UI.addListener = function (type, listener) {
  1817. eventEmitter.on(type, listener);
  1818. }
  1819. UI.clickOnVideo = function (videoNumber) {
  1820. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  1821. if (remoteVideos.length > videoNumber) {
  1822. remoteVideos[videoNumber].click();
  1823. }
  1824. }
  1825. //Used by torture
  1826. UI.showToolbar = function () {
  1827. return ToolbarToggler.showToolbar();
  1828. }
  1829. //Used by torture
  1830. UI.dockToolbar = function (isDock) {
  1831. return ToolbarToggler.dockToolbar(isDock);
  1832. }
  1833. UI.setVideoMuteButtonsState = function (mute) {
  1834. var video = $('#video');
  1835. var communicativeClass = "icon-camera";
  1836. var muteClass = "icon-camera icon-camera-disabled";
  1837. if (mute) {
  1838. video.removeClass(communicativeClass);
  1839. video.addClass(muteClass);
  1840. } else {
  1841. video.removeClass(muteClass);
  1842. video.addClass(communicativeClass);
  1843. }
  1844. }
  1845. module.exports = UI;
  1846. },{"../../service/RTC/RTCEvents":89,"../../service/RTC/StreamEventTypes":91,"../../service/connectionquality/CQEvents":94,"../../service/desktopsharing/DesktopSharingEventTypes":95,"../../service/xmpp/XMPPEvents":97,"./../settings/Settings":38,"./audio_levels/AudioLevels.js":9,"./authentication/Authentication":11,"./avatar/Avatar":13,"./etherpad/Etherpad.js":14,"./prezi/Prezi.js":15,"./side_pannels/SidePanelToggler":17,"./side_pannels/chat/Chat.js":18,"./side_pannels/contactlist/ContactList":22,"./side_pannels/settings/SettingsMenu":23,"./toolbars/BottomToolbar":24,"./toolbars/Toolbar":25,"./toolbars/ToolbarToggler":26,"./util/MessageHandler":28,"./util/NicknameHandler":29,"./util/UIUtil":30,"./videolayout/VideoLayout.js":32,"./welcome_page/RoomnameGenerator":33,"./welcome_page/WelcomePage":34,"events":98}],9:[function(require,module,exports){
  1847. var CanvasUtil = require("./CanvasUtils");
  1848. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  1849. function initActiveSpeakerAudioLevels() {
  1850. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  1851. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  1852. // Draw a circle.
  1853. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  1854. // Add a shadow around the circle
  1855. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  1856. ASDrawContext.shadowOffsetX = 0;
  1857. ASDrawContext.shadowOffsetY = 0;
  1858. }
  1859. /**
  1860. * The audio Levels plugin.
  1861. */
  1862. var AudioLevels = (function(my) {
  1863. var audioLevelCanvasCache = {};
  1864. my.LOCAL_LEVEL = 'local';
  1865. my.init = function () {
  1866. initActiveSpeakerAudioLevels();
  1867. }
  1868. /**
  1869. * Updates the audio level canvas for the given peerJid. If the canvas
  1870. * didn't exist we create it.
  1871. */
  1872. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  1873. var resourceJid = null;
  1874. var videoSpanId = null;
  1875. if (!peerJid)
  1876. videoSpanId = 'localVideoContainer';
  1877. else {
  1878. resourceJid = Strophe.getResourceFromJid(peerJid);
  1879. videoSpanId = 'participant_' + resourceJid;
  1880. }
  1881. var videoSpan = document.getElementById(videoSpanId);
  1882. if (!videoSpan) {
  1883. if (resourceJid)
  1884. console.error("No video element for jid", resourceJid);
  1885. else
  1886. console.error("No video element for local video.");
  1887. return;
  1888. }
  1889. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  1890. var videoSpaceWidth = $('#remoteVideos').width();
  1891. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  1892. var thumbnailWidth = thumbnailSize[0];
  1893. var thumbnailHeight = thumbnailSize[1];
  1894. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  1895. audioLevelCanvas = document.createElement('canvas');
  1896. audioLevelCanvas.className = "audiolevel";
  1897. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1898. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1899. resizeAudioLevelCanvas( audioLevelCanvas,
  1900. thumbnailWidth,
  1901. thumbnailHeight);
  1902. videoSpan.appendChild(audioLevelCanvas);
  1903. } else {
  1904. audioLevelCanvas = audioLevelCanvas.get(0);
  1905. resizeAudioLevelCanvas( audioLevelCanvas,
  1906. thumbnailWidth,
  1907. thumbnailHeight);
  1908. }
  1909. };
  1910. /**
  1911. * Updates the audio level UI for the given resourceJid.
  1912. *
  1913. * @param resourceJid the resource jid indicating the video element for
  1914. * which we draw the audio level
  1915. * @param audioLevel the newAudio level to render
  1916. */
  1917. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  1918. drawAudioLevelCanvas(resourceJid, audioLevel);
  1919. var videoSpanId = getVideoSpanId(resourceJid);
  1920. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  1921. if (!audioLevelCanvas)
  1922. return;
  1923. var drawContext = audioLevelCanvas.getContext('2d');
  1924. var canvasCache = audioLevelCanvasCache[resourceJid];
  1925. drawContext.clearRect (0, 0,
  1926. audioLevelCanvas.width, audioLevelCanvas.height);
  1927. drawContext.drawImage(canvasCache, 0, 0);
  1928. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  1929. if(!APP.xmpp.myJid()) {
  1930. return;
  1931. }
  1932. resourceJid = APP.xmpp.myResource();
  1933. }
  1934. if(resourceJid === largeVideoResourceJid) {
  1935. window.requestAnimationFrame(function () {
  1936. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  1937. });
  1938. }
  1939. };
  1940. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  1941. if($("#activeSpeaker").css("visibility") == "hidden")
  1942. return;
  1943. ASDrawContext.clearRect(0, 0, 300, 300);
  1944. if(audioLevel == 0)
  1945. return;
  1946. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  1947. // Fill the shape.
  1948. ASDrawContext.fill();
  1949. };
  1950. /**
  1951. * Resizes the given audio level canvas to match the given thumbnail size.
  1952. */
  1953. function resizeAudioLevelCanvas(audioLevelCanvas,
  1954. thumbnailWidth,
  1955. thumbnailHeight) {
  1956. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  1957. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  1958. }
  1959. /**
  1960. * Draws the audio level canvas into the cached canvas object.
  1961. *
  1962. * @param resourceJid the resource jid indicating the video element for
  1963. * which we draw the audio level
  1964. * @param audioLevel the newAudio level to render
  1965. */
  1966. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  1967. if (!audioLevelCanvasCache[resourceJid]) {
  1968. var videoSpanId = getVideoSpanId(resourceJid);
  1969. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  1970. /*
  1971. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  1972. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  1973. * error. Since audio levels are frequently updated, the errors have
  1974. * been observed to pile into the console, strain the CPU.
  1975. */
  1976. if (audioLevelCanvasOrig)
  1977. {
  1978. audioLevelCanvasCache[resourceJid]
  1979. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  1980. }
  1981. }
  1982. var canvas = audioLevelCanvasCache[resourceJid];
  1983. if (!canvas)
  1984. return;
  1985. var drawContext = canvas.getContext('2d');
  1986. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  1987. var shadowLevel = getShadowLevel(audioLevel);
  1988. if (shadowLevel > 0)
  1989. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  1990. CanvasUtil.drawRoundRectGlow( drawContext,
  1991. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  1992. canvas.width - interfaceConfig.CANVAS_EXTRA,
  1993. canvas.height - interfaceConfig.CANVAS_EXTRA,
  1994. interfaceConfig.CANVAS_RADIUS,
  1995. interfaceConfig.SHADOW_COLOR,
  1996. shadowLevel);
  1997. }
  1998. /**
  1999. * Returns the shadow/glow level for the given audio level.
  2000. *
  2001. * @param audioLevel the audio level from which we determine the shadow
  2002. * level
  2003. */
  2004. function getShadowLevel (audioLevel) {
  2005. var shadowLevel = 0;
  2006. if (audioLevel <= 0.3) {
  2007. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  2008. }
  2009. else if (audioLevel <= 0.6) {
  2010. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  2011. }
  2012. else {
  2013. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  2014. }
  2015. return shadowLevel;
  2016. }
  2017. /**
  2018. * Returns the video span id corresponding to the given resourceJid or local
  2019. * user.
  2020. */
  2021. function getVideoSpanId(resourceJid) {
  2022. var videoSpanId = null;
  2023. if (resourceJid === AudioLevels.LOCAL_LEVEL
  2024. || (APP.xmpp.myResource() && resourceJid
  2025. === APP.xmpp.myResource()))
  2026. videoSpanId = 'localVideoContainer';
  2027. else
  2028. videoSpanId = 'participant_' + resourceJid;
  2029. return videoSpanId;
  2030. }
  2031. /**
  2032. * Indicates that the remote video has been resized.
  2033. */
  2034. $(document).bind('remotevideo.resized', function (event, width, height) {
  2035. var resized = false;
  2036. $('#remoteVideos>span>canvas').each(function() {
  2037. var canvas = $(this).get(0);
  2038. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  2039. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  2040. resized = true;
  2041. }
  2042. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  2043. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  2044. resized = true;
  2045. }
  2046. });
  2047. if (resized)
  2048. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  2049. audioLevelCanvasCache[resourceJid].width
  2050. = width + interfaceConfig.CANVAS_EXTRA;
  2051. audioLevelCanvasCache[resourceJid].height
  2052. = height + interfaceConfig.CANVAS_EXTRA;
  2053. });
  2054. });
  2055. return my;
  2056. })(AudioLevels || {});
  2057. module.exports = AudioLevels;
  2058. },{"./CanvasUtils":10}],10:[function(require,module,exports){
  2059. /**
  2060. * Utility class for drawing canvas shapes.
  2061. */
  2062. var CanvasUtil = (function(my) {
  2063. /**
  2064. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  2065. * of the glow.
  2066. *
  2067. * @param drawContext the context of the canvas to draw to
  2068. * @param x the x coordinate of the round rectangle
  2069. * @param y the y coordinate of the round rectangle
  2070. * @param w the width of the round rectangle
  2071. * @param h the height of the round rectangle
  2072. * @param glowColor the color of the glow
  2073. * @param glowWidth the width of the glow
  2074. */
  2075. my.drawRoundRectGlow
  2076. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  2077. // Save the previous state of the context.
  2078. drawContext.save();
  2079. if (w < 2 * r) r = w / 2;
  2080. if (h < 2 * r) r = h / 2;
  2081. // Draw a round rectangle.
  2082. drawContext.beginPath();
  2083. drawContext.moveTo(x+r, y);
  2084. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2085. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2086. drawContext.arcTo(x, y+h, x, y, r);
  2087. drawContext.arcTo(x, y, x+w, y, r);
  2088. drawContext.closePath();
  2089. // Add a shadow around the rectangle
  2090. drawContext.shadowColor = glowColor;
  2091. drawContext.shadowBlur = glowWidth;
  2092. drawContext.shadowOffsetX = 0;
  2093. drawContext.shadowOffsetY = 0;
  2094. // Fill the shape.
  2095. drawContext.fill();
  2096. drawContext.save();
  2097. drawContext.restore();
  2098. // 1) Uncomment this line to use Composite Operation, which is doing the
  2099. // same as the clip function below and is also antialiasing the round
  2100. // border, but is said to be less fast performance wise.
  2101. // drawContext.globalCompositeOperation='destination-out';
  2102. drawContext.beginPath();
  2103. drawContext.moveTo(x+r, y);
  2104. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2105. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2106. drawContext.arcTo(x, y+h, x, y, r);
  2107. drawContext.arcTo(x, y, x+w, y, r);
  2108. drawContext.closePath();
  2109. // 2) Uncomment this line to use Composite Operation, which is doing the
  2110. // same as the clip function below and is also antialiasing the round
  2111. // border, but is said to be less fast performance wise.
  2112. // drawContext.fill();
  2113. // Comment these two lines if choosing to do the same with composite
  2114. // operation above 1 and 2.
  2115. drawContext.clip();
  2116. drawContext.clearRect(0, 0, 277, 200);
  2117. // Restore the previous context state.
  2118. drawContext.restore();
  2119. };
  2120. /**
  2121. * Clones the given canvas.
  2122. *
  2123. * @return the new cloned canvas.
  2124. */
  2125. my.cloneCanvas = function (oldCanvas) {
  2126. /*
  2127. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2128. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2129. * levels are frequently updated, the errors have been observed to pile
  2130. * into the console, strain the CPU.
  2131. */
  2132. if (!oldCanvas)
  2133. return oldCanvas;
  2134. //create a new canvas
  2135. var newCanvas = document.createElement('canvas');
  2136. var context = newCanvas.getContext('2d');
  2137. //set dimensions
  2138. newCanvas.width = oldCanvas.width;
  2139. newCanvas.height = oldCanvas.height;
  2140. //apply the old canvas to the new one
  2141. context.drawImage(oldCanvas, 0, 0);
  2142. //return the new canvas
  2143. return newCanvas;
  2144. };
  2145. return my;
  2146. })(CanvasUtil || {});
  2147. module.exports = CanvasUtil;
  2148. },{}],11:[function(require,module,exports){
  2149. /* global $, APP*/
  2150. var LoginDialog = require('./LoginDialog');
  2151. var Moderator = require('../../xmpp/moderator');
  2152. /* Initial "authentication required" dialog */
  2153. var authDialog = null;
  2154. /* Loop retry ID that wits for other user to create the room */
  2155. var authRetryId = null;
  2156. var authenticationWindow = null;
  2157. var Authentication = {
  2158. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2159. // This is the loop that will wait for the room to be created by
  2160. // someone else. 'auth_required.moderator' will bring us back here.
  2161. authRetryId = window.setTimeout(intervalCallback, 5000);
  2162. // Show prompt only if it's not open
  2163. if (authDialog !== null) {
  2164. return;
  2165. }
  2166. // extract room name from 'room@muc.server.net'
  2167. var room = roomName.substr(0, roomName.indexOf('@'));
  2168. var title = APP.translation.generateTranslatonHTML("dialog.Stop");
  2169. var msg = APP.translation.generateTranslatonHTML("dialog.AuthMsg",
  2170. {room: room});
  2171. var buttonTxt
  2172. = APP.translation.generateTranslatonHTML("dialog.Authenticate");
  2173. var buttons = [];
  2174. buttons.push({title: buttonTxt, value: "authNow"});
  2175. authDialog = APP.UI.messageHandler.openDialog(
  2176. title,
  2177. msg,
  2178. true,
  2179. buttons,
  2180. function (onSubmitEvent, submitValue) {
  2181. // Do not close the dialog yet
  2182. onSubmitEvent.preventDefault();
  2183. // Open login popup
  2184. if (submitValue === 'authNow') {
  2185. callback();
  2186. }
  2187. }
  2188. );
  2189. },
  2190. closeAuthenticationWindow: function () {
  2191. if (authenticationWindow) {
  2192. authenticationWindow.close();
  2193. authenticationWindow = null;
  2194. }
  2195. },
  2196. xmppAuthenticate: function () {
  2197. var loginDialog = LoginDialog.show(
  2198. function (connection, state) {
  2199. if (!state) {
  2200. // User cancelled
  2201. loginDialog.close();
  2202. return;
  2203. } else if (state == APP.xmpp.Status.CONNECTED) {
  2204. loginDialog.close();
  2205. Authentication.stopInterval();
  2206. Authentication.closeAuthenticationDialog();
  2207. // Close the connection as anonymous one will be used
  2208. // to create the conference. Session-id will authorize
  2209. // the request.
  2210. connection.disconnect();
  2211. var roomName = APP.UI.generateRoomName();
  2212. Moderator.allocateConferenceFocus(roomName, function () {
  2213. // If it's not "on the fly" authentication now join
  2214. // the conference room
  2215. if (!APP.xmpp.getMUCJoined()) {
  2216. APP.UI.checkForNicknameAndJoin();
  2217. }
  2218. });
  2219. }
  2220. }, true);
  2221. },
  2222. focusAuthenticationWindow: function () {
  2223. // If auth window exists just bring it to the front
  2224. if (authenticationWindow) {
  2225. authenticationWindow.focus();
  2226. return;
  2227. }
  2228. },
  2229. closeAuthenticationDialog: function () {
  2230. // Close authentication dialog if opened
  2231. if (authDialog) {
  2232. authDialog.close();
  2233. authDialog = null;
  2234. }
  2235. },
  2236. createAuthenticationWindow: function (callback, url) {
  2237. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2238. url, 910, 660,
  2239. // On closed
  2240. function () {
  2241. // Close authentication dialog if opened
  2242. Authentication.closeAuthenticationDialog();
  2243. callback();
  2244. authenticationWindow = null;
  2245. });
  2246. return authenticationWindow;
  2247. },
  2248. stopInterval: function () {
  2249. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2250. if (authRetryId) {
  2251. window.clearTimeout(authRetryId);
  2252. authRetryId = null;
  2253. }
  2254. }
  2255. };
  2256. module.exports = Authentication;
  2257. },{"../../xmpp/moderator":53,"./LoginDialog":12}],12:[function(require,module,exports){
  2258. /* global $, APP, config*/
  2259. var XMPP = require('../../xmpp/xmpp');
  2260. var Moderator = require('../../xmpp/moderator');
  2261. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  2262. // anonymous domain is not enabled
  2263. /**
  2264. * Creates new <tt>Dialog</tt> instance.
  2265. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  2266. * when we either fail to connect or succeed(check Strophe.Status).
  2267. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  2268. * in order to create session-id after the connection is established.
  2269. * @constructor
  2270. */
  2271. function Dialog(callback, obtainSession) {
  2272. var self = this;
  2273. var stop = false;
  2274. var connection = APP.xmpp.createConnection();
  2275. var message = '<h2 data-i18n="dialog.passwordRequired">';
  2276. message += APP.translation.translateString("dialog.passwordRequired");
  2277. message += '</h2>' +
  2278. '<input name="username" type="text" ' +
  2279. 'placeholder="user@domain.net" autofocus>' +
  2280. '<input name="password" ' +
  2281. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  2282. ' placeholder="user password">';
  2283. var okButton = APP.translation.generateTranslatonHTML("dialog.Ok");
  2284. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel");
  2285. var states = {
  2286. login: {
  2287. html: message,
  2288. buttons: [
  2289. { title: okButton, value: true},
  2290. { title: cancelButton, value: false}
  2291. ],
  2292. focus: ':input:first',
  2293. submit: function (e, v, m, f) {
  2294. e.preventDefault();
  2295. if (v) {
  2296. var jid = f.username;
  2297. var password = f.password;
  2298. if (jid && password) {
  2299. stop = false;
  2300. connection.reset();
  2301. connDialog.goToState('connecting');
  2302. connection.connect(jid, password, stateHandler);
  2303. }
  2304. } else {
  2305. // User cancelled
  2306. stop = true;
  2307. callback();
  2308. }
  2309. }
  2310. },
  2311. connecting: {
  2312. title: APP.translation.translateString('dialog.connecting'),
  2313. html: '<div id="connectionStatus"></div>',
  2314. buttons: [],
  2315. defaultButton: 0
  2316. },
  2317. finished: {
  2318. title: APP.translation.translateString('dialog.error'),
  2319. html: '<div id="errorMessage"></div>',
  2320. buttons: [
  2321. {
  2322. title: APP.translation.translateString('dialog.retry'),
  2323. value: 'retry'
  2324. },
  2325. {
  2326. title: APP.translation.translateString('dialog.Cancel'),
  2327. value: 'cancel'
  2328. },
  2329. ],
  2330. defaultButton: 0,
  2331. submit: function (e, v, m, f) {
  2332. e.preventDefault();
  2333. if (v === 'retry')
  2334. connDialog.goToState('login');
  2335. else
  2336. callback();
  2337. }
  2338. }
  2339. };
  2340. var connDialog
  2341. = APP.UI.messageHandler.openDialogWithStates(states,
  2342. { persistent: true, closeText: '' }, null);
  2343. var stateHandler = function (status, message) {
  2344. if (stop) {
  2345. return;
  2346. }
  2347. var translateKey = "connection." + XMPP.getStatusString(status);
  2348. var statusStr = APP.translation.translateString(translateKey);
  2349. // Display current state
  2350. var connectionStatus =
  2351. connDialog.getState('connecting').find('#connectionStatus');
  2352. connectionStatus.text(statusStr);
  2353. switch (status) {
  2354. case XMPP.Status.CONNECTED:
  2355. stop = true;
  2356. if (!obtainSession) {
  2357. callback(connection, status);
  2358. return;
  2359. }
  2360. // Obtaining session-id status
  2361. connectionStatus.text(
  2362. APP.translation.translateString(
  2363. 'connection.FETCH_SESSION_ID'));
  2364. // Authenticate with Jicofo and obtain session-id
  2365. var roomName = APP.UI.generateRoomName();
  2366. // Jicofo will return new session-id when connected
  2367. // from authenticated domain
  2368. connection.sendIQ(
  2369. Moderator.createConferenceIq(roomName),
  2370. function (result) {
  2371. connectionStatus.text(
  2372. APP.translation.translateString(
  2373. 'connection.GOT_SESSION_ID'));
  2374. stop = true;
  2375. // Parse session-id
  2376. Moderator.parseSessionId(result);
  2377. callback(connection, status);
  2378. },
  2379. function (error) {
  2380. console.error("Auth on the fly failed", error);
  2381. stop = true;
  2382. var errorMsg =
  2383. APP.translation.translateString(
  2384. 'connection.GET_SESSION_ID_ERROR') +
  2385. $(error).find('>error').attr('code');
  2386. self.displayError(errorMsg);
  2387. connection.disconnect();
  2388. });
  2389. break;
  2390. case XMPP.Status.AUTHFAIL:
  2391. case XMPP.Status.CONNFAIL:
  2392. case XMPP.Status.DISCONNECTED:
  2393. stop = true;
  2394. callback(connection, status);
  2395. var errorMessage = statusStr;
  2396. if (message)
  2397. {
  2398. errorMessage += ': ' + message;
  2399. }
  2400. self.displayError(errorMessage);
  2401. break;
  2402. default:
  2403. break;
  2404. }
  2405. };
  2406. /**
  2407. * Displays error message in 'finished' state which allows either to cancel
  2408. * or retry.
  2409. * @param message the final message to be displayed.
  2410. */
  2411. this.displayError = function (message) {
  2412. var finishedState = connDialog.getState('finished');
  2413. var errorMessageElem = finishedState.find('#errorMessage');
  2414. errorMessageElem.text(message);
  2415. connDialog.goToState('finished');
  2416. };
  2417. /**
  2418. * Closes LoginDialog.
  2419. */
  2420. this.close = function () {
  2421. stop = true;
  2422. connDialog.close();
  2423. };
  2424. }
  2425. var LoginDialog = {
  2426. /**
  2427. * Displays login prompt used to establish new XMPP connection. Given
  2428. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  2429. * called when we connect successfully(status === CONNECTED) or when we fail
  2430. * to do so. On connection failure program can call Dialog.close() method in
  2431. * order to cancel or do nothing to let the user retry.
  2432. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  2433. * called when we either fail to connect or succeed(check
  2434. * Strophe.Status).
  2435. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  2436. * Jicofo in order to create session-id after the connection is
  2437. * established.
  2438. * @returns {Dialog}
  2439. */
  2440. show: function (callback, obtainSession) {
  2441. return new Dialog(callback, obtainSession);
  2442. }
  2443. };
  2444. module.exports = LoginDialog;
  2445. },{"../../xmpp/moderator":53,"../../xmpp/xmpp":61}],13:[function(require,module,exports){
  2446. var Settings = require("../../settings/Settings");
  2447. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2448. var users = {};
  2449. var activeSpeakerJid;
  2450. function setVisibility(selector, show) {
  2451. if (selector && selector.length > 0) {
  2452. selector.css("visibility", show ? "visible" : "hidden");
  2453. }
  2454. }
  2455. function isUserMuted(jid) {
  2456. // XXX(gp) we may want to rename this method to something like
  2457. // isUserStreaming, for example.
  2458. if (jid && jid != APP.xmpp.myJid()) {
  2459. var resource = Strophe.getResourceFromJid(jid);
  2460. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2461. return true;
  2462. }
  2463. }
  2464. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2465. return null;
  2466. }
  2467. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2468. }
  2469. function getGravatarUrl(id, size) {
  2470. if(id === APP.xmpp.myJid() || !id) {
  2471. id = Settings.getSettings().uid;
  2472. }
  2473. return 'https://www.gravatar.com/avatar/' +
  2474. MD5.hexdigest(id.trim().toLowerCase()) +
  2475. "?d=wavatar&size=" + (size || "30");
  2476. }
  2477. var Avatar = {
  2478. /**
  2479. * Sets the user's avatar in the settings menu(if local user), contact list
  2480. * and thumbnail
  2481. * @param jid jid of the user
  2482. * @param id email or userID to be used as a hash
  2483. */
  2484. setUserAvatar: function (jid, id) {
  2485. if (id) {
  2486. if (users[jid] === id) {
  2487. return;
  2488. }
  2489. users[jid] = id;
  2490. }
  2491. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2492. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2493. var resourceJid = Strophe.getResourceFromJid(jid);
  2494. var thumbnail = $('#participant_' + resourceJid);
  2495. var avatar = $('#avatar_' + resourceJid);
  2496. // set the avatar in the settings menu if it is local user and get the
  2497. // local video container
  2498. if (jid === APP.xmpp.myJid()) {
  2499. $('#avatar').get(0).src = thumbUrl;
  2500. thumbnail = $('#localVideoContainer');
  2501. }
  2502. // set the avatar in the contact list
  2503. var contact = $('#' + resourceJid + '>img');
  2504. if (contact && contact.length > 0) {
  2505. contact.get(0).src = contactListUrl;
  2506. }
  2507. // set the avatar in the thumbnail
  2508. if (avatar && avatar.length > 0) {
  2509. avatar[0].src = thumbUrl;
  2510. } else {
  2511. if (thumbnail && thumbnail.length > 0) {
  2512. avatar = document.createElement('img');
  2513. avatar.id = 'avatar_' + resourceJid;
  2514. avatar.className = 'userAvatar';
  2515. avatar.src = thumbUrl;
  2516. thumbnail.append(avatar);
  2517. }
  2518. }
  2519. //if the user is the current active speaker - update the active speaker
  2520. // avatar
  2521. if (jid === activeSpeakerJid) {
  2522. this.updateActiveSpeakerAvatarSrc(jid);
  2523. }
  2524. },
  2525. /**
  2526. * Hides or shows the user's avatar
  2527. * @param jid jid of the user
  2528. * @param show whether we should show the avatar or not
  2529. * video because there is no dominant speaker and no focused speaker
  2530. */
  2531. showUserAvatar: function (jid, show) {
  2532. if (users[jid]) {
  2533. var resourceJid = Strophe.getResourceFromJid(jid);
  2534. var video = $('#participant_' + resourceJid + '>video');
  2535. var avatar = $('#avatar_' + resourceJid);
  2536. if (jid === APP.xmpp.myJid()) {
  2537. video = $('#localVideoWrapper>video');
  2538. }
  2539. if (show === undefined || show === null) {
  2540. show = isUserMuted(jid);
  2541. }
  2542. //if the user is the currently focused, the dominant speaker or if
  2543. //there is no focused and no dominant speaker and the large video is
  2544. //currently shown
  2545. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2546. setVisibility($("#largeVideo"), !show);
  2547. setVisibility($('#activeSpeaker'), show);
  2548. setVisibility(avatar, false);
  2549. setVisibility(video, false);
  2550. } else {
  2551. if (video && video.length > 0) {
  2552. setVisibility(video, !show);
  2553. setVisibility(avatar, show);
  2554. }
  2555. }
  2556. }
  2557. },
  2558. /**
  2559. * Updates the src of the active speaker avatar
  2560. * @param jid of the current active speaker
  2561. */
  2562. updateActiveSpeakerAvatarSrc: function (jid) {
  2563. if (!jid) {
  2564. jid = APP.xmpp.findJidFromResource(
  2565. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2566. }
  2567. var avatar = $("#activeSpeakerAvatar")[0];
  2568. var url = getGravatarUrl(users[jid],
  2569. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2570. if (jid === activeSpeakerJid && avatar.src === url) {
  2571. return;
  2572. }
  2573. activeSpeakerJid = jid;
  2574. var isMuted = isUserMuted(jid);
  2575. if (jid && isMuted !== null) {
  2576. avatar.src = url;
  2577. setVisibility($("#largeVideo"), !isMuted);
  2578. Avatar.showUserAvatar(jid, isMuted);
  2579. }
  2580. }
  2581. };
  2582. module.exports = Avatar;
  2583. },{"../../../service/RTC/MediaStreamTypes":87,"../../settings/Settings":38,"../videolayout/VideoLayout":32}],14:[function(require,module,exports){
  2584. /* global $, config,
  2585. setLargeVideoVisible, Util */
  2586. var VideoLayout = require("../videolayout/VideoLayout");
  2587. var Prezi = require("../prezi/Prezi");
  2588. var UIUtil = require("../util/UIUtil");
  2589. var etherpadName = null;
  2590. var etherpadIFrame = null;
  2591. var domain = null;
  2592. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2593. /**
  2594. * Resizes the etherpad.
  2595. */
  2596. function resize() {
  2597. if ($('#etherpad>iframe').length) {
  2598. var remoteVideos = $('#remoteVideos');
  2599. var availableHeight
  2600. = window.innerHeight - remoteVideos.outerHeight();
  2601. var availableWidth = UIUtil.getAvailableVideoWidth();
  2602. $('#etherpad>iframe').width(availableWidth);
  2603. $('#etherpad>iframe').height(availableHeight);
  2604. }
  2605. }
  2606. /**
  2607. * Shares the Etherpad name with other participants.
  2608. */
  2609. function shareEtherpad() {
  2610. APP.xmpp.addToPresence("etherpad", etherpadName);
  2611. }
  2612. /**
  2613. * Creates the Etherpad button and adds it to the toolbar.
  2614. */
  2615. function enableEtherpadButton() {
  2616. if (!$('#etherpadButton').is(":visible"))
  2617. $('#etherpadButton').css({display: 'inline-block'});
  2618. }
  2619. /**
  2620. * Creates the IFrame for the etherpad.
  2621. */
  2622. function createIFrame() {
  2623. etherpadIFrame = document.createElement('iframe');
  2624. etherpadIFrame.src = domain + etherpadName + options;
  2625. etherpadIFrame.frameBorder = 0;
  2626. etherpadIFrame.scrolling = "no";
  2627. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2628. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2629. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2630. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2631. etherpadIFrame.onload = function() {
  2632. document.domain = document.domain;
  2633. bubbleIframeMouseMove(etherpadIFrame);
  2634. setTimeout(function() {
  2635. // the iframes inside of the etherpad are
  2636. // not yet loaded when the etherpad iframe is loaded
  2637. var outer = etherpadIFrame.
  2638. contentDocument.getElementsByName("ace_outer")[0];
  2639. bubbleIframeMouseMove(outer);
  2640. var inner = outer.
  2641. contentDocument.getElementsByName("ace_inner")[0];
  2642. bubbleIframeMouseMove(inner);
  2643. }, 2000);
  2644. };
  2645. }
  2646. function bubbleIframeMouseMove(iframe){
  2647. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2648. iframe.contentWindow.onmousemove = function(e){
  2649. if(existingOnMouseMove) existingOnMouseMove(e);
  2650. var evt = document.createEvent("MouseEvents");
  2651. var boundingClientRect = iframe.getBoundingClientRect();
  2652. evt.initMouseEvent(
  2653. "mousemove",
  2654. true, // bubbles
  2655. false, // not cancelable
  2656. window,
  2657. e.detail,
  2658. e.screenX,
  2659. e.screenY,
  2660. e.clientX + boundingClientRect.left,
  2661. e.clientY + boundingClientRect.top,
  2662. e.ctrlKey,
  2663. e.altKey,
  2664. e.shiftKey,
  2665. e.metaKey,
  2666. e.button,
  2667. null // no related element
  2668. );
  2669. iframe.dispatchEvent(evt);
  2670. };
  2671. }
  2672. /**
  2673. * On video selected event.
  2674. */
  2675. $(document).bind('video.selected', function (event, isPresentation) {
  2676. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2677. Etherpad.toggleEtherpad(isPresentation);
  2678. });
  2679. var Etherpad = {
  2680. /**
  2681. * Initializes the etherpad.
  2682. */
  2683. init: function (name) {
  2684. if (config.etherpad_base && !etherpadName) {
  2685. domain = config.etherpad_base;
  2686. if (!name) {
  2687. // In case we're the focus we generate the name.
  2688. etherpadName = Math.random().toString(36).substring(7) +
  2689. '_' + (new Date().getTime()).toString();
  2690. shareEtherpad();
  2691. }
  2692. else
  2693. etherpadName = name;
  2694. enableEtherpadButton();
  2695. /**
  2696. * Resizes the etherpad, when the window is resized.
  2697. */
  2698. $(window).resize(function () {
  2699. resize();
  2700. });
  2701. }
  2702. },
  2703. /**
  2704. * Opens/hides the Etherpad.
  2705. */
  2706. toggleEtherpad: function (isPresentation) {
  2707. if (!etherpadIFrame)
  2708. createIFrame();
  2709. var largeVideo = null;
  2710. if (Prezi.isPresentationVisible())
  2711. largeVideo = $('#presentation>iframe');
  2712. else
  2713. largeVideo = $('#largeVideo');
  2714. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2715. $('#activeSpeaker').css('visibility', 'hidden');
  2716. largeVideo.fadeOut(300, function () {
  2717. if (Prezi.isPresentationVisible()) {
  2718. largeVideo.css({opacity: '0'});
  2719. } else {
  2720. VideoLayout.setLargeVideoVisible(false);
  2721. }
  2722. });
  2723. $('#etherpad>iframe').fadeIn(300, function () {
  2724. document.body.style.background = '#eeeeee';
  2725. $('#etherpad>iframe').css({visibility: 'visible'});
  2726. $('#etherpad').css({zIndex: 2});
  2727. });
  2728. }
  2729. else if ($('#etherpad>iframe')) {
  2730. $('#etherpad>iframe').fadeOut(300, function () {
  2731. $('#etherpad>iframe').css({visibility: 'hidden'});
  2732. $('#etherpad').css({zIndex: 0});
  2733. document.body.style.background = 'black';
  2734. });
  2735. if (!isPresentation) {
  2736. $('#largeVideo').fadeIn(300, function () {
  2737. VideoLayout.setLargeVideoVisible(true);
  2738. });
  2739. }
  2740. }
  2741. resize();
  2742. },
  2743. isVisible: function() {
  2744. var etherpadIframe = $('#etherpad>iframe');
  2745. return etherpadIframe && etherpadIframe.is(':visible');
  2746. }
  2747. };
  2748. module.exports = Etherpad;
  2749. },{"../prezi/Prezi":15,"../util/UIUtil":30,"../videolayout/VideoLayout":32}],15:[function(require,module,exports){
  2750. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2751. var UIUtil = require("../util/UIUtil");
  2752. var VideoLayout = require("../videolayout/VideoLayout");
  2753. var messageHandler = require("../util/MessageHandler");
  2754. var PreziPlayer = require("./PreziPlayer");
  2755. var preziPlayer = null;
  2756. var Prezi = {
  2757. /**
  2758. * Reloads the current presentation.
  2759. */
  2760. reloadPresentation: function() {
  2761. var iframe = document.getElementById(preziPlayer.options.preziId);
  2762. iframe.src = iframe.src;
  2763. },
  2764. /**
  2765. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2766. * otherwise.
  2767. */
  2768. isPresentationVisible: function () {
  2769. return ($('#presentation>iframe') != null
  2770. && $('#presentation>iframe').css('opacity') == 1);
  2771. },
  2772. /**
  2773. * Opens the Prezi dialog, from which the user could choose a presentation
  2774. * to load.
  2775. */
  2776. openPreziDialog: function() {
  2777. var myprezi = APP.xmpp.getPrezi();
  2778. if (myprezi) {
  2779. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  2780. null,
  2781. "dialog.removePreziMsg",
  2782. null,
  2783. false,
  2784. "dialog.Remove",
  2785. function(e,v,m,f) {
  2786. if(v) {
  2787. APP.xmpp.removePreziFromPresence();
  2788. }
  2789. }
  2790. );
  2791. }
  2792. else if (preziPlayer != null) {
  2793. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  2794. null, "dialog.sharePreziMsg",
  2795. null,
  2796. false,
  2797. "dialog.Ok",
  2798. function(e,v,m,f) {
  2799. $.prompt.close();
  2800. }
  2801. );
  2802. }
  2803. else {
  2804. var html = APP.translation.generateTranslatonHTML(
  2805. "dialog.sharePreziTitle");
  2806. var cancelButton = APP.translation.generateTranslatonHTML(
  2807. "dialog.Cancel");
  2808. var shareButton = APP.translation.generateTranslatonHTML(
  2809. "dialog.Share");
  2810. var backButton = APP.translation.generateTranslatonHTML(
  2811. "dialog.Back");
  2812. var buttons = [];
  2813. var buttons1 = [];
  2814. // Cancel button to both states
  2815. buttons.push({title: cancelButton, value: false});
  2816. buttons1.push({title: cancelButton, value: false});
  2817. // Share button
  2818. buttons.push({title: shareButton, value: true});
  2819. // Back button
  2820. buttons1.push({title: backButton, value: true});
  2821. var linkError = APP.translation.generateTranslatonHTML(
  2822. "dialog.preziLinkError");
  2823. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  2824. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  2825. var openPreziState = {
  2826. state0: {
  2827. html: '<h2>' + html + '</h2>' +
  2828. '<input name="preziUrl" type="text" ' +
  2829. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  2830. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  2831. '\' placeholder="' + defaultUrl + '" autofocus>',
  2832. persistent: false,
  2833. buttons: buttons,
  2834. focus: ':input:first',
  2835. defaultButton: 0,
  2836. submit: function (e, v, m, f) {
  2837. e.preventDefault();
  2838. if(v)
  2839. {
  2840. var preziUrl = f.preziUrl;
  2841. if (preziUrl)
  2842. {
  2843. var urlValue
  2844. = encodeURI(UIUtil.escapeHtml(preziUrl));
  2845. if (urlValue.indexOf('http://prezi.com/') != 0
  2846. && urlValue.indexOf('https://prezi.com/') != 0)
  2847. {
  2848. $.prompt.goToState('state1');
  2849. return false;
  2850. }
  2851. else {
  2852. var presIdTmp = urlValue.substring(
  2853. urlValue.indexOf("prezi.com/") + 10);
  2854. if (!isAlphanumeric(presIdTmp)
  2855. || presIdTmp.indexOf('/') < 2) {
  2856. $.prompt.goToState('state1');
  2857. return false;
  2858. }
  2859. else {
  2860. APP.xmpp.addToPresence("prezi", urlValue);
  2861. $.prompt.close();
  2862. }
  2863. }
  2864. }
  2865. }
  2866. else
  2867. $.prompt.close();
  2868. }
  2869. },
  2870. state1: {
  2871. html: '<h2>' + html + '</h2>' +
  2872. linkError,
  2873. persistent: false,
  2874. buttons: buttons1,
  2875. focus: ':input:first',
  2876. defaultButton: 1,
  2877. submit: function (e, v, m, f) {
  2878. e.preventDefault();
  2879. if (v === 0)
  2880. $.prompt.close();
  2881. else
  2882. $.prompt.goToState('state0');
  2883. }
  2884. }
  2885. };
  2886. messageHandler.openDialogWithStates(openPreziState);
  2887. }
  2888. }
  2889. };
  2890. /**
  2891. * A new presentation has been added.
  2892. *
  2893. * @param event the event indicating the add of a presentation
  2894. * @param jid the jid from which the presentation was added
  2895. * @param presUrl url of the presentation
  2896. * @param currentSlide the current slide to which we should move
  2897. */
  2898. function presentationAdded(event, jid, presUrl, currentSlide) {
  2899. console.log("presentation added", presUrl);
  2900. var presId = getPresentationId(presUrl);
  2901. var elementId = 'participant_'
  2902. + Strophe.getResourceFromJid(jid)
  2903. + '_' + presId;
  2904. // We explicitly don't specify the peer jid here, because we don't want
  2905. // this video to be dealt with as a peer related one (for example we
  2906. // don't want to show a mute/kick menu for this one, etc.).
  2907. VideoLayout.addRemoteVideoContainer(null, elementId);
  2908. VideoLayout.resizeThumbnails();
  2909. var controlsEnabled = false;
  2910. if (jid === APP.xmpp.myJid())
  2911. controlsEnabled = true;
  2912. setPresentationVisible(true);
  2913. $('#largeVideoContainer').hover(
  2914. function (event) {
  2915. if (Prezi.isPresentationVisible()) {
  2916. var reloadButtonRight = window.innerWidth
  2917. - $('#presentation>iframe').offset().left
  2918. - $('#presentation>iframe').width();
  2919. $('#reloadPresentation').css({ right: reloadButtonRight,
  2920. display:'inline-block'});
  2921. }
  2922. },
  2923. function (event) {
  2924. if (!Prezi.isPresentationVisible())
  2925. $('#reloadPresentation').css({display:'none'});
  2926. else {
  2927. var e = event.toElement || event.relatedTarget;
  2928. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  2929. $('#reloadPresentation').css({display:'none'});
  2930. }
  2931. });
  2932. preziPlayer = new PreziPlayer(
  2933. 'presentation',
  2934. {preziId: presId,
  2935. width: getPresentationWidth(),
  2936. height: getPresentationHeihgt(),
  2937. controls: controlsEnabled,
  2938. debug: true
  2939. });
  2940. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  2941. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  2942. console.log("prezi status", event.value);
  2943. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  2944. if (jid != APP.xmpp.myJid())
  2945. preziPlayer.flyToStep(currentSlide);
  2946. }
  2947. });
  2948. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  2949. console.log("event value", event.value);
  2950. APP.xmpp.addToPresence("preziSlide", event.value);
  2951. });
  2952. $("#" + elementId).css( 'background-image',
  2953. 'url(../images/avatarprezi.png)');
  2954. $("#" + elementId).click(
  2955. function () {
  2956. setPresentationVisible(true);
  2957. }
  2958. );
  2959. };
  2960. /**
  2961. * A presentation has been removed.
  2962. *
  2963. * @param event the event indicating the remove of a presentation
  2964. * @param jid the jid for which the presentation was removed
  2965. * @param the url of the presentation
  2966. */
  2967. function presentationRemoved(event, jid, presUrl) {
  2968. console.log('presentation removed', presUrl);
  2969. var presId = getPresentationId(presUrl);
  2970. setPresentationVisible(false);
  2971. $('#participant_'
  2972. + Strophe.getResourceFromJid(jid)
  2973. + '_' + presId).remove();
  2974. $('#presentation>iframe').remove();
  2975. if (preziPlayer != null) {
  2976. preziPlayer.destroy();
  2977. preziPlayer = null;
  2978. }
  2979. };
  2980. /**
  2981. * Indicates if the given string is an alphanumeric string.
  2982. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  2983. * purpose of checking URIs.
  2984. */
  2985. function isAlphanumeric(unsafeText) {
  2986. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  2987. return regex.test(unsafeText);
  2988. }
  2989. /**
  2990. * Returns the presentation id from the given url.
  2991. */
  2992. function getPresentationId (presUrl) {
  2993. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  2994. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  2995. }
  2996. /**
  2997. * Returns the presentation width.
  2998. */
  2999. function getPresentationWidth() {
  3000. var availableWidth = UIUtil.getAvailableVideoWidth();
  3001. var availableHeight = getPresentationHeihgt();
  3002. var aspectRatio = 16.0 / 9.0;
  3003. if (availableHeight < availableWidth / aspectRatio) {
  3004. availableWidth = Math.floor(availableHeight * aspectRatio);
  3005. }
  3006. return availableWidth;
  3007. }
  3008. /**
  3009. * Returns the presentation height.
  3010. */
  3011. function getPresentationHeihgt() {
  3012. var remoteVideos = $('#remoteVideos');
  3013. return window.innerHeight - remoteVideos.outerHeight();
  3014. }
  3015. /**
  3016. * Resizes the presentation iframe.
  3017. */
  3018. function resize() {
  3019. if ($('#presentation>iframe')) {
  3020. $('#presentation>iframe').width(getPresentationWidth());
  3021. $('#presentation>iframe').height(getPresentationHeihgt());
  3022. }
  3023. }
  3024. /**
  3025. * Shows/hides a presentation.
  3026. */
  3027. function setPresentationVisible(visible) {
  3028. var prezi = $('#presentation>iframe');
  3029. if (visible) {
  3030. // Trigger the video.selected event to indicate a change in the
  3031. // large video.
  3032. $(document).trigger("video.selected", [true]);
  3033. $('#largeVideo').fadeOut(300);
  3034. prezi.fadeIn(300, function() {
  3035. prezi.css({opacity:'1'});
  3036. ToolbarToggler.dockToolbar(true);
  3037. VideoLayout.setLargeVideoVisible(false);
  3038. });
  3039. $('#activeSpeaker').css('visibility', 'hidden');
  3040. }
  3041. else {
  3042. if (prezi.css('opacity') == '1') {
  3043. prezi.fadeOut(300, function () {
  3044. prezi.css({opacity:'0'});
  3045. $('#reloadPresentation').css({display:'none'});
  3046. $('#largeVideo').fadeIn(300, function() {
  3047. VideoLayout.setLargeVideoVisible(true);
  3048. ToolbarToggler.dockToolbar(false);
  3049. });
  3050. });
  3051. }
  3052. }
  3053. }
  3054. /**
  3055. * Presentation has been removed.
  3056. */
  3057. $(document).bind('presentationremoved.muc', presentationRemoved);
  3058. /**
  3059. * Presentation has been added.
  3060. */
  3061. $(document).bind('presentationadded.muc', presentationAdded);
  3062. /*
  3063. * Indicates presentation slide change.
  3064. */
  3065. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  3066. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  3067. preziPlayer.flyToStep(current);
  3068. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  3069. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  3070. preziPlayer.flyToStep(current, i);
  3071. }
  3072. }
  3073. });
  3074. /**
  3075. * On video selected event.
  3076. */
  3077. $(document).bind('video.selected', function (event, isPresentation) {
  3078. if (!isPresentation && $('#presentation>iframe')) {
  3079. setPresentationVisible(false);
  3080. }
  3081. });
  3082. $(window).resize(function () {
  3083. resize();
  3084. });
  3085. module.exports = Prezi;
  3086. },{"../toolbars/ToolbarToggler":26,"../util/MessageHandler":28,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./PreziPlayer":16}],16:[function(require,module,exports){
  3087. (function() {
  3088. "use strict";
  3089. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  3090. window.PreziPlayer = (function() {
  3091. PreziPlayer.API_VERSION = 1;
  3092. PreziPlayer.CURRENT_STEP = 'currentStep';
  3093. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  3094. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  3095. PreziPlayer.STATUS_LOADING = 'loading';
  3096. PreziPlayer.STATUS_READY = 'ready';
  3097. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  3098. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  3099. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  3100. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  3101. PreziPlayer.EVENT_STATUS = "statusChange";
  3102. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  3103. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  3104. PreziPlayer.domain = "https://prezi.com";
  3105. PreziPlayer.path = "/player/";
  3106. PreziPlayer.players = {};
  3107. PreziPlayer.binded_methods = ['changesHandler'];
  3108. PreziPlayer.createMultiplePlayers = function(optionArray){
  3109. for(var i=0; i<optionArray.length; i++) {
  3110. var optionSet = optionArray[i];
  3111. new PreziPlayer(optionSet.id, optionSet);
  3112. };
  3113. };
  3114. PreziPlayer.messageReceived = function(event){
  3115. var message, item, player;
  3116. try {
  3117. message = JSON.parse(event.data);
  3118. if (message.id && (player = PreziPlayer.players[message.id])) {
  3119. if (player.options.debug === true) {
  3120. if (console && console.log)
  3121. console.log('received', message);
  3122. }
  3123. if (message.type === "changes") {
  3124. player.changesHandler(message);
  3125. }
  3126. for (var i = 0; i < player.callbacks.length; i++) {
  3127. item = player.callbacks[i];
  3128. if (item && message.type === item.event) {
  3129. item.callback(message);
  3130. }
  3131. }
  3132. }
  3133. } catch (e) { }
  3134. };
  3135. function PreziPlayer(id, options) {
  3136. var params, paramString = "", _this = this;
  3137. if (PreziPlayer.players[id]){
  3138. PreziPlayer.players[id].destroy();
  3139. }
  3140. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  3141. var method_name = PreziPlayer.binded_methods[i];
  3142. _this[method_name] = __bind(_this[method_name], _this);
  3143. };
  3144. options = options || {};
  3145. this.options = options;
  3146. this.values = {'status': PreziPlayer.STATUS_LOADING};
  3147. this.values[PreziPlayer.CURRENT_STEP] = 0;
  3148. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  3149. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  3150. this.callbacks = [];
  3151. this.id = id;
  3152. this.embedTo = document.getElementById(id);
  3153. if (!this.embedTo) {
  3154. throw "The element id is not available.";
  3155. }
  3156. this.iframe = document.createElement('iframe');
  3157. params = [
  3158. { name: 'oid', value: options.preziId },
  3159. { name: 'explorable', value: options.explorable ? 1 : 0 },
  3160. { name: 'controls', value: options.controls ? 1 : 0 }
  3161. ];
  3162. for(var i=0; i<params.length; i++) {
  3163. var param = params[i];
  3164. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  3165. };
  3166. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  3167. this.iframe.frameBorder = 0;
  3168. this.iframe.scrolling = "no";
  3169. this.iframe.width = options.width || 640;
  3170. this.iframe.height = options.height || 480;
  3171. this.embedTo.innerHTML = '';
  3172. // JITSI: IN CASE SOMETHING GOES WRONG.
  3173. try {
  3174. this.embedTo.appendChild(this.iframe);
  3175. }
  3176. catch (err) {
  3177. console.log("CATCH ERROR");
  3178. }
  3179. // JITSI: Increase interval from 200 to 500, which fixes prezi
  3180. // crashes for us.
  3181. this.initPollInterval = setInterval(function(){
  3182. _this.sendMessage({'action': 'init'});
  3183. }, 500);
  3184. PreziPlayer.players[id] = this;
  3185. }
  3186. PreziPlayer.prototype.changesHandler = function(message) {
  3187. var key, value, j, item;
  3188. if (this.initPollInterval) {
  3189. clearInterval(this.initPollInterval);
  3190. this.initPollInterval = false;
  3191. }
  3192. for (key in message.data) {
  3193. if (message.data.hasOwnProperty(key)){
  3194. value = message.data[key];
  3195. this.values[key] = value;
  3196. for (j=0; j<this.callbacks.length; j++) {
  3197. item = this.callbacks[j];
  3198. if (item && item.event === key + "Change"){
  3199. item.callback({type: item.event, value: value});
  3200. }
  3201. }
  3202. }
  3203. }
  3204. };
  3205. PreziPlayer.prototype.destroy = function() {
  3206. if (this.initPollInterval) {
  3207. clearInterval(this.initPollInterval);
  3208. this.initPollInterval = false;
  3209. }
  3210. this.embedTo.innerHTML = '';
  3211. };
  3212. PreziPlayer.prototype.sendMessage = function(message) {
  3213. if (this.options.debug === true) {
  3214. if (console && console.log) console.log('sent', message);
  3215. }
  3216. message.version = PreziPlayer.API_VERSION;
  3217. message.id = this.id;
  3218. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  3219. };
  3220. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  3221. PreziPlayer.prototype.flyToNextStep = function() {
  3222. return this.sendMessage({
  3223. 'action': 'present',
  3224. 'data': ['moveToNextStep']
  3225. });
  3226. };
  3227. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  3228. PreziPlayer.prototype.flyToPreviousStep = function() {
  3229. return this.sendMessage({
  3230. 'action': 'present',
  3231. 'data': ['moveToPrevStep']
  3232. });
  3233. };
  3234. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  3235. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  3236. var obj = this;
  3237. // check animation_step
  3238. if (animation_step > 0 &&
  3239. obj.values.animationCountOnSteps &&
  3240. obj.values.animationCountOnSteps[step] <= animation_step) {
  3241. animation_step = obj.values.animationCountOnSteps[step];
  3242. }
  3243. // jump to animation steps by calling flyToNextStep()
  3244. function doAnimationSteps() {
  3245. if (obj.values.isMoving == true) {
  3246. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  3247. return;
  3248. }
  3249. while (animation_step-- > 0) {
  3250. obj.flyToNextStep(); // do the animation steps
  3251. }
  3252. }
  3253. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  3254. // jump to the step
  3255. return this.sendMessage({
  3256. 'action': 'present',
  3257. 'data': ['moveToStep', step]
  3258. });
  3259. };
  3260. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  3261. PreziPlayer.prototype.flyToObject = function(objectId) {
  3262. return this.sendMessage({
  3263. 'action': 'present',
  3264. 'data': ['moveToObject', objectId]
  3265. });
  3266. };
  3267. PreziPlayer.prototype.play = function(defaultDelay) {
  3268. return this.sendMessage({
  3269. 'action': 'present',
  3270. 'data': ['startAutoPlay', defaultDelay]
  3271. });
  3272. };
  3273. PreziPlayer.prototype.stop = function() {
  3274. return this.sendMessage({
  3275. 'action': 'present',
  3276. 'data': ['stopAutoPlay']
  3277. });
  3278. };
  3279. PreziPlayer.prototype.pause = function(defaultDelay) {
  3280. return this.sendMessage({
  3281. 'action': 'present',
  3282. 'data': ['pauseAutoPlay', defaultDelay]
  3283. });
  3284. };
  3285. PreziPlayer.prototype.getCurrentStep = function() {
  3286. return this.values.currentStep;
  3287. };
  3288. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  3289. return this.values.currentAnimationStep;
  3290. };
  3291. PreziPlayer.prototype.getCurrentObject = function() {
  3292. return this.values.currentObject;
  3293. };
  3294. PreziPlayer.prototype.getStatus = function() {
  3295. return this.values.status;
  3296. };
  3297. PreziPlayer.prototype.isPlaying = function() {
  3298. return this.values.isAutoPlaying;
  3299. };
  3300. PreziPlayer.prototype.getStepCount = function() {
  3301. return this.values.stepCount;
  3302. };
  3303. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  3304. return this.values.animationCountOnSteps;
  3305. };
  3306. PreziPlayer.prototype.getTitle = function() {
  3307. return this.values.title;
  3308. };
  3309. PreziPlayer.prototype.setDimensions = function(dims) {
  3310. for (var parameter in dims) {
  3311. this.iframe[parameter] = dims[parameter];
  3312. }
  3313. }
  3314. PreziPlayer.prototype.getDimensions = function() {
  3315. return {
  3316. width: parseInt(this.iframe.width, 10),
  3317. height: parseInt(this.iframe.height, 10)
  3318. }
  3319. }
  3320. PreziPlayer.prototype.on = function(event, callback) {
  3321. this.callbacks.push({
  3322. event: event,
  3323. callback: callback
  3324. });
  3325. };
  3326. PreziPlayer.prototype.off = function(event, callback) {
  3327. var j, item;
  3328. if (event === undefined) {
  3329. this.callbacks = [];
  3330. }
  3331. j = this.callbacks.length;
  3332. while (j--) {
  3333. item = this.callbacks[j];
  3334. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3335. this.callbacks.splice(j, 1);
  3336. }
  3337. }
  3338. };
  3339. if (window.addEventListener) {
  3340. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3341. } else {
  3342. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3343. }
  3344. return PreziPlayer;
  3345. })();
  3346. })();
  3347. module.exports = PreziPlayer;
  3348. },{}],17:[function(require,module,exports){
  3349. var Chat = require("./chat/Chat");
  3350. var ContactList = require("./contactlist/ContactList");
  3351. var Settings = require("./../../settings/Settings");
  3352. var SettingsMenu = require("./settings/SettingsMenu");
  3353. var VideoLayout = require("../videolayout/VideoLayout");
  3354. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3355. var UIUtil = require("../util/UIUtil");
  3356. /**
  3357. * Toggler for the chat, contact list, settings menu, etc..
  3358. */
  3359. var PanelToggler = (function(my) {
  3360. var currentlyOpen = null;
  3361. var buttons = {
  3362. '#chatspace': '#chatBottomButton',
  3363. '#contactlist': '#contactListButton',
  3364. '#settingsmenu': '#settingsButton'
  3365. };
  3366. /**
  3367. * Resizes the video area
  3368. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3369. * @param completeFunction a function to be called when the video space is resized
  3370. */
  3371. var resizeVideoArea = function(isClosing, completeFunction) {
  3372. var videospace = $('#videospace');
  3373. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3374. var videospaceWidth = window.innerWidth - panelSize[0];
  3375. var videospaceHeight = window.innerHeight;
  3376. var videoSize
  3377. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3378. var videoWidth = videoSize[0];
  3379. var videoHeight = videoSize[1];
  3380. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3381. videoHeight,
  3382. videospaceWidth,
  3383. videospaceHeight);
  3384. var horizontalIndent = videoPosition[0];
  3385. var verticalIndent = videoPosition[1];
  3386. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3387. var thumbnailsWidth = thumbnailSize[0];
  3388. var thumbnailsHeight = thumbnailSize[1];
  3389. //for chat
  3390. videospace.animate({
  3391. right: panelSize[0],
  3392. width: videospaceWidth,
  3393. height: videospaceHeight
  3394. },
  3395. {
  3396. queue: false,
  3397. duration: 500,
  3398. complete: completeFunction
  3399. });
  3400. $('#remoteVideos').animate({
  3401. height: thumbnailsHeight
  3402. },
  3403. {
  3404. queue: false,
  3405. duration: 500
  3406. });
  3407. $('#remoteVideos>span').animate({
  3408. height: thumbnailsHeight,
  3409. width: thumbnailsWidth
  3410. },
  3411. {
  3412. queue: false,
  3413. duration: 500,
  3414. complete: function () {
  3415. $(document).trigger(
  3416. "remotevideo.resized",
  3417. [thumbnailsWidth,
  3418. thumbnailsHeight]);
  3419. }
  3420. });
  3421. $('#largeVideoContainer').animate({
  3422. width: videospaceWidth,
  3423. height: videospaceHeight
  3424. },
  3425. {
  3426. queue: false,
  3427. duration: 500
  3428. });
  3429. $('#largeVideo').animate({
  3430. width: videoWidth,
  3431. height: videoHeight,
  3432. top: verticalIndent,
  3433. bottom: verticalIndent,
  3434. left: horizontalIndent,
  3435. right: horizontalIndent
  3436. },
  3437. {
  3438. queue: false,
  3439. duration: 500
  3440. });
  3441. };
  3442. /**
  3443. * Toggles the windows in the side panel
  3444. * @param object the window that should be shown
  3445. * @param selector the selector for the element containing the panel
  3446. * @param onOpenComplete function to be called when the panel is opened
  3447. * @param onOpen function to be called if the window is going to be opened
  3448. * @param onClose function to be called if the window is going to be closed
  3449. */
  3450. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3451. UIUtil.buttonClick(buttons[selector], "active");
  3452. if (object.isVisible()) {
  3453. $("#toast-container").animate({
  3454. right: '5px'
  3455. },
  3456. {
  3457. queue: false,
  3458. duration: 500
  3459. });
  3460. $(selector).hide("slide", {
  3461. direction: "right",
  3462. queue: false,
  3463. duration: 500
  3464. });
  3465. if(typeof onClose === "function") {
  3466. onClose();
  3467. }
  3468. currentlyOpen = null;
  3469. }
  3470. else {
  3471. // Undock the toolbar when the chat is shown and if we're in a
  3472. // video mode.
  3473. if (VideoLayout.isLargeVideoVisible()) {
  3474. ToolbarToggler.dockToolbar(false);
  3475. }
  3476. if(currentlyOpen) {
  3477. var current = $(currentlyOpen);
  3478. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3479. current.css('z-index', 4);
  3480. setTimeout(function () {
  3481. current.css('display', 'none');
  3482. current.css('z-index', 5);
  3483. }, 500);
  3484. }
  3485. $("#toast-container").animate({
  3486. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3487. },
  3488. {
  3489. queue: false,
  3490. duration: 500
  3491. });
  3492. $(selector).show("slide", {
  3493. direction: "right",
  3494. queue: false,
  3495. duration: 500,
  3496. complete: onOpenComplete
  3497. });
  3498. if(typeof onOpen === "function") {
  3499. onOpen();
  3500. }
  3501. currentlyOpen = selector;
  3502. }
  3503. };
  3504. /**
  3505. * Opens / closes the chat area.
  3506. */
  3507. my.toggleChat = function() {
  3508. var chatCompleteFunction = Chat.isVisible() ?
  3509. function() {} : function () {
  3510. Chat.scrollChatToBottom();
  3511. $('#chatspace').trigger('shown');
  3512. };
  3513. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3514. toggle(Chat,
  3515. '#chatspace',
  3516. function () {
  3517. // Request the focus in the nickname field or the chat input field.
  3518. if ($('#nickname').css('visibility') === 'visible') {
  3519. $('#nickinput').focus();
  3520. } else {
  3521. $('#usermsg').focus();
  3522. }
  3523. },
  3524. null,
  3525. Chat.resizeChat,
  3526. null);
  3527. };
  3528. /**
  3529. * Opens / closes the contact list area.
  3530. */
  3531. my.toggleContactList = function () {
  3532. var completeFunction = ContactList.isVisible() ?
  3533. function() {} : function () { $('#contactlist').trigger('shown');};
  3534. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3535. toggle(ContactList,
  3536. '#contactlist',
  3537. null,
  3538. function() {
  3539. ContactList.setVisualNotification(false);
  3540. },
  3541. null);
  3542. };
  3543. /**
  3544. * Opens / closes the settings menu
  3545. */
  3546. my.toggleSettingsMenu = function() {
  3547. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3548. toggle(SettingsMenu,
  3549. '#settingsmenu',
  3550. null,
  3551. function() {
  3552. var settings = Settings.getSettings();
  3553. $('#setDisplayName').get(0).value = settings.displayName;
  3554. $('#setEmail').get(0).value = settings.email;
  3555. },
  3556. null);
  3557. };
  3558. /**
  3559. * Returns the size of the side panel.
  3560. */
  3561. my.getPanelSize = function () {
  3562. var availableHeight = window.innerHeight;
  3563. var availableWidth = window.innerWidth;
  3564. var panelWidth = 200;
  3565. if (availableWidth * 0.2 < 200) {
  3566. panelWidth = availableWidth * 0.2;
  3567. }
  3568. return [panelWidth, availableHeight];
  3569. };
  3570. my.isVisible = function() {
  3571. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3572. };
  3573. return my;
  3574. }(PanelToggler || {}));
  3575. module.exports = PanelToggler;
  3576. },{"../toolbars/ToolbarToggler":26,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./../../settings/Settings":38,"./chat/Chat":18,"./contactlist/ContactList":22,"./settings/SettingsMenu":23}],18:[function(require,module,exports){
  3577. /* global $, Util, nickname:true */
  3578. var Replacement = require("./Replacement");
  3579. var CommandsProcessor = require("./Commands");
  3580. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3581. var smileys = require("./smileys.json").smileys;
  3582. var NicknameHandler = require("../../util/NicknameHandler");
  3583. var UIUtil = require("../../util/UIUtil");
  3584. var UIEvents = require("../../../../service/UI/UIEvents");
  3585. var notificationInterval = false;
  3586. var unreadMessages = 0;
  3587. /**
  3588. * Shows/hides a visual notification, indicating that a message has arrived.
  3589. */
  3590. function setVisualNotification(show) {
  3591. var unreadMsgElement = document.getElementById('unreadMessages');
  3592. var unreadMsgBottomElement
  3593. = document.getElementById('bottomUnreadMessages');
  3594. var glower = $('#chatButton');
  3595. var bottomGlower = $('#chatBottomButton');
  3596. if (unreadMessages) {
  3597. unreadMsgElement.innerHTML = unreadMessages.toString();
  3598. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3599. ToolbarToggler.dockToolbar(true);
  3600. var chatButtonElement
  3601. = document.getElementById('chatButton').parentNode;
  3602. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3603. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3604. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3605. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3606. unreadMsgElement.setAttribute(
  3607. 'style',
  3608. 'top:' + topIndent +
  3609. '; left:' + leftIndent + ';');
  3610. var chatBottomButtonElement
  3611. = document.getElementById('chatBottomButton').parentNode;
  3612. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3613. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3614. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3615. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3616. unreadMsgBottomElement.setAttribute(
  3617. 'style',
  3618. 'top:' + bottomTopIndent +
  3619. '; left:' + bottomLeftIndent + ';');
  3620. if (!glower.hasClass('icon-chat-simple')) {
  3621. glower.removeClass('icon-chat');
  3622. glower.addClass('icon-chat-simple');
  3623. }
  3624. }
  3625. else {
  3626. unreadMsgElement.innerHTML = '';
  3627. unreadMsgBottomElement.innerHTML = '';
  3628. glower.removeClass('icon-chat-simple');
  3629. glower.addClass('icon-chat');
  3630. }
  3631. if (show && !notificationInterval) {
  3632. notificationInterval = window.setInterval(function () {
  3633. glower.toggleClass('active');
  3634. bottomGlower.toggleClass('active glowing');
  3635. }, 800);
  3636. }
  3637. else if (!show && notificationInterval) {
  3638. window.clearInterval(notificationInterval);
  3639. notificationInterval = false;
  3640. glower.removeClass('active');
  3641. bottomGlower.removeClass('glowing');
  3642. bottomGlower.addClass('active');
  3643. }
  3644. }
  3645. /**
  3646. * Returns the current time in the format it is shown to the user
  3647. * @returns {string}
  3648. */
  3649. function getCurrentTime() {
  3650. var now = new Date();
  3651. var hour = now.getHours();
  3652. var minute = now.getMinutes();
  3653. var second = now.getSeconds();
  3654. if(hour.toString().length === 1) {
  3655. hour = '0'+hour;
  3656. }
  3657. if(minute.toString().length === 1) {
  3658. minute = '0'+minute;
  3659. }
  3660. if(second.toString().length === 1) {
  3661. second = '0'+second;
  3662. }
  3663. return hour+':'+minute+':'+second;
  3664. }
  3665. function toggleSmileys()
  3666. {
  3667. var smileys = $('#smileysContainer');
  3668. if(!smileys.is(':visible')) {
  3669. smileys.show("slide", { direction: "down", duration: 300});
  3670. } else {
  3671. smileys.hide("slide", { direction: "down", duration: 300});
  3672. }
  3673. $('#usermsg').focus();
  3674. }
  3675. function addClickFunction(smiley, number) {
  3676. smiley.onclick = function addSmileyToMessage() {
  3677. var usermsg = $('#usermsg');
  3678. var message = usermsg.val();
  3679. message += smileys['smiley' + number];
  3680. usermsg.val(message);
  3681. usermsg.get(0).setSelectionRange(message.length, message.length);
  3682. toggleSmileys();
  3683. usermsg.focus();
  3684. };
  3685. }
  3686. /**
  3687. * Adds the smileys container to the chat
  3688. */
  3689. function addSmileys() {
  3690. var smileysContainer = document.createElement('div');
  3691. smileysContainer.id = 'smileysContainer';
  3692. for(var i = 1; i <= 21; i++) {
  3693. var smileyContainer = document.createElement('div');
  3694. smileyContainer.id = 'smiley' + i;
  3695. smileyContainer.className = 'smileyContainer';
  3696. var smiley = document.createElement('img');
  3697. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3698. smiley.className = 'smiley';
  3699. addClickFunction(smiley, i);
  3700. smileyContainer.appendChild(smiley);
  3701. smileysContainer.appendChild(smileyContainer);
  3702. }
  3703. $("#chatspace").append(smileysContainer);
  3704. }
  3705. /**
  3706. * Resizes the chat conversation.
  3707. */
  3708. function resizeChatConversation() {
  3709. var msgareaHeight = $('#usermsg').outerHeight();
  3710. var chatspace = $('#chatspace');
  3711. var width = chatspace.width();
  3712. var chat = $('#chatconversation');
  3713. var smileys = $('#smileysarea');
  3714. smileys.height(msgareaHeight);
  3715. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3716. $('#smileysContainer').css('bottom', msgareaHeight);
  3717. chat.width(width - 10);
  3718. chat.height(window.innerHeight - 15 - msgareaHeight);
  3719. }
  3720. /**
  3721. * Chat related user interface.
  3722. */
  3723. var Chat = (function (my) {
  3724. /**
  3725. * Initializes chat related interface.
  3726. */
  3727. my.init = function () {
  3728. if(NicknameHandler.getNickname())
  3729. Chat.setChatConversationMode(true);
  3730. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3731. function (nickname) {
  3732. Chat.setChatConversationMode(true);
  3733. });
  3734. $('#nickinput').keydown(function (event) {
  3735. if (event.keyCode === 13) {
  3736. event.preventDefault();
  3737. var val = UIUtil.escapeHtml(this.value);
  3738. this.value = '';
  3739. if (!NicknameHandler.getNickname()) {
  3740. NicknameHandler.setNickname(val);
  3741. return;
  3742. }
  3743. }
  3744. });
  3745. $('#usermsg').keydown(function (event) {
  3746. if (event.keyCode === 13) {
  3747. event.preventDefault();
  3748. var value = this.value;
  3749. $('#usermsg').val('').trigger('autosize.resize');
  3750. this.focus();
  3751. var command = new CommandsProcessor(value);
  3752. if(command.isCommand())
  3753. {
  3754. command.processCommand();
  3755. }
  3756. else
  3757. {
  3758. var message = UIUtil.escapeHtml(value);
  3759. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3760. }
  3761. }
  3762. });
  3763. var onTextAreaResize = function () {
  3764. resizeChatConversation();
  3765. Chat.scrollChatToBottom();
  3766. };
  3767. $('#usermsg').autosize({callback: onTextAreaResize});
  3768. $("#chatspace").bind("shown",
  3769. function () {
  3770. unreadMessages = 0;
  3771. setVisualNotification(false);
  3772. });
  3773. addSmileys();
  3774. };
  3775. /**
  3776. * Appends the given message to the chat conversation.
  3777. */
  3778. my.updateChatConversation = function (from, displayName, message) {
  3779. var divClassName = '';
  3780. if (APP.xmpp.myJid() === from) {
  3781. divClassName = "localuser";
  3782. }
  3783. else {
  3784. divClassName = "remoteuser";
  3785. if (!Chat.isVisible()) {
  3786. unreadMessages++;
  3787. UIUtil.playSoundNotification('chatNotification');
  3788. setVisualNotification(true);
  3789. }
  3790. }
  3791. // replace links and smileys
  3792. // Strophe already escapes special symbols on sending,
  3793. // so we escape here only tags to avoid double &amp;
  3794. var escMessage = message.replace(/</g, '&lt;').
  3795. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  3796. var escDisplayName = UIUtil.escapeHtml(displayName);
  3797. message = Replacement.processReplacements(escMessage);
  3798. var messageContainer =
  3799. '<div class="chatmessage">'+
  3800. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  3801. '<div class="username ' + divClassName +'">' + escDisplayName +
  3802. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  3803. '</div>' + '<div class="usermessage">' + message + '</div>' +
  3804. '</div>';
  3805. $('#chatconversation').append(messageContainer);
  3806. $('#chatconversation').animate(
  3807. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3808. };
  3809. /**
  3810. * Appends error message to the conversation
  3811. * @param errorMessage the received error message.
  3812. * @param originalText the original message.
  3813. */
  3814. my.chatAddError = function(errorMessage, originalText)
  3815. {
  3816. errorMessage = UIUtil.escapeHtml(errorMessage);
  3817. originalText = UIUtil.escapeHtml(originalText);
  3818. $('#chatconversation').append(
  3819. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  3820. (originalText? (' \"'+ originalText + '\"') : "") +
  3821. ' was not sent.' +
  3822. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  3823. $('#chatconversation').animate(
  3824. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3825. };
  3826. /**
  3827. * Sets the subject to the UI
  3828. * @param subject the subject
  3829. */
  3830. my.chatSetSubject = function(subject)
  3831. {
  3832. if(subject)
  3833. subject = subject.trim();
  3834. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  3835. if(subject === "")
  3836. {
  3837. $("#subject").css({display: "none"});
  3838. }
  3839. else
  3840. {
  3841. $("#subject").css({display: "block"});
  3842. }
  3843. };
  3844. /**
  3845. * Sets the chat conversation mode.
  3846. */
  3847. my.setChatConversationMode = function (isConversationMode) {
  3848. if (isConversationMode) {
  3849. $('#nickname').css({visibility: 'hidden'});
  3850. $('#chatconversation').css({visibility: 'visible'});
  3851. $('#usermsg').css({visibility: 'visible'});
  3852. $('#smileysarea').css({visibility: 'visible'});
  3853. $('#usermsg').focus();
  3854. }
  3855. };
  3856. /**
  3857. * Resizes the chat area.
  3858. */
  3859. my.resizeChat = function () {
  3860. var chatSize = require("../SidePanelToggler").getPanelSize();
  3861. $('#chatspace').width(chatSize[0]);
  3862. $('#chatspace').height(chatSize[1]);
  3863. resizeChatConversation();
  3864. };
  3865. /**
  3866. * Indicates if the chat is currently visible.
  3867. */
  3868. my.isVisible = function () {
  3869. return $('#chatspace').is(":visible");
  3870. };
  3871. /**
  3872. * Shows and hides the window with the smileys
  3873. */
  3874. my.toggleSmileys = toggleSmileys;
  3875. /**
  3876. * Scrolls chat to the bottom.
  3877. */
  3878. my.scrollChatToBottom = function() {
  3879. setTimeout(function () {
  3880. $('#chatconversation').scrollTop(
  3881. $('#chatconversation')[0].scrollHeight);
  3882. }, 5);
  3883. };
  3884. return my;
  3885. }(Chat || {}));
  3886. module.exports = Chat;
  3887. },{"../../../../service/UI/UIEvents":92,"../../toolbars/ToolbarToggler":26,"../../util/NicknameHandler":29,"../../util/UIUtil":30,"../SidePanelToggler":17,"./Commands":19,"./Replacement":20,"./smileys.json":21}],19:[function(require,module,exports){
  3888. var UIUtil = require("../../util/UIUtil");
  3889. /**
  3890. * List with supported commands. The keys are the names of the commands and
  3891. * the value is the function that processes the message.
  3892. * @type {{String: function}}
  3893. */
  3894. var commands = {
  3895. "topic" : processTopic
  3896. };
  3897. /**
  3898. * Extracts the command from the message.
  3899. * @param message the received message
  3900. * @returns {string} the command
  3901. */
  3902. function getCommand(message)
  3903. {
  3904. if(message)
  3905. {
  3906. for(var command in commands)
  3907. {
  3908. if(message.indexOf("/" + command) == 0)
  3909. return command;
  3910. }
  3911. }
  3912. return "";
  3913. };
  3914. /**
  3915. * Processes the data for topic command.
  3916. * @param commandArguments the arguments of the topic command.
  3917. */
  3918. function processTopic(commandArguments)
  3919. {
  3920. var topic = UIUtil.escapeHtml(commandArguments);
  3921. APP.xmpp.setSubject(topic);
  3922. }
  3923. /**
  3924. * Constructs new CommandProccessor instance from a message that
  3925. * handles commands received via chat messages.
  3926. * @param message the message
  3927. * @constructor
  3928. */
  3929. function CommandsProcessor(message)
  3930. {
  3931. var command = getCommand(message);
  3932. /**
  3933. * Returns the name of the command.
  3934. * @returns {String} the command
  3935. */
  3936. this.getCommand = function()
  3937. {
  3938. return command;
  3939. };
  3940. var messageArgument = message.substr(command.length + 2);
  3941. /**
  3942. * Returns the arguments of the command.
  3943. * @returns {string}
  3944. */
  3945. this.getArgument = function()
  3946. {
  3947. return messageArgument;
  3948. };
  3949. }
  3950. /**
  3951. * Checks whether this instance is valid command or not.
  3952. * @returns {boolean}
  3953. */
  3954. CommandsProcessor.prototype.isCommand = function()
  3955. {
  3956. if(this.getCommand())
  3957. return true;
  3958. return false;
  3959. };
  3960. /**
  3961. * Processes the command.
  3962. */
  3963. CommandsProcessor.prototype.processCommand = function()
  3964. {
  3965. if(!this.isCommand())
  3966. return;
  3967. commands[this.getCommand()](this.getArgument());
  3968. };
  3969. module.exports = CommandsProcessor;
  3970. },{"../../util/UIUtil":30}],20:[function(require,module,exports){
  3971. var Smileys = require("./smileys.json");
  3972. /**
  3973. * Processes links and smileys in "body"
  3974. */
  3975. function processReplacements(body)
  3976. {
  3977. //make links clickable
  3978. body = linkify(body);
  3979. //add smileys
  3980. body = smilify(body);
  3981. return body;
  3982. }
  3983. /**
  3984. * Finds and replaces all links in the links in "body"
  3985. * with their <a href=""></a>
  3986. */
  3987. function linkify(inputText)
  3988. {
  3989. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  3990. //URLs starting with http://, https://, or ftp://
  3991. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  3992. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  3993. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  3994. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  3995. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  3996. //Change email addresses to mailto:: links.
  3997. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  3998. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  3999. return replacedText;
  4000. }
  4001. /**
  4002. * Replaces common smiley strings with images
  4003. */
  4004. function smilify(body)
  4005. {
  4006. if(!body) {
  4007. return body;
  4008. }
  4009. var regexs = Smileys["regexs"];
  4010. for(var smiley in regexs) {
  4011. if(regexs.hasOwnProperty(smiley)) {
  4012. body = body.replace(regexs[smiley],
  4013. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  4014. }
  4015. }
  4016. return body;
  4017. }
  4018. module.exports = {
  4019. processReplacements: processReplacements,
  4020. linkify: linkify
  4021. };
  4022. },{"./smileys.json":21}],21:[function(require,module,exports){
  4023. module.exports={
  4024. "smileys": {
  4025. "smiley1": ":)",
  4026. "smiley2": ":(",
  4027. "smiley3": ":D",
  4028. "smiley4": "(y)",
  4029. "smiley5": " :P",
  4030. "smiley6": "(wave)",
  4031. "smiley7": "(blush)",
  4032. "smiley8": "(chuckle)",
  4033. "smiley9": "(shocked)",
  4034. "smiley10": ":*",
  4035. "smiley11": "(n)",
  4036. "smiley12": "(search)",
  4037. "smiley13": " <3",
  4038. "smiley14": "(oops)",
  4039. "smiley15": "(angry)",
  4040. "smiley16": "(angel)",
  4041. "smiley17": "(sick)",
  4042. "smiley18": ";(",
  4043. "smiley19": "(bomb)",
  4044. "smiley20": "(clap)",
  4045. "smiley21": " ;)"
  4046. },
  4047. "regexs": {
  4048. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  4049. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  4050. "smiley1": /(:-\)|:\))/gi,
  4051. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  4052. "smiley5": /(:-P|:P|:-p|:p)/gi,
  4053. "smiley6": /(\(wave\))/gi,
  4054. "smiley7": /(\(blush\))/gi,
  4055. "smiley8": /(\(chuckle\))/gi,
  4056. "smiley9": /(:-0|\(shocked\))/gi,
  4057. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  4058. "smiley11": /(\(n\))/gi,
  4059. "smiley12": /(\(search\))/g,
  4060. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  4061. "smiley14": /(\(oops\))/gi,
  4062. "smiley15": /(\(angry\))/gi,
  4063. "smiley16": /(\(angel\))/gi,
  4064. "smiley17": /(\(sick\))/gi,
  4065. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  4066. "smiley19": /(\(bomb\))/gi,
  4067. "smiley20": /(\(clap\))/gi,
  4068. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  4069. }
  4070. }
  4071. },{}],22:[function(require,module,exports){
  4072. var numberOfContacts = 0;
  4073. var notificationInterval;
  4074. /**
  4075. * Updates the number of participants in the contact list button and sets
  4076. * the glow
  4077. * @param delta indicates whether a new user has joined (1) or someone has
  4078. * left(-1)
  4079. */
  4080. function updateNumberOfParticipants(delta) {
  4081. //when the user is alone we don't show the number of participants
  4082. if(numberOfContacts === 0) {
  4083. $("#numberOfParticipants").text('');
  4084. numberOfContacts += delta;
  4085. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  4086. ContactList.setVisualNotification(true);
  4087. numberOfContacts += delta;
  4088. $("#numberOfParticipants").text(numberOfContacts);
  4089. }
  4090. }
  4091. /**
  4092. * Creates the avatar element.
  4093. *
  4094. * @return the newly created avatar element
  4095. */
  4096. function createAvatar(id) {
  4097. var avatar = document.createElement('img');
  4098. avatar.className = "icon-avatar avatar";
  4099. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  4100. return avatar;
  4101. }
  4102. /**
  4103. * Creates the display name paragraph.
  4104. *
  4105. * @param displayName the display name to set
  4106. */
  4107. function createDisplayNameParagraph(key, displayName) {
  4108. var p = document.createElement('p');
  4109. if(displayName)
  4110. p.innerText = displayName;
  4111. else if(key)
  4112. {
  4113. p.setAttribute("data-i18n",key);
  4114. p.innerText = APP.translation.translateString(key);
  4115. }
  4116. return p;
  4117. }
  4118. function stopGlowing(glower) {
  4119. window.clearInterval(notificationInterval);
  4120. notificationInterval = false;
  4121. glower.removeClass('glowing');
  4122. if (!ContactList.isVisible()) {
  4123. glower.removeClass('active');
  4124. }
  4125. }
  4126. /**
  4127. * Contact list.
  4128. */
  4129. var ContactList = {
  4130. /**
  4131. * Indicates if the chat is currently visible.
  4132. *
  4133. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  4134. * otherwise
  4135. */
  4136. isVisible: function () {
  4137. return $('#contactlist').is(":visible");
  4138. },
  4139. /**
  4140. * Adds a contact for the given peerJid if such doesn't yet exist.
  4141. *
  4142. * @param peerJid the peerJid corresponding to the contact
  4143. * @param id the user's email or userId used to get the user's avatar
  4144. */
  4145. ensureAddContact: function (peerJid, id) {
  4146. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4147. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4148. if (!contact || contact.length <= 0)
  4149. ContactList.addContact(peerJid, id);
  4150. },
  4151. /**
  4152. * Adds a contact for the given peer jid.
  4153. *
  4154. * @param peerJid the jid of the contact to add
  4155. * @param id the email or userId of the user
  4156. */
  4157. addContact: function (peerJid, id) {
  4158. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4159. var contactlist = $('#contactlist>ul');
  4160. var newContact = document.createElement('li');
  4161. newContact.id = resourceJid;
  4162. newContact.className = "clickable";
  4163. newContact.onclick = function (event) {
  4164. if (event.currentTarget.className === "clickable") {
  4165. $(ContactList).trigger('contactclicked', [peerJid]);
  4166. }
  4167. };
  4168. newContact.appendChild(createAvatar(id));
  4169. newContact.appendChild(createDisplayNameParagraph("participant"));
  4170. var clElement = contactlist.get(0);
  4171. if (resourceJid === APP.xmpp.myResource()
  4172. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  4173. clElement.insertBefore(newContact,
  4174. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  4175. }
  4176. else {
  4177. clElement.appendChild(newContact);
  4178. }
  4179. updateNumberOfParticipants(1);
  4180. },
  4181. /**
  4182. * Removes a contact for the given peer jid.
  4183. *
  4184. * @param peerJid the peerJid corresponding to the contact to remove
  4185. */
  4186. removeContact: function (peerJid) {
  4187. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4188. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4189. if (contact && contact.length > 0) {
  4190. var contactlist = $('#contactlist>ul');
  4191. contactlist.get(0).removeChild(contact.get(0));
  4192. updateNumberOfParticipants(-1);
  4193. }
  4194. },
  4195. setVisualNotification: function (show, stopGlowingIn) {
  4196. var glower = $('#contactListButton');
  4197. if (show && !notificationInterval) {
  4198. notificationInterval = window.setInterval(function () {
  4199. glower.toggleClass('active glowing');
  4200. }, 800);
  4201. }
  4202. else if (!show && notificationInterval) {
  4203. stopGlowing(glower);
  4204. }
  4205. if (stopGlowingIn) {
  4206. setTimeout(function () {
  4207. stopGlowing(glower);
  4208. }, stopGlowingIn);
  4209. }
  4210. },
  4211. setClickable: function (resourceJid, isClickable) {
  4212. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4213. if (isClickable) {
  4214. contact.addClass('clickable');
  4215. } else {
  4216. contact.removeClass('clickable');
  4217. }
  4218. },
  4219. onDisplayNameChange: function (peerJid, displayName) {
  4220. if (peerJid === 'localVideoContainer')
  4221. peerJid = APP.xmpp.myJid();
  4222. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4223. var contactName = $('#contactlist #' + resourceJid + '>p');
  4224. if (contactName && displayName && displayName.length > 0)
  4225. contactName.html(displayName);
  4226. }
  4227. };
  4228. module.exports = ContactList;
  4229. },{}],23:[function(require,module,exports){
  4230. var Avatar = require("../../avatar/Avatar");
  4231. var Settings = require("./../../../settings/Settings");
  4232. var UIUtil = require("../../util/UIUtil");
  4233. var languages = require("../../../../service/translation/languages");
  4234. function generateLanguagesSelectBox()
  4235. {
  4236. var currentLang = APP.translation.getCurrentLanguage();
  4237. var html = "<select id=\"languages_selectbox\">";
  4238. var langArray = languages.getLanguages();
  4239. for(var i = 0; i < langArray.length; i++)
  4240. {
  4241. var lang = langArray[i];
  4242. html += "<option ";
  4243. if(lang === currentLang)
  4244. html += "selected ";
  4245. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  4246. html += "</option>";
  4247. }
  4248. return html + "</select>";
  4249. }
  4250. var SettingsMenu = {
  4251. init: function () {
  4252. $("#updateSettings").before(generateLanguagesSelectBox());
  4253. APP.translation.translateElement($("#languages_selectbox"));
  4254. $('#settingsmenu>input').keyup(function(event){
  4255. if(event.keyCode === 13) {//enter
  4256. SettingsMenu.update();
  4257. }
  4258. });
  4259. $("#updateSettings").click(function () {
  4260. SettingsMenu.update();
  4261. });
  4262. },
  4263. update: function() {
  4264. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  4265. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  4266. if(newDisplayName) {
  4267. var displayName = Settings.setDisplayName(newDisplayName);
  4268. APP.xmpp.addToPresence("displayName", displayName, true);
  4269. }
  4270. var language = $("#languages_selectbox").val();
  4271. APP.translation.setLanguage(language);
  4272. Settings.setLanguage(language);
  4273. APP.xmpp.addToPresence("email", newEmail);
  4274. var email = Settings.setEmail(newEmail);
  4275. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  4276. },
  4277. isVisible: function() {
  4278. return $('#settingsmenu').is(':visible');
  4279. },
  4280. setDisplayName: function(newDisplayName) {
  4281. var displayName = Settings.setDisplayName(newDisplayName);
  4282. $('#setDisplayName').get(0).value = displayName;
  4283. },
  4284. onDisplayNameChange: function(peerJid, newDisplayName) {
  4285. if(peerJid === 'localVideoContainer' ||
  4286. peerJid === APP.xmpp.myJid()) {
  4287. this.setDisplayName(newDisplayName);
  4288. }
  4289. }
  4290. };
  4291. module.exports = SettingsMenu;
  4292. },{"../../../../service/translation/languages":96,"../../avatar/Avatar":13,"../../util/UIUtil":30,"./../../../settings/Settings":38}],24:[function(require,module,exports){
  4293. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4294. var buttonHandlers = {
  4295. "bottom_toolbar_contact_list": function () {
  4296. BottomToolbar.toggleContactList();
  4297. },
  4298. "bottom_toolbar_film_strip": function () {
  4299. BottomToolbar.toggleFilmStrip();
  4300. },
  4301. "bottom_toolbar_chat": function () {
  4302. BottomToolbar.toggleChat();
  4303. }
  4304. };
  4305. var BottomToolbar = (function (my) {
  4306. my.init = function () {
  4307. for(var k in buttonHandlers)
  4308. $("#" + k).click(buttonHandlers[k]);
  4309. };
  4310. my.toggleChat = function() {
  4311. PanelToggler.toggleChat();
  4312. };
  4313. my.toggleContactList = function() {
  4314. PanelToggler.toggleContactList();
  4315. };
  4316. my.toggleFilmStrip = function() {
  4317. var filmstrip = $("#remoteVideos");
  4318. filmstrip.toggleClass("hidden");
  4319. };
  4320. $(document).bind("remotevideo.resized", function (event, width, height) {
  4321. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  4322. $('#bottomToolbar').css({bottom: bottom + 'px'});
  4323. });
  4324. return my;
  4325. }(BottomToolbar || {}));
  4326. module.exports = BottomToolbar;
  4327. },{"../side_pannels/SidePanelToggler":17}],25:[function(require,module,exports){
  4328. /* global APP,$, buttonClick, config, lockRoom,
  4329. setSharedKey, Util */
  4330. var messageHandler = require("../util/MessageHandler");
  4331. var BottomToolbar = require("./BottomToolbar");
  4332. var Prezi = require("../prezi/Prezi");
  4333. var Etherpad = require("../etherpad/Etherpad");
  4334. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4335. var Authentication = require("../authentication/Authentication");
  4336. var UIUtil = require("../util/UIUtil");
  4337. var AuthenticationEvents
  4338. = require("../../../service/authentication/AuthenticationEvents");
  4339. var roomUrl = null;
  4340. var sharedKey = '';
  4341. var UI = null;
  4342. var buttonHandlers =
  4343. {
  4344. "toolbar_button_mute": function () {
  4345. return APP.UI.toggleAudio();
  4346. },
  4347. "toolbar_button_camera": function () {
  4348. return APP.UI.toggleVideo();
  4349. },
  4350. /*"toolbar_button_authentication": function () {
  4351. return Toolbar.authenticateClicked();
  4352. },*/
  4353. "toolbar_button_record": function () {
  4354. return toggleRecording();
  4355. },
  4356. "toolbar_button_security": function () {
  4357. return Toolbar.openLockDialog();
  4358. },
  4359. "toolbar_button_link": function () {
  4360. return Toolbar.openLinkDialog();
  4361. },
  4362. "toolbar_button_chat": function () {
  4363. return BottomToolbar.toggleChat();
  4364. },
  4365. "toolbar_button_prezi": function () {
  4366. return Prezi.openPreziDialog();
  4367. },
  4368. "toolbar_button_etherpad": function () {
  4369. return Etherpad.toggleEtherpad(0);
  4370. },
  4371. "toolbar_button_desktopsharing": function () {
  4372. return APP.desktopsharing.toggleScreenSharing();
  4373. },
  4374. "toolbar_button_fullScreen": function()
  4375. {
  4376. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4377. return Toolbar.toggleFullScreen();
  4378. },
  4379. "toolbar_button_sip": function () {
  4380. return callSipButtonClicked();
  4381. },
  4382. "toolbar_button_settings": function () {
  4383. PanelToggler.toggleSettingsMenu();
  4384. },
  4385. "toolbar_button_hangup": function () {
  4386. return hangup();
  4387. },
  4388. "toolbar_button_login": function () {
  4389. Toolbar.authenticateClicked();
  4390. },
  4391. "toolbar_button_logout": function () {
  4392. // Ask for confirmation
  4393. messageHandler.openTwoButtonDialog(
  4394. "dialog.logoutTitle",
  4395. null,
  4396. "dialog.logoutQuestion",
  4397. null,
  4398. false,
  4399. "dialog.Yes",
  4400. function (evt, yes) {
  4401. if (yes) {
  4402. APP.xmpp.logout(function (url) {
  4403. if (url) {
  4404. window.location.href = url;
  4405. } else {
  4406. hangup();
  4407. }
  4408. });
  4409. }
  4410. });
  4411. }
  4412. };
  4413. function hangup() {
  4414. APP.xmpp.disposeConference();
  4415. if(config.enableWelcomePage)
  4416. {
  4417. setTimeout(function()
  4418. {
  4419. window.localStorage.welcomePageDisabled = false;
  4420. window.location.pathname = "/";
  4421. }, 10000);
  4422. }
  4423. var title = APP.translation.generateTranslatonHTML(
  4424. "dialog.sessTerminated");
  4425. var msg = APP.translation.generateTranslatonHTML(
  4426. "dialog.hungUp");
  4427. var button = APP.translation.generateTranslatonHTML(
  4428. "dialog.joinAgain");
  4429. var buttons = [];
  4430. buttons.push({title: button, value: true});
  4431. UI.messageHandler.openDialog(
  4432. title,
  4433. msg,
  4434. true,
  4435. buttons,
  4436. function(event, value, message, formVals)
  4437. {
  4438. window.location.reload();
  4439. return false;
  4440. }
  4441. );
  4442. }
  4443. /**
  4444. * Starts or stops the recording for the conference.
  4445. */
  4446. function toggleRecording() {
  4447. APP.xmpp.toggleRecording(function (callback) {
  4448. var msg = APP.translation.generateTranslatonHTML(
  4449. "dialog.recordingToken");
  4450. var token = APP.translation.translateString("dialog.token");
  4451. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  4452. '<h2>' + msg + '</h2>' +
  4453. '<input name="recordingToken" type="text" ' +
  4454. ' data-i18n="[placeholder]dialog.token" ' +
  4455. 'placeholder="' + token + '" autofocus>',
  4456. false,
  4457. "dialog.Save",
  4458. function (e, v, m, f) {
  4459. if (v) {
  4460. var token = f.recordingToken;
  4461. if (token) {
  4462. callback(UIUtil.escapeHtml(token));
  4463. }
  4464. }
  4465. },
  4466. null,
  4467. function () { },
  4468. ':input:first'
  4469. );
  4470. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4471. }
  4472. /**
  4473. * Locks / unlocks the room.
  4474. */
  4475. function lockRoom(lock) {
  4476. var currentSharedKey = '';
  4477. if (lock)
  4478. currentSharedKey = sharedKey;
  4479. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4480. // password is required
  4481. if (sharedKey)
  4482. {
  4483. console.log('set room password');
  4484. Toolbar.lockLockButton();
  4485. }
  4486. else
  4487. {
  4488. console.log('removed room password');
  4489. Toolbar.unlockLockButton();
  4490. }
  4491. }, function (err) {
  4492. console.warn('setting password failed', err);
  4493. messageHandler.showError("dialog.lockTitle",
  4494. "dialog.lockMessage");
  4495. Toolbar.setSharedKey('');
  4496. }, function () {
  4497. console.warn('room passwords not supported');
  4498. messageHandler.showError("dialog.warning",
  4499. "dialog.passwordNotSupported");
  4500. Toolbar.setSharedKey('');
  4501. });
  4502. };
  4503. /**
  4504. * Invite participants to conference.
  4505. */
  4506. function inviteParticipants() {
  4507. if (roomUrl === null)
  4508. return;
  4509. var sharedKeyText = "";
  4510. if (sharedKey && sharedKey.length > 0) {
  4511. sharedKeyText =
  4512. APP.translation.translateString("email.sharedKey",
  4513. {sharedKey: sharedKey});
  4514. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  4515. }
  4516. var supportedBrowsers = "Chromium, Google Chrome " +
  4517. APP.translation.translateString("email.and") + " Opera";
  4518. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4519. var subject = APP.translation.translateString("email.subject",
  4520. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  4521. var body = APP.translation.translateString("email.body",
  4522. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  4523. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  4524. body = body.replace(/\n/g, "%0D%0A");
  4525. if (window.localStorage.displayname) {
  4526. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4527. }
  4528. if (interfaceConfig.INVITATION_POWERED_BY) {
  4529. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4530. }
  4531. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4532. }
  4533. function callSipButtonClicked()
  4534. {
  4535. var defaultNumber
  4536. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4537. var sipMsg = APP.translation.generateTranslatonHTML(
  4538. "dialog.sipMsg");
  4539. messageHandler.openTwoButtonDialog(null, null, null,
  4540. '<h2>' + sipMsg + '</h2>' +
  4541. '<input name="sipNumber" type="text"' +
  4542. ' value="' + defaultNumber + '" autofocus>',
  4543. false,
  4544. "dialog.Dial",
  4545. function (e, v, m, f) {
  4546. if (v) {
  4547. var numberInput = f.sipNumber;
  4548. if (numberInput) {
  4549. APP.xmpp.dial(
  4550. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  4551. }
  4552. }
  4553. },
  4554. null, null, ':input:first'
  4555. );
  4556. }
  4557. var Toolbar = (function (my) {
  4558. my.init = function (ui) {
  4559. for(var k in buttonHandlers)
  4560. $("#" + k).click(buttonHandlers[k]);
  4561. UI = ui;
  4562. // Update login info
  4563. APP.xmpp.addListener(
  4564. AuthenticationEvents.IDENTITY_UPDATED,
  4565. function (authenticationEnabled, userIdentity) {
  4566. var loggedIn = false;
  4567. if (userIdentity) {
  4568. loggedIn = true;
  4569. }
  4570. Toolbar.showAuthenticateButton(authenticationEnabled);
  4571. if (authenticationEnabled) {
  4572. Toolbar.setAuthenticatedIdentity(userIdentity);
  4573. Toolbar.showLoginButton(!loggedIn);
  4574. Toolbar.showLogoutButton(loggedIn);
  4575. }
  4576. }
  4577. );
  4578. },
  4579. /**
  4580. * Sets shared key
  4581. * @param sKey the shared key
  4582. */
  4583. my.setSharedKey = function (sKey) {
  4584. sharedKey = sKey;
  4585. };
  4586. my.authenticateClicked = function () {
  4587. Authentication.focusAuthenticationWindow();
  4588. if (!APP.xmpp.isExternalAuthEnabled()) {
  4589. Authentication.xmppAuthenticate();
  4590. return;
  4591. }
  4592. // Get authentication URL
  4593. if (!APP.xmpp.getMUCJoined()) {
  4594. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4595. // If conference has not been started yet - redirect to login page
  4596. window.location.href = url;
  4597. });
  4598. } else {
  4599. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4600. // Otherwise - open popup with authentication URL
  4601. var authenticationWindow = Authentication.createAuthenticationWindow(
  4602. function () {
  4603. // On popup closed - retry room allocation
  4604. APP.xmpp.allocateConferenceFocus(
  4605. APP.UI.getRoomName(),
  4606. function () { console.info("AUTH DONE"); }
  4607. );
  4608. }, url);
  4609. if (!authenticationWindow) {
  4610. messageHandler.openMessageDialog(
  4611. null, "dialog.popupError");
  4612. }
  4613. });
  4614. }
  4615. };
  4616. /**
  4617. * Updates the room invite url.
  4618. */
  4619. my.updateRoomUrl = function (newRoomUrl) {
  4620. roomUrl = newRoomUrl;
  4621. // If the invite dialog has been already opened we update the information.
  4622. var inviteLink = document.getElementById('inviteLinkRef');
  4623. if (inviteLink) {
  4624. inviteLink.value = roomUrl;
  4625. inviteLink.select();
  4626. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  4627. }
  4628. };
  4629. /**
  4630. * Disables and enables some of the buttons.
  4631. */
  4632. my.setupButtonsFromConfig = function () {
  4633. if (config.disablePrezi)
  4634. {
  4635. $("#prezi_button").css({display: "none"});
  4636. }
  4637. };
  4638. /**
  4639. * Opens the lock room dialog.
  4640. */
  4641. my.openLockDialog = function () {
  4642. // Only the focus is able to set a shared key.
  4643. if (!APP.xmpp.isModerator()) {
  4644. if (sharedKey) {
  4645. messageHandler.openMessageDialog(null,
  4646. "dialog.passwordError");
  4647. } else {
  4648. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  4649. }
  4650. } else {
  4651. if (sharedKey) {
  4652. messageHandler.openTwoButtonDialog(null, null,
  4653. "dialog.passwordCheck",
  4654. null,
  4655. false,
  4656. "dialog.Remove",
  4657. function (e, v) {
  4658. if (v) {
  4659. Toolbar.setSharedKey('');
  4660. lockRoom(false);
  4661. }
  4662. });
  4663. } else {
  4664. var msg = APP.translation.generateTranslatonHTML(
  4665. "dialog.passwordMsg");
  4666. var yourPassword = APP.translation.translateString(
  4667. "dialog.yourPassword");
  4668. messageHandler.openTwoButtonDialog(null, null, null,
  4669. '<h2>' + msg + '</h2>' +
  4670. '<input name="lockKey" type="text"' +
  4671. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  4672. 'placeholder="' + yourPassword + '" autofocus>',
  4673. false,
  4674. "dialog.Save",
  4675. function (e, v, m, f) {
  4676. if (v) {
  4677. var lockKey = f.lockKey;
  4678. if (lockKey) {
  4679. Toolbar.setSharedKey(
  4680. UIUtil.escapeHtml(lockKey));
  4681. lockRoom(true);
  4682. }
  4683. }
  4684. },
  4685. null, null, 'input:first'
  4686. );
  4687. }
  4688. }
  4689. };
  4690. /**
  4691. * Opens the invite link dialog.
  4692. */
  4693. my.openLinkDialog = function () {
  4694. var inviteAttreibutes;
  4695. if (roomUrl === null) {
  4696. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  4697. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  4698. } else {
  4699. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  4700. }
  4701. messageHandler.openTwoButtonDialog("dialog.shareLink",
  4702. null, null,
  4703. '<input id="inviteLinkRef" type="text" ' +
  4704. inviteAttreibutes + ' onclick="this.select();" readonly>',
  4705. false,
  4706. "dialog.Invite",
  4707. function (e, v) {
  4708. if (v) {
  4709. if (roomUrl) {
  4710. inviteParticipants();
  4711. }
  4712. }
  4713. },
  4714. function () {
  4715. if (roomUrl) {
  4716. document.getElementById('inviteLinkRef').select();
  4717. } else {
  4718. document.getElementById('jqi_state0_buttonInvite')
  4719. .disabled = true;
  4720. }
  4721. }
  4722. );
  4723. };
  4724. /**
  4725. * Opens the settings dialog.
  4726. * FIXME: not used ?
  4727. */
  4728. my.openSettingsDialog = function () {
  4729. var settings1 = APP.translation.generateTranslatonHTML(
  4730. "dialog.settings1");
  4731. var settings2 = APP.translation.generateTranslatonHTML(
  4732. "dialog.settings2");
  4733. var settings3 = APP.translation.generateTranslatonHTML(
  4734. "dialog.settings3");
  4735. var yourPassword = APP.translation.translateString(
  4736. "dialog.yourPassword");
  4737. messageHandler.openTwoButtonDialog(null,
  4738. '<h2>' + settings1 + '</h2>' +
  4739. '<input type="checkbox" id="initMuted">' +
  4740. settings2 + '<br/>' +
  4741. '<input type="checkbox" id="requireNicknames">' +
  4742. settings3 +
  4743. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  4744. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  4745. null,
  4746. null,
  4747. false,
  4748. "dialog.Save",
  4749. function () {
  4750. document.getElementById('lockKey').focus();
  4751. },
  4752. function (e, v) {
  4753. if (v) {
  4754. if ($('#initMuted').is(":checked")) {
  4755. // it is checked
  4756. }
  4757. if ($('#requireNicknames').is(":checked")) {
  4758. // it is checked
  4759. }
  4760. /*
  4761. var lockKey = document.getElementById('lockKey');
  4762. if (lockKey.value) {
  4763. setSharedKey(lockKey.value);
  4764. lockRoom(true);
  4765. }
  4766. */
  4767. }
  4768. }
  4769. );
  4770. };
  4771. /**
  4772. * Toggles the application in and out of full screen mode
  4773. * (a.k.a. presentation mode in Chrome).
  4774. */
  4775. my.toggleFullScreen = function () {
  4776. var fsElement = document.documentElement;
  4777. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  4778. //Enter Full Screen
  4779. if (fsElement.mozRequestFullScreen) {
  4780. fsElement.mozRequestFullScreen();
  4781. }
  4782. else {
  4783. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  4784. }
  4785. } else {
  4786. //Exit Full Screen
  4787. if (document.mozCancelFullScreen) {
  4788. document.mozCancelFullScreen();
  4789. } else {
  4790. document.webkitCancelFullScreen();
  4791. }
  4792. }
  4793. };
  4794. /**
  4795. * Unlocks the lock button state.
  4796. */
  4797. my.unlockLockButton = function () {
  4798. if ($("#lockIcon").hasClass("icon-security-locked"))
  4799. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4800. };
  4801. /**
  4802. * Updates the lock button state to locked.
  4803. */
  4804. my.lockLockButton = function () {
  4805. if ($("#lockIcon").hasClass("icon-security"))
  4806. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4807. };
  4808. /**
  4809. * Shows or hides authentication button
  4810. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  4811. */
  4812. my.showAuthenticateButton = function (show) {
  4813. if (show) {
  4814. $('#authentication').css({display: "inline"});
  4815. }
  4816. else {
  4817. $('#authentication').css({display: "none"});
  4818. }
  4819. };
  4820. // Shows or hides the 'recording' button.
  4821. my.showRecordingButton = function (show) {
  4822. if (!config.enableRecording) {
  4823. return;
  4824. }
  4825. if (show) {
  4826. $('#recording').css({display: "inline"});
  4827. }
  4828. else {
  4829. $('#recording').css({display: "none"});
  4830. }
  4831. };
  4832. // Sets the state of the recording button
  4833. my.setRecordingButtonState = function (isRecording) {
  4834. if (isRecording) {
  4835. $('#recordButton').removeClass("icon-recEnable");
  4836. $('#recordButton').addClass("icon-recEnable active");
  4837. } else {
  4838. $('#recordButton').removeClass("icon-recEnable active");
  4839. $('#recordButton').addClass("icon-recEnable");
  4840. }
  4841. };
  4842. // Shows or hides SIP calls button
  4843. my.showSipCallButton = function (show) {
  4844. if (APP.xmpp.isSipGatewayEnabled() && show) {
  4845. $('#sipCallButton').css({display: "inline-block"});
  4846. } else {
  4847. $('#sipCallButton').css({display: "none"});
  4848. }
  4849. };
  4850. /**
  4851. * Displays user authenticated identity name(login).
  4852. * @param authIdentity identity name to be displayed.
  4853. */
  4854. my.setAuthenticatedIdentity = function (authIdentity) {
  4855. if (authIdentity) {
  4856. $('#toolbar_auth_identity').css({display: "list-item"});
  4857. $('#toolbar_auth_identity').text(authIdentity);
  4858. } else {
  4859. $('#toolbar_auth_identity').css({display: "none"});
  4860. }
  4861. };
  4862. /**
  4863. * Shows/hides login button.
  4864. * @param show <tt>true</tt> to show
  4865. */
  4866. my.showLoginButton = function (show) {
  4867. if (show) {
  4868. $('#toolbar_button_login').css({display: "list-item"});
  4869. } else {
  4870. $('#toolbar_button_login').css({display: "none"});
  4871. }
  4872. };
  4873. /**
  4874. * Shows/hides logout button.
  4875. * @param show <tt>true</tt> to show
  4876. */
  4877. my.showLogoutButton = function (show) {
  4878. if (show) {
  4879. $('#toolbar_button_logout').css({display: "list-item"});
  4880. } else {
  4881. $('#toolbar_button_logout').css({display: "none"});
  4882. }
  4883. };
  4884. /**
  4885. * Sets the state of the button. The button has blue glow if desktop
  4886. * streaming is active.
  4887. * @param active the state of the desktop streaming.
  4888. */
  4889. my.changeDesktopSharingButtonState = function (active) {
  4890. var button = $("#desktopsharing > a");
  4891. if (active)
  4892. {
  4893. button.addClass("glow");
  4894. }
  4895. else
  4896. {
  4897. button.removeClass("glow");
  4898. }
  4899. };
  4900. return my;
  4901. }(Toolbar || {}));
  4902. module.exports = Toolbar;
  4903. },{"../../../service/authentication/AuthenticationEvents":93,"../authentication/Authentication":11,"../etherpad/Etherpad":14,"../prezi/Prezi":15,"../side_pannels/SidePanelToggler":17,"../util/MessageHandler":28,"../util/UIUtil":30,"./BottomToolbar":24}],26:[function(require,module,exports){
  4904. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  4905. var toolbarTimeoutObject,
  4906. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  4907. function showDesktopSharingButton() {
  4908. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  4909. $('#desktopsharing').css({display: "inline"});
  4910. } else {
  4911. $('#desktopsharing').css({display: "none"});
  4912. }
  4913. }
  4914. /**
  4915. * Hides the toolbar.
  4916. */
  4917. function hideToolbar() {
  4918. var header = $("#header"),
  4919. bottomToolbar = $("#bottomToolbar");
  4920. var isToolbarHover = false;
  4921. header.find('*').each(function () {
  4922. var id = $(this).attr('id');
  4923. if ($("#" + id + ":hover").length > 0) {
  4924. isToolbarHover = true;
  4925. }
  4926. });
  4927. if ($("#bottomToolbar:hover").length > 0) {
  4928. isToolbarHover = true;
  4929. }
  4930. clearTimeout(toolbarTimeoutObject);
  4931. toolbarTimeoutObject = null;
  4932. if (!isToolbarHover) {
  4933. header.hide("slide", { direction: "up", duration: 300});
  4934. $('#subject').animate({top: "-=40"}, 300);
  4935. if ($("#remoteVideos").hasClass("hidden")) {
  4936. bottomToolbar.hide(
  4937. "slide", {direction: "right", duration: 300});
  4938. }
  4939. }
  4940. else {
  4941. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4942. }
  4943. }
  4944. var ToolbarToggler = {
  4945. /**
  4946. * Shows the main toolbar.
  4947. */
  4948. showToolbar: function () {
  4949. var header = $("#header"),
  4950. bottomToolbar = $("#bottomToolbar");
  4951. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  4952. header.show("slide", { direction: "up", duration: 300});
  4953. $('#subject').animate({top: "+=40"}, 300);
  4954. if (!bottomToolbar.is(":visible")) {
  4955. bottomToolbar.show(
  4956. "slide", {direction: "right", duration: 300});
  4957. }
  4958. if (toolbarTimeoutObject) {
  4959. clearTimeout(toolbarTimeoutObject);
  4960. toolbarTimeoutObject = null;
  4961. }
  4962. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4963. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  4964. }
  4965. if (APP.xmpp.isModerator())
  4966. {
  4967. // TODO: Enable settings functionality.
  4968. // Need to uncomment the settings button in index.html.
  4969. // $('#settingsButton').css({visibility:"visible"});
  4970. }
  4971. // Show/hide desktop sharing button
  4972. showDesktopSharingButton();
  4973. },
  4974. /**
  4975. * Docks/undocks the toolbar.
  4976. *
  4977. * @param isDock indicates what operation to perform
  4978. */
  4979. dockToolbar: function (isDock) {
  4980. if (isDock) {
  4981. // First make sure the toolbar is shown.
  4982. if (!$('#header').is(':visible')) {
  4983. this.showToolbar();
  4984. }
  4985. // Then clear the time out, to dock the toolbar.
  4986. if (toolbarTimeoutObject) {
  4987. clearTimeout(toolbarTimeoutObject);
  4988. toolbarTimeoutObject = null;
  4989. }
  4990. }
  4991. else {
  4992. if (!$('#header').is(':visible')) {
  4993. this.showToolbar();
  4994. }
  4995. else {
  4996. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4997. }
  4998. }
  4999. },
  5000. showDesktopSharingButton: showDesktopSharingButton
  5001. };
  5002. module.exports = ToolbarToggler;
  5003. },{}],27:[function(require,module,exports){
  5004. var JitsiPopover = (function () {
  5005. /**
  5006. * Constructs new JitsiPopover and attaches it to the element
  5007. * @param element jquery selector
  5008. * @param options the options for the popover.
  5009. * @constructor
  5010. */
  5011. function JitsiPopover(element, options)
  5012. {
  5013. this.options = {
  5014. skin: "white",
  5015. content: ""
  5016. };
  5017. if(options)
  5018. {
  5019. if(options.skin)
  5020. this.options.skin = options.skin;
  5021. if(options.content)
  5022. this.options.content = options.content;
  5023. }
  5024. this.elementIsHovered = false;
  5025. this.popoverIsHovered = false;
  5026. this.popoverShown = false;
  5027. element.data("jitsi_popover", this);
  5028. this.element = element;
  5029. this.template = ' <div class="jitsipopover ' + this.options.skin +
  5030. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  5031. '<div class="jitsiPopupmenuPadding"></div></div>';
  5032. var self = this;
  5033. this.element.on("mouseenter", function () {
  5034. self.elementIsHovered = true;
  5035. self.show();
  5036. }).on("mouseleave", function () {
  5037. self.elementIsHovered = false;
  5038. setTimeout(function () {
  5039. self.hide();
  5040. }, 10);
  5041. });
  5042. }
  5043. /**
  5044. * Shows the popover
  5045. */
  5046. JitsiPopover.prototype.show = function () {
  5047. this.createPopover();
  5048. this.popoverShown = true;
  5049. };
  5050. /**
  5051. * Hides the popover
  5052. */
  5053. JitsiPopover.prototype.hide = function () {
  5054. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  5055. {
  5056. this.forceHide();
  5057. }
  5058. };
  5059. /**
  5060. * Hides the popover
  5061. */
  5062. JitsiPopover.prototype.forceHide = function () {
  5063. $(".jitsipopover").remove();
  5064. this.popoverShown = false;
  5065. };
  5066. /**
  5067. * Creates the popover html
  5068. */
  5069. JitsiPopover.prototype.createPopover = function () {
  5070. $("body").append(this.template);
  5071. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  5072. var self = this;
  5073. $(".jitsipopover").on("mouseenter", function () {
  5074. self.popoverIsHovered = true;
  5075. }).on("mouseleave", function () {
  5076. self.popoverIsHovered = false;
  5077. self.hide();
  5078. });
  5079. this.refreshPosition();
  5080. };
  5081. /**
  5082. * Refreshes the position of the popover
  5083. */
  5084. JitsiPopover.prototype.refreshPosition = function () {
  5085. $(".jitsipopover").position({
  5086. my: "bottom",
  5087. at: "top",
  5088. collision: "fit",
  5089. of: this.element,
  5090. using: function (position, elements) {
  5091. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  5092. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  5093. $(".jitsipopover > .arrow").css({left: calcLeft});
  5094. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  5095. }
  5096. });
  5097. };
  5098. /**
  5099. * Updates the content of popover.
  5100. * @param content new content
  5101. */
  5102. JitsiPopover.prototype.updateContent = function (content) {
  5103. this.options.content = content;
  5104. if(!this.popoverShown)
  5105. return;
  5106. $(".jitsipopover").remove();
  5107. this.createPopover();
  5108. };
  5109. return JitsiPopover;
  5110. })();
  5111. module.exports = JitsiPopover;
  5112. },{}],28:[function(require,module,exports){
  5113. /* global $, APP, jQuery, toastr */
  5114. var messageHandler = (function(my) {
  5115. /**
  5116. * Shows a message to the user.
  5117. *
  5118. * @param titleString the title of the message
  5119. * @param messageString the text of the message
  5120. */
  5121. my.openMessageDialog = function(titleKey, messageKey) {
  5122. var title = null;
  5123. if(titleKey)
  5124. {
  5125. title = APP.translation.generateTranslatonHTML(titleKey);
  5126. }
  5127. var message = APP.translation.generateTranslatonHTML(messageKey);
  5128. $.prompt(message,
  5129. {
  5130. title: title,
  5131. persistent: false
  5132. }
  5133. );
  5134. };
  5135. /**
  5136. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5137. *
  5138. * @param titleString the title of the message
  5139. * @param msgString the text of the message
  5140. * @param persistent boolean value which determines whether the message is persistent or not
  5141. * @param leftButton the fist button's text
  5142. * @param submitFunction function to be called on submit
  5143. * @param loadedFunction function to be called after the prompt is fully loaded
  5144. * @param closeFunction function to be called after the prompt is closed
  5145. * @param focus optional focus selector or button index to be focused after
  5146. * the dialog is opened
  5147. * @param defaultButton index of default button which will be activated when
  5148. * the user press 'enter'. Indexed from 0.
  5149. */
  5150. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  5151. persistent, leftButtonKey, submitFunction, loadedFunction,
  5152. closeFunction, focus, defaultButton)
  5153. {
  5154. var buttons = [];
  5155. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  5156. buttons.push({ title: leftButton, value: true});
  5157. var cancelButton
  5158. = APP.translation.generateTranslatonHTML("dialog.Cancel");
  5159. buttons.push({title: cancelButton, value: false});
  5160. var message = msgString, title = titleString;
  5161. if (titleKey)
  5162. {
  5163. title = APP.translation.generateTranslatonHTML(titleKey);
  5164. }
  5165. if (msgKey) {
  5166. message = APP.translation.generateTranslatonHTML(msgKey);
  5167. }
  5168. $.prompt(message, {
  5169. title: title,
  5170. persistent: false,
  5171. buttons: buttons,
  5172. defaultButton: defaultButton,
  5173. focus: focus,
  5174. loaded: loadedFunction,
  5175. submit: submitFunction,
  5176. close: closeFunction
  5177. });
  5178. };
  5179. /**
  5180. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5181. *
  5182. * @param titleString the title of the message
  5183. * @param msgString the text of the message
  5184. * @param persistent boolean value which determines whether the message is persistent or not
  5185. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  5186. * that will be passed to submitFunction
  5187. * @param submitFunction function to be called on submit
  5188. * @param loadedFunction function to be called after the prompt is fully loaded
  5189. */
  5190. my.openDialog = function (titleString, msgString, persistent, buttons,
  5191. submitFunction, loadedFunction) {
  5192. var args = {
  5193. title: titleString,
  5194. persistent: persistent,
  5195. buttons: buttons,
  5196. defaultButton: 1,
  5197. loaded: loadedFunction,
  5198. submit: submitFunction
  5199. };
  5200. if (persistent) {
  5201. args.closeText = '';
  5202. }
  5203. return new Impromptu(msgString, args);
  5204. };
  5205. /**
  5206. * Closes currently opened dialog.
  5207. */
  5208. my.closeDialog = function () {
  5209. $.prompt.close();
  5210. };
  5211. /**
  5212. * Shows a dialog with different states to the user.
  5213. *
  5214. * @param statesObject object containing all the states of the dialog
  5215. */
  5216. my.openDialogWithStates = function (statesObject, options) {
  5217. return new Impromptu(statesObject, options);
  5218. };
  5219. /**
  5220. * Opens new popup window for given <tt>url</tt> centered over current
  5221. * window.
  5222. *
  5223. * @param url the URL to be displayed in the popup window
  5224. * @param w the width of the popup window
  5225. * @param h the height of the popup window
  5226. * @param onPopupClosed optional callback function called when popup window
  5227. * has been closed.
  5228. *
  5229. * @returns popup window object if opened successfully or undefined
  5230. * in case we failed to open it(popup blocked)
  5231. */
  5232. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  5233. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  5234. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  5235. var popup = window.open(
  5236. url, '_blank',
  5237. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  5238. if (popup && onPopupClosed) {
  5239. var pollTimer = window.setInterval(function () {
  5240. if (popup.closed !== false) {
  5241. window.clearInterval(pollTimer);
  5242. onPopupClosed();
  5243. }
  5244. }, 200);
  5245. }
  5246. return popup;
  5247. };
  5248. /**
  5249. * Shows a dialog prompting the user to send an error report.
  5250. *
  5251. * @param titleString the title of the message
  5252. * @param msgString the text of the message
  5253. * @param error the error that is being reported
  5254. */
  5255. my.openReportDialog = function(titleKey, msgKey, error) {
  5256. my.openMessageDialog(titleKey, msgKey);
  5257. console.log(error);
  5258. //FIXME send the error to the server
  5259. };
  5260. /**
  5261. * Shows an error dialog to the user.
  5262. * @param title the title of the message
  5263. * @param message the text of the messafe
  5264. */
  5265. my.showError = function(titleKey, msgKey) {
  5266. if(!titleKey) {
  5267. titleKey = "dialog.oops";
  5268. }
  5269. if(!msgKey)
  5270. {
  5271. msgKey = "dialog.defaultError";
  5272. }
  5273. messageHandler.openMessageDialog(titleKey, msgKey);
  5274. };
  5275. my.notify = function(displayName, displayNameKey,
  5276. cls, messageKey, messageArguments) {
  5277. var displayNameSpan = '<span class="nickname" ';
  5278. if(displayName)
  5279. {
  5280. displayNameSpan += ">" + displayName;
  5281. }
  5282. else
  5283. {
  5284. displayNameSpan += "data-i18n='" + displayNameKey +
  5285. "'>" + APP.translation.translateString(displayNameKey);
  5286. }
  5287. displayNameSpan += "</span>";
  5288. toastr.info(
  5289. displayNameSpan + '<br>' +
  5290. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  5291. (messageArguments?
  5292. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  5293. : "") + ">" +
  5294. APP.translation.translateString(messageKey,
  5295. messageArguments) +
  5296. '</span>');
  5297. };
  5298. return my;
  5299. }(messageHandler || {}));
  5300. module.exports = messageHandler;
  5301. },{}],29:[function(require,module,exports){
  5302. var UIEvents = require("../../../service/UI/UIEvents");
  5303. var nickname = null;
  5304. var eventEmitter = null;
  5305. var NickanameHandler = {
  5306. init: function (emitter) {
  5307. eventEmitter = emitter;
  5308. var storedDisplayName = window.localStorage.displayname;
  5309. if (storedDisplayName) {
  5310. nickname = storedDisplayName;
  5311. }
  5312. },
  5313. setNickname: function (newNickname) {
  5314. if (!newNickname || nickname === newNickname)
  5315. return;
  5316. nickname = newNickname;
  5317. window.localStorage.displayname = nickname;
  5318. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  5319. },
  5320. getNickname: function () {
  5321. return nickname;
  5322. },
  5323. addListener: function (type, listener) {
  5324. eventEmitter.on(type, listener);
  5325. }
  5326. };
  5327. module.exports = NickanameHandler;
  5328. },{"../../../service/UI/UIEvents":92}],30:[function(require,module,exports){
  5329. /**
  5330. * Created by hristo on 12/22/14.
  5331. */
  5332. module.exports = {
  5333. /**
  5334. * Returns the available video width.
  5335. */
  5336. getAvailableVideoWidth: function () {
  5337. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5338. var rightPanelWidth
  5339. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5340. return window.innerWidth - rightPanelWidth;
  5341. },
  5342. /**
  5343. * Changes the style class of the element given by id.
  5344. */
  5345. buttonClick: function(id, classname) {
  5346. $(id).toggleClass(classname); // add the class to the clicked element
  5347. },
  5348. /**
  5349. * Returns the text width for the given element.
  5350. *
  5351. * @param el the element
  5352. */
  5353. getTextWidth: function (el) {
  5354. return (el.clientWidth + 1);
  5355. },
  5356. /**
  5357. * Returns the text height for the given element.
  5358. *
  5359. * @param el the element
  5360. */
  5361. getTextHeight: function (el) {
  5362. return (el.clientHeight + 1);
  5363. },
  5364. /**
  5365. * Plays the sound given by id.
  5366. *
  5367. * @param id the identifier of the audio element.
  5368. */
  5369. playSoundNotification: function (id) {
  5370. document.getElementById(id).play();
  5371. },
  5372. /**
  5373. * Escapes the given text.
  5374. */
  5375. escapeHtml: function (unsafeText) {
  5376. return $('<div/>').text(unsafeText).html();
  5377. },
  5378. imageToGrayScale: function (canvas) {
  5379. var context = canvas.getContext('2d');
  5380. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5381. var pixels = imgData.data;
  5382. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5383. var grayscale
  5384. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5385. pixels[i ] = grayscale; // red
  5386. pixels[i+1] = grayscale; // green
  5387. pixels[i+2] = grayscale; // blue
  5388. // pixels[i+3] is alpha
  5389. }
  5390. // redraw the image in black & white
  5391. context.putImageData(imgData, 0, 0);
  5392. },
  5393. setTooltip: function (element, key, position) {
  5394. element.setAttribute("data-i18n", "[data-content]" + key);
  5395. element.setAttribute("data-toggle", "popover");
  5396. element.setAttribute("data-placement", position);
  5397. element.setAttribute("data-html", true);
  5398. element.setAttribute("data-container", "body");
  5399. }
  5400. };
  5401. },{"../side_pannels/SidePanelToggler":17}],31:[function(require,module,exports){
  5402. var JitsiPopover = require("../util/JitsiPopover");
  5403. /**
  5404. * Constructs new connection indicator.
  5405. * @param videoContainer the video container associated with the indicator.
  5406. * @constructor
  5407. */
  5408. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5409. {
  5410. this.videoContainer = videoContainer;
  5411. this.bandwidth = null;
  5412. this.packetLoss = null;
  5413. this.bitrate = null;
  5414. this.showMoreValue = false;
  5415. this.resolution = null;
  5416. this.transport = [];
  5417. this.popover = null;
  5418. this.jid = jid;
  5419. this.create();
  5420. this.videoLayout = VideoLayout;
  5421. }
  5422. /**
  5423. * Values for the connection quality
  5424. * @type {{98: string,
  5425. * 81: string,
  5426. * 64: string,
  5427. * 47: string,
  5428. * 30: string,
  5429. * 0: string}}
  5430. */
  5431. ConnectionIndicator.connectionQualityValues = {
  5432. 98: "18px", //full
  5433. 81: "15px",//4 bars
  5434. 64: "11px",//3 bars
  5435. 47: "7px",//2 bars
  5436. 30: "3px",//1 bar
  5437. 0: "0px"//empty
  5438. };
  5439. ConnectionIndicator.getIP = function(value)
  5440. {
  5441. return value.substring(0, value.lastIndexOf(":"));
  5442. };
  5443. ConnectionIndicator.getPort = function(value)
  5444. {
  5445. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5446. };
  5447. ConnectionIndicator.getStringFromArray = function (array) {
  5448. var res = "";
  5449. for(var i = 0; i < array.length; i++)
  5450. {
  5451. res += (i === 0? "" : ", ") + array[i];
  5452. }
  5453. return res;
  5454. };
  5455. /**
  5456. * Generates the html content.
  5457. * @returns {string} the html content.
  5458. */
  5459. ConnectionIndicator.prototype.generateText = function () {
  5460. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5461. var translate = APP.translation.translateString;
  5462. if(this.bitrate === null)
  5463. {
  5464. downloadBitrate = "N/A";
  5465. uploadBitrate = "N/A";
  5466. }
  5467. else
  5468. {
  5469. downloadBitrate =
  5470. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5471. uploadBitrate =
  5472. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5473. }
  5474. if(this.packetLoss === null)
  5475. {
  5476. packetLoss = "N/A";
  5477. }
  5478. else
  5479. {
  5480. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5481. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5482. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5483. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5484. }
  5485. var resolutionValue = null;
  5486. if(this.resolution && this.jid != null)
  5487. {
  5488. var keys = Object.keys(this.resolution);
  5489. if(keys.length == 1)
  5490. {
  5491. for(var ssrc in this.resolution)
  5492. {
  5493. resolutionValue = this.resolution[ssrc];
  5494. }
  5495. }
  5496. else if(keys.length > 1)
  5497. {
  5498. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  5499. resolutionValue = this.resolution[displayedSsrc];
  5500. }
  5501. }
  5502. if(this.jid === null)
  5503. {
  5504. resolution = "";
  5505. if(this.resolution === null || !Object.keys(this.resolution) ||
  5506. Object.keys(this.resolution).length === 0)
  5507. {
  5508. resolution = "N/A";
  5509. }
  5510. else
  5511. for(i in this.resolution)
  5512. {
  5513. resolutionValue = this.resolution[i];
  5514. if(resolutionValue)
  5515. {
  5516. if(resolutionValue.height &&
  5517. resolutionValue.width)
  5518. {
  5519. resolution += (resolution === ""? "" : ", ") +
  5520. resolutionValue.width + "x" +
  5521. resolutionValue.height;
  5522. }
  5523. }
  5524. }
  5525. }
  5526. else if(!resolutionValue ||
  5527. !resolutionValue.height ||
  5528. !resolutionValue.width)
  5529. {
  5530. resolution = "N/A";
  5531. }
  5532. else
  5533. {
  5534. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5535. }
  5536. var result = "<table style='width:100%'>" +
  5537. "<tr>" +
  5538. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5539. translate("connectionindicator.bitrate") + "</span></td>" +
  5540. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5541. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5542. uploadBitrate + "</td>" +
  5543. "</tr><tr>" +
  5544. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5545. translate("connectionindicator.packetloss") + "</span></td>" +
  5546. "<td>" + packetLoss + "</td>" +
  5547. "</tr><tr>" +
  5548. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5549. translate("connectionindicator.resolution") + "</span></td>" +
  5550. "<td>" + resolution + "</td></tr></table>";
  5551. if(this.videoContainer.id == "localVideoContainer") {
  5552. result += "<div class=\"jitsipopover_showmore\" " +
  5553. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5554. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5555. (this.showMoreValue ? "less" : "more") + "'>" +
  5556. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5557. "</div><br />";
  5558. }
  5559. if(this.showMoreValue)
  5560. {
  5561. var downloadBandwidth, uploadBandwidth, transport;
  5562. if(this.bandwidth === null)
  5563. {
  5564. downloadBandwidth = "N/A";
  5565. uploadBandwidth = "N/A";
  5566. }
  5567. else
  5568. {
  5569. downloadBandwidth = this.bandwidth.download?
  5570. this.bandwidth.download + " Kbps" :
  5571. "N/A";
  5572. uploadBandwidth = this.bandwidth.upload?
  5573. this.bandwidth.upload + " Kbps" :
  5574. "N/A";
  5575. }
  5576. if(!this.transport || this.transport.length === 0)
  5577. {
  5578. transport = "<tr>" +
  5579. "<td><span class='jitsipopover_blue' " +
  5580. "data-i18n='connectionindicator.address'>" +
  5581. translate("connectionindicator.address") + "</span></td>" +
  5582. "<td> N/A</td></tr>";
  5583. }
  5584. else
  5585. {
  5586. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5587. for(i = 0; i < this.transport.length; i++)
  5588. {
  5589. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5590. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5591. var localIP =
  5592. ConnectionIndicator.getIP(this.transport[i].localip);
  5593. var localPort =
  5594. ConnectionIndicator.getPort(this.transport[i].localip);
  5595. if(data.remoteIP.indexOf(ip) == -1)
  5596. {
  5597. data.remoteIP.push(ip);
  5598. }
  5599. if(data.remotePort.indexOf(port) == -1)
  5600. {
  5601. data.remotePort.push(port);
  5602. }
  5603. if(data.localIP.indexOf(localIP) == -1)
  5604. {
  5605. data.localIP.push(localIP);
  5606. }
  5607. if(data.localPort.indexOf(localPort) == -1)
  5608. {
  5609. data.localPort.push(localPort);
  5610. }
  5611. }
  5612. var local_address_key = "connectionindicator.localaddress";
  5613. var remote_address_key = "connectionindicator.remoteaddress";
  5614. var localTransport =
  5615. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5616. local_address_key +"' data-i18n-options='" +
  5617. JSON.stringify({count: data.localIP.length}) + "'>" +
  5618. translate(local_address_key, {count: data.localIP.length}) +
  5619. "</span></td><td> " +
  5620. ConnectionIndicator.getStringFromArray(data.localIP) +
  5621. "</td></tr>";
  5622. transport =
  5623. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5624. remote_address_key + "' data-i18n-options='" +
  5625. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  5626. translate(remote_address_key,
  5627. {count: data.remoteIP.length}) +
  5628. "</span></td><td> " +
  5629. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5630. "</td></tr>";
  5631. var key_remote = "connectionindicator.remoteport",
  5632. key_local = "connectionindicator.localport";
  5633. transport += "<tr>" +
  5634. "<td>" +
  5635. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5636. "' data-i18n-options='" +
  5637. JSON.stringify({count: this.transport.length}) + "'>" +
  5638. translate(key_remote, {count: this.transport.length}) +
  5639. "</span></td><td>";
  5640. localTransport += "<tr>" +
  5641. "<td>" +
  5642. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5643. "' data-i18n-options='" +
  5644. JSON.stringify({count: this.transport.length}) + "'>" +
  5645. translate(key_local, {count: this.transport.length}) +
  5646. "</span></td><td>";
  5647. transport +=
  5648. ConnectionIndicator.getStringFromArray(data.remotePort);
  5649. localTransport +=
  5650. ConnectionIndicator.getStringFromArray(data.localPort);
  5651. transport += "</td></tr>";
  5652. transport += localTransport + "</td></tr>";
  5653. transport +="<tr>" +
  5654. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5655. translate("connectionindicator.transport") + "</span></td>" +
  5656. "<td>" + this.transport[0].type + "</td></tr>";
  5657. }
  5658. result += "<table style='width:100%'>" +
  5659. "<tr>" +
  5660. "<td>" +
  5661. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5662. translate("connectionindicator.bandwidth") + "</span>" +
  5663. "</td><td>" +
  5664. "<span class='jitsipopover_green'>&darr;</span>" +
  5665. downloadBandwidth +
  5666. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5667. uploadBandwidth + "</td></tr>";
  5668. result += transport + "</table>";
  5669. }
  5670. return result;
  5671. };
  5672. /**
  5673. * Shows or hide the additional information.
  5674. */
  5675. ConnectionIndicator.prototype.showMore = function () {
  5676. this.showMoreValue = !this.showMoreValue;
  5677. this.updatePopoverData();
  5678. };
  5679. function createIcon(classes)
  5680. {
  5681. var icon = document.createElement("span");
  5682. for(var i in classes)
  5683. {
  5684. icon.classList.add(classes[i]);
  5685. }
  5686. icon.appendChild(
  5687. document.createElement("i")).classList.add("icon-connection");
  5688. return icon;
  5689. }
  5690. /**
  5691. * Creates the indicator
  5692. */
  5693. ConnectionIndicator.prototype.create = function () {
  5694. this.connectionIndicatorContainer = document.createElement("div");
  5695. this.connectionIndicatorContainer.className = "connectionindicator";
  5696. this.connectionIndicatorContainer.style.display = "none";
  5697. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5698. this.popover = new JitsiPopover(
  5699. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5700. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5701. APP.translation.translateString("connectionindicator.na") + "</div>",
  5702. skin: "black"});
  5703. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5704. createIcon(["connection", "connection_empty"]));
  5705. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5706. createIcon(["connection", "connection_full"]));
  5707. };
  5708. /**
  5709. * Removes the indicator
  5710. */
  5711. ConnectionIndicator.prototype.remove = function()
  5712. {
  5713. this.connectionIndicatorContainer.remove();
  5714. this.popover.forceHide();
  5715. };
  5716. /**
  5717. * Updates the data of the indicator
  5718. * @param percent the percent of connection quality
  5719. * @param object the statistics data.
  5720. */
  5721. ConnectionIndicator.prototype.updateConnectionQuality =
  5722. function (percent, object) {
  5723. if(percent === null)
  5724. {
  5725. this.connectionIndicatorContainer.style.display = "none";
  5726. this.popover.forceHide();
  5727. return;
  5728. }
  5729. else
  5730. {
  5731. if(this.connectionIndicatorContainer.style.display == "none") {
  5732. this.connectionIndicatorContainer.style.display = "block";
  5733. this.videoLayout.updateMutePosition(this.videoContainer.id);
  5734. }
  5735. }
  5736. this.bandwidth = object.bandwidth;
  5737. this.bitrate = object.bitrate;
  5738. this.packetLoss = object.packetLoss;
  5739. this.transport = object.transport;
  5740. if(object.resolution)
  5741. {
  5742. this.resolution = object.resolution;
  5743. }
  5744. for(var quality in ConnectionIndicator.connectionQualityValues)
  5745. {
  5746. if(percent >= quality)
  5747. {
  5748. this.fullIcon.style.width =
  5749. ConnectionIndicator.connectionQualityValues[quality];
  5750. }
  5751. }
  5752. this.updatePopoverData();
  5753. };
  5754. /**
  5755. * Updates the resolution
  5756. * @param resolution the new resolution
  5757. */
  5758. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  5759. this.resolution = resolution;
  5760. this.updatePopoverData();
  5761. };
  5762. /**
  5763. * Updates the content of the popover
  5764. */
  5765. ConnectionIndicator.prototype.updatePopoverData = function () {
  5766. this.popover.updateContent(
  5767. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  5768. APP.translation.translateElement($(".connection_info"));
  5769. };
  5770. /**
  5771. * Hides the popover
  5772. */
  5773. ConnectionIndicator.prototype.hide = function () {
  5774. this.popover.forceHide();
  5775. };
  5776. /**
  5777. * Hides the indicator
  5778. */
  5779. ConnectionIndicator.prototype.hideIndicator = function () {
  5780. this.connectionIndicatorContainer.style.display = "none";
  5781. if(this.popover)
  5782. this.popover.forceHide();
  5783. };
  5784. module.exports = ConnectionIndicator;
  5785. },{"../util/JitsiPopover":27}],32:[function(require,module,exports){
  5786. var AudioLevels = require("../audio_levels/AudioLevels");
  5787. var Avatar = require("../avatar/Avatar");
  5788. var Chat = require("../side_pannels/chat/Chat");
  5789. var ContactList = require("../side_pannels/contactlist/ContactList");
  5790. var UIUtil = require("../util/UIUtil");
  5791. var ConnectionIndicator = require("./ConnectionIndicator");
  5792. var NicknameHandler = require("../util/NicknameHandler");
  5793. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  5794. var UIEvents = require("../../../service/UI/UIEvents");
  5795. var currentDominantSpeaker = null;
  5796. var lastNCount = config.channelLastN;
  5797. var localLastNCount = config.channelLastN;
  5798. var localLastNSet = [];
  5799. var lastNEndpointsCache = [];
  5800. var lastNPickupJid = null;
  5801. var largeVideoState = {
  5802. updateInProgress: false,
  5803. newSrc: ''
  5804. };
  5805. var eventEmitter = null;
  5806. /**
  5807. * Currently focused video "src"(displayed in large video).
  5808. * @type {String}
  5809. */
  5810. var focusedVideoInfo = null;
  5811. /**
  5812. * Indicates if we have muted our audio before the conference has started.
  5813. * @type {boolean}
  5814. */
  5815. var preMuted = false;
  5816. var mutedAudios = {};
  5817. var flipXLocalVideo = true;
  5818. var currentVideoWidth = null;
  5819. var currentVideoHeight = null;
  5820. var localVideoSrc = null;
  5821. function videoactive( videoelem) {
  5822. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  5823. // ignore mixedmslabela0 and v0
  5824. videoelem.show();
  5825. VideoLayout.resizeThumbnails();
  5826. var videoParent = videoelem.parent();
  5827. var parentResourceJid = null;
  5828. if (videoParent)
  5829. parentResourceJid
  5830. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  5831. // Update the large video to the last added video only if there's no
  5832. // current dominant, focused speaker or prezi playing or update it to
  5833. // the current dominant speaker.
  5834. if ((!focusedVideoInfo &&
  5835. !VideoLayout.getDominantSpeakerResourceJid() &&
  5836. !require("../prezi/Prezi").isPresentationVisible()) ||
  5837. (parentResourceJid &&
  5838. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  5839. VideoLayout.updateLargeVideo(
  5840. APP.RTC.getVideoSrc(videoelem[0]),
  5841. 1,
  5842. parentResourceJid);
  5843. }
  5844. VideoLayout.showModeratorIndicator();
  5845. }
  5846. }
  5847. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  5848. // XXX(gp) so, every call to this function is *always* preceded by a call
  5849. // to the RTC.attachMediaStream() function but that call is *not* followed
  5850. // by an update to the videoSrcToSsrc map!
  5851. //
  5852. // The above way of doing things results in video SRCs that don't correspond
  5853. // to any SSRC for a short period of time (to be more precise, for as long
  5854. // the waitForRemoteVideo takes to complete). This causes problems (see
  5855. // bellow).
  5856. //
  5857. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  5858. // a second time in here and only then update the videoSrcToSsrc map? Why
  5859. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  5860. // is called the first time? I actually do that in the lastN changed event
  5861. // handler because the "orphan" video SRC is causing troubles there. The
  5862. // purpose of this method would then be to fire the "videoactive.jingle".
  5863. //
  5864. // Food for though I guess :-)
  5865. if (selector.removed || !selector.parent().is(":visible")) {
  5866. console.warn("Media removed before had started", selector);
  5867. return;
  5868. }
  5869. if (stream.id === 'mixedmslabel') return;
  5870. if (selector[0].currentTime > 0) {
  5871. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  5872. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  5873. videoactive(selector);
  5874. } else {
  5875. setTimeout(function () {
  5876. waitForRemoteVideo(selector, ssrc, stream, jid);
  5877. }, 250);
  5878. }
  5879. }
  5880. /**
  5881. * Returns an array of the video horizontal and vertical indents,
  5882. * so that if fits its parent.
  5883. *
  5884. * @return an array with 2 elements, the horizontal indent and the vertical
  5885. * indent
  5886. */
  5887. function getCameraVideoPosition(videoWidth,
  5888. videoHeight,
  5889. videoSpaceWidth,
  5890. videoSpaceHeight) {
  5891. // Parent height isn't completely calculated when we position the video in
  5892. // full screen mode and this is why we use the screen height in this case.
  5893. // Need to think it further at some point and implement it properly.
  5894. var isFullScreen = document.fullScreen ||
  5895. document.mozFullScreen ||
  5896. document.webkitIsFullScreen;
  5897. if (isFullScreen)
  5898. videoSpaceHeight = window.innerHeight;
  5899. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5900. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  5901. return [horizontalIndent, verticalIndent];
  5902. }
  5903. /**
  5904. * Returns an array of the video horizontal and vertical indents.
  5905. * Centers horizontally and top aligns vertically.
  5906. *
  5907. * @return an array with 2 elements, the horizontal indent and the vertical
  5908. * indent
  5909. */
  5910. function getDesktopVideoPosition(videoWidth,
  5911. videoHeight,
  5912. videoSpaceWidth,
  5913. videoSpaceHeight) {
  5914. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5915. var verticalIndent = 0;// Top aligned
  5916. return [horizontalIndent, verticalIndent];
  5917. }
  5918. /**
  5919. * Returns an array of the video dimensions, so that it covers the screen.
  5920. * It leaves no empty areas, but some parts of the video might not be visible.
  5921. *
  5922. * @return an array with 2 elements, the video width and the video height
  5923. */
  5924. function getCameraVideoSize(videoWidth,
  5925. videoHeight,
  5926. videoSpaceWidth,
  5927. videoSpaceHeight) {
  5928. if (!videoWidth)
  5929. videoWidth = currentVideoWidth;
  5930. if (!videoHeight)
  5931. videoHeight = currentVideoHeight;
  5932. var aspectRatio = videoWidth / videoHeight;
  5933. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5934. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5935. if (availableWidth / aspectRatio < videoSpaceHeight) {
  5936. availableHeight = videoSpaceHeight;
  5937. availableWidth = availableHeight * aspectRatio;
  5938. }
  5939. if (availableHeight * aspectRatio < videoSpaceWidth) {
  5940. availableWidth = videoSpaceWidth;
  5941. availableHeight = availableWidth / aspectRatio;
  5942. }
  5943. return [availableWidth, availableHeight];
  5944. }
  5945. /**
  5946. * Sets the display name for the given video span id.
  5947. */
  5948. function setDisplayName(videoSpanId, displayName, key) {
  5949. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  5950. var defaultLocalDisplayName = APP.translation.generateTranslatonHTML(
  5951. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  5952. // If we already have a display name for this video.
  5953. if (nameSpan.length > 0) {
  5954. var nameSpanElement = nameSpan.get(0);
  5955. if (nameSpanElement.id === 'localDisplayName' &&
  5956. $('#localDisplayName').text() !== displayName) {
  5957. if (displayName && displayName.length > 0)
  5958. {
  5959. var meHTML = APP.translation.generateTranslatonHTML("me");
  5960. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  5961. }
  5962. else
  5963. $('#localDisplayName').html(defaultLocalDisplayName);
  5964. } else {
  5965. if (displayName && displayName.length > 0)
  5966. {
  5967. $('#' + videoSpanId + '_name').html(displayName);
  5968. }
  5969. else if (key && key.length > 0)
  5970. {
  5971. var nameHtml = APP.translation.generateTranslatonHTML(key);
  5972. $('#' + videoSpanId + '_name').html(nameHtml);
  5973. }
  5974. else
  5975. $('#' + videoSpanId + '_name').text(
  5976. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  5977. }
  5978. } else {
  5979. var editButton = null;
  5980. nameSpan = document.createElement('span');
  5981. nameSpan.className = 'displayname';
  5982. $('#' + videoSpanId)[0].appendChild(nameSpan);
  5983. if (videoSpanId === 'localVideoContainer') {
  5984. editButton = createEditDisplayNameButton();
  5985. if (displayName && displayName.length > 0) {
  5986. var meHTML = APP.translation.generateTranslatonHTML("me");
  5987. nameSpan.innerHTML = displayName + meHTML;
  5988. }
  5989. else
  5990. nameSpan.innerHTML = defaultLocalDisplayName;
  5991. }
  5992. else {
  5993. if (displayName && displayName.length > 0) {
  5994. nameSpan.innerText = displayName;
  5995. }
  5996. else
  5997. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  5998. }
  5999. if (!editButton) {
  6000. nameSpan.id = videoSpanId + '_name';
  6001. } else {
  6002. nameSpan.id = 'localDisplayName';
  6003. $('#' + videoSpanId)[0].appendChild(editButton);
  6004. //translates popover of edit button
  6005. APP.translation.translateElement($("a.displayname"));
  6006. var editableText = document.createElement('input');
  6007. editableText.className = 'displayname';
  6008. editableText.type = 'text';
  6009. editableText.id = 'editDisplayName';
  6010. if (displayName && displayName.length) {
  6011. editableText.value
  6012. = displayName;
  6013. }
  6014. var defaultNickname = APP.translation.translateString(
  6015. "defaultNickname", {name: "Jane Pink"});
  6016. editableText.setAttribute('style', 'display:none;');
  6017. editableText.setAttribute('data-18n',
  6018. '[placeholder]defaultNickname');
  6019. editableText.setAttribute("data-i18n-options",
  6020. JSON.stringify({name: "Jane Pink"}));
  6021. editableText.setAttribute("placeholder", defaultNickname);
  6022. $('#' + videoSpanId)[0].appendChild(editableText);
  6023. $('#localVideoContainer .displayname')
  6024. .bind("click", function (e) {
  6025. e.preventDefault();
  6026. e.stopPropagation();
  6027. $('#localDisplayName').hide();
  6028. $('#editDisplayName').show();
  6029. $('#editDisplayName').focus();
  6030. $('#editDisplayName').select();
  6031. $('#editDisplayName').one("focusout", function (e) {
  6032. VideoLayout.inputDisplayNameHandler(this.value);
  6033. });
  6034. $('#editDisplayName').on('keydown', function (e) {
  6035. if (e.keyCode === 13) {
  6036. e.preventDefault();
  6037. VideoLayout.inputDisplayNameHandler(this.value);
  6038. }
  6039. });
  6040. });
  6041. }
  6042. }
  6043. }
  6044. /**
  6045. * Gets the selector of video thumbnail container for the user identified by
  6046. * given <tt>userJid</tt>
  6047. * @param resourceJid user's Jid for whom we want to get the video container.
  6048. */
  6049. function getParticipantContainer(resourceJid)
  6050. {
  6051. if (!resourceJid)
  6052. return null;
  6053. if (resourceJid === APP.xmpp.myResource())
  6054. return $("#localVideoContainer");
  6055. else
  6056. return $("#participant_" + resourceJid);
  6057. }
  6058. /**
  6059. * Sets the size and position of the given video element.
  6060. *
  6061. * @param video the video element to position
  6062. * @param width the desired video width
  6063. * @param height the desired video height
  6064. * @param horizontalIndent the left and right indent
  6065. * @param verticalIndent the top and bottom indent
  6066. */
  6067. function positionVideo(video,
  6068. width,
  6069. height,
  6070. horizontalIndent,
  6071. verticalIndent) {
  6072. video.width(width);
  6073. video.height(height);
  6074. video.css({ top: verticalIndent + 'px',
  6075. bottom: verticalIndent + 'px',
  6076. left: horizontalIndent + 'px',
  6077. right: horizontalIndent + 'px'});
  6078. }
  6079. /**
  6080. * Adds the remote video menu element for the given <tt>jid</tt> in the
  6081. * given <tt>parentElement</tt>.
  6082. *
  6083. * @param jid the jid indicating the video for which we're adding a menu.
  6084. * @param parentElement the parent element where this menu will be added
  6085. */
  6086. function addRemoteVideoMenu(jid, parentElement) {
  6087. var spanElement = document.createElement('span');
  6088. spanElement.className = 'remotevideomenu';
  6089. parentElement.appendChild(spanElement);
  6090. var menuElement = document.createElement('i');
  6091. menuElement.className = 'fa fa-angle-down';
  6092. menuElement.title = 'Remote user controls';
  6093. spanElement.appendChild(menuElement);
  6094. // <ul class="popupmenu">
  6095. // <li><a href="#">Mute</a></li>
  6096. // <li><a href="#">Eject</a></li>
  6097. // </ul>
  6098. var popupmenuElement = document.createElement('ul');
  6099. popupmenuElement.className = 'popupmenu';
  6100. popupmenuElement.id
  6101. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  6102. spanElement.appendChild(popupmenuElement);
  6103. var muteMenuItem = document.createElement('li');
  6104. var muteLinkItem = document.createElement('a');
  6105. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  6106. if (!mutedAudios[jid]) {
  6107. muteLinkItem.innerHTML = mutedIndicator +
  6108. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6109. muteLinkItem.className = 'mutelink';
  6110. }
  6111. else {
  6112. muteLinkItem.innerHTML = mutedIndicator +
  6113. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6114. muteLinkItem.className = 'mutelink disabled';
  6115. }
  6116. muteLinkItem.onclick = function(){
  6117. if ($(this).attr('disabled') != undefined) {
  6118. event.preventDefault();
  6119. }
  6120. var isMute = mutedAudios[jid] == true;
  6121. APP.xmpp.setMute(jid, !isMute);
  6122. popupmenuElement.setAttribute('style', 'display:none;');
  6123. if (isMute) {
  6124. this.innerHTML = mutedIndicator +
  6125. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6126. this.className = 'mutelink disabled';
  6127. }
  6128. else {
  6129. this.innerHTML = mutedIndicator +
  6130. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6131. this.className = 'mutelink';
  6132. }
  6133. };
  6134. muteMenuItem.appendChild(muteLinkItem);
  6135. popupmenuElement.appendChild(muteMenuItem);
  6136. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  6137. var ejectMenuItem = document.createElement('li');
  6138. var ejectLinkItem = document.createElement('a');
  6139. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  6140. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  6141. ejectLinkItem.onclick = function(){
  6142. APP.xmpp.eject(jid);
  6143. popupmenuElement.setAttribute('style', 'display:none;');
  6144. };
  6145. ejectMenuItem.appendChild(ejectLinkItem);
  6146. popupmenuElement.appendChild(ejectMenuItem);
  6147. var paddingSpan = document.createElement('span');
  6148. paddingSpan.className = 'popupmenuPadding';
  6149. popupmenuElement.appendChild(paddingSpan);
  6150. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  6151. }
  6152. /**
  6153. * Removes remote video menu element from video element identified by
  6154. * given <tt>videoElementId</tt>.
  6155. *
  6156. * @param videoElementId the id of local or remote video element.
  6157. */
  6158. function removeRemoteVideoMenu(videoElementId) {
  6159. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  6160. if (menuSpan.length) {
  6161. menuSpan.remove();
  6162. }
  6163. }
  6164. /**
  6165. * Updates the data for the indicator
  6166. * @param id the id of the indicator
  6167. * @param percent the percent for connection quality
  6168. * @param object the data
  6169. */
  6170. function updateStatsIndicator(id, percent, object) {
  6171. if(VideoLayout.connectionIndicators[id])
  6172. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  6173. }
  6174. /**
  6175. * Returns an array of the video dimensions, so that it keeps it's aspect
  6176. * ratio and fits available area with it's larger dimension. This method
  6177. * ensures that whole video will be visible and can leave empty areas.
  6178. *
  6179. * @return an array with 2 elements, the video width and the video height
  6180. */
  6181. function getDesktopVideoSize(videoWidth,
  6182. videoHeight,
  6183. videoSpaceWidth,
  6184. videoSpaceHeight) {
  6185. if (!videoWidth)
  6186. videoWidth = currentVideoWidth;
  6187. if (!videoHeight)
  6188. videoHeight = currentVideoHeight;
  6189. var aspectRatio = videoWidth / videoHeight;
  6190. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6191. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6192. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  6193. if (availableWidth / aspectRatio >= videoSpaceHeight)
  6194. {
  6195. availableHeight = videoSpaceHeight;
  6196. availableWidth = availableHeight * aspectRatio;
  6197. }
  6198. if (availableHeight * aspectRatio >= videoSpaceWidth)
  6199. {
  6200. availableWidth = videoSpaceWidth;
  6201. availableHeight = availableWidth / aspectRatio;
  6202. }
  6203. return [availableWidth, availableHeight];
  6204. }
  6205. /**
  6206. * Creates the edit display name button.
  6207. *
  6208. * @returns the edit button
  6209. */
  6210. function createEditDisplayNameButton() {
  6211. var editButton = document.createElement('a');
  6212. editButton.className = 'displayname';
  6213. UIUtil.setTooltip(editButton,
  6214. "videothumbnail.editnickname",
  6215. "top");
  6216. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  6217. return editButton;
  6218. }
  6219. /**
  6220. * Creates the element indicating the moderator(owner) of the conference.
  6221. *
  6222. * @param parentElement the parent element where the owner indicator will
  6223. * be added
  6224. */
  6225. function createModeratorIndicatorElement(parentElement) {
  6226. var moderatorIndicator = document.createElement('i');
  6227. moderatorIndicator.className = 'fa fa-star';
  6228. parentElement.appendChild(moderatorIndicator);
  6229. UIUtil.setTooltip(parentElement,
  6230. "videothumbnail.moderator",
  6231. "top");
  6232. }
  6233. var VideoLayout = (function (my) {
  6234. my.connectionIndicators = {};
  6235. // By default we use camera
  6236. my.getVideoSize = getCameraVideoSize;
  6237. my.getVideoPosition = getCameraVideoPosition;
  6238. my.init = function (emitter) {
  6239. // Listen for large video size updates
  6240. document.getElementById('largeVideo')
  6241. .addEventListener('loadedmetadata', function (e) {
  6242. currentVideoWidth = this.videoWidth;
  6243. currentVideoHeight = this.videoHeight;
  6244. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6245. });
  6246. eventEmitter = emitter;
  6247. };
  6248. my.isInLastN = function(resource) {
  6249. return lastNCount < 0 // lastN is disabled, return true
  6250. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  6251. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  6252. };
  6253. my.changeLocalStream = function (stream) {
  6254. VideoLayout.changeLocalVideo(stream);
  6255. };
  6256. my.changeLocalAudio = function(stream) {
  6257. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  6258. document.getElementById('localAudio').autoplay = true;
  6259. document.getElementById('localAudio').volume = 0;
  6260. if (preMuted) {
  6261. if(!APP.UI.setAudioMuted(true))
  6262. {
  6263. preMuted = mute;
  6264. }
  6265. preMuted = false;
  6266. }
  6267. };
  6268. my.changeLocalVideo = function(stream) {
  6269. var flipX = true;
  6270. if(stream.videoType == "screen")
  6271. flipX = false;
  6272. var localVideo = document.createElement('video');
  6273. localVideo.id = 'localVideo_' +
  6274. APP.RTC.getStreamID(stream.getOriginalStream());
  6275. localVideo.autoplay = true;
  6276. localVideo.volume = 0; // is it required if audio is separated ?
  6277. localVideo.oncontextmenu = function () { return false; };
  6278. var localVideoContainer = document.getElementById('localVideoWrapper');
  6279. localVideoContainer.appendChild(localVideo);
  6280. // Set default display name.
  6281. setDisplayName('localVideoContainer');
  6282. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  6283. VideoLayout.connectionIndicators["localVideoContainer"]
  6284. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  6285. }
  6286. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  6287. var localVideoSelector = $('#' + localVideo.id);
  6288. function localVideoClick(event) {
  6289. event.stopPropagation();
  6290. VideoLayout.handleVideoThumbClicked(
  6291. APP.RTC.getVideoSrc(localVideo),
  6292. false,
  6293. APP.xmpp.myResource());
  6294. }
  6295. // Add click handler to both video and video wrapper elements in case
  6296. // there's no video.
  6297. localVideoSelector.click(localVideoClick);
  6298. $('#localVideoContainer').click(localVideoClick);
  6299. // Add hover handler
  6300. $('#localVideoContainer').hover(
  6301. function() {
  6302. VideoLayout.showDisplayName('localVideoContainer', true);
  6303. },
  6304. function() {
  6305. if (!VideoLayout.isLargeVideoVisible()
  6306. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6307. VideoLayout.showDisplayName('localVideoContainer', false);
  6308. }
  6309. );
  6310. // Add stream ended handler
  6311. stream.getOriginalStream().onended = function () {
  6312. localVideoContainer.removeChild(localVideo);
  6313. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  6314. };
  6315. // Flip video x axis if needed
  6316. flipXLocalVideo = flipX;
  6317. if (flipX) {
  6318. localVideoSelector.addClass("flipVideoX");
  6319. }
  6320. // Attach WebRTC stream
  6321. var videoStream = APP.simulcast.getLocalVideoStream();
  6322. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  6323. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  6324. var myResourceJid = APP.xmpp.myResource();
  6325. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  6326. myResourceJid);
  6327. };
  6328. /**
  6329. * Adds or removes icons for not available camera and microphone.
  6330. * @param resourceJid the jid of user
  6331. * @param devices available devices
  6332. */
  6333. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  6334. if(!devices)
  6335. return;
  6336. var container = null
  6337. if(!resourceJid)
  6338. {
  6339. container = $("#localVideoContainer")[0];
  6340. }
  6341. else
  6342. {
  6343. container = $("#participant_" + resourceJid)[0];
  6344. }
  6345. if(!container)
  6346. return;
  6347. $("#" + container.id + " > .noMic").remove();
  6348. $("#" + container.id + " > .noVideo").remove();
  6349. if(!devices.audio)
  6350. {
  6351. container.appendChild(document.createElement("div")).setAttribute("class","noMic");
  6352. }
  6353. if(!devices.video)
  6354. {
  6355. container.appendChild(document.createElement("div")).setAttribute("class","noVideo");
  6356. }
  6357. if(!devices.audio && !devices.video)
  6358. {
  6359. $("#" + container.id + " > .noMic").css("background-position", "75%");
  6360. $("#" + container.id + " > .noVideo").css("background-position", "25%");
  6361. $("#" + container.id + " > .noVideo").css("background-color", "transparent");
  6362. }
  6363. }
  6364. /**
  6365. * Checks if removed video is currently displayed and tries to display
  6366. * another one instead.
  6367. * @param removedVideoSrc src stream identifier of the video.
  6368. */
  6369. my.updateRemovedVideo = function(removedVideoSrc) {
  6370. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  6371. // this is currently displayed as large
  6372. // pick the last visible video in the row
  6373. // if nobody else is left, this picks the local video
  6374. var pick
  6375. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  6376. .get(0);
  6377. if (!pick) {
  6378. console.info("Last visible video no longer exists");
  6379. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  6380. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  6381. // Try local video
  6382. console.info("Fallback to local video...");
  6383. pick = $('#remoteVideos>span>span>video').get(0);
  6384. }
  6385. }
  6386. // mute if localvideo
  6387. if (pick) {
  6388. var container = pick.parentNode;
  6389. var jid = null;
  6390. if(container)
  6391. {
  6392. if(container.id == "localVideoWrapper")
  6393. {
  6394. jid = APP.xmpp.myResource();
  6395. }
  6396. else
  6397. {
  6398. jid = VideoLayout.getPeerContainerResourceJid(container);
  6399. }
  6400. }
  6401. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(pick), pick.volume, jid);
  6402. } else {
  6403. console.warn("Failed to elect large video");
  6404. }
  6405. }
  6406. };
  6407. my.onRemoteStreamAdded = function (stream) {
  6408. var container;
  6409. var remotes = document.getElementById('remoteVideos');
  6410. if (stream.peerjid) {
  6411. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6412. container = document.getElementById(
  6413. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6414. } else {
  6415. var id = stream.getOriginalStream().id;
  6416. if (id !== 'mixedmslabel'
  6417. // FIXME: default stream is added always with new focus
  6418. // (to be investigated)
  6419. && id !== 'default') {
  6420. console.error('can not associate stream',
  6421. id,
  6422. 'with a participant');
  6423. // We don't want to add it here since it will cause troubles
  6424. return;
  6425. }
  6426. // FIXME: for the mixed ms we dont need a video -- currently
  6427. container = document.createElement('span');
  6428. container.id = 'mixedstream';
  6429. container.className = 'videocontainer';
  6430. remotes.appendChild(container);
  6431. UIUtil.playSoundNotification('userJoined');
  6432. }
  6433. if (container) {
  6434. VideoLayout.addRemoteStreamElement( container,
  6435. stream.sid,
  6436. stream.getOriginalStream(),
  6437. stream.peerjid,
  6438. stream.ssrc);
  6439. }
  6440. }
  6441. my.getLargeVideoState = function () {
  6442. return largeVideoState;
  6443. };
  6444. /**
  6445. * Updates the large video with the given new video source.
  6446. */
  6447. my.updateLargeVideo = function(newSrc, vol, resourceJid) {
  6448. console.log('hover in', newSrc);
  6449. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc) {
  6450. $('#activeSpeaker').css('visibility', 'hidden');
  6451. // Due to the simulcast the localVideoSrc may have changed when the
  6452. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6453. // isVideoSrcDesktop methods will not function correctly.
  6454. //
  6455. // Also, again due to the simulcast, the updateLargeVideo method can
  6456. // be called multiple times almost simultaneously. Therefore, we
  6457. // store the state here and update only once.
  6458. largeVideoState.newSrc = newSrc;
  6459. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6460. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(
  6461. APP.xmpp.findJidFromResource(resourceJid));
  6462. if(largeVideoState.userResourceJid) {
  6463. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6464. } else {
  6465. largeVideoState.oldResourceJid = null;
  6466. }
  6467. largeVideoState.userResourceJid = resourceJid;
  6468. // Screen stream is already rotated
  6469. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6470. var userChanged = false;
  6471. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6472. userChanged = true;
  6473. // we want the notification to trigger even if userJid is undefined,
  6474. // or null.
  6475. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6476. largeVideoState.userResourceJid);
  6477. }
  6478. if (!largeVideoState.updateInProgress) {
  6479. largeVideoState.updateInProgress = true;
  6480. var doUpdate = function () {
  6481. Avatar.updateActiveSpeakerAvatarSrc(
  6482. APP.xmpp.findJidFromResource(
  6483. largeVideoState.userResourceJid));
  6484. if (!userChanged && largeVideoState.preload &&
  6485. largeVideoState.preload !== null &&
  6486. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  6487. {
  6488. console.info('Switching to preloaded video');
  6489. var attributes = $('#largeVideo').prop("attributes");
  6490. // loop through largeVideo attributes and apply them on
  6491. // preload.
  6492. $.each(attributes, function () {
  6493. if (this.name !== 'id' && this.name !== 'src') {
  6494. largeVideoState.preload.attr(this.name, this.value);
  6495. }
  6496. });
  6497. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  6498. $('#largeVideo').attr('id', 'previousLargeVideo');
  6499. largeVideoState.preload.attr('id', 'largeVideo');
  6500. $('#previousLargeVideo').remove();
  6501. largeVideoState.preload.on('loadedmetadata', function (e) {
  6502. currentVideoWidth = this.videoWidth;
  6503. currentVideoHeight = this.videoHeight;
  6504. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6505. });
  6506. largeVideoState.preload = null;
  6507. largeVideoState.preload_ssrc = 0;
  6508. } else {
  6509. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6510. }
  6511. var videoTransform = document.getElementById('largeVideo')
  6512. .style.webkitTransform;
  6513. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6514. document.getElementById('largeVideo').style.webkitTransform
  6515. = "scaleX(-1)";
  6516. }
  6517. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6518. document.getElementById('largeVideo').style.webkitTransform
  6519. = "none";
  6520. }
  6521. // Change the way we'll be measuring and positioning large video
  6522. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6523. ? getDesktopVideoSize
  6524. : getCameraVideoSize;
  6525. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6526. ? getDesktopVideoPosition
  6527. : getCameraVideoPosition;
  6528. // Only if the large video is currently visible.
  6529. // Disable previous dominant speaker video.
  6530. if (largeVideoState.oldResourceJid) {
  6531. VideoLayout.enableDominantSpeaker(
  6532. largeVideoState.oldResourceJid,
  6533. false);
  6534. }
  6535. // Enable new dominant speaker in the remote videos section.
  6536. if (largeVideoState.userResourceJid) {
  6537. VideoLayout.enableDominantSpeaker(
  6538. largeVideoState.userResourceJid,
  6539. true);
  6540. }
  6541. if (userChanged && largeVideoState.isVisible) {
  6542. // using "this" should be ok because we're called
  6543. // from within the fadeOut event.
  6544. $(this).fadeIn(300);
  6545. }
  6546. if(userChanged) {
  6547. Avatar.showUserAvatar(
  6548. APP.xmpp.findJidFromResource(
  6549. largeVideoState.oldResourceJid));
  6550. }
  6551. largeVideoState.updateInProgress = false;
  6552. };
  6553. if (userChanged) {
  6554. $('#largeVideo').fadeOut(300, doUpdate);
  6555. } else {
  6556. doUpdate();
  6557. }
  6558. }
  6559. } else {
  6560. Avatar.showUserAvatar(
  6561. APP.xmpp.findJidFromResource(
  6562. largeVideoState.userResourceJid));
  6563. }
  6564. };
  6565. my.handleVideoThumbClicked = function(videoSrc,
  6566. noPinnedEndpointChangedEvent,
  6567. resourceJid) {
  6568. // Restore style for previously focused video
  6569. var oldContainer = null;
  6570. if(focusedVideoInfo) {
  6571. var focusResourceJid = focusedVideoInfo.resourceJid;
  6572. oldContainer = getParticipantContainer(focusResourceJid);
  6573. }
  6574. if (oldContainer) {
  6575. oldContainer.removeClass("videoContainerFocused");
  6576. }
  6577. // Unlock current focused.
  6578. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6579. {
  6580. focusedVideoInfo = null;
  6581. var dominantSpeakerVideo = null;
  6582. // Enable the currently set dominant speaker.
  6583. if (currentDominantSpeaker) {
  6584. dominantSpeakerVideo
  6585. = $('#participant_' + currentDominantSpeaker + '>video')
  6586. .get(0);
  6587. if (dominantSpeakerVideo) {
  6588. VideoLayout.updateLargeVideo(
  6589. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6590. 1,
  6591. currentDominantSpeaker);
  6592. }
  6593. }
  6594. if (!noPinnedEndpointChangedEvent) {
  6595. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6596. }
  6597. return;
  6598. }
  6599. // Lock new video
  6600. focusedVideoInfo = {
  6601. src: videoSrc,
  6602. resourceJid: resourceJid
  6603. };
  6604. // Update focused/pinned interface.
  6605. if (resourceJid)
  6606. {
  6607. var container = getParticipantContainer(resourceJid);
  6608. container.addClass("videoContainerFocused");
  6609. if (!noPinnedEndpointChangedEvent) {
  6610. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6611. }
  6612. }
  6613. if ($('#largeVideo').attr('src') === videoSrc &&
  6614. VideoLayout.isLargeVideoOnTop()) {
  6615. return;
  6616. }
  6617. // Triggers a "video.selected" event. The "false" parameter indicates
  6618. // this isn't a prezi.
  6619. $(document).trigger("video.selected", [false]);
  6620. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6621. $('audio').each(function (idx, el) {
  6622. if (el.id.indexOf('mixedmslabel') !== -1) {
  6623. el.volume = 0;
  6624. el.volume = 1;
  6625. }
  6626. });
  6627. };
  6628. /**
  6629. * Positions the large video.
  6630. *
  6631. * @param videoWidth the stream video width
  6632. * @param videoHeight the stream video height
  6633. */
  6634. my.positionLarge = function (videoWidth, videoHeight) {
  6635. var videoSpaceWidth = $('#videospace').width();
  6636. var videoSpaceHeight = window.innerHeight;
  6637. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6638. videoHeight,
  6639. videoSpaceWidth,
  6640. videoSpaceHeight);
  6641. var largeVideoWidth = videoSize[0];
  6642. var largeVideoHeight = videoSize[1];
  6643. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6644. largeVideoHeight,
  6645. videoSpaceWidth,
  6646. videoSpaceHeight);
  6647. var horizontalIndent = videoPosition[0];
  6648. var verticalIndent = videoPosition[1];
  6649. positionVideo($('#largeVideo'),
  6650. largeVideoWidth,
  6651. largeVideoHeight,
  6652. horizontalIndent, verticalIndent);
  6653. };
  6654. /**
  6655. * Shows/hides the large video.
  6656. */
  6657. my.setLargeVideoVisible = function(isVisible) {
  6658. var resourceJid = largeVideoState.userResourceJid;
  6659. if (isVisible) {
  6660. $('#largeVideo').css({visibility: 'visible'});
  6661. $('.watermark').css({visibility: 'visible'});
  6662. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6663. }
  6664. else {
  6665. $('#largeVideo').css({visibility: 'hidden'});
  6666. $('#activeSpeaker').css('visibility', 'hidden');
  6667. $('.watermark').css({visibility: 'hidden'});
  6668. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6669. if(focusedVideoInfo) {
  6670. var focusResourceJid = focusedVideoInfo.resourceJid;
  6671. var oldContainer = getParticipantContainer(focusResourceJid);
  6672. if (oldContainer && oldContainer.length > 0) {
  6673. oldContainer.removeClass("videoContainerFocused");
  6674. }
  6675. focusedVideoInfo = null;
  6676. if(focusResourceJid) {
  6677. Avatar.showUserAvatar(
  6678. APP.xmpp.findJidFromResource(focusResourceJid));
  6679. }
  6680. }
  6681. }
  6682. };
  6683. /**
  6684. * Indicates if the large video is currently visible.
  6685. *
  6686. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6687. */
  6688. my.isLargeVideoVisible = function() {
  6689. return $('#largeVideo').is(':visible');
  6690. };
  6691. my.isLargeVideoOnTop = function () {
  6692. var Etherpad = require("../etherpad/Etherpad");
  6693. var Prezi = require("../prezi/Prezi");
  6694. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6695. };
  6696. /**
  6697. * Checks if container for participant identified by given peerJid exists
  6698. * in the document and creates it eventually.
  6699. *
  6700. * @param peerJid peer Jid to check.
  6701. * @param userId user email or id for setting the avatar
  6702. *
  6703. * @return Returns <tt>true</tt> if the peer container exists,
  6704. * <tt>false</tt> - otherwise
  6705. */
  6706. my.ensurePeerContainerExists = function(peerJid, userId) {
  6707. ContactList.ensureAddContact(peerJid, userId);
  6708. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6709. var videoSpanId = 'participant_' + resourceJid;
  6710. if (!$('#' + videoSpanId).length) {
  6711. var container =
  6712. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6713. Avatar.setUserAvatar(peerJid, userId);
  6714. // Set default display name.
  6715. setDisplayName(videoSpanId);
  6716. VideoLayout.connectionIndicators[videoSpanId] =
  6717. new ConnectionIndicator(container, peerJid, VideoLayout);
  6718. var nickfield = document.createElement('span');
  6719. nickfield.className = "nick";
  6720. nickfield.appendChild(document.createTextNode(resourceJid));
  6721. container.appendChild(nickfield);
  6722. // In case this is not currently in the last n we don't show it.
  6723. if (localLastNCount
  6724. && localLastNCount > 0
  6725. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  6726. showPeerContainer(resourceJid, 'hide');
  6727. }
  6728. else
  6729. VideoLayout.resizeThumbnails();
  6730. }
  6731. };
  6732. my.addRemoteVideoContainer = function(peerJid, spanId) {
  6733. var container = document.createElement('span');
  6734. container.id = spanId;
  6735. container.className = 'videocontainer';
  6736. var remotes = document.getElementById('remoteVideos');
  6737. remotes.appendChild(container);
  6738. // If the peerJid is null then this video span couldn't be directly
  6739. // associated with a participant (this could happen in the case of prezi).
  6740. if (APP.xmpp.isModerator() && peerJid !== null)
  6741. addRemoteVideoMenu(peerJid, container);
  6742. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  6743. return container;
  6744. };
  6745. /**
  6746. * Creates an audio or video stream element.
  6747. */
  6748. my.createStreamElement = function (sid, stream) {
  6749. var isVideo = stream.getVideoTracks().length > 0;
  6750. var element = isVideo
  6751. ? document.createElement('video')
  6752. : document.createElement('audio');
  6753. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  6754. + sid + '_' + APP.RTC.getStreamID(stream);
  6755. element.id = id;
  6756. element.autoplay = true;
  6757. element.oncontextmenu = function () { return false; };
  6758. return element;
  6759. };
  6760. my.addRemoteStreamElement
  6761. = function (container, sid, stream, peerJid, thessrc) {
  6762. var newElementId = null;
  6763. var isVideo = stream.getVideoTracks().length > 0;
  6764. if (container) {
  6765. var streamElement = VideoLayout.createStreamElement(sid, stream);
  6766. newElementId = streamElement.id;
  6767. container.appendChild(streamElement);
  6768. var sel = $('#' + newElementId);
  6769. sel.hide();
  6770. // If the container is currently visible we attach the stream.
  6771. if (!isVideo
  6772. || (container.offsetParent !== null && isVideo)) {
  6773. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6774. APP.RTC.attachMediaStream(sel, videoStream);
  6775. if (isVideo)
  6776. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  6777. }
  6778. stream.onended = function () {
  6779. console.log('stream ended', this);
  6780. VideoLayout.removeRemoteStreamElement(
  6781. stream, isVideo, container);
  6782. // NOTE(gp) it seems that under certain circumstances, the
  6783. // onended event is not fired and thus the contact list is not
  6784. // updated.
  6785. //
  6786. // The onended event of a stream should be fired when the SSRCs
  6787. // corresponding to that stream are removed from the SDP; but
  6788. // this doesn't seem to always be the case, resulting in ghost
  6789. // contacts.
  6790. //
  6791. // In an attempt to fix the ghost contacts problem, I'm moving
  6792. // the removeContact() method call in app.js, inside the
  6793. // 'muc.left' event handler.
  6794. //if (peerJid)
  6795. // ContactList.removeContact(peerJid);
  6796. };
  6797. // Add click handler.
  6798. container.onclick = function (event) {
  6799. /*
  6800. * FIXME It turns out that videoThumb may not exist (if there is
  6801. * no actual video).
  6802. */
  6803. var videoThumb = $('#' + container.id + '>video').get(0);
  6804. if (videoThumb) {
  6805. VideoLayout.handleVideoThumbClicked(
  6806. APP.RTC.getVideoSrc(videoThumb),
  6807. false,
  6808. Strophe.getResourceFromJid(peerJid));
  6809. }
  6810. event.stopPropagation();
  6811. event.preventDefault();
  6812. return false;
  6813. };
  6814. // Add hover handler
  6815. $(container).hover(
  6816. function() {
  6817. VideoLayout.showDisplayName(container.id, true);
  6818. },
  6819. function() {
  6820. var videoSrc = null;
  6821. if ($('#' + container.id + '>video')
  6822. && $('#' + container.id + '>video').length > 0) {
  6823. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  6824. }
  6825. // If the video has been "pinned" by the user we want to
  6826. // keep the display name on place.
  6827. if (!VideoLayout.isLargeVideoVisible()
  6828. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6829. VideoLayout.showDisplayName(container.id, false);
  6830. }
  6831. );
  6832. }
  6833. return newElementId;
  6834. };
  6835. /**
  6836. * Removes the remote stream element corresponding to the given stream and
  6837. * parent container.
  6838. *
  6839. * @param stream the stream
  6840. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  6841. * @param container
  6842. */
  6843. my.removeRemoteStreamElement = function (stream, isVideo, container) {
  6844. if (!container)
  6845. return;
  6846. var select = null;
  6847. var removedVideoSrc = null;
  6848. if (isVideo) {
  6849. select = $('#' + container.id + '>video');
  6850. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  6851. }
  6852. else
  6853. select = $('#' + container.id + '>audio');
  6854. // Mark video as removed to cancel waiting loop(if video is removed
  6855. // before has started)
  6856. select.removed = true;
  6857. select.remove();
  6858. var audioCount = $('#' + container.id + '>audio').length;
  6859. var videoCount = $('#' + container.id + '>video').length;
  6860. if (!audioCount && !videoCount) {
  6861. console.log("Remove whole user", container.id);
  6862. if(VideoLayout.connectionIndicators[container.id])
  6863. VideoLayout.connectionIndicators[container.id].remove();
  6864. // Remove whole container
  6865. container.remove();
  6866. UIUtil.playSoundNotification('userLeft');
  6867. VideoLayout.resizeThumbnails();
  6868. }
  6869. if (removedVideoSrc)
  6870. VideoLayout.updateRemovedVideo(removedVideoSrc);
  6871. };
  6872. /**
  6873. * Show/hide peer container for the given resourceJid.
  6874. */
  6875. function showPeerContainer(resourceJid, state) {
  6876. var peerContainer = $('#participant_' + resourceJid);
  6877. if (!peerContainer)
  6878. return;
  6879. var isHide = state === 'hide';
  6880. var resizeThumbnails = false;
  6881. if (!isHide) {
  6882. if (!peerContainer.is(':visible')) {
  6883. resizeThumbnails = true;
  6884. peerContainer.show();
  6885. }
  6886. var jid = APP.xmpp.findJidFromResource(resourceJid);
  6887. if (state == 'show')
  6888. {
  6889. // peerContainer.css('-webkit-filter', '');
  6890. Avatar.showUserAvatar(jid, false);
  6891. }
  6892. else // if (state == 'avatar')
  6893. {
  6894. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  6895. Avatar.showUserAvatar(jid, true);
  6896. }
  6897. }
  6898. else if (peerContainer.is(':visible') && isHide)
  6899. {
  6900. resizeThumbnails = true;
  6901. peerContainer.hide();
  6902. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  6903. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  6904. }
  6905. if (resizeThumbnails) {
  6906. VideoLayout.resizeThumbnails();
  6907. }
  6908. // We want to be able to pin a participant from the contact list, even
  6909. // if he's not in the lastN set!
  6910. // ContactList.setClickable(resourceJid, !isHide);
  6911. };
  6912. my.inputDisplayNameHandler = function (name) {
  6913. NicknameHandler.setNickname(name);
  6914. if (!$('#localDisplayName').is(":visible")) {
  6915. if (NicknameHandler.getNickname())
  6916. {
  6917. var meHTML = APP.translation.generateTranslatonHTML("me");
  6918. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  6919. }
  6920. else
  6921. {
  6922. var defaultHTML = APP.translation.generateTranslatonHTML(
  6923. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6924. $('#localDisplayName')
  6925. .html(defaultHTML);
  6926. }
  6927. $('#localDisplayName').show();
  6928. }
  6929. $('#editDisplayName').hide();
  6930. };
  6931. /**
  6932. * Shows/hides the display name on the remote video.
  6933. * @param videoSpanId the identifier of the video span element
  6934. * @param isShow indicates if the display name should be shown or hidden
  6935. */
  6936. my.showDisplayName = function(videoSpanId, isShow) {
  6937. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  6938. if (isShow) {
  6939. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  6940. nameSpan.setAttribute("style", "display:inline-block;");
  6941. }
  6942. else {
  6943. if (nameSpan)
  6944. nameSpan.setAttribute("style", "display:none;");
  6945. }
  6946. };
  6947. /**
  6948. * Shows the presence status message for the given video.
  6949. */
  6950. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  6951. if (!$('#' + videoSpanId).length) {
  6952. // No container
  6953. return;
  6954. }
  6955. var statusSpan = $('#' + videoSpanId + '>span.status');
  6956. if (!statusSpan.length) {
  6957. //Add status span
  6958. statusSpan = document.createElement('span');
  6959. statusSpan.className = 'status';
  6960. statusSpan.id = videoSpanId + '_status';
  6961. $('#' + videoSpanId)[0].appendChild(statusSpan);
  6962. statusSpan = $('#' + videoSpanId + '>span.status');
  6963. }
  6964. // Display status
  6965. if (statusMsg && statusMsg.length) {
  6966. $('#' + videoSpanId + '_status').text(statusMsg);
  6967. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  6968. }
  6969. else {
  6970. // Hide
  6971. statusSpan.get(0).setAttribute("style", "display:none;");
  6972. }
  6973. };
  6974. /**
  6975. * Shows a visual indicator for the moderator of the conference.
  6976. */
  6977. my.showModeratorIndicator = function () {
  6978. var isModerator = APP.xmpp.isModerator();
  6979. if (isModerator) {
  6980. var indicatorSpan = $('#localVideoContainer .focusindicator');
  6981. if (indicatorSpan.children().length === 0)
  6982. {
  6983. createModeratorIndicatorElement(indicatorSpan[0]);
  6984. //translates text in focus indicator
  6985. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  6986. }
  6987. }
  6988. var members = APP.xmpp.getMembers();
  6989. Object.keys(members).forEach(function (jid) {
  6990. if (Strophe.getResourceFromJid(jid) === 'focus') {
  6991. // Skip server side focus
  6992. return;
  6993. }
  6994. var resourceJid = Strophe.getResourceFromJid(jid);
  6995. var videoSpanId = 'participant_' + resourceJid;
  6996. var videoContainer = document.getElementById(videoSpanId);
  6997. if (!videoContainer) {
  6998. console.error("No video container for " + jid);
  6999. return;
  7000. }
  7001. var member = members[jid];
  7002. if (member.role === 'moderator') {
  7003. // Remove menu if peer is moderator
  7004. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  7005. if (menuSpan.length) {
  7006. removeRemoteVideoMenu(videoSpanId);
  7007. }
  7008. // Show moderator indicator
  7009. var indicatorSpan
  7010. = $('#' + videoSpanId + ' .focusindicator');
  7011. if (!indicatorSpan || indicatorSpan.length === 0) {
  7012. indicatorSpan = document.createElement('span');
  7013. indicatorSpan.className = 'focusindicator';
  7014. videoContainer.appendChild(indicatorSpan);
  7015. createModeratorIndicatorElement(indicatorSpan);
  7016. //translates text in focus indicators
  7017. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  7018. }
  7019. } else if (isModerator) {
  7020. // We are moderator, but user is not - add menu
  7021. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  7022. addRemoteVideoMenu(
  7023. jid,
  7024. document.getElementById('participant_' + resourceJid));
  7025. }
  7026. }
  7027. });
  7028. };
  7029. /**
  7030. * Shows video muted indicator over small videos.
  7031. */
  7032. my.showVideoIndicator = function(videoSpanId, isMuted) {
  7033. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  7034. if (isMuted === 'false') {
  7035. if (videoMutedSpan.length > 0) {
  7036. videoMutedSpan.remove();
  7037. }
  7038. }
  7039. else {
  7040. if(videoMutedSpan.length == 0) {
  7041. videoMutedSpan = document.createElement('span');
  7042. videoMutedSpan.className = 'videoMuted';
  7043. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  7044. var mutedIndicator = document.createElement('i');
  7045. mutedIndicator.className = 'icon-camera-disabled';
  7046. UIUtil.setTooltip(mutedIndicator,
  7047. "videothumbnail.videomute",
  7048. "top");
  7049. videoMutedSpan.appendChild(mutedIndicator);
  7050. //translate texts for muted indicator
  7051. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  7052. }
  7053. VideoLayout.updateMutePosition(videoSpanId);
  7054. }
  7055. };
  7056. my.updateMutePosition = function (videoSpanId) {
  7057. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  7058. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  7059. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  7060. if(connectionIndicator.length > 0
  7061. && connectionIndicator[0].style.display != "none") {
  7062. audioMutedSpan.css({right: "23px"});
  7063. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  7064. }
  7065. else
  7066. {
  7067. audioMutedSpan.css({right: "0px"});
  7068. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  7069. }
  7070. }
  7071. /**
  7072. * Shows audio muted indicator over small videos.
  7073. * @param {string} isMuted
  7074. */
  7075. my.showAudioIndicator = function(videoSpanId, isMuted) {
  7076. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  7077. if (isMuted === 'false') {
  7078. if (audioMutedSpan.length > 0) {
  7079. audioMutedSpan.popover('hide');
  7080. audioMutedSpan.remove();
  7081. }
  7082. }
  7083. else {
  7084. if(audioMutedSpan.length == 0 ) {
  7085. audioMutedSpan = document.createElement('span');
  7086. audioMutedSpan.className = 'audioMuted';
  7087. UIUtil.setTooltip(audioMutedSpan,
  7088. "videothumbnail.mute",
  7089. "top");
  7090. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  7091. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  7092. var mutedIndicator = document.createElement('i');
  7093. mutedIndicator.className = 'icon-mic-disabled';
  7094. audioMutedSpan.appendChild(mutedIndicator);
  7095. }
  7096. VideoLayout.updateMutePosition(videoSpanId);
  7097. }
  7098. };
  7099. /*
  7100. * Shows or hides the audio muted indicator over the local thumbnail video.
  7101. * @param {boolean} isMuted
  7102. */
  7103. my.showLocalAudioIndicator = function(isMuted) {
  7104. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  7105. };
  7106. /**
  7107. * Resizes the large video container.
  7108. */
  7109. my.resizeLargeVideoContainer = function () {
  7110. Chat.resizeChat();
  7111. var availableHeight = window.innerHeight;
  7112. var availableWidth = UIUtil.getAvailableVideoWidth();
  7113. if (availableWidth < 0 || availableHeight < 0) return;
  7114. $('#videospace').width(availableWidth);
  7115. $('#videospace').height(availableHeight);
  7116. $('#largeVideoContainer').width(availableWidth);
  7117. $('#largeVideoContainer').height(availableHeight);
  7118. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7119. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7120. $('#activeSpeaker').css('top', top);
  7121. VideoLayout.resizeThumbnails();
  7122. };
  7123. /**
  7124. * Resizes thumbnails.
  7125. */
  7126. my.resizeThumbnails = function() {
  7127. var videoSpaceWidth = $('#remoteVideos').width();
  7128. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  7129. var width = thumbnailSize[0];
  7130. var height = thumbnailSize[1];
  7131. // size videos so that while keeping AR and max height, we have a
  7132. // nice fit
  7133. $('#remoteVideos').height(height);
  7134. $('#remoteVideos>span').width(width);
  7135. $('#remoteVideos>span').height(height);
  7136. $('.userAvatar').css('left', (width - height) / 2);
  7137. $(document).trigger("remotevideo.resized", [width, height]);
  7138. };
  7139. /**
  7140. * Enables the dominant speaker UI.
  7141. *
  7142. * @param resourceJid the jid indicating the video element to
  7143. * activate/deactivate
  7144. * @param isEnable indicates if the dominant speaker should be enabled or
  7145. * disabled
  7146. */
  7147. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  7148. var videoSpanId = null;
  7149. var videoContainerId = null;
  7150. if (resourceJid
  7151. === APP.xmpp.myResource()) {
  7152. videoSpanId = 'localVideoWrapper';
  7153. videoContainerId = 'localVideoContainer';
  7154. }
  7155. else {
  7156. videoSpanId = 'participant_' + resourceJid;
  7157. videoContainerId = videoSpanId;
  7158. }
  7159. var displayName = resourceJid;
  7160. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  7161. if (nameSpan.length > 0)
  7162. displayName = nameSpan.html();
  7163. console.log("UI enable dominant speaker",
  7164. displayName,
  7165. resourceJid,
  7166. isEnable);
  7167. videoSpan = document.getElementById(videoContainerId);
  7168. if (!videoSpan) {
  7169. return;
  7170. }
  7171. var video = $('#' + videoSpanId + '>video');
  7172. if (video && video.length > 0) {
  7173. if (isEnable) {
  7174. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  7175. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  7176. if (!videoSpan.classList.contains("dominantspeaker"))
  7177. videoSpan.classList.add("dominantspeaker");
  7178. }
  7179. else {
  7180. VideoLayout.showDisplayName(videoContainerId, false);
  7181. if (videoSpan.classList.contains("dominantspeaker"))
  7182. videoSpan.classList.remove("dominantspeaker");
  7183. }
  7184. Avatar.showUserAvatar(
  7185. APP.xmpp.findJidFromResource(resourceJid));
  7186. }
  7187. };
  7188. /**
  7189. * Calculates the thumbnail size.
  7190. *
  7191. * @param videoSpaceWidth the width of the video space
  7192. */
  7193. my.calculateThumbnailSize = function (videoSpaceWidth) {
  7194. // Calculate the available height, which is the inner window height minus
  7195. // 39px for the header minus 2px for the delimiter lines on the top and
  7196. // bottom of the large video, minus the 36px space inside the remoteVideos
  7197. // container used for highlighting shadow.
  7198. var availableHeight = 100;
  7199. var numvids = $('#remoteVideos>span:visible').length;
  7200. if (localLastNCount && localLastNCount > 0) {
  7201. numvids = Math.min(localLastNCount + 1, numvids);
  7202. }
  7203. // Remove the 3px borders arround videos and border around the remote
  7204. // videos area and the 4 pixels between the local video and the others
  7205. //TODO: Find out where the 4 pixels come from and remove them
  7206. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  7207. var availableWidth = availableWinWidth / numvids;
  7208. var aspectRatio = 16.0 / 9.0;
  7209. var maxHeight = Math.min(160, availableHeight);
  7210. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  7211. if (availableHeight < availableWidth / aspectRatio) {
  7212. availableWidth = Math.floor(availableHeight * aspectRatio);
  7213. }
  7214. return [availableWidth, availableHeight];
  7215. };
  7216. /**
  7217. * Updates the remote video menu.
  7218. *
  7219. * @param jid the jid indicating the video for which we're adding a menu.
  7220. * @param isMuted indicates the current mute state
  7221. */
  7222. my.updateRemoteVideoMenu = function(jid, isMuted) {
  7223. var muteMenuItem
  7224. = $('#remote_popupmenu_'
  7225. + Strophe.getResourceFromJid(jid)
  7226. + '>li>a.mutelink');
  7227. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  7228. if (muteMenuItem.length) {
  7229. var muteLink = muteMenuItem.get(0);
  7230. if (isMuted === 'true') {
  7231. muteLink.innerHTML = mutedIndicator + ' Muted';
  7232. muteLink.className = 'mutelink disabled';
  7233. }
  7234. else {
  7235. muteLink.innerHTML = mutedIndicator + ' Mute';
  7236. muteLink.className = 'mutelink';
  7237. }
  7238. }
  7239. };
  7240. /**
  7241. * Returns the current dominant speaker resource jid.
  7242. */
  7243. my.getDominantSpeakerResourceJid = function () {
  7244. return currentDominantSpeaker;
  7245. };
  7246. /**
  7247. * Returns the corresponding resource jid to the given peer container
  7248. * DOM element.
  7249. *
  7250. * @return the corresponding resource jid to the given peer container
  7251. * DOM element
  7252. */
  7253. my.getPeerContainerResourceJid = function (containerElement) {
  7254. var i = containerElement.id.indexOf('participant_');
  7255. if (i >= 0)
  7256. return containerElement.id.substring(i + 12);
  7257. };
  7258. /**
  7259. * On contact list item clicked.
  7260. */
  7261. $(ContactList).bind('contactclicked', function(event, jid) {
  7262. if (!jid) {
  7263. return;
  7264. }
  7265. var resource = Strophe.getResourceFromJid(jid);
  7266. var videoContainer = $("#participant_" + resource);
  7267. if (videoContainer.length > 0) {
  7268. var videoThumb = $('video', videoContainer).get(0);
  7269. // It is not always the case that a videoThumb exists (if there is
  7270. // no actual video).
  7271. if (videoThumb) {
  7272. if (videoThumb.src && videoThumb.src != '') {
  7273. // We have a video src, great! Let's update the large video
  7274. // now.
  7275. VideoLayout.handleVideoThumbClicked(
  7276. videoThumb.src,
  7277. false,
  7278. Strophe.getResourceFromJid(jid));
  7279. } else {
  7280. // If we don't have a video src for jid, there's absolutely
  7281. // no point in calling handleVideoThumbClicked; Quite
  7282. // simply, it won't work because it needs an src to attach
  7283. // to the large video.
  7284. //
  7285. // Instead, we trigger the pinned endpoint changed event to
  7286. // let the bridge adjust its lastN set for myjid and store
  7287. // the pinned user in the lastNPickupJid variable to be
  7288. // picked up later by the lastN changed event handler.
  7289. lastNPickupJid = jid;
  7290. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  7291. Strophe.getResourceFromJid(jid));
  7292. }
  7293. } else if (jid == APP.xmpp.myJid()) {
  7294. $("#localVideoContainer").click();
  7295. }
  7296. }
  7297. });
  7298. /**
  7299. * On audio muted event.
  7300. */
  7301. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  7302. /*
  7303. // FIXME: but focus can not mute in this case ? - check
  7304. if (jid === xmpp.myJid()) {
  7305. // The local mute indicator is controlled locally
  7306. return;
  7307. }*/
  7308. var videoSpanId = null;
  7309. if (jid === APP.xmpp.myJid()) {
  7310. videoSpanId = 'localVideoContainer';
  7311. } else {
  7312. VideoLayout.ensurePeerContainerExists(jid);
  7313. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7314. }
  7315. mutedAudios[jid] = isMuted;
  7316. if (APP.xmpp.isModerator()) {
  7317. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  7318. }
  7319. if (videoSpanId)
  7320. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  7321. });
  7322. /**
  7323. * On video muted event.
  7324. */
  7325. $(document).bind('videomuted.muc', function (event, jid, value) {
  7326. var isMuted = (value === "true");
  7327. if(jid !== APP.xmpp.myJid() && !APP.RTC.muteRemoteVideoStream(jid, isMuted))
  7328. return;
  7329. Avatar.showUserAvatar(jid, isMuted);
  7330. var videoSpanId = null;
  7331. if (jid === APP.xmpp.myJid()) {
  7332. videoSpanId = 'localVideoContainer';
  7333. } else {
  7334. VideoLayout.ensurePeerContainerExists(jid);
  7335. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7336. }
  7337. if (videoSpanId)
  7338. VideoLayout.showVideoIndicator(videoSpanId, value);
  7339. });
  7340. /**
  7341. * Display name changed.
  7342. */
  7343. my.onDisplayNameChanged =
  7344. function (jid, displayName, status) {
  7345. if (jid === 'localVideoContainer'
  7346. || jid === APP.xmpp.myJid()) {
  7347. setDisplayName('localVideoContainer',
  7348. displayName);
  7349. } else {
  7350. VideoLayout.ensurePeerContainerExists(jid);
  7351. setDisplayName(
  7352. 'participant_' + Strophe.getResourceFromJid(jid),
  7353. displayName,
  7354. status);
  7355. }
  7356. };
  7357. /**
  7358. * On dominant speaker changed event.
  7359. */
  7360. my.onDominantSpeakerChanged = function (resourceJid) {
  7361. // We ignore local user events.
  7362. if (resourceJid
  7363. === APP.xmpp.myResource())
  7364. return;
  7365. var members = APP.xmpp.getMembers();
  7366. // Update the current dominant speaker.
  7367. if (resourceJid !== currentDominantSpeaker) {
  7368. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  7369. newSpeakerVideoSpanId = "participant_" + resourceJid;
  7370. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  7371. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  7372. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  7373. !members[currentJID].displayName)) {
  7374. setDisplayName(oldSpeakerVideoSpanId, null);
  7375. }
  7376. if(resourceJid && (!members || !members[newJID] ||
  7377. !members[newJID].displayName)) {
  7378. setDisplayName(newSpeakerVideoSpanId, null,
  7379. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  7380. }
  7381. currentDominantSpeaker = resourceJid;
  7382. } else {
  7383. return;
  7384. }
  7385. // Obtain container for new dominant speaker.
  7386. var container = document.getElementById(
  7387. 'participant_' + resourceJid);
  7388. // Local video will not have container found, but that's ok
  7389. // since we don't want to switch to local video.
  7390. if (container && !focusedVideoInfo)
  7391. {
  7392. var video = container.getElementsByTagName("video");
  7393. // Update the large video if the video source is already available,
  7394. // otherwise wait for the "videoactive.jingle" event.
  7395. if (video.length && video[0].currentTime > 0)
  7396. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  7397. }
  7398. };
  7399. /**
  7400. * On last N change event.
  7401. *
  7402. * @param lastNEndpoints the list of last N endpoints
  7403. * @param endpointsEnteringLastN the list currently entering last N
  7404. * endpoints
  7405. */
  7406. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7407. endpointsEnteringLastN,
  7408. stream) {
  7409. if (lastNCount !== lastNEndpoints.length)
  7410. lastNCount = lastNEndpoints.length;
  7411. lastNEndpointsCache = lastNEndpoints;
  7412. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7413. //
  7414. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7415. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7416. // so E sees them. C is only in E's local LastN set.
  7417. //
  7418. // If F starts talking and LastN = 3, then E should see thumbnails for
  7419. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7420. // enters E's local LastN ejecting C.
  7421. // Increase the local LastN set size, if necessary.
  7422. if (lastNCount > localLastNCount) {
  7423. localLastNCount = lastNCount;
  7424. }
  7425. // Update the local LastN set preserving the order in which the
  7426. // endpoints appeared in the LastN/local LastN set.
  7427. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7428. for (var i = 0; i < localLastNSet.length; i++) {
  7429. if (nextLocalLastNSet.length >= localLastNCount) {
  7430. break;
  7431. }
  7432. var resourceJid = localLastNSet[i];
  7433. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7434. nextLocalLastNSet.push(resourceJid);
  7435. }
  7436. }
  7437. localLastNSet = nextLocalLastNSet;
  7438. var updateLargeVideo = false;
  7439. // Handle LastN/local LastN changes.
  7440. $('#remoteVideos>span').each(function( index, element ) {
  7441. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7442. var isReceived = true;
  7443. if (resourceJid
  7444. && lastNEndpoints.indexOf(resourceJid) < 0
  7445. && localLastNSet.indexOf(resourceJid) < 0) {
  7446. console.log("Remove from last N", resourceJid);
  7447. showPeerContainer(resourceJid, 'hide');
  7448. isReceived = false;
  7449. } else if (resourceJid
  7450. && $('#participant_' + resourceJid).is(':visible')
  7451. && lastNEndpoints.indexOf(resourceJid) < 0
  7452. && localLastNSet.indexOf(resourceJid) >= 0) {
  7453. showPeerContainer(resourceJid, 'avatar');
  7454. isReceived = false;
  7455. }
  7456. if (!isReceived) {
  7457. // resourceJid has dropped out of the server side lastN set, so
  7458. // it is no longer being received. If resourceJid was being
  7459. // displayed in the large video we have to switch to another
  7460. // user.
  7461. var largeVideoResource = largeVideoState.userResourceJid;
  7462. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7463. updateLargeVideo = true;
  7464. }
  7465. }
  7466. });
  7467. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7468. endpointsEnteringLastN = lastNEndpoints;
  7469. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7470. endpointsEnteringLastN.forEach(function (resourceJid) {
  7471. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7472. showPeerContainer(resourceJid, 'show');
  7473. if (!isVisible) {
  7474. console.log("Add to last N", resourceJid);
  7475. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7476. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7477. var sel = $('#participant_' + resourceJid + '>video');
  7478. var videoStream = APP.simulcast.getReceivingVideoStream(
  7479. mediaStream.stream);
  7480. APP.RTC.attachMediaStream(sel, videoStream);
  7481. if (lastNPickupJid == mediaStream.peerjid) {
  7482. // Clean up the lastN pickup jid.
  7483. lastNPickupJid = null;
  7484. // Don't fire the events again, they've already
  7485. // been fired in the contact list click handler.
  7486. VideoLayout.handleVideoThumbClicked(
  7487. $(sel).attr('src'),
  7488. false,
  7489. Strophe.getResourceFromJid(mediaStream.peerjid));
  7490. updateLargeVideo = false;
  7491. }
  7492. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7493. }
  7494. })
  7495. }
  7496. // The endpoint that was being shown in the large video has dropped out
  7497. // of the lastN set and there was no lastN pickup jid. We need to update
  7498. // the large video now.
  7499. if (updateLargeVideo) {
  7500. var resource, container, src;
  7501. var myResource
  7502. = APP.xmpp.myResource();
  7503. // Find out which endpoint to show in the large video.
  7504. for (var i = 0; i < lastNEndpoints.length; i++) {
  7505. resource = lastNEndpoints[i];
  7506. if (!resource || resource === myResource)
  7507. continue;
  7508. container = $("#participant_" + resource);
  7509. if (container.length == 0)
  7510. continue;
  7511. src = $('video', container).attr('src');
  7512. if (!src)
  7513. continue;
  7514. // videoSrcToSsrc needs to be update for this call to succeed.
  7515. VideoLayout.updateLargeVideo(src);
  7516. break;
  7517. }
  7518. }
  7519. };
  7520. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  7521. endpointSimulcastLayers.forEach(function (esl) {
  7522. var resource = esl.endpoint;
  7523. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7524. // then ignore the event (= do not preload anything).
  7525. //
  7526. // The bridge could probably stop sending this message if it's for
  7527. // an endpoint that's not in lastN.
  7528. if (lastNCount != -1
  7529. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7530. return;
  7531. }
  7532. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7533. // Get session and stream from primary ssrc.
  7534. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7535. var sid = res.sid;
  7536. var electedStream = res.stream;
  7537. if (sid && electedStream) {
  7538. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7539. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7540. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  7541. if (preload) {
  7542. if (largeVideoState.preload)
  7543. {
  7544. $(largeVideoState.preload).remove();
  7545. }
  7546. console.info('Preloading remote video');
  7547. largeVideoState.preload = $('<video autoplay></video>');
  7548. // ssrcs are unique in an rtp session
  7549. largeVideoState.preload_ssrc = primarySSRC;
  7550. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  7551. }
  7552. } else {
  7553. console.error('Could not find a stream or a session.', sid, electedStream);
  7554. }
  7555. });
  7556. };
  7557. /**
  7558. * On simulcast layers changed event.
  7559. */
  7560. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  7561. endpointSimulcastLayers.forEach(function (esl) {
  7562. var resource = esl.endpoint;
  7563. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7564. // then ignore the event (= do not change large video/thumbnail
  7565. // SRCs).
  7566. //
  7567. // Note that even if we ignore the "changed" event in this event
  7568. // handler, the bridge must continue sending these events because
  7569. // the simulcast code in simulcast.js uses it to know what's going
  7570. // to be streamed by the bridge when/if the endpoint gets back into
  7571. // the lastN set.
  7572. if (lastNCount != -1
  7573. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7574. return;
  7575. }
  7576. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7577. // Get session and stream from primary ssrc.
  7578. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7579. var sid = res.sid;
  7580. var electedStream = res.stream;
  7581. if (sid && electedStream) {
  7582. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7583. console.info('Switching simulcast substream.');
  7584. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7585. var msidParts = msid.split(' ');
  7586. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  7587. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  7588. == largeVideoState.userResourceJid);
  7589. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  7590. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  7591. var electedStreamUrl;
  7592. if (largeVideoState.preload_ssrc == primarySSRC)
  7593. {
  7594. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  7595. }
  7596. else
  7597. {
  7598. if (largeVideoState.preload
  7599. && largeVideoState.preload != null) {
  7600. $(largeVideoState.preload).remove();
  7601. }
  7602. largeVideoState.preload_ssrc = 0;
  7603. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  7604. }
  7605. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  7606. if (updateLargeVideo) {
  7607. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  7608. Strophe.getResourceFromJid(jid));
  7609. }
  7610. if (updateFocusedVideoSrc) {
  7611. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  7612. }
  7613. var videoId;
  7614. if(resource == APP.xmpp.myResource())
  7615. {
  7616. videoId = "localVideoContainer";
  7617. }
  7618. else
  7619. {
  7620. videoId = "participant_" + resource;
  7621. }
  7622. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  7623. if(connectionIndicator)
  7624. connectionIndicator.updatePopoverData();
  7625. } else {
  7626. console.error('Could not find a stream or a sid.', sid, electedStream);
  7627. }
  7628. });
  7629. };
  7630. /**
  7631. * Updates local stats
  7632. * @param percent
  7633. * @param object
  7634. */
  7635. my.updateLocalConnectionStats = function (percent, object) {
  7636. var resolution = null;
  7637. if(object.resolution !== null)
  7638. {
  7639. resolution = object.resolution;
  7640. object.resolution = resolution[APP.xmpp.myJid()];
  7641. delete resolution[APP.xmpp.myJid()];
  7642. }
  7643. updateStatsIndicator("localVideoContainer", percent, object);
  7644. for(var jid in resolution)
  7645. {
  7646. if(resolution[jid] === null)
  7647. continue;
  7648. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7649. if(VideoLayout.connectionIndicators[id])
  7650. {
  7651. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7652. }
  7653. }
  7654. };
  7655. /**
  7656. * Updates remote stats.
  7657. * @param jid the jid associated with the stats
  7658. * @param percent the connection quality percent
  7659. * @param object the stats data
  7660. */
  7661. my.updateConnectionStats = function (jid, percent, object) {
  7662. var resourceJid = Strophe.getResourceFromJid(jid);
  7663. var videoSpanId = 'participant_' + resourceJid;
  7664. updateStatsIndicator(videoSpanId, percent, object);
  7665. };
  7666. /**
  7667. * Removes the connection
  7668. * @param jid
  7669. */
  7670. my.removeConnectionIndicator = function (jid) {
  7671. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7672. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7673. };
  7674. /**
  7675. * Hides the connection indicator
  7676. * @param jid
  7677. */
  7678. my.hideConnectionIndicator = function (jid) {
  7679. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7680. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7681. };
  7682. /**
  7683. * Hides all the indicators
  7684. */
  7685. my.onStatsStop = function () {
  7686. for(var indicator in VideoLayout.connectionIndicators)
  7687. {
  7688. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7689. }
  7690. };
  7691. my.participantLeft = function (jid) {
  7692. // Unlock large video
  7693. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7694. {
  7695. console.info("Focused video owner has left the conference");
  7696. focusedVideoInfo = null;
  7697. }
  7698. }
  7699. my.onVideoTypeChanged = function (jid) {
  7700. if(jid &&
  7701. Strophe.getResourceFromJid(jid) === largeVideoState.userResourceJid)
  7702. {
  7703. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  7704. VideoLayout.getVideoSize = largeVideoState.isDesktop
  7705. ? getDesktopVideoSize
  7706. : getCameraVideoSize;
  7707. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  7708. ? getDesktopVideoPosition
  7709. : getCameraVideoPosition;
  7710. VideoLayout.positionLarge(null, null);
  7711. }
  7712. }
  7713. return my;
  7714. }(VideoLayout || {}));
  7715. module.exports = VideoLayout;
  7716. },{"../../../service/RTC/MediaStreamTypes":87,"../../../service/UI/UIEvents":92,"../audio_levels/AudioLevels":9,"../avatar/Avatar":13,"../etherpad/Etherpad":14,"../prezi/Prezi":15,"../side_pannels/chat/Chat":18,"../side_pannels/contactlist/ContactList":22,"../util/NicknameHandler":29,"../util/UIUtil":30,"./ConnectionIndicator":31}],33:[function(require,module,exports){
  7717. //var nouns = [
  7718. //];
  7719. var pluralNouns = [
  7720. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7721. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  7722. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  7723. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  7724. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  7725. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  7726. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  7727. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  7728. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  7729. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  7730. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  7731. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  7732. ];
  7733. //var places = [
  7734. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  7735. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  7736. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  7737. // "Bridge"
  7738. //];
  7739. var verbs = [
  7740. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  7741. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  7742. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  7743. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  7744. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  7745. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  7746. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  7747. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  7748. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  7749. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  7750. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  7751. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  7752. ];
  7753. var adverbs = [
  7754. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  7755. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  7756. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  7757. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  7758. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  7759. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  7760. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  7761. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  7762. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  7763. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  7764. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  7765. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  7766. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  7767. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  7768. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  7769. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  7770. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  7771. ];
  7772. var adjectives = [
  7773. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  7774. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  7775. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  7776. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  7777. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  7778. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  7779. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  7780. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  7781. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  7782. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  7783. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  7784. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  7785. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  7786. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  7787. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  7788. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  7789. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  7790. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  7791. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  7792. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  7793. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  7794. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  7795. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  7796. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  7797. "Zealous"
  7798. ];
  7799. //var pronouns = [
  7800. //];
  7801. //var conjunctions = [
  7802. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  7803. //];
  7804. /*
  7805. * Maps a string (category name) to the array of words from that category.
  7806. */
  7807. var CATEGORIES =
  7808. {
  7809. //"_NOUN_": nouns,
  7810. "_PLURALNOUN_": pluralNouns,
  7811. //"_PLACE_": places,
  7812. "_VERB_": verbs,
  7813. "_ADVERB_": adverbs,
  7814. "_ADJECTIVE_": adjectives
  7815. //"_PRONOUN_": pronouns,
  7816. //"_CONJUNCTION_": conjunctions,
  7817. };
  7818. var PATTERNS = [
  7819. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  7820. // BeautifulFungiOrSpaghetti
  7821. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  7822. // AmazinglyScaryToy
  7823. //"_ADVERB__ADJECTIVE__NOUN_",
  7824. // NeitherTrashNorRifle
  7825. //"Neither_NOUN_Nor_NOUN_",
  7826. //"Either_NOUN_Or_NOUN_",
  7827. // EitherCopulateOrInvestigate
  7828. //"Either_VERB_Or_VERB_",
  7829. //"Neither_VERB_Nor_VERB_",
  7830. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  7831. //"The_ADVERB__ADJECTIVE__NOUN_",
  7832. //"The_ADVERB__ADJECTIVE__NOUN_s",
  7833. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  7834. // WolvesComputeBadly
  7835. //"_PLURALNOUN__VERB__ADVERB_",
  7836. // UniteFacilitateAndMerge
  7837. //"_VERB__VERB_And_VERB_",
  7838. //NastyWitchesAtThePub
  7839. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  7840. ];
  7841. /*
  7842. * Returns a random element from the array 'arr'
  7843. */
  7844. function randomElement(arr)
  7845. {
  7846. return arr[Math.floor(Math.random() * arr.length)];
  7847. }
  7848. /*
  7849. * Returns true if the string 's' contains one of the
  7850. * template strings.
  7851. */
  7852. function hasTemplate(s)
  7853. {
  7854. for (var template in CATEGORIES){
  7855. if (s.indexOf(template) >= 0){
  7856. return true;
  7857. }
  7858. }
  7859. }
  7860. /**
  7861. * Generates new room name.
  7862. */
  7863. var RoomNameGenerator = {
  7864. generateRoomWithoutSeparator: function()
  7865. {
  7866. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  7867. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  7868. var name = randomElement(PATTERNS);
  7869. var word;
  7870. while (hasTemplate(name)){
  7871. for (var template in CATEGORIES){
  7872. word = randomElement(CATEGORIES[template]);
  7873. name = name.replace(template, word);
  7874. }
  7875. }
  7876. return name;
  7877. }
  7878. }
  7879. module.exports = RoomNameGenerator;
  7880. },{}],34:[function(require,module,exports){
  7881. var animateTimeout, updateTimeout;
  7882. var RoomNameGenerator = require("./RoomnameGenerator");
  7883. function enter_room()
  7884. {
  7885. var val = $("#enter_room_field").val();
  7886. if(!val) {
  7887. val = $("#enter_room_field").attr("room_name");
  7888. }
  7889. if (val) {
  7890. window.location.pathname = "/" + val;
  7891. }
  7892. }
  7893. function animate(word) {
  7894. var currentVal = $("#enter_room_field").attr("placeholder");
  7895. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  7896. animateTimeout = setTimeout(function() {
  7897. animate(word.substring(1, word.length))
  7898. }, 70);
  7899. }
  7900. function update_roomname()
  7901. {
  7902. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  7903. $("#enter_room_field").attr("room_name", word);
  7904. $("#enter_room_field").attr("placeholder", "");
  7905. clearTimeout(animateTimeout);
  7906. animate(word);
  7907. updateTimeout = setTimeout(update_roomname, 10000);
  7908. }
  7909. function setupWelcomePage()
  7910. {
  7911. $("#videoconference_page").hide();
  7912. $("#domain_name").text(
  7913. window.location.protocol + "//" + window.location.host + "/");
  7914. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7915. var leftWatermarkDiv
  7916. = $("#welcome_page_header div[class='watermark leftwatermark']");
  7917. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  7918. {
  7919. leftWatermarkDiv.css({display: 'block'});
  7920. leftWatermarkDiv.parent().get(0).href
  7921. = interfaceConfig.JITSI_WATERMARK_LINK;
  7922. }
  7923. }
  7924. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7925. var rightWatermarkDiv
  7926. = $("#welcome_page_header div[class='watermark rightwatermark']");
  7927. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  7928. rightWatermarkDiv.css({display: 'block'});
  7929. rightWatermarkDiv.parent().get(0).href
  7930. = interfaceConfig.BRAND_WATERMARK_LINK;
  7931. rightWatermarkDiv.get(0).style.backgroundImage
  7932. = "url(images/rightwatermark.png)";
  7933. }
  7934. }
  7935. if (interfaceConfig.SHOW_POWERED_BY) {
  7936. $("#welcome_page_header>a[class='poweredby']")
  7937. .css({display: 'block'});
  7938. }
  7939. $("#enter_room_button").click(function()
  7940. {
  7941. enter_room();
  7942. });
  7943. $("#enter_room_field").keydown(function (event) {
  7944. if (event.keyCode === 13 /* enter */) {
  7945. enter_room();
  7946. }
  7947. });
  7948. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  7949. var updateTimeout;
  7950. var animateTimeout;
  7951. $("#reload_roomname").click(function () {
  7952. clearTimeout(updateTimeout);
  7953. clearTimeout(animateTimeout);
  7954. update_roomname();
  7955. });
  7956. $("#reload_roomname").show();
  7957. update_roomname();
  7958. }
  7959. $("#disable_welcome").click(function () {
  7960. window.localStorage.welcomePageDisabled
  7961. = $("#disable_welcome").is(":checked");
  7962. });
  7963. }
  7964. module.exports = setupWelcomePage;
  7965. },{"./RoomnameGenerator":33}],35:[function(require,module,exports){
  7966. var EventEmitter = require("events");
  7967. var eventEmitter = new EventEmitter();
  7968. var CQEvents = require("../../service/connectionquality/CQEvents");
  7969. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7970. /**
  7971. * local stats
  7972. * @type {{}}
  7973. */
  7974. var stats = {};
  7975. /**
  7976. * remote stats
  7977. * @type {{}}
  7978. */
  7979. var remoteStats = {};
  7980. /**
  7981. * Interval for sending statistics to other participants
  7982. * @type {null}
  7983. */
  7984. var sendIntervalId = null;
  7985. /**
  7986. * Start statistics sending.
  7987. */
  7988. function startSendingStats() {
  7989. sendStats();
  7990. sendIntervalId = setInterval(sendStats, 10000);
  7991. }
  7992. /**
  7993. * Sends statistics to other participants
  7994. */
  7995. function sendStats() {
  7996. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  7997. }
  7998. /**
  7999. * Converts statistics to format for sending through XMPP
  8000. * @param stats the statistics
  8001. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  8002. */
  8003. function convertToMUCStats(stats) {
  8004. return {
  8005. "bitrate_download": stats.bitrate.download,
  8006. "bitrate_upload": stats.bitrate.upload,
  8007. "packetLoss_total": stats.packetLoss.total,
  8008. "packetLoss_download": stats.packetLoss.download,
  8009. "packetLoss_upload": stats.packetLoss.upload
  8010. };
  8011. }
  8012. /**
  8013. * Converts statitistics to format used by VideoLayout
  8014. * @param stats
  8015. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  8016. */
  8017. function parseMUCStats(stats) {
  8018. return {
  8019. bitrate: {
  8020. download: stats.bitrate_download,
  8021. upload: stats.bitrate_upload
  8022. },
  8023. packetLoss: {
  8024. total: stats.packetLoss_total,
  8025. download: stats.packetLoss_download,
  8026. upload: stats.packetLoss_upload
  8027. }
  8028. };
  8029. }
  8030. var ConnectionQuality = {
  8031. init: function () {
  8032. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  8033. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  8034. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  8035. },
  8036. /**
  8037. * Updates the local statistics
  8038. * @param data new statistics
  8039. */
  8040. updateLocalStats: function (data) {
  8041. stats = data;
  8042. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  8043. if (sendIntervalId == null) {
  8044. startSendingStats();
  8045. }
  8046. },
  8047. /**
  8048. * Updates remote statistics
  8049. * @param jid the jid associated with the statistics
  8050. * @param data the statistics
  8051. */
  8052. updateRemoteStats: function (jid, data) {
  8053. if (data == null || data.packetLoss_total == null) {
  8054. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  8055. return;
  8056. }
  8057. remoteStats[jid] = parseMUCStats(data);
  8058. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  8059. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  8060. },
  8061. /**
  8062. * Stops statistics sending.
  8063. */
  8064. stopSendingStats: function () {
  8065. clearInterval(sendIntervalId);
  8066. sendIntervalId = null;
  8067. //notify UI about stopping statistics gathering
  8068. eventEmitter.emit(CQEvents.STOP);
  8069. },
  8070. /**
  8071. * Returns the local statistics.
  8072. */
  8073. getStats: function () {
  8074. return stats;
  8075. },
  8076. addListener: function (type, listener) {
  8077. eventEmitter.on(type, listener);
  8078. }
  8079. };
  8080. module.exports = ConnectionQuality;
  8081. },{"../../service/connectionquality/CQEvents":94,"../../service/xmpp/XMPPEvents":97,"events":98}],36:[function(require,module,exports){
  8082. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  8083. getUserMediaWithConstraints */
  8084. /**
  8085. * Indicates that desktop stream is currently in use(for toggle purpose).
  8086. * @type {boolean}
  8087. */
  8088. var isUsingScreenStream = false;
  8089. /**
  8090. * Indicates that switch stream operation is in progress and prevent from
  8091. * triggering new events.
  8092. * @type {boolean}
  8093. */
  8094. var switchInProgress = false;
  8095. /**
  8096. * Method used to get screen sharing stream.
  8097. *
  8098. * @type {function (stream_callback, failure_callback}
  8099. */
  8100. var obtainDesktopStream = null;
  8101. /**
  8102. * Indicates whether desktop sharing extension is installed.
  8103. * @type {boolean}
  8104. */
  8105. var extInstalled = false;
  8106. /**
  8107. * Indicates whether update of desktop sharing extension is required.
  8108. * @type {boolean}
  8109. */
  8110. var extUpdateRequired = false;
  8111. /**
  8112. * Flag used to cache desktop sharing enabled state. Do not use directly as
  8113. * it can be <tt>null</tt>.
  8114. *
  8115. * @type {null|boolean}
  8116. */
  8117. var _desktopSharingEnabled = null;
  8118. var EventEmitter = require("events");
  8119. var eventEmitter = new EventEmitter();
  8120. var DesktopSharingEventTypes
  8121. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  8122. /**
  8123. * Method obtains desktop stream from WebRTC 'screen' source.
  8124. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  8125. */
  8126. function obtainWebRTCScreen(streamCallback, failCallback) {
  8127. APP.RTC.getUserMediaWithConstraints(
  8128. ['screen'],
  8129. streamCallback,
  8130. failCallback
  8131. );
  8132. }
  8133. /**
  8134. * Constructs inline install URL for Chrome desktop streaming extension.
  8135. * The 'chromeExtensionId' must be defined in config.js.
  8136. * @returns {string}
  8137. */
  8138. function getWebStoreInstallUrl()
  8139. {
  8140. return "https://chrome.google.com/webstore/detail/" +
  8141. config.chromeExtensionId;
  8142. }
  8143. /**
  8144. * Checks whether extension update is required.
  8145. * @param minVersion minimal required version
  8146. * @param extVersion current extension version
  8147. * @returns {boolean}
  8148. */
  8149. function isUpdateRequired(minVersion, extVersion)
  8150. {
  8151. try
  8152. {
  8153. var s1 = minVersion.split('.');
  8154. var s2 = extVersion.split('.');
  8155. var len = Math.max(s1.length, s2.length);
  8156. for (var i = 0; i < len; i++)
  8157. {
  8158. var n1 = 0,
  8159. n2 = 0;
  8160. if (i < s1.length)
  8161. n1 = parseInt(s1[i]);
  8162. if (i < s2.length)
  8163. n2 = parseInt(s2[i]);
  8164. if (isNaN(n1) || isNaN(n2))
  8165. {
  8166. return true;
  8167. }
  8168. else if (n1 !== n2)
  8169. {
  8170. return n1 > n2;
  8171. }
  8172. }
  8173. // will happen if boths version has identical numbers in
  8174. // their components (even if one of them is longer, has more components)
  8175. return false;
  8176. }
  8177. catch (e)
  8178. {
  8179. console.error("Failed to parse extension version", e);
  8180. APP.UI.messageHandler.showError("dialog.error",
  8181. "dialog.detectext");
  8182. return true;
  8183. }
  8184. }
  8185. function checkExtInstalled(callback) {
  8186. if (!chrome.runtime) {
  8187. // No API, so no extension for sure
  8188. callback(false, false);
  8189. return;
  8190. }
  8191. chrome.runtime.sendMessage(
  8192. config.chromeExtensionId,
  8193. { getVersion: true },
  8194. function (response) {
  8195. if (!response || !response.version) {
  8196. // Communication failure - assume that no endpoint exists
  8197. console.warn(
  8198. "Extension not installed?: ", chrome.runtime.lastError);
  8199. callback(false, false);
  8200. return;
  8201. }
  8202. // Check installed extension version
  8203. var extVersion = response.version;
  8204. console.log('Extension version is: ' + extVersion);
  8205. var updateRequired
  8206. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  8207. callback(!updateRequired, updateRequired);
  8208. }
  8209. );
  8210. }
  8211. function doGetStreamFromExtension(streamCallback, failCallback) {
  8212. // Sends 'getStream' msg to the extension.
  8213. // Extension id must be defined in the config.
  8214. chrome.runtime.sendMessage(
  8215. config.chromeExtensionId,
  8216. { getStream: true, sources: config.desktopSharingSources },
  8217. function (response) {
  8218. if (!response) {
  8219. failCallback(chrome.runtime.lastError);
  8220. return;
  8221. }
  8222. console.log("Response from extension: " + response);
  8223. if (response.streamId) {
  8224. APP.RTC.getUserMediaWithConstraints(
  8225. ['desktop'],
  8226. function (stream) {
  8227. streamCallback(stream);
  8228. },
  8229. failCallback,
  8230. null, null, null,
  8231. response.streamId);
  8232. } else {
  8233. failCallback("Extension failed to get the stream");
  8234. }
  8235. }
  8236. );
  8237. }
  8238. /**
  8239. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  8240. * stream for returned stream token.
  8241. */
  8242. function obtainScreenFromExtension(streamCallback, failCallback) {
  8243. if (extInstalled) {
  8244. doGetStreamFromExtension(streamCallback, failCallback);
  8245. } else {
  8246. if (extUpdateRequired) {
  8247. alert(
  8248. 'Jitsi Desktop Streamer requires update. ' +
  8249. 'Changes will take effect after next Chrome restart.');
  8250. }
  8251. chrome.webstore.install(
  8252. getWebStoreInstallUrl(),
  8253. function (arg) {
  8254. console.log("Extension installed successfully", arg);
  8255. // We need to reload the page in order to get the access to
  8256. // chrome.runtime
  8257. window.location.reload(false);
  8258. },
  8259. function (arg) {
  8260. console.log("Failed to install the extension", arg);
  8261. failCallback(arg);
  8262. APP.UI.messageHandler.showError("dialog.error",
  8263. "dialog.failtoinstall");
  8264. }
  8265. );
  8266. }
  8267. }
  8268. /**
  8269. * Call this method to toggle desktop sharing feature.
  8270. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  8271. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  8272. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  8273. * enabled), pass any other string or nothing in order to disable this
  8274. * feature completely.
  8275. */
  8276. function setDesktopSharing(method) {
  8277. // Check if we are running chrome
  8278. if (!navigator.webkitGetUserMedia) {
  8279. obtainDesktopStream = null;
  8280. console.info("Desktop sharing disabled");
  8281. } else if (method == "ext") {
  8282. obtainDesktopStream = obtainScreenFromExtension;
  8283. console.info("Using Chrome extension for desktop sharing");
  8284. } else if (method == "webrtc") {
  8285. obtainDesktopStream = obtainWebRTCScreen;
  8286. console.info("Using Chrome WebRTC for desktop sharing");
  8287. }
  8288. // Reset enabled cache
  8289. _desktopSharingEnabled = null;
  8290. }
  8291. /**
  8292. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  8293. * config.js to support inline installs. Host site must be selected as main
  8294. * website of published extension.
  8295. */
  8296. function initInlineInstalls()
  8297. {
  8298. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  8299. }
  8300. function getSwitchStreamFailed(error) {
  8301. console.error("Failed to obtain the stream to switch to", error);
  8302. switchInProgress = false;
  8303. isUsingScreenStream = false;
  8304. newStreamCreated(null);
  8305. }
  8306. function streamSwitchDone() {
  8307. switchInProgress = false;
  8308. eventEmitter.emit(
  8309. DesktopSharingEventTypes.SWITCHING_DONE,
  8310. isUsingScreenStream);
  8311. }
  8312. function newStreamCreated(stream)
  8313. {
  8314. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  8315. stream, isUsingScreenStream, streamSwitchDone);
  8316. }
  8317. module.exports = {
  8318. isUsingScreenStream: function () {
  8319. return isUsingScreenStream;
  8320. },
  8321. /**
  8322. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  8323. * and enabled.
  8324. */
  8325. isDesktopSharingEnabled: function () {
  8326. if (_desktopSharingEnabled === null) {
  8327. if (obtainDesktopStream === obtainScreenFromExtension) {
  8328. // Parse chrome version
  8329. var userAgent = navigator.userAgent.toLowerCase();
  8330. // We can assume that user agent is chrome, because it's
  8331. // enforced when 'ext' streaming method is set
  8332. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  8333. console.log("Chrome version" + userAgent, ver);
  8334. _desktopSharingEnabled = ver >= 34;
  8335. } else {
  8336. _desktopSharingEnabled =
  8337. obtainDesktopStream === obtainWebRTCScreen;
  8338. }
  8339. }
  8340. return _desktopSharingEnabled;
  8341. },
  8342. init: function () {
  8343. setDesktopSharing(config.desktopSharing);
  8344. // Initialize Chrome extension inline installs
  8345. if (config.chromeExtensionId) {
  8346. initInlineInstalls();
  8347. // Check if extension is installed
  8348. checkExtInstalled(function (installed, updateRequired) {
  8349. extInstalled = installed;
  8350. extUpdateRequired = updateRequired;
  8351. console.info(
  8352. "Chrome extension installed: " + extInstalled +
  8353. " updateRequired: " + extUpdateRequired);
  8354. });
  8355. }
  8356. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  8357. },
  8358. addListener: function (listener, type)
  8359. {
  8360. eventEmitter.on(type, listener);
  8361. },
  8362. removeListener: function (listener, type) {
  8363. eventEmitter.removeListener(type, listener);
  8364. },
  8365. /*
  8366. * Toggles screen sharing.
  8367. */
  8368. toggleScreenSharing: function () {
  8369. if (switchInProgress || !obtainDesktopStream) {
  8370. console.warn("Switch in progress or no method defined");
  8371. return;
  8372. }
  8373. switchInProgress = true;
  8374. if (!isUsingScreenStream)
  8375. {
  8376. // Switch to desktop stream
  8377. obtainDesktopStream(
  8378. function (stream) {
  8379. // We now use screen stream
  8380. isUsingScreenStream = true;
  8381. // Hook 'ended' event to restore camera
  8382. // when screen stream stops
  8383. stream.addEventListener('ended',
  8384. function (e) {
  8385. if (!switchInProgress && isUsingScreenStream) {
  8386. APP.desktopsharing.toggleScreenSharing();
  8387. }
  8388. }
  8389. );
  8390. newStreamCreated(stream);
  8391. },
  8392. getSwitchStreamFailed);
  8393. } else {
  8394. // Disable screen stream
  8395. APP.RTC.getUserMediaWithConstraints(
  8396. ['video'],
  8397. function (stream) {
  8398. // We are now using camera stream
  8399. isUsingScreenStream = false;
  8400. newStreamCreated(stream);
  8401. },
  8402. getSwitchStreamFailed, config.resolution || '360'
  8403. );
  8404. }
  8405. }
  8406. };
  8407. },{"../../service/desktopsharing/DesktopSharingEventTypes":95,"events":98}],37:[function(require,module,exports){
  8408. //maps keycode to character, id of popover for given function and function
  8409. var shortcuts = {
  8410. 67: {
  8411. character: "C",
  8412. id: "toggleChatPopover",
  8413. function: APP.UI.toggleChat
  8414. },
  8415. 70: {
  8416. character: "F",
  8417. id: "filmstripPopover",
  8418. function: APP.UI.toggleFilmStrip
  8419. },
  8420. 77: {
  8421. character: "M",
  8422. id: "mutePopover",
  8423. function: APP.UI.toggleAudio
  8424. },
  8425. 84: {
  8426. character: "T",
  8427. function: function() {
  8428. if(!APP.RTC.localAudio.isMuted()) {
  8429. APP.UI.toggleAudio();
  8430. }
  8431. }
  8432. },
  8433. 86: {
  8434. character: "V",
  8435. id: "toggleVideoPopover",
  8436. function: APP.UI.toggleVideo
  8437. }
  8438. };
  8439. var KeyboardShortcut = {
  8440. init: function () {
  8441. window.onkeyup = function(e) {
  8442. var keycode = e.which;
  8443. if(!($(":focus").is("input[type=text]") ||
  8444. $(":focus").is("input[type=password]") ||
  8445. $(":focus").is("textarea"))) {
  8446. if (typeof shortcuts[keycode] === "object") {
  8447. shortcuts[keycode].function();
  8448. }
  8449. else if (keycode >= "0".charCodeAt(0) &&
  8450. keycode <= "9".charCodeAt(0)) {
  8451. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8452. }
  8453. //esc while the smileys are visible hides them
  8454. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8455. APP.UI.toggleSmileys();
  8456. }
  8457. };
  8458. window.onkeydown = function(e) {
  8459. if(!($(":focus").is("input[type=text]") ||
  8460. $(":focus").is("input[type=password]") ||
  8461. $(":focus").is("textarea"))) {
  8462. if(e.which === "T".charCodeAt(0)) {
  8463. if(APP.RTC.localAudio.isMuted()) {
  8464. APP.UI.toggleAudio();
  8465. }
  8466. }
  8467. }
  8468. };
  8469. var self = this;
  8470. $('body').popover({ selector: '[data-toggle=popover]',
  8471. trigger: 'click hover',
  8472. content: function() {
  8473. return this.getAttribute("content") +
  8474. self.getShortcut(this.getAttribute("shortcut"));
  8475. }
  8476. });
  8477. },
  8478. /**
  8479. *
  8480. * @param id indicates the popover associated with the shortcut
  8481. * @returns {string} the keyboard shortcut used for the id given
  8482. */
  8483. getShortcut: function (id) {
  8484. for (var keycode in shortcuts) {
  8485. if (shortcuts.hasOwnProperty(keycode)) {
  8486. if (shortcuts[keycode].id === id) {
  8487. return " (" + shortcuts[keycode].character + ")";
  8488. }
  8489. }
  8490. }
  8491. return "";
  8492. }
  8493. };
  8494. module.exports = KeyboardShortcut;
  8495. },{}],38:[function(require,module,exports){
  8496. var email = '';
  8497. var displayName = '';
  8498. var userId;
  8499. var language = null;
  8500. function supportsLocalStorage() {
  8501. try {
  8502. return 'localStorage' in window && window.localStorage !== null;
  8503. } catch (e) {
  8504. console.log("localstorage is not supported");
  8505. return false;
  8506. }
  8507. }
  8508. function generateUniqueId() {
  8509. function _p8() {
  8510. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8511. }
  8512. return _p8() + _p8() + _p8() + _p8();
  8513. }
  8514. if (supportsLocalStorage()) {
  8515. if (!window.localStorage.jitsiMeetId) {
  8516. window.localStorage.jitsiMeetId = generateUniqueId();
  8517. console.log("generated id", window.localStorage.jitsiMeetId);
  8518. }
  8519. userId = window.localStorage.jitsiMeetId || '';
  8520. email = window.localStorage.email || '';
  8521. displayName = window.localStorage.displayname || '';
  8522. language = window.localStorage.language;
  8523. } else {
  8524. console.log("local storage is not supported");
  8525. userId = generateUniqueId();
  8526. }
  8527. var Settings =
  8528. {
  8529. setDisplayName: function (newDisplayName) {
  8530. displayName = newDisplayName;
  8531. window.localStorage.displayname = displayName;
  8532. return displayName;
  8533. },
  8534. setEmail: function (newEmail)
  8535. {
  8536. email = newEmail;
  8537. window.localStorage.email = newEmail;
  8538. return email;
  8539. },
  8540. getSettings: function () {
  8541. return {
  8542. email: email,
  8543. displayName: displayName,
  8544. uid: userId,
  8545. language: language
  8546. };
  8547. },
  8548. setLanguage: function (lang) {
  8549. language = lang;
  8550. window.localStorage.language = lang;
  8551. }
  8552. };
  8553. module.exports = Settings;
  8554. },{}],39:[function(require,module,exports){
  8555. /**
  8556. *
  8557. * @constructor
  8558. */
  8559. function SimulcastLogger(name, lvl) {
  8560. this.name = name;
  8561. this.lvl = lvl;
  8562. }
  8563. SimulcastLogger.prototype.log = function (text) {
  8564. if (this.lvl) {
  8565. console.log(text);
  8566. }
  8567. };
  8568. SimulcastLogger.prototype.info = function (text) {
  8569. if (this.lvl > 1) {
  8570. console.info(text);
  8571. }
  8572. };
  8573. SimulcastLogger.prototype.fine = function (text) {
  8574. if (this.lvl > 2) {
  8575. console.log(text);
  8576. }
  8577. };
  8578. SimulcastLogger.prototype.error = function (text) {
  8579. console.error(text);
  8580. };
  8581. module.exports = SimulcastLogger;
  8582. },{}],40:[function(require,module,exports){
  8583. var SimulcastLogger = require("./SimulcastLogger");
  8584. var SimulcastUtils = require("./SimulcastUtils");
  8585. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  8586. function SimulcastReceiver() {
  8587. this.simulcastUtils = new SimulcastUtils();
  8588. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  8589. }
  8590. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  8591. SimulcastReceiver.prototype._remoteMaps = {
  8592. msid2Quality: {},
  8593. ssrc2Msid: {},
  8594. msid2ssrc: {},
  8595. receivingVideoStreams: {}
  8596. };
  8597. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  8598. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8599. };
  8600. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  8601. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  8602. };
  8603. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  8604. var sb;
  8605. this.logger.info('Ensuring x-google-conference flag...')
  8606. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8607. // TODO(gp) do that for the audio as well as suggested by fippo.
  8608. // Add the google conference flag
  8609. sb = this.simulcastUtils._getVideoSources(lines);
  8610. sb = ['a=x-google-flag:conference'].concat(sb);
  8611. this.simulcastUtils._replaceVideoSources(lines, sb);
  8612. }
  8613. };
  8614. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  8615. this._restoreRemoteVideoSources(sb);
  8616. };
  8617. /**
  8618. * Restores the simulcast groups of the remote description. In
  8619. * transformRemoteDescription we remove those in order for the set remote
  8620. * description to succeed. The focus needs the signal the groups to new
  8621. * participants.
  8622. *
  8623. * @param desc
  8624. * @returns {*}
  8625. */
  8626. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  8627. var sb;
  8628. if (!this.simulcastUtils.isValidDescription(desc)) {
  8629. return desc;
  8630. }
  8631. if (config.enableSimulcast) {
  8632. sb = desc.sdp.split('\r\n');
  8633. this._restoreSimulcastGroups(sb);
  8634. desc = new RTCSessionDescription({
  8635. type: desc.type,
  8636. sdp: sb.join('\r\n')
  8637. });
  8638. }
  8639. return desc;
  8640. };
  8641. SimulcastUtils.prototype._ensureOrder = function (lines) {
  8642. var videoSources, sb;
  8643. videoSources = this.parseMedia(lines, ['video'])[0];
  8644. sb = this._compileVideoSources(videoSources);
  8645. this._replaceVideoSources(lines, sb);
  8646. };
  8647. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  8648. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  8649. videoSource, quality;
  8650. // (re) initialize the remote maps.
  8651. this._remoteMaps.msid2Quality = {};
  8652. this._remoteMaps.ssrc2Msid = {};
  8653. this._remoteMaps.msid2ssrc = {};
  8654. var self = this;
  8655. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  8656. remoteVideoSources.groups.forEach(function (group) {
  8657. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  8658. quality = 0;
  8659. group.ssrcs.forEach(function (ssrc) {
  8660. videoSource = remoteVideoSources.sources[ssrc];
  8661. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  8662. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  8663. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  8664. });
  8665. }
  8666. });
  8667. }
  8668. };
  8669. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  8670. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  8671. };
  8672. /**
  8673. * Returns a stream with single video track, the one currently being
  8674. * received by this endpoint.
  8675. *
  8676. * @param stream the remote simulcast stream.
  8677. * @returns {webkitMediaStream}
  8678. */
  8679. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  8680. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  8681. var self = this;
  8682. if (config.enableSimulcast) {
  8683. stream.getVideoTracks().some(function (track) {
  8684. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  8685. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  8686. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  8687. if (msid == [stream.id, track.id].join(' ')) {
  8688. electedTrack = track;
  8689. return true;
  8690. }
  8691. });
  8692. });
  8693. if (!electedTrack) {
  8694. // we don't have an elected track, choose by initial quality.
  8695. tracks = stream.getVideoTracks();
  8696. for (i = 0; i < tracks.length; i++) {
  8697. msid = [stream.id, tracks[i].id].join(' ');
  8698. if (this._remoteMaps.msid2Quality[msid] === quality) {
  8699. electedTrack = tracks[i];
  8700. break;
  8701. }
  8702. }
  8703. // TODO(gp) if the initialQuality could not be satisfied, lower
  8704. // the requirement and try again.
  8705. }
  8706. }
  8707. return (electedTrack)
  8708. ? new webkitMediaStream([electedTrack])
  8709. : stream;
  8710. };
  8711. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  8712. var resource = Strophe.getResourceFromJid(jid);
  8713. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  8714. // If we haven't receiving a "changed" event yet, then we must be receiving
  8715. // low quality (that the sender always streams).
  8716. if(!ssrc)
  8717. {
  8718. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8719. var remoteStream = remoteStreamObject.getOriginalStream();
  8720. var tracks = remoteStream.getVideoTracks();
  8721. if (tracks) {
  8722. for (var k = 0; k < tracks.length; k++) {
  8723. var track = tracks[k];
  8724. var msid = [remoteStream.id, track.id].join(' ');
  8725. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  8726. var quality = this._remoteMaps.msid2Quality[msid];
  8727. if (quality == 0) {
  8728. ssrc = _ssrc;
  8729. }
  8730. }
  8731. }
  8732. }
  8733. return ssrc;
  8734. };
  8735. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  8736. {
  8737. var sid, electedStream;
  8738. var i, j, k;
  8739. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  8740. if(jid && APP.RTC.remoteStreams[jid])
  8741. {
  8742. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8743. var remoteStream = remoteStreamObject.getOriginalStream();
  8744. var tracks = remoteStream.getVideoTracks();
  8745. if (tracks) {
  8746. for (k = 0; k < tracks.length; k++) {
  8747. var track = tracks[k];
  8748. var msid = [remoteStream.id, track.id].join(' ');
  8749. var tmp = this._remoteMaps.msid2ssrc[msid];
  8750. if (tmp == ssrc) {
  8751. electedStream = new webkitMediaStream([track]);
  8752. sid = remoteStreamObject.sid;
  8753. // stream found, stop.
  8754. break;
  8755. }
  8756. }
  8757. }
  8758. }
  8759. else
  8760. {
  8761. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  8762. }
  8763. return {
  8764. sid: sid,
  8765. stream: electedStream
  8766. };
  8767. };
  8768. /**
  8769. * Gets the fully qualified msid (stream.id + track.id) associated to the
  8770. * SSRC.
  8771. *
  8772. * @param ssrc
  8773. * @returns {*}
  8774. */
  8775. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  8776. return this._remoteMaps.ssrc2Msid[ssrc];
  8777. };
  8778. /**
  8779. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  8780. * either gets confused and thinks this is an FID group or, if an FID group
  8781. * is already present, it fails to set the remote description.
  8782. *
  8783. * @param desc
  8784. * @returns {*}
  8785. */
  8786. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  8787. if (desc && desc.sdp) {
  8788. var sb = desc.sdp.split('\r\n');
  8789. this._updateRemoteMaps(sb);
  8790. this._cacheRemoteVideoSources(sb);
  8791. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  8792. // need the simulcast group in the _updateRemoteMaps() method.
  8793. this.simulcastUtils._removeSimulcastGroup(sb);
  8794. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  8795. // We don't need the goog conference flag if we're not doing
  8796. // simulcast.
  8797. this._ensureGoogConference(sb);
  8798. }
  8799. desc = new RTCSessionDescription({
  8800. type: desc.type,
  8801. sdp: sb.join('\r\n')
  8802. });
  8803. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  8804. }
  8805. return desc;
  8806. };
  8807. module.exports = SimulcastReceiver;
  8808. },{"../../service/RTC/MediaStreamTypes":87,"./SimulcastLogger":39,"./SimulcastUtils":42}],41:[function(require,module,exports){
  8809. var SimulcastLogger = require("./SimulcastLogger");
  8810. var SimulcastUtils = require("./SimulcastUtils");
  8811. function SimulcastSender() {
  8812. this.simulcastUtils = new SimulcastUtils();
  8813. this.logger = new SimulcastLogger('SimulcastSender', 1);
  8814. }
  8815. SimulcastSender.prototype.displayedLocalVideoStream = null;
  8816. SimulcastSender.prototype._generateGuid = (function () {
  8817. function s4() {
  8818. return Math.floor((1 + Math.random()) * 0x10000)
  8819. .toString(16)
  8820. .substring(1);
  8821. }
  8822. return function () {
  8823. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  8824. s4() + '-' + s4() + s4() + s4();
  8825. };
  8826. }());
  8827. // Returns a random integer between min (included) and max (excluded)
  8828. // Using Math.round() gives a non-uniform distribution!
  8829. SimulcastSender.prototype._generateRandomSSRC = function () {
  8830. var min = 0, max = 0xffffffff;
  8831. return Math.floor(Math.random() * (max - min)) + min;
  8832. };
  8833. SimulcastSender.prototype.getLocalVideoStream = function () {
  8834. return (this.displayedLocalVideoStream != null)
  8835. ? this.displayedLocalVideoStream
  8836. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  8837. : APP.RTC.localVideo.getOriginalStream();
  8838. };
  8839. function NativeSimulcastSender() {
  8840. SimulcastSender.call(this); // call the super constructor.
  8841. }
  8842. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8843. NativeSimulcastSender.prototype._localExplosionMap = {};
  8844. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  8845. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  8846. NativeSimulcastSender.prototype.reset = function () {
  8847. this._localExplosionMap = {};
  8848. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  8849. };
  8850. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  8851. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8852. };
  8853. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  8854. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  8855. };
  8856. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  8857. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  8858. this.logger.info('Appending simulcast group...');
  8859. // Get the primary SSRC information.
  8860. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8861. // Start building the SIM SSRC group.
  8862. ssrcGroup = ['a=ssrc-group:SIM'];
  8863. // The video source buffer.
  8864. sb = [];
  8865. // Create the simulcast sub-streams.
  8866. for (i = 0; i < numOfSubs; i++) {
  8867. // TODO(gp) prevent SSRC collision.
  8868. simSSRC = this._generateRandomSSRC();
  8869. ssrcGroup.push(simSSRC);
  8870. if (videoSources.base) {
  8871. sb.splice.apply(sb, [sb.length, 0].concat(
  8872. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  8873. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  8874. ));
  8875. }
  8876. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  8877. }
  8878. // Add the group sim layers.
  8879. sb.splice(0, 0, ssrcGroup.join(' '))
  8880. this.simulcastUtils._replaceVideoSources(lines, sb);
  8881. };
  8882. // Does the actual patching.
  8883. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  8884. this.logger.info('Ensuring simulcast group...');
  8885. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8886. this._appendSimulcastGroup(lines);
  8887. this._cacheLocalVideoSources(lines);
  8888. } else {
  8889. // verify that the ssrcs participating in the SIM group are present
  8890. // in the SDP (needed for presence).
  8891. this._restoreLocalVideoSources(lines);
  8892. }
  8893. };
  8894. /**
  8895. * Produces a single stream with multiple tracks for local video sources.
  8896. *
  8897. * @param lines
  8898. * @private
  8899. */
  8900. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  8901. var sb, msid, sid, tid, videoSources, self;
  8902. this.logger.info('Exploding local video sources...');
  8903. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8904. self = this;
  8905. if (videoSources.groups && videoSources.groups.length !== 0) {
  8906. videoSources.groups.forEach(function (group) {
  8907. if (group.semantics === 'SIM') {
  8908. group.ssrcs.forEach(function (ssrc) {
  8909. // Get the msid for this ssrc..
  8910. if (self._localExplosionMap[ssrc]) {
  8911. // .. either from the explosion map..
  8912. msid = self._localExplosionMap[ssrc];
  8913. } else {
  8914. // .. or generate a new one (msid).
  8915. sid = videoSources.sources[ssrc].msid
  8916. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  8917. tid = self._generateGuid();
  8918. msid = [sid, tid].join(' ');
  8919. self._localExplosionMap[ssrc] = msid;
  8920. }
  8921. // Assign it to the source object.
  8922. videoSources.sources[ssrc].msid = msid;
  8923. // TODO(gp) Change the msid of associated sources.
  8924. });
  8925. }
  8926. });
  8927. }
  8928. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8929. this.simulcastUtils._replaceVideoSources(lines, sb);
  8930. };
  8931. /**
  8932. * GUM for simulcast.
  8933. *
  8934. * @param constraints
  8935. * @param success
  8936. * @param err
  8937. */
  8938. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8939. // There's nothing special to do for native simulcast, so just do a normal GUM.
  8940. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8941. success(hqStream);
  8942. }, err);
  8943. };
  8944. /**
  8945. * Prepares the local description for public usage (i.e. to be signaled
  8946. * through Jingle to the focus).
  8947. *
  8948. * @param desc
  8949. * @returns {RTCSessionDescription}
  8950. */
  8951. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8952. var sb;
  8953. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8954. return desc;
  8955. }
  8956. sb = desc.sdp.split('\r\n');
  8957. this._explodeSimulcastSenderSources(sb);
  8958. desc = new RTCSessionDescription({
  8959. type: desc.type,
  8960. sdp: sb.join('\r\n')
  8961. });
  8962. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  8963. return desc;
  8964. };
  8965. /**
  8966. * Ensures that the simulcast group is present in the answer, _if_ native
  8967. * simulcast is enabled,
  8968. *
  8969. * @param desc
  8970. * @returns {*}
  8971. */
  8972. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  8973. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8974. return desc;
  8975. }
  8976. var sb = desc.sdp.split('\r\n');
  8977. // Even if we have enabled native simulcasting previously
  8978. // (with a call to SLD with an appropriate SDP, for example),
  8979. // createAnswer seems to consistently generate incomplete SDP
  8980. // with missing SSRCS.
  8981. //
  8982. // So, subsequent calls to SLD will have missing SSRCS and presence
  8983. // won't have the complete list of SRCs.
  8984. this._ensureSimulcastGroup(sb);
  8985. desc = new RTCSessionDescription({
  8986. type: desc.type,
  8987. sdp: sb.join('\r\n')
  8988. });
  8989. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  8990. return desc;
  8991. };
  8992. /**
  8993. *
  8994. *
  8995. * @param desc
  8996. * @returns {*}
  8997. */
  8998. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8999. return desc;
  9000. };
  9001. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9002. // Nothing to do here, native simulcast does that auto-magically.
  9003. };
  9004. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  9005. function SimpleSimulcastSender() {
  9006. SimulcastSender.call(this);
  9007. }
  9008. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9009. SimpleSimulcastSender.prototype.localStream = null;
  9010. SimpleSimulcastSender.prototype._localMaps = {
  9011. msids: [],
  9012. msid2ssrc: {}
  9013. };
  9014. /**
  9015. * Groups local video sources together in the ssrc-group:SIM group.
  9016. *
  9017. * @param lines
  9018. * @private
  9019. */
  9020. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  9021. var sb, videoSources, ssrcs = [], ssrc;
  9022. this.logger.info('Grouping local video sources...');
  9023. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  9024. for (ssrc in videoSources.sources) {
  9025. // jitsi-meet destroys/creates streams at various places causing
  9026. // the original local stream ids to change. The only thing that
  9027. // remains unchanged is the trackid.
  9028. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  9029. }
  9030. var self = this;
  9031. // TODO(gp) add only "free" sources.
  9032. this._localMaps.msids.forEach(function (msid) {
  9033. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  9034. });
  9035. if (!videoSources.groups) {
  9036. videoSources.groups = [];
  9037. }
  9038. videoSources.groups.push({
  9039. 'semantics': 'SIM',
  9040. 'ssrcs': ssrcs
  9041. });
  9042. sb = this.simulcastUtils._compileVideoSources(videoSources);
  9043. this.simulcastUtils._replaceVideoSources(lines, sb);
  9044. };
  9045. /**
  9046. * GUM for simulcast.
  9047. *
  9048. * @param constraints
  9049. * @param success
  9050. * @param err
  9051. */
  9052. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9053. // TODO(gp) what if we request a resolution not supported by the hardware?
  9054. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  9055. var lqConstraints = {
  9056. audio: false,
  9057. video: {
  9058. mandatory: {
  9059. maxWidth: 320,
  9060. maxHeight: 180,
  9061. maxFrameRate: 15
  9062. }
  9063. }
  9064. };
  9065. this.logger.info('HQ constraints: ', constraints);
  9066. this.logger.info('LQ constraints: ', lqConstraints);
  9067. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  9068. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  9069. // reason appears to be that Chrome only acquires the cam once and
  9070. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  9071. var self = this;
  9072. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9073. self.localStream = hqStream;
  9074. // reset local maps.
  9075. self._localMaps.msids = [];
  9076. self._localMaps.msid2ssrc = {};
  9077. // add hq trackid to local map
  9078. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  9079. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  9080. self.displayedLocalVideoStream = lqStream;
  9081. // NOTE(gp) The specification says Array.forEach() will visit
  9082. // the array elements in numeric order, and that it doesn't
  9083. // visit elements that don't exist.
  9084. // add lq trackid to local map
  9085. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  9086. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  9087. success(self.localStream);
  9088. }, err);
  9089. }, err);
  9090. };
  9091. /**
  9092. * Prepares the local description for public usage (i.e. to be signaled
  9093. * through Jingle to the focus).
  9094. *
  9095. * @param desc
  9096. * @returns {RTCSessionDescription}
  9097. */
  9098. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9099. var sb;
  9100. if (!this.simulcastUtils.isValidDescription(desc)) {
  9101. return desc;
  9102. }
  9103. sb = desc.sdp.split('\r\n');
  9104. this._groupLocalVideoSources(sb);
  9105. desc = new RTCSessionDescription({
  9106. type: desc.type,
  9107. sdp: sb.join('\r\n')
  9108. });
  9109. this.logger.fine('Grouped local video sources');
  9110. this.logger.fine(desc.sdp);
  9111. return desc;
  9112. };
  9113. /**
  9114. * Ensures that the simulcast group is present in the answer, _if_ native
  9115. * simulcast is enabled,
  9116. *
  9117. * @param desc
  9118. * @returns {*}
  9119. */
  9120. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  9121. return desc;
  9122. };
  9123. /**
  9124. *
  9125. *
  9126. * @param desc
  9127. * @returns {*}
  9128. */
  9129. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9130. var sb = desc.sdp.split('\r\n');
  9131. this.simulcastUtils._removeSimulcastGroup(sb);
  9132. desc = new RTCSessionDescription({
  9133. type: desc.type,
  9134. sdp: sb.join('\r\n')
  9135. });
  9136. this.logger.fine('Transformed local description');
  9137. this.logger.fine(desc.sdp);
  9138. return desc;
  9139. };
  9140. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9141. var trackid;
  9142. var self = this;
  9143. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  9144. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  9145. // Search for the track id that corresponds to the ssrc
  9146. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  9147. trackid = tid;
  9148. return true;
  9149. }
  9150. }) && self.localStream.getVideoTracks().some(function (track) {
  9151. // Start/stop the track that corresponds to the track id
  9152. if (track.id === trackid) {
  9153. track.enabled = enabled;
  9154. return true;
  9155. }
  9156. })) {
  9157. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  9158. $(document).trigger(enabled
  9159. ? 'simulcastlayerstarted'
  9160. : 'simulcastlayerstopped');
  9161. } else {
  9162. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  9163. }
  9164. };
  9165. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  9166. function NoSimulcastSender() {
  9167. SimulcastSender.call(this);
  9168. }
  9169. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9170. /**
  9171. * GUM for simulcast.
  9172. *
  9173. * @param constraints
  9174. * @param success
  9175. * @param err
  9176. */
  9177. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9178. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9179. success(hqStream);
  9180. }, err);
  9181. };
  9182. /**
  9183. * Prepares the local description for public usage (i.e. to be signaled
  9184. * through Jingle to the focus).
  9185. *
  9186. * @param desc
  9187. * @returns {RTCSessionDescription}
  9188. */
  9189. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9190. return desc;
  9191. };
  9192. /**
  9193. * Ensures that the simulcast group is present in the answer, _if_ native
  9194. * simulcast is enabled,
  9195. *
  9196. * @param desc
  9197. * @returns {*}
  9198. */
  9199. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  9200. return desc;
  9201. };
  9202. /**
  9203. *
  9204. *
  9205. * @param desc
  9206. * @returns {*}
  9207. */
  9208. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9209. return desc;
  9210. };
  9211. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9212. };
  9213. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  9214. module.exports = {
  9215. "native": NativeSimulcastSender,
  9216. "no": NoSimulcastSender
  9217. }
  9218. },{"./SimulcastLogger":39,"./SimulcastUtils":42}],42:[function(require,module,exports){
  9219. var SimulcastLogger = require("./SimulcastLogger");
  9220. /**
  9221. *
  9222. * @constructor
  9223. */
  9224. function SimulcastUtils() {
  9225. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  9226. }
  9227. /**
  9228. *
  9229. * @type {{}}
  9230. * @private
  9231. */
  9232. SimulcastUtils.prototype._emptyCompoundIndex = {};
  9233. /**
  9234. *
  9235. * @param lines
  9236. * @param videoSources
  9237. * @private
  9238. */
  9239. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  9240. var i, inVideo = false, index = -1, howMany = 0;
  9241. this.logger.info('Replacing video sources...');
  9242. for (i = 0; i < lines.length; i++) {
  9243. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9244. // Out of video.
  9245. break;
  9246. }
  9247. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9248. // In video.
  9249. inVideo = true;
  9250. }
  9251. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  9252. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  9253. if (index === -1) {
  9254. index = i;
  9255. }
  9256. howMany++;
  9257. }
  9258. }
  9259. // efficiency baby ;)
  9260. lines.splice.apply(lines,
  9261. [index, howMany].concat(videoSources));
  9262. };
  9263. SimulcastUtils.prototype.isValidDescription = function (desc)
  9264. {
  9265. return desc && desc != null
  9266. && desc.type && desc.type != ''
  9267. && desc.sdp && desc.sdp != '';
  9268. };
  9269. SimulcastUtils.prototype._getVideoSources = function (lines) {
  9270. var i, inVideo = false, sb = [];
  9271. this.logger.info('Getting video sources...');
  9272. for (i = 0; i < lines.length; i++) {
  9273. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9274. // Out of video.
  9275. break;
  9276. }
  9277. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9278. // In video.
  9279. inVideo = true;
  9280. }
  9281. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9282. // In SSRC.
  9283. sb.push(lines[i]);
  9284. }
  9285. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9286. sb.push(lines[i]);
  9287. }
  9288. }
  9289. return sb;
  9290. };
  9291. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  9292. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  9293. ssrc_attribute, group, semantics, skip = true;
  9294. this.logger.info('Parsing media sources...');
  9295. for (i = 0; i < lines.length; i++) {
  9296. if (lines[i].substring(0, 'm='.length) === 'm=') {
  9297. type = lines[i]
  9298. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  9299. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  9300. if (!skip) {
  9301. cur_media = {
  9302. 'type': type,
  9303. 'sources': {},
  9304. 'groups': []
  9305. };
  9306. res.push(cur_media);
  9307. }
  9308. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9309. idx = lines[i].indexOf(' ');
  9310. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  9311. if (cur_media.sources[ssrc] === undefined) {
  9312. cur_ssrc = {'ssrc': ssrc};
  9313. cur_media.sources[ssrc] = cur_ssrc;
  9314. }
  9315. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  9316. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  9317. if (cur_media.base === undefined) {
  9318. cur_media.base = cur_ssrc;
  9319. }
  9320. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9321. idx = lines[i].indexOf(' ');
  9322. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  9323. ssrcs = lines[i].substr(idx).trim().split(' ');
  9324. group = {
  9325. 'semantics': semantics,
  9326. 'ssrcs': ssrcs
  9327. };
  9328. cur_media.groups.push(group);
  9329. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  9330. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  9331. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  9332. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  9333. cur_media.direction = lines[i].substring('a='.length);
  9334. }
  9335. }
  9336. return res;
  9337. };
  9338. /**
  9339. * The _indexOfArray() method returns the first a CompoundIndex at which a
  9340. * given element can be found in the array, or _emptyCompoundIndex if it is
  9341. * not present.
  9342. *
  9343. * Example:
  9344. *
  9345. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  9346. *
  9347. * returns {row: 2, column: 14}
  9348. *
  9349. * @param needle
  9350. * @param haystack
  9351. * @param start
  9352. * @returns {}
  9353. * @private
  9354. */
  9355. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  9356. var length = haystack.length, idx, i;
  9357. if (!start) {
  9358. start = 0;
  9359. }
  9360. for (i = start; i < length; i++) {
  9361. idx = haystack[i].indexOf(needle);
  9362. if (idx !== -1) {
  9363. return {row: i, column: idx};
  9364. }
  9365. }
  9366. return this._emptyCompoundIndex;
  9367. };
  9368. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  9369. var i;
  9370. for (i = lines.length - 1; i >= 0; i--) {
  9371. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  9372. lines.splice(i, 1);
  9373. }
  9374. }
  9375. };
  9376. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  9377. var sb = [], ssrc, addedSSRCs = [];
  9378. this.logger.info('Compiling video sources...');
  9379. // Add the groups
  9380. if (videoSources.groups && videoSources.groups.length !== 0) {
  9381. videoSources.groups.forEach(function (group) {
  9382. if (group.ssrcs && group.ssrcs.length !== 0) {
  9383. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  9384. // if (group.semantics !== 'SIM') {
  9385. group.ssrcs.forEach(function (ssrc) {
  9386. addedSSRCs.push(ssrc);
  9387. sb.splice.apply(sb, [sb.length, 0].concat([
  9388. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9389. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9390. });
  9391. //}
  9392. }
  9393. });
  9394. }
  9395. // Then add any free sources.
  9396. if (videoSources.sources) {
  9397. for (ssrc in videoSources.sources) {
  9398. if (addedSSRCs.indexOf(ssrc) === -1) {
  9399. sb.splice.apply(sb, [sb.length, 0].concat([
  9400. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9401. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9402. }
  9403. }
  9404. }
  9405. return sb;
  9406. };
  9407. module.exports = SimulcastUtils;
  9408. },{"./SimulcastLogger":39}],43:[function(require,module,exports){
  9409. /*jslint plusplus: true */
  9410. /*jslint nomen: true*/
  9411. var SimulcastSender = require("./SimulcastSender");
  9412. var NoSimulcastSender = SimulcastSender["no"];
  9413. var NativeSimulcastSender = SimulcastSender["native"];
  9414. var SimulcastReceiver = require("./SimulcastReceiver");
  9415. var SimulcastUtils = require("./SimulcastUtils");
  9416. var RTCEvents = require("../../service/RTC/RTCEvents");
  9417. /**
  9418. *
  9419. * @constructor
  9420. */
  9421. function SimulcastManager() {
  9422. // Create the simulcast utilities.
  9423. this.simulcastUtils = new SimulcastUtils();
  9424. // Create remote simulcast.
  9425. this.simulcastReceiver = new SimulcastReceiver();
  9426. // Initialize local simulcast.
  9427. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  9428. // account constraints.
  9429. if (!config.enableSimulcast) {
  9430. this.simulcastSender = new NoSimulcastSender();
  9431. } else {
  9432. var isChromium = window.chrome,
  9433. vendorName = window.navigator.vendor;
  9434. if(isChromium !== null && isChromium !== undefined
  9435. /* skip opera */
  9436. && vendorName === "Google Inc."
  9437. /* skip Chromium as suggested by fippo */
  9438. && !window.navigator.appVersion.match(/Chromium\//) ) {
  9439. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  9440. if (ver > 37) {
  9441. this.simulcastSender = new NativeSimulcastSender();
  9442. } else {
  9443. this.simulcastSender = new NoSimulcastSender();
  9444. }
  9445. } else {
  9446. this.simulcastSender = new NoSimulcastSender();
  9447. }
  9448. }
  9449. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  9450. function (endpointSimulcastLayers) {
  9451. endpointSimulcastLayers.forEach(function (esl) {
  9452. var ssrc = esl.simulcastLayer.primarySSRC;
  9453. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  9454. });
  9455. });
  9456. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  9457. var ssrc = simulcastLayer.primarySSRC;
  9458. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  9459. });
  9460. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  9461. var ssrc = simulcastLayer.primarySSRC;
  9462. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  9463. });
  9464. }
  9465. /**
  9466. * Restores the simulcast groups of the remote description. In
  9467. * transformRemoteDescription we remove those in order for the set remote
  9468. * description to succeed. The focus needs the signal the groups to new
  9469. * participants.
  9470. *
  9471. * @param desc
  9472. * @returns {*}
  9473. */
  9474. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  9475. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  9476. };
  9477. /**
  9478. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9479. * either gets confused and thinks this is an FID group or, if an FID group
  9480. * is already present, it fails to set the remote description.
  9481. *
  9482. * @param desc
  9483. * @returns {*}
  9484. */
  9485. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  9486. return this.simulcastReceiver.transformRemoteDescription(desc);
  9487. };
  9488. /**
  9489. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9490. * SSRC.
  9491. *
  9492. * @param ssrc
  9493. * @returns {*}
  9494. */
  9495. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9496. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  9497. };
  9498. /**
  9499. * Returns a stream with single video track, the one currently being
  9500. * received by this endpoint.
  9501. *
  9502. * @param stream the remote simulcast stream.
  9503. * @returns {webkitMediaStream}
  9504. */
  9505. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  9506. return this.simulcastReceiver.getReceivingVideoStream(stream);
  9507. };
  9508. /**
  9509. *
  9510. *
  9511. * @param desc
  9512. * @returns {*}
  9513. */
  9514. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  9515. return this.simulcastSender.transformLocalDescription(desc);
  9516. };
  9517. /**
  9518. *
  9519. * @returns {*}
  9520. */
  9521. SimulcastManager.prototype.getLocalVideoStream = function() {
  9522. return this.simulcastSender.getLocalVideoStream();
  9523. };
  9524. /**
  9525. * GUM for simulcast.
  9526. *
  9527. * @param constraints
  9528. * @param success
  9529. * @param err
  9530. */
  9531. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  9532. this.simulcastSender.getUserMedia(constraints, success, err);
  9533. };
  9534. /**
  9535. * Prepares the local description for public usage (i.e. to be signaled
  9536. * through Jingle to the focus).
  9537. *
  9538. * @param desc
  9539. * @returns {RTCSessionDescription}
  9540. */
  9541. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  9542. return this.simulcastSender.reverseTransformLocalDescription(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. SimulcastManager.prototype.transformAnswer = function (desc) {
  9552. return this.simulcastSender.transformAnswer(desc);
  9553. };
  9554. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  9555. return this.simulcastReceiver.getReceivingSSRC(jid);
  9556. };
  9557. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  9558. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  9559. };
  9560. /**
  9561. *
  9562. * @param lines
  9563. * @param mediatypes
  9564. * @returns {*}
  9565. */
  9566. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  9567. var sb = lines.sdp.split('\r\n');
  9568. return this.simulcastUtils.parseMedia(sb, mediatypes);
  9569. };
  9570. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  9571. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  9572. };
  9573. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  9574. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  9575. };
  9576. SimulcastManager.prototype.resetSender = function() {
  9577. if (typeof this.simulcastSender.reset === 'function'){
  9578. this.simulcastSender.reset();
  9579. }
  9580. };
  9581. var simulcast = new SimulcastManager();
  9582. module.exports = simulcast;
  9583. },{"../../service/RTC/RTCEvents":89,"./SimulcastReceiver":40,"./SimulcastSender":41,"./SimulcastUtils":42}],44:[function(require,module,exports){
  9584. /**
  9585. * Provides statistics for the local stream.
  9586. */
  9587. /**
  9588. * Size of the webaudio analizer buffer.
  9589. * @type {number}
  9590. */
  9591. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  9592. /**
  9593. * Value of the webaudio analizer smoothing time parameter.
  9594. * @type {number}
  9595. */
  9596. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  9597. /**
  9598. * Converts time domain data array to audio level.
  9599. * @param array the time domain data array.
  9600. * @returns {number} the audio level
  9601. */
  9602. function timeDomainDataToAudioLevel(samples) {
  9603. var maxVolume = 0;
  9604. var length = samples.length;
  9605. for (var i = 0; i < length; i++) {
  9606. if (maxVolume < samples[i])
  9607. maxVolume = samples[i];
  9608. }
  9609. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  9610. };
  9611. /**
  9612. * Animates audio level change
  9613. * @param newLevel the new audio level
  9614. * @param lastLevel the last audio level
  9615. * @returns {Number} the audio level to be set
  9616. */
  9617. function animateLevel(newLevel, lastLevel)
  9618. {
  9619. var value = 0;
  9620. var diff = lastLevel - newLevel;
  9621. if(diff > 0.2)
  9622. {
  9623. value = lastLevel - 0.2;
  9624. }
  9625. else if(diff < -0.4)
  9626. {
  9627. value = lastLevel + 0.4;
  9628. }
  9629. else
  9630. {
  9631. value = newLevel;
  9632. }
  9633. return parseFloat(value.toFixed(3));
  9634. }
  9635. /**
  9636. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  9637. *
  9638. * @param stream the local stream
  9639. * @param interval stats refresh interval given in ms.
  9640. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  9641. * update.
  9642. * @constructor
  9643. */
  9644. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  9645. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  9646. this.stream = stream;
  9647. this.intervalId = null;
  9648. this.intervalMilis = interval;
  9649. this.eventEmitter = eventEmitter;
  9650. this.audioLevel = 0;
  9651. this.statisticsService = statisticsService;
  9652. }
  9653. /**
  9654. * Starts the collecting the statistics.
  9655. */
  9656. LocalStatsCollector.prototype.start = function () {
  9657. if (config.disableAudioLevels || !window.AudioContext)
  9658. return;
  9659. var context = new AudioContext();
  9660. var analyser = context.createAnalyser();
  9661. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  9662. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  9663. var source = context.createMediaStreamSource(this.stream);
  9664. source.connect(analyser);
  9665. var self = this;
  9666. this.intervalId = setInterval(
  9667. function () {
  9668. var array = new Uint8Array(analyser.frequencyBinCount);
  9669. analyser.getByteTimeDomainData(array);
  9670. var audioLevel = timeDomainDataToAudioLevel(array);
  9671. if(audioLevel != self.audioLevel) {
  9672. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  9673. self.eventEmitter.emit(
  9674. "statistics.audioLevel",
  9675. self.statisticsService.LOCAL_JID,
  9676. self.audioLevel);
  9677. }
  9678. },
  9679. this.intervalMilis
  9680. );
  9681. };
  9682. /**
  9683. * Stops collecting the statistics.
  9684. */
  9685. LocalStatsCollector.prototype.stop = function () {
  9686. if (this.intervalId) {
  9687. clearInterval(this.intervalId);
  9688. this.intervalId = null;
  9689. }
  9690. };
  9691. module.exports = LocalStatsCollector;
  9692. },{}],45:[function(require,module,exports){
  9693. /* global ssrc2jid */
  9694. /* jshint -W117 */
  9695. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9696. /**
  9697. * Calculates packet lost percent using the number of lost packets and the
  9698. * number of all packet.
  9699. * @param lostPackets the number of lost packets
  9700. * @param totalPackets the number of all packets.
  9701. * @returns {number} packet loss percent
  9702. */
  9703. function calculatePacketLoss(lostPackets, totalPackets) {
  9704. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  9705. return 0;
  9706. return Math.round((lostPackets/totalPackets)*100);
  9707. }
  9708. function getStatValue(item, name) {
  9709. if(!keyMap[APP.RTC.getBrowserType()][name])
  9710. throw "The property isn't supported!";
  9711. var key = keyMap[APP.RTC.getBrowserType()][name];
  9712. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  9713. }
  9714. /**
  9715. * Peer statistics data holder.
  9716. * @constructor
  9717. */
  9718. function PeerStats()
  9719. {
  9720. this.ssrc2Loss = {};
  9721. this.ssrc2AudioLevel = {};
  9722. this.ssrc2bitrate = {};
  9723. this.ssrc2resolution = {};
  9724. }
  9725. /**
  9726. * The bandwidth
  9727. * @type {{}}
  9728. */
  9729. PeerStats.bandwidth = {};
  9730. /**
  9731. * The bit rate
  9732. * @type {{}}
  9733. */
  9734. PeerStats.bitrate = {};
  9735. /**
  9736. * The packet loss rate
  9737. * @type {{}}
  9738. */
  9739. PeerStats.packetLoss = null;
  9740. /**
  9741. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  9742. * represented by this instance.
  9743. * @param ssrc audio or video RTP stream SSRC.
  9744. * @param lossRate new packet loss rate value to be set.
  9745. */
  9746. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  9747. {
  9748. this.ssrc2Loss[ssrc] = lossRate;
  9749. };
  9750. /**
  9751. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  9752. * represented by this instance.
  9753. * @param ssrc audio or video RTP stream SSRC.
  9754. * @param resolution new resolution value to be set.
  9755. */
  9756. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  9757. {
  9758. if(resolution === null && this.ssrc2resolution[ssrc])
  9759. {
  9760. delete this.ssrc2resolution[ssrc];
  9761. }
  9762. else if(resolution !== null)
  9763. this.ssrc2resolution[ssrc] = resolution;
  9764. };
  9765. /**
  9766. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  9767. * represented by this instance.
  9768. * @param ssrc audio or video RTP stream SSRC.
  9769. * @param bitrate new bitrate value to be set.
  9770. */
  9771. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  9772. {
  9773. if(this.ssrc2bitrate[ssrc])
  9774. {
  9775. this.ssrc2bitrate[ssrc].download += bitrate.download;
  9776. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  9777. }
  9778. else {
  9779. this.ssrc2bitrate[ssrc] = bitrate;
  9780. }
  9781. };
  9782. /**
  9783. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  9784. * the stream which belongs to the peer represented by this instance.
  9785. * @param ssrc RTP stream SSRC for which current audio level value will be
  9786. * updated.
  9787. * @param audioLevel the new audio level value to be set. Value is truncated to
  9788. * fit the range from 0 to 1.
  9789. */
  9790. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  9791. {
  9792. // Range limit 0 - 1
  9793. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  9794. };
  9795. function formatAudioLevel(audioLevel) {
  9796. return Math.min(Math.max(audioLevel, 0), 1);
  9797. }
  9798. /**
  9799. * Array with the transport information.
  9800. * @type {Array}
  9801. */
  9802. PeerStats.transport = [];
  9803. /**
  9804. * <tt>StatsCollector</tt> registers for stats updates of given
  9805. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  9806. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  9807. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9808. * instance as an event source.
  9809. *
  9810. * @param peerconnection webRTC peer connection object.
  9811. * @param interval stats refresh interval given in ms.
  9812. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  9813. * called on stats update.
  9814. * @constructor
  9815. */
  9816. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  9817. {
  9818. this.peerconnection = peerconnection;
  9819. this.baselineAudioLevelsReport = null;
  9820. this.currentAudioLevelsReport = null;
  9821. this.currentStatsReport = null;
  9822. this.baselineStatsReport = null;
  9823. this.audioLevelsIntervalId = null;
  9824. this.eventEmitter = eventEmitter;
  9825. /**
  9826. * Gather PeerConnection stats once every this many milliseconds.
  9827. */
  9828. this.GATHER_INTERVAL = 15000;
  9829. /**
  9830. * Log stats via the focus once every this many milliseconds.
  9831. */
  9832. this.LOG_INTERVAL = 60000;
  9833. /**
  9834. * Gather stats and store them in this.statsToBeLogged.
  9835. */
  9836. this.gatherStatsIntervalId = null;
  9837. /**
  9838. * Send the stats already saved in this.statsToBeLogged to be logged via
  9839. * the focus.
  9840. */
  9841. this.logStatsIntervalId = null;
  9842. /**
  9843. * Stores the statistics which will be send to the focus to be logged.
  9844. */
  9845. this.statsToBeLogged =
  9846. {
  9847. timestamps: [],
  9848. stats: {}
  9849. };
  9850. // Updates stats interval
  9851. this.audioLevelsIntervalMilis = audioLevelsInterval;
  9852. this.statsIntervalId = null;
  9853. this.statsIntervalMilis = statsInterval;
  9854. // Map of jids to PeerStats
  9855. this.jid2stats = {};
  9856. }
  9857. module.exports = StatsCollector;
  9858. /**
  9859. * Stops stats updates.
  9860. */
  9861. StatsCollector.prototype.stop = function () {
  9862. if (this.audioLevelsIntervalId) {
  9863. clearInterval(this.audioLevelsIntervalId);
  9864. this.audioLevelsIntervalId = null;
  9865. }
  9866. if (this.statsIntervalId)
  9867. {
  9868. clearInterval(this.statsIntervalId);
  9869. this.statsIntervalId = null;
  9870. }
  9871. if(this.logStatsIntervalId)
  9872. {
  9873. clearInterval(this.logStatsIntervalId);
  9874. this.logStatsIntervalId = null;
  9875. }
  9876. if(this.gatherStatsIntervalId)
  9877. {
  9878. clearInterval(this.gatherStatsIntervalId);
  9879. this.gatherStatsIntervalId = null;
  9880. }
  9881. };
  9882. /**
  9883. * Callback passed to <tt>getStats</tt> method.
  9884. * @param error an error that occurred on <tt>getStats</tt> call.
  9885. */
  9886. StatsCollector.prototype.errorCallback = function (error)
  9887. {
  9888. console.error("Get stats error", error);
  9889. this.stop();
  9890. };
  9891. /**
  9892. * Starts stats updates.
  9893. */
  9894. StatsCollector.prototype.start = function ()
  9895. {
  9896. var self = this;
  9897. if(!config.disableAudioLevels) {
  9898. this.audioLevelsIntervalId = setInterval(
  9899. function () {
  9900. // Interval updates
  9901. self.peerconnection.getStats(
  9902. function (report) {
  9903. var results = null;
  9904. if (!report || !report.result ||
  9905. typeof report.result != 'function') {
  9906. results = report;
  9907. }
  9908. else {
  9909. results = report.result();
  9910. }
  9911. //console.error("Got interval report", results);
  9912. self.currentAudioLevelsReport = results;
  9913. self.processAudioLevelReport();
  9914. self.baselineAudioLevelsReport =
  9915. self.currentAudioLevelsReport;
  9916. },
  9917. self.errorCallback
  9918. );
  9919. },
  9920. self.audioLevelsIntervalMilis
  9921. );
  9922. }
  9923. if(!config.disableStats) {
  9924. this.statsIntervalId = setInterval(
  9925. function () {
  9926. // Interval updates
  9927. self.peerconnection.getStats(
  9928. function (report) {
  9929. var results = null;
  9930. if (!report || !report.result ||
  9931. typeof report.result != 'function') {
  9932. //firefox
  9933. results = report;
  9934. }
  9935. else {
  9936. //chrome
  9937. results = report.result();
  9938. }
  9939. //console.error("Got interval report", results);
  9940. self.currentStatsReport = results;
  9941. try {
  9942. self.processStatsReport();
  9943. }
  9944. catch (e) {
  9945. console.error("Unsupported key:" + e, e);
  9946. }
  9947. self.baselineStatsReport = self.currentStatsReport;
  9948. },
  9949. self.errorCallback
  9950. );
  9951. },
  9952. self.statsIntervalMilis
  9953. );
  9954. }
  9955. if (config.logStats) {
  9956. this.gatherStatsIntervalId = setInterval(
  9957. function () {
  9958. self.peerconnection.getStats(
  9959. function (report) {
  9960. self.addStatsToBeLogged(report.result());
  9961. },
  9962. function () {
  9963. }
  9964. );
  9965. },
  9966. this.GATHER_INTERVAL
  9967. );
  9968. this.logStatsIntervalId = setInterval(
  9969. function() { self.logStats(); },
  9970. this.LOG_INTERVAL);
  9971. }
  9972. };
  9973. /**
  9974. * Checks whether a certain record should be included in the logged statistics.
  9975. */
  9976. function acceptStat(reportId, reportType, statName) {
  9977. if (reportType == "googCandidatePair" && statName == "googChannelId")
  9978. return false;
  9979. if (reportType == "ssrc") {
  9980. if (statName == "googTrackId" ||
  9981. statName == "transportId" ||
  9982. statName == "ssrc")
  9983. return false;
  9984. }
  9985. return true;
  9986. }
  9987. /**
  9988. * Checks whether a certain record should be included in the logged statistics.
  9989. */
  9990. function acceptReport(id, type) {
  9991. if (id.substring(0, 15) == "googCertificate" ||
  9992. id.substring(0, 9) == "googTrack" ||
  9993. id.substring(0, 20) == "googLibjingleSession")
  9994. return false;
  9995. if (type == "googComponent")
  9996. return false;
  9997. return true;
  9998. }
  9999. /**
  10000. * Converts the stats to the format used for logging, and saves the data in
  10001. * this.statsToBeLogged.
  10002. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  10003. */
  10004. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  10005. var self = this;
  10006. var num_records = this.statsToBeLogged.timestamps.length;
  10007. this.statsToBeLogged.timestamps.push(new Date().getTime());
  10008. reports.map(function (report) {
  10009. if (!acceptReport(report.id, report.type))
  10010. return;
  10011. var stat = self.statsToBeLogged.stats[report.id];
  10012. if (!stat) {
  10013. stat = self.statsToBeLogged.stats[report.id] = {};
  10014. }
  10015. stat.type = report.type;
  10016. report.names().map(function (name) {
  10017. if (!acceptStat(report.id, report.type, name))
  10018. return;
  10019. var values = stat[name];
  10020. if (!values) {
  10021. values = stat[name] = [];
  10022. }
  10023. while (values.length < num_records) {
  10024. values.push(null);
  10025. }
  10026. values.push(report.stat(name));
  10027. });
  10028. });
  10029. };
  10030. StatsCollector.prototype.logStats = function () {
  10031. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  10032. return;
  10033. // Reset the stats
  10034. this.statsToBeLogged.stats = {};
  10035. this.statsToBeLogged.timestamps = [];
  10036. };
  10037. var keyMap = {};
  10038. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  10039. "ssrc": "ssrc",
  10040. "packetsReceived": "packetsReceived",
  10041. "packetsLost": "packetsLost",
  10042. "packetsSent": "packetsSent",
  10043. "bytesReceived": "bytesReceived",
  10044. "bytesSent": "bytesSent"
  10045. };
  10046. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  10047. "receiveBandwidth": "googAvailableReceiveBandwidth",
  10048. "sendBandwidth": "googAvailableSendBandwidth",
  10049. "remoteAddress": "googRemoteAddress",
  10050. "transportType": "googTransportType",
  10051. "localAddress": "googLocalAddress",
  10052. "activeConnection": "googActiveConnection",
  10053. "ssrc": "ssrc",
  10054. "packetsReceived": "packetsReceived",
  10055. "packetsSent": "packetsSent",
  10056. "packetsLost": "packetsLost",
  10057. "bytesReceived": "bytesReceived",
  10058. "bytesSent": "bytesSent",
  10059. "googFrameHeightReceived": "googFrameHeightReceived",
  10060. "googFrameWidthReceived": "googFrameWidthReceived",
  10061. "googFrameHeightSent": "googFrameHeightSent",
  10062. "googFrameWidthSent": "googFrameWidthSent",
  10063. "audioInputLevel": "audioInputLevel",
  10064. "audioOutputLevel": "audioOutputLevel"
  10065. };
  10066. /**
  10067. * Stats processing logic.
  10068. */
  10069. StatsCollector.prototype.processStatsReport = function () {
  10070. if (!this.baselineStatsReport) {
  10071. return;
  10072. }
  10073. for (var idx in this.currentStatsReport) {
  10074. var now = this.currentStatsReport[idx];
  10075. try {
  10076. if (getStatValue(now, 'receiveBandwidth') ||
  10077. getStatValue(now, 'sendBandwidth')) {
  10078. PeerStats.bandwidth = {
  10079. "download": Math.round(
  10080. (getStatValue(now, 'receiveBandwidth')) / 1000),
  10081. "upload": Math.round(
  10082. (getStatValue(now, 'sendBandwidth')) / 1000)
  10083. };
  10084. }
  10085. }
  10086. catch(e){/*not supported*/}
  10087. if(now.type == 'googCandidatePair')
  10088. {
  10089. var ip, type, localIP, active;
  10090. try {
  10091. ip = getStatValue(now, 'remoteAddress');
  10092. type = getStatValue(now, "transportType");
  10093. localIP = getStatValue(now, "localAddress");
  10094. active = getStatValue(now, "activeConnection");
  10095. }
  10096. catch(e){/*not supported*/}
  10097. if(!ip || !type || !localIP || active != "true")
  10098. continue;
  10099. var addressSaved = false;
  10100. for(var i = 0; i < PeerStats.transport.length; i++)
  10101. {
  10102. if(PeerStats.transport[i].ip == ip &&
  10103. PeerStats.transport[i].type == type &&
  10104. PeerStats.transport[i].localip == localIP)
  10105. {
  10106. addressSaved = true;
  10107. }
  10108. }
  10109. if(addressSaved)
  10110. continue;
  10111. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  10112. continue;
  10113. }
  10114. if(now.type == "candidatepair")
  10115. {
  10116. if(now.state == "succeeded")
  10117. continue;
  10118. var local = this.currentStatsReport[now.localCandidateId];
  10119. var remote = this.currentStatsReport[now.remoteCandidateId];
  10120. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  10121. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  10122. }
  10123. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  10124. now.type != "inboundrtp") {
  10125. continue;
  10126. }
  10127. var before = this.baselineStatsReport[idx];
  10128. if (!before) {
  10129. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10130. continue;
  10131. }
  10132. var ssrc = getStatValue(now, 'ssrc');
  10133. if(!ssrc)
  10134. continue;
  10135. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10136. if (!jid && (Date.now() - now.timestamp) < 3000) {
  10137. console.warn("No jid for ssrc: " + ssrc);
  10138. continue;
  10139. }
  10140. var jidStats = this.jid2stats[jid];
  10141. if (!jidStats) {
  10142. jidStats = new PeerStats();
  10143. this.jid2stats[jid] = jidStats;
  10144. }
  10145. var isDownloadStream = true;
  10146. var key = 'packetsReceived';
  10147. if (!getStatValue(now, key))
  10148. {
  10149. isDownloadStream = false;
  10150. key = 'packetsSent';
  10151. if (!getStatValue(now, key))
  10152. {
  10153. console.warn("No packetsReceived nor packetSent stat found");
  10154. continue;
  10155. }
  10156. }
  10157. var packetsNow = getStatValue(now, key);
  10158. if(!packetsNow || packetsNow < 0)
  10159. packetsNow = 0;
  10160. var packetsBefore = getStatValue(before, key);
  10161. if(!packetsBefore || packetsBefore < 0)
  10162. packetsBefore = 0;
  10163. var packetRate = packetsNow - packetsBefore;
  10164. if(!packetRate || packetRate < 0)
  10165. packetRate = 0;
  10166. var currentLoss = getStatValue(now, 'packetsLost');
  10167. if(!currentLoss || currentLoss < 0)
  10168. currentLoss = 0;
  10169. var previousLoss = getStatValue(before, 'packetsLost');
  10170. if(!previousLoss || previousLoss < 0)
  10171. previousLoss = 0;
  10172. var lossRate = currentLoss - previousLoss;
  10173. if(!lossRate || lossRate < 0)
  10174. lossRate = 0;
  10175. var packetsTotal = (packetRate + lossRate);
  10176. jidStats.setSsrcLoss(ssrc,
  10177. {"packetsTotal": packetsTotal,
  10178. "packetsLost": lossRate,
  10179. "isDownloadStream": isDownloadStream});
  10180. var bytesReceived = 0, bytesSent = 0;
  10181. if(getStatValue(now, "bytesReceived"))
  10182. {
  10183. bytesReceived = getStatValue(now, "bytesReceived") -
  10184. getStatValue(before, "bytesReceived");
  10185. }
  10186. if(getStatValue(now, "bytesSent"))
  10187. {
  10188. bytesSent = getStatValue(now, "bytesSent") -
  10189. getStatValue(before, "bytesSent");
  10190. }
  10191. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  10192. if(bytesReceived <= 0 || time <= 0)
  10193. {
  10194. bytesReceived = 0;
  10195. }
  10196. else
  10197. {
  10198. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  10199. }
  10200. if(bytesSent <= 0 || time <= 0)
  10201. {
  10202. bytesSent = 0;
  10203. }
  10204. else
  10205. {
  10206. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  10207. }
  10208. jidStats.setSsrcBitrate(ssrc, {
  10209. "download": bytesReceived,
  10210. "upload": bytesSent});
  10211. var resolution = {height: null, width: null};
  10212. try {
  10213. if (getStatValue(now, "googFrameHeightReceived") &&
  10214. getStatValue(now, "googFrameWidthReceived")) {
  10215. resolution.height = getStatValue(now, "googFrameHeightReceived");
  10216. resolution.width = getStatValue(now, "googFrameWidthReceived");
  10217. }
  10218. else if (getStatValue(now, "googFrameHeightSent") &&
  10219. getStatValue(now, "googFrameWidthSent")) {
  10220. resolution.height = getStatValue(now, "googFrameHeightSent");
  10221. resolution.width = getStatValue(now, "googFrameWidthSent");
  10222. }
  10223. }
  10224. catch(e){/*not supported*/}
  10225. if(resolution.height && resolution.width)
  10226. {
  10227. jidStats.setSsrcResolution(ssrc, resolution);
  10228. }
  10229. else
  10230. {
  10231. jidStats.setSsrcResolution(ssrc, null);
  10232. }
  10233. }
  10234. var self = this;
  10235. // Jid stats
  10236. var totalPackets = {download: 0, upload: 0};
  10237. var lostPackets = {download: 0, upload: 0};
  10238. var bitrateDownload = 0;
  10239. var bitrateUpload = 0;
  10240. var resolutions = {};
  10241. Object.keys(this.jid2stats).forEach(
  10242. function (jid)
  10243. {
  10244. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  10245. function (ssrc)
  10246. {
  10247. var type = "upload";
  10248. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  10249. type = "download";
  10250. totalPackets[type] +=
  10251. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  10252. lostPackets[type] +=
  10253. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  10254. }
  10255. );
  10256. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  10257. function (ssrc) {
  10258. bitrateDownload +=
  10259. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  10260. bitrateUpload +=
  10261. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  10262. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  10263. }
  10264. );
  10265. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  10266. }
  10267. );
  10268. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  10269. PeerStats.packetLoss = {
  10270. total:
  10271. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  10272. totalPackets.download + totalPackets.upload),
  10273. download:
  10274. calculatePacketLoss(lostPackets.download, totalPackets.download),
  10275. upload:
  10276. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  10277. };
  10278. this.eventEmitter.emit("statistics.connectionstats",
  10279. {
  10280. "bitrate": PeerStats.bitrate,
  10281. "packetLoss": PeerStats.packetLoss,
  10282. "bandwidth": PeerStats.bandwidth,
  10283. "resolution": resolutions,
  10284. "transport": PeerStats.transport
  10285. });
  10286. PeerStats.transport = [];
  10287. };
  10288. /**
  10289. * Stats processing logic.
  10290. */
  10291. StatsCollector.prototype.processAudioLevelReport = function ()
  10292. {
  10293. if (!this.baselineAudioLevelsReport)
  10294. {
  10295. return;
  10296. }
  10297. for (var idx in this.currentAudioLevelsReport)
  10298. {
  10299. var now = this.currentAudioLevelsReport[idx];
  10300. if (now.type != 'ssrc')
  10301. {
  10302. continue;
  10303. }
  10304. var before = this.baselineAudioLevelsReport[idx];
  10305. if (!before)
  10306. {
  10307. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10308. continue;
  10309. }
  10310. var ssrc = getStatValue(now, 'ssrc');
  10311. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10312. if (!jid && (Date.now() - now.timestamp) < 3000)
  10313. {
  10314. console.warn("No jid for ssrc: " + ssrc);
  10315. continue;
  10316. }
  10317. var jidStats = this.jid2stats[jid];
  10318. if (!jidStats)
  10319. {
  10320. jidStats = new PeerStats();
  10321. this.jid2stats[jid] = jidStats;
  10322. }
  10323. // Audio level
  10324. var audioLevel = null;
  10325. try {
  10326. audioLevel = getStatValue(now, 'audioInputLevel');
  10327. if (!audioLevel)
  10328. audioLevel = getStatValue(now, 'audioOutputLevel');
  10329. }
  10330. catch(e) {/*not supported*/
  10331. console.warn("Audio Levels are not available in the statistics.");
  10332. clearInterval(this.audioLevelsIntervalId);
  10333. return;
  10334. }
  10335. if (audioLevel)
  10336. {
  10337. // TODO: can't find specs about what this value really is,
  10338. // but it seems to vary between 0 and around 32k.
  10339. audioLevel = audioLevel / 32767;
  10340. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  10341. if(jid != APP.xmpp.myJid())
  10342. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  10343. }
  10344. }
  10345. };
  10346. },{"../../service/RTC/RTCBrowserType":88}],46:[function(require,module,exports){
  10347. /**
  10348. * Created by hristo on 8/4/14.
  10349. */
  10350. var LocalStats = require("./LocalStatsCollector.js");
  10351. var RTPStats = require("./RTPStatsCollector.js");
  10352. var EventEmitter = require("events");
  10353. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  10354. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10355. var eventEmitter = new EventEmitter();
  10356. var localStats = null;
  10357. var rtpStats = null;
  10358. function stopLocal()
  10359. {
  10360. if(localStats)
  10361. {
  10362. localStats.stop();
  10363. localStats = null;
  10364. }
  10365. }
  10366. function stopRemote()
  10367. {
  10368. if(rtpStats)
  10369. {
  10370. rtpStats.stop();
  10371. eventEmitter.emit("statistics.stop");
  10372. rtpStats = null;
  10373. }
  10374. }
  10375. function startRemoteStats (peerconnection) {
  10376. if(rtpStats)
  10377. {
  10378. rtpStats.stop();
  10379. rtpStats = null;
  10380. }
  10381. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  10382. rtpStats.start();
  10383. }
  10384. function onStreamCreated(stream)
  10385. {
  10386. if(stream.getOriginalStream().getAudioTracks().length === 0)
  10387. return;
  10388. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  10389. eventEmitter);
  10390. localStats.start();
  10391. }
  10392. function onDisposeConference(onUnload) {
  10393. stopRemote();
  10394. if(onUnload) {
  10395. stopLocal();
  10396. eventEmitter.removeAllListeners();
  10397. }
  10398. }
  10399. var statistics =
  10400. {
  10401. /**
  10402. * Indicates that this audio level is for local jid.
  10403. * @type {string}
  10404. */
  10405. LOCAL_JID: 'local',
  10406. addAudioLevelListener: function(listener)
  10407. {
  10408. eventEmitter.on("statistics.audioLevel", listener);
  10409. },
  10410. removeAudioLevelListener: function(listener)
  10411. {
  10412. eventEmitter.removeListener("statistics.audioLevel", listener);
  10413. },
  10414. addConnectionStatsListener: function(listener)
  10415. {
  10416. eventEmitter.on("statistics.connectionstats", listener);
  10417. },
  10418. removeConnectionStatsListener: function(listener)
  10419. {
  10420. eventEmitter.removeListener("statistics.connectionstats", listener);
  10421. },
  10422. addRemoteStatsStopListener: function(listener)
  10423. {
  10424. eventEmitter.on("statistics.stop", listener);
  10425. },
  10426. removeRemoteStatsStopListener: function(listener)
  10427. {
  10428. eventEmitter.removeListener("statistics.stop", listener);
  10429. },
  10430. stop: function () {
  10431. stopLocal();
  10432. stopRemote();
  10433. if(eventEmitter)
  10434. {
  10435. eventEmitter.removeAllListeners();
  10436. }
  10437. },
  10438. stopRemoteStatistics: function()
  10439. {
  10440. stopRemote();
  10441. },
  10442. start: function () {
  10443. APP.RTC.addStreamListener(onStreamCreated,
  10444. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10445. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10446. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10447. startRemoteStats(event.peerconnection);
  10448. });
  10449. }
  10450. };
  10451. module.exports = statistics;
  10452. },{"../../service/RTC/StreamEventTypes.js":91,"../../service/xmpp/XMPPEvents":97,"./LocalStatsCollector.js":44,"./RTPStatsCollector.js":45,"events":98}],47:[function(require,module,exports){
  10453. var i18n = require("i18next-client");
  10454. var languages = require("../../service/translation/languages");
  10455. var Settings = require("../settings/Settings");
  10456. var DEFAULT_LANG = languages.EN;
  10457. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10458. return value.replace("__app__", interfaceConfig.APP_NAME);
  10459. });
  10460. var defaultOptions = {
  10461. detectLngQS: "lang",
  10462. useCookie: false,
  10463. fallbackLng: DEFAULT_LANG,
  10464. load: "unspecific",
  10465. resGetPath: 'lang/__ns__-__lng__.json',
  10466. ns: {
  10467. namespaces: ['main', 'languages'],
  10468. defaultNs: 'main'
  10469. },
  10470. lngWhitelist : languages.getLanguages(),
  10471. fallbackOnNull: true,
  10472. fallbackOnEmpty: true,
  10473. useDataAttrOptions: true,
  10474. defaultValueFromContent: false,
  10475. app: interfaceConfig.APP_NAME,
  10476. getAsync: false,
  10477. defaultValueFromContent: false,
  10478. customLoad: function(lng, ns, options, done) {
  10479. var resPath = "lang/__ns__-__lng__.json";
  10480. if(lng === languages.EN)
  10481. resPath = "lang/__ns__.json";
  10482. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10483. i18n.functions.ajax({
  10484. url: url,
  10485. success: function(data, status, xhr) {
  10486. i18n.functions.log('loaded: ' + url);
  10487. done(null, data);
  10488. },
  10489. error : function(xhr, status, error) {
  10490. if ((status && status == 200) ||
  10491. (xhr && xhr.status && xhr.status == 200)) {
  10492. // file loaded but invalid json, stop waste time !
  10493. i18n.functions.error('There is a typo in: ' + url);
  10494. } else if ((status && status == 404) ||
  10495. (xhr && xhr.status && xhr.status == 404)) {
  10496. i18n.functions.log('Does not exist: ' + url);
  10497. } else {
  10498. var theStatus = status ? status :
  10499. ((xhr && xhr.status) ? xhr.status : null);
  10500. i18n.functions.log(theStatus + ' when loading ' + url);
  10501. }
  10502. done(error, {});
  10503. },
  10504. dataType: "json",
  10505. async : options.getAsync
  10506. });
  10507. }
  10508. // options for caching
  10509. // useLocalStorage: true,
  10510. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10511. };
  10512. function initCompleted(t)
  10513. {
  10514. $("[data-i18n]").i18n();
  10515. }
  10516. function checkForParameter() {
  10517. var query = window.location.search.substring(1);
  10518. var vars = query.split("&");
  10519. for (var i=0;i<vars.length;i++) {
  10520. var pair = vars[i].split("=");
  10521. if(pair[0] == "lang")
  10522. {
  10523. return pair[1];
  10524. }
  10525. }
  10526. return null;
  10527. }
  10528. module.exports = {
  10529. init: function (lang) {
  10530. var options = defaultOptions;
  10531. if(!lang)
  10532. {
  10533. lang = checkForParameter();
  10534. if(!lang)
  10535. {
  10536. var settings = Settings.getSettings();
  10537. if(settings)
  10538. lang = settings.language;
  10539. }
  10540. }
  10541. if(lang) {
  10542. options.lng = lang;
  10543. }
  10544. i18n.init(options, initCompleted);
  10545. },
  10546. translateString: function (key, options) {
  10547. return i18n.t(key, options);
  10548. },
  10549. setLanguage: function (lang) {
  10550. if(!lang)
  10551. lang = DEFAULT_LANG;
  10552. i18n.setLng(lang, defaultOptions, initCompleted);
  10553. },
  10554. getCurrentLanguage: function () {
  10555. return i18n.lng();
  10556. },
  10557. translateElement: function (selector) {
  10558. selector.i18n();
  10559. },
  10560. generateTranslatonHTML: function (key, options) {
  10561. var str = "<span data-i18n=\"" + key + "\"";
  10562. if(options)
  10563. {
  10564. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10565. }
  10566. str += ">";
  10567. str += this.translateString(key, options);
  10568. str += "</span>";
  10569. return str;
  10570. }
  10571. };
  10572. },{"../../service/translation/languages":96,"../settings/Settings":38,"i18next-client":62}],48:[function(require,module,exports){
  10573. /* jshint -W117 */
  10574. var TraceablePeerConnection = require("./TraceablePeerConnection");
  10575. var SDPDiffer = require("./SDPDiffer");
  10576. var SDPUtil = require("./SDPUtil");
  10577. var SDP = require("./SDP");
  10578. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10579. // Jingle stuff
  10580. function JingleSession(me, sid, connection, service) {
  10581. this.me = me;
  10582. this.sid = sid;
  10583. this.connection = connection;
  10584. this.initiator = null;
  10585. this.responder = null;
  10586. this.isInitiator = null;
  10587. this.peerjid = null;
  10588. this.state = null;
  10589. this.localSDP = null;
  10590. this.remoteSDP = null;
  10591. this.relayedStreams = [];
  10592. this.startTime = null;
  10593. this.stopTime = null;
  10594. this.media_constraints = null;
  10595. this.pc_constraints = null;
  10596. this.ice_config = {};
  10597. this.drip_container = [];
  10598. this.service = service;
  10599. this.usetrickle = true;
  10600. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  10601. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  10602. this.hadstuncandidate = false;
  10603. this.hadturncandidate = false;
  10604. this.lasticecandidate = false;
  10605. this.statsinterval = null;
  10606. this.reason = null;
  10607. this.addssrc = [];
  10608. this.removessrc = [];
  10609. this.pendingop = null;
  10610. this.switchstreams = false;
  10611. this.wait = true;
  10612. this.localStreamsSSRC = null;
  10613. /**
  10614. * The indicator which determines whether the (local) video has been muted
  10615. * in response to a user command in contrast to an automatic decision made
  10616. * by the application logic.
  10617. */
  10618. this.videoMuteByUser = false;
  10619. }
  10620. //TODO: this array must be removed when firefox implement multistream support
  10621. JingleSession.notReceivedSSRCs = [];
  10622. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  10623. var self = this;
  10624. if (this.state !== null) {
  10625. console.error('attempt to initiate on session ' + this.sid +
  10626. 'in state ' + this.state);
  10627. return;
  10628. }
  10629. this.isInitiator = isInitiator;
  10630. this.state = 'pending';
  10631. this.initiator = isInitiator ? this.me : peerjid;
  10632. this.responder = !isInitiator ? this.me : peerjid;
  10633. this.peerjid = peerjid;
  10634. this.hadstuncandidate = false;
  10635. this.hadturncandidate = false;
  10636. this.lasticecandidate = false;
  10637. this.peerconnection
  10638. = new TraceablePeerConnection(
  10639. this.connection.jingle.ice_config,
  10640. this.connection.jingle.pc_constraints );
  10641. this.peerconnection.onicecandidate = function (event) {
  10642. self.sendIceCandidate(event.candidate);
  10643. };
  10644. this.peerconnection.onaddstream = function (event) {
  10645. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  10646. self.remoteStreamAdded(event);
  10647. };
  10648. this.peerconnection.onremovestream = function (event) {
  10649. // Remove the stream from remoteStreams
  10650. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  10651. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  10652. };
  10653. this.peerconnection.onsignalingstatechange = function (event) {
  10654. if (!(self && self.peerconnection)) return;
  10655. };
  10656. this.peerconnection.oniceconnectionstatechange = function (event) {
  10657. if (!(self && self.peerconnection)) return;
  10658. switch (self.peerconnection.iceConnectionState) {
  10659. case 'connected':
  10660. this.startTime = new Date();
  10661. break;
  10662. case 'disconnected':
  10663. this.stopTime = new Date();
  10664. break;
  10665. }
  10666. onIceConnectionStateChange(self.sid, self);
  10667. };
  10668. // add any local and relayed stream
  10669. APP.RTC.localStreams.forEach(function(stream) {
  10670. self.peerconnection.addStream(stream.getOriginalStream());
  10671. });
  10672. this.relayedStreams.forEach(function(stream) {
  10673. self.peerconnection.addStream(stream);
  10674. });
  10675. };
  10676. function onIceConnectionStateChange(sid, session) {
  10677. switch (session.peerconnection.iceConnectionState) {
  10678. case 'checking':
  10679. session.timeChecking = (new Date()).getTime();
  10680. session.firstconnect = true;
  10681. break;
  10682. case 'completed': // on caller side
  10683. case 'connected':
  10684. if (session.firstconnect) {
  10685. session.firstconnect = false;
  10686. var metadata = {};
  10687. metadata.setupTime
  10688. = (new Date()).getTime() - session.timeChecking;
  10689. session.peerconnection.getStats(function (res) {
  10690. if(res && res.result) {
  10691. res.result().forEach(function (report) {
  10692. if (report.type == 'googCandidatePair' &&
  10693. report.stat('googActiveConnection') == 'true') {
  10694. metadata.localCandidateType
  10695. = report.stat('googLocalCandidateType');
  10696. metadata.remoteCandidateType
  10697. = report.stat('googRemoteCandidateType');
  10698. // log pair as well so we can get nice pie
  10699. // charts
  10700. metadata.candidatePair
  10701. = report.stat('googLocalCandidateType') +
  10702. ';' +
  10703. report.stat('googRemoteCandidateType');
  10704. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  10705. {
  10706. metadata.ipv6 = true;
  10707. }
  10708. }
  10709. });
  10710. }
  10711. });
  10712. }
  10713. break;
  10714. }
  10715. }
  10716. JingleSession.prototype.accept = function () {
  10717. var self = this;
  10718. this.state = 'active';
  10719. var pranswer = this.peerconnection.localDescription;
  10720. if (!pranswer || pranswer.type != 'pranswer') {
  10721. return;
  10722. }
  10723. console.log('going from pranswer to answer');
  10724. if (this.usetrickle) {
  10725. // remove candidates already sent from session-accept
  10726. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  10727. for (var i = 0; i < lines.length; i++) {
  10728. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  10729. }
  10730. }
  10731. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  10732. // FIXME: change any inactive to sendrecv or whatever they were originally
  10733. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  10734. }
  10735. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  10736. var prsdp = new SDP(pranswer.sdp);
  10737. var accept = $iq({to: this.peerjid,
  10738. type: 'set'})
  10739. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10740. action: 'session-accept',
  10741. initiator: this.initiator,
  10742. responder: this.responder,
  10743. sid: this.sid });
  10744. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10745. var sdp = this.peerconnection.localDescription.sdp;
  10746. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  10747. // FIXME: change any inactive to sendrecv or whatever they were originally
  10748. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  10749. }
  10750. var self = this;
  10751. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  10752. function () {
  10753. //console.log('setLocalDescription success');
  10754. self.setLocalDescription();
  10755. self.connection.sendIQ(accept,
  10756. function () {
  10757. var ack = {};
  10758. ack.source = 'answer';
  10759. $(document).trigger('ack.jingle', [self.sid, ack]);
  10760. },
  10761. function (stanza) {
  10762. var error = ($(stanza).find('error').length) ? {
  10763. code: $(stanza).find('error').attr('code'),
  10764. reason: $(stanza).find('error :first')[0].tagName
  10765. }:{};
  10766. error.source = 'answer';
  10767. JingleSession.onJingleError(self.sid, error);
  10768. },
  10769. 10000);
  10770. },
  10771. function (e) {
  10772. console.error('setLocalDescription failed', e);
  10773. }
  10774. );
  10775. };
  10776. JingleSession.prototype.terminate = function (reason) {
  10777. this.state = 'ended';
  10778. this.reason = reason;
  10779. this.peerconnection.close();
  10780. if (this.statsinterval !== null) {
  10781. window.clearInterval(this.statsinterval);
  10782. this.statsinterval = null;
  10783. }
  10784. };
  10785. JingleSession.prototype.active = function () {
  10786. return this.state == 'active';
  10787. };
  10788. JingleSession.prototype.sendIceCandidate = function (candidate) {
  10789. var self = this;
  10790. if (candidate && !this.lasticecandidate) {
  10791. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  10792. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  10793. if (!(ice && jcand)) {
  10794. console.error('failed to get ice && jcand');
  10795. return;
  10796. }
  10797. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10798. if (jcand.type === 'srflx') {
  10799. this.hadstuncandidate = true;
  10800. } else if (jcand.type === 'relay') {
  10801. this.hadturncandidate = true;
  10802. }
  10803. if (this.usetrickle) {
  10804. if (this.usedrip) {
  10805. if (this.drip_container.length === 0) {
  10806. // start 20ms callout
  10807. window.setTimeout(function () {
  10808. if (self.drip_container.length === 0) return;
  10809. self.sendIceCandidates(self.drip_container);
  10810. self.drip_container = [];
  10811. }, 20);
  10812. }
  10813. this.drip_container.push(candidate);
  10814. return;
  10815. } else {
  10816. self.sendIceCandidate([candidate]);
  10817. }
  10818. }
  10819. } else {
  10820. //console.log('sendIceCandidate: last candidate.');
  10821. if (!this.usetrickle) {
  10822. //console.log('should send full offer now...');
  10823. var init = $iq({to: this.peerjid,
  10824. type: 'set'})
  10825. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10826. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  10827. initiator: this.initiator,
  10828. sid: this.sid});
  10829. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  10830. var self = this;
  10831. var sendJingle = function (ssrc) {
  10832. if(!ssrc)
  10833. ssrc = {};
  10834. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  10835. self.connection.sendIQ(init,
  10836. function () {
  10837. //console.log('session initiate ack');
  10838. var ack = {};
  10839. ack.source = 'offer';
  10840. $(document).trigger('ack.jingle', [self.sid, ack]);
  10841. },
  10842. function (stanza) {
  10843. self.state = 'error';
  10844. self.peerconnection.close();
  10845. var error = ($(stanza).find('error').length) ? {
  10846. code: $(stanza).find('error').attr('code'),
  10847. reason: $(stanza).find('error :first')[0].tagName,
  10848. }:{};
  10849. error.source = 'offer';
  10850. JingleSession.onJingleError(self.sid, error);
  10851. },
  10852. 10000);
  10853. }
  10854. sendJingle();
  10855. }
  10856. this.lasticecandidate = true;
  10857. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  10858. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  10859. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  10860. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  10861. }
  10862. }
  10863. };
  10864. JingleSession.prototype.sendIceCandidates = function (candidates) {
  10865. console.log('sendIceCandidates', candidates);
  10866. var cand = $iq({to: this.peerjid, type: 'set'})
  10867. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10868. action: 'transport-info',
  10869. initiator: this.initiator,
  10870. sid: this.sid});
  10871. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  10872. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  10873. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  10874. if (cands.length > 0) {
  10875. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  10876. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10877. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  10878. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  10879. }).c('transport', ice);
  10880. for (var i = 0; i < cands.length; i++) {
  10881. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  10882. }
  10883. // add fingerprint
  10884. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  10885. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  10886. tmp.required = true;
  10887. cand.c(
  10888. 'fingerprint',
  10889. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  10890. .t(tmp.fingerprint);
  10891. delete tmp.fingerprint;
  10892. cand.attrs(tmp);
  10893. cand.up();
  10894. }
  10895. cand.up(); // transport
  10896. cand.up(); // content
  10897. }
  10898. }
  10899. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  10900. //console.log('was this the last candidate', this.lasticecandidate);
  10901. this.connection.sendIQ(cand,
  10902. function () {
  10903. var ack = {};
  10904. ack.source = 'transportinfo';
  10905. $(document).trigger('ack.jingle', [this.sid, ack]);
  10906. },
  10907. function (stanza) {
  10908. var error = ($(stanza).find('error').length) ? {
  10909. code: $(stanza).find('error').attr('code'),
  10910. reason: $(stanza).find('error :first')[0].tagName,
  10911. }:{};
  10912. error.source = 'transportinfo';
  10913. JingleSession.onJingleError(this.sid, error);
  10914. },
  10915. 10000);
  10916. };
  10917. JingleSession.prototype.sendOffer = function () {
  10918. //console.log('sendOffer...');
  10919. var self = this;
  10920. this.peerconnection.createOffer(function (sdp) {
  10921. self.createdOffer(sdp);
  10922. },
  10923. function (e) {
  10924. console.error('createOffer failed', e);
  10925. },
  10926. this.media_constraints
  10927. );
  10928. };
  10929. JingleSession.prototype.createdOffer = function (sdp) {
  10930. //console.log('createdOffer', sdp);
  10931. var self = this;
  10932. this.localSDP = new SDP(sdp.sdp);
  10933. //this.localSDP.mangle();
  10934. var sendJingle = function () {
  10935. var init = $iq({to: this.peerjid,
  10936. type: 'set'})
  10937. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10938. action: 'session-initiate',
  10939. initiator: this.initiator,
  10940. sid: this.sid});
  10941. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10942. self.connection.sendIQ(init,
  10943. function () {
  10944. var ack = {};
  10945. ack.source = 'offer';
  10946. $(document).trigger('ack.jingle', [self.sid, ack]);
  10947. },
  10948. function (stanza) {
  10949. self.state = 'error';
  10950. self.peerconnection.close();
  10951. var error = ($(stanza).find('error').length) ? {
  10952. code: $(stanza).find('error').attr('code'),
  10953. reason: $(stanza).find('error :first')[0].tagName,
  10954. }:{};
  10955. error.source = 'offer';
  10956. JingleSession.onJingleError(self.sid, error);
  10957. },
  10958. 10000);
  10959. }
  10960. sdp.sdp = this.localSDP.raw;
  10961. this.peerconnection.setLocalDescription(sdp,
  10962. function () {
  10963. if(self.usetrickle)
  10964. {
  10965. sendJingle();
  10966. }
  10967. self.setLocalDescription();
  10968. //console.log('setLocalDescription success');
  10969. },
  10970. function (e) {
  10971. console.error('setLocalDescription failed', e);
  10972. }
  10973. );
  10974. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10975. for (var i = 0; i < cands.length; i++) {
  10976. var cand = SDPUtil.parse_icecandidate(cands[i]);
  10977. if (cand.type == 'srflx') {
  10978. this.hadstuncandidate = true;
  10979. } else if (cand.type == 'relay') {
  10980. this.hadturncandidate = true;
  10981. }
  10982. }
  10983. };
  10984. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  10985. //console.log('setting remote description... ', desctype);
  10986. this.remoteSDP = new SDP('');
  10987. this.remoteSDP.fromJingle(elem);
  10988. if (this.peerconnection.remoteDescription !== null) {
  10989. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  10990. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  10991. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  10992. for (var i = 0; i < pranswer.media.length; i++) {
  10993. // make sure we have ice ufrag and pwd
  10994. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  10995. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  10996. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  10997. } else {
  10998. console.warn('no ice ufrag?');
  10999. }
  11000. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  11001. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  11002. } else {
  11003. console.warn('no ice pwd?');
  11004. }
  11005. }
  11006. // copy over candidates
  11007. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  11008. for (var j = 0; j < lines.length; j++) {
  11009. this.remoteSDP.media[i] += lines[j] + '\r\n';
  11010. }
  11011. }
  11012. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11013. }
  11014. }
  11015. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  11016. this.peerconnection.setRemoteDescription(remotedesc,
  11017. function () {
  11018. //console.log('setRemoteDescription success');
  11019. },
  11020. function (e) {
  11021. console.error('setRemoteDescription error', e);
  11022. JingleSession.onJingleFatalError(self, e);
  11023. }
  11024. );
  11025. };
  11026. JingleSession.prototype.addIceCandidate = function (elem) {
  11027. var self = this;
  11028. if (this.peerconnection.signalingState == 'closed') {
  11029. return;
  11030. }
  11031. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  11032. console.log('trickle ice candidate arriving before session accept...');
  11033. // create a PRANSWER for setRemoteDescription
  11034. if (!this.remoteSDP) {
  11035. var cobbled = 'v=0\r\n' +
  11036. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11037. 's=-\r\n' +
  11038. 't=0 0\r\n';
  11039. // first, take some things from the local description
  11040. for (var i = 0; i < this.localSDP.media.length; i++) {
  11041. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  11042. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  11043. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  11044. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  11045. }
  11046. cobbled += 'a=inactive\r\n';
  11047. }
  11048. this.remoteSDP = new SDP(cobbled);
  11049. }
  11050. // then add things like ice and dtls from remote candidate
  11051. elem.each(function () {
  11052. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  11053. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11054. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11055. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  11056. var tmp = $(this).find('transport');
  11057. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  11058. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  11059. tmp = $(this).find('transport>fingerprint');
  11060. if (tmp.length) {
  11061. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  11062. } else {
  11063. console.log('no dtls fingerprint (webrtc issue #1718?)');
  11064. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  11065. }
  11066. break;
  11067. }
  11068. }
  11069. }
  11070. });
  11071. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11072. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  11073. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  11074. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  11075. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  11076. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  11077. }).length == this.remoteSDP.media.length;
  11078. if (iscomplete) {
  11079. console.log('setting pranswer');
  11080. try {
  11081. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  11082. function() {
  11083. },
  11084. function(e) {
  11085. console.log('setRemoteDescription pranswer failed', e.toString());
  11086. });
  11087. } catch (e) {
  11088. console.error('setting pranswer failed', e);
  11089. }
  11090. } else {
  11091. //console.log('not yet setting pranswer');
  11092. }
  11093. }
  11094. // operate on each content element
  11095. elem.each(function () {
  11096. // would love to deactivate this, but firefox still requires it
  11097. var idx = -1;
  11098. var i;
  11099. for (i = 0; i < self.remoteSDP.media.length; i++) {
  11100. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11101. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11102. idx = i;
  11103. break;
  11104. }
  11105. }
  11106. if (idx == -1) { // fall back to localdescription
  11107. for (i = 0; i < self.localSDP.media.length; i++) {
  11108. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11109. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11110. idx = i;
  11111. break;
  11112. }
  11113. }
  11114. }
  11115. var name = $(this).attr('name');
  11116. // TODO: check ice-pwd and ice-ufrag?
  11117. $(this).find('transport>candidate').each(function () {
  11118. var line, candidate;
  11119. line = SDPUtil.candidateFromJingle(this);
  11120. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  11121. sdpMid: name,
  11122. candidate: line});
  11123. try {
  11124. self.peerconnection.addIceCandidate(candidate);
  11125. } catch (e) {
  11126. console.error('addIceCandidate failed', e.toString(), line);
  11127. }
  11128. });
  11129. });
  11130. };
  11131. JingleSession.prototype.sendAnswer = function (provisional) {
  11132. //console.log('createAnswer', provisional);
  11133. var self = this;
  11134. this.peerconnection.createAnswer(
  11135. function (sdp) {
  11136. self.createdAnswer(sdp, provisional);
  11137. },
  11138. function (e) {
  11139. console.error('createAnswer failed', e);
  11140. },
  11141. this.media_constraints
  11142. );
  11143. };
  11144. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  11145. //console.log('createAnswer callback');
  11146. var self = this;
  11147. this.localSDP = new SDP(sdp.sdp);
  11148. //this.localSDP.mangle();
  11149. this.usepranswer = provisional === true;
  11150. if (this.usetrickle) {
  11151. if (this.usepranswer) {
  11152. sdp.type = 'pranswer';
  11153. for (var i = 0; i < this.localSDP.media.length; i++) {
  11154. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  11155. }
  11156. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  11157. }
  11158. }
  11159. var self = this;
  11160. var sendJingle = function (ssrcs) {
  11161. var accept = $iq({to: self.peerjid,
  11162. type: 'set'})
  11163. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11164. action: 'session-accept',
  11165. initiator: self.initiator,
  11166. responder: self.responder,
  11167. sid: self.sid });
  11168. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  11169. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  11170. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  11171. self.connection.sendIQ(accept,
  11172. function () {
  11173. var ack = {};
  11174. ack.source = 'answer';
  11175. $(document).trigger('ack.jingle', [self.sid, ack]);
  11176. },
  11177. function (stanza) {
  11178. var error = ($(stanza).find('error').length) ? {
  11179. code: $(stanza).find('error').attr('code'),
  11180. reason: $(stanza).find('error :first')[0].tagName,
  11181. }:{};
  11182. error.source = 'answer';
  11183. JingleSession.onJingleError(self.sid, error);
  11184. },
  11185. 10000);
  11186. }
  11187. sdp.sdp = this.localSDP.raw;
  11188. this.peerconnection.setLocalDescription(sdp,
  11189. function () {
  11190. //console.log('setLocalDescription success');
  11191. if (self.usetrickle && !self.usepranswer) {
  11192. sendJingle();
  11193. }
  11194. self.setLocalDescription();
  11195. },
  11196. function (e) {
  11197. console.error('setLocalDescription failed', e);
  11198. }
  11199. );
  11200. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11201. for (var j = 0; j < cands.length; j++) {
  11202. var cand = SDPUtil.parse_icecandidate(cands[j]);
  11203. if (cand.type == 'srflx') {
  11204. this.hadstuncandidate = true;
  11205. } else if (cand.type == 'relay') {
  11206. this.hadturncandidate = true;
  11207. }
  11208. }
  11209. };
  11210. JingleSession.prototype.sendTerminate = function (reason, text) {
  11211. var self = this,
  11212. term = $iq({to: this.peerjid,
  11213. type: 'set'})
  11214. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11215. action: 'session-terminate',
  11216. initiator: this.initiator,
  11217. sid: this.sid})
  11218. .c('reason')
  11219. .c(reason || 'success');
  11220. if (text) {
  11221. term.up().c('text').t(text);
  11222. }
  11223. this.connection.sendIQ(term,
  11224. function () {
  11225. self.peerconnection.close();
  11226. self.peerconnection = null;
  11227. self.terminate();
  11228. var ack = {};
  11229. ack.source = 'terminate';
  11230. $(document).trigger('ack.jingle', [self.sid, ack]);
  11231. },
  11232. function (stanza) {
  11233. var error = ($(stanza).find('error').length) ? {
  11234. code: $(stanza).find('error').attr('code'),
  11235. reason: $(stanza).find('error :first')[0].tagName,
  11236. }:{};
  11237. $(document).trigger('ack.jingle', [self.sid, error]);
  11238. },
  11239. 10000);
  11240. if (this.statsinterval !== null) {
  11241. window.clearInterval(this.statsinterval);
  11242. this.statsinterval = null;
  11243. }
  11244. };
  11245. JingleSession.prototype.addSource = function (elem, fromJid) {
  11246. var self = this;
  11247. // FIXME: dirty waiting
  11248. if (!this.peerconnection.localDescription)
  11249. {
  11250. console.warn("addSource - localDescription not ready yet")
  11251. setTimeout(function()
  11252. {
  11253. self.addSource(elem, fromJid);
  11254. },
  11255. 200
  11256. );
  11257. return;
  11258. }
  11259. console.log('addssrc', new Date().getTime());
  11260. console.log('ice', this.peerconnection.iceConnectionState);
  11261. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11262. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11263. $(elem).each(function (idx, content) {
  11264. var name = $(content).attr('name');
  11265. var lines = '';
  11266. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11267. var semantics = this.getAttribute('semantics');
  11268. var ssrcs = $(this).find('>source').map(function () {
  11269. return this.getAttribute('ssrc');
  11270. }).get();
  11271. if (ssrcs.length != 0) {
  11272. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11273. }
  11274. });
  11275. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11276. tmp.each(function () {
  11277. var ssrc = $(this).attr('ssrc');
  11278. if(mySdp.containsSSRC(ssrc)){
  11279. /**
  11280. * This happens when multiple participants change their streams at the same time and
  11281. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  11282. * addssrc are scheduled for update IQ. See
  11283. */
  11284. console.warn("Got add stream request for my own ssrc: "+ssrc);
  11285. return;
  11286. }
  11287. $(this).find('>parameter').each(function () {
  11288. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11289. if ($(this).attr('value') && $(this).attr('value').length)
  11290. lines += ':' + $(this).attr('value');
  11291. lines += '\r\n';
  11292. });
  11293. });
  11294. sdp.media.forEach(function(media, idx) {
  11295. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11296. return;
  11297. sdp.media[idx] += lines;
  11298. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  11299. self.addssrc[idx] += lines;
  11300. });
  11301. sdp.raw = sdp.session + sdp.media.join('');
  11302. });
  11303. this.modifySources();
  11304. };
  11305. JingleSession.prototype.removeSource = function (elem, fromJid) {
  11306. var self = this;
  11307. // FIXME: dirty waiting
  11308. if (!this.peerconnection.localDescription)
  11309. {
  11310. console.warn("removeSource - localDescription not ready yet")
  11311. setTimeout(function()
  11312. {
  11313. self.removeSource(elem, fromJid);
  11314. },
  11315. 200
  11316. );
  11317. return;
  11318. }
  11319. console.log('removessrc', new Date().getTime());
  11320. console.log('ice', this.peerconnection.iceConnectionState);
  11321. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11322. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11323. $(elem).each(function (idx, content) {
  11324. var name = $(content).attr('name');
  11325. var lines = '';
  11326. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11327. var semantics = this.getAttribute('semantics');
  11328. var ssrcs = $(this).find('>source').map(function () {
  11329. return this.getAttribute('ssrc');
  11330. }).get();
  11331. if (ssrcs.length != 0) {
  11332. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11333. }
  11334. });
  11335. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11336. tmp.each(function () {
  11337. var ssrc = $(this).attr('ssrc');
  11338. // This should never happen, but can be useful for bug detection
  11339. if(mySdp.containsSSRC(ssrc)){
  11340. console.error("Got remove stream request for my own ssrc: "+ssrc);
  11341. return;
  11342. }
  11343. $(this).find('>parameter').each(function () {
  11344. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11345. if ($(this).attr('value') && $(this).attr('value').length)
  11346. lines += ':' + $(this).attr('value');
  11347. lines += '\r\n';
  11348. });
  11349. });
  11350. sdp.media.forEach(function(media, idx) {
  11351. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11352. return;
  11353. sdp.media[idx] += lines;
  11354. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  11355. self.removessrc[idx] += lines;
  11356. });
  11357. sdp.raw = sdp.session + sdp.media.join('');
  11358. });
  11359. this.modifySources();
  11360. };
  11361. JingleSession.prototype.modifySources = function (successCallback) {
  11362. var self = this;
  11363. if (this.peerconnection.signalingState == 'closed') return;
  11364. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  11365. // There is nothing to do since scheduled job might have been executed by another succeeding call
  11366. this.setLocalDescription();
  11367. if(successCallback){
  11368. successCallback();
  11369. }
  11370. return;
  11371. }
  11372. // FIXME: this is a big hack
  11373. // https://code.google.com/p/webrtc/issues/detail?id=2688
  11374. // ^ has been fixed.
  11375. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
  11376. console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
  11377. this.wait = true;
  11378. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  11379. return;
  11380. }
  11381. if (this.wait) {
  11382. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  11383. this.wait = false;
  11384. return;
  11385. }
  11386. // Reset switch streams flag
  11387. this.switchstreams = false;
  11388. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11389. // add sources
  11390. this.addssrc.forEach(function(lines, idx) {
  11391. sdp.media[idx] += lines;
  11392. });
  11393. this.addssrc = [];
  11394. // remove sources
  11395. this.removessrc.forEach(function(lines, idx) {
  11396. lines = lines.split('\r\n');
  11397. lines.pop(); // remove empty last element;
  11398. lines.forEach(function(line) {
  11399. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  11400. });
  11401. });
  11402. this.removessrc = [];
  11403. // FIXME:
  11404. // this was a hack for the situation when only one peer exists
  11405. // in the conference.
  11406. // check if still required and remove
  11407. if (sdp.media[0])
  11408. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  11409. if (sdp.media[1])
  11410. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11411. sdp.raw = sdp.session + sdp.media.join('');
  11412. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  11413. function() {
  11414. if(self.signalingState == 'closed') {
  11415. console.error("createAnswer attempt on closed state");
  11416. return;
  11417. }
  11418. self.peerconnection.createAnswer(
  11419. function(modifiedAnswer) {
  11420. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  11421. if (self.pendingop !== null) {
  11422. var sdp = new SDP(modifiedAnswer.sdp);
  11423. if (sdp.media.length > 1) {
  11424. switch(self.pendingop) {
  11425. case 'mute':
  11426. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  11427. break;
  11428. case 'unmute':
  11429. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11430. break;
  11431. }
  11432. sdp.raw = sdp.session + sdp.media.join('');
  11433. modifiedAnswer.sdp = sdp.raw;
  11434. }
  11435. self.pendingop = null;
  11436. }
  11437. // FIXME: pushing down an answer while ice connection state
  11438. // is still checking is bad...
  11439. //console.log(self.peerconnection.iceConnectionState);
  11440. // trying to work around another chrome bug
  11441. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11442. self.peerconnection.setLocalDescription(modifiedAnswer,
  11443. function() {
  11444. //console.log('modified setLocalDescription ok');
  11445. self.setLocalDescription();
  11446. if(successCallback){
  11447. successCallback();
  11448. }
  11449. },
  11450. function(error) {
  11451. console.error('modified setLocalDescription failed', error);
  11452. }
  11453. );
  11454. },
  11455. function(error) {
  11456. console.error('modified answer failed', error);
  11457. }
  11458. );
  11459. },
  11460. function(error) {
  11461. console.error('modify failed', error);
  11462. }
  11463. );
  11464. };
  11465. /**
  11466. * Switches video streams.
  11467. * @param new_stream new stream that will be used as video of this session.
  11468. * @param oldStream old video stream of this session.
  11469. * @param success_callback callback executed after successful stream switch.
  11470. */
  11471. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback) {
  11472. var self = this;
  11473. // Remember SDP to figure out added/removed SSRCs
  11474. var oldSdp = null;
  11475. if(self.peerconnection) {
  11476. if(self.peerconnection.localDescription) {
  11477. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11478. }
  11479. self.peerconnection.removeStream(oldStream, true);
  11480. if(new_stream)
  11481. self.peerconnection.addStream(new_stream);
  11482. }
  11483. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11484. // Conference is not active
  11485. if(!oldSdp || !self.peerconnection) {
  11486. success_callback();
  11487. return;
  11488. }
  11489. self.switchstreams = true;
  11490. self.modifySources(function() {
  11491. console.log('modify sources done');
  11492. success_callback();
  11493. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11494. console.log("SDPs", oldSdp, newSdp);
  11495. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11496. });
  11497. };
  11498. /**
  11499. * Figures out added/removed ssrcs and send update IQs.
  11500. * @param old_sdp SDP object for old description.
  11501. * @param new_sdp SDP object for new description.
  11502. */
  11503. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11504. if (!(this.peerconnection.signalingState == 'stable' &&
  11505. this.peerconnection.iceConnectionState == 'connected')){
  11506. console.log("Too early to send updates");
  11507. return;
  11508. }
  11509. // send source-remove IQ.
  11510. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11511. var remove = $iq({to: this.peerjid, type: 'set'})
  11512. .c('jingle', {
  11513. xmlns: 'urn:xmpp:jingle:1',
  11514. action: 'source-remove',
  11515. initiator: this.initiator,
  11516. sid: this.sid
  11517. }
  11518. );
  11519. var removed = sdpDiffer.toJingle(remove);
  11520. if (removed) {
  11521. this.connection.sendIQ(remove,
  11522. function (res) {
  11523. console.info('got remove result', res);
  11524. },
  11525. function (err) {
  11526. console.error('got remove error', err);
  11527. }
  11528. );
  11529. } else {
  11530. console.log('removal not necessary');
  11531. }
  11532. // send source-add IQ.
  11533. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11534. var add = $iq({to: this.peerjid, type: 'set'})
  11535. .c('jingle', {
  11536. xmlns: 'urn:xmpp:jingle:1',
  11537. action: 'source-add',
  11538. initiator: this.initiator,
  11539. sid: this.sid
  11540. }
  11541. );
  11542. var added = sdpDiffer.toJingle(add);
  11543. if (added) {
  11544. this.connection.sendIQ(add,
  11545. function (res) {
  11546. console.info('got add result', res);
  11547. },
  11548. function (err) {
  11549. console.error('got add error', err);
  11550. }
  11551. );
  11552. } else {
  11553. console.log('addition not necessary');
  11554. }
  11555. };
  11556. /**
  11557. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  11558. *
  11559. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  11560. * tracks; otherwise, <tt>false</tt>
  11561. * @param callback a function to be invoked with <tt>mute</tt> after all video
  11562. * tracks have been enabled/disabled. The function may, optionally, return
  11563. * another function which is to be invoked after the whole mute/unmute operation
  11564. * has completed successfully.
  11565. * @param options an object which specifies optional arguments such as the
  11566. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  11567. * specifies whether the method was initiated in response to a user command (in
  11568. * contrast to an automatic decision made by the application logic)
  11569. */
  11570. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  11571. var byUser;
  11572. if (options) {
  11573. byUser = options.byUser;
  11574. if (typeof byUser === 'undefined') {
  11575. byUser = true;
  11576. }
  11577. } else {
  11578. byUser = true;
  11579. }
  11580. // The user's command to mute the (local) video takes precedence over any
  11581. // automatic decision made by the application logic.
  11582. if (byUser) {
  11583. this.videoMuteByUser = mute;
  11584. } else if (this.videoMuteByUser) {
  11585. return;
  11586. }
  11587. this.hardMuteVideo(mute);
  11588. this.modifySources(callback(mute));
  11589. };
  11590. JingleSession.prototype.hardMuteVideo = function (muted) {
  11591. this.pendingop = muted ? 'mute' : 'unmute';
  11592. };
  11593. JingleSession.prototype.sendMute = function (muted, content) {
  11594. var info = $iq({to: this.peerjid,
  11595. type: 'set'})
  11596. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11597. action: 'session-info',
  11598. initiator: this.initiator,
  11599. sid: this.sid });
  11600. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11601. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  11602. if (content) {
  11603. info.attrs({'name': content});
  11604. }
  11605. this.connection.send(info);
  11606. };
  11607. JingleSession.prototype.sendRinging = function () {
  11608. var info = $iq({to: this.peerjid,
  11609. type: 'set'})
  11610. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11611. action: 'session-info',
  11612. initiator: this.initiator,
  11613. sid: this.sid });
  11614. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11615. this.connection.send(info);
  11616. };
  11617. JingleSession.prototype.getStats = function (interval) {
  11618. var self = this;
  11619. var recv = {audio: 0, video: 0};
  11620. var lost = {audio: 0, video: 0};
  11621. var lastrecv = {audio: 0, video: 0};
  11622. var lastlost = {audio: 0, video: 0};
  11623. var loss = {audio: 0, video: 0};
  11624. var delta = {audio: 0, video: 0};
  11625. this.statsinterval = window.setInterval(function () {
  11626. if (self && self.peerconnection && self.peerconnection.getStats) {
  11627. self.peerconnection.getStats(function (stats) {
  11628. var results = stats.result();
  11629. // TODO: there are so much statistics you can get from this..
  11630. for (var i = 0; i < results.length; ++i) {
  11631. if (results[i].type == 'ssrc') {
  11632. var packetsrecv = results[i].stat('packetsReceived');
  11633. var packetslost = results[i].stat('packetsLost');
  11634. if (packetsrecv && packetslost) {
  11635. packetsrecv = parseInt(packetsrecv, 10);
  11636. packetslost = parseInt(packetslost, 10);
  11637. if (results[i].stat('googFrameRateReceived')) {
  11638. lastlost.video = lost.video;
  11639. lastrecv.video = recv.video;
  11640. recv.video = packetsrecv;
  11641. lost.video = packetslost;
  11642. } else {
  11643. lastlost.audio = lost.audio;
  11644. lastrecv.audio = recv.audio;
  11645. recv.audio = packetsrecv;
  11646. lost.audio = packetslost;
  11647. }
  11648. }
  11649. }
  11650. }
  11651. delta.audio = recv.audio - lastrecv.audio;
  11652. delta.video = recv.video - lastrecv.video;
  11653. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  11654. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  11655. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  11656. });
  11657. }
  11658. }, interval || 3000);
  11659. return this.statsinterval;
  11660. };
  11661. JingleSession.onJingleError = function (session, error)
  11662. {
  11663. console.error("Jingle error", error);
  11664. }
  11665. JingleSession.onJingleFatalError = function (session, error)
  11666. {
  11667. this.service.sessionTerminated = true;
  11668. this.connection.emuc.doLeave();
  11669. APP.UI.messageHandler.showError("dialog.sorry",
  11670. "dialog.internalError");
  11671. }
  11672. JingleSession.prototype.setLocalDescription = function () {
  11673. // put our ssrcs into presence so other clients can identify our stream
  11674. var newssrcs = [];
  11675. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  11676. media.forEach(function (media) {
  11677. if(Object.keys(media.sources).length > 0) {
  11678. // TODO(gp) maybe exclude FID streams?
  11679. Object.keys(media.sources).forEach(function (ssrc) {
  11680. newssrcs.push({
  11681. 'ssrc': ssrc,
  11682. 'type': media.type,
  11683. 'direction': media.direction
  11684. });
  11685. });
  11686. }
  11687. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  11688. {
  11689. newssrcs.push({
  11690. 'ssrc': this.localStreamsSSRC[media.type],
  11691. 'type': media.type,
  11692. 'direction': media.direction
  11693. });
  11694. }
  11695. });
  11696. console.log('new ssrcs', newssrcs);
  11697. // Have to clear presence map to get rid of removed streams
  11698. this.connection.emuc.clearPresenceMedia();
  11699. if (newssrcs.length > 0) {
  11700. for (var i = 1; i <= newssrcs.length; i ++) {
  11701. // Change video type to screen
  11702. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  11703. newssrcs[i-1].type = 'screen';
  11704. }
  11705. this.connection.emuc.addMediaToPresence(i,
  11706. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  11707. }
  11708. this.connection.emuc.sendPresence();
  11709. }
  11710. }
  11711. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11712. function sendKeyframe(pc) {
  11713. console.log('sendkeyframe', pc.iceConnectionState);
  11714. if (pc.iceConnectionState !== 'connected') return; // safe...
  11715. pc.setRemoteDescription(
  11716. pc.remoteDescription,
  11717. function () {
  11718. pc.createAnswer(
  11719. function (modifiedAnswer) {
  11720. pc.setLocalDescription(
  11721. modifiedAnswer,
  11722. function () {
  11723. // noop
  11724. },
  11725. function (error) {
  11726. console.log('triggerKeyframe setLocalDescription failed', error);
  11727. APP.UI.messageHandler.showError();
  11728. }
  11729. );
  11730. },
  11731. function (error) {
  11732. console.log('triggerKeyframe createAnswer failed', error);
  11733. APP.UI.messageHandler.showError();
  11734. }
  11735. );
  11736. },
  11737. function (error) {
  11738. console.log('triggerKeyframe setRemoteDescription failed', error);
  11739. APP.UI.messageHandler.showError();
  11740. }
  11741. );
  11742. }
  11743. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  11744. var self = this;
  11745. var thessrc;
  11746. var ssrc2jid = this.connection.emuc.ssrc2jid;
  11747. // look up an associated JID for a stream id
  11748. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  11749. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  11750. var ssrclines
  11751. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  11752. ssrclines = ssrclines.filter(function (line) {
  11753. // NOTE(gp) previously we filtered on the mslabel, but that property
  11754. // is not always present.
  11755. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  11756. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  11757. });
  11758. if (ssrclines.length) {
  11759. thessrc = ssrclines[0].substring(7).split(' ')[0];
  11760. // We signal our streams (through Jingle to the focus) before we set
  11761. // our presence (through which peers associate remote streams to
  11762. // jids). So, it might arrive that a remote stream is added but
  11763. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  11764. // successfully set. Here we wait for up to a second for the
  11765. // presence to arrive.
  11766. if (!ssrc2jid[thessrc]) {
  11767. if (typeof times === 'undefined')
  11768. {
  11769. times = 0;
  11770. }
  11771. if (times > 10)
  11772. {
  11773. console.warning('Waiting for jid timed out', thessrc);
  11774. }
  11775. else
  11776. {
  11777. setTimeout(function(d) {
  11778. return function() {
  11779. self.remoteStreamAdded(d, times++);
  11780. }
  11781. }(data), 250);
  11782. }
  11783. return;
  11784. }
  11785. // ok to overwrite the one from focus? might save work in colibri.js
  11786. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  11787. if (ssrc2jid[thessrc]) {
  11788. data.peerjid = ssrc2jid[thessrc];
  11789. }
  11790. }
  11791. }
  11792. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  11793. var isVideo = data.stream.getVideoTracks().length > 0;
  11794. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11795. if (isVideo &&
  11796. data.peerjid && this.peerjid === data.peerjid &&
  11797. data.stream.getVideoTracks().length === 0 &&
  11798. APP.RTC.localVideo.getTracks().length > 0) {
  11799. window.setTimeout(function () {
  11800. sendKeyframe(self.peerconnection);
  11801. }, 3000);
  11802. }
  11803. }
  11804. module.exports = JingleSession;
  11805. },{"../../service/RTC/RTCBrowserType":88,"./SDP":49,"./SDPDiffer":50,"./SDPUtil":51,"./TraceablePeerConnection":52}],49:[function(require,module,exports){
  11806. /* jshint -W117 */
  11807. var SDPUtil = require("./SDPUtil");
  11808. // SDP STUFF
  11809. function SDP(sdp) {
  11810. this.media = sdp.split('\r\nm=');
  11811. for (var i = 1; i < this.media.length; i++) {
  11812. this.media[i] = 'm=' + this.media[i];
  11813. if (i != this.media.length - 1) {
  11814. this.media[i] += '\r\n';
  11815. }
  11816. }
  11817. this.session = this.media.shift() + '\r\n';
  11818. this.raw = this.session + this.media.join('');
  11819. }
  11820. /**
  11821. * Returns map of MediaChannel mapped per channel idx.
  11822. */
  11823. SDP.prototype.getMediaSsrcMap = function() {
  11824. var self = this;
  11825. var media_ssrcs = {};
  11826. var tmp;
  11827. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  11828. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  11829. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  11830. var media = {
  11831. mediaindex: mediaindex,
  11832. mid: mid,
  11833. ssrcs: {},
  11834. ssrcGroups: []
  11835. };
  11836. media_ssrcs[mediaindex] = media;
  11837. tmp.forEach(function (line) {
  11838. var linessrc = line.substring(7).split(' ')[0];
  11839. // allocate new ChannelSsrc
  11840. if(!media.ssrcs[linessrc]) {
  11841. media.ssrcs[linessrc] = {
  11842. ssrc: linessrc,
  11843. lines: []
  11844. };
  11845. }
  11846. media.ssrcs[linessrc].lines.push(line);
  11847. });
  11848. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  11849. tmp.forEach(function(line){
  11850. var semantics = line.substr(0, idx).substr(13);
  11851. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11852. if (ssrcs.length != 0) {
  11853. media.ssrcGroups.push({
  11854. semantics: semantics,
  11855. ssrcs: ssrcs
  11856. });
  11857. }
  11858. });
  11859. }
  11860. return media_ssrcs;
  11861. };
  11862. /**
  11863. * Returns <tt>true</tt> if this SDP contains given SSRC.
  11864. * @param ssrc the ssrc to check.
  11865. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  11866. */
  11867. SDP.prototype.containsSSRC = function(ssrc) {
  11868. var medias = this.getMediaSsrcMap();
  11869. var contains = false;
  11870. Object.keys(medias).forEach(function(mediaindex){
  11871. var media = medias[mediaindex];
  11872. //console.log("Check", channel, ssrc);
  11873. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  11874. contains = true;
  11875. }
  11876. });
  11877. return contains;
  11878. };
  11879. // remove iSAC and CN from SDP
  11880. SDP.prototype.mangle = function () {
  11881. var i, j, mline, lines, rtpmap, newdesc;
  11882. for (i = 0; i < this.media.length; i++) {
  11883. lines = this.media[i].split('\r\n');
  11884. lines.pop(); // remove empty last element
  11885. mline = SDPUtil.parse_mline(lines.shift());
  11886. if (mline.media != 'audio')
  11887. continue;
  11888. newdesc = '';
  11889. mline.fmt.length = 0;
  11890. for (j = 0; j < lines.length; j++) {
  11891. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  11892. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  11893. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  11894. continue;
  11895. mline.fmt.push(rtpmap.id);
  11896. newdesc += lines[j] + '\r\n';
  11897. } else {
  11898. newdesc += lines[j] + '\r\n';
  11899. }
  11900. }
  11901. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  11902. this.media[i] += newdesc;
  11903. }
  11904. this.raw = this.session + this.media.join('');
  11905. };
  11906. // remove lines matching prefix from session section
  11907. SDP.prototype.removeSessionLines = function(prefix) {
  11908. var self = this;
  11909. var lines = SDPUtil.find_lines(this.session, prefix);
  11910. lines.forEach(function(line) {
  11911. self.session = self.session.replace(line + '\r\n', '');
  11912. });
  11913. this.raw = this.session + this.media.join('');
  11914. return lines;
  11915. }
  11916. // remove lines matching prefix from a media section specified by mediaindex
  11917. // TODO: non-numeric mediaindex could match mid
  11918. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  11919. var self = this;
  11920. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  11921. lines.forEach(function(line) {
  11922. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  11923. });
  11924. this.raw = this.session + this.media.join('');
  11925. return lines;
  11926. }
  11927. // add content's to a jingle element
  11928. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  11929. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  11930. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  11931. var self = this;
  11932. // new bundle plan
  11933. if (SDPUtil.find_line(this.session, 'a=group:')) {
  11934. lines = SDPUtil.find_lines(this.session, 'a=group:');
  11935. for (i = 0; i < lines.length; i++) {
  11936. tmp = lines[i].split(' ');
  11937. var semantics = tmp.shift().substr(8);
  11938. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  11939. for (j = 0; j < tmp.length; j++) {
  11940. elem.c('content', {name: tmp[j]}).up();
  11941. }
  11942. elem.up();
  11943. }
  11944. }
  11945. for (i = 0; i < this.media.length; i++) {
  11946. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  11947. if (!(mline.media === 'audio' ||
  11948. mline.media === 'video' ||
  11949. mline.media === 'application'))
  11950. {
  11951. continue;
  11952. }
  11953. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  11954. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  11955. } else {
  11956. if(ssrcs && ssrcs[mline.media])
  11957. {
  11958. ssrc = ssrcs[mline.media];
  11959. }
  11960. else
  11961. ssrc = false;
  11962. }
  11963. elem.c('content', {creator: thecreator, name: mline.media});
  11964. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  11965. // prefer identifier from a=mid if present
  11966. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  11967. elem.attrs({ name: mid });
  11968. }
  11969. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  11970. {
  11971. elem.c('description',
  11972. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  11973. media: mline.media });
  11974. if (ssrc) {
  11975. elem.attrs({ssrc: ssrc});
  11976. }
  11977. for (j = 0; j < mline.fmt.length; j++) {
  11978. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  11979. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  11980. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  11981. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  11982. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  11983. for (k = 0; k < tmp.length; k++) {
  11984. elem.c('parameter', tmp[k]).up();
  11985. }
  11986. }
  11987. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  11988. elem.up();
  11989. }
  11990. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  11991. elem.c('encryption', {required: 1});
  11992. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  11993. crypto.forEach(function(line) {
  11994. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  11995. });
  11996. elem.up(); // end of encryption
  11997. }
  11998. if (ssrc) {
  11999. // new style mapping
  12000. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12001. // FIXME: group by ssrc and support multiple different ssrcs
  12002. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  12003. if(ssrclines.length > 0) {
  12004. ssrclines.forEach(function (line) {
  12005. idx = line.indexOf(' ');
  12006. var linessrc = line.substr(0, idx).substr(7);
  12007. if (linessrc != ssrc) {
  12008. elem.up();
  12009. ssrc = linessrc;
  12010. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12011. }
  12012. var kv = line.substr(idx + 1);
  12013. elem.c('parameter');
  12014. if (kv.indexOf(':') == -1) {
  12015. elem.attrs({ name: kv });
  12016. } else {
  12017. elem.attrs({ name: kv.split(':', 2)[0] });
  12018. elem.attrs({ value: kv.split(':', 2)[1] });
  12019. }
  12020. elem.up();
  12021. });
  12022. elem.up();
  12023. }
  12024. else
  12025. {
  12026. elem.up();
  12027. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12028. elem.c('parameter');
  12029. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  12030. elem.up();
  12031. var msid = null;
  12032. if(mline.media == "audio")
  12033. {
  12034. msid = APP.RTC.localAudio.getId();
  12035. }
  12036. else
  12037. {
  12038. msid = APP.RTC.localVideo.getId();
  12039. }
  12040. if(msid != null)
  12041. {
  12042. msid = msid.replace(/[\{,\}]/g,"");
  12043. elem.c('parameter');
  12044. elem.attrs({name: "msid", value:msid});
  12045. elem.up();
  12046. elem.c('parameter');
  12047. elem.attrs({name: "mslabel", value:msid});
  12048. elem.up();
  12049. elem.c('parameter');
  12050. elem.attrs({name: "label", value:msid});
  12051. elem.up();
  12052. elem.up();
  12053. }
  12054. }
  12055. // XEP-0339 handle ssrc-group attributes
  12056. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  12057. ssrc_group_lines.forEach(function(line) {
  12058. idx = line.indexOf(' ');
  12059. var semantics = line.substr(0, idx).substr(13);
  12060. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12061. if (ssrcs.length != 0) {
  12062. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12063. ssrcs.forEach(function(ssrc) {
  12064. elem.c('source', { ssrc: ssrc })
  12065. .up();
  12066. });
  12067. elem.up();
  12068. }
  12069. });
  12070. }
  12071. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  12072. elem.c('rtcp-mux').up();
  12073. }
  12074. // XEP-0293 -- map a=rtcp-fb:*
  12075. this.RtcpFbToJingle(i, elem, '*');
  12076. // XEP-0294
  12077. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  12078. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  12079. for (j = 0; j < lines.length; j++) {
  12080. tmp = SDPUtil.parse_extmap(lines[j]);
  12081. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  12082. uri: tmp.uri,
  12083. id: tmp.value });
  12084. if (tmp.hasOwnProperty('direction')) {
  12085. switch (tmp.direction) {
  12086. case 'sendonly':
  12087. elem.attrs({senders: 'responder'});
  12088. break;
  12089. case 'recvonly':
  12090. elem.attrs({senders: 'initiator'});
  12091. break;
  12092. case 'sendrecv':
  12093. elem.attrs({senders: 'both'});
  12094. break;
  12095. case 'inactive':
  12096. elem.attrs({senders: 'none'});
  12097. break;
  12098. }
  12099. }
  12100. // TODO: handle params
  12101. elem.up();
  12102. }
  12103. }
  12104. elem.up(); // end of description
  12105. }
  12106. // map ice-ufrag/pwd, dtls fingerprint, candidates
  12107. this.TransportToJingle(i, elem);
  12108. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  12109. elem.attrs({senders: 'both'});
  12110. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  12111. elem.attrs({senders: 'initiator'});
  12112. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  12113. elem.attrs({senders: 'responder'});
  12114. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  12115. elem.attrs({senders: 'none'});
  12116. }
  12117. if (mline.port == '0') {
  12118. // estos hack to reject an m-line
  12119. elem.attrs({senders: 'rejected'});
  12120. }
  12121. elem.up(); // end of content
  12122. }
  12123. elem.up();
  12124. return elem;
  12125. };
  12126. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  12127. var i = mediaindex;
  12128. var tmp;
  12129. var self = this;
  12130. elem.c('transport');
  12131. // XEP-0343 DTLS/SCTP
  12132. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  12133. {
  12134. var sctpmap = SDPUtil.find_line(
  12135. this.media[i], 'a=sctpmap:', self.session);
  12136. if (sctpmap)
  12137. {
  12138. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  12139. elem.c('sctpmap',
  12140. {
  12141. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  12142. number: sctpAttrs[0], /* SCTP port */
  12143. protocol: sctpAttrs[1], /* protocol */
  12144. });
  12145. // Optional stream count attribute
  12146. if (sctpAttrs.length > 2)
  12147. elem.attrs({ streams: sctpAttrs[2]});
  12148. elem.up();
  12149. }
  12150. }
  12151. // XEP-0320
  12152. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  12153. fingerprints.forEach(function(line) {
  12154. tmp = SDPUtil.parse_fingerprint(line);
  12155. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  12156. elem.c('fingerprint').t(tmp.fingerprint);
  12157. delete tmp.fingerprint;
  12158. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  12159. if (line) {
  12160. tmp.setup = line.substr(8);
  12161. }
  12162. elem.attrs(tmp);
  12163. elem.up(); // end of fingerprint
  12164. });
  12165. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  12166. if (tmp) {
  12167. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12168. elem.attrs(tmp);
  12169. // XEP-0176
  12170. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  12171. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  12172. lines.forEach(function (line) {
  12173. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  12174. });
  12175. }
  12176. }
  12177. elem.up(); // end of transport
  12178. }
  12179. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  12180. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  12181. lines.forEach(function (line) {
  12182. var tmp = SDPUtil.parse_rtcpfb(line);
  12183. if (tmp.type == 'trr-int') {
  12184. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  12185. elem.up();
  12186. } else {
  12187. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  12188. if (tmp.params.length > 0) {
  12189. elem.attrs({'subtype': tmp.params[0]});
  12190. }
  12191. elem.up();
  12192. }
  12193. });
  12194. };
  12195. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  12196. var media = '';
  12197. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12198. if (tmp.length) {
  12199. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  12200. if (tmp.attr('value')) {
  12201. media += tmp.attr('value');
  12202. } else {
  12203. media += '0';
  12204. }
  12205. media += '\r\n';
  12206. }
  12207. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12208. tmp.each(function () {
  12209. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  12210. if ($(this).attr('subtype')) {
  12211. media += ' ' + $(this).attr('subtype');
  12212. }
  12213. media += '\r\n';
  12214. });
  12215. return media;
  12216. };
  12217. // construct an SDP from a jingle stanza
  12218. SDP.prototype.fromJingle = function (jingle) {
  12219. var self = this;
  12220. this.raw = 'v=0\r\n' +
  12221. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12222. 's=-\r\n' +
  12223. 't=0 0\r\n';
  12224. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  12225. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  12226. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  12227. var contents = $(group).find('>content').map(function (idx, content) {
  12228. return content.getAttribute('name');
  12229. }).get();
  12230. if (contents.length > 0) {
  12231. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  12232. }
  12233. });
  12234. }
  12235. this.session = this.raw;
  12236. jingle.find('>content').each(function () {
  12237. var m = self.jingle2media($(this));
  12238. self.media.push(m);
  12239. });
  12240. // reconstruct msid-semantic -- apparently not necessary
  12241. /*
  12242. var msid = SDPUtil.parse_ssrc(this.raw);
  12243. if (msid.hasOwnProperty('mslabel')) {
  12244. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  12245. }
  12246. */
  12247. this.raw = this.session + this.media.join('');
  12248. };
  12249. // translate a jingle content element into an an SDP media part
  12250. SDP.prototype.jingle2media = function (content) {
  12251. var media = '',
  12252. desc = content.find('description'),
  12253. ssrc = desc.attr('ssrc'),
  12254. self = this,
  12255. tmp;
  12256. var sctp = content.find(
  12257. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  12258. tmp = { media: desc.attr('media') };
  12259. tmp.port = '1';
  12260. if (content.attr('senders') == 'rejected') {
  12261. // estos hack to reject an m-line.
  12262. tmp.port = '0';
  12263. }
  12264. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  12265. if (sctp.length)
  12266. tmp.proto = 'DTLS/SCTP';
  12267. else
  12268. tmp.proto = 'RTP/SAVPF';
  12269. } else {
  12270. tmp.proto = 'RTP/AVPF';
  12271. }
  12272. if (!sctp.length)
  12273. {
  12274. tmp.fmt = desc.find('payload-type').map(
  12275. function () { return this.getAttribute('id'); }).get();
  12276. media += SDPUtil.build_mline(tmp) + '\r\n';
  12277. }
  12278. else
  12279. {
  12280. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  12281. media += 'a=sctpmap:' + sctp.attr('number') +
  12282. ' ' + sctp.attr('protocol');
  12283. var streamCount = sctp.attr('streams');
  12284. if (streamCount)
  12285. media += ' ' + streamCount + '\r\n';
  12286. else
  12287. media += '\r\n';
  12288. }
  12289. media += 'c=IN IP4 0.0.0.0\r\n';
  12290. if (!sctp.length)
  12291. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  12292. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  12293. if (tmp.length) {
  12294. if (tmp.attr('ufrag')) {
  12295. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  12296. }
  12297. if (tmp.attr('pwd')) {
  12298. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  12299. }
  12300. tmp.find('>fingerprint').each(function () {
  12301. // FIXME: check namespace at some point
  12302. media += 'a=fingerprint:' + this.getAttribute('hash');
  12303. media += ' ' + $(this).text();
  12304. media += '\r\n';
  12305. if (this.getAttribute('setup')) {
  12306. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  12307. }
  12308. });
  12309. }
  12310. switch (content.attr('senders')) {
  12311. case 'initiator':
  12312. media += 'a=sendonly\r\n';
  12313. break;
  12314. case 'responder':
  12315. media += 'a=recvonly\r\n';
  12316. break;
  12317. case 'none':
  12318. media += 'a=inactive\r\n';
  12319. break;
  12320. case 'both':
  12321. media += 'a=sendrecv\r\n';
  12322. break;
  12323. }
  12324. media += 'a=mid:' + content.attr('name') + '\r\n';
  12325. // <description><rtcp-mux/></description>
  12326. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  12327. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  12328. if (desc.find('rtcp-mux').length) {
  12329. media += 'a=rtcp-mux\r\n';
  12330. }
  12331. if (desc.find('encryption').length) {
  12332. desc.find('encryption>crypto').each(function () {
  12333. media += 'a=crypto:' + this.getAttribute('tag');
  12334. media += ' ' + this.getAttribute('crypto-suite');
  12335. media += ' ' + this.getAttribute('key-params');
  12336. if (this.getAttribute('session-params')) {
  12337. media += ' ' + this.getAttribute('session-params');
  12338. }
  12339. media += '\r\n';
  12340. });
  12341. }
  12342. desc.find('payload-type').each(function () {
  12343. media += SDPUtil.build_rtpmap(this) + '\r\n';
  12344. if ($(this).find('>parameter').length) {
  12345. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  12346. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  12347. media += '\r\n';
  12348. }
  12349. // xep-0293
  12350. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  12351. });
  12352. // xep-0293
  12353. media += self.RtcpFbFromJingle(desc, '*');
  12354. // xep-0294
  12355. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  12356. tmp.each(function () {
  12357. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  12358. });
  12359. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  12360. media += SDPUtil.candidateFromJingle(this);
  12361. });
  12362. // XEP-0339 handle ssrc-group attributes
  12363. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12364. var semantics = this.getAttribute('semantics');
  12365. var ssrcs = $(this).find('>source').map(function() {
  12366. return this.getAttribute('ssrc');
  12367. }).get();
  12368. if (ssrcs.length != 0) {
  12369. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12370. }
  12371. });
  12372. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12373. tmp.each(function () {
  12374. var ssrc = this.getAttribute('ssrc');
  12375. $(this).find('>parameter').each(function () {
  12376. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  12377. if (this.getAttribute('value') && this.getAttribute('value').length)
  12378. media += ':' + this.getAttribute('value');
  12379. media += '\r\n';
  12380. });
  12381. });
  12382. return media;
  12383. };
  12384. module.exports = SDP;
  12385. },{"./SDPUtil":51}],50:[function(require,module,exports){
  12386. function SDPDiffer(mySDP, otherSDP) {
  12387. this.mySDP = mySDP;
  12388. this.otherSDP = otherSDP;
  12389. }
  12390. /**
  12391. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  12392. * @param otherSdp the other SDP to check ssrc with.
  12393. */
  12394. SDPDiffer.prototype.getNewMedia = function() {
  12395. // this could be useful in Array.prototype.
  12396. function arrayEquals(array) {
  12397. // if the other array is a falsy value, return
  12398. if (!array)
  12399. return false;
  12400. // compare lengths - can save a lot of time
  12401. if (this.length != array.length)
  12402. return false;
  12403. for (var i = 0, l=this.length; i < l; i++) {
  12404. // Check if we have nested arrays
  12405. if (this[i] instanceof Array && array[i] instanceof Array) {
  12406. // recurse into the nested arrays
  12407. if (!this[i].equals(array[i]))
  12408. return false;
  12409. }
  12410. else if (this[i] != array[i]) {
  12411. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12412. return false;
  12413. }
  12414. }
  12415. return true;
  12416. }
  12417. var myMedias = this.mySDP.getMediaSsrcMap();
  12418. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12419. var newMedia = {};
  12420. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12421. var myMedia = myMedias[othersMediaIdx];
  12422. var othersMedia = othersMedias[othersMediaIdx];
  12423. if(!myMedia && othersMedia) {
  12424. // Add whole channel
  12425. newMedia[othersMediaIdx] = othersMedia;
  12426. return;
  12427. }
  12428. // Look for new ssrcs accross the channel
  12429. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12430. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12431. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12432. if(!newMedia[othersMediaIdx]){
  12433. newMedia[othersMediaIdx] = {
  12434. mediaindex: othersMedia.mediaindex,
  12435. mid: othersMedia.mid,
  12436. ssrcs: {},
  12437. ssrcGroups: []
  12438. };
  12439. }
  12440. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12441. }
  12442. });
  12443. // Look for new ssrc groups across the channels
  12444. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12445. // try to match the other ssrc-group with an ssrc-group of ours
  12446. var matched = false;
  12447. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12448. var mySsrcGroup = myMedia.ssrcGroups[i];
  12449. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12450. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12451. matched = true;
  12452. break;
  12453. }
  12454. }
  12455. if (!matched) {
  12456. // Allocate channel if we've found an ssrc-group that doesn't
  12457. // exist in our channel
  12458. if(!newMedia[othersMediaIdx]){
  12459. newMedia[othersMediaIdx] = {
  12460. mediaindex: othersMedia.mediaindex,
  12461. mid: othersMedia.mid,
  12462. ssrcs: {},
  12463. ssrcGroups: []
  12464. };
  12465. }
  12466. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12467. }
  12468. });
  12469. });
  12470. return newMedia;
  12471. };
  12472. /**
  12473. * Sends SSRC update IQ.
  12474. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12475. * @param sid session identifier that will be put into the IQ.
  12476. * @param initiator initiator identifier.
  12477. * @param toJid destination Jid
  12478. * @param isAdd indicates if this is remove or add operation.
  12479. */
  12480. SDPDiffer.prototype.toJingle = function(modify) {
  12481. var sdpMediaSsrcs = this.getNewMedia();
  12482. var self = this;
  12483. // FIXME: only announce video ssrcs since we mix audio and dont need
  12484. // the audio ssrcs therefore
  12485. var modified = false;
  12486. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12487. modified = true;
  12488. var media = sdpMediaSsrcs[mediaindex];
  12489. modify.c('content', {name: media.mid});
  12490. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12491. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12492. // generate sources from lines
  12493. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12494. var mediaSsrc = media.ssrcs[ssrcNum];
  12495. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12496. modify.attrs({ssrc: mediaSsrc.ssrc});
  12497. // iterate over ssrc lines
  12498. mediaSsrc.lines.forEach(function (line) {
  12499. var idx = line.indexOf(' ');
  12500. var kv = line.substr(idx + 1);
  12501. modify.c('parameter');
  12502. if (kv.indexOf(':') == -1) {
  12503. modify.attrs({ name: kv });
  12504. } else {
  12505. modify.attrs({ name: kv.split(':', 2)[0] });
  12506. modify.attrs({ value: kv.split(':', 2)[1] });
  12507. }
  12508. modify.up(); // end of parameter
  12509. });
  12510. modify.up(); // end of source
  12511. });
  12512. // generate source groups from lines
  12513. media.ssrcGroups.forEach(function(ssrcGroup) {
  12514. if (ssrcGroup.ssrcs.length != 0) {
  12515. modify.c('ssrc-group', {
  12516. semantics: ssrcGroup.semantics,
  12517. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12518. });
  12519. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12520. modify.c('source', { ssrc: ssrc })
  12521. .up(); // end of source
  12522. });
  12523. modify.up(); // end of ssrc-group
  12524. }
  12525. });
  12526. modify.up(); // end of description
  12527. modify.up(); // end of content
  12528. });
  12529. return modified;
  12530. };
  12531. module.exports = SDPDiffer;
  12532. },{}],51:[function(require,module,exports){
  12533. SDPUtil = {
  12534. iceparams: function (mediadesc, sessiondesc) {
  12535. var data = null;
  12536. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  12537. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  12538. data = {
  12539. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  12540. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  12541. };
  12542. }
  12543. return data;
  12544. },
  12545. parse_iceufrag: function (line) {
  12546. return line.substring(12);
  12547. },
  12548. build_iceufrag: function (frag) {
  12549. return 'a=ice-ufrag:' + frag;
  12550. },
  12551. parse_icepwd: function (line) {
  12552. return line.substring(10);
  12553. },
  12554. build_icepwd: function (pwd) {
  12555. return 'a=ice-pwd:' + pwd;
  12556. },
  12557. parse_mid: function (line) {
  12558. return line.substring(6);
  12559. },
  12560. parse_mline: function (line) {
  12561. var parts = line.substring(2).split(' '),
  12562. data = {};
  12563. data.media = parts.shift();
  12564. data.port = parts.shift();
  12565. data.proto = parts.shift();
  12566. if (parts[parts.length - 1] === '') { // trailing whitespace
  12567. parts.pop();
  12568. }
  12569. data.fmt = parts;
  12570. return data;
  12571. },
  12572. build_mline: function (mline) {
  12573. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  12574. },
  12575. parse_rtpmap: function (line) {
  12576. var parts = line.substring(9).split(' '),
  12577. data = {};
  12578. data.id = parts.shift();
  12579. parts = parts[0].split('/');
  12580. data.name = parts.shift();
  12581. data.clockrate = parts.shift();
  12582. data.channels = parts.length ? parts.shift() : '1';
  12583. return data;
  12584. },
  12585. /**
  12586. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  12587. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  12588. * @returns [SCTP port number, protocol, streams]
  12589. */
  12590. parse_sctpmap: function (line)
  12591. {
  12592. var parts = line.substring(10).split(' ');
  12593. var sctpPort = parts[0];
  12594. var protocol = parts[1];
  12595. // Stream count is optional
  12596. var streamCount = parts.length > 2 ? parts[2] : null;
  12597. return [sctpPort, protocol, streamCount];// SCTP port
  12598. },
  12599. build_rtpmap: function (el) {
  12600. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  12601. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  12602. line += '/' + el.getAttribute('channels');
  12603. }
  12604. return line;
  12605. },
  12606. parse_crypto: function (line) {
  12607. var parts = line.substring(9).split(' '),
  12608. data = {};
  12609. data.tag = parts.shift();
  12610. data['crypto-suite'] = parts.shift();
  12611. data['key-params'] = parts.shift();
  12612. if (parts.length) {
  12613. data['session-params'] = parts.join(' ');
  12614. }
  12615. return data;
  12616. },
  12617. parse_fingerprint: function (line) { // RFC 4572
  12618. var parts = line.substring(14).split(' '),
  12619. data = {};
  12620. data.hash = parts.shift();
  12621. data.fingerprint = parts.shift();
  12622. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  12623. return data;
  12624. },
  12625. parse_fmtp: function (line) {
  12626. var parts = line.split(' '),
  12627. i, key, value,
  12628. data = [];
  12629. parts.shift();
  12630. parts = parts.join(' ').split(';');
  12631. for (i = 0; i < parts.length; i++) {
  12632. key = parts[i].split('=')[0];
  12633. while (key.length && key[0] == ' ') {
  12634. key = key.substring(1);
  12635. }
  12636. value = parts[i].split('=')[1];
  12637. if (key && value) {
  12638. data.push({name: key, value: value});
  12639. } else if (key) {
  12640. // rfc 4733 (DTMF) style stuff
  12641. data.push({name: '', value: key});
  12642. }
  12643. }
  12644. return data;
  12645. },
  12646. parse_icecandidate: function (line) {
  12647. var candidate = {},
  12648. elems = line.split(' ');
  12649. candidate.foundation = elems[0].substring(12);
  12650. candidate.component = elems[1];
  12651. candidate.protocol = elems[2].toLowerCase();
  12652. candidate.priority = elems[3];
  12653. candidate.ip = elems[4];
  12654. candidate.port = elems[5];
  12655. // elems[6] => "typ"
  12656. candidate.type = elems[7];
  12657. candidate.generation = 0; // default value, may be overwritten below
  12658. for (var i = 8; i < elems.length; i += 2) {
  12659. switch (elems[i]) {
  12660. case 'raddr':
  12661. candidate['rel-addr'] = elems[i + 1];
  12662. break;
  12663. case 'rport':
  12664. candidate['rel-port'] = elems[i + 1];
  12665. break;
  12666. case 'generation':
  12667. candidate.generation = elems[i + 1];
  12668. break;
  12669. case 'tcptype':
  12670. candidate.tcptype = elems[i + 1];
  12671. break;
  12672. default: // TODO
  12673. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12674. }
  12675. }
  12676. candidate.network = '1';
  12677. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12678. return candidate;
  12679. },
  12680. build_icecandidate: function (cand) {
  12681. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  12682. line += ' ';
  12683. switch (cand.type) {
  12684. case 'srflx':
  12685. case 'prflx':
  12686. case 'relay':
  12687. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  12688. line += 'raddr';
  12689. line += ' ';
  12690. line += cand['rel-addr'];
  12691. line += ' ';
  12692. line += 'rport';
  12693. line += ' ';
  12694. line += cand['rel-port'];
  12695. line += ' ';
  12696. }
  12697. break;
  12698. }
  12699. if (cand.hasOwnAttribute('tcptype')) {
  12700. line += 'tcptype';
  12701. line += ' ';
  12702. line += cand.tcptype;
  12703. line += ' ';
  12704. }
  12705. line += 'generation';
  12706. line += ' ';
  12707. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  12708. return line;
  12709. },
  12710. parse_ssrc: function (desc) {
  12711. // proprietary mapping of a=ssrc lines
  12712. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  12713. // and parse according to that
  12714. var lines = desc.split('\r\n'),
  12715. data = {};
  12716. for (var i = 0; i < lines.length; i++) {
  12717. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  12718. var idx = lines[i].indexOf(' ');
  12719. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  12720. }
  12721. }
  12722. return data;
  12723. },
  12724. parse_rtcpfb: function (line) {
  12725. var parts = line.substr(10).split(' ');
  12726. var data = {};
  12727. data.pt = parts.shift();
  12728. data.type = parts.shift();
  12729. data.params = parts;
  12730. return data;
  12731. },
  12732. parse_extmap: function (line) {
  12733. var parts = line.substr(9).split(' ');
  12734. var data = {};
  12735. data.value = parts.shift();
  12736. if (data.value.indexOf('/') != -1) {
  12737. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  12738. data.value = data.value.substr(0, data.value.indexOf('/'));
  12739. } else {
  12740. data.direction = 'both';
  12741. }
  12742. data.uri = parts.shift();
  12743. data.params = parts;
  12744. return data;
  12745. },
  12746. find_line: function (haystack, needle, sessionpart) {
  12747. var lines = haystack.split('\r\n');
  12748. for (var i = 0; i < lines.length; i++) {
  12749. if (lines[i].substring(0, needle.length) == needle) {
  12750. return lines[i];
  12751. }
  12752. }
  12753. if (!sessionpart) {
  12754. return false;
  12755. }
  12756. // search session part
  12757. lines = sessionpart.split('\r\n');
  12758. for (var j = 0; j < lines.length; j++) {
  12759. if (lines[j].substring(0, needle.length) == needle) {
  12760. return lines[j];
  12761. }
  12762. }
  12763. return false;
  12764. },
  12765. find_lines: function (haystack, needle, sessionpart) {
  12766. var lines = haystack.split('\r\n'),
  12767. needles = [];
  12768. for (var i = 0; i < lines.length; i++) {
  12769. if (lines[i].substring(0, needle.length) == needle)
  12770. needles.push(lines[i]);
  12771. }
  12772. if (needles.length || !sessionpart) {
  12773. return needles;
  12774. }
  12775. // search session part
  12776. lines = sessionpart.split('\r\n');
  12777. for (var j = 0; j < lines.length; j++) {
  12778. if (lines[j].substring(0, needle.length) == needle) {
  12779. needles.push(lines[j]);
  12780. }
  12781. }
  12782. return needles;
  12783. },
  12784. candidateToJingle: function (line) {
  12785. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  12786. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  12787. if (line.indexOf('candidate:') === 0) {
  12788. line = 'a=' + line;
  12789. } else if (line.substring(0, 12) != 'a=candidate:') {
  12790. console.log('parseCandidate called with a line that is not a candidate line');
  12791. console.log(line);
  12792. return null;
  12793. }
  12794. if (line.substring(line.length - 2) == '\r\n') // chomp it
  12795. line = line.substring(0, line.length - 2);
  12796. var candidate = {},
  12797. elems = line.split(' '),
  12798. i;
  12799. if (elems[6] != 'typ') {
  12800. console.log('did not find typ in the right place');
  12801. console.log(line);
  12802. return null;
  12803. }
  12804. candidate.foundation = elems[0].substring(12);
  12805. candidate.component = elems[1];
  12806. candidate.protocol = elems[2].toLowerCase();
  12807. candidate.priority = elems[3];
  12808. candidate.ip = elems[4];
  12809. candidate.port = elems[5];
  12810. // elems[6] => "typ"
  12811. candidate.type = elems[7];
  12812. candidate.generation = '0'; // default, may be overwritten below
  12813. for (i = 8; i < elems.length; i += 2) {
  12814. switch (elems[i]) {
  12815. case 'raddr':
  12816. candidate['rel-addr'] = elems[i + 1];
  12817. break;
  12818. case 'rport':
  12819. candidate['rel-port'] = elems[i + 1];
  12820. break;
  12821. case 'generation':
  12822. candidate.generation = elems[i + 1];
  12823. break;
  12824. case 'tcptype':
  12825. candidate.tcptype = elems[i + 1];
  12826. break;
  12827. default: // TODO
  12828. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12829. }
  12830. }
  12831. candidate.network = '1';
  12832. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12833. return candidate;
  12834. },
  12835. candidateFromJingle: function (cand) {
  12836. var line = 'a=candidate:';
  12837. line += cand.getAttribute('foundation');
  12838. line += ' ';
  12839. line += cand.getAttribute('component');
  12840. line += ' ';
  12841. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  12842. line += ' ';
  12843. line += cand.getAttribute('priority');
  12844. line += ' ';
  12845. line += cand.getAttribute('ip');
  12846. line += ' ';
  12847. line += cand.getAttribute('port');
  12848. line += ' ';
  12849. line += 'typ';
  12850. line += ' ' + cand.getAttribute('type');
  12851. line += ' ';
  12852. switch (cand.getAttribute('type')) {
  12853. case 'srflx':
  12854. case 'prflx':
  12855. case 'relay':
  12856. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  12857. line += 'raddr';
  12858. line += ' ';
  12859. line += cand.getAttribute('rel-addr');
  12860. line += ' ';
  12861. line += 'rport';
  12862. line += ' ';
  12863. line += cand.getAttribute('rel-port');
  12864. line += ' ';
  12865. }
  12866. break;
  12867. }
  12868. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  12869. line += 'tcptype';
  12870. line += ' ';
  12871. line += cand.getAttribute('tcptype');
  12872. line += ' ';
  12873. }
  12874. line += 'generation';
  12875. line += ' ';
  12876. line += cand.getAttribute('generation') || '0';
  12877. return line + '\r\n';
  12878. }
  12879. };
  12880. module.exports = SDPUtil;
  12881. },{}],52:[function(require,module,exports){
  12882. function TraceablePeerConnection(ice_config, constraints) {
  12883. var self = this;
  12884. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  12885. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  12886. this.updateLog = [];
  12887. this.stats = {};
  12888. this.statsinterval = null;
  12889. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  12890. var Interop = require('sdp-interop').Interop;
  12891. this.interop = new Interop();
  12892. // override as desired
  12893. this.trace = function (what, info) {
  12894. //console.warn('WTRACE', what, info);
  12895. self.updateLog.push({
  12896. time: new Date(),
  12897. type: what,
  12898. value: info || ""
  12899. });
  12900. };
  12901. this.onicecandidate = null;
  12902. this.peerconnection.onicecandidate = function (event) {
  12903. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  12904. if (self.onicecandidate !== null) {
  12905. self.onicecandidate(event);
  12906. }
  12907. };
  12908. this.onaddstream = null;
  12909. this.peerconnection.onaddstream = function (event) {
  12910. self.trace('onaddstream', event.stream.id);
  12911. if (self.onaddstream !== null) {
  12912. self.onaddstream(event);
  12913. }
  12914. };
  12915. this.onremovestream = null;
  12916. this.peerconnection.onremovestream = function (event) {
  12917. self.trace('onremovestream', event.stream.id);
  12918. if (self.onremovestream !== null) {
  12919. self.onremovestream(event);
  12920. }
  12921. };
  12922. this.onsignalingstatechange = null;
  12923. this.peerconnection.onsignalingstatechange = function (event) {
  12924. self.trace('onsignalingstatechange', self.signalingState);
  12925. if (self.onsignalingstatechange !== null) {
  12926. self.onsignalingstatechange(event);
  12927. }
  12928. };
  12929. this.oniceconnectionstatechange = null;
  12930. this.peerconnection.oniceconnectionstatechange = function (event) {
  12931. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12932. if (self.oniceconnectionstatechange !== null) {
  12933. self.oniceconnectionstatechange(event);
  12934. }
  12935. };
  12936. this.onnegotiationneeded = null;
  12937. this.peerconnection.onnegotiationneeded = function (event) {
  12938. self.trace('onnegotiationneeded');
  12939. if (self.onnegotiationneeded !== null) {
  12940. self.onnegotiationneeded(event);
  12941. }
  12942. };
  12943. self.ondatachannel = null;
  12944. this.peerconnection.ondatachannel = function (event) {
  12945. self.trace('ondatachannel', event);
  12946. if (self.ondatachannel !== null) {
  12947. self.ondatachannel(event);
  12948. }
  12949. };
  12950. if (!navigator.mozGetUserMedia && this.maxstats) {
  12951. this.statsinterval = window.setInterval(function() {
  12952. self.peerconnection.getStats(function(stats) {
  12953. var results = stats.result();
  12954. for (var i = 0; i < results.length; ++i) {
  12955. //console.log(results[i].type, results[i].id, results[i].names())
  12956. var now = new Date();
  12957. results[i].names().forEach(function (name) {
  12958. var id = results[i].id + '-' + name;
  12959. if (!self.stats[id]) {
  12960. self.stats[id] = {
  12961. startTime: now,
  12962. endTime: now,
  12963. values: [],
  12964. times: []
  12965. };
  12966. }
  12967. self.stats[id].values.push(results[i].stat(name));
  12968. self.stats[id].times.push(now.getTime());
  12969. if (self.stats[id].values.length > self.maxstats) {
  12970. self.stats[id].values.shift();
  12971. self.stats[id].times.shift();
  12972. }
  12973. self.stats[id].endTime = now;
  12974. });
  12975. }
  12976. });
  12977. }, 1000);
  12978. }
  12979. };
  12980. dumpSDP = function(description) {
  12981. if (typeof description === 'undefined' || description == null) {
  12982. return '';
  12983. }
  12984. return 'type: ' + description.type + '\r\n' + description.sdp;
  12985. };
  12986. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  12987. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  12988. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  12989. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  12990. this.trace('getLocalDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.localDescription));
  12991. // if we're running on FF, transform to Plan B first.
  12992. var desc = this.peerconnection.localDescription;
  12993. if (navigator.mozGetUserMedia) {
  12994. desc = this.interop.toPlanB(desc);
  12995. } else {
  12996. desc = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  12997. }
  12998. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  12999. return desc;
  13000. });
  13001. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  13002. this.trace('getRemoteDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.remoteDescription));
  13003. // if we're running on FF, transform to Plan B first.
  13004. var desc = this.peerconnection.remoteDescription;
  13005. if (navigator.mozGetUserMedia) {
  13006. desc = this.interop.toPlanB(desc);
  13007. } else {
  13008. desc = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  13009. }
  13010. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  13011. return desc;
  13012. });
  13013. }
  13014. TraceablePeerConnection.prototype.addStream = function (stream) {
  13015. this.trace('addStream', stream.id);
  13016. APP.simulcast.resetSender();
  13017. try
  13018. {
  13019. this.peerconnection.addStream(stream);
  13020. }
  13021. catch (e)
  13022. {
  13023. console.error(e);
  13024. return;
  13025. }
  13026. };
  13027. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  13028. this.trace('removeStream', stream.id);
  13029. APP.simulcast.resetSender();
  13030. if(stopStreams) {
  13031. stream.getAudioTracks().forEach(function (track) {
  13032. track.stop();
  13033. });
  13034. stream.getVideoTracks().forEach(function (track) {
  13035. track.stop();
  13036. });
  13037. }
  13038. try {
  13039. // FF doesn't support this yet.
  13040. this.peerconnection.removeStream(stream);
  13041. } catch (e) {
  13042. console.error(e);
  13043. }
  13044. };
  13045. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  13046. this.trace('createDataChannel', label, opts);
  13047. return this.peerconnection.createDataChannel(label, opts);
  13048. };
  13049. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  13050. this.trace('setLocalDescription::preTransform (Plan B)', dumpSDP(description));
  13051. // if we're running on FF, transform to Plan A first.
  13052. if (navigator.mozGetUserMedia) {
  13053. description = this.interop.toPlanA(description);
  13054. } else {
  13055. description = APP.simulcast.transformLocalDescription(description);
  13056. }
  13057. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  13058. var self = this;
  13059. this.peerconnection.setLocalDescription(description,
  13060. function () {
  13061. self.trace('setLocalDescriptionOnSuccess');
  13062. successCallback();
  13063. },
  13064. function (err) {
  13065. self.trace('setLocalDescriptionOnFailure', err);
  13066. failureCallback(err);
  13067. }
  13068. );
  13069. /*
  13070. if (this.statsinterval === null && this.maxstats > 0) {
  13071. // start gathering stats
  13072. }
  13073. */
  13074. };
  13075. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  13076. this.trace('setRemoteDescription::preTransform (Plan B)', dumpSDP(description));
  13077. // if we're running on FF, transform to Plan A first.
  13078. if (navigator.mozGetUserMedia) {
  13079. description = this.interop.toPlanA(description);
  13080. }
  13081. else {
  13082. description = APP.simulcast.transformRemoteDescription(description);
  13083. }
  13084. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  13085. var self = this;
  13086. this.peerconnection.setRemoteDescription(description,
  13087. function () {
  13088. self.trace('setRemoteDescriptionOnSuccess');
  13089. successCallback();
  13090. },
  13091. function (err) {
  13092. self.trace('setRemoteDescriptionOnFailure', err);
  13093. failureCallback(err);
  13094. }
  13095. );
  13096. /*
  13097. if (this.statsinterval === null && this.maxstats > 0) {
  13098. // start gathering stats
  13099. }
  13100. */
  13101. };
  13102. TraceablePeerConnection.prototype.close = function () {
  13103. this.trace('stop');
  13104. if (this.statsinterval !== null) {
  13105. window.clearInterval(this.statsinterval);
  13106. this.statsinterval = null;
  13107. }
  13108. this.peerconnection.close();
  13109. };
  13110. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  13111. var self = this;
  13112. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  13113. this.peerconnection.createOffer(
  13114. function (offer) {
  13115. self.trace('createOfferOnSuccess::preTransform (Plan A)', dumpSDP(offer));
  13116. // if we're running on FF, transform to Plan B first.
  13117. if (navigator.mozGetUserMedia) {
  13118. offer = self.interop.toPlanB(offer);
  13119. }
  13120. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  13121. successCallback(offer);
  13122. },
  13123. function(err) {
  13124. self.trace('createOfferOnFailure', err);
  13125. failureCallback(err);
  13126. },
  13127. constraints
  13128. );
  13129. };
  13130. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  13131. var self = this;
  13132. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  13133. this.peerconnection.createAnswer(
  13134. function (answer) {
  13135. self.trace('createAnswerOnSuccess::preTransfom (Plan A)', dumpSDP(answer));
  13136. // if we're running on FF, transform to Plan A first.
  13137. if (navigator.mozGetUserMedia) {
  13138. answer = self.interop.toPlanB(answer);
  13139. } else {
  13140. answer = APP.simulcast.transformAnswer(answer);
  13141. }
  13142. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  13143. successCallback(answer);
  13144. },
  13145. function(err) {
  13146. self.trace('createAnswerOnFailure', err);
  13147. failureCallback(err);
  13148. },
  13149. constraints
  13150. );
  13151. };
  13152. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  13153. var self = this;
  13154. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  13155. this.peerconnection.addIceCandidate(candidate);
  13156. /* maybe later
  13157. this.peerconnection.addIceCandidate(candidate,
  13158. function () {
  13159. self.trace('addIceCandidateOnSuccess');
  13160. successCallback();
  13161. },
  13162. function (err) {
  13163. self.trace('addIceCandidateOnFailure', err);
  13164. failureCallback(err);
  13165. }
  13166. );
  13167. */
  13168. };
  13169. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  13170. if (navigator.mozGetUserMedia) {
  13171. // ignore for now...
  13172. if(!errback)
  13173. errback = function () {
  13174. }
  13175. this.peerconnection.getStats(null,callback,errback);
  13176. } else {
  13177. this.peerconnection.getStats(callback);
  13178. }
  13179. };
  13180. module.exports = TraceablePeerConnection;
  13181. },{"sdp-interop":80}],53:[function(require,module,exports){
  13182. /* global $, $iq, APP, config, connection, UI, messageHandler,
  13183. roomName, sessionTerminated, Strophe, Util */
  13184. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13185. var Settings = require("../settings/Settings");
  13186. var AuthenticationEvents
  13187. = require("../../service/authentication/AuthenticationEvents");
  13188. /**
  13189. * Contains logic responsible for enabling/disabling functionality available
  13190. * only to moderator users.
  13191. */
  13192. var connection = null;
  13193. var focusUserJid;
  13194. function createExpBackoffTimer(step) {
  13195. var count = 1;
  13196. return function (reset) {
  13197. // Reset call
  13198. if (reset) {
  13199. count = 1;
  13200. return;
  13201. }
  13202. // Calculate next timeout
  13203. var timeout = Math.pow(2, count - 1);
  13204. count += 1;
  13205. return timeout * step;
  13206. };
  13207. }
  13208. var getNextTimeout = createExpBackoffTimer(1000);
  13209. var getNextErrorTimeout = createExpBackoffTimer(1000);
  13210. // External authentication stuff
  13211. var externalAuthEnabled = false;
  13212. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  13213. // it will be enabled automatically if focus detects the component through
  13214. // service discovery.
  13215. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  13216. var eventEmitter = null;
  13217. var Moderator = {
  13218. isModerator: function () {
  13219. return connection && connection.emuc.isModerator();
  13220. },
  13221. isPeerModerator: function (peerJid) {
  13222. return connection &&
  13223. connection.emuc.getMemberRole(peerJid) === 'moderator';
  13224. },
  13225. isExternalAuthEnabled: function () {
  13226. return externalAuthEnabled;
  13227. },
  13228. isSipGatewayEnabled: function () {
  13229. return sipGatewayEnabled;
  13230. },
  13231. setConnection: function (con) {
  13232. connection = con;
  13233. },
  13234. init: function (xmpp, emitter) {
  13235. this.xmppService = xmpp;
  13236. eventEmitter = emitter;
  13237. // Message listener that talks to POPUP window
  13238. function listener(event) {
  13239. if (event.data && event.data.sessionId) {
  13240. if (event.origin !== window.location.origin) {
  13241. console.warn(
  13242. "Ignoring sessionId from different origin: " + event.origin);
  13243. return;
  13244. }
  13245. localStorage.setItem('sessionId', event.data.sessionId);
  13246. // After popup is closed we will authenticate
  13247. }
  13248. }
  13249. // Register
  13250. if (window.addEventListener) {
  13251. window.addEventListener("message", listener, false);
  13252. } else {
  13253. window.attachEvent("onmessage", listener);
  13254. }
  13255. },
  13256. onMucLeft: function (jid) {
  13257. console.info("Someone left is it focus ? " + jid);
  13258. var resource = Strophe.getResourceFromJid(jid);
  13259. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  13260. console.info(
  13261. "Focus has left the room - leaving conference");
  13262. //hangUp();
  13263. // We'd rather reload to have everything re-initialized
  13264. // FIXME: show some message before reload
  13265. location.reload();
  13266. }
  13267. },
  13268. setFocusUserJid: function (focusJid) {
  13269. if (!focusUserJid) {
  13270. focusUserJid = focusJid;
  13271. console.info("Focus jid set to: " + focusUserJid);
  13272. }
  13273. },
  13274. getFocusUserJid: function () {
  13275. return focusUserJid;
  13276. },
  13277. getFocusComponent: function () {
  13278. // Get focus component address
  13279. var focusComponent = config.hosts.focus;
  13280. // If not specified use default: 'focus.domain'
  13281. if (!focusComponent) {
  13282. focusComponent = 'focus.' + config.hosts.domain;
  13283. }
  13284. return focusComponent;
  13285. },
  13286. createConferenceIq: function (roomName) {
  13287. // Generate create conference IQ
  13288. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13289. // Session Id used for authentication
  13290. var sessionId = localStorage.getItem('sessionId');
  13291. var machineUID = Settings.getSettings().uid;
  13292. console.info(
  13293. "Session ID: " + sessionId + " machine UID: " + machineUID);
  13294. elem.c('conference', {
  13295. xmlns: 'http://jitsi.org/protocol/focus',
  13296. room: roomName,
  13297. 'machine-uid': machineUID
  13298. });
  13299. if (sessionId) {
  13300. elem.attrs({ 'session-id': sessionId});
  13301. }
  13302. if (config.hosts.bridge !== undefined) {
  13303. elem.c(
  13304. 'property',
  13305. { name: 'bridge', value: config.hosts.bridge})
  13306. .up();
  13307. }
  13308. // Tell the focus we have Jigasi configured
  13309. if (config.hosts.call_control !== undefined) {
  13310. elem.c(
  13311. 'property',
  13312. { name: 'call_control', value: config.hosts.call_control})
  13313. .up();
  13314. }
  13315. if (config.channelLastN !== undefined) {
  13316. elem.c(
  13317. 'property',
  13318. { name: 'channelLastN', value: config.channelLastN})
  13319. .up();
  13320. }
  13321. if (config.adaptiveLastN !== undefined) {
  13322. elem.c(
  13323. 'property',
  13324. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  13325. .up();
  13326. }
  13327. if (config.adaptiveSimulcast !== undefined) {
  13328. elem.c(
  13329. 'property',
  13330. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  13331. .up();
  13332. }
  13333. if (config.openSctp !== undefined) {
  13334. elem.c(
  13335. 'property',
  13336. { name: 'openSctp', value: config.openSctp})
  13337. .up();
  13338. }
  13339. var roomName = APP.UI.generateRoomName();
  13340. if (typeof roomName !== 'string') roomName = '';
  13341. if (config.enableFirefoxSupport !== undefined && roomName.indexOf('rembson@') === -1) {
  13342. elem.c(
  13343. 'property',
  13344. { name: 'enableFirefoxHacks',
  13345. value: config.enableFirefoxSupport})
  13346. .up();
  13347. }
  13348. elem.up();
  13349. return elem;
  13350. },
  13351. parseSessionId: function (resultIq) {
  13352. var sessionId = $(resultIq).find('conference').attr('session-id');
  13353. if (sessionId) {
  13354. console.info('Received sessionId: ' + sessionId);
  13355. localStorage.setItem('sessionId', sessionId);
  13356. }
  13357. },
  13358. parseConfigOptions: function (resultIq) {
  13359. Moderator.setFocusUserJid(
  13360. $(resultIq).find('conference').attr('focusjid'));
  13361. var authenticationEnabled
  13362. = $(resultIq).find(
  13363. '>conference>property' +
  13364. '[name=\'authentication\'][value=\'true\']').length > 0;
  13365. console.info("Authentication enabled: " + authenticationEnabled);
  13366. externalAuthEnabled
  13367. = $(resultIq).find(
  13368. '>conference>property' +
  13369. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  13370. console.info('External authentication enabled: ' + externalAuthEnabled);
  13371. if (!externalAuthEnabled) {
  13372. // We expect to receive sessionId in 'internal' authentication mode
  13373. Moderator.parseSessionId(resultIq);
  13374. }
  13375. var authIdentity = $(resultIq).find('>conference').attr('identity');
  13376. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  13377. authenticationEnabled, authIdentity);
  13378. // Check if focus has auto-detected Jigasi component(this will be also
  13379. // included if we have passed our host from the config)
  13380. if ($(resultIq).find(
  13381. '>conference>property' +
  13382. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  13383. sipGatewayEnabled = true;
  13384. }
  13385. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  13386. },
  13387. // FIXME: we need to show the fact that we're waiting for the focus
  13388. // to the user(or that focus is not available)
  13389. allocateConferenceFocus: function (roomName, callback) {
  13390. // Try to use focus user JID from the config
  13391. Moderator.setFocusUserJid(config.focusUserJid);
  13392. // Send create conference IQ
  13393. var iq = Moderator.createConferenceIq(roomName);
  13394. var self = this;
  13395. connection.sendIQ(
  13396. iq,
  13397. function (result) {
  13398. // Setup config options
  13399. Moderator.parseConfigOptions(result);
  13400. if ('true' === $(result).find('conference').attr('ready')) {
  13401. // Reset both timers
  13402. getNextTimeout(true);
  13403. getNextErrorTimeout(true);
  13404. // Exec callback
  13405. callback();
  13406. } else {
  13407. var waitMs = getNextTimeout();
  13408. console.info("Waiting for the focus... " + waitMs);
  13409. // Reset error timeout
  13410. getNextErrorTimeout(true);
  13411. window.setTimeout(
  13412. function () {
  13413. Moderator.allocateConferenceFocus(
  13414. roomName, callback);
  13415. }, waitMs);
  13416. }
  13417. },
  13418. function (error) {
  13419. // Invalid session ? remove and try again
  13420. // without session ID to get a new one
  13421. var invalidSession
  13422. = $(error).find('>error>session-invalid').length;
  13423. if (invalidSession) {
  13424. console.info("Session expired! - removing");
  13425. localStorage.removeItem("sessionId");
  13426. }
  13427. if ($(error).find('>error>graceful-shutdown').length) {
  13428. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  13429. return;
  13430. }
  13431. // Check for error returned by the reservation system
  13432. var reservationErr = $(error).find('>error>reservation-error');
  13433. if (reservationErr.length) {
  13434. // Trigger error event
  13435. var errorCode = reservationErr.attr('error-code');
  13436. var errorMsg;
  13437. if ($(error).find('>error>text')) {
  13438. errorMsg = $(error).find('>error>text').text();
  13439. }
  13440. eventEmitter.emit(
  13441. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  13442. return;
  13443. }
  13444. // Not authorized to create new room
  13445. if ($(error).find('>error>not-authorized').length) {
  13446. console.warn("Unauthorized to start the conference", error);
  13447. var toDomain
  13448. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13449. if (toDomain !== config.hosts.anonymousdomain) {
  13450. // FIXME: "is external" should come either from
  13451. // the focus or config.js
  13452. externalAuthEnabled = true;
  13453. }
  13454. eventEmitter.emit(
  13455. XMPPEvents.AUTHENTICATION_REQUIRED,
  13456. function () {
  13457. Moderator.allocateConferenceFocus(
  13458. roomName, callback);
  13459. });
  13460. return;
  13461. }
  13462. var waitMs = getNextErrorTimeout();
  13463. console.error("Focus error, retry after " + waitMs, error);
  13464. // Show message
  13465. var focusComponent = Moderator.getFocusComponent();
  13466. var retrySec = waitMs / 1000;
  13467. // FIXME: message is duplicated ?
  13468. // Do not show in case of session invalid
  13469. // which means just a retry
  13470. if (!invalidSession) {
  13471. APP.UI.messageHandler.notify(
  13472. null, "notify.focus",
  13473. 'disconnected', "notify.focusFail",
  13474. {component: focusComponent, ms: retrySec});
  13475. }
  13476. // Reset response timeout
  13477. getNextTimeout(true);
  13478. window.setTimeout(
  13479. function () {
  13480. Moderator.allocateConferenceFocus(roomName, callback);
  13481. }, waitMs);
  13482. }
  13483. );
  13484. },
  13485. getLoginUrl: function (roomName, urlCallback) {
  13486. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13487. iq.c('login-url', {
  13488. xmlns: 'http://jitsi.org/protocol/focus',
  13489. room: roomName,
  13490. 'machine-uid': Settings.getSettings().uid
  13491. });
  13492. connection.sendIQ(
  13493. iq,
  13494. function (result) {
  13495. var url = $(result).find('login-url').attr('url');
  13496. url = url = decodeURIComponent(url);
  13497. if (url) {
  13498. console.info("Got auth url: " + url);
  13499. urlCallback(url);
  13500. } else {
  13501. console.error(
  13502. "Failed to get auth url from the focus", result);
  13503. }
  13504. },
  13505. function (error) {
  13506. console.error("Get auth url error", error);
  13507. }
  13508. );
  13509. },
  13510. getPopupLoginUrl: function (roomName, urlCallback) {
  13511. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13512. iq.c('login-url', {
  13513. xmlns: 'http://jitsi.org/protocol/focus',
  13514. room: roomName,
  13515. 'machine-uid': Settings.getSettings().uid,
  13516. popup: true
  13517. });
  13518. connection.sendIQ(
  13519. iq,
  13520. function (result) {
  13521. var url = $(result).find('login-url').attr('url');
  13522. url = url = decodeURIComponent(url);
  13523. if (url) {
  13524. console.info("Got POPUP auth url: " + url);
  13525. urlCallback(url);
  13526. } else {
  13527. console.error(
  13528. "Failed to get POPUP auth url from the focus", result);
  13529. }
  13530. },
  13531. function (error) {
  13532. console.error('Get POPUP auth url error', error);
  13533. }
  13534. );
  13535. },
  13536. logout: function (callback) {
  13537. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13538. var sessionId = localStorage.getItem('sessionId');
  13539. if (!sessionId) {
  13540. callback();
  13541. return;
  13542. }
  13543. iq.c('logout', {
  13544. xmlns: 'http://jitsi.org/protocol/focus',
  13545. 'session-id': sessionId
  13546. });
  13547. connection.sendIQ(
  13548. iq,
  13549. function (result) {
  13550. var logoutUrl = $(result).find('logout').attr('logout-url');
  13551. if (logoutUrl) {
  13552. logoutUrl = decodeURIComponent(logoutUrl);
  13553. }
  13554. console.info("Log out OK, url: " + logoutUrl, result);
  13555. localStorage.removeItem('sessionId');
  13556. callback(logoutUrl);
  13557. },
  13558. function (error) {
  13559. console.error("Logout error", error);
  13560. }
  13561. );
  13562. }
  13563. };
  13564. module.exports = Moderator;
  13565. },{"../../service/authentication/AuthenticationEvents":93,"../../service/xmpp/XMPPEvents":97,"../settings/Settings":38}],54:[function(require,module,exports){
  13566. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  13567. Toolbar, Util */
  13568. var Moderator = require("./moderator");
  13569. var recordingToken = null;
  13570. var recordingEnabled;
  13571. /**
  13572. * Whether to use a jirecon component for recording, or use the videobridge
  13573. * through COLIBRI.
  13574. */
  13575. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  13576. /**
  13577. * The ID of the jirecon recording session. Jirecon generates it when we
  13578. * initially start recording, and it needs to be used in subsequent requests
  13579. * to jirecon.
  13580. */
  13581. var jireconRid = null;
  13582. function setRecordingToken(token) {
  13583. recordingToken = token;
  13584. }
  13585. function setRecording(state, token, callback, connection) {
  13586. if (useJirecon){
  13587. setRecordingJirecon(state, token, callback, connection);
  13588. } else {
  13589. setRecordingColibri(state, token, callback, connection);
  13590. }
  13591. }
  13592. function setRecordingJirecon(state, token, callback, connection) {
  13593. if (state == recordingEnabled){
  13594. return;
  13595. }
  13596. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  13597. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  13598. action: state ? 'start' : 'stop',
  13599. mucjid: connection.emuc.roomjid});
  13600. if (!state){
  13601. iq.attrs({rid: jireconRid});
  13602. }
  13603. console.log('Start recording');
  13604. connection.sendIQ(
  13605. iq,
  13606. function (result) {
  13607. // TODO wait for an IQ with the real status, since this is
  13608. // provisional?
  13609. jireconRid = $(result).find('recording').attr('rid');
  13610. console.log('Recording ' + (state ? 'started' : 'stopped') +
  13611. '(jirecon)' + result);
  13612. recordingEnabled = state;
  13613. if (!state){
  13614. jireconRid = null;
  13615. }
  13616. callback(state);
  13617. },
  13618. function (error) {
  13619. console.log('Failed to start recording, error: ', error);
  13620. callback(recordingEnabled);
  13621. });
  13622. }
  13623. // Sends a COLIBRI message which enables or disables (according to 'state')
  13624. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  13625. // with the new recording state, according to the IQ.
  13626. function setRecordingColibri(state, token, callback, connection) {
  13627. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  13628. elem.c('conference', {
  13629. xmlns: 'http://jitsi.org/protocol/colibri'
  13630. });
  13631. elem.c('recording', {state: state, token: token});
  13632. connection.sendIQ(elem,
  13633. function (result) {
  13634. console.log('Set recording "', state, '". Result:', result);
  13635. var recordingElem = $(result).find('>conference>recording');
  13636. var newState = ('true' === recordingElem.attr('state'));
  13637. recordingEnabled = newState;
  13638. callback(newState);
  13639. },
  13640. function (error) {
  13641. console.warn(error);
  13642. callback(recordingEnabled);
  13643. }
  13644. );
  13645. }
  13646. var Recording = {
  13647. toggleRecording: function (tokenEmptyCallback,
  13648. startingCallback, startedCallback, connection) {
  13649. if (!Moderator.isModerator()) {
  13650. console.log(
  13651. 'non-focus, or conference not yet organized:' +
  13652. ' not enabling recording');
  13653. return;
  13654. }
  13655. var self = this;
  13656. // Jirecon does not (currently) support a token.
  13657. if (!recordingToken && !useJirecon) {
  13658. tokenEmptyCallback(function (value) {
  13659. setRecordingToken(value);
  13660. self.toggleRecording(tokenEmptyCallback,
  13661. startingCallback, startedCallback, connection);
  13662. });
  13663. return;
  13664. }
  13665. var oldState = recordingEnabled;
  13666. startingCallback(!oldState);
  13667. setRecording(!oldState,
  13668. recordingToken,
  13669. function (state) {
  13670. console.log("New recording state: ", state);
  13671. if (state === oldState) {
  13672. // FIXME: new focus:
  13673. // this will not work when moderator changes
  13674. // during active session. Then it will assume that
  13675. // recording status has changed to true, but it might have
  13676. // been already true(and we only received actual status from
  13677. // the focus).
  13678. //
  13679. // SO we start with status null, so that it is initialized
  13680. // here and will fail only after second click, so if invalid
  13681. // token was used we have to press the button twice before
  13682. // current status will be fetched and token will be reset.
  13683. //
  13684. // Reliable way would be to return authentication error.
  13685. // Or status update when moderator connects.
  13686. // Or we have to stop recording session when current
  13687. // moderator leaves the room.
  13688. // Failed to change, reset the token because it might
  13689. // have been wrong
  13690. setRecordingToken(null);
  13691. }
  13692. startedCallback(state);
  13693. },
  13694. connection
  13695. );
  13696. }
  13697. }
  13698. module.exports = Recording;
  13699. },{"./moderator":53}],55:[function(require,module,exports){
  13700. /* jshint -W117 */
  13701. /* a simple MUC connection plugin
  13702. * can only handle a single MUC room
  13703. */
  13704. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13705. var Moderator = require("./moderator");
  13706. var JingleSession = require("./JingleSession");
  13707. var bridgeIsDown = false;
  13708. module.exports = function(XMPP, eventEmitter) {
  13709. Strophe.addConnectionPlugin('emuc', {
  13710. connection: null,
  13711. roomjid: null,
  13712. myroomjid: null,
  13713. members: {},
  13714. list_members: [], // so we can elect a new focus
  13715. presMap: {},
  13716. preziMap: {},
  13717. joined: false,
  13718. isOwner: false,
  13719. role: null,
  13720. focusMucJid: null,
  13721. ssrc2jid: {},
  13722. init: function (conn) {
  13723. this.connection = conn;
  13724. },
  13725. initPresenceMap: function (myroomjid) {
  13726. this.presMap['to'] = myroomjid;
  13727. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  13728. },
  13729. doJoin: function (jid, password) {
  13730. this.myroomjid = jid;
  13731. console.info("Joined MUC as " + this.myroomjid);
  13732. this.initPresenceMap(this.myroomjid);
  13733. if (!this.roomjid) {
  13734. this.roomjid = Strophe.getBareJidFromJid(jid);
  13735. // add handlers (just once)
  13736. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  13737. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  13738. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  13739. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  13740. }
  13741. if (password !== undefined) {
  13742. this.presMap['password'] = password;
  13743. }
  13744. this.sendPresence();
  13745. },
  13746. doLeave: function () {
  13747. console.log("do leave", this.myroomjid);
  13748. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  13749. this.presMap.length = 0;
  13750. this.connection.send(pres);
  13751. },
  13752. createNonAnonymousRoom: function () {
  13753. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  13754. var getForm = $iq({type: 'get', to: this.roomjid})
  13755. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  13756. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13757. var self = this;
  13758. this.connection.sendIQ(getForm, function (form) {
  13759. if (!$(form).find(
  13760. '>query>x[xmlns="jabber:x:data"]' +
  13761. '>field[var="muc#roomconfig_whois"]').length) {
  13762. console.error('non-anonymous rooms not supported');
  13763. return;
  13764. }
  13765. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  13766. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13767. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13768. formSubmit.c('field', {'var': 'FORM_TYPE'})
  13769. .c('value')
  13770. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13771. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  13772. .c('value').t('anyone').up().up();
  13773. self.connection.sendIQ(formSubmit);
  13774. }, function (error) {
  13775. console.error("Error getting room configuration form");
  13776. });
  13777. },
  13778. onPresence: function (pres) {
  13779. var from = pres.getAttribute('from');
  13780. // What is this for? A workaround for something?
  13781. if (pres.getAttribute('type')) {
  13782. return true;
  13783. }
  13784. // Parse etherpad tag.
  13785. var etherpad = $(pres).find('>etherpad');
  13786. if (etherpad.length) {
  13787. if (config.etherpad_base && !Moderator.isModerator()) {
  13788. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  13789. }
  13790. }
  13791. // Parse prezi tag.
  13792. var presentation = $(pres).find('>prezi');
  13793. if (presentation.length) {
  13794. var url = presentation.attr('url');
  13795. var current = presentation.find('>current').text();
  13796. console.log('presentation info received from', from, url);
  13797. if (this.preziMap[from] == null) {
  13798. this.preziMap[from] = url;
  13799. $(document).trigger('presentationadded.muc', [from, url, current]);
  13800. }
  13801. else {
  13802. $(document).trigger('gotoslide.muc', [from, url, current]);
  13803. }
  13804. }
  13805. else if (this.preziMap[from] != null) {
  13806. var url = this.preziMap[from];
  13807. delete this.preziMap[from];
  13808. $(document).trigger('presentationremoved.muc', [from, url]);
  13809. }
  13810. // Parse audio info tag.
  13811. var audioMuted = $(pres).find('>audiomuted');
  13812. if (audioMuted.length) {
  13813. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  13814. }
  13815. // Parse video info tag.
  13816. var videoMuted = $(pres).find('>videomuted');
  13817. if (videoMuted.length) {
  13818. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  13819. }
  13820. var devices = $(pres).find('>devices');
  13821. if(devices.length)
  13822. {
  13823. var audio = devices.find('>audio');
  13824. var video = devices.find('>video');
  13825. var devicesValues = {audio: false, video: false};
  13826. if(audio.length && audio.text() === "true")
  13827. {
  13828. devicesValues.audio = true;
  13829. }
  13830. if(video.length && video.text() === "true")
  13831. {
  13832. devicesValues.video = true;
  13833. }
  13834. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  13835. Strophe.getResourceFromJid(from), devicesValues);
  13836. }
  13837. var stats = $(pres).find('>stats');
  13838. if (stats.length) {
  13839. var statsObj = {};
  13840. Strophe.forEachChild(stats[0], "stat", function (el) {
  13841. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  13842. });
  13843. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  13844. }
  13845. // Parse status.
  13846. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  13847. this.isOwner = true;
  13848. this.createNonAnonymousRoom();
  13849. }
  13850. // Parse roles.
  13851. var member = {};
  13852. member.show = $(pres).find('>show').text();
  13853. member.status = $(pres).find('>status').text();
  13854. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  13855. member.affiliation = tmp.attr('affiliation');
  13856. member.role = tmp.attr('role');
  13857. // Focus recognition
  13858. member.jid = tmp.attr('jid');
  13859. member.isFocus = false;
  13860. if (member.jid
  13861. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  13862. member.isFocus = true;
  13863. }
  13864. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  13865. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  13866. if (from == this.myroomjid) {
  13867. if (member.affiliation == 'owner') this.isOwner = true;
  13868. if (this.role !== member.role) {
  13869. this.role = member.role;
  13870. eventEmitter.emit(XMPPEvents.LOCALROLE_CHANGED,
  13871. from, member, pres, Moderator.isModerator());
  13872. }
  13873. if (!this.joined) {
  13874. this.joined = true;
  13875. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  13876. this.list_members.push(from);
  13877. }
  13878. } else if (this.members[from] === undefined) {
  13879. // new participant
  13880. this.members[from] = member;
  13881. this.list_members.push(from);
  13882. console.log('entered', from, member);
  13883. if (member.isFocus) {
  13884. this.focusMucJid = from;
  13885. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  13886. }
  13887. else {
  13888. var id = $(pres).find('>userID').text();
  13889. var email = $(pres).find('>email');
  13890. if (email.length > 0) {
  13891. id = email.text();
  13892. }
  13893. eventEmitter.emit(XMPPEvents.MUC_ENTER, from, id, member.displayName);
  13894. }
  13895. } else {
  13896. // Presence update for existing participant
  13897. // Watch role change:
  13898. if (this.members[from].role != member.role) {
  13899. this.members[from].role = member.role;
  13900. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  13901. member.role, member.displayName);
  13902. }
  13903. }
  13904. // Always trigger presence to update bindings
  13905. this.parsePresence(from, member, pres);
  13906. // Trigger status message update
  13907. if (member.status) {
  13908. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  13909. }
  13910. return true;
  13911. },
  13912. onPresenceUnavailable: function (pres) {
  13913. var from = pres.getAttribute('from');
  13914. // room destroyed ?
  13915. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13916. '>destroy').length) {
  13917. var reason;
  13918. var reasonSelect = $(pres).find(
  13919. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13920. '>destroy>reason');
  13921. if (reasonSelect.length) {
  13922. reason = reasonSelect.text();
  13923. }
  13924. XMPP.disposeConference(false);
  13925. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  13926. return true;
  13927. }
  13928. // Status code 110 indicates that this notification is "self-presence".
  13929. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  13930. delete this.members[from];
  13931. this.list_members.splice(this.list_members.indexOf(from), 1);
  13932. this.onParticipantLeft(from);
  13933. }
  13934. // If the status code is 110 this means we're leaving and we would like
  13935. // to remove everyone else from our view, so we trigger the event.
  13936. else if (this.list_members.length > 1) {
  13937. for (var i = 0; i < this.list_members.length; i++) {
  13938. var member = this.list_members[i];
  13939. delete this.members[i];
  13940. this.list_members.splice(i, 1);
  13941. this.onParticipantLeft(member);
  13942. }
  13943. }
  13944. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  13945. $(document).trigger('kicked.muc', [from]);
  13946. if (this.myroomjid === from) {
  13947. XMPP.disposeConference(false);
  13948. eventEmitter.emit(XMPPEvents.KICKED);
  13949. }
  13950. }
  13951. return true;
  13952. },
  13953. onPresenceError: function (pres) {
  13954. var from = pres.getAttribute('from');
  13955. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13956. console.log('on password required', from);
  13957. var self = this;
  13958. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  13959. self.doJoin(from, value);
  13960. });
  13961. } else if ($(pres).find(
  13962. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13963. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  13964. if (toDomain === config.hosts.anonymousdomain) {
  13965. // enter the room by replying with 'not-authorized'. This would
  13966. // result in reconnection from authorized domain.
  13967. // We're either missing Jicofo/Prosody config for anonymous
  13968. // domains or something is wrong.
  13969. // XMPP.promptLogin();
  13970. APP.UI.messageHandler.openReportDialog(null,
  13971. "dialog.joinError", pres);
  13972. } else {
  13973. console.warn('onPresError ', pres);
  13974. APP.UI.messageHandler.openReportDialog(null,
  13975. "dialog.connectError",
  13976. pres);
  13977. }
  13978. } else {
  13979. console.warn('onPresError ', pres);
  13980. APP.UI.messageHandler.openReportDialog(null,
  13981. "dialog.connectError",
  13982. pres);
  13983. }
  13984. return true;
  13985. },
  13986. sendMessage: function (body, nickname) {
  13987. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13988. msg.c('body', body).up();
  13989. if (nickname) {
  13990. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  13991. }
  13992. this.connection.send(msg);
  13993. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  13994. },
  13995. setSubject: function (subject) {
  13996. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13997. msg.c('subject', subject);
  13998. this.connection.send(msg);
  13999. console.log("topic changed to " + subject);
  14000. },
  14001. onMessage: function (msg) {
  14002. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  14003. var from = msg.getAttribute('from');
  14004. var nick =
  14005. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  14006. .text() ||
  14007. Strophe.getResourceFromJid(from);
  14008. var txt = $(msg).find('>body').text();
  14009. var type = msg.getAttribute("type");
  14010. if (type == "error") {
  14011. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  14012. $(msg).find('>text').text(), txt);
  14013. return true;
  14014. }
  14015. var subject = $(msg).find('>subject');
  14016. if (subject.length) {
  14017. var subjectText = subject.text();
  14018. if (subjectText || subjectText == "") {
  14019. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  14020. console.log("Subject is changed to " + subjectText);
  14021. }
  14022. }
  14023. if (txt) {
  14024. console.log('chat', nick, txt);
  14025. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  14026. from, nick, txt, this.myroomjid);
  14027. }
  14028. return true;
  14029. },
  14030. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14031. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  14032. var ob = this;
  14033. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  14034. function (res) {
  14035. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  14036. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  14037. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14038. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  14039. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  14040. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  14041. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  14042. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  14043. ob.connection.sendIQ(formsubmit,
  14044. onSuccess,
  14045. onError);
  14046. } else {
  14047. onNotSupported();
  14048. }
  14049. }, onError);
  14050. },
  14051. kick: function (jid) {
  14052. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  14053. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  14054. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  14055. .c('reason').t('You have been kicked.').up().up().up();
  14056. this.connection.sendIQ(
  14057. kickIQ,
  14058. function (result) {
  14059. console.log('Kick participant with jid: ', jid, result);
  14060. },
  14061. function (error) {
  14062. console.log('Kick participant error: ', error);
  14063. });
  14064. },
  14065. sendPresence: function () {
  14066. var pres = $pres({to: this.presMap['to'] });
  14067. pres.c('x', {xmlns: this.presMap['xns']});
  14068. if (this.presMap['password']) {
  14069. pres.c('password').t(this.presMap['password']).up();
  14070. }
  14071. pres.up();
  14072. // Send XEP-0115 'c' stanza that contains our capabilities info
  14073. if (this.connection.caps) {
  14074. this.connection.caps.node = config.clientNode;
  14075. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  14076. }
  14077. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  14078. .t(navigator.userAgent).up();
  14079. if (this.presMap['bridgeIsDown']) {
  14080. pres.c('bridgeIsDown').up();
  14081. }
  14082. if (this.presMap['email']) {
  14083. pres.c('email').t(this.presMap['email']).up();
  14084. }
  14085. if (this.presMap['userId']) {
  14086. pres.c('userId').t(this.presMap['userId']).up();
  14087. }
  14088. if (this.presMap['displayName']) {
  14089. // XEP-0172
  14090. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  14091. .t(this.presMap['displayName']).up();
  14092. }
  14093. if(this.presMap["devices"])
  14094. {
  14095. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  14096. .c('video').t(this.presMap['devices'].video).up().up();
  14097. }
  14098. if (this.presMap['audions']) {
  14099. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  14100. .t(this.presMap['audiomuted']).up();
  14101. }
  14102. if (this.presMap['videons']) {
  14103. pres.c('videomuted', {xmlns: this.presMap['videons']})
  14104. .t(this.presMap['videomuted']).up();
  14105. }
  14106. if (this.presMap['statsns']) {
  14107. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  14108. for (var stat in this.presMap["stats"])
  14109. if (this.presMap["stats"][stat] != null)
  14110. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  14111. pres.up();
  14112. }
  14113. if (this.presMap['prezins']) {
  14114. pres.c('prezi',
  14115. {xmlns: this.presMap['prezins'],
  14116. 'url': this.presMap['preziurl']})
  14117. .c('current').t(this.presMap['prezicurrent']).up().up();
  14118. }
  14119. if (this.presMap['etherpadns']) {
  14120. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  14121. .t(this.presMap['etherpadname']).up();
  14122. }
  14123. if (this.presMap['medians']) {
  14124. pres.c('media', {xmlns: this.presMap['medians']});
  14125. var sourceNumber = 0;
  14126. Object.keys(this.presMap).forEach(function (key) {
  14127. if (key.indexOf('source') >= 0) {
  14128. sourceNumber++;
  14129. }
  14130. });
  14131. if (sourceNumber > 0)
  14132. for (var i = 1; i <= sourceNumber / 3; i++) {
  14133. pres.c('source',
  14134. {type: this.presMap['source' + i + '_type'],
  14135. ssrc: this.presMap['source' + i + '_ssrc'],
  14136. direction: this.presMap['source' + i + '_direction']
  14137. || 'sendrecv' }
  14138. ).up();
  14139. }
  14140. }
  14141. pres.up();
  14142. this.connection.send(pres);
  14143. },
  14144. addDisplayNameToPresence: function (displayName) {
  14145. this.presMap['displayName'] = displayName;
  14146. },
  14147. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  14148. if (!this.presMap['medians'])
  14149. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  14150. this.presMap['source' + sourceNumber + '_type'] = mtype;
  14151. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  14152. this.presMap['source' + sourceNumber + '_direction'] = direction;
  14153. },
  14154. addDevicesToPresence: function (devices) {
  14155. this.presMap['devices'] = devices;
  14156. },
  14157. clearPresenceMedia: function () {
  14158. var self = this;
  14159. Object.keys(this.presMap).forEach(function (key) {
  14160. if (key.indexOf('source') != -1) {
  14161. delete self.presMap[key];
  14162. }
  14163. });
  14164. },
  14165. addPreziToPresence: function (url, currentSlide) {
  14166. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  14167. this.presMap['preziurl'] = url;
  14168. this.presMap['prezicurrent'] = currentSlide;
  14169. },
  14170. removePreziFromPresence: function () {
  14171. delete this.presMap['prezins'];
  14172. delete this.presMap['preziurl'];
  14173. delete this.presMap['prezicurrent'];
  14174. },
  14175. addCurrentSlideToPresence: function (currentSlide) {
  14176. this.presMap['prezicurrent'] = currentSlide;
  14177. },
  14178. getPrezi: function (roomjid) {
  14179. return this.preziMap[roomjid];
  14180. },
  14181. addEtherpadToPresence: function (etherpadName) {
  14182. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  14183. this.presMap['etherpadname'] = etherpadName;
  14184. },
  14185. addAudioInfoToPresence: function (isMuted) {
  14186. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  14187. this.presMap['audiomuted'] = isMuted.toString();
  14188. },
  14189. addVideoInfoToPresence: function (isMuted) {
  14190. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  14191. this.presMap['videomuted'] = isMuted.toString();
  14192. },
  14193. addConnectionInfoToPresence: function (stats) {
  14194. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  14195. this.presMap['stats'] = stats;
  14196. },
  14197. findJidFromResource: function (resourceJid) {
  14198. if (resourceJid &&
  14199. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  14200. return this.myroomjid;
  14201. }
  14202. var peerJid = null;
  14203. Object.keys(this.members).some(function (jid) {
  14204. peerJid = jid;
  14205. return Strophe.getResourceFromJid(jid) === resourceJid;
  14206. });
  14207. return peerJid;
  14208. },
  14209. addBridgeIsDownToPresence: function () {
  14210. this.presMap['bridgeIsDown'] = true;
  14211. },
  14212. addEmailToPresence: function (email) {
  14213. this.presMap['email'] = email;
  14214. },
  14215. addUserIdToPresence: function (userId) {
  14216. this.presMap['userId'] = userId;
  14217. },
  14218. isModerator: function () {
  14219. return this.role === 'moderator';
  14220. },
  14221. getMemberRole: function (peerJid) {
  14222. if (this.members[peerJid]) {
  14223. return this.members[peerJid].role;
  14224. }
  14225. return null;
  14226. },
  14227. onParticipantLeft: function (jid) {
  14228. eventEmitter.emit(XMPPEvents.MUC_LEFT, jid);
  14229. this.connection.jingle.terminateByJid(jid);
  14230. if (this.getPrezi(jid)) {
  14231. $(document).trigger('presentationremoved.muc',
  14232. [jid, this.getPrezi(jid)]);
  14233. }
  14234. Moderator.onMucLeft(jid);
  14235. },
  14236. parsePresence: function (from, memeber, pres) {
  14237. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  14238. bridgeIsDown = true;
  14239. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  14240. }
  14241. if(memeber.isFocus)
  14242. return;
  14243. var self = this;
  14244. // Remove old ssrcs coming from the jid
  14245. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  14246. if (self.ssrc2jid[ssrc] == from) {
  14247. delete self.ssrc2jid[ssrc];
  14248. }
  14249. });
  14250. var changedStreams = [];
  14251. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  14252. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  14253. var ssrcV = ssrc.getAttribute('ssrc');
  14254. self.ssrc2jid[ssrcV] = from;
  14255. JingleSession.notReceivedSSRCs.push(ssrcV);
  14256. var type = ssrc.getAttribute('type');
  14257. var direction = ssrc.getAttribute('direction');
  14258. changedStreams.push({type: type, direction: direction});
  14259. });
  14260. eventEmitter.emit(XMPPEvents.CHANGED_STREAMS, from, changedStreams);
  14261. var displayName = !config.displayJids
  14262. ? memeber.displayName : Strophe.getResourceFromJid(from);
  14263. if (displayName && displayName.length > 0)
  14264. {
  14265. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  14266. }
  14267. var id = $(pres).find('>userID').text();
  14268. var email = $(pres).find('>email');
  14269. if(email.length > 0) {
  14270. id = email.text();
  14271. }
  14272. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  14273. }
  14274. });
  14275. };
  14276. },{"../../service/xmpp/XMPPEvents":97,"./JingleSession":48,"./moderator":53}],56:[function(require,module,exports){
  14277. /* jshint -W117 */
  14278. var JingleSession = require("./JingleSession");
  14279. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14280. module.exports = function(XMPP, eventEmitter)
  14281. {
  14282. function CallIncomingJingle(sid, connection) {
  14283. var sess = connection.jingle.sessions[sid];
  14284. // TODO: do we check activecall == null?
  14285. connection.jingle.activecall = sess;
  14286. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  14287. // TODO: check affiliation and/or role
  14288. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  14289. sess.usedrip = true; // not-so-naive trickle ice
  14290. sess.sendAnswer();
  14291. sess.accept();
  14292. };
  14293. Strophe.addConnectionPlugin('jingle', {
  14294. connection: null,
  14295. sessions: {},
  14296. jid2session: {},
  14297. ice_config: {iceServers: []},
  14298. pc_constraints: {},
  14299. activecall: null,
  14300. media_constraints: {
  14301. mandatory: {
  14302. 'OfferToReceiveAudio': true,
  14303. 'OfferToReceiveVideo': true
  14304. }
  14305. // MozDontOfferDataChannel: true when this is firefox
  14306. },
  14307. init: function (conn) {
  14308. this.connection = conn;
  14309. if (this.connection.disco) {
  14310. // http://xmpp.org/extensions/xep-0167.html#support
  14311. // http://xmpp.org/extensions/xep-0176.html#support
  14312. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  14313. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  14314. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  14315. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  14316. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  14317. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  14318. // this is dealt with by SDP O/A so we don't need to annouce this
  14319. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  14320. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  14321. if (config.useRtcpMux) {
  14322. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  14323. }
  14324. if (config.useBundle) {
  14325. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  14326. }
  14327. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  14328. }
  14329. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  14330. },
  14331. onJingle: function (iq) {
  14332. var sid = $(iq).find('jingle').attr('sid');
  14333. var action = $(iq).find('jingle').attr('action');
  14334. var fromJid = iq.getAttribute('from');
  14335. // send ack first
  14336. var ack = $iq({type: 'result',
  14337. to: fromJid,
  14338. id: iq.getAttribute('id')
  14339. });
  14340. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  14341. var sess = this.sessions[sid];
  14342. if ('session-initiate' != action) {
  14343. if (sess === null) {
  14344. ack.type = 'error';
  14345. ack.c('error', {type: 'cancel'})
  14346. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14347. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14348. this.connection.send(ack);
  14349. return true;
  14350. }
  14351. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  14352. // local jid is not checked
  14353. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  14354. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  14355. ack.type = 'error';
  14356. ack.c('error', {type: 'cancel'})
  14357. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14358. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14359. this.connection.send(ack);
  14360. return true;
  14361. }
  14362. } else if (sess !== undefined) {
  14363. // existing session with same session id
  14364. // this might be out-of-order if the sess.peerjid is the same as from
  14365. ack.type = 'error';
  14366. ack.c('error', {type: 'cancel'})
  14367. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  14368. console.warn('duplicate session id', sid);
  14369. this.connection.send(ack);
  14370. return true;
  14371. }
  14372. // FIXME: check for a defined action
  14373. this.connection.send(ack);
  14374. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  14375. switch (action) {
  14376. case 'session-initiate':
  14377. sess = new JingleSession(
  14378. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  14379. this.connection, XMPP);
  14380. // configure session
  14381. sess.media_constraints = this.media_constraints;
  14382. sess.pc_constraints = this.pc_constraints;
  14383. sess.ice_config = this.ice_config;
  14384. sess.initiate(fromJid, false);
  14385. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  14386. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  14387. this.sessions[sess.sid] = sess;
  14388. this.jid2session[sess.peerjid] = sess;
  14389. // the callback should either
  14390. // .sendAnswer and .accept
  14391. // or .sendTerminate -- not necessarily synchronus
  14392. CallIncomingJingle(sess.sid, this.connection);
  14393. break;
  14394. case 'session-accept':
  14395. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  14396. sess.accept();
  14397. $(document).trigger('callaccepted.jingle', [sess.sid]);
  14398. break;
  14399. case 'session-terminate':
  14400. // If this is not the focus sending the terminate, we have
  14401. // nothing more to do here.
  14402. if (Object.keys(this.sessions).length < 1
  14403. || !(this.sessions[Object.keys(this.sessions)[0]]
  14404. instanceof JingleSession))
  14405. {
  14406. break;
  14407. }
  14408. console.log('terminating...', sess.sid);
  14409. sess.terminate();
  14410. this.terminate(sess.sid);
  14411. if ($(iq).find('>jingle>reason').length) {
  14412. $(document).trigger('callterminated.jingle', [
  14413. sess.sid,
  14414. sess.peerjid,
  14415. $(iq).find('>jingle>reason>:first')[0].tagName,
  14416. $(iq).find('>jingle>reason>text').text()
  14417. ]);
  14418. } else {
  14419. $(document).trigger('callterminated.jingle',
  14420. [sess.sid, sess.peerjid]);
  14421. }
  14422. break;
  14423. case 'transport-info':
  14424. sess.addIceCandidate($(iq).find('>jingle>content'));
  14425. break;
  14426. case 'session-info':
  14427. var affected;
  14428. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14429. $(document).trigger('ringing.jingle', [sess.sid]);
  14430. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14431. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14432. $(document).trigger('mute.jingle', [sess.sid, affected]);
  14433. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14434. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14435. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  14436. }
  14437. break;
  14438. case 'addsource': // FIXME: proprietary, un-jingleish
  14439. case 'source-add': // FIXME: proprietary
  14440. sess.addSource($(iq).find('>jingle>content'), fromJid);
  14441. break;
  14442. case 'removesource': // FIXME: proprietary, un-jingleish
  14443. case 'source-remove': // FIXME: proprietary
  14444. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  14445. break;
  14446. default:
  14447. console.warn('jingle action not implemented', action);
  14448. break;
  14449. }
  14450. return true;
  14451. },
  14452. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  14453. var sess = new JingleSession(myjid || this.connection.jid,
  14454. Math.random().toString(36).substr(2, 12), // random string
  14455. this.connection, XMPP);
  14456. // configure session
  14457. sess.media_constraints = this.media_constraints;
  14458. sess.pc_constraints = this.pc_constraints;
  14459. sess.ice_config = this.ice_config;
  14460. sess.initiate(peerjid, true);
  14461. this.sessions[sess.sid] = sess;
  14462. this.jid2session[sess.peerjid] = sess;
  14463. sess.sendOffer();
  14464. return sess;
  14465. },
  14466. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  14467. if (sid === null || sid === undefined) {
  14468. for (sid in this.sessions) {
  14469. if (this.sessions[sid].state != 'ended') {
  14470. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14471. this.sessions[sid].terminate();
  14472. }
  14473. delete this.jid2session[this.sessions[sid].peerjid];
  14474. delete this.sessions[sid];
  14475. }
  14476. } else if (this.sessions.hasOwnProperty(sid)) {
  14477. if (this.sessions[sid].state != 'ended') {
  14478. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14479. this.sessions[sid].terminate();
  14480. }
  14481. delete this.jid2session[this.sessions[sid].peerjid];
  14482. delete this.sessions[sid];
  14483. }
  14484. },
  14485. // Used to terminate a session when an unavailable presence is received.
  14486. terminateByJid: function (jid) {
  14487. if (this.jid2session.hasOwnProperty(jid)) {
  14488. var sess = this.jid2session[jid];
  14489. if (sess) {
  14490. sess.terminate();
  14491. console.log('peer went away silently', jid);
  14492. delete this.sessions[sess.sid];
  14493. delete this.jid2session[jid];
  14494. $(document).trigger('callterminated.jingle',
  14495. [sess.sid, jid], 'gone');
  14496. }
  14497. }
  14498. },
  14499. terminateRemoteByJid: function (jid, reason) {
  14500. if (this.jid2session.hasOwnProperty(jid)) {
  14501. var sess = this.jid2session[jid];
  14502. if (sess) {
  14503. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  14504. sess.terminate();
  14505. console.log('terminate peer with jid', sess.sid, jid);
  14506. delete this.sessions[sess.sid];
  14507. delete this.jid2session[jid];
  14508. $(document).trigger('callterminated.jingle',
  14509. [sess.sid, jid, 'kicked']);
  14510. }
  14511. }
  14512. },
  14513. getStunAndTurnCredentials: function () {
  14514. // get stun and turn configuration from server via xep-0215
  14515. // uses time-limited credentials as described in
  14516. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  14517. //
  14518. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  14519. // for a prosody module which implements this
  14520. //
  14521. // currently, this doesn't work with updateIce and therefore credentials with a long
  14522. // validity have to be fetched before creating the peerconnection
  14523. // TODO: implement refresh via updateIce as described in
  14524. // https://code.google.com/p/webrtc/issues/detail?id=1650
  14525. var self = this;
  14526. this.connection.sendIQ(
  14527. $iq({type: 'get', to: this.connection.domain})
  14528. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  14529. function (res) {
  14530. var iceservers = [];
  14531. $(res).find('>services>service').each(function (idx, el) {
  14532. el = $(el);
  14533. var dict = {};
  14534. var type = el.attr('type');
  14535. switch (type) {
  14536. case 'stun':
  14537. dict.url = 'stun:' + el.attr('host');
  14538. if (el.attr('port')) {
  14539. dict.url += ':' + el.attr('port');
  14540. }
  14541. iceservers.push(dict);
  14542. break;
  14543. case 'turn':
  14544. case 'turns':
  14545. dict.url = type + ':';
  14546. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  14547. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  14548. dict.url += el.attr('username') + '@';
  14549. } else {
  14550. dict.username = el.attr('username'); // only works in M28
  14551. }
  14552. }
  14553. dict.url += el.attr('host');
  14554. if (el.attr('port') && el.attr('port') != '3478') {
  14555. dict.url += ':' + el.attr('port');
  14556. }
  14557. if (el.attr('transport') && el.attr('transport') != 'udp') {
  14558. dict.url += '?transport=' + el.attr('transport');
  14559. }
  14560. if (el.attr('password')) {
  14561. dict.credential = el.attr('password');
  14562. }
  14563. iceservers.push(dict);
  14564. break;
  14565. }
  14566. });
  14567. self.ice_config.iceServers = iceservers;
  14568. },
  14569. function (err) {
  14570. console.warn('getting turn credentials failed', err);
  14571. console.warn('is mod_turncredentials or similar installed?');
  14572. }
  14573. );
  14574. // implement push?
  14575. },
  14576. /**
  14577. * Populates the log data
  14578. */
  14579. populateData: function () {
  14580. var data = {};
  14581. Object.keys(this.sessions).forEach(function (sid) {
  14582. var session = this.sessions[sid];
  14583. if (session.peerconnection && session.peerconnection.updateLog) {
  14584. // FIXME: should probably be a .dump call
  14585. data["jingle_" + session.sid] = {
  14586. updateLog: session.peerconnection.updateLog,
  14587. stats: session.peerconnection.stats,
  14588. url: window.location.href
  14589. };
  14590. }
  14591. });
  14592. return data;
  14593. }
  14594. });
  14595. };
  14596. },{"../../service/xmpp/XMPPEvents":97,"./JingleSession":48}],57:[function(require,module,exports){
  14597. /* global Strophe */
  14598. module.exports = function () {
  14599. Strophe.addConnectionPlugin('logger', {
  14600. // logs raw stanzas and makes them available for download as JSON
  14601. connection: null,
  14602. log: [],
  14603. init: function (conn) {
  14604. this.connection = conn;
  14605. this.connection.rawInput = this.log_incoming.bind(this);
  14606. this.connection.rawOutput = this.log_outgoing.bind(this);
  14607. },
  14608. log_incoming: function (stanza) {
  14609. this.log.push([new Date().getTime(), 'incoming', stanza]);
  14610. },
  14611. log_outgoing: function (stanza) {
  14612. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  14613. }
  14614. });
  14615. };
  14616. },{}],58:[function(require,module,exports){
  14617. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  14618. setAudioMuted, Strophe */
  14619. /**
  14620. * Moderate connection plugin.
  14621. */
  14622. module.exports = function (XMPP) {
  14623. Strophe.addConnectionPlugin('moderate', {
  14624. connection: null,
  14625. init: function (conn) {
  14626. this.connection = conn;
  14627. this.connection.addHandler(this.onMute.bind(this),
  14628. 'http://jitsi.org/jitmeet/audio',
  14629. 'iq',
  14630. 'set',
  14631. null,
  14632. null);
  14633. },
  14634. setMute: function (jid, mute) {
  14635. console.info("set mute", mute);
  14636. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  14637. .c('mute', {
  14638. xmlns: 'http://jitsi.org/jitmeet/audio',
  14639. jid: jid
  14640. })
  14641. .t(mute.toString())
  14642. .up();
  14643. this.connection.sendIQ(
  14644. iqToFocus,
  14645. function (result) {
  14646. console.log('set mute', result);
  14647. },
  14648. function (error) {
  14649. console.log('set mute error', error);
  14650. });
  14651. },
  14652. onMute: function (iq) {
  14653. var from = iq.getAttribute('from');
  14654. if (from !== this.connection.emuc.focusMucJid) {
  14655. console.warn("Ignored mute from non focus peer");
  14656. return false;
  14657. }
  14658. var mute = $(iq).find('mute');
  14659. if (mute.length) {
  14660. var doMuteAudio = mute.text() === "true";
  14661. APP.UI.setAudioMuted(doMuteAudio);
  14662. XMPP.forceMuted = doMuteAudio;
  14663. }
  14664. return true;
  14665. },
  14666. eject: function (jid) {
  14667. // We're not the focus, so can't terminate
  14668. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  14669. this.connection.emuc.kick(jid);
  14670. }
  14671. });
  14672. }
  14673. },{}],59:[function(require,module,exports){
  14674. /* jshint -W117 */
  14675. module.exports = function() {
  14676. Strophe.addConnectionPlugin('rayo',
  14677. {
  14678. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  14679. connection: null,
  14680. init: function (conn) {
  14681. this.connection = conn;
  14682. if (this.connection.disco) {
  14683. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  14684. }
  14685. this.connection.addHandler(
  14686. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  14687. },
  14688. onRayo: function (iq) {
  14689. console.info("Rayo IQ", iq);
  14690. },
  14691. dial: function (to, from, roomName, roomPass) {
  14692. var self = this;
  14693. var req = $iq(
  14694. {
  14695. type: 'set',
  14696. to: this.connection.emuc.focusMucJid
  14697. }
  14698. );
  14699. req.c('dial',
  14700. {
  14701. xmlns: this.RAYO_XMLNS,
  14702. to: to,
  14703. from: from
  14704. });
  14705. req.c('header',
  14706. {
  14707. name: 'JvbRoomName',
  14708. value: roomName
  14709. }).up();
  14710. if (roomPass !== null && roomPass.length) {
  14711. req.c('header',
  14712. {
  14713. name: 'JvbRoomPassword',
  14714. value: roomPass
  14715. }).up();
  14716. }
  14717. this.connection.sendIQ(
  14718. req,
  14719. function (result) {
  14720. console.info('Dial result ', result);
  14721. var resource = $(result).find('ref').attr('uri');
  14722. this.call_resource = resource.substr('xmpp:'.length);
  14723. console.info(
  14724. "Received call resource: " + this.call_resource);
  14725. },
  14726. function (error) {
  14727. console.info('Dial error ', error);
  14728. }
  14729. );
  14730. },
  14731. hang_up: function () {
  14732. if (!this.call_resource) {
  14733. console.warn("No call in progress");
  14734. return;
  14735. }
  14736. var self = this;
  14737. var req = $iq(
  14738. {
  14739. type: 'set',
  14740. to: this.call_resource
  14741. }
  14742. );
  14743. req.c('hangup',
  14744. {
  14745. xmlns: this.RAYO_XMLNS
  14746. });
  14747. this.connection.sendIQ(
  14748. req,
  14749. function (result) {
  14750. console.info('Hangup result ', result);
  14751. self.call_resource = null;
  14752. },
  14753. function (error) {
  14754. console.info('Hangup error ', error);
  14755. self.call_resource = null;
  14756. }
  14757. );
  14758. }
  14759. }
  14760. );
  14761. };
  14762. },{}],60:[function(require,module,exports){
  14763. /**
  14764. * Strophe logger implementation. Logs from level WARN and above.
  14765. */
  14766. module.exports = function () {
  14767. Strophe.log = function (level, msg) {
  14768. switch (level) {
  14769. case Strophe.LogLevel.WARN:
  14770. console.warn("Strophe: " + msg);
  14771. break;
  14772. case Strophe.LogLevel.ERROR:
  14773. case Strophe.LogLevel.FATAL:
  14774. console.error("Strophe: " + msg);
  14775. break;
  14776. }
  14777. };
  14778. Strophe.getStatusString = function (status) {
  14779. switch (status) {
  14780. case Strophe.Status.ERROR:
  14781. return "ERROR";
  14782. case Strophe.Status.CONNECTING:
  14783. return "CONNECTING";
  14784. case Strophe.Status.CONNFAIL:
  14785. return "CONNFAIL";
  14786. case Strophe.Status.AUTHENTICATING:
  14787. return "AUTHENTICATING";
  14788. case Strophe.Status.AUTHFAIL:
  14789. return "AUTHFAIL";
  14790. case Strophe.Status.CONNECTED:
  14791. return "CONNECTED";
  14792. case Strophe.Status.DISCONNECTED:
  14793. return "DISCONNECTED";
  14794. case Strophe.Status.DISCONNECTING:
  14795. return "DISCONNECTING";
  14796. case Strophe.Status.ATTACHED:
  14797. return "ATTACHED";
  14798. default:
  14799. return "unknown";
  14800. }
  14801. };
  14802. };
  14803. },{}],61:[function(require,module,exports){
  14804. /* global $, APP, config, Strophe*/
  14805. var Moderator = require("./moderator");
  14806. var EventEmitter = require("events");
  14807. var Recording = require("./recording");
  14808. var SDP = require("./SDP");
  14809. var Settings = require("../settings/Settings");
  14810. var Pako = require("pako");
  14811. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  14812. var RTCEvents = require("../../service/RTC/RTCEvents");
  14813. var UIEvents = require("../../service/UI/UIEvents");
  14814. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14815. var eventEmitter = new EventEmitter();
  14816. var connection = null;
  14817. var authenticatedUser = false;
  14818. function connect(jid, password) {
  14819. connection = XMPP.createConnection();
  14820. Moderator.setConnection(connection);
  14821. if (connection.disco) {
  14822. // for chrome, add multistream cap
  14823. }
  14824. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  14825. if (config.useIPv6) {
  14826. // https://code.google.com/p/webrtc/issues/detail?id=2828
  14827. if (!connection.jingle.pc_constraints.optional)
  14828. connection.jingle.pc_constraints.optional = [];
  14829. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  14830. }
  14831. // Include user info in MUC presence
  14832. var settings = Settings.getSettings();
  14833. if (settings.email) {
  14834. connection.emuc.addEmailToPresence(settings.email);
  14835. }
  14836. if (settings.uid) {
  14837. connection.emuc.addUserIdToPresence(settings.uid);
  14838. }
  14839. if (settings.displayName) {
  14840. connection.emuc.addDisplayNameToPresence(settings.displayName);
  14841. }
  14842. var anonymousConnectionFailed = false;
  14843. connection.connect(jid, password, function (status, msg) {
  14844. console.log('Strophe status changed to',
  14845. Strophe.getStatusString(status));
  14846. if (status === Strophe.Status.CONNECTED) {
  14847. if (config.useStunTurn) {
  14848. connection.jingle.getStunAndTurnCredentials();
  14849. }
  14850. console.info("My Jabber ID: " + connection.jid);
  14851. if(password)
  14852. authenticatedUser = true;
  14853. maybeDoJoin();
  14854. } else if (status === Strophe.Status.CONNFAIL) {
  14855. if(msg === 'x-strophe-bad-non-anon-jid') {
  14856. anonymousConnectionFailed = true;
  14857. }
  14858. } else if (status === Strophe.Status.DISCONNECTED) {
  14859. if(anonymousConnectionFailed) {
  14860. // prompt user for username and password
  14861. XMPP.promptLogin();
  14862. }
  14863. } else if (status === Strophe.Status.AUTHFAIL) {
  14864. // wrong password or username, prompt user
  14865. XMPP.promptLogin();
  14866. }
  14867. });
  14868. }
  14869. function maybeDoJoin() {
  14870. if (connection && connection.connected &&
  14871. Strophe.getResourceFromJid(connection.jid)
  14872. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  14873. // .connected is true while connecting?
  14874. doJoin();
  14875. }
  14876. }
  14877. function doJoin() {
  14878. var roomName = APP.UI.generateRoomName();
  14879. Moderator.allocateConferenceFocus(
  14880. roomName, APP.UI.checkForNicknameAndJoin);
  14881. }
  14882. function initStrophePlugins()
  14883. {
  14884. require("./strophe.emuc")(XMPP, eventEmitter);
  14885. require("./strophe.jingle")(XMPP, eventEmitter);
  14886. require("./strophe.moderate")(XMPP);
  14887. require("./strophe.util")();
  14888. require("./strophe.rayo")();
  14889. require("./strophe.logger")();
  14890. }
  14891. function registerListeners() {
  14892. APP.RTC.addStreamListener(maybeDoJoin,
  14893. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  14894. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  14895. XMPP.addToPresence("devices", devices);
  14896. })
  14897. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  14898. XMPP.addToPresence("displayName", nickname);
  14899. });
  14900. }
  14901. function setupEvents() {
  14902. $(window).bind('beforeunload', function () {
  14903. if (connection && connection.connected) {
  14904. // ensure signout
  14905. $.ajax({
  14906. type: 'POST',
  14907. url: config.bosh,
  14908. async: false,
  14909. cache: false,
  14910. contentType: 'application/xml',
  14911. data: "<body rid='" + (connection.rid || connection._proto.rid)
  14912. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  14913. + (connection.sid || connection._proto.sid)
  14914. + "' type='terminate'>" +
  14915. "<presence xmlns='jabber:client' type='unavailable'/>" +
  14916. "</body>",
  14917. success: function (data) {
  14918. console.log('signed out');
  14919. console.log(data);
  14920. },
  14921. error: function (XMLHttpRequest, textStatus, errorThrown) {
  14922. console.log('signout error',
  14923. textStatus + ' (' + errorThrown + ')');
  14924. }
  14925. });
  14926. }
  14927. XMPP.disposeConference(true);
  14928. });
  14929. }
  14930. var XMPP = {
  14931. sessionTerminated: false,
  14932. /**
  14933. * XMPP connection status
  14934. */
  14935. Status: Strophe.Status,
  14936. /**
  14937. * Remembers if we were muted by the focus.
  14938. * @type {boolean}
  14939. */
  14940. forceMuted: false,
  14941. start: function () {
  14942. setupEvents();
  14943. initStrophePlugins();
  14944. registerListeners();
  14945. Moderator.init(this, eventEmitter);
  14946. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  14947. // Force authenticated domain if room is appended with '?login=true'
  14948. if (config.hosts.anonymousdomain &&
  14949. window.location.search.indexOf("login=true") !== -1) {
  14950. configDomain = config.hosts.domain;
  14951. }
  14952. var jid = configDomain || window.location.hostname;
  14953. connect(jid, null);
  14954. },
  14955. createConnection: function () {
  14956. var bosh = config.bosh || '/http-bind';
  14957. return new Strophe.Connection(bosh);
  14958. },
  14959. getStatusString: function (status) {
  14960. return Strophe.getStatusString(status);
  14961. },
  14962. promptLogin: function () {
  14963. // FIXME: re-use LoginDialog which supports retries
  14964. APP.UI.showLoginPopup(connect);
  14965. },
  14966. joinRoom: function(roomName, useNicks, nick)
  14967. {
  14968. var roomjid;
  14969. roomjid = roomName;
  14970. if (useNicks) {
  14971. if (nick) {
  14972. roomjid += '/' + nick;
  14973. } else {
  14974. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  14975. }
  14976. } else {
  14977. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  14978. if(!authenticatedUser)
  14979. tmpJid = tmpJid.substr(0, 8);
  14980. roomjid += '/' + tmpJid;
  14981. }
  14982. connection.emuc.doJoin(roomjid);
  14983. },
  14984. myJid: function () {
  14985. if(!connection)
  14986. return null;
  14987. return connection.emuc.myroomjid;
  14988. },
  14989. myResource: function () {
  14990. if(!connection || ! connection.emuc.myroomjid)
  14991. return null;
  14992. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  14993. },
  14994. disposeConference: function (onUnload) {
  14995. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  14996. var handler = connection.jingle.activecall;
  14997. if (handler && handler.peerconnection) {
  14998. // FIXME: probably removing streams is not required and close() should
  14999. // be enough
  15000. if (APP.RTC.localAudio) {
  15001. handler.peerconnection.removeStream(
  15002. APP.RTC.localAudio.getOriginalStream(), onUnload);
  15003. }
  15004. if (APP.RTC.localVideo) {
  15005. handler.peerconnection.removeStream(
  15006. APP.RTC.localVideo.getOriginalStream(), onUnload);
  15007. }
  15008. handler.peerconnection.close();
  15009. }
  15010. connection.jingle.activecall = null;
  15011. if(!onUnload)
  15012. {
  15013. this.sessionTerminated = true;
  15014. connection.emuc.doLeave();
  15015. }
  15016. },
  15017. addListener: function(type, listener)
  15018. {
  15019. eventEmitter.on(type, listener);
  15020. },
  15021. removeListener: function (type, listener) {
  15022. eventEmitter.removeListener(type, listener);
  15023. },
  15024. allocateConferenceFocus: function(roomName, callback) {
  15025. Moderator.allocateConferenceFocus(roomName, callback);
  15026. },
  15027. getLoginUrl: function (roomName, callback) {
  15028. Moderator.getLoginUrl(roomName, callback);
  15029. },
  15030. getPopupLoginUrl: function (roomName, callback) {
  15031. Moderator.getPopupLoginUrl(roomName, callback);
  15032. },
  15033. isModerator: function () {
  15034. return Moderator.isModerator();
  15035. },
  15036. isSipGatewayEnabled: function () {
  15037. return Moderator.isSipGatewayEnabled();
  15038. },
  15039. isExternalAuthEnabled: function () {
  15040. return Moderator.isExternalAuthEnabled();
  15041. },
  15042. switchStreams: function (stream, oldStream, callback) {
  15043. if (connection && connection.jingle.activecall) {
  15044. // FIXME: will block switchInProgress on true value in case of exception
  15045. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  15046. } else {
  15047. // We are done immediately
  15048. console.warn("No conference handler or conference not started yet");
  15049. callback();
  15050. }
  15051. },
  15052. sendVideoInfoPresence: function (mute) {
  15053. connection.emuc.addVideoInfoToPresence(mute);
  15054. connection.emuc.sendPresence();
  15055. },
  15056. setVideoMute: function (mute, callback, options) {
  15057. if(!connection)
  15058. return;
  15059. var self = this;
  15060. var localCallback = function (mute) {
  15061. self.sendVideoInfoPresence(mute);
  15062. return callback(mute);
  15063. };
  15064. if(connection.jingle.activecall)
  15065. {
  15066. connection.jingle.activecall.setVideoMute(
  15067. mute, localCallback, options);
  15068. }
  15069. else {
  15070. localCallback(mute);
  15071. }
  15072. },
  15073. setAudioMute: function (mute, callback) {
  15074. if (!(connection && APP.RTC.localAudio)) {
  15075. return false;
  15076. }
  15077. if (this.forceMuted && !mute) {
  15078. console.info("Asking focus for unmute");
  15079. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  15080. // FIXME: wait for result before resetting muted status
  15081. this.forceMuted = false;
  15082. }
  15083. if (mute == APP.RTC.localAudio.isMuted()) {
  15084. // Nothing to do
  15085. return true;
  15086. }
  15087. // It is not clear what is the right way to handle multiple tracks.
  15088. // So at least make sure that they are all muted or all unmuted and
  15089. // that we send presence just once.
  15090. APP.RTC.localAudio.mute();
  15091. // isMuted is the opposite of audioEnabled
  15092. connection.emuc.addAudioInfoToPresence(mute);
  15093. connection.emuc.sendPresence();
  15094. callback();
  15095. return true;
  15096. },
  15097. // Really mute video, i.e. dont even send black frames
  15098. muteVideo: function (pc, unmute) {
  15099. // FIXME: this probably needs another of those lovely state safeguards...
  15100. // which checks for iceconn == connected and sigstate == stable
  15101. pc.setRemoteDescription(pc.remoteDescription,
  15102. function () {
  15103. pc.createAnswer(
  15104. function (answer) {
  15105. var sdp = new SDP(answer.sdp);
  15106. if (sdp.media.length > 1) {
  15107. if (unmute)
  15108. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  15109. else
  15110. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  15111. sdp.raw = sdp.session + sdp.media.join('');
  15112. answer.sdp = sdp.raw;
  15113. }
  15114. pc.setLocalDescription(answer,
  15115. function () {
  15116. console.log('mute SLD ok');
  15117. },
  15118. function (error) {
  15119. console.log('mute SLD error');
  15120. APP.UI.messageHandler.showError("dialog.error",
  15121. "dialog.SLDFailure");
  15122. }
  15123. );
  15124. },
  15125. function (error) {
  15126. console.log(error);
  15127. APP.UI.messageHandler.showError();
  15128. }
  15129. );
  15130. },
  15131. function (error) {
  15132. console.log('muteVideo SRD error');
  15133. APP.UI.messageHandler.showError("dialog.error",
  15134. "dialog.SRDFailure");
  15135. }
  15136. );
  15137. },
  15138. toggleRecording: function (tokenEmptyCallback,
  15139. startingCallback, startedCallback) {
  15140. Recording.toggleRecording(tokenEmptyCallback,
  15141. startingCallback, startedCallback, connection);
  15142. },
  15143. addToPresence: function (name, value, dontSend) {
  15144. switch (name)
  15145. {
  15146. case "displayName":
  15147. connection.emuc.addDisplayNameToPresence(value);
  15148. break;
  15149. case "etherpad":
  15150. connection.emuc.addEtherpadToPresence(value);
  15151. break;
  15152. case "prezi":
  15153. connection.emuc.addPreziToPresence(value, 0);
  15154. break;
  15155. case "preziSlide":
  15156. connection.emuc.addCurrentSlideToPresence(value);
  15157. break;
  15158. case "connectionQuality":
  15159. connection.emuc.addConnectionInfoToPresence(value);
  15160. break;
  15161. case "email":
  15162. connection.emuc.addEmailToPresence(value);
  15163. break;
  15164. case "devices":
  15165. connection.emuc.addDevicesToPresence(value);
  15166. break;
  15167. default :
  15168. console.log("Unknown tag for presence: " + name);
  15169. return;
  15170. }
  15171. if (!dontSend)
  15172. connection.emuc.sendPresence();
  15173. },
  15174. /**
  15175. * Sends 'data' as a log message to the focus. Returns true iff a message
  15176. * was sent.
  15177. * @param data
  15178. * @returns {boolean} true iff a message was sent.
  15179. */
  15180. sendLogs: function (data) {
  15181. if(!connection.emuc.focusMucJid)
  15182. return false;
  15183. var deflate = true;
  15184. var content = JSON.stringify(data);
  15185. if (deflate) {
  15186. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  15187. }
  15188. content = Base64.encode(content);
  15189. // XEP-0337-ish
  15190. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  15191. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  15192. id: 'PeerConnectionStats'});
  15193. message.c('message').t(content).up();
  15194. if (deflate) {
  15195. message.c('tag', {name: "deflated", value: "true"}).up();
  15196. }
  15197. message.up();
  15198. connection.send(message);
  15199. return true;
  15200. },
  15201. populateData: function () {
  15202. var data = {};
  15203. if (connection.jingle) {
  15204. data = connection.jingle.populateData();
  15205. }
  15206. return data;
  15207. },
  15208. getLogger: function () {
  15209. if(connection.logger)
  15210. return connection.logger.log;
  15211. return null;
  15212. },
  15213. getPrezi: function () {
  15214. return connection.emuc.getPrezi(this.myJid());
  15215. },
  15216. removePreziFromPresence: function () {
  15217. connection.emuc.removePreziFromPresence();
  15218. connection.emuc.sendPresence();
  15219. },
  15220. sendChatMessage: function (message, nickname) {
  15221. connection.emuc.sendMessage(message, nickname);
  15222. },
  15223. setSubject: function (topic) {
  15224. connection.emuc.setSubject(topic);
  15225. },
  15226. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15227. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  15228. },
  15229. dial: function (to, from, roomName,roomPass) {
  15230. connection.rayo.dial(to, from, roomName,roomPass);
  15231. },
  15232. setMute: function (jid, mute) {
  15233. connection.moderate.setMute(jid, mute);
  15234. },
  15235. eject: function (jid) {
  15236. connection.moderate.eject(jid);
  15237. },
  15238. logout: function (callback) {
  15239. Moderator.logout(callback);
  15240. },
  15241. findJidFromResource: function (resource) {
  15242. return connection.emuc.findJidFromResource(resource);
  15243. },
  15244. getMembers: function () {
  15245. return connection.emuc.members;
  15246. },
  15247. getJidFromSSRC: function (ssrc) {
  15248. if(!connection)
  15249. return null;
  15250. return connection.emuc.ssrc2jid[ssrc];
  15251. },
  15252. getMUCJoined: function () {
  15253. return connection.emuc.joined;
  15254. },
  15255. getSessions: function () {
  15256. return connection.jingle.sessions;
  15257. },
  15258. removeStream: function (stream) {
  15259. if(!connection || !connection.jingle.activecall ||
  15260. !connection.jingle.activecall.peerconnection)
  15261. return;
  15262. connection.jingle.activecall.peerconnection.removeStream(stream);
  15263. }
  15264. };
  15265. module.exports = XMPP;
  15266. },{"../../service/RTC/RTCEvents":89,"../../service/RTC/StreamEventTypes":91,"../../service/UI/UIEvents":92,"../../service/xmpp/XMPPEvents":97,"../settings/Settings":38,"./SDP":49,"./moderator":53,"./recording":54,"./strophe.emuc":55,"./strophe.jingle":56,"./strophe.logger":57,"./strophe.moderate":58,"./strophe.rayo":59,"./strophe.util":60,"events":98,"pako":63}],62:[function(require,module,exports){
  15267. // i18next, v1.7.7
  15268. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  15269. // Distributed under MIT license
  15270. // http://i18next.com
  15271. (function() {
  15272. // add indexOf to non ECMA-262 standard compliant browsers
  15273. if (!Array.prototype.indexOf) {
  15274. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  15275. "use strict";
  15276. if (this == null) {
  15277. throw new TypeError();
  15278. }
  15279. var t = Object(this);
  15280. var len = t.length >>> 0;
  15281. if (len === 0) {
  15282. return -1;
  15283. }
  15284. var n = 0;
  15285. if (arguments.length > 0) {
  15286. n = Number(arguments[1]);
  15287. if (n != n) { // shortcut for verifying if it's NaN
  15288. n = 0;
  15289. } else if (n != 0 && n != Infinity && n != -Infinity) {
  15290. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  15291. }
  15292. }
  15293. if (n >= len) {
  15294. return -1;
  15295. }
  15296. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  15297. for (; k < len; k++) {
  15298. if (k in t && t[k] === searchElement) {
  15299. return k;
  15300. }
  15301. }
  15302. return -1;
  15303. }
  15304. }
  15305. // add lastIndexOf to non ECMA-262 standard compliant browsers
  15306. if (!Array.prototype.lastIndexOf) {
  15307. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  15308. "use strict";
  15309. if (this == null) {
  15310. throw new TypeError();
  15311. }
  15312. var t = Object(this);
  15313. var len = t.length >>> 0;
  15314. if (len === 0) {
  15315. return -1;
  15316. }
  15317. var n = len;
  15318. if (arguments.length > 1) {
  15319. n = Number(arguments[1]);
  15320. if (n != n) {
  15321. n = 0;
  15322. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  15323. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  15324. }
  15325. }
  15326. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  15327. for (; k >= 0; k--) {
  15328. if (k in t && t[k] === searchElement) {
  15329. return k;
  15330. }
  15331. }
  15332. return -1;
  15333. };
  15334. }
  15335. // Add string trim for IE8.
  15336. if (typeof String.prototype.trim !== 'function') {
  15337. String.prototype.trim = function() {
  15338. return this.replace(/^\s+|\s+$/g, '');
  15339. }
  15340. }
  15341. var root = this
  15342. , $ = root.jQuery || root.Zepto
  15343. , i18n = {}
  15344. , resStore = {}
  15345. , currentLng
  15346. , replacementCounter = 0
  15347. , languages = []
  15348. , initialized = false
  15349. , sync = {};
  15350. // Export the i18next object for **CommonJS**.
  15351. // If we're not in CommonJS, add `i18n` to the
  15352. // global object or to jquery.
  15353. if (typeof module !== 'undefined' && module.exports) {
  15354. if (!$) {
  15355. try {
  15356. $ = require('jquery');
  15357. } catch(e) {
  15358. // just ignore
  15359. }
  15360. }
  15361. if ($) {
  15362. $.i18n = $.i18n || i18n;
  15363. }
  15364. module.exports = i18n;
  15365. } else {
  15366. if ($) {
  15367. $.i18n = $.i18n || i18n;
  15368. }
  15369. root.i18n = root.i18n || i18n;
  15370. }
  15371. sync = {
  15372. load: function(lngs, options, cb) {
  15373. if (options.useLocalStorage) {
  15374. sync._loadLocal(lngs, options, function(err, store) {
  15375. var missingLngs = [];
  15376. for (var i = 0, len = lngs.length; i < len; i++) {
  15377. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  15378. }
  15379. if (missingLngs.length > 0) {
  15380. sync._fetch(missingLngs, options, function(err, fetched) {
  15381. f.extend(store, fetched);
  15382. sync._storeLocal(fetched);
  15383. cb(null, store);
  15384. });
  15385. } else {
  15386. cb(null, store);
  15387. }
  15388. });
  15389. } else {
  15390. sync._fetch(lngs, options, function(err, store){
  15391. cb(null, store);
  15392. });
  15393. }
  15394. },
  15395. _loadLocal: function(lngs, options, cb) {
  15396. var store = {}
  15397. , nowMS = new Date().getTime();
  15398. if(window.localStorage) {
  15399. var todo = lngs.length;
  15400. f.each(lngs, function(key, lng) {
  15401. var local = window.localStorage.getItem('res_' + lng);
  15402. if (local) {
  15403. local = JSON.parse(local);
  15404. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  15405. store[lng] = local;
  15406. }
  15407. }
  15408. todo--; // wait for all done befor callback
  15409. if (todo === 0) cb(null, store);
  15410. });
  15411. }
  15412. },
  15413. _storeLocal: function(store) {
  15414. if(window.localStorage) {
  15415. for (var m in store) {
  15416. store[m].i18nStamp = new Date().getTime();
  15417. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  15418. }
  15419. }
  15420. return;
  15421. },
  15422. _fetch: function(lngs, options, cb) {
  15423. var ns = options.ns
  15424. , store = {};
  15425. if (!options.dynamicLoad) {
  15426. var todo = ns.namespaces.length * lngs.length
  15427. , errors;
  15428. // load each file individual
  15429. f.each(ns.namespaces, function(nsIndex, nsValue) {
  15430. f.each(lngs, function(lngIndex, lngValue) {
  15431. // Call this once our translation has returned.
  15432. var loadComplete = function(err, data) {
  15433. if (err) {
  15434. errors = errors || [];
  15435. errors.push(err);
  15436. }
  15437. store[lngValue] = store[lngValue] || {};
  15438. store[lngValue][nsValue] = data;
  15439. todo--; // wait for all done befor callback
  15440. if (todo === 0) cb(errors, store);
  15441. };
  15442. if(typeof options.customLoad == 'function'){
  15443. // Use the specified custom callback.
  15444. options.customLoad(lngValue, nsValue, options, loadComplete);
  15445. } else {
  15446. //~ // Use our inbuilt sync.
  15447. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  15448. }
  15449. });
  15450. });
  15451. } else {
  15452. // Call this once our translation has returned.
  15453. var loadComplete = function(err, data) {
  15454. cb(null, data);
  15455. };
  15456. if(typeof options.customLoad == 'function'){
  15457. // Use the specified custom callback.
  15458. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  15459. } else {
  15460. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  15461. // load all needed stuff once
  15462. f.ajax({
  15463. url: url,
  15464. success: function(data, status, xhr) {
  15465. f.log('loaded: ' + url);
  15466. loadComplete(null, data);
  15467. },
  15468. error : function(xhr, status, error) {
  15469. f.log('failed loading: ' + url);
  15470. loadComplete('failed loading resource.json error: ' + error);
  15471. },
  15472. dataType: "json",
  15473. async : options.getAsync
  15474. });
  15475. }
  15476. }
  15477. },
  15478. _fetchOne: function(lng, ns, options, done) {
  15479. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  15480. f.ajax({
  15481. url: url,
  15482. success: function(data, status, xhr) {
  15483. f.log('loaded: ' + url);
  15484. done(null, data);
  15485. },
  15486. error : function(xhr, status, error) {
  15487. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  15488. // file loaded but invalid json, stop waste time !
  15489. f.error('There is a typo in: ' + url);
  15490. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  15491. f.log('Does not exist: ' + url);
  15492. } else {
  15493. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  15494. f.log(theStatus + ' when loading ' + url);
  15495. }
  15496. done(error, {});
  15497. },
  15498. dataType: "json",
  15499. async : options.getAsync
  15500. });
  15501. },
  15502. postMissing: function(lng, ns, key, defaultValue, lngs) {
  15503. var payload = {};
  15504. payload[key] = defaultValue;
  15505. var urls = [];
  15506. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  15507. for (var i = 0; i < o.fallbackLng.length; i++) {
  15508. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  15509. }
  15510. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  15511. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  15512. } else if (o.sendMissingTo === 'all') {
  15513. for (var i = 0, l = lngs.length; i < l; i++) {
  15514. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  15515. }
  15516. }
  15517. for (var y = 0, len = urls.length; y < len; y++) {
  15518. var item = urls[y];
  15519. f.ajax({
  15520. url: item.url,
  15521. type: o.sendType,
  15522. data: payload,
  15523. success: function(data, status, xhr) {
  15524. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  15525. // add key to resStore
  15526. var keys = key.split('.');
  15527. var x = 0;
  15528. var value = resStore[item.lng][ns];
  15529. while (keys[x]) {
  15530. if (x === keys.length - 1) {
  15531. value = value[keys[x]] = defaultValue;
  15532. } else {
  15533. value = value[keys[x]] = value[keys[x]] || {};
  15534. }
  15535. x++;
  15536. }
  15537. },
  15538. error : function(xhr, status, error) {
  15539. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  15540. },
  15541. dataType: "json",
  15542. async : o.postAsync
  15543. });
  15544. }
  15545. },
  15546. reload: reload
  15547. };
  15548. // defaults
  15549. var o = {
  15550. lng: undefined,
  15551. load: 'all',
  15552. preload: [],
  15553. lowerCaseLng: false,
  15554. returnObjectTrees: false,
  15555. fallbackLng: ['dev'],
  15556. fallbackNS: [],
  15557. detectLngQS: 'setLng',
  15558. detectLngFromLocalStorage: false,
  15559. ns: 'translation',
  15560. fallbackOnNull: true,
  15561. fallbackOnEmpty: false,
  15562. fallbackToDefaultNS: false,
  15563. nsseparator: ':',
  15564. keyseparator: '.',
  15565. selectorAttr: 'data-i18n',
  15566. debug: false,
  15567. resGetPath: 'locales/__lng__/__ns__.json',
  15568. resPostPath: 'locales/add/__lng__/__ns__',
  15569. getAsync: true,
  15570. postAsync: true,
  15571. resStore: undefined,
  15572. useLocalStorage: false,
  15573. localStorageExpirationTime: 7*24*60*60*1000,
  15574. dynamicLoad: false,
  15575. sendMissing: false,
  15576. sendMissingTo: 'fallback', // current | all
  15577. sendType: 'POST',
  15578. interpolationPrefix: '__',
  15579. interpolationSuffix: '__',
  15580. defaultVariables: false,
  15581. reusePrefix: '$t(',
  15582. reuseSuffix: ')',
  15583. pluralSuffix: '_plural',
  15584. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  15585. contextNotFound: ['context_not_found', Math.random()].join(''),
  15586. escapeInterpolation: false,
  15587. indefiniteSuffix: '_indefinite',
  15588. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  15589. setJqueryExt: true,
  15590. defaultValueFromContent: true,
  15591. useDataAttrOptions: false,
  15592. cookieExpirationTime: undefined,
  15593. useCookie: true,
  15594. cookieName: 'i18next',
  15595. cookieDomain: undefined,
  15596. objectTreeKeyHandler: undefined,
  15597. postProcess: undefined,
  15598. parseMissingKey: undefined,
  15599. missingKeyHandler: sync.postMissing,
  15600. shortcutFunction: 'sprintf' // or: defaultValue
  15601. };
  15602. function _extend(target, source) {
  15603. if (!source || typeof source === 'function') {
  15604. return target;
  15605. }
  15606. for (var attr in source) { target[attr] = source[attr]; }
  15607. return target;
  15608. }
  15609. function _deepExtend(target, source) {
  15610. for (var prop in source)
  15611. if (prop in target)
  15612. _deepExtend(target[prop], source[prop]);
  15613. else
  15614. target[prop] = source[prop];
  15615. return target;
  15616. }
  15617. function _each(object, callback, args) {
  15618. var name, i = 0,
  15619. length = object.length,
  15620. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  15621. if (args) {
  15622. if (isObj) {
  15623. for (name in object) {
  15624. if (callback.apply(object[name], args) === false) {
  15625. break;
  15626. }
  15627. }
  15628. } else {
  15629. for ( ; i < length; ) {
  15630. if (callback.apply(object[i++], args) === false) {
  15631. break;
  15632. }
  15633. }
  15634. }
  15635. // A special, fast, case for the most common use of each
  15636. } else {
  15637. if (isObj) {
  15638. for (name in object) {
  15639. if (callback.call(object[name], name, object[name]) === false) {
  15640. break;
  15641. }
  15642. }
  15643. } else {
  15644. for ( ; i < length; ) {
  15645. if (callback.call(object[i], i, object[i++]) === false) {
  15646. break;
  15647. }
  15648. }
  15649. }
  15650. }
  15651. return object;
  15652. }
  15653. var _entityMap = {
  15654. "&": "&amp;",
  15655. "<": "&lt;",
  15656. ">": "&gt;",
  15657. '"': '&quot;',
  15658. "'": '&#39;',
  15659. "/": '&#x2F;'
  15660. };
  15661. function _escape(data) {
  15662. if (typeof data === 'string') {
  15663. return data.replace(/[&<>"'\/]/g, function (s) {
  15664. return _entityMap[s];
  15665. });
  15666. }else{
  15667. return data;
  15668. }
  15669. }
  15670. function _ajax(options) {
  15671. // v0.5.0 of https://github.com/goloroden/http.js
  15672. var getXhr = function (callback) {
  15673. // Use the native XHR object if the browser supports it.
  15674. if (window.XMLHttpRequest) {
  15675. return callback(null, new XMLHttpRequest());
  15676. } else if (window.ActiveXObject) {
  15677. // In Internet Explorer check for ActiveX versions of the XHR object.
  15678. try {
  15679. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  15680. } catch (e) {
  15681. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  15682. }
  15683. }
  15684. // If no XHR support was found, throw an error.
  15685. return callback(new Error());
  15686. };
  15687. var encodeUsingUrlEncoding = function (data) {
  15688. if(typeof data === 'string') {
  15689. return data;
  15690. }
  15691. var result = [];
  15692. for(var dataItem in data) {
  15693. if(data.hasOwnProperty(dataItem)) {
  15694. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  15695. }
  15696. }
  15697. return result.join('&');
  15698. };
  15699. var utf8 = function (text) {
  15700. text = text.replace(/\r\n/g, '\n');
  15701. var result = '';
  15702. for(var i = 0; i < text.length; i++) {
  15703. var c = text.charCodeAt(i);
  15704. if(c < 128) {
  15705. result += String.fromCharCode(c);
  15706. } else if((c > 127) && (c < 2048)) {
  15707. result += String.fromCharCode((c >> 6) | 192);
  15708. result += String.fromCharCode((c & 63) | 128);
  15709. } else {
  15710. result += String.fromCharCode((c >> 12) | 224);
  15711. result += String.fromCharCode(((c >> 6) & 63) | 128);
  15712. result += String.fromCharCode((c & 63) | 128);
  15713. }
  15714. }
  15715. return result;
  15716. };
  15717. var base64 = function (text) {
  15718. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15719. text = utf8(text);
  15720. var result = '',
  15721. chr1, chr2, chr3,
  15722. enc1, enc2, enc3, enc4,
  15723. i = 0;
  15724. do {
  15725. chr1 = text.charCodeAt(i++);
  15726. chr2 = text.charCodeAt(i++);
  15727. chr3 = text.charCodeAt(i++);
  15728. enc1 = chr1 >> 2;
  15729. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  15730. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  15731. enc4 = chr3 & 63;
  15732. if(isNaN(chr2)) {
  15733. enc3 = enc4 = 64;
  15734. } else if(isNaN(chr3)) {
  15735. enc4 = 64;
  15736. }
  15737. result +=
  15738. keyStr.charAt(enc1) +
  15739. keyStr.charAt(enc2) +
  15740. keyStr.charAt(enc3) +
  15741. keyStr.charAt(enc4);
  15742. chr1 = chr2 = chr3 = '';
  15743. enc1 = enc2 = enc3 = enc4 = '';
  15744. } while(i < text.length);
  15745. return result;
  15746. };
  15747. var mergeHeaders = function () {
  15748. // Use the first header object as base.
  15749. var result = arguments[0];
  15750. // Iterate through the remaining header objects and add them.
  15751. for(var i = 1; i < arguments.length; i++) {
  15752. var currentHeaders = arguments[i];
  15753. for(var header in currentHeaders) {
  15754. if(currentHeaders.hasOwnProperty(header)) {
  15755. result[header] = currentHeaders[header];
  15756. }
  15757. }
  15758. }
  15759. // Return the merged headers.
  15760. return result;
  15761. };
  15762. var ajax = function (method, url, options, callback) {
  15763. // Adjust parameters.
  15764. if(typeof options === 'function') {
  15765. callback = options;
  15766. options = {};
  15767. }
  15768. // Set default parameter values.
  15769. options.cache = options.cache || false;
  15770. options.data = options.data || {};
  15771. options.headers = options.headers || {};
  15772. options.jsonp = options.jsonp || false;
  15773. options.async = options.async === undefined ? true : options.async;
  15774. // Merge the various header objects.
  15775. var headers = mergeHeaders({
  15776. 'accept': '*/*',
  15777. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  15778. }, ajax.headers, options.headers);
  15779. // Encode the data according to the content-type.
  15780. var payload;
  15781. if (headers['content-type'] === 'application/json') {
  15782. payload = JSON.stringify(options.data);
  15783. } else {
  15784. payload = encodeUsingUrlEncoding(options.data);
  15785. }
  15786. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  15787. // if neccessary.
  15788. if(method === 'GET') {
  15789. // Setup the query string.
  15790. var queryString = [];
  15791. if(payload) {
  15792. queryString.push(payload);
  15793. payload = null;
  15794. }
  15795. // Handle caching.
  15796. if(!options.cache) {
  15797. queryString.push('_=' + (new Date()).getTime());
  15798. }
  15799. // If neccessary prepare the query string for a JSONP call.
  15800. if(options.jsonp) {
  15801. queryString.push('callback=' + options.jsonp);
  15802. queryString.push('jsonp=' + options.jsonp);
  15803. }
  15804. // Merge the query string and attach it to the url.
  15805. queryString = queryString.join('&');
  15806. if (queryString.length > 1) {
  15807. if (url.indexOf('?') > -1) {
  15808. url += '&' + queryString;
  15809. } else {
  15810. url += '?' + queryString;
  15811. }
  15812. }
  15813. // Make a JSONP call if neccessary.
  15814. if(options.jsonp) {
  15815. var head = document.getElementsByTagName('head')[0];
  15816. var script = document.createElement('script');
  15817. script.type = 'text/javascript';
  15818. script.src = url;
  15819. head.appendChild(script);
  15820. return;
  15821. }
  15822. }
  15823. // Since we got here, it is no JSONP request, so make a normal XHR request.
  15824. getXhr(function (err, xhr) {
  15825. if(err) return callback(err);
  15826. // Open the request.
  15827. xhr.open(method, url, options.async);
  15828. // Set the request headers.
  15829. for(var header in headers) {
  15830. if(headers.hasOwnProperty(header)) {
  15831. xhr.setRequestHeader(header, headers[header]);
  15832. }
  15833. }
  15834. // Handle the request events.
  15835. xhr.onreadystatechange = function () {
  15836. if(xhr.readyState === 4) {
  15837. var data = xhr.responseText || '';
  15838. // If no callback is given, return.
  15839. if(!callback) {
  15840. return;
  15841. }
  15842. // Return an object that provides access to the data as text and JSON.
  15843. callback(xhr.status, {
  15844. text: function () {
  15845. return data;
  15846. },
  15847. json: function () {
  15848. try {
  15849. return JSON.parse(data)
  15850. } catch (e) {
  15851. f.error('Can not parse JSON. URL: ' + url);
  15852. return {};
  15853. }
  15854. }
  15855. });
  15856. }
  15857. };
  15858. // Actually send the XHR request.
  15859. xhr.send(payload);
  15860. });
  15861. };
  15862. // Define the external interface.
  15863. var http = {
  15864. authBasic: function (username, password) {
  15865. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  15866. },
  15867. connect: function (url, options, callback) {
  15868. return ajax('CONNECT', url, options, callback);
  15869. },
  15870. del: function (url, options, callback) {
  15871. return ajax('DELETE', url, options, callback);
  15872. },
  15873. get: function (url, options, callback) {
  15874. return ajax('GET', url, options, callback);
  15875. },
  15876. head: function (url, options, callback) {
  15877. return ajax('HEAD', url, options, callback);
  15878. },
  15879. headers: function (headers) {
  15880. ajax.headers = headers || {};
  15881. },
  15882. isAllowed: function (url, verb, callback) {
  15883. this.options(url, function (status, data) {
  15884. callback(data.text().indexOf(verb) !== -1);
  15885. });
  15886. },
  15887. options: function (url, options, callback) {
  15888. return ajax('OPTIONS', url, options, callback);
  15889. },
  15890. patch: function (url, options, callback) {
  15891. return ajax('PATCH', url, options, callback);
  15892. },
  15893. post: function (url, options, callback) {
  15894. return ajax('POST', url, options, callback);
  15895. },
  15896. put: function (url, options, callback) {
  15897. return ajax('PUT', url, options, callback);
  15898. },
  15899. trace: function (url, options, callback) {
  15900. return ajax('TRACE', url, options, callback);
  15901. }
  15902. };
  15903. var methode = options.type ? options.type.toLowerCase() : 'get';
  15904. http[methode](options.url, options, function (status, data) {
  15905. // file: protocol always gives status code 0, so check for data
  15906. if (status === 200 || (status === 0 && data.text())) {
  15907. options.success(data.json(), status, null);
  15908. } else {
  15909. options.error(data.text(), status, null);
  15910. }
  15911. });
  15912. }
  15913. var _cookie = {
  15914. create: function(name,value,minutes,domain) {
  15915. var expires;
  15916. if (minutes) {
  15917. var date = new Date();
  15918. date.setTime(date.getTime()+(minutes*60*1000));
  15919. expires = "; expires="+date.toGMTString();
  15920. }
  15921. else expires = "";
  15922. domain = (domain)? "domain="+domain+";" : "";
  15923. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  15924. },
  15925. read: function(name) {
  15926. var nameEQ = name + "=";
  15927. var ca = document.cookie.split(';');
  15928. for(var i=0;i < ca.length;i++) {
  15929. var c = ca[i];
  15930. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  15931. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  15932. }
  15933. return null;
  15934. },
  15935. remove: function(name) {
  15936. this.create(name,"",-1);
  15937. }
  15938. };
  15939. var cookie_noop = {
  15940. create: function(name,value,minutes,domain) {},
  15941. read: function(name) { return null; },
  15942. remove: function(name) {}
  15943. };
  15944. // move dependent functions to a container so that
  15945. // they can be overriden easier in no jquery environment (node.js)
  15946. var f = {
  15947. extend: $ ? $.extend : _extend,
  15948. deepExtend: _deepExtend,
  15949. each: $ ? $.each : _each,
  15950. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  15951. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  15952. detectLanguage: detectLanguage,
  15953. escape: _escape,
  15954. log: function(str) {
  15955. if (o.debug && typeof console !== "undefined") console.log(str);
  15956. },
  15957. error: function(str) {
  15958. if (typeof console !== "undefined") console.error(str);
  15959. },
  15960. getCountyIndexOfLng: function(lng) {
  15961. var lng_index = 0;
  15962. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  15963. return lng_index;
  15964. },
  15965. toLanguages: function(lng) {
  15966. var log = this.log;
  15967. function applyCase(l) {
  15968. var ret = l;
  15969. if (typeof l === 'string' && l.indexOf('-') > -1) {
  15970. var parts = l.split('-');
  15971. ret = o.lowerCaseLng ?
  15972. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  15973. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  15974. } else {
  15975. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  15976. }
  15977. return ret;
  15978. }
  15979. var languages = [];
  15980. var whitelist = o.lngWhitelist || false;
  15981. var addLanguage = function(language){
  15982. //reject langs not whitelisted
  15983. if(!whitelist || whitelist.indexOf(language) > -1){
  15984. languages.push(language);
  15985. }else{
  15986. log('rejecting non-whitelisted language: ' + language);
  15987. }
  15988. };
  15989. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  15990. var parts = lng.split('-');
  15991. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  15992. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  15993. } else {
  15994. addLanguage(applyCase(lng));
  15995. }
  15996. for (var i = 0; i < o.fallbackLng.length; i++) {
  15997. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  15998. }
  15999. return languages;
  16000. },
  16001. regexEscape: function(str) {
  16002. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  16003. },
  16004. regexReplacementEscape: function(strOrFn) {
  16005. if (typeof strOrFn === 'string') {
  16006. return strOrFn.replace(/\$/g, "$$$$");
  16007. } else {
  16008. return strOrFn;
  16009. }
  16010. },
  16011. localStorage: {
  16012. setItem: function(key, value) {
  16013. if (window.localStorage) {
  16014. try {
  16015. window.localStorage.setItem(key, value);
  16016. } catch (e) {
  16017. f.log('failed to set value for key "' + key + '" to localStorage.');
  16018. }
  16019. }
  16020. }
  16021. }
  16022. };
  16023. function init(options, cb) {
  16024. if (typeof options === 'function') {
  16025. cb = options;
  16026. options = {};
  16027. }
  16028. options = options || {};
  16029. // override defaults with passed in options
  16030. f.extend(o, options);
  16031. delete o.fixLng; /* passed in each time */
  16032. // override functions: .log(), .detectLanguage(), etc
  16033. if (o.functions) {
  16034. delete o.functions;
  16035. f.extend(f, options.functions);
  16036. }
  16037. // create namespace object if namespace is passed in as string
  16038. if (typeof o.ns == 'string') {
  16039. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  16040. }
  16041. // fallback namespaces
  16042. if (typeof o.fallbackNS == 'string') {
  16043. o.fallbackNS = [o.fallbackNS];
  16044. }
  16045. // fallback languages
  16046. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  16047. o.fallbackLng = [o.fallbackLng];
  16048. }
  16049. // escape prefix/suffix
  16050. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  16051. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  16052. if (!o.lng) o.lng = f.detectLanguage();
  16053. languages = f.toLanguages(o.lng);
  16054. currentLng = languages[0];
  16055. f.log('currentLng set to: ' + currentLng);
  16056. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  16057. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  16058. }
  16059. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  16060. f.localStorage.setItem('i18next_lng', currentLng);
  16061. }
  16062. var lngTranslate = translate;
  16063. if (options.fixLng) {
  16064. lngTranslate = function(key, options) {
  16065. options = options || {};
  16066. options.lng = options.lng || lngTranslate.lng;
  16067. return translate(key, options);
  16068. };
  16069. lngTranslate.lng = currentLng;
  16070. }
  16071. pluralExtensions.setCurrentLng(currentLng);
  16072. // add JQuery extensions
  16073. if ($ && o.setJqueryExt) addJqueryFunct();
  16074. // jQuery deferred
  16075. var deferred;
  16076. if ($ && $.Deferred) {
  16077. deferred = $.Deferred();
  16078. }
  16079. // return immidiatly if res are passed in
  16080. if (o.resStore) {
  16081. resStore = o.resStore;
  16082. initialized = true;
  16083. if (cb) cb(lngTranslate);
  16084. if (deferred) deferred.resolve(lngTranslate);
  16085. if (deferred) return deferred.promise();
  16086. return;
  16087. }
  16088. // languages to load
  16089. var lngsToLoad = f.toLanguages(o.lng);
  16090. if (typeof o.preload === 'string') o.preload = [o.preload];
  16091. for (var i = 0, l = o.preload.length; i < l; i++) {
  16092. var pres = f.toLanguages(o.preload[i]);
  16093. for (var y = 0, len = pres.length; y < len; y++) {
  16094. if (lngsToLoad.indexOf(pres[y]) < 0) {
  16095. lngsToLoad.push(pres[y]);
  16096. }
  16097. }
  16098. }
  16099. // else load them
  16100. i18n.sync.load(lngsToLoad, o, function(err, store) {
  16101. resStore = store;
  16102. initialized = true;
  16103. if (cb) cb(lngTranslate);
  16104. if (deferred) deferred.resolve(lngTranslate);
  16105. });
  16106. if (deferred) return deferred.promise();
  16107. }
  16108. function preload(lngs, cb) {
  16109. if (typeof lngs === 'string') lngs = [lngs];
  16110. for (var i = 0, l = lngs.length; i < l; i++) {
  16111. if (o.preload.indexOf(lngs[i]) < 0) {
  16112. o.preload.push(lngs[i]);
  16113. }
  16114. }
  16115. return init(cb);
  16116. }
  16117. function addResourceBundle(lng, ns, resources, deep) {
  16118. if (typeof ns !== 'string') {
  16119. resources = ns;
  16120. ns = o.ns.defaultNs;
  16121. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  16122. o.ns.namespaces.push(ns);
  16123. }
  16124. resStore[lng] = resStore[lng] || {};
  16125. resStore[lng][ns] = resStore[lng][ns] || {};
  16126. if (deep) {
  16127. f.deepExtend(resStore[lng][ns], resources);
  16128. } else {
  16129. f.extend(resStore[lng][ns], resources);
  16130. }
  16131. }
  16132. function hasResourceBundle(lng, ns) {
  16133. if (typeof ns !== 'string') {
  16134. ns = o.ns.defaultNs;
  16135. }
  16136. resStore[lng] = resStore[lng] || {};
  16137. var res = resStore[lng][ns] || {};
  16138. var hasValues = false;
  16139. for(var prop in res) {
  16140. if (res.hasOwnProperty(prop)) {
  16141. hasValues = true;
  16142. }
  16143. }
  16144. return hasValues;
  16145. }
  16146. function removeResourceBundle(lng, ns) {
  16147. if (typeof ns !== 'string') {
  16148. ns = o.ns.defaultNs;
  16149. }
  16150. resStore[lng] = resStore[lng] || {};
  16151. resStore[lng][ns] = {};
  16152. }
  16153. function addResource(lng, ns, key, value) {
  16154. if (typeof ns !== 'string') {
  16155. resource = ns;
  16156. ns = o.ns.defaultNs;
  16157. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  16158. o.ns.namespaces.push(ns);
  16159. }
  16160. resStore[lng] = resStore[lng] || {};
  16161. resStore[lng][ns] = resStore[lng][ns] || {};
  16162. var keys = key.split(o.keyseparator);
  16163. var x = 0;
  16164. var node = resStore[lng][ns];
  16165. var origRef = node;
  16166. while (keys[x]) {
  16167. if (x == keys.length - 1)
  16168. node[keys[x]] = value;
  16169. else {
  16170. if (node[keys[x]] == null)
  16171. node[keys[x]] = {};
  16172. node = node[keys[x]];
  16173. }
  16174. x++;
  16175. }
  16176. }
  16177. function addResources(lng, ns, resources) {
  16178. if (typeof ns !== 'string') {
  16179. resource = ns;
  16180. ns = o.ns.defaultNs;
  16181. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  16182. o.ns.namespaces.push(ns);
  16183. }
  16184. for (var m in resources) {
  16185. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  16186. }
  16187. }
  16188. function setDefaultNamespace(ns) {
  16189. o.ns.defaultNs = ns;
  16190. }
  16191. function loadNamespace(namespace, cb) {
  16192. loadNamespaces([namespace], cb);
  16193. }
  16194. function loadNamespaces(namespaces, cb) {
  16195. var opts = {
  16196. dynamicLoad: o.dynamicLoad,
  16197. resGetPath: o.resGetPath,
  16198. getAsync: o.getAsync,
  16199. customLoad: o.customLoad,
  16200. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  16201. };
  16202. // languages to load
  16203. var lngsToLoad = f.toLanguages(o.lng);
  16204. if (typeof o.preload === 'string') o.preload = [o.preload];
  16205. for (var i = 0, l = o.preload.length; i < l; i++) {
  16206. var pres = f.toLanguages(o.preload[i]);
  16207. for (var y = 0, len = pres.length; y < len; y++) {
  16208. if (lngsToLoad.indexOf(pres[y]) < 0) {
  16209. lngsToLoad.push(pres[y]);
  16210. }
  16211. }
  16212. }
  16213. // check if we have to load
  16214. var lngNeedLoad = [];
  16215. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  16216. var needLoad = false;
  16217. var resSet = resStore[lngsToLoad[a]];
  16218. if (resSet) {
  16219. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  16220. if (!resSet[namespaces[b]]) needLoad = true;
  16221. }
  16222. } else {
  16223. needLoad = true;
  16224. }
  16225. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  16226. }
  16227. if (lngNeedLoad.length) {
  16228. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  16229. var todo = namespaces.length * lngNeedLoad.length;
  16230. // load each file individual
  16231. f.each(namespaces, function(nsIndex, nsValue) {
  16232. // append namespace to namespace array
  16233. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  16234. o.ns.namespaces.push(nsValue);
  16235. }
  16236. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  16237. resStore[lngValue] = resStore[lngValue] || {};
  16238. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  16239. todo--; // wait for all done befor callback
  16240. if (todo === 0 && cb) {
  16241. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  16242. cb();
  16243. }
  16244. });
  16245. });
  16246. });
  16247. } else {
  16248. if (cb) cb();
  16249. }
  16250. }
  16251. function setLng(lng, options, cb) {
  16252. if (typeof options === 'function') {
  16253. cb = options;
  16254. options = {};
  16255. } else if (!options) {
  16256. options = {};
  16257. }
  16258. options.lng = lng;
  16259. return init(options, cb);
  16260. }
  16261. function lng() {
  16262. return currentLng;
  16263. }
  16264. function reload(cb) {
  16265. resStore = {};
  16266. setLng(currentLng, cb);
  16267. }
  16268. function addJqueryFunct() {
  16269. // $.t shortcut
  16270. $.t = $.t || translate;
  16271. function parse(ele, key, options) {
  16272. if (key.length === 0) return;
  16273. var attr = 'text';
  16274. if (key.indexOf('[') === 0) {
  16275. var parts = key.split(']');
  16276. key = parts[1];
  16277. attr = parts[0].substr(1, parts[0].length-1);
  16278. }
  16279. if (key.indexOf(';') === key.length-1) {
  16280. key = key.substr(0, key.length-2);
  16281. }
  16282. var optionsToUse;
  16283. if (attr === 'html') {
  16284. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16285. ele.html($.t(key, optionsToUse));
  16286. } else if (attr === 'text') {
  16287. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  16288. ele.text($.t(key, optionsToUse));
  16289. } else if (attr === 'prepend') {
  16290. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16291. ele.prepend($.t(key, optionsToUse));
  16292. } else if (attr === 'append') {
  16293. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16294. ele.append($.t(key, optionsToUse));
  16295. } else if (attr.indexOf("data-") === 0) {
  16296. var dataAttr = attr.substr(("data-").length);
  16297. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  16298. var translated = $.t(key, optionsToUse);
  16299. //we change into the data cache
  16300. ele.data(dataAttr, translated);
  16301. //we change into the dom
  16302. ele.attr(attr, translated);
  16303. } else {
  16304. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  16305. ele.attr(attr, $.t(key, optionsToUse));
  16306. }
  16307. }
  16308. function localize(ele, options) {
  16309. var key = ele.attr(o.selectorAttr);
  16310. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  16311. if (!key) return;
  16312. var target = ele
  16313. , targetSelector = ele.data("i18n-target");
  16314. if (targetSelector) {
  16315. target = ele.find(targetSelector) || ele;
  16316. }
  16317. if (!options && o.useDataAttrOptions === true) {
  16318. options = ele.data("i18n-options");
  16319. }
  16320. options = options || {};
  16321. if (key.indexOf(';') >= 0) {
  16322. var keys = key.split(';');
  16323. $.each(keys, function(m, k) {
  16324. if (k !== '') parse(target, k, options);
  16325. });
  16326. } else {
  16327. parse(target, key, options);
  16328. }
  16329. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  16330. }
  16331. // fn
  16332. $.fn.i18n = function (options) {
  16333. return this.each(function() {
  16334. // localize element itself
  16335. localize($(this), options);
  16336. // localize childs
  16337. var elements = $(this).find('[' + o.selectorAttr + ']');
  16338. elements.each(function() {
  16339. localize($(this), options);
  16340. });
  16341. });
  16342. };
  16343. }
  16344. function applyReplacement(str, replacementHash, nestedKey, options) {
  16345. if (!str) return str;
  16346. options = options || replacementHash; // first call uses replacement hash combined with options
  16347. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  16348. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  16349. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  16350. , unEscapingSuffix = 'HTML'+suffix;
  16351. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  16352. f.each(hash, function(key, value) {
  16353. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  16354. if (typeof value === 'object' && value !== null) {
  16355. str = applyReplacement(str, value, nextKey, options);
  16356. } else {
  16357. if (options.escapeInterpolation || o.escapeInterpolation) {
  16358. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  16359. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  16360. } else {
  16361. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  16362. }
  16363. // str = options.escapeInterpolation;
  16364. }
  16365. });
  16366. return str;
  16367. }
  16368. // append it to functions
  16369. f.applyReplacement = applyReplacement;
  16370. function applyReuse(translated, options) {
  16371. var comma = ',';
  16372. var options_open = '{';
  16373. var options_close = '}';
  16374. var opts = f.extend({}, options);
  16375. delete opts.postProcess;
  16376. while (translated.indexOf(o.reusePrefix) != -1) {
  16377. replacementCounter++;
  16378. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  16379. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  16380. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  16381. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  16382. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  16383. if (index_of_end_of_closing <= index_of_opening) {
  16384. f.error('there is an missing closing in following translation value', translated);
  16385. return '';
  16386. }
  16387. if (token_without_symbols.indexOf(comma) != -1) {
  16388. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  16389. 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) {
  16390. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  16391. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  16392. try {
  16393. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  16394. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  16395. } catch (e) {
  16396. }
  16397. }
  16398. }
  16399. var translated_token = _translate(token_without_symbols, opts);
  16400. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  16401. }
  16402. return translated;
  16403. }
  16404. function hasContext(options) {
  16405. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  16406. }
  16407. function needsPlural(options, lng) {
  16408. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  16409. }
  16410. function needsIndefiniteArticle(options) {
  16411. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  16412. }
  16413. function exists(key, options) {
  16414. options = options || {};
  16415. var notFound = _getDefaultValue(key, options)
  16416. , found = _find(key, options);
  16417. return found !== undefined || found === notFound;
  16418. }
  16419. function translate(key, options) {
  16420. options = options || {};
  16421. if (!initialized) {
  16422. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  16423. return options.defaultValue || '';
  16424. };
  16425. replacementCounter = 0;
  16426. return _translate.apply(null, arguments);
  16427. }
  16428. function _getDefaultValue(key, options) {
  16429. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  16430. }
  16431. function _injectSprintfProcessor() {
  16432. var values = [];
  16433. // mh: build array from second argument onwards
  16434. for (var i = 1; i < arguments.length; i++) {
  16435. values.push(arguments[i]);
  16436. }
  16437. return {
  16438. postProcess: 'sprintf',
  16439. sprintf: values
  16440. };
  16441. }
  16442. function _translate(potentialKeys, options) {
  16443. if (options && typeof options !== 'object') {
  16444. if (o.shortcutFunction === 'sprintf') {
  16445. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  16446. options = _injectSprintfProcessor.apply(null, arguments);
  16447. } else if (o.shortcutFunction === 'defaultValue') {
  16448. options = {
  16449. defaultValue: options
  16450. }
  16451. }
  16452. } else {
  16453. options = options || {};
  16454. }
  16455. if (typeof o.defaultVariables === 'object') {
  16456. options = f.extend({}, o.defaultVariables, options);
  16457. }
  16458. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  16459. if (typeof potentialKeys === 'string') {
  16460. potentialKeys = [potentialKeys];
  16461. }
  16462. var key = potentialKeys[0];
  16463. if (potentialKeys.length > 1) {
  16464. for (var i = 0; i < potentialKeys.length; i++) {
  16465. key = potentialKeys[i];
  16466. if (exists(key, options)) {
  16467. break;
  16468. }
  16469. }
  16470. }
  16471. var notFound = _getDefaultValue(key, options)
  16472. , found = _find(key, options)
  16473. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  16474. , ns = options.ns || o.ns.defaultNs
  16475. , parts;
  16476. // split ns and key
  16477. if (key.indexOf(o.nsseparator) > -1) {
  16478. parts = key.split(o.nsseparator);
  16479. ns = parts[0];
  16480. key = parts[1];
  16481. }
  16482. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  16483. if (options.lng) {
  16484. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  16485. } else {
  16486. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  16487. }
  16488. }
  16489. var postProcessor = options.postProcess || o.postProcess;
  16490. if (found !== undefined && postProcessor) {
  16491. if (postProcessors[postProcessor]) {
  16492. found = postProcessors[postProcessor](found, key, options);
  16493. }
  16494. }
  16495. // process notFound if function exists
  16496. var splitNotFound = notFound;
  16497. if (notFound.indexOf(o.nsseparator) > -1) {
  16498. parts = notFound.split(o.nsseparator);
  16499. splitNotFound = parts[1];
  16500. }
  16501. if (splitNotFound === key && o.parseMissingKey) {
  16502. notFound = o.parseMissingKey(notFound);
  16503. }
  16504. if (found === undefined) {
  16505. notFound = applyReplacement(notFound, options);
  16506. notFound = applyReuse(notFound, options);
  16507. if (postProcessor && postProcessors[postProcessor]) {
  16508. var val = _getDefaultValue(key, options);
  16509. found = postProcessors[postProcessor](val, key, options);
  16510. }
  16511. }
  16512. return (found !== undefined) ? found : notFound;
  16513. }
  16514. function _find(key, options) {
  16515. options = options || {};
  16516. var optionWithoutCount, translated
  16517. , notFound = _getDefaultValue(key, options)
  16518. , lngs = languages;
  16519. if (!resStore) { return notFound; } // no resStore to translate from
  16520. // CI mode
  16521. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  16522. // passed in lng
  16523. if (options.lngs) lngs = options.lngs;
  16524. if (options.lng) {
  16525. lngs = f.toLanguages(options.lng, options.fallbackLng);
  16526. if (!resStore[lngs[0]]) {
  16527. var oldAsync = o.getAsync;
  16528. o.getAsync = false;
  16529. i18n.sync.load(lngs, o, function(err, store) {
  16530. f.extend(resStore, store);
  16531. o.getAsync = oldAsync;
  16532. });
  16533. }
  16534. }
  16535. var ns = options.ns || o.ns.defaultNs;
  16536. if (key.indexOf(o.nsseparator) > -1) {
  16537. var parts = key.split(o.nsseparator);
  16538. ns = parts[0];
  16539. key = parts[1];
  16540. }
  16541. if (hasContext(options)) {
  16542. optionWithoutCount = f.extend({}, options);
  16543. delete optionWithoutCount.context;
  16544. optionWithoutCount.defaultValue = o.contextNotFound;
  16545. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  16546. translated = translate(contextKey, optionWithoutCount);
  16547. if (translated != o.contextNotFound) {
  16548. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  16549. } // else continue translation with original/nonContext key
  16550. }
  16551. if (needsPlural(options, lngs[0])) {
  16552. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  16553. delete optionWithoutCount.count;
  16554. delete optionWithoutCount.lng;
  16555. optionWithoutCount.defaultValue = o.pluralNotFound;
  16556. var pluralKey;
  16557. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  16558. pluralKey = ns + o.nsseparator + key;
  16559. } else {
  16560. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  16561. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  16562. if (pluralExtension >= 0) {
  16563. pluralKey = pluralKey + '_' + pluralExtension;
  16564. } else if (pluralExtension === 1) {
  16565. pluralKey = ns + o.nsseparator + key; // singular
  16566. }
  16567. }
  16568. translated = translate(pluralKey, optionWithoutCount);
  16569. if (translated != o.pluralNotFound) {
  16570. return applyReplacement(translated, {
  16571. count: options.count,
  16572. interpolationPrefix: options.interpolationPrefix,
  16573. interpolationSuffix: options.interpolationSuffix
  16574. }); // apply replacement for count only
  16575. } else if (lngs.length > 1) {
  16576. // remove failed lng
  16577. var clone = lngs.slice();
  16578. clone.shift();
  16579. options = f.extend(options, { lngs: clone });
  16580. delete options.lng;
  16581. // retry with fallbacks
  16582. translated = translate(ns + o.nsseparator + key, options);
  16583. if (translated != o.pluralNotFound) return translated;
  16584. } else {
  16585. return translated;
  16586. }
  16587. }
  16588. if (needsIndefiniteArticle(options)) {
  16589. var optionsWithoutIndef = f.extend({}, options);
  16590. delete optionsWithoutIndef.indefinite_article;
  16591. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  16592. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  16593. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  16594. translated = translate(indefiniteKey, optionsWithoutIndef);
  16595. if (translated != o.indefiniteNotFound) {
  16596. return translated;
  16597. }
  16598. }
  16599. var found;
  16600. var keys = key.split(o.keyseparator);
  16601. for (var i = 0, len = lngs.length; i < len; i++ ) {
  16602. if (found !== undefined) break;
  16603. var l = lngs[i];
  16604. var x = 0;
  16605. var value = resStore[l] && resStore[l][ns];
  16606. while (keys[x]) {
  16607. value = value && value[keys[x]];
  16608. x++;
  16609. }
  16610. if (value !== undefined) {
  16611. var valueType = Object.prototype.toString.apply(value);
  16612. if (typeof value === 'string') {
  16613. value = applyReplacement(value, options);
  16614. value = applyReuse(value, options);
  16615. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  16616. value = value.join('\n');
  16617. value = applyReplacement(value, options);
  16618. value = applyReuse(value, options);
  16619. } else if (value === null && o.fallbackOnNull === true) {
  16620. value = undefined;
  16621. } else if (value !== null) {
  16622. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  16623. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  16624. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  16625. } else {
  16626. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  16627. 'returned an object instead of string.';
  16628. f.log(value);
  16629. }
  16630. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  16631. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  16632. f.each(value, function(m) {
  16633. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  16634. });
  16635. value = copy;
  16636. }
  16637. }
  16638. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  16639. value = undefined;
  16640. found = value;
  16641. }
  16642. }
  16643. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  16644. // set flag for fallback lookup - avoid recursion
  16645. options.isFallbackLookup = true;
  16646. if (o.fallbackNS.length) {
  16647. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  16648. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  16649. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  16650. /* compare value without namespace */
  16651. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  16652. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  16653. if (foundValue !== notFoundValue) break;
  16654. }
  16655. }
  16656. } else {
  16657. found = _find(key, options); // fallback to default NS
  16658. }
  16659. options.isFallbackLookup = false;
  16660. }
  16661. return found;
  16662. }
  16663. function detectLanguage() {
  16664. var detectedLng;
  16665. var whitelist = o.lngWhitelist || [];
  16666. var userLngChoices = [];
  16667. // get from qs
  16668. var qsParm = [];
  16669. if (typeof window !== 'undefined') {
  16670. (function() {
  16671. var query = window.location.search.substring(1);
  16672. var params = query.split('&');
  16673. for (var i=0; i<params.length; i++) {
  16674. var pos = params[i].indexOf('=');
  16675. if (pos > 0) {
  16676. var key = params[i].substring(0,pos);
  16677. if (key == o.detectLngQS) {
  16678. userLngChoices.push(params[i].substring(pos+1));
  16679. }
  16680. }
  16681. }
  16682. })();
  16683. }
  16684. // get from cookie
  16685. if (o.useCookie && typeof document !== 'undefined') {
  16686. var c = f.cookie.read(o.cookieName);
  16687. if (c) userLngChoices.push(c);
  16688. }
  16689. // get from localStorage
  16690. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  16691. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  16692. }
  16693. // get from navigator
  16694. if (typeof navigator !== 'undefined') {
  16695. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  16696. for (var i=0;i<navigator.languages.length;i++) {
  16697. userLngChoices.push(navigator.languages[i]);
  16698. }
  16699. }
  16700. if (navigator.userLanguage) {
  16701. userLngChoices.push(navigator.userLanguage);
  16702. }
  16703. if (navigator.language) {
  16704. userLngChoices.push(navigator.language);
  16705. }
  16706. }
  16707. (function() {
  16708. for (var i=0;i<userLngChoices.length;i++) {
  16709. var lng = userLngChoices[i];
  16710. if (lng.indexOf('-') > -1) {
  16711. var parts = lng.split('-');
  16712. lng = o.lowerCaseLng ?
  16713. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  16714. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  16715. }
  16716. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  16717. detectedLng = lng;
  16718. break;
  16719. }
  16720. }
  16721. })();
  16722. //fallback
  16723. if (!detectedLng){
  16724. detectedLng = o.fallbackLng[0];
  16725. }
  16726. return detectedLng;
  16727. }
  16728. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  16729. /* [code, name, numbers, pluralsType] */
  16730. var _rules = [
  16731. ["ach", "Acholi", [1,2], 1],
  16732. ["af", "Afrikaans",[1,2], 2],
  16733. ["ak", "Akan", [1,2], 1],
  16734. ["am", "Amharic", [1,2], 1],
  16735. ["an", "Aragonese",[1,2], 2],
  16736. ["ar", "Arabic", [0,1,2,3,11,100],5],
  16737. ["arn", "Mapudungun",[1,2], 1],
  16738. ["ast", "Asturian", [1,2], 2],
  16739. ["ay", "Aymará", [1], 3],
  16740. ["az", "Azerbaijani",[1,2],2],
  16741. ["be", "Belarusian",[1,2,5],4],
  16742. ["bg", "Bulgarian",[1,2], 2],
  16743. ["bn", "Bengali", [1,2], 2],
  16744. ["bo", "Tibetan", [1], 3],
  16745. ["br", "Breton", [1,2], 1],
  16746. ["bs", "Bosnian", [1,2,5],4],
  16747. ["ca", "Catalan", [1,2], 2],
  16748. ["cgg", "Chiga", [1], 3],
  16749. ["cs", "Czech", [1,2,5],6],
  16750. ["csb", "Kashubian",[1,2,5],7],
  16751. ["cy", "Welsh", [1,2,3,8],8],
  16752. ["da", "Danish", [1,2], 2],
  16753. ["de", "German", [1,2], 2],
  16754. ["dev", "Development Fallback", [1,2], 2],
  16755. ["dz", "Dzongkha", [1], 3],
  16756. ["el", "Greek", [1,2], 2],
  16757. ["en", "English", [1,2], 2],
  16758. ["eo", "Esperanto",[1,2], 2],
  16759. ["es", "Spanish", [1,2], 2],
  16760. ["es_ar","Argentinean Spanish", [1,2], 2],
  16761. ["et", "Estonian", [1,2], 2],
  16762. ["eu", "Basque", [1,2], 2],
  16763. ["fa", "Persian", [1], 3],
  16764. ["fi", "Finnish", [1,2], 2],
  16765. ["fil", "Filipino", [1,2], 1],
  16766. ["fo", "Faroese", [1,2], 2],
  16767. ["fr", "French", [1,2], 9],
  16768. ["fur", "Friulian", [1,2], 2],
  16769. ["fy", "Frisian", [1,2], 2],
  16770. ["ga", "Irish", [1,2,3,7,11],10],
  16771. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  16772. ["gl", "Galician", [1,2], 2],
  16773. ["gu", "Gujarati", [1,2], 2],
  16774. ["gun", "Gun", [1,2], 1],
  16775. ["ha", "Hausa", [1,2], 2],
  16776. ["he", "Hebrew", [1,2], 2],
  16777. ["hi", "Hindi", [1,2], 2],
  16778. ["hr", "Croatian", [1,2,5],4],
  16779. ["hu", "Hungarian",[1,2], 2],
  16780. ["hy", "Armenian", [1,2], 2],
  16781. ["ia", "Interlingua",[1,2],2],
  16782. ["id", "Indonesian",[1], 3],
  16783. ["is", "Icelandic",[1,2], 12],
  16784. ["it", "Italian", [1,2], 2],
  16785. ["ja", "Japanese", [1], 3],
  16786. ["jbo", "Lojban", [1], 3],
  16787. ["jv", "Javanese", [0,1], 13],
  16788. ["ka", "Georgian", [1], 3],
  16789. ["kk", "Kazakh", [1], 3],
  16790. ["km", "Khmer", [1], 3],
  16791. ["kn", "Kannada", [1,2], 2],
  16792. ["ko", "Korean", [1], 3],
  16793. ["ku", "Kurdish", [1,2], 2],
  16794. ["kw", "Cornish", [1,2,3,4],14],
  16795. ["ky", "Kyrgyz", [1], 3],
  16796. ["lb", "Letzeburgesch",[1,2],2],
  16797. ["ln", "Lingala", [1,2], 1],
  16798. ["lo", "Lao", [1], 3],
  16799. ["lt", "Lithuanian",[1,2,10],15],
  16800. ["lv", "Latvian", [1,2,0],16],
  16801. ["mai", "Maithili", [1,2], 2],
  16802. ["mfe", "Mauritian Creole",[1,2],1],
  16803. ["mg", "Malagasy", [1,2], 1],
  16804. ["mi", "Maori", [1,2], 1],
  16805. ["mk", "Macedonian",[1,2],17],
  16806. ["ml", "Malayalam",[1,2], 2],
  16807. ["mn", "Mongolian",[1,2], 2],
  16808. ["mnk", "Mandinka", [0,1,2],18],
  16809. ["mr", "Marathi", [1,2], 2],
  16810. ["ms", "Malay", [1], 3],
  16811. ["mt", "Maltese", [1,2,11,20],19],
  16812. ["nah", "Nahuatl", [1,2], 2],
  16813. ["nap", "Neapolitan",[1,2], 2],
  16814. ["nb", "Norwegian Bokmal",[1,2],2],
  16815. ["ne", "Nepali", [1,2], 2],
  16816. ["nl", "Dutch", [1,2], 2],
  16817. ["nn", "Norwegian Nynorsk",[1,2],2],
  16818. ["no", "Norwegian",[1,2], 2],
  16819. ["nso", "Northern Sotho",[1,2],2],
  16820. ["oc", "Occitan", [1,2], 1],
  16821. ["or", "Oriya", [2,1], 2],
  16822. ["pa", "Punjabi", [1,2], 2],
  16823. ["pap", "Papiamento",[1,2], 2],
  16824. ["pl", "Polish", [1,2,5],7],
  16825. ["pms", "Piemontese",[1,2], 2],
  16826. ["ps", "Pashto", [1,2], 2],
  16827. ["pt", "Portuguese",[1,2], 2],
  16828. ["pt_br","Brazilian Portuguese",[1,2], 2],
  16829. ["rm", "Romansh", [1,2], 2],
  16830. ["ro", "Romanian", [1,2,20],20],
  16831. ["ru", "Russian", [1,2,5],4],
  16832. ["sah", "Yakut", [1], 3],
  16833. ["sco", "Scots", [1,2], 2],
  16834. ["se", "Northern Sami",[1,2], 2],
  16835. ["si", "Sinhala", [1,2], 2],
  16836. ["sk", "Slovak", [1,2,5],6],
  16837. ["sl", "Slovenian",[5,1,2,3],21],
  16838. ["so", "Somali", [1,2], 2],
  16839. ["son", "Songhay", [1,2], 2],
  16840. ["sq", "Albanian", [1,2], 2],
  16841. ["sr", "Serbian", [1,2,5],4],
  16842. ["su", "Sundanese",[1], 3],
  16843. ["sv", "Swedish", [1,2], 2],
  16844. ["sw", "Swahili", [1,2], 2],
  16845. ["ta", "Tamil", [1,2], 2],
  16846. ["te", "Telugu", [1,2], 2],
  16847. ["tg", "Tajik", [1,2], 1],
  16848. ["th", "Thai", [1], 3],
  16849. ["ti", "Tigrinya", [1,2], 1],
  16850. ["tk", "Turkmen", [1,2], 2],
  16851. ["tr", "Turkish", [1,2], 1],
  16852. ["tt", "Tatar", [1], 3],
  16853. ["ug", "Uyghur", [1], 3],
  16854. ["uk", "Ukrainian",[1,2,5],4],
  16855. ["ur", "Urdu", [1,2], 2],
  16856. ["uz", "Uzbek", [1,2], 1],
  16857. ["vi", "Vietnamese",[1], 3],
  16858. ["wa", "Walloon", [1,2], 1],
  16859. ["wo", "Wolof", [1], 3],
  16860. ["yo", "Yoruba", [1,2], 2],
  16861. ["zh", "Chinese", [1], 3]
  16862. ];
  16863. var _rulesPluralsTypes = {
  16864. 1: function(n) {return Number(n > 1);},
  16865. 2: function(n) {return Number(n != 1);},
  16866. 3: function(n) {return 0;},
  16867. 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);},
  16868. 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);},
  16869. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  16870. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16871. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  16872. 9: function(n) {return Number(n >= 2);},
  16873. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  16874. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  16875. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  16876. 13: function(n) {return Number(n !== 0);},
  16877. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  16878. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16879. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  16880. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  16881. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  16882. 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);},
  16883. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  16884. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  16885. };
  16886. var pluralExtensions = {
  16887. rules: (function () {
  16888. var l, rules = {};
  16889. for (l=_rules.length; l-- ;) {
  16890. rules[_rules[l][0]] = {
  16891. name: _rules[l][1],
  16892. numbers: _rules[l][2],
  16893. plurals: _rulesPluralsTypes[_rules[l][3]]
  16894. }
  16895. }
  16896. return rules;
  16897. }()),
  16898. // you can add your own pluralExtensions
  16899. addRule: function(lng, obj) {
  16900. pluralExtensions.rules[lng] = obj;
  16901. },
  16902. setCurrentLng: function(lng) {
  16903. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  16904. var parts = lng.split('-');
  16905. pluralExtensions.currentRule = {
  16906. lng: lng,
  16907. rule: pluralExtensions.rules[parts[0]]
  16908. };
  16909. }
  16910. },
  16911. needsPlural: function(lng, count) {
  16912. var parts = lng.split('-');
  16913. var ext;
  16914. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16915. ext = pluralExtensions.currentRule.rule;
  16916. } else {
  16917. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  16918. }
  16919. if (ext && ext.numbers.length <= 1) {
  16920. return false;
  16921. } else {
  16922. return this.get(lng, count) !== 1;
  16923. }
  16924. },
  16925. get: function(lng, count) {
  16926. var parts = lng.split('-');
  16927. function getResult(l, c) {
  16928. var ext;
  16929. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16930. ext = pluralExtensions.currentRule.rule;
  16931. } else {
  16932. ext = pluralExtensions.rules[l];
  16933. }
  16934. if (ext) {
  16935. var i;
  16936. if (ext.noAbs) {
  16937. i = ext.plurals(c);
  16938. } else {
  16939. i = ext.plurals(Math.abs(c));
  16940. }
  16941. var number = ext.numbers[i];
  16942. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  16943. if (number === 2) {
  16944. number = -1; // regular plural
  16945. } else if (number === 1) {
  16946. number = 1; // singular
  16947. }
  16948. }//console.log(count + '-' + number);
  16949. return number;
  16950. } else {
  16951. return c === 1 ? '1' : '-1';
  16952. }
  16953. }
  16954. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  16955. }
  16956. };
  16957. var postProcessors = {};
  16958. var addPostProcessor = function(name, fc) {
  16959. postProcessors[name] = fc;
  16960. };
  16961. // sprintf support
  16962. var sprintf = (function() {
  16963. function get_type(variable) {
  16964. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  16965. }
  16966. function str_repeat(input, multiplier) {
  16967. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  16968. return output.join('');
  16969. }
  16970. var str_format = function() {
  16971. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  16972. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  16973. }
  16974. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  16975. };
  16976. str_format.format = function(parse_tree, argv) {
  16977. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  16978. for (i = 0; i < tree_length; i++) {
  16979. node_type = get_type(parse_tree[i]);
  16980. if (node_type === 'string') {
  16981. output.push(parse_tree[i]);
  16982. }
  16983. else if (node_type === 'array') {
  16984. match = parse_tree[i]; // convenience purposes only
  16985. if (match[2]) { // keyword argument
  16986. arg = argv[cursor];
  16987. for (k = 0; k < match[2].length; k++) {
  16988. if (!arg.hasOwnProperty(match[2][k])) {
  16989. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  16990. }
  16991. arg = arg[match[2][k]];
  16992. }
  16993. }
  16994. else if (match[1]) { // positional argument (explicit)
  16995. arg = argv[match[1]];
  16996. }
  16997. else { // positional argument (implicit)
  16998. arg = argv[cursor++];
  16999. }
  17000. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  17001. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  17002. }
  17003. switch (match[8]) {
  17004. case 'b': arg = arg.toString(2); break;
  17005. case 'c': arg = String.fromCharCode(arg); break;
  17006. case 'd': arg = parseInt(arg, 10); break;
  17007. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  17008. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  17009. case 'o': arg = arg.toString(8); break;
  17010. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  17011. case 'u': arg = Math.abs(arg); break;
  17012. case 'x': arg = arg.toString(16); break;
  17013. case 'X': arg = arg.toString(16).toUpperCase(); break;
  17014. }
  17015. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  17016. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  17017. pad_length = match[6] - String(arg).length;
  17018. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  17019. output.push(match[5] ? arg + pad : pad + arg);
  17020. }
  17021. }
  17022. return output.join('');
  17023. };
  17024. str_format.cache = {};
  17025. str_format.parse = function(fmt) {
  17026. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  17027. while (_fmt) {
  17028. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  17029. parse_tree.push(match[0]);
  17030. }
  17031. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  17032. parse_tree.push('%');
  17033. }
  17034. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  17035. if (match[2]) {
  17036. arg_names |= 1;
  17037. var field_list = [], replacement_field = match[2], field_match = [];
  17038. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  17039. field_list.push(field_match[1]);
  17040. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  17041. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  17042. field_list.push(field_match[1]);
  17043. }
  17044. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  17045. field_list.push(field_match[1]);
  17046. }
  17047. else {
  17048. throw('[sprintf] huh?');
  17049. }
  17050. }
  17051. }
  17052. else {
  17053. throw('[sprintf] huh?');
  17054. }
  17055. match[2] = field_list;
  17056. }
  17057. else {
  17058. arg_names |= 2;
  17059. }
  17060. if (arg_names === 3) {
  17061. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  17062. }
  17063. parse_tree.push(match);
  17064. }
  17065. else {
  17066. throw('[sprintf] huh?');
  17067. }
  17068. _fmt = _fmt.substring(match[0].length);
  17069. }
  17070. return parse_tree;
  17071. };
  17072. return str_format;
  17073. })();
  17074. var vsprintf = function(fmt, argv) {
  17075. argv.unshift(fmt);
  17076. return sprintf.apply(null, argv);
  17077. };
  17078. addPostProcessor("sprintf", function(val, key, opts) {
  17079. if (!opts.sprintf) return val;
  17080. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  17081. return vsprintf(val, opts.sprintf);
  17082. } else if (typeof opts.sprintf === 'object') {
  17083. return sprintf(val, opts.sprintf);
  17084. }
  17085. return val;
  17086. });
  17087. // public api interface
  17088. i18n.init = init;
  17089. i18n.setLng = setLng;
  17090. i18n.preload = preload;
  17091. i18n.addResourceBundle = addResourceBundle;
  17092. i18n.hasResourceBundle = hasResourceBundle;
  17093. i18n.addResource = addResource;
  17094. i18n.addResources = addResources;
  17095. i18n.removeResourceBundle = removeResourceBundle;
  17096. i18n.loadNamespace = loadNamespace;
  17097. i18n.loadNamespaces = loadNamespaces;
  17098. i18n.setDefaultNamespace = setDefaultNamespace;
  17099. i18n.t = translate;
  17100. i18n.translate = translate;
  17101. i18n.exists = exists;
  17102. i18n.detectLanguage = f.detectLanguage;
  17103. i18n.pluralExtensions = pluralExtensions;
  17104. i18n.sync = sync;
  17105. i18n.functions = f;
  17106. i18n.lng = lng;
  17107. i18n.addPostProcessor = addPostProcessor;
  17108. i18n.options = o;
  17109. })();
  17110. },{"jquery":"jquery"}],63:[function(require,module,exports){
  17111. // Top level file is just a mixin of submodules & constants
  17112. 'use strict';
  17113. var assign = require('./lib/utils/common').assign;
  17114. var deflate = require('./lib/deflate');
  17115. var inflate = require('./lib/inflate');
  17116. var constants = require('./lib/zlib/constants');
  17117. var pako = {};
  17118. assign(pako, deflate, inflate, constants);
  17119. module.exports = pako;
  17120. },{"./lib/deflate":64,"./lib/inflate":65,"./lib/utils/common":66,"./lib/zlib/constants":69}],64:[function(require,module,exports){
  17121. 'use strict';
  17122. var zlib_deflate = require('./zlib/deflate.js');
  17123. var utils = require('./utils/common');
  17124. var strings = require('./utils/strings');
  17125. var msg = require('./zlib/messages');
  17126. var zstream = require('./zlib/zstream');
  17127. var toString = Object.prototype.toString;
  17128. /* Public constants ==========================================================*/
  17129. /* ===========================================================================*/
  17130. var Z_NO_FLUSH = 0;
  17131. var Z_FINISH = 4;
  17132. var Z_OK = 0;
  17133. var Z_STREAM_END = 1;
  17134. var Z_DEFAULT_COMPRESSION = -1;
  17135. var Z_DEFAULT_STRATEGY = 0;
  17136. var Z_DEFLATED = 8;
  17137. /* ===========================================================================*/
  17138. /**
  17139. * class Deflate
  17140. *
  17141. * Generic JS-style wrapper for zlib calls. If you don't need
  17142. * streaming behaviour - use more simple functions: [[deflate]],
  17143. * [[deflateRaw]] and [[gzip]].
  17144. **/
  17145. /* internal
  17146. * Deflate.chunks -> Array
  17147. *
  17148. * Chunks of output data, if [[Deflate#onData]] not overriden.
  17149. **/
  17150. /**
  17151. * Deflate.result -> Uint8Array|Array
  17152. *
  17153. * Compressed result, generated by default [[Deflate#onData]]
  17154. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  17155. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  17156. **/
  17157. /**
  17158. * Deflate.err -> Number
  17159. *
  17160. * Error code after deflate finished. 0 (Z_OK) on success.
  17161. * You will not need it in real life, because deflate errors
  17162. * are possible only on wrong options or bad `onData` / `onEnd`
  17163. * custom handlers.
  17164. **/
  17165. /**
  17166. * Deflate.msg -> String
  17167. *
  17168. * Error message, if [[Deflate.err]] != 0
  17169. **/
  17170. /**
  17171. * new Deflate(options)
  17172. * - options (Object): zlib deflate options.
  17173. *
  17174. * Creates new deflator instance with specified params. Throws exception
  17175. * on bad params. Supported options:
  17176. *
  17177. * - `level`
  17178. * - `windowBits`
  17179. * - `memLevel`
  17180. * - `strategy`
  17181. *
  17182. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17183. * for more information on these.
  17184. *
  17185. * Additional options, for internal needs:
  17186. *
  17187. * - `chunkSize` - size of generated data chunks (16K by default)
  17188. * - `raw` (Boolean) - do raw deflate
  17189. * - `gzip` (Boolean) - create gzip wrapper
  17190. * - `to` (String) - if equal to 'string', then result will be "binary string"
  17191. * (each char code [0..255])
  17192. * - `header` (Object) - custom header for gzip
  17193. * - `text` (Boolean) - true if compressed data believed to be text
  17194. * - `time` (Number) - modification time, unix timestamp
  17195. * - `os` (Number) - operation system code
  17196. * - `extra` (Array) - array of bytes with extra data (max 65536)
  17197. * - `name` (String) - file name (binary string)
  17198. * - `comment` (String) - comment (binary string)
  17199. * - `hcrc` (Boolean) - true if header crc should be added
  17200. *
  17201. * ##### Example:
  17202. *
  17203. * ```javascript
  17204. * var pako = require('pako')
  17205. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17206. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17207. *
  17208. * var deflate = new pako.Deflate({ level: 3});
  17209. *
  17210. * deflate.push(chunk1, false);
  17211. * deflate.push(chunk2, true); // true -> last chunk
  17212. *
  17213. * if (deflate.err) { throw new Error(deflate.err); }
  17214. *
  17215. * console.log(deflate.result);
  17216. * ```
  17217. **/
  17218. var Deflate = function(options) {
  17219. this.options = utils.assign({
  17220. level: Z_DEFAULT_COMPRESSION,
  17221. method: Z_DEFLATED,
  17222. chunkSize: 16384,
  17223. windowBits: 15,
  17224. memLevel: 8,
  17225. strategy: Z_DEFAULT_STRATEGY,
  17226. to: ''
  17227. }, options || {});
  17228. var opt = this.options;
  17229. if (opt.raw && (opt.windowBits > 0)) {
  17230. opt.windowBits = -opt.windowBits;
  17231. }
  17232. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  17233. opt.windowBits += 16;
  17234. }
  17235. this.err = 0; // error code, if happens (0 = Z_OK)
  17236. this.msg = ''; // error message
  17237. this.ended = false; // used to avoid multiple onEnd() calls
  17238. this.chunks = []; // chunks of compressed data
  17239. this.strm = new zstream();
  17240. this.strm.avail_out = 0;
  17241. var status = zlib_deflate.deflateInit2(
  17242. this.strm,
  17243. opt.level,
  17244. opt.method,
  17245. opt.windowBits,
  17246. opt.memLevel,
  17247. opt.strategy
  17248. );
  17249. if (status !== Z_OK) {
  17250. throw new Error(msg[status]);
  17251. }
  17252. if (opt.header) {
  17253. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  17254. }
  17255. };
  17256. /**
  17257. * Deflate#push(data[, mode]) -> Boolean
  17258. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  17259. * converted to utf8 byte sequence.
  17260. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17261. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17262. *
  17263. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  17264. * new compressed chunks. Returns `true` on success. The last data block must have
  17265. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17266. * [[Deflate#onEnd]].
  17267. *
  17268. * On fail call [[Deflate#onEnd]] with error code and return false.
  17269. *
  17270. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17271. * array format is detected automatically). Also, don't skip last param and always
  17272. * use the same type in your code (boolean or number). That will improve JS speed.
  17273. *
  17274. * For regular `Array`-s make sure all elements are [0..255].
  17275. *
  17276. * ##### Example
  17277. *
  17278. * ```javascript
  17279. * push(chunk, false); // push one of data chunks
  17280. * ...
  17281. * push(chunk, true); // push last chunk
  17282. * ```
  17283. **/
  17284. Deflate.prototype.push = function(data, mode) {
  17285. var strm = this.strm;
  17286. var chunkSize = this.options.chunkSize;
  17287. var status, _mode;
  17288. if (this.ended) { return false; }
  17289. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  17290. // Convert data if needed
  17291. if (typeof data === 'string') {
  17292. // If we need to compress text, change encoding to utf8.
  17293. strm.input = strings.string2buf(data);
  17294. } else if (toString.call(data) === '[object ArrayBuffer]') {
  17295. strm.input = new Uint8Array(data);
  17296. } else {
  17297. strm.input = data;
  17298. }
  17299. strm.next_in = 0;
  17300. strm.avail_in = strm.input.length;
  17301. do {
  17302. if (strm.avail_out === 0) {
  17303. strm.output = new utils.Buf8(chunkSize);
  17304. strm.next_out = 0;
  17305. strm.avail_out = chunkSize;
  17306. }
  17307. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  17308. if (status !== Z_STREAM_END && status !== Z_OK) {
  17309. this.onEnd(status);
  17310. this.ended = true;
  17311. return false;
  17312. }
  17313. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  17314. if (this.options.to === 'string') {
  17315. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  17316. } else {
  17317. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17318. }
  17319. }
  17320. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  17321. // Finalize on the last chunk.
  17322. if (_mode === Z_FINISH) {
  17323. status = zlib_deflate.deflateEnd(this.strm);
  17324. this.onEnd(status);
  17325. this.ended = true;
  17326. return status === Z_OK;
  17327. }
  17328. return true;
  17329. };
  17330. /**
  17331. * Deflate#onData(chunk) -> Void
  17332. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17333. * on js engine support. When string output requested, each chunk
  17334. * will be string.
  17335. *
  17336. * By default, stores data blocks in `chunks[]` property and glue
  17337. * those in `onEnd`. Override this handler, if you need another behaviour.
  17338. **/
  17339. Deflate.prototype.onData = function(chunk) {
  17340. this.chunks.push(chunk);
  17341. };
  17342. /**
  17343. * Deflate#onEnd(status) -> Void
  17344. * - status (Number): deflate status. 0 (Z_OK) on success,
  17345. * other if not.
  17346. *
  17347. * Called once after you tell deflate that input stream complete
  17348. * or error happenned. By default - join collected chunks,
  17349. * free memory and fill `results` / `err` properties.
  17350. **/
  17351. Deflate.prototype.onEnd = function(status) {
  17352. // On success - join
  17353. if (status === Z_OK) {
  17354. if (this.options.to === 'string') {
  17355. this.result = this.chunks.join('');
  17356. } else {
  17357. this.result = utils.flattenChunks(this.chunks);
  17358. }
  17359. }
  17360. this.chunks = [];
  17361. this.err = status;
  17362. this.msg = this.strm.msg;
  17363. };
  17364. /**
  17365. * deflate(data[, options]) -> Uint8Array|Array|String
  17366. * - data (Uint8Array|Array|String): input data to compress.
  17367. * - options (Object): zlib deflate options.
  17368. *
  17369. * Compress `data` with deflate alrorythm and `options`.
  17370. *
  17371. * Supported options are:
  17372. *
  17373. * - level
  17374. * - windowBits
  17375. * - memLevel
  17376. * - strategy
  17377. *
  17378. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17379. * for more information on these.
  17380. *
  17381. * Sugar (options):
  17382. *
  17383. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17384. * negative windowBits implicitly.
  17385. * - `to` (String) - if equal to 'string', then result will be "binary string"
  17386. * (each char code [0..255])
  17387. *
  17388. * ##### Example:
  17389. *
  17390. * ```javascript
  17391. * var pako = require('pako')
  17392. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  17393. *
  17394. * console.log(pako.deflate(data));
  17395. * ```
  17396. **/
  17397. function deflate(input, options) {
  17398. var deflator = new Deflate(options);
  17399. deflator.push(input, true);
  17400. // That will never happens, if you don't cheat with options :)
  17401. if (deflator.err) { throw deflator.msg; }
  17402. return deflator.result;
  17403. }
  17404. /**
  17405. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  17406. * - data (Uint8Array|Array|String): input data to compress.
  17407. * - options (Object): zlib deflate options.
  17408. *
  17409. * The same as [[deflate]], but creates raw data, without wrapper
  17410. * (header and adler32 crc).
  17411. **/
  17412. function deflateRaw(input, options) {
  17413. options = options || {};
  17414. options.raw = true;
  17415. return deflate(input, options);
  17416. }
  17417. /**
  17418. * gzip(data[, options]) -> Uint8Array|Array|String
  17419. * - data (Uint8Array|Array|String): input data to compress.
  17420. * - options (Object): zlib deflate options.
  17421. *
  17422. * The same as [[deflate]], but create gzip wrapper instead of
  17423. * deflate one.
  17424. **/
  17425. function gzip(input, options) {
  17426. options = options || {};
  17427. options.gzip = true;
  17428. return deflate(input, options);
  17429. }
  17430. exports.Deflate = Deflate;
  17431. exports.deflate = deflate;
  17432. exports.deflateRaw = deflateRaw;
  17433. exports.gzip = gzip;
  17434. },{"./utils/common":66,"./utils/strings":67,"./zlib/deflate.js":71,"./zlib/messages":76,"./zlib/zstream":78}],65:[function(require,module,exports){
  17435. 'use strict';
  17436. var zlib_inflate = require('./zlib/inflate.js');
  17437. var utils = require('./utils/common');
  17438. var strings = require('./utils/strings');
  17439. var c = require('./zlib/constants');
  17440. var msg = require('./zlib/messages');
  17441. var zstream = require('./zlib/zstream');
  17442. var gzheader = require('./zlib/gzheader');
  17443. var toString = Object.prototype.toString;
  17444. /**
  17445. * class Inflate
  17446. *
  17447. * Generic JS-style wrapper for zlib calls. If you don't need
  17448. * streaming behaviour - use more simple functions: [[inflate]]
  17449. * and [[inflateRaw]].
  17450. **/
  17451. /* internal
  17452. * inflate.chunks -> Array
  17453. *
  17454. * Chunks of output data, if [[Inflate#onData]] not overriden.
  17455. **/
  17456. /**
  17457. * Inflate.result -> Uint8Array|Array|String
  17458. *
  17459. * Uncompressed result, generated by default [[Inflate#onData]]
  17460. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  17461. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  17462. **/
  17463. /**
  17464. * Inflate.err -> Number
  17465. *
  17466. * Error code after inflate finished. 0 (Z_OK) on success.
  17467. * Should be checked if broken data possible.
  17468. **/
  17469. /**
  17470. * Inflate.msg -> String
  17471. *
  17472. * Error message, if [[Inflate.err]] != 0
  17473. **/
  17474. /**
  17475. * new Inflate(options)
  17476. * - options (Object): zlib inflate options.
  17477. *
  17478. * Creates new inflator instance with specified params. Throws exception
  17479. * on bad params. Supported options:
  17480. *
  17481. * - `windowBits`
  17482. *
  17483. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17484. * for more information on these.
  17485. *
  17486. * Additional options, for internal needs:
  17487. *
  17488. * - `chunkSize` - size of generated data chunks (16K by default)
  17489. * - `raw` (Boolean) - do raw inflate
  17490. * - `to` (String) - if equal to 'string', then result will be converted
  17491. * from utf8 to utf16 (javascript) string. When string output requested,
  17492. * chunk length can differ from `chunkSize`, depending on content.
  17493. *
  17494. * By default, when no options set, autodetect deflate/gzip data format via
  17495. * wrapper header.
  17496. *
  17497. * ##### Example:
  17498. *
  17499. * ```javascript
  17500. * var pako = require('pako')
  17501. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17502. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17503. *
  17504. * var inflate = new pako.Inflate({ level: 3});
  17505. *
  17506. * inflate.push(chunk1, false);
  17507. * inflate.push(chunk2, true); // true -> last chunk
  17508. *
  17509. * if (inflate.err) { throw new Error(inflate.err); }
  17510. *
  17511. * console.log(inflate.result);
  17512. * ```
  17513. **/
  17514. var Inflate = function(options) {
  17515. this.options = utils.assign({
  17516. chunkSize: 16384,
  17517. windowBits: 0,
  17518. to: ''
  17519. }, options || {});
  17520. var opt = this.options;
  17521. // Force window size for `raw` data, if not set directly,
  17522. // because we have no header for autodetect.
  17523. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  17524. opt.windowBits = -opt.windowBits;
  17525. if (opt.windowBits === 0) { opt.windowBits = -15; }
  17526. }
  17527. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  17528. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  17529. !(options && options.windowBits)) {
  17530. opt.windowBits += 32;
  17531. }
  17532. // Gzip header has no info about windows size, we can do autodetect only
  17533. // for deflate. So, if window size not set, force it to max when gzip possible
  17534. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  17535. // bit 3 (16) -> gzipped data
  17536. // bit 4 (32) -> autodetect gzip/deflate
  17537. if ((opt.windowBits & 15) === 0) {
  17538. opt.windowBits |= 15;
  17539. }
  17540. }
  17541. this.err = 0; // error code, if happens (0 = Z_OK)
  17542. this.msg = ''; // error message
  17543. this.ended = false; // used to avoid multiple onEnd() calls
  17544. this.chunks = []; // chunks of compressed data
  17545. this.strm = new zstream();
  17546. this.strm.avail_out = 0;
  17547. var status = zlib_inflate.inflateInit2(
  17548. this.strm,
  17549. opt.windowBits
  17550. );
  17551. if (status !== c.Z_OK) {
  17552. throw new Error(msg[status]);
  17553. }
  17554. this.header = new gzheader();
  17555. zlib_inflate.inflateGetHeader(this.strm, this.header);
  17556. };
  17557. /**
  17558. * Inflate#push(data[, mode]) -> Boolean
  17559. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  17560. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17561. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17562. *
  17563. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  17564. * new output chunks. Returns `true` on success. The last data block must have
  17565. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17566. * [[Inflate#onEnd]].
  17567. *
  17568. * On fail call [[Inflate#onEnd]] with error code and return false.
  17569. *
  17570. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17571. * format is detected automatically). Also, don't skip last param and always
  17572. * use the same type in your code (boolean or number). That will improve JS speed.
  17573. *
  17574. * For regular `Array`-s make sure all elements are [0..255].
  17575. *
  17576. * ##### Example
  17577. *
  17578. * ```javascript
  17579. * push(chunk, false); // push one of data chunks
  17580. * ...
  17581. * push(chunk, true); // push last chunk
  17582. * ```
  17583. **/
  17584. Inflate.prototype.push = function(data, mode) {
  17585. var strm = this.strm;
  17586. var chunkSize = this.options.chunkSize;
  17587. var status, _mode;
  17588. var next_out_utf8, tail, utf8str;
  17589. if (this.ended) { return false; }
  17590. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  17591. // Convert data if needed
  17592. if (typeof data === 'string') {
  17593. // Only binary strings can be decompressed on practice
  17594. strm.input = strings.binstring2buf(data);
  17595. } else if (toString.call(data) === '[object ArrayBuffer]') {
  17596. strm.input = new Uint8Array(data);
  17597. } else {
  17598. strm.input = data;
  17599. }
  17600. strm.next_in = 0;
  17601. strm.avail_in = strm.input.length;
  17602. do {
  17603. if (strm.avail_out === 0) {
  17604. strm.output = new utils.Buf8(chunkSize);
  17605. strm.next_out = 0;
  17606. strm.avail_out = chunkSize;
  17607. }
  17608. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  17609. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  17610. this.onEnd(status);
  17611. this.ended = true;
  17612. return false;
  17613. }
  17614. if (strm.next_out) {
  17615. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  17616. if (this.options.to === 'string') {
  17617. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  17618. tail = strm.next_out - next_out_utf8;
  17619. utf8str = strings.buf2string(strm.output, next_out_utf8);
  17620. // move tail
  17621. strm.next_out = tail;
  17622. strm.avail_out = chunkSize - tail;
  17623. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  17624. this.onData(utf8str);
  17625. } else {
  17626. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17627. }
  17628. }
  17629. }
  17630. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  17631. if (status === c.Z_STREAM_END) {
  17632. _mode = c.Z_FINISH;
  17633. }
  17634. // Finalize on the last chunk.
  17635. if (_mode === c.Z_FINISH) {
  17636. status = zlib_inflate.inflateEnd(this.strm);
  17637. this.onEnd(status);
  17638. this.ended = true;
  17639. return status === c.Z_OK;
  17640. }
  17641. return true;
  17642. };
  17643. /**
  17644. * Inflate#onData(chunk) -> Void
  17645. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17646. * on js engine support. When string output requested, each chunk
  17647. * will be string.
  17648. *
  17649. * By default, stores data blocks in `chunks[]` property and glue
  17650. * those in `onEnd`. Override this handler, if you need another behaviour.
  17651. **/
  17652. Inflate.prototype.onData = function(chunk) {
  17653. this.chunks.push(chunk);
  17654. };
  17655. /**
  17656. * Inflate#onEnd(status) -> Void
  17657. * - status (Number): inflate status. 0 (Z_OK) on success,
  17658. * other if not.
  17659. *
  17660. * Called once after you tell inflate that input stream complete
  17661. * or error happenned. By default - join collected chunks,
  17662. * free memory and fill `results` / `err` properties.
  17663. **/
  17664. Inflate.prototype.onEnd = function(status) {
  17665. // On success - join
  17666. if (status === c.Z_OK) {
  17667. if (this.options.to === 'string') {
  17668. // Glue & convert here, until we teach pako to send
  17669. // utf8 alligned strings to onData
  17670. this.result = this.chunks.join('');
  17671. } else {
  17672. this.result = utils.flattenChunks(this.chunks);
  17673. }
  17674. }
  17675. this.chunks = [];
  17676. this.err = status;
  17677. this.msg = this.strm.msg;
  17678. };
  17679. /**
  17680. * inflate(data[, options]) -> Uint8Array|Array|String
  17681. * - data (Uint8Array|Array|String): input data to decompress.
  17682. * - options (Object): zlib inflate options.
  17683. *
  17684. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  17685. * format via wrapper header by default. That's why we don't provide
  17686. * separate `ungzip` method.
  17687. *
  17688. * Supported options are:
  17689. *
  17690. * - windowBits
  17691. *
  17692. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17693. * for more information.
  17694. *
  17695. * Sugar (options):
  17696. *
  17697. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17698. * negative windowBits implicitly.
  17699. * - `to` (String) - if equal to 'string', then result will be converted
  17700. * from utf8 to utf16 (javascript) string. When string output requested,
  17701. * chunk length can differ from `chunkSize`, depending on content.
  17702. *
  17703. *
  17704. * ##### Example:
  17705. *
  17706. * ```javascript
  17707. * var pako = require('pako')
  17708. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  17709. * , output;
  17710. *
  17711. * try {
  17712. * output = pako.inflate(input);
  17713. * } catch (err)
  17714. * console.log(err);
  17715. * }
  17716. * ```
  17717. **/
  17718. function inflate(input, options) {
  17719. var inflator = new Inflate(options);
  17720. inflator.push(input, true);
  17721. // That will never happens, if you don't cheat with options :)
  17722. if (inflator.err) { throw inflator.msg; }
  17723. return inflator.result;
  17724. }
  17725. /**
  17726. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  17727. * - data (Uint8Array|Array|String): input data to decompress.
  17728. * - options (Object): zlib inflate options.
  17729. *
  17730. * The same as [[inflate]], but creates raw data, without wrapper
  17731. * (header and adler32 crc).
  17732. **/
  17733. function inflateRaw(input, options) {
  17734. options = options || {};
  17735. options.raw = true;
  17736. return inflate(input, options);
  17737. }
  17738. /**
  17739. * ungzip(data[, options]) -> Uint8Array|Array|String
  17740. * - data (Uint8Array|Array|String): input data to decompress.
  17741. * - options (Object): zlib inflate options.
  17742. *
  17743. * Just shortcut to [[inflate]], because it autodetects format
  17744. * by header.content. Done for convenience.
  17745. **/
  17746. exports.Inflate = Inflate;
  17747. exports.inflate = inflate;
  17748. exports.inflateRaw = inflateRaw;
  17749. exports.ungzip = inflate;
  17750. },{"./utils/common":66,"./utils/strings":67,"./zlib/constants":69,"./zlib/gzheader":72,"./zlib/inflate.js":74,"./zlib/messages":76,"./zlib/zstream":78}],66:[function(require,module,exports){
  17751. 'use strict';
  17752. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  17753. (typeof Uint16Array !== 'undefined') &&
  17754. (typeof Int32Array !== 'undefined');
  17755. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  17756. var sources = Array.prototype.slice.call(arguments, 1);
  17757. while (sources.length) {
  17758. var source = sources.shift();
  17759. if (!source) { continue; }
  17760. if (typeof(source) !== 'object') {
  17761. throw new TypeError(source + 'must be non-object');
  17762. }
  17763. for (var p in source) {
  17764. if (source.hasOwnProperty(p)) {
  17765. obj[p] = source[p];
  17766. }
  17767. }
  17768. }
  17769. return obj;
  17770. };
  17771. // reduce buffer size, avoiding mem copy
  17772. exports.shrinkBuf = function (buf, size) {
  17773. if (buf.length === size) { return buf; }
  17774. if (buf.subarray) { return buf.subarray(0, size); }
  17775. buf.length = size;
  17776. return buf;
  17777. };
  17778. var fnTyped = {
  17779. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17780. if (src.subarray && dest.subarray) {
  17781. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  17782. return;
  17783. }
  17784. // Fallback to ordinary array
  17785. for(var i=0; i<len; i++) {
  17786. dest[dest_offs + i] = src[src_offs + i];
  17787. }
  17788. },
  17789. // Join array of chunks to single array.
  17790. flattenChunks: function(chunks) {
  17791. var i, l, len, pos, chunk, result;
  17792. // calculate data length
  17793. len = 0;
  17794. for (i=0, l=chunks.length; i<l; i++) {
  17795. len += chunks[i].length;
  17796. }
  17797. // join chunks
  17798. result = new Uint8Array(len);
  17799. pos = 0;
  17800. for (i=0, l=chunks.length; i<l; i++) {
  17801. chunk = chunks[i];
  17802. result.set(chunk, pos);
  17803. pos += chunk.length;
  17804. }
  17805. return result;
  17806. }
  17807. };
  17808. var fnUntyped = {
  17809. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17810. for(var i=0; i<len; i++) {
  17811. dest[dest_offs + i] = src[src_offs + i];
  17812. }
  17813. },
  17814. // Join array of chunks to single array.
  17815. flattenChunks: function(chunks) {
  17816. return [].concat.apply([], chunks);
  17817. }
  17818. };
  17819. // Enable/Disable typed arrays use, for testing
  17820. //
  17821. exports.setTyped = function (on) {
  17822. if (on) {
  17823. exports.Buf8 = Uint8Array;
  17824. exports.Buf16 = Uint16Array;
  17825. exports.Buf32 = Int32Array;
  17826. exports.assign(exports, fnTyped);
  17827. } else {
  17828. exports.Buf8 = Array;
  17829. exports.Buf16 = Array;
  17830. exports.Buf32 = Array;
  17831. exports.assign(exports, fnUntyped);
  17832. }
  17833. };
  17834. exports.setTyped(TYPED_OK);
  17835. },{}],67:[function(require,module,exports){
  17836. // String encode/decode helpers
  17837. 'use strict';
  17838. var utils = require('./common');
  17839. // Quick check if we can use fast array to bin string conversion
  17840. //
  17841. // - apply(Array) can fail on Android 2.2
  17842. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  17843. //
  17844. var STR_APPLY_OK = true;
  17845. var STR_APPLY_UIA_OK = true;
  17846. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  17847. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  17848. // Table with utf8 lengths (calculated by first byte of sequence)
  17849. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  17850. // because max possible codepoint is 0x10ffff
  17851. var _utf8len = new utils.Buf8(256);
  17852. for (var i=0; i<256; i++) {
  17853. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  17854. }
  17855. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  17856. // convert string to array (typed, when possible)
  17857. exports.string2buf = function (str) {
  17858. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  17859. // count binary size
  17860. for (m_pos = 0; m_pos < str_len; m_pos++) {
  17861. c = str.charCodeAt(m_pos);
  17862. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17863. c2 = str.charCodeAt(m_pos+1);
  17864. if ((c2 & 0xfc00) === 0xdc00) {
  17865. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17866. m_pos++;
  17867. }
  17868. }
  17869. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  17870. }
  17871. // allocate buffer
  17872. buf = new utils.Buf8(buf_len);
  17873. // convert
  17874. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  17875. c = str.charCodeAt(m_pos);
  17876. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17877. c2 = str.charCodeAt(m_pos+1);
  17878. if ((c2 & 0xfc00) === 0xdc00) {
  17879. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17880. m_pos++;
  17881. }
  17882. }
  17883. if (c < 0x80) {
  17884. /* one byte */
  17885. buf[i++] = c;
  17886. } else if (c < 0x800) {
  17887. /* two bytes */
  17888. buf[i++] = 0xC0 | (c >>> 6);
  17889. buf[i++] = 0x80 | (c & 0x3f);
  17890. } else if (c < 0x10000) {
  17891. /* three bytes */
  17892. buf[i++] = 0xE0 | (c >>> 12);
  17893. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17894. buf[i++] = 0x80 | (c & 0x3f);
  17895. } else {
  17896. /* four bytes */
  17897. buf[i++] = 0xf0 | (c >>> 18);
  17898. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  17899. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17900. buf[i++] = 0x80 | (c & 0x3f);
  17901. }
  17902. }
  17903. return buf;
  17904. };
  17905. // Helper (used in 2 places)
  17906. function buf2binstring(buf, len) {
  17907. // use fallback for big arrays to avoid stack overflow
  17908. if (len < 65537) {
  17909. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  17910. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  17911. }
  17912. }
  17913. var result = '';
  17914. for(var i=0; i < len; i++) {
  17915. result += String.fromCharCode(buf[i]);
  17916. }
  17917. return result;
  17918. }
  17919. // Convert byte array to binary string
  17920. exports.buf2binstring = function(buf) {
  17921. return buf2binstring(buf, buf.length);
  17922. };
  17923. // Convert binary string (typed, when possible)
  17924. exports.binstring2buf = function(str) {
  17925. var buf = new utils.Buf8(str.length);
  17926. for(var i=0, len=buf.length; i < len; i++) {
  17927. buf[i] = str.charCodeAt(i);
  17928. }
  17929. return buf;
  17930. };
  17931. // convert array to string
  17932. exports.buf2string = function (buf, max) {
  17933. var i, out, c, c_len;
  17934. var len = max || buf.length;
  17935. // Reserve max possible length (2 words per char)
  17936. // NB: by unknown reasons, Array is significantly faster for
  17937. // String.fromCharCode.apply than Uint16Array.
  17938. var utf16buf = new Array(len*2);
  17939. for (out=0, i=0; i<len;) {
  17940. c = buf[i++];
  17941. // quick process ascii
  17942. if (c < 0x80) { utf16buf[out++] = c; continue; }
  17943. c_len = _utf8len[c];
  17944. // skip 5 & 6 byte codes
  17945. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  17946. // apply mask on first byte
  17947. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  17948. // join the rest
  17949. while (c_len > 1 && i < len) {
  17950. c = (c << 6) | (buf[i++] & 0x3f);
  17951. c_len--;
  17952. }
  17953. // terminated by end of string?
  17954. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  17955. if (c < 0x10000) {
  17956. utf16buf[out++] = c;
  17957. } else {
  17958. c -= 0x10000;
  17959. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  17960. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  17961. }
  17962. }
  17963. return buf2binstring(utf16buf, out);
  17964. };
  17965. // Calculate max possible position in utf8 buffer,
  17966. // that will not break sequence. If that's not possible
  17967. // - (very small limits) return max size as is.
  17968. //
  17969. // buf[] - utf8 bytes array
  17970. // max - length limit (mandatory);
  17971. exports.utf8border = function(buf, max) {
  17972. var pos;
  17973. max = max || buf.length;
  17974. if (max > buf.length) { max = buf.length; }
  17975. // go back from last position, until start of sequence found
  17976. pos = max-1;
  17977. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  17978. // Fuckup - very small and broken sequence,
  17979. // return max, because we should return something anyway.
  17980. if (pos < 0) { return max; }
  17981. // If we came to start of buffer - that means vuffer is too small,
  17982. // return max too.
  17983. if (pos === 0) { return max; }
  17984. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  17985. };
  17986. },{"./common":66}],68:[function(require,module,exports){
  17987. 'use strict';
  17988. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  17989. // It doesn't worth to make additional optimizationa as in original.
  17990. // Small size is preferable.
  17991. function adler32(adler, buf, len, pos) {
  17992. var s1 = (adler & 0xffff) |0
  17993. , s2 = ((adler >>> 16) & 0xffff) |0
  17994. , n = 0;
  17995. while (len !== 0) {
  17996. // Set limit ~ twice less than 5552, to keep
  17997. // s2 in 31-bits, because we force signed ints.
  17998. // in other case %= will fail.
  17999. n = len > 2000 ? 2000 : len;
  18000. len -= n;
  18001. do {
  18002. s1 = (s1 + buf[pos++]) |0;
  18003. s2 = (s2 + s1) |0;
  18004. } while (--n);
  18005. s1 %= 65521;
  18006. s2 %= 65521;
  18007. }
  18008. return (s1 | (s2 << 16)) |0;
  18009. }
  18010. module.exports = adler32;
  18011. },{}],69:[function(require,module,exports){
  18012. module.exports = {
  18013. /* Allowed flush values; see deflate() and inflate() below for details */
  18014. Z_NO_FLUSH: 0,
  18015. Z_PARTIAL_FLUSH: 1,
  18016. Z_SYNC_FLUSH: 2,
  18017. Z_FULL_FLUSH: 3,
  18018. Z_FINISH: 4,
  18019. Z_BLOCK: 5,
  18020. Z_TREES: 6,
  18021. /* Return codes for the compression/decompression functions. Negative values
  18022. * are errors, positive values are used for special but normal events.
  18023. */
  18024. Z_OK: 0,
  18025. Z_STREAM_END: 1,
  18026. Z_NEED_DICT: 2,
  18027. Z_ERRNO: -1,
  18028. Z_STREAM_ERROR: -2,
  18029. Z_DATA_ERROR: -3,
  18030. //Z_MEM_ERROR: -4,
  18031. Z_BUF_ERROR: -5,
  18032. //Z_VERSION_ERROR: -6,
  18033. /* compression levels */
  18034. Z_NO_COMPRESSION: 0,
  18035. Z_BEST_SPEED: 1,
  18036. Z_BEST_COMPRESSION: 9,
  18037. Z_DEFAULT_COMPRESSION: -1,
  18038. Z_FILTERED: 1,
  18039. Z_HUFFMAN_ONLY: 2,
  18040. Z_RLE: 3,
  18041. Z_FIXED: 4,
  18042. Z_DEFAULT_STRATEGY: 0,
  18043. /* Possible values of the data_type field (though see inflate()) */
  18044. Z_BINARY: 0,
  18045. Z_TEXT: 1,
  18046. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  18047. Z_UNKNOWN: 2,
  18048. /* The deflate compression method */
  18049. Z_DEFLATED: 8
  18050. //Z_NULL: null // Use -1 or null inline, depending on var type
  18051. };
  18052. },{}],70:[function(require,module,exports){
  18053. 'use strict';
  18054. // Note: we can't get significant speed boost here.
  18055. // So write code to minimize size - no pregenerated tables
  18056. // and array tools dependencies.
  18057. // Use ordinary array, since untyped makes no boost here
  18058. function makeTable() {
  18059. var c, table = [];
  18060. for(var n =0; n < 256; n++){
  18061. c = n;
  18062. for(var k =0; k < 8; k++){
  18063. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  18064. }
  18065. table[n] = c;
  18066. }
  18067. return table;
  18068. }
  18069. // Create table on load. Just 255 signed longs. Not a problem.
  18070. var crcTable = makeTable();
  18071. function crc32(crc, buf, len, pos) {
  18072. var t = crcTable
  18073. , end = pos + len;
  18074. crc = crc ^ (-1);
  18075. for (var i = pos; i < end; i++ ) {
  18076. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  18077. }
  18078. return (crc ^ (-1)); // >>> 0;
  18079. }
  18080. module.exports = crc32;
  18081. },{}],71:[function(require,module,exports){
  18082. 'use strict';
  18083. var utils = require('../utils/common');
  18084. var trees = require('./trees');
  18085. var adler32 = require('./adler32');
  18086. var crc32 = require('./crc32');
  18087. var msg = require('./messages');
  18088. /* Public constants ==========================================================*/
  18089. /* ===========================================================================*/
  18090. /* Allowed flush values; see deflate() and inflate() below for details */
  18091. var Z_NO_FLUSH = 0;
  18092. var Z_PARTIAL_FLUSH = 1;
  18093. //var Z_SYNC_FLUSH = 2;
  18094. var Z_FULL_FLUSH = 3;
  18095. var Z_FINISH = 4;
  18096. var Z_BLOCK = 5;
  18097. //var Z_TREES = 6;
  18098. /* Return codes for the compression/decompression functions. Negative values
  18099. * are errors, positive values are used for special but normal events.
  18100. */
  18101. var Z_OK = 0;
  18102. var Z_STREAM_END = 1;
  18103. //var Z_NEED_DICT = 2;
  18104. //var Z_ERRNO = -1;
  18105. var Z_STREAM_ERROR = -2;
  18106. var Z_DATA_ERROR = -3;
  18107. //var Z_MEM_ERROR = -4;
  18108. var Z_BUF_ERROR = -5;
  18109. //var Z_VERSION_ERROR = -6;
  18110. /* compression levels */
  18111. //var Z_NO_COMPRESSION = 0;
  18112. //var Z_BEST_SPEED = 1;
  18113. //var Z_BEST_COMPRESSION = 9;
  18114. var Z_DEFAULT_COMPRESSION = -1;
  18115. var Z_FILTERED = 1;
  18116. var Z_HUFFMAN_ONLY = 2;
  18117. var Z_RLE = 3;
  18118. var Z_FIXED = 4;
  18119. var Z_DEFAULT_STRATEGY = 0;
  18120. /* Possible values of the data_type field (though see inflate()) */
  18121. //var Z_BINARY = 0;
  18122. //var Z_TEXT = 1;
  18123. //var Z_ASCII = 1; // = Z_TEXT
  18124. var Z_UNKNOWN = 2;
  18125. /* The deflate compression method */
  18126. var Z_DEFLATED = 8;
  18127. /*============================================================================*/
  18128. var MAX_MEM_LEVEL = 9;
  18129. /* Maximum value for memLevel in deflateInit2 */
  18130. var MAX_WBITS = 15;
  18131. /* 32K LZ77 window */
  18132. var DEF_MEM_LEVEL = 8;
  18133. var LENGTH_CODES = 29;
  18134. /* number of length codes, not counting the special END_BLOCK code */
  18135. var LITERALS = 256;
  18136. /* number of literal bytes 0..255 */
  18137. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  18138. /* number of Literal or Length codes, including the END_BLOCK code */
  18139. var D_CODES = 30;
  18140. /* number of distance codes */
  18141. var BL_CODES = 19;
  18142. /* number of codes used to transfer the bit lengths */
  18143. var HEAP_SIZE = 2*L_CODES + 1;
  18144. /* maximum heap size */
  18145. var MAX_BITS = 15;
  18146. /* All codes must not exceed MAX_BITS bits */
  18147. var MIN_MATCH = 3;
  18148. var MAX_MATCH = 258;
  18149. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  18150. var PRESET_DICT = 0x20;
  18151. var INIT_STATE = 42;
  18152. var EXTRA_STATE = 69;
  18153. var NAME_STATE = 73;
  18154. var COMMENT_STATE = 91;
  18155. var HCRC_STATE = 103;
  18156. var BUSY_STATE = 113;
  18157. var FINISH_STATE = 666;
  18158. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  18159. var BS_BLOCK_DONE = 2; /* block flush performed */
  18160. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  18161. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  18162. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  18163. function err(strm, errorCode) {
  18164. strm.msg = msg[errorCode];
  18165. return errorCode;
  18166. }
  18167. function rank(f) {
  18168. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  18169. }
  18170. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  18171. /* =========================================================================
  18172. * Flush as much pending output as possible. All deflate() output goes
  18173. * through this function so some applications may wish to modify it
  18174. * to avoid allocating a large strm->output buffer and copying into it.
  18175. * (See also read_buf()).
  18176. */
  18177. function flush_pending(strm) {
  18178. var s = strm.state;
  18179. //_tr_flush_bits(s);
  18180. var len = s.pending;
  18181. if (len > strm.avail_out) {
  18182. len = strm.avail_out;
  18183. }
  18184. if (len === 0) { return; }
  18185. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  18186. strm.next_out += len;
  18187. s.pending_out += len;
  18188. strm.total_out += len;
  18189. strm.avail_out -= len;
  18190. s.pending -= len;
  18191. if (s.pending === 0) {
  18192. s.pending_out = 0;
  18193. }
  18194. }
  18195. function flush_block_only (s, last) {
  18196. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  18197. s.block_start = s.strstart;
  18198. flush_pending(s.strm);
  18199. }
  18200. function put_byte(s, b) {
  18201. s.pending_buf[s.pending++] = b;
  18202. }
  18203. /* =========================================================================
  18204. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  18205. * IN assertion: the stream state is correct and there is enough room in
  18206. * pending_buf.
  18207. */
  18208. function putShortMSB(s, b) {
  18209. // put_byte(s, (Byte)(b >> 8));
  18210. // put_byte(s, (Byte)(b & 0xff));
  18211. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  18212. s.pending_buf[s.pending++] = b & 0xff;
  18213. }
  18214. /* ===========================================================================
  18215. * Read a new buffer from the current input stream, update the adler32
  18216. * and total number of bytes read. All deflate() input goes through
  18217. * this function so some applications may wish to modify it to avoid
  18218. * allocating a large strm->input buffer and copying from it.
  18219. * (See also flush_pending()).
  18220. */
  18221. function read_buf(strm, buf, start, size) {
  18222. var len = strm.avail_in;
  18223. if (len > size) { len = size; }
  18224. if (len === 0) { return 0; }
  18225. strm.avail_in -= len;
  18226. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  18227. if (strm.state.wrap === 1) {
  18228. strm.adler = adler32(strm.adler, buf, len, start);
  18229. }
  18230. else if (strm.state.wrap === 2) {
  18231. strm.adler = crc32(strm.adler, buf, len, start);
  18232. }
  18233. strm.next_in += len;
  18234. strm.total_in += len;
  18235. return len;
  18236. }
  18237. /* ===========================================================================
  18238. * Set match_start to the longest match starting at the given string and
  18239. * return its length. Matches shorter or equal to prev_length are discarded,
  18240. * in which case the result is equal to prev_length and match_start is
  18241. * garbage.
  18242. * IN assertions: cur_match is the head of the hash chain for the current
  18243. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  18244. * OUT assertion: the match length is not greater than s->lookahead.
  18245. */
  18246. function longest_match(s, cur_match) {
  18247. var chain_length = s.max_chain_length; /* max hash chain length */
  18248. var scan = s.strstart; /* current string */
  18249. var match; /* matched string */
  18250. var len; /* length of current match */
  18251. var best_len = s.prev_length; /* best match length so far */
  18252. var nice_match = s.nice_match; /* stop if match long enough */
  18253. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  18254. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  18255. var _win = s.window; // shortcut
  18256. var wmask = s.w_mask;
  18257. var prev = s.prev;
  18258. /* Stop when cur_match becomes <= limit. To simplify the code,
  18259. * we prevent matches with the string of window index 0.
  18260. */
  18261. var strend = s.strstart + MAX_MATCH;
  18262. var scan_end1 = _win[scan + best_len - 1];
  18263. var scan_end = _win[scan + best_len];
  18264. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  18265. * It is easy to get rid of this optimization if necessary.
  18266. */
  18267. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  18268. /* Do not waste too much time if we already have a good match: */
  18269. if (s.prev_length >= s.good_match) {
  18270. chain_length >>= 2;
  18271. }
  18272. /* Do not look for matches beyond the end of the input. This is necessary
  18273. * to make deflate deterministic.
  18274. */
  18275. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  18276. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  18277. do {
  18278. // Assert(cur_match < s->strstart, "no future");
  18279. match = cur_match;
  18280. /* Skip to next match if the match length cannot increase
  18281. * or if the match length is less than 2. Note that the checks below
  18282. * for insufficient lookahead only occur occasionally for performance
  18283. * reasons. Therefore uninitialized memory will be accessed, and
  18284. * conditional jumps will be made that depend on those values.
  18285. * However the length of the match is limited to the lookahead, so
  18286. * the output of deflate is not affected by the uninitialized values.
  18287. */
  18288. if (_win[match + best_len] !== scan_end ||
  18289. _win[match + best_len - 1] !== scan_end1 ||
  18290. _win[match] !== _win[scan] ||
  18291. _win[++match] !== _win[scan + 1]) {
  18292. continue;
  18293. }
  18294. /* The check at best_len-1 can be removed because it will be made
  18295. * again later. (This heuristic is not always a win.)
  18296. * It is not necessary to compare scan[2] and match[2] since they
  18297. * are always equal when the other bytes match, given that
  18298. * the hash keys are equal and that HASH_BITS >= 8.
  18299. */
  18300. scan += 2;
  18301. match++;
  18302. // Assert(*scan == *match, "match[2]?");
  18303. /* We check for insufficient lookahead only every 8th comparison;
  18304. * the 256th check will be made at strstart+258.
  18305. */
  18306. do {
  18307. /*jshint noempty:false*/
  18308. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18309. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18310. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18311. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18312. scan < strend);
  18313. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  18314. len = MAX_MATCH - (strend - scan);
  18315. scan = strend - MAX_MATCH;
  18316. if (len > best_len) {
  18317. s.match_start = cur_match;
  18318. best_len = len;
  18319. if (len >= nice_match) {
  18320. break;
  18321. }
  18322. scan_end1 = _win[scan + best_len - 1];
  18323. scan_end = _win[scan + best_len];
  18324. }
  18325. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  18326. if (best_len <= s.lookahead) {
  18327. return best_len;
  18328. }
  18329. return s.lookahead;
  18330. }
  18331. /* ===========================================================================
  18332. * Fill the window when the lookahead becomes insufficient.
  18333. * Updates strstart and lookahead.
  18334. *
  18335. * IN assertion: lookahead < MIN_LOOKAHEAD
  18336. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  18337. * At least one byte has been read, or avail_in == 0; reads are
  18338. * performed for at least two bytes (required for the zip translate_eol
  18339. * option -- not supported here).
  18340. */
  18341. function fill_window(s) {
  18342. var _w_size = s.w_size;
  18343. var p, n, m, more, str;
  18344. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  18345. do {
  18346. more = s.window_size - s.lookahead - s.strstart;
  18347. // JS ints have 32 bit, block below not needed
  18348. /* Deal with !@#$% 64K limit: */
  18349. //if (sizeof(int) <= 2) {
  18350. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  18351. // more = wsize;
  18352. //
  18353. // } else if (more == (unsigned)(-1)) {
  18354. // /* Very unlikely, but possible on 16 bit machine if
  18355. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  18356. // */
  18357. // more--;
  18358. // }
  18359. //}
  18360. /* If the window is almost full and there is insufficient lookahead,
  18361. * move the upper half to the lower one to make room in the upper half.
  18362. */
  18363. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  18364. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  18365. s.match_start -= _w_size;
  18366. s.strstart -= _w_size;
  18367. /* we now have strstart >= MAX_DIST */
  18368. s.block_start -= _w_size;
  18369. /* Slide the hash table (could be avoided with 32 bit values
  18370. at the expense of memory usage). We slide even when level == 0
  18371. to keep the hash table consistent if we switch back to level > 0
  18372. later. (Using level 0 permanently is not an optimal usage of
  18373. zlib, so we don't care about this pathological case.)
  18374. */
  18375. n = s.hash_size;
  18376. p = n;
  18377. do {
  18378. m = s.head[--p];
  18379. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  18380. } while (--n);
  18381. n = _w_size;
  18382. p = n;
  18383. do {
  18384. m = s.prev[--p];
  18385. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  18386. /* If n is not on any hash chain, prev[n] is garbage but
  18387. * its value will never be used.
  18388. */
  18389. } while (--n);
  18390. more += _w_size;
  18391. }
  18392. if (s.strm.avail_in === 0) {
  18393. break;
  18394. }
  18395. /* If there was no sliding:
  18396. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  18397. * more == window_size - lookahead - strstart
  18398. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  18399. * => more >= window_size - 2*WSIZE + 2
  18400. * In the BIG_MEM or MMAP case (not yet supported),
  18401. * window_size == input_size + MIN_LOOKAHEAD &&
  18402. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  18403. * Otherwise, window_size == 2*WSIZE so more >= 2.
  18404. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  18405. */
  18406. //Assert(more >= 2, "more < 2");
  18407. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  18408. s.lookahead += n;
  18409. /* Initialize the hash value now that we have some input: */
  18410. if (s.lookahead + s.insert >= MIN_MATCH) {
  18411. str = s.strstart - s.insert;
  18412. s.ins_h = s.window[str];
  18413. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  18414. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  18415. //#if MIN_MATCH != 3
  18416. // Call update_hash() MIN_MATCH-3 more times
  18417. //#endif
  18418. while (s.insert) {
  18419. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  18420. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  18421. s.prev[str & s.w_mask] = s.head[s.ins_h];
  18422. s.head[s.ins_h] = str;
  18423. str++;
  18424. s.insert--;
  18425. if (s.lookahead + s.insert < MIN_MATCH) {
  18426. break;
  18427. }
  18428. }
  18429. }
  18430. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  18431. * but this is not important since only literal bytes will be emitted.
  18432. */
  18433. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  18434. /* If the WIN_INIT bytes after the end of the current data have never been
  18435. * written, then zero those bytes in order to avoid memory check reports of
  18436. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  18437. * the longest match routines. Update the high water mark for the next
  18438. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  18439. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  18440. */
  18441. // if (s.high_water < s.window_size) {
  18442. // var curr = s.strstart + s.lookahead;
  18443. // var init = 0;
  18444. //
  18445. // if (s.high_water < curr) {
  18446. // /* Previous high water mark below current data -- zero WIN_INIT
  18447. // * bytes or up to end of window, whichever is less.
  18448. // */
  18449. // init = s.window_size - curr;
  18450. // if (init > WIN_INIT)
  18451. // init = WIN_INIT;
  18452. // zmemzero(s->window + curr, (unsigned)init);
  18453. // s->high_water = curr + init;
  18454. // }
  18455. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  18456. // /* High water mark at or above current data, but below current data
  18457. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  18458. // * to end of window, whichever is less.
  18459. // */
  18460. // init = (ulg)curr + WIN_INIT - s->high_water;
  18461. // if (init > s->window_size - s->high_water)
  18462. // init = s->window_size - s->high_water;
  18463. // zmemzero(s->window + s->high_water, (unsigned)init);
  18464. // s->high_water += init;
  18465. // }
  18466. // }
  18467. //
  18468. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  18469. // "not enough room for search");
  18470. }
  18471. /* ===========================================================================
  18472. * Copy without compression as much as possible from the input stream, return
  18473. * the current block state.
  18474. * This function does not insert new strings in the dictionary since
  18475. * uncompressible data is probably not useful. This function is used
  18476. * only for the level=0 compression option.
  18477. * NOTE: this function should be optimized to avoid extra copying from
  18478. * window to pending_buf.
  18479. */
  18480. function deflate_stored(s, flush) {
  18481. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  18482. * to pending_buf_size, and each stored block has a 5 byte header:
  18483. */
  18484. var max_block_size = 0xffff;
  18485. if (max_block_size > s.pending_buf_size - 5) {
  18486. max_block_size = s.pending_buf_size - 5;
  18487. }
  18488. /* Copy as much as possible from input to output: */
  18489. for (;;) {
  18490. /* Fill the window as much as possible: */
  18491. if (s.lookahead <= 1) {
  18492. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  18493. // s->block_start >= (long)s->w_size, "slide too late");
  18494. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  18495. // s.block_start >= s.w_size)) {
  18496. // throw new Error("slide too late");
  18497. // }
  18498. fill_window(s);
  18499. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  18500. return BS_NEED_MORE;
  18501. }
  18502. if (s.lookahead === 0) {
  18503. break;
  18504. }
  18505. /* flush the current block */
  18506. }
  18507. //Assert(s->block_start >= 0L, "block gone");
  18508. // if (s.block_start < 0) throw new Error("block gone");
  18509. s.strstart += s.lookahead;
  18510. s.lookahead = 0;
  18511. /* Emit a stored block if pending_buf will be full: */
  18512. var max_start = s.block_start + max_block_size;
  18513. if (s.strstart === 0 || s.strstart >= max_start) {
  18514. /* strstart == 0 is possible when wraparound on 16-bit machine */
  18515. s.lookahead = s.strstart - max_start;
  18516. s.strstart = max_start;
  18517. /*** FLUSH_BLOCK(s, 0); ***/
  18518. flush_block_only(s, false);
  18519. if (s.strm.avail_out === 0) {
  18520. return BS_NEED_MORE;
  18521. }
  18522. /***/
  18523. }
  18524. /* Flush if we may have to slide, otherwise block_start may become
  18525. * negative and the data will be gone:
  18526. */
  18527. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  18528. /*** FLUSH_BLOCK(s, 0); ***/
  18529. flush_block_only(s, false);
  18530. if (s.strm.avail_out === 0) {
  18531. return BS_NEED_MORE;
  18532. }
  18533. /***/
  18534. }
  18535. }
  18536. s.insert = 0;
  18537. if (flush === Z_FINISH) {
  18538. /*** FLUSH_BLOCK(s, 1); ***/
  18539. flush_block_only(s, true);
  18540. if (s.strm.avail_out === 0) {
  18541. return BS_FINISH_STARTED;
  18542. }
  18543. /***/
  18544. return BS_FINISH_DONE;
  18545. }
  18546. if (s.strstart > s.block_start) {
  18547. /*** FLUSH_BLOCK(s, 0); ***/
  18548. flush_block_only(s, false);
  18549. if (s.strm.avail_out === 0) {
  18550. return BS_NEED_MORE;
  18551. }
  18552. /***/
  18553. }
  18554. return BS_NEED_MORE;
  18555. }
  18556. /* ===========================================================================
  18557. * Compress as much as possible from the input stream, return the current
  18558. * block state.
  18559. * This function does not perform lazy evaluation of matches and inserts
  18560. * new strings in the dictionary only for unmatched strings or for short
  18561. * matches. It is used only for the fast compression options.
  18562. */
  18563. function deflate_fast(s, flush) {
  18564. var hash_head; /* head of the hash chain */
  18565. var bflush; /* set if current block must be flushed */
  18566. for (;;) {
  18567. /* Make sure that we always have enough lookahead, except
  18568. * at the end of the input file. We need MAX_MATCH bytes
  18569. * for the next match, plus MIN_MATCH bytes to insert the
  18570. * string following the next match.
  18571. */
  18572. if (s.lookahead < MIN_LOOKAHEAD) {
  18573. fill_window(s);
  18574. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18575. return BS_NEED_MORE;
  18576. }
  18577. if (s.lookahead === 0) {
  18578. break; /* flush the current block */
  18579. }
  18580. }
  18581. /* Insert the string window[strstart .. strstart+2] in the
  18582. * dictionary, and set hash_head to the head of the hash chain:
  18583. */
  18584. hash_head = 0/*NIL*/;
  18585. if (s.lookahead >= MIN_MATCH) {
  18586. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18587. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18588. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18589. s.head[s.ins_h] = s.strstart;
  18590. /***/
  18591. }
  18592. /* Find the longest match, discarding those <= prev_length.
  18593. * At this point we have always match_length < MIN_MATCH
  18594. */
  18595. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  18596. /* To simplify the code, we prevent matches with the string
  18597. * of window index 0 (in particular we have to avoid a match
  18598. * of the string with itself at the start of the input file).
  18599. */
  18600. s.match_length = longest_match(s, hash_head);
  18601. /* longest_match() sets match_start */
  18602. }
  18603. if (s.match_length >= MIN_MATCH) {
  18604. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  18605. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  18606. s.match_length - MIN_MATCH, bflush); ***/
  18607. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  18608. s.lookahead -= s.match_length;
  18609. /* Insert new strings in the hash table only if the match length
  18610. * is not too large. This saves time but degrades compression.
  18611. */
  18612. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  18613. s.match_length--; /* string at strstart already in table */
  18614. do {
  18615. s.strstart++;
  18616. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18617. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18618. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18619. s.head[s.ins_h] = s.strstart;
  18620. /***/
  18621. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  18622. * always MIN_MATCH bytes ahead.
  18623. */
  18624. } while (--s.match_length !== 0);
  18625. s.strstart++;
  18626. } else
  18627. {
  18628. s.strstart += s.match_length;
  18629. s.match_length = 0;
  18630. s.ins_h = s.window[s.strstart];
  18631. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  18632. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  18633. //#if MIN_MATCH != 3
  18634. // Call UPDATE_HASH() MIN_MATCH-3 more times
  18635. //#endif
  18636. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  18637. * matter since it will be recomputed at next deflate call.
  18638. */
  18639. }
  18640. } else {
  18641. /* No match, output a literal byte */
  18642. //Tracevv((stderr,"%c", s.window[s.strstart]));
  18643. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18644. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18645. s.lookahead--;
  18646. s.strstart++;
  18647. }
  18648. if (bflush) {
  18649. /*** FLUSH_BLOCK(s, 0); ***/
  18650. flush_block_only(s, false);
  18651. if (s.strm.avail_out === 0) {
  18652. return BS_NEED_MORE;
  18653. }
  18654. /***/
  18655. }
  18656. }
  18657. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  18658. if (flush === Z_FINISH) {
  18659. /*** FLUSH_BLOCK(s, 1); ***/
  18660. flush_block_only(s, true);
  18661. if (s.strm.avail_out === 0) {
  18662. return BS_FINISH_STARTED;
  18663. }
  18664. /***/
  18665. return BS_FINISH_DONE;
  18666. }
  18667. if (s.last_lit) {
  18668. /*** FLUSH_BLOCK(s, 0); ***/
  18669. flush_block_only(s, false);
  18670. if (s.strm.avail_out === 0) {
  18671. return BS_NEED_MORE;
  18672. }
  18673. /***/
  18674. }
  18675. return BS_BLOCK_DONE;
  18676. }
  18677. /* ===========================================================================
  18678. * Same as above, but achieves better compression. We use a lazy
  18679. * evaluation for matches: a match is finally adopted only if there is
  18680. * no better match at the next window position.
  18681. */
  18682. function deflate_slow(s, flush) {
  18683. var hash_head; /* head of hash chain */
  18684. var bflush; /* set if current block must be flushed */
  18685. var max_insert;
  18686. /* Process the input block. */
  18687. for (;;) {
  18688. /* Make sure that we always have enough lookahead, except
  18689. * at the end of the input file. We need MAX_MATCH bytes
  18690. * for the next match, plus MIN_MATCH bytes to insert the
  18691. * string following the next match.
  18692. */
  18693. if (s.lookahead < MIN_LOOKAHEAD) {
  18694. fill_window(s);
  18695. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18696. return BS_NEED_MORE;
  18697. }
  18698. if (s.lookahead === 0) { break; } /* flush the current block */
  18699. }
  18700. /* Insert the string window[strstart .. strstart+2] in the
  18701. * dictionary, and set hash_head to the head of the hash chain:
  18702. */
  18703. hash_head = 0/*NIL*/;
  18704. if (s.lookahead >= MIN_MATCH) {
  18705. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18706. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18707. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18708. s.head[s.ins_h] = s.strstart;
  18709. /***/
  18710. }
  18711. /* Find the longest match, discarding those <= prev_length.
  18712. */
  18713. s.prev_length = s.match_length;
  18714. s.prev_match = s.match_start;
  18715. s.match_length = MIN_MATCH-1;
  18716. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  18717. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  18718. /* To simplify the code, we prevent matches with the string
  18719. * of window index 0 (in particular we have to avoid a match
  18720. * of the string with itself at the start of the input file).
  18721. */
  18722. s.match_length = longest_match(s, hash_head);
  18723. /* longest_match() sets match_start */
  18724. if (s.match_length <= 5 &&
  18725. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  18726. /* If prev_match is also MIN_MATCH, match_start is garbage
  18727. * but we will ignore the current match anyway.
  18728. */
  18729. s.match_length = MIN_MATCH-1;
  18730. }
  18731. }
  18732. /* If there was a match at the previous step and the current
  18733. * match is not better, output the previous match:
  18734. */
  18735. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  18736. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  18737. /* Do not insert strings in hash table beyond this. */
  18738. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  18739. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  18740. s.prev_length - MIN_MATCH, bflush);***/
  18741. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  18742. /* Insert in hash table all strings up to the end of the match.
  18743. * strstart-1 and strstart are already inserted. If there is not
  18744. * enough lookahead, the last two strings are not inserted in
  18745. * the hash table.
  18746. */
  18747. s.lookahead -= s.prev_length-1;
  18748. s.prev_length -= 2;
  18749. do {
  18750. if (++s.strstart <= max_insert) {
  18751. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18752. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18753. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18754. s.head[s.ins_h] = s.strstart;
  18755. /***/
  18756. }
  18757. } while (--s.prev_length !== 0);
  18758. s.match_available = 0;
  18759. s.match_length = MIN_MATCH-1;
  18760. s.strstart++;
  18761. if (bflush) {
  18762. /*** FLUSH_BLOCK(s, 0); ***/
  18763. flush_block_only(s, false);
  18764. if (s.strm.avail_out === 0) {
  18765. return BS_NEED_MORE;
  18766. }
  18767. /***/
  18768. }
  18769. } else if (s.match_available) {
  18770. /* If there was no match at the previous position, output a
  18771. * single literal. If there was a match but the current match
  18772. * is longer, truncate the previous match to a single literal.
  18773. */
  18774. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18775. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18776. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18777. if (bflush) {
  18778. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  18779. flush_block_only(s, false);
  18780. /***/
  18781. }
  18782. s.strstart++;
  18783. s.lookahead--;
  18784. if (s.strm.avail_out === 0) {
  18785. return BS_NEED_MORE;
  18786. }
  18787. } else {
  18788. /* There is no previous match to compare with, wait for
  18789. * the next step to decide.
  18790. */
  18791. s.match_available = 1;
  18792. s.strstart++;
  18793. s.lookahead--;
  18794. }
  18795. }
  18796. //Assert (flush != Z_NO_FLUSH, "no flush?");
  18797. if (s.match_available) {
  18798. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18799. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18800. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18801. s.match_available = 0;
  18802. }
  18803. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  18804. if (flush === Z_FINISH) {
  18805. /*** FLUSH_BLOCK(s, 1); ***/
  18806. flush_block_only(s, true);
  18807. if (s.strm.avail_out === 0) {
  18808. return BS_FINISH_STARTED;
  18809. }
  18810. /***/
  18811. return BS_FINISH_DONE;
  18812. }
  18813. if (s.last_lit) {
  18814. /*** FLUSH_BLOCK(s, 0); ***/
  18815. flush_block_only(s, false);
  18816. if (s.strm.avail_out === 0) {
  18817. return BS_NEED_MORE;
  18818. }
  18819. /***/
  18820. }
  18821. return BS_BLOCK_DONE;
  18822. }
  18823. /* ===========================================================================
  18824. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  18825. * one. Do not maintain a hash table. (It will be regenerated if this run of
  18826. * deflate switches away from Z_RLE.)
  18827. */
  18828. function deflate_rle(s, flush) {
  18829. var bflush; /* set if current block must be flushed */
  18830. var prev; /* byte at distance one to match */
  18831. var scan, strend; /* scan goes up to strend for length of run */
  18832. var _win = s.window;
  18833. for (;;) {
  18834. /* Make sure that we always have enough lookahead, except
  18835. * at the end of the input file. We need MAX_MATCH bytes
  18836. * for the longest run, plus one for the unrolled loop.
  18837. */
  18838. if (s.lookahead <= MAX_MATCH) {
  18839. fill_window(s);
  18840. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  18841. return BS_NEED_MORE;
  18842. }
  18843. if (s.lookahead === 0) { break; } /* flush the current block */
  18844. }
  18845. /* See how many times the previous byte repeats */
  18846. s.match_length = 0;
  18847. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  18848. scan = s.strstart - 1;
  18849. prev = _win[scan];
  18850. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  18851. strend = s.strstart + MAX_MATCH;
  18852. do {
  18853. /*jshint noempty:false*/
  18854. } while (prev === _win[++scan] && prev === _win[++scan] &&
  18855. prev === _win[++scan] && prev === _win[++scan] &&
  18856. prev === _win[++scan] && prev === _win[++scan] &&
  18857. prev === _win[++scan] && prev === _win[++scan] &&
  18858. scan < strend);
  18859. s.match_length = MAX_MATCH - (strend - scan);
  18860. if (s.match_length > s.lookahead) {
  18861. s.match_length = s.lookahead;
  18862. }
  18863. }
  18864. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  18865. }
  18866. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  18867. if (s.match_length >= MIN_MATCH) {
  18868. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  18869. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  18870. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  18871. s.lookahead -= s.match_length;
  18872. s.strstart += s.match_length;
  18873. s.match_length = 0;
  18874. } else {
  18875. /* No match, output a literal byte */
  18876. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18877. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18878. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18879. s.lookahead--;
  18880. s.strstart++;
  18881. }
  18882. if (bflush) {
  18883. /*** FLUSH_BLOCK(s, 0); ***/
  18884. flush_block_only(s, false);
  18885. if (s.strm.avail_out === 0) {
  18886. return BS_NEED_MORE;
  18887. }
  18888. /***/
  18889. }
  18890. }
  18891. s.insert = 0;
  18892. if (flush === Z_FINISH) {
  18893. /*** FLUSH_BLOCK(s, 1); ***/
  18894. flush_block_only(s, true);
  18895. if (s.strm.avail_out === 0) {
  18896. return BS_FINISH_STARTED;
  18897. }
  18898. /***/
  18899. return BS_FINISH_DONE;
  18900. }
  18901. if (s.last_lit) {
  18902. /*** FLUSH_BLOCK(s, 0); ***/
  18903. flush_block_only(s, false);
  18904. if (s.strm.avail_out === 0) {
  18905. return BS_NEED_MORE;
  18906. }
  18907. /***/
  18908. }
  18909. return BS_BLOCK_DONE;
  18910. }
  18911. /* ===========================================================================
  18912. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  18913. * (It will be regenerated if this run of deflate switches away from Huffman.)
  18914. */
  18915. function deflate_huff(s, flush) {
  18916. var bflush; /* set if current block must be flushed */
  18917. for (;;) {
  18918. /* Make sure that we have a literal to write. */
  18919. if (s.lookahead === 0) {
  18920. fill_window(s);
  18921. if (s.lookahead === 0) {
  18922. if (flush === Z_NO_FLUSH) {
  18923. return BS_NEED_MORE;
  18924. }
  18925. break; /* flush the current block */
  18926. }
  18927. }
  18928. /* Output a literal byte */
  18929. s.match_length = 0;
  18930. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18931. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18932. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18933. s.lookahead--;
  18934. s.strstart++;
  18935. if (bflush) {
  18936. /*** FLUSH_BLOCK(s, 0); ***/
  18937. flush_block_only(s, false);
  18938. if (s.strm.avail_out === 0) {
  18939. return BS_NEED_MORE;
  18940. }
  18941. /***/
  18942. }
  18943. }
  18944. s.insert = 0;
  18945. if (flush === Z_FINISH) {
  18946. /*** FLUSH_BLOCK(s, 1); ***/
  18947. flush_block_only(s, true);
  18948. if (s.strm.avail_out === 0) {
  18949. return BS_FINISH_STARTED;
  18950. }
  18951. /***/
  18952. return BS_FINISH_DONE;
  18953. }
  18954. if (s.last_lit) {
  18955. /*** FLUSH_BLOCK(s, 0); ***/
  18956. flush_block_only(s, false);
  18957. if (s.strm.avail_out === 0) {
  18958. return BS_NEED_MORE;
  18959. }
  18960. /***/
  18961. }
  18962. return BS_BLOCK_DONE;
  18963. }
  18964. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  18965. * the desired pack level (0..9). The values given below have been tuned to
  18966. * exclude worst case performance for pathological files. Better values may be
  18967. * found for specific files.
  18968. */
  18969. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  18970. this.good_length = good_length;
  18971. this.max_lazy = max_lazy;
  18972. this.nice_length = nice_length;
  18973. this.max_chain = max_chain;
  18974. this.func = func;
  18975. };
  18976. var configuration_table;
  18977. configuration_table = [
  18978. /* good lazy nice chain */
  18979. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  18980. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  18981. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  18982. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  18983. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  18984. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  18985. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  18986. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  18987. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  18988. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  18989. ];
  18990. /* ===========================================================================
  18991. * Initialize the "longest match" routines for a new zlib stream
  18992. */
  18993. function lm_init(s) {
  18994. s.window_size = 2 * s.w_size;
  18995. /*** CLEAR_HASH(s); ***/
  18996. zero(s.head); // Fill with NIL (= 0);
  18997. /* Set the default configuration parameters:
  18998. */
  18999. s.max_lazy_match = configuration_table[s.level].max_lazy;
  19000. s.good_match = configuration_table[s.level].good_length;
  19001. s.nice_match = configuration_table[s.level].nice_length;
  19002. s.max_chain_length = configuration_table[s.level].max_chain;
  19003. s.strstart = 0;
  19004. s.block_start = 0;
  19005. s.lookahead = 0;
  19006. s.insert = 0;
  19007. s.match_length = s.prev_length = MIN_MATCH - 1;
  19008. s.match_available = 0;
  19009. s.ins_h = 0;
  19010. }
  19011. function DeflateState() {
  19012. this.strm = null; /* pointer back to this zlib stream */
  19013. this.status = 0; /* as the name implies */
  19014. this.pending_buf = null; /* output still pending */
  19015. this.pending_buf_size = 0; /* size of pending_buf */
  19016. this.pending_out = 0; /* next pending byte to output to the stream */
  19017. this.pending = 0; /* nb of bytes in the pending buffer */
  19018. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  19019. this.gzhead = null; /* gzip header information to write */
  19020. this.gzindex = 0; /* where in extra, name, or comment */
  19021. this.method = Z_DEFLATED; /* can only be DEFLATED */
  19022. this.last_flush = -1; /* value of flush param for previous deflate call */
  19023. this.w_size = 0; /* LZ77 window size (32K by default) */
  19024. this.w_bits = 0; /* log2(w_size) (8..16) */
  19025. this.w_mask = 0; /* w_size - 1 */
  19026. this.window = null;
  19027. /* Sliding window. Input bytes are read into the second half of the window,
  19028. * and move to the first half later to keep a dictionary of at least wSize
  19029. * bytes. With this organization, matches are limited to a distance of
  19030. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  19031. * performed with a length multiple of the block size.
  19032. */
  19033. this.window_size = 0;
  19034. /* Actual size of window: 2*wSize, except when the user input buffer
  19035. * is directly used as sliding window.
  19036. */
  19037. this.prev = null;
  19038. /* Link to older string with same hash index. To limit the size of this
  19039. * array to 64K, this link is maintained only for the last 32K strings.
  19040. * An index in this array is thus a window index modulo 32K.
  19041. */
  19042. this.head = null; /* Heads of the hash chains or NIL. */
  19043. this.ins_h = 0; /* hash index of string to be inserted */
  19044. this.hash_size = 0; /* number of elements in hash table */
  19045. this.hash_bits = 0; /* log2(hash_size) */
  19046. this.hash_mask = 0; /* hash_size-1 */
  19047. this.hash_shift = 0;
  19048. /* Number of bits by which ins_h must be shifted at each input
  19049. * step. It must be such that after MIN_MATCH steps, the oldest
  19050. * byte no longer takes part in the hash key, that is:
  19051. * hash_shift * MIN_MATCH >= hash_bits
  19052. */
  19053. this.block_start = 0;
  19054. /* Window position at the beginning of the current output block. Gets
  19055. * negative when the window is moved backwards.
  19056. */
  19057. this.match_length = 0; /* length of best match */
  19058. this.prev_match = 0; /* previous match */
  19059. this.match_available = 0; /* set if previous match exists */
  19060. this.strstart = 0; /* start of string to insert */
  19061. this.match_start = 0; /* start of matching string */
  19062. this.lookahead = 0; /* number of valid bytes ahead in window */
  19063. this.prev_length = 0;
  19064. /* Length of the best match at previous step. Matches not greater than this
  19065. * are discarded. This is used in the lazy match evaluation.
  19066. */
  19067. this.max_chain_length = 0;
  19068. /* To speed up deflation, hash chains are never searched beyond this
  19069. * length. A higher limit improves compression ratio but degrades the
  19070. * speed.
  19071. */
  19072. this.max_lazy_match = 0;
  19073. /* Attempt to find a better match only when the current match is strictly
  19074. * smaller than this value. This mechanism is used only for compression
  19075. * levels >= 4.
  19076. */
  19077. // That's alias to max_lazy_match, don't use directly
  19078. //this.max_insert_length = 0;
  19079. /* Insert new strings in the hash table only if the match length is not
  19080. * greater than this length. This saves time but degrades compression.
  19081. * max_insert_length is used only for compression levels <= 3.
  19082. */
  19083. this.level = 0; /* compression level (1..9) */
  19084. this.strategy = 0; /* favor or force Huffman coding*/
  19085. this.good_match = 0;
  19086. /* Use a faster search when the previous match is longer than this */
  19087. this.nice_match = 0; /* Stop searching when current match exceeds this */
  19088. /* used by trees.c: */
  19089. /* Didn't use ct_data typedef below to suppress compiler warning */
  19090. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  19091. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  19092. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  19093. // Use flat array of DOUBLE size, with interleaved fata,
  19094. // because JS does not support effective
  19095. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  19096. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  19097. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  19098. zero(this.dyn_ltree);
  19099. zero(this.dyn_dtree);
  19100. zero(this.bl_tree);
  19101. this.l_desc = null; /* desc. for literal tree */
  19102. this.d_desc = null; /* desc. for distance tree */
  19103. this.bl_desc = null; /* desc. for bit length tree */
  19104. //ush bl_count[MAX_BITS+1];
  19105. this.bl_count = new utils.Buf16(MAX_BITS+1);
  19106. /* number of codes at each bit length for an optimal tree */
  19107. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  19108. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  19109. zero(this.heap);
  19110. this.heap_len = 0; /* number of elements in the heap */
  19111. this.heap_max = 0; /* element of largest frequency */
  19112. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  19113. * The same heap array is used to build all trees.
  19114. */
  19115. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  19116. zero(this.depth);
  19117. /* Depth of each subtree used as tie breaker for trees of equal frequency
  19118. */
  19119. this.l_buf = 0; /* buffer index for literals or lengths */
  19120. this.lit_bufsize = 0;
  19121. /* Size of match buffer for literals/lengths. There are 4 reasons for
  19122. * limiting lit_bufsize to 64K:
  19123. * - frequencies can be kept in 16 bit counters
  19124. * - if compression is not successful for the first block, all input
  19125. * data is still in the window so we can still emit a stored block even
  19126. * when input comes from standard input. (This can also be done for
  19127. * all blocks if lit_bufsize is not greater than 32K.)
  19128. * - if compression is not successful for a file smaller than 64K, we can
  19129. * even emit a stored file instead of a stored block (saving 5 bytes).
  19130. * This is applicable only for zip (not gzip or zlib).
  19131. * - creating new Huffman trees less frequently may not provide fast
  19132. * adaptation to changes in the input data statistics. (Take for
  19133. * example a binary file with poorly compressible code followed by
  19134. * a highly compressible string table.) Smaller buffer sizes give
  19135. * fast adaptation but have of course the overhead of transmitting
  19136. * trees more frequently.
  19137. * - I can't count above 4
  19138. */
  19139. this.last_lit = 0; /* running index in l_buf */
  19140. this.d_buf = 0;
  19141. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  19142. * the same number of elements. To use different lengths, an extra flag
  19143. * array would be necessary.
  19144. */
  19145. this.opt_len = 0; /* bit length of current block with optimal trees */
  19146. this.static_len = 0; /* bit length of current block with static trees */
  19147. this.matches = 0; /* number of string matches in current block */
  19148. this.insert = 0; /* bytes at end of window left to insert */
  19149. this.bi_buf = 0;
  19150. /* Output buffer. bits are inserted starting at the bottom (least
  19151. * significant bits).
  19152. */
  19153. this.bi_valid = 0;
  19154. /* Number of valid bits in bi_buf. All bits above the last valid bit
  19155. * are always zero.
  19156. */
  19157. // Used for window memory init. We safely ignore it for JS. That makes
  19158. // sense only for pointers and memory check tools.
  19159. //this.high_water = 0;
  19160. /* High water mark offset in window for initialized bytes -- bytes above
  19161. * this are set to zero in order to avoid memory check warnings when
  19162. * longest match routines access bytes past the input. This is then
  19163. * updated to the new high water mark.
  19164. */
  19165. }
  19166. function deflateResetKeep(strm) {
  19167. var s;
  19168. if (!strm || !strm.state) {
  19169. return err(strm, Z_STREAM_ERROR);
  19170. }
  19171. strm.total_in = strm.total_out = 0;
  19172. strm.data_type = Z_UNKNOWN;
  19173. s = strm.state;
  19174. s.pending = 0;
  19175. s.pending_out = 0;
  19176. if (s.wrap < 0) {
  19177. s.wrap = -s.wrap;
  19178. /* was made negative by deflate(..., Z_FINISH); */
  19179. }
  19180. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  19181. strm.adler = (s.wrap === 2) ?
  19182. 0 // crc32(0, Z_NULL, 0)
  19183. :
  19184. 1; // adler32(0, Z_NULL, 0)
  19185. s.last_flush = Z_NO_FLUSH;
  19186. trees._tr_init(s);
  19187. return Z_OK;
  19188. }
  19189. function deflateReset(strm) {
  19190. var ret = deflateResetKeep(strm);
  19191. if (ret === Z_OK) {
  19192. lm_init(strm.state);
  19193. }
  19194. return ret;
  19195. }
  19196. function deflateSetHeader(strm, head) {
  19197. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19198. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  19199. strm.state.gzhead = head;
  19200. return Z_OK;
  19201. }
  19202. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  19203. if (!strm) { // === Z_NULL
  19204. return Z_STREAM_ERROR;
  19205. }
  19206. var wrap = 1;
  19207. if (level === Z_DEFAULT_COMPRESSION) {
  19208. level = 6;
  19209. }
  19210. if (windowBits < 0) { /* suppress zlib wrapper */
  19211. wrap = 0;
  19212. windowBits = -windowBits;
  19213. }
  19214. else if (windowBits > 15) {
  19215. wrap = 2; /* write gzip wrapper instead */
  19216. windowBits -= 16;
  19217. }
  19218. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  19219. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  19220. strategy < 0 || strategy > Z_FIXED) {
  19221. return err(strm, Z_STREAM_ERROR);
  19222. }
  19223. if (windowBits === 8) {
  19224. windowBits = 9;
  19225. }
  19226. /* until 256-byte window bug fixed */
  19227. var s = new DeflateState();
  19228. strm.state = s;
  19229. s.strm = strm;
  19230. s.wrap = wrap;
  19231. s.gzhead = null;
  19232. s.w_bits = windowBits;
  19233. s.w_size = 1 << s.w_bits;
  19234. s.w_mask = s.w_size - 1;
  19235. s.hash_bits = memLevel + 7;
  19236. s.hash_size = 1 << s.hash_bits;
  19237. s.hash_mask = s.hash_size - 1;
  19238. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  19239. s.window = new utils.Buf8(s.w_size * 2);
  19240. s.head = new utils.Buf16(s.hash_size);
  19241. s.prev = new utils.Buf16(s.w_size);
  19242. // Don't need mem init magic for JS.
  19243. //s.high_water = 0; /* nothing written to s->window yet */
  19244. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  19245. s.pending_buf_size = s.lit_bufsize * 4;
  19246. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  19247. s.d_buf = s.lit_bufsize >> 1;
  19248. s.l_buf = (1 + 2) * s.lit_bufsize;
  19249. s.level = level;
  19250. s.strategy = strategy;
  19251. s.method = method;
  19252. return deflateReset(strm);
  19253. }
  19254. function deflateInit(strm, level) {
  19255. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  19256. }
  19257. function deflate(strm, flush) {
  19258. var old_flush, s;
  19259. var beg, val; // for gzip header write only
  19260. if (!strm || !strm.state ||
  19261. flush > Z_BLOCK || flush < 0) {
  19262. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  19263. }
  19264. s = strm.state;
  19265. if (!strm.output ||
  19266. (!strm.input && strm.avail_in !== 0) ||
  19267. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  19268. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  19269. }
  19270. s.strm = strm; /* just in case */
  19271. old_flush = s.last_flush;
  19272. s.last_flush = flush;
  19273. /* Write the header */
  19274. if (s.status === INIT_STATE) {
  19275. if (s.wrap === 2) { // GZIP header
  19276. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19277. put_byte(s, 31);
  19278. put_byte(s, 139);
  19279. put_byte(s, 8);
  19280. if (!s.gzhead) { // s->gzhead == Z_NULL
  19281. put_byte(s, 0);
  19282. put_byte(s, 0);
  19283. put_byte(s, 0);
  19284. put_byte(s, 0);
  19285. put_byte(s, 0);
  19286. put_byte(s, s.level === 9 ? 2 :
  19287. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  19288. 4 : 0));
  19289. put_byte(s, OS_CODE);
  19290. s.status = BUSY_STATE;
  19291. }
  19292. else {
  19293. put_byte(s, (s.gzhead.text ? 1 : 0) +
  19294. (s.gzhead.hcrc ? 2 : 0) +
  19295. (!s.gzhead.extra ? 0 : 4) +
  19296. (!s.gzhead.name ? 0 : 8) +
  19297. (!s.gzhead.comment ? 0 : 16)
  19298. );
  19299. put_byte(s, s.gzhead.time & 0xff);
  19300. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  19301. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  19302. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  19303. put_byte(s, s.level === 9 ? 2 :
  19304. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  19305. 4 : 0));
  19306. put_byte(s, s.gzhead.os & 0xff);
  19307. if (s.gzhead.extra && s.gzhead.extra.length) {
  19308. put_byte(s, s.gzhead.extra.length & 0xff);
  19309. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  19310. }
  19311. if (s.gzhead.hcrc) {
  19312. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  19313. }
  19314. s.gzindex = 0;
  19315. s.status = EXTRA_STATE;
  19316. }
  19317. }
  19318. else // DEFLATE header
  19319. {
  19320. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  19321. var level_flags = -1;
  19322. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  19323. level_flags = 0;
  19324. } else if (s.level < 6) {
  19325. level_flags = 1;
  19326. } else if (s.level === 6) {
  19327. level_flags = 2;
  19328. } else {
  19329. level_flags = 3;
  19330. }
  19331. header |= (level_flags << 6);
  19332. if (s.strstart !== 0) { header |= PRESET_DICT; }
  19333. header += 31 - (header % 31);
  19334. s.status = BUSY_STATE;
  19335. putShortMSB(s, header);
  19336. /* Save the adler32 of the preset dictionary: */
  19337. if (s.strstart !== 0) {
  19338. putShortMSB(s, strm.adler >>> 16);
  19339. putShortMSB(s, strm.adler & 0xffff);
  19340. }
  19341. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  19342. }
  19343. }
  19344. //#ifdef GZIP
  19345. if (s.status === EXTRA_STATE) {
  19346. if (s.gzhead.extra/* != Z_NULL*/) {
  19347. beg = s.pending; /* start of bytes to update crc */
  19348. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  19349. if (s.pending === s.pending_buf_size) {
  19350. if (s.gzhead.hcrc && s.pending > beg) {
  19351. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19352. }
  19353. flush_pending(strm);
  19354. beg = s.pending;
  19355. if (s.pending === s.pending_buf_size) {
  19356. break;
  19357. }
  19358. }
  19359. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  19360. s.gzindex++;
  19361. }
  19362. if (s.gzhead.hcrc && s.pending > beg) {
  19363. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19364. }
  19365. if (s.gzindex === s.gzhead.extra.length) {
  19366. s.gzindex = 0;
  19367. s.status = NAME_STATE;
  19368. }
  19369. }
  19370. else {
  19371. s.status = NAME_STATE;
  19372. }
  19373. }
  19374. if (s.status === NAME_STATE) {
  19375. if (s.gzhead.name/* != Z_NULL*/) {
  19376. beg = s.pending; /* start of bytes to update crc */
  19377. //int val;
  19378. do {
  19379. if (s.pending === s.pending_buf_size) {
  19380. if (s.gzhead.hcrc && s.pending > beg) {
  19381. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19382. }
  19383. flush_pending(strm);
  19384. beg = s.pending;
  19385. if (s.pending === s.pending_buf_size) {
  19386. val = 1;
  19387. break;
  19388. }
  19389. }
  19390. // JS specific: little magic to add zero terminator to end of string
  19391. if (s.gzindex < s.gzhead.name.length) {
  19392. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  19393. } else {
  19394. val = 0;
  19395. }
  19396. put_byte(s, val);
  19397. } while (val !== 0);
  19398. if (s.gzhead.hcrc && s.pending > beg){
  19399. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19400. }
  19401. if (val === 0) {
  19402. s.gzindex = 0;
  19403. s.status = COMMENT_STATE;
  19404. }
  19405. }
  19406. else {
  19407. s.status = COMMENT_STATE;
  19408. }
  19409. }
  19410. if (s.status === COMMENT_STATE) {
  19411. if (s.gzhead.comment/* != Z_NULL*/) {
  19412. beg = s.pending; /* start of bytes to update crc */
  19413. //int val;
  19414. do {
  19415. if (s.pending === s.pending_buf_size) {
  19416. if (s.gzhead.hcrc && s.pending > beg) {
  19417. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19418. }
  19419. flush_pending(strm);
  19420. beg = s.pending;
  19421. if (s.pending === s.pending_buf_size) {
  19422. val = 1;
  19423. break;
  19424. }
  19425. }
  19426. // JS specific: little magic to add zero terminator to end of string
  19427. if (s.gzindex < s.gzhead.comment.length) {
  19428. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  19429. } else {
  19430. val = 0;
  19431. }
  19432. put_byte(s, val);
  19433. } while (val !== 0);
  19434. if (s.gzhead.hcrc && s.pending > beg) {
  19435. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19436. }
  19437. if (val === 0) {
  19438. s.status = HCRC_STATE;
  19439. }
  19440. }
  19441. else {
  19442. s.status = HCRC_STATE;
  19443. }
  19444. }
  19445. if (s.status === HCRC_STATE) {
  19446. if (s.gzhead.hcrc) {
  19447. if (s.pending + 2 > s.pending_buf_size) {
  19448. flush_pending(strm);
  19449. }
  19450. if (s.pending + 2 <= s.pending_buf_size) {
  19451. put_byte(s, strm.adler & 0xff);
  19452. put_byte(s, (strm.adler >> 8) & 0xff);
  19453. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19454. s.status = BUSY_STATE;
  19455. }
  19456. }
  19457. else {
  19458. s.status = BUSY_STATE;
  19459. }
  19460. }
  19461. //#endif
  19462. /* Flush as much pending output as possible */
  19463. if (s.pending !== 0) {
  19464. flush_pending(strm);
  19465. if (strm.avail_out === 0) {
  19466. /* Since avail_out is 0, deflate will be called again with
  19467. * more output space, but possibly with both pending and
  19468. * avail_in equal to zero. There won't be anything to do,
  19469. * but this is not an error situation so make sure we
  19470. * return OK instead of BUF_ERROR at next call of deflate:
  19471. */
  19472. s.last_flush = -1;
  19473. return Z_OK;
  19474. }
  19475. /* Make sure there is something to do and avoid duplicate consecutive
  19476. * flushes. For repeated and useless calls with Z_FINISH, we keep
  19477. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  19478. */
  19479. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  19480. flush !== Z_FINISH) {
  19481. return err(strm, Z_BUF_ERROR);
  19482. }
  19483. /* User must not provide more input after the first FINISH: */
  19484. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  19485. return err(strm, Z_BUF_ERROR);
  19486. }
  19487. /* Start a new block or continue the current one.
  19488. */
  19489. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  19490. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  19491. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  19492. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  19493. configuration_table[s.level].func(s, flush));
  19494. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  19495. s.status = FINISH_STATE;
  19496. }
  19497. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  19498. if (strm.avail_out === 0) {
  19499. s.last_flush = -1;
  19500. /* avoid BUF_ERROR next call, see above */
  19501. }
  19502. return Z_OK;
  19503. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  19504. * of deflate should use the same flush parameter to make sure
  19505. * that the flush is complete. So we don't have to output an
  19506. * empty block here, this will be done at next call. This also
  19507. * ensures that for a very small output buffer, we emit at most
  19508. * one empty block.
  19509. */
  19510. }
  19511. if (bstate === BS_BLOCK_DONE) {
  19512. if (flush === Z_PARTIAL_FLUSH) {
  19513. trees._tr_align(s);
  19514. }
  19515. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  19516. trees._tr_stored_block(s, 0, 0, false);
  19517. /* For a full flush, this empty block will be recognized
  19518. * as a special marker by inflate_sync().
  19519. */
  19520. if (flush === Z_FULL_FLUSH) {
  19521. /*** CLEAR_HASH(s); ***/ /* forget history */
  19522. zero(s.head); // Fill with NIL (= 0);
  19523. if (s.lookahead === 0) {
  19524. s.strstart = 0;
  19525. s.block_start = 0;
  19526. s.insert = 0;
  19527. }
  19528. }
  19529. }
  19530. flush_pending(strm);
  19531. if (strm.avail_out === 0) {
  19532. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  19533. return Z_OK;
  19534. }
  19535. }
  19536. }
  19537. //Assert(strm->avail_out > 0, "bug2");
  19538. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  19539. if (flush !== Z_FINISH) { return Z_OK; }
  19540. if (s.wrap <= 0) { return Z_STREAM_END; }
  19541. /* Write the trailer */
  19542. if (s.wrap === 2) {
  19543. put_byte(s, strm.adler & 0xff);
  19544. put_byte(s, (strm.adler >> 8) & 0xff);
  19545. put_byte(s, (strm.adler >> 16) & 0xff);
  19546. put_byte(s, (strm.adler >> 24) & 0xff);
  19547. put_byte(s, strm.total_in & 0xff);
  19548. put_byte(s, (strm.total_in >> 8) & 0xff);
  19549. put_byte(s, (strm.total_in >> 16) & 0xff);
  19550. put_byte(s, (strm.total_in >> 24) & 0xff);
  19551. }
  19552. else
  19553. {
  19554. putShortMSB(s, strm.adler >>> 16);
  19555. putShortMSB(s, strm.adler & 0xffff);
  19556. }
  19557. flush_pending(strm);
  19558. /* If avail_out is zero, the application will call deflate again
  19559. * to flush the rest.
  19560. */
  19561. if (s.wrap > 0) { s.wrap = -s.wrap; }
  19562. /* write the trailer only once! */
  19563. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  19564. }
  19565. function deflateEnd(strm) {
  19566. var status;
  19567. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  19568. return Z_STREAM_ERROR;
  19569. }
  19570. status = strm.state.status;
  19571. if (status !== INIT_STATE &&
  19572. status !== EXTRA_STATE &&
  19573. status !== NAME_STATE &&
  19574. status !== COMMENT_STATE &&
  19575. status !== HCRC_STATE &&
  19576. status !== BUSY_STATE &&
  19577. status !== FINISH_STATE
  19578. ) {
  19579. return err(strm, Z_STREAM_ERROR);
  19580. }
  19581. strm.state = null;
  19582. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  19583. }
  19584. /* =========================================================================
  19585. * Copy the source state to the destination state
  19586. */
  19587. //function deflateCopy(dest, source) {
  19588. //
  19589. //}
  19590. exports.deflateInit = deflateInit;
  19591. exports.deflateInit2 = deflateInit2;
  19592. exports.deflateReset = deflateReset;
  19593. exports.deflateResetKeep = deflateResetKeep;
  19594. exports.deflateSetHeader = deflateSetHeader;
  19595. exports.deflate = deflate;
  19596. exports.deflateEnd = deflateEnd;
  19597. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  19598. /* Not implemented
  19599. exports.deflateBound = deflateBound;
  19600. exports.deflateCopy = deflateCopy;
  19601. exports.deflateSetDictionary = deflateSetDictionary;
  19602. exports.deflateParams = deflateParams;
  19603. exports.deflatePending = deflatePending;
  19604. exports.deflatePrime = deflatePrime;
  19605. exports.deflateTune = deflateTune;
  19606. */
  19607. },{"../utils/common":66,"./adler32":68,"./crc32":70,"./messages":76,"./trees":77}],72:[function(require,module,exports){
  19608. 'use strict';
  19609. function GZheader() {
  19610. /* true if compressed data believed to be text */
  19611. this.text = 0;
  19612. /* modification time */
  19613. this.time = 0;
  19614. /* extra flags (not used when writing a gzip file) */
  19615. this.xflags = 0;
  19616. /* operating system */
  19617. this.os = 0;
  19618. /* pointer to extra field or Z_NULL if none */
  19619. this.extra = null;
  19620. /* extra field length (valid if extra != Z_NULL) */
  19621. this.extra_len = 0; // Actually, we don't need it in JS,
  19622. // but leave for few code modifications
  19623. //
  19624. // Setup limits is not necessary because in js we should not preallocate memory
  19625. // for inflate use constant limit in 65536 bytes
  19626. //
  19627. /* space at extra (only when reading header) */
  19628. // this.extra_max = 0;
  19629. /* pointer to zero-terminated file name or Z_NULL */
  19630. this.name = '';
  19631. /* space at name (only when reading header) */
  19632. // this.name_max = 0;
  19633. /* pointer to zero-terminated comment or Z_NULL */
  19634. this.comment = '';
  19635. /* space at comment (only when reading header) */
  19636. // this.comm_max = 0;
  19637. /* true if there was or will be a header crc */
  19638. this.hcrc = 0;
  19639. /* true when done reading gzip header (not used when writing a gzip file) */
  19640. this.done = false;
  19641. }
  19642. module.exports = GZheader;
  19643. },{}],73:[function(require,module,exports){
  19644. 'use strict';
  19645. // See state defs from inflate.js
  19646. var BAD = 30; /* got a data error -- remain here until reset */
  19647. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19648. /*
  19649. Decode literal, length, and distance codes and write out the resulting
  19650. literal and match bytes until either not enough input or output is
  19651. available, an end-of-block is encountered, or a data error is encountered.
  19652. When large enough input and output buffers are supplied to inflate(), for
  19653. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  19654. inflate execution time is spent in this routine.
  19655. Entry assumptions:
  19656. state.mode === LEN
  19657. strm.avail_in >= 6
  19658. strm.avail_out >= 258
  19659. start >= strm.avail_out
  19660. state.bits < 8
  19661. On return, state.mode is one of:
  19662. LEN -- ran out of enough output space or enough available input
  19663. TYPE -- reached end of block code, inflate() to interpret next block
  19664. BAD -- error in block data
  19665. Notes:
  19666. - The maximum input bits used by a length/distance pair is 15 bits for the
  19667. length code, 5 bits for the length extra, 15 bits for the distance code,
  19668. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  19669. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  19670. checking for available input while decoding.
  19671. - The maximum bytes that a single length/distance pair can output is 258
  19672. bytes, which is the maximum length that can be coded. inflate_fast()
  19673. requires strm.avail_out >= 258 for each loop to avoid checking for
  19674. output space.
  19675. */
  19676. module.exports = function inflate_fast(strm, start) {
  19677. var state;
  19678. var _in; /* local strm.input */
  19679. var last; /* have enough input while in < last */
  19680. var _out; /* local strm.output */
  19681. var beg; /* inflate()'s initial strm.output */
  19682. var end; /* while out < end, enough space available */
  19683. //#ifdef INFLATE_STRICT
  19684. var dmax; /* maximum distance from zlib header */
  19685. //#endif
  19686. var wsize; /* window size or zero if not using window */
  19687. var whave; /* valid bytes in the window */
  19688. var wnext; /* window write index */
  19689. var window; /* allocated sliding window, if wsize != 0 */
  19690. var hold; /* local strm.hold */
  19691. var bits; /* local strm.bits */
  19692. var lcode; /* local strm.lencode */
  19693. var dcode; /* local strm.distcode */
  19694. var lmask; /* mask for first level of length codes */
  19695. var dmask; /* mask for first level of distance codes */
  19696. var here; /* retrieved table entry */
  19697. var op; /* code bits, operation, extra bits, or */
  19698. /* window position, window bytes to copy */
  19699. var len; /* match length, unused bytes */
  19700. var dist; /* match distance */
  19701. var from; /* where to copy match from */
  19702. var from_source;
  19703. var input, output; // JS specific, because we have no pointers
  19704. /* copy state to local variables */
  19705. state = strm.state;
  19706. //here = state.here;
  19707. _in = strm.next_in;
  19708. input = strm.input;
  19709. last = _in + (strm.avail_in - 5);
  19710. _out = strm.next_out;
  19711. output = strm.output;
  19712. beg = _out - (start - strm.avail_out);
  19713. end = _out + (strm.avail_out - 257);
  19714. //#ifdef INFLATE_STRICT
  19715. dmax = state.dmax;
  19716. //#endif
  19717. wsize = state.wsize;
  19718. whave = state.whave;
  19719. wnext = state.wnext;
  19720. window = state.window;
  19721. hold = state.hold;
  19722. bits = state.bits;
  19723. lcode = state.lencode;
  19724. dcode = state.distcode;
  19725. lmask = (1 << state.lenbits) - 1;
  19726. dmask = (1 << state.distbits) - 1;
  19727. /* decode literals and length/distances until end-of-block or not enough
  19728. input data or output space */
  19729. top:
  19730. do {
  19731. if (bits < 15) {
  19732. hold += input[_in++] << bits;
  19733. bits += 8;
  19734. hold += input[_in++] << bits;
  19735. bits += 8;
  19736. }
  19737. here = lcode[hold & lmask];
  19738. dolen:
  19739. for (;;) { // Goto emulation
  19740. op = here >>> 24/*here.bits*/;
  19741. hold >>>= op;
  19742. bits -= op;
  19743. op = (here >>> 16) & 0xff/*here.op*/;
  19744. if (op === 0) { /* literal */
  19745. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  19746. // "inflate: literal '%c'\n" :
  19747. // "inflate: literal 0x%02x\n", here.val));
  19748. output[_out++] = here & 0xffff/*here.val*/;
  19749. }
  19750. else if (op & 16) { /* length base */
  19751. len = here & 0xffff/*here.val*/;
  19752. op &= 15; /* number of extra bits */
  19753. if (op) {
  19754. if (bits < op) {
  19755. hold += input[_in++] << bits;
  19756. bits += 8;
  19757. }
  19758. len += hold & ((1 << op) - 1);
  19759. hold >>>= op;
  19760. bits -= op;
  19761. }
  19762. //Tracevv((stderr, "inflate: length %u\n", len));
  19763. if (bits < 15) {
  19764. hold += input[_in++] << bits;
  19765. bits += 8;
  19766. hold += input[_in++] << bits;
  19767. bits += 8;
  19768. }
  19769. here = dcode[hold & dmask];
  19770. dodist:
  19771. for (;;) { // goto emulation
  19772. op = here >>> 24/*here.bits*/;
  19773. hold >>>= op;
  19774. bits -= op;
  19775. op = (here >>> 16) & 0xff/*here.op*/;
  19776. if (op & 16) { /* distance base */
  19777. dist = here & 0xffff/*here.val*/;
  19778. op &= 15; /* number of extra bits */
  19779. if (bits < op) {
  19780. hold += input[_in++] << bits;
  19781. bits += 8;
  19782. if (bits < op) {
  19783. hold += input[_in++] << bits;
  19784. bits += 8;
  19785. }
  19786. }
  19787. dist += hold & ((1 << op) - 1);
  19788. //#ifdef INFLATE_STRICT
  19789. if (dist > dmax) {
  19790. strm.msg = 'invalid distance too far back';
  19791. state.mode = BAD;
  19792. break top;
  19793. }
  19794. //#endif
  19795. hold >>>= op;
  19796. bits -= op;
  19797. //Tracevv((stderr, "inflate: distance %u\n", dist));
  19798. op = _out - beg; /* max distance in output */
  19799. if (dist > op) { /* see if copy from window */
  19800. op = dist - op; /* distance back in window */
  19801. if (op > whave) {
  19802. if (state.sane) {
  19803. strm.msg = 'invalid distance too far back';
  19804. state.mode = BAD;
  19805. break top;
  19806. }
  19807. // (!) This block is disabled in zlib defailts,
  19808. // don't enable it for binary compatibility
  19809. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  19810. // if (len <= op - whave) {
  19811. // do {
  19812. // output[_out++] = 0;
  19813. // } while (--len);
  19814. // continue top;
  19815. // }
  19816. // len -= op - whave;
  19817. // do {
  19818. // output[_out++] = 0;
  19819. // } while (--op > whave);
  19820. // if (op === 0) {
  19821. // from = _out - dist;
  19822. // do {
  19823. // output[_out++] = output[from++];
  19824. // } while (--len);
  19825. // continue top;
  19826. // }
  19827. //#endif
  19828. }
  19829. from = 0; // window index
  19830. from_source = window;
  19831. if (wnext === 0) { /* very common case */
  19832. from += wsize - op;
  19833. if (op < len) { /* some from window */
  19834. len -= op;
  19835. do {
  19836. output[_out++] = window[from++];
  19837. } while (--op);
  19838. from = _out - dist; /* rest from output */
  19839. from_source = output;
  19840. }
  19841. }
  19842. else if (wnext < op) { /* wrap around window */
  19843. from += wsize + wnext - op;
  19844. op -= wnext;
  19845. if (op < len) { /* some from end of window */
  19846. len -= op;
  19847. do {
  19848. output[_out++] = window[from++];
  19849. } while (--op);
  19850. from = 0;
  19851. if (wnext < len) { /* some from start of window */
  19852. op = wnext;
  19853. len -= op;
  19854. do {
  19855. output[_out++] = window[from++];
  19856. } while (--op);
  19857. from = _out - dist; /* rest from output */
  19858. from_source = output;
  19859. }
  19860. }
  19861. }
  19862. else { /* contiguous in window */
  19863. from += wnext - op;
  19864. if (op < len) { /* some from window */
  19865. len -= op;
  19866. do {
  19867. output[_out++] = window[from++];
  19868. } while (--op);
  19869. from = _out - dist; /* rest from output */
  19870. from_source = output;
  19871. }
  19872. }
  19873. while (len > 2) {
  19874. output[_out++] = from_source[from++];
  19875. output[_out++] = from_source[from++];
  19876. output[_out++] = from_source[from++];
  19877. len -= 3;
  19878. }
  19879. if (len) {
  19880. output[_out++] = from_source[from++];
  19881. if (len > 1) {
  19882. output[_out++] = from_source[from++];
  19883. }
  19884. }
  19885. }
  19886. else {
  19887. from = _out - dist; /* copy direct from output */
  19888. do { /* minimum length is three */
  19889. output[_out++] = output[from++];
  19890. output[_out++] = output[from++];
  19891. output[_out++] = output[from++];
  19892. len -= 3;
  19893. } while (len > 2);
  19894. if (len) {
  19895. output[_out++] = output[from++];
  19896. if (len > 1) {
  19897. output[_out++] = output[from++];
  19898. }
  19899. }
  19900. }
  19901. }
  19902. else if ((op & 64) === 0) { /* 2nd level distance code */
  19903. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19904. continue dodist;
  19905. }
  19906. else {
  19907. strm.msg = 'invalid distance code';
  19908. state.mode = BAD;
  19909. break top;
  19910. }
  19911. break; // need to emulate goto via "continue"
  19912. }
  19913. }
  19914. else if ((op & 64) === 0) { /* 2nd level length code */
  19915. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19916. continue dolen;
  19917. }
  19918. else if (op & 32) { /* end-of-block */
  19919. //Tracevv((stderr, "inflate: end of block\n"));
  19920. state.mode = TYPE;
  19921. break top;
  19922. }
  19923. else {
  19924. strm.msg = 'invalid literal/length code';
  19925. state.mode = BAD;
  19926. break top;
  19927. }
  19928. break; // need to emulate goto via "continue"
  19929. }
  19930. } while (_in < last && _out < end);
  19931. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  19932. len = bits >> 3;
  19933. _in -= len;
  19934. bits -= len << 3;
  19935. hold &= (1 << bits) - 1;
  19936. /* update state and return */
  19937. strm.next_in = _in;
  19938. strm.next_out = _out;
  19939. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  19940. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  19941. state.hold = hold;
  19942. state.bits = bits;
  19943. return;
  19944. };
  19945. },{}],74:[function(require,module,exports){
  19946. 'use strict';
  19947. var utils = require('../utils/common');
  19948. var adler32 = require('./adler32');
  19949. var crc32 = require('./crc32');
  19950. var inflate_fast = require('./inffast');
  19951. var inflate_table = require('./inftrees');
  19952. var CODES = 0;
  19953. var LENS = 1;
  19954. var DISTS = 2;
  19955. /* Public constants ==========================================================*/
  19956. /* ===========================================================================*/
  19957. /* Allowed flush values; see deflate() and inflate() below for details */
  19958. //var Z_NO_FLUSH = 0;
  19959. //var Z_PARTIAL_FLUSH = 1;
  19960. //var Z_SYNC_FLUSH = 2;
  19961. //var Z_FULL_FLUSH = 3;
  19962. var Z_FINISH = 4;
  19963. var Z_BLOCK = 5;
  19964. var Z_TREES = 6;
  19965. /* Return codes for the compression/decompression functions. Negative values
  19966. * are errors, positive values are used for special but normal events.
  19967. */
  19968. var Z_OK = 0;
  19969. var Z_STREAM_END = 1;
  19970. var Z_NEED_DICT = 2;
  19971. //var Z_ERRNO = -1;
  19972. var Z_STREAM_ERROR = -2;
  19973. var Z_DATA_ERROR = -3;
  19974. var Z_MEM_ERROR = -4;
  19975. var Z_BUF_ERROR = -5;
  19976. //var Z_VERSION_ERROR = -6;
  19977. /* The deflate compression method */
  19978. var Z_DEFLATED = 8;
  19979. /* STATES ====================================================================*/
  19980. /* ===========================================================================*/
  19981. var HEAD = 1; /* i: waiting for magic header */
  19982. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  19983. var TIME = 3; /* i: waiting for modification time (gzip) */
  19984. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  19985. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  19986. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  19987. var NAME = 7; /* i: waiting for end of file name (gzip) */
  19988. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  19989. var HCRC = 9; /* i: waiting for header crc (gzip) */
  19990. var DICTID = 10; /* i: waiting for dictionary check value */
  19991. var DICT = 11; /* waiting for inflateSetDictionary() call */
  19992. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19993. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  19994. var STORED = 14; /* i: waiting for stored size (length and complement) */
  19995. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  19996. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  19997. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  19998. var LENLENS = 18; /* i: waiting for code length code lengths */
  19999. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  20000. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  20001. var LEN = 21; /* i: waiting for length/lit/eob code */
  20002. var LENEXT = 22; /* i: waiting for length extra bits */
  20003. var DIST = 23; /* i: waiting for distance code */
  20004. var DISTEXT = 24; /* i: waiting for distance extra bits */
  20005. var MATCH = 25; /* o: waiting for output space to copy string */
  20006. var LIT = 26; /* o: waiting for output space to write literal */
  20007. var CHECK = 27; /* i: waiting for 32-bit check value */
  20008. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  20009. var DONE = 29; /* finished check, done -- remain here until reset */
  20010. var BAD = 30; /* got a data error -- remain here until reset */
  20011. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  20012. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  20013. /* ===========================================================================*/
  20014. var ENOUGH_LENS = 852;
  20015. var ENOUGH_DISTS = 592;
  20016. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  20017. var MAX_WBITS = 15;
  20018. /* 32K LZ77 window */
  20019. var DEF_WBITS = MAX_WBITS;
  20020. function ZSWAP32(q) {
  20021. return (((q >>> 24) & 0xff) +
  20022. ((q >>> 8) & 0xff00) +
  20023. ((q & 0xff00) << 8) +
  20024. ((q & 0xff) << 24));
  20025. }
  20026. function InflateState() {
  20027. this.mode = 0; /* current inflate mode */
  20028. this.last = false; /* true if processing last block */
  20029. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  20030. this.havedict = false; /* true if dictionary provided */
  20031. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  20032. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  20033. this.check = 0; /* protected copy of check value */
  20034. this.total = 0; /* protected copy of output count */
  20035. // TODO: may be {}
  20036. this.head = null; /* where to save gzip header information */
  20037. /* sliding window */
  20038. this.wbits = 0; /* log base 2 of requested window size */
  20039. this.wsize = 0; /* window size or zero if not using window */
  20040. this.whave = 0; /* valid bytes in the window */
  20041. this.wnext = 0; /* window write index */
  20042. this.window = null; /* allocated sliding window, if needed */
  20043. /* bit accumulator */
  20044. this.hold = 0; /* input bit accumulator */
  20045. this.bits = 0; /* number of bits in "in" */
  20046. /* for string and stored block copying */
  20047. this.length = 0; /* literal or length of data to copy */
  20048. this.offset = 0; /* distance back to copy string from */
  20049. /* for table and code decoding */
  20050. this.extra = 0; /* extra bits needed */
  20051. /* fixed and dynamic code tables */
  20052. this.lencode = null; /* starting table for length/literal codes */
  20053. this.distcode = null; /* starting table for distance codes */
  20054. this.lenbits = 0; /* index bits for lencode */
  20055. this.distbits = 0; /* index bits for distcode */
  20056. /* dynamic table building */
  20057. this.ncode = 0; /* number of code length code lengths */
  20058. this.nlen = 0; /* number of length code lengths */
  20059. this.ndist = 0; /* number of distance code lengths */
  20060. this.have = 0; /* number of code lengths in lens[] */
  20061. this.next = null; /* next available space in codes[] */
  20062. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  20063. this.work = new utils.Buf16(288); /* work area for code table building */
  20064. /*
  20065. because we don't have pointers in js, we use lencode and distcode directly
  20066. as buffers so we don't need codes
  20067. */
  20068. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  20069. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  20070. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  20071. this.sane = 0; /* if false, allow invalid distance too far */
  20072. this.back = 0; /* bits back of last unprocessed length/lit */
  20073. this.was = 0; /* initial length of match */
  20074. }
  20075. function inflateResetKeep(strm) {
  20076. var state;
  20077. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20078. state = strm.state;
  20079. strm.total_in = strm.total_out = state.total = 0;
  20080. strm.msg = ''; /*Z_NULL*/
  20081. if (state.wrap) { /* to support ill-conceived Java test suite */
  20082. strm.adler = state.wrap & 1;
  20083. }
  20084. state.mode = HEAD;
  20085. state.last = 0;
  20086. state.havedict = 0;
  20087. state.dmax = 32768;
  20088. state.head = null/*Z_NULL*/;
  20089. state.hold = 0;
  20090. state.bits = 0;
  20091. //state.lencode = state.distcode = state.next = state.codes;
  20092. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  20093. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  20094. state.sane = 1;
  20095. state.back = -1;
  20096. //Tracev((stderr, "inflate: reset\n"));
  20097. return Z_OK;
  20098. }
  20099. function inflateReset(strm) {
  20100. var state;
  20101. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20102. state = strm.state;
  20103. state.wsize = 0;
  20104. state.whave = 0;
  20105. state.wnext = 0;
  20106. return inflateResetKeep(strm);
  20107. }
  20108. function inflateReset2(strm, windowBits) {
  20109. var wrap;
  20110. var state;
  20111. /* get the state */
  20112. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20113. state = strm.state;
  20114. /* extract wrap request from windowBits parameter */
  20115. if (windowBits < 0) {
  20116. wrap = 0;
  20117. windowBits = -windowBits;
  20118. }
  20119. else {
  20120. wrap = (windowBits >> 4) + 1;
  20121. if (windowBits < 48) {
  20122. windowBits &= 15;
  20123. }
  20124. }
  20125. /* set number of window bits, free window if different */
  20126. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  20127. return Z_STREAM_ERROR;
  20128. }
  20129. if (state.window !== null && state.wbits !== windowBits) {
  20130. state.window = null;
  20131. }
  20132. /* update state and reset the rest of it */
  20133. state.wrap = wrap;
  20134. state.wbits = windowBits;
  20135. return inflateReset(strm);
  20136. }
  20137. function inflateInit2(strm, windowBits) {
  20138. var ret;
  20139. var state;
  20140. if (!strm) { return Z_STREAM_ERROR; }
  20141. //strm.msg = Z_NULL; /* in case we return an error */
  20142. state = new InflateState();
  20143. //if (state === Z_NULL) return Z_MEM_ERROR;
  20144. //Tracev((stderr, "inflate: allocated\n"));
  20145. strm.state = state;
  20146. state.window = null/*Z_NULL*/;
  20147. ret = inflateReset2(strm, windowBits);
  20148. if (ret !== Z_OK) {
  20149. strm.state = null/*Z_NULL*/;
  20150. }
  20151. return ret;
  20152. }
  20153. function inflateInit(strm) {
  20154. return inflateInit2(strm, DEF_WBITS);
  20155. }
  20156. /*
  20157. Return state with length and distance decoding tables and index sizes set to
  20158. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  20159. If BUILDFIXED is defined, then instead this routine builds the tables the
  20160. first time it's called, and returns those tables the first time and
  20161. thereafter. This reduces the size of the code by about 2K bytes, in
  20162. exchange for a little execution time. However, BUILDFIXED should not be
  20163. used for threaded applications, since the rewriting of the tables and virgin
  20164. may not be thread-safe.
  20165. */
  20166. var virgin = true;
  20167. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  20168. function fixedtables(state) {
  20169. /* build fixed huffman tables if first call (may not be thread safe) */
  20170. if (virgin) {
  20171. var sym;
  20172. lenfix = new utils.Buf32(512);
  20173. distfix = new utils.Buf32(32);
  20174. /* literal/length table */
  20175. sym = 0;
  20176. while (sym < 144) { state.lens[sym++] = 8; }
  20177. while (sym < 256) { state.lens[sym++] = 9; }
  20178. while (sym < 280) { state.lens[sym++] = 7; }
  20179. while (sym < 288) { state.lens[sym++] = 8; }
  20180. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  20181. /* distance table */
  20182. sym = 0;
  20183. while (sym < 32) { state.lens[sym++] = 5; }
  20184. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  20185. /* do this just once */
  20186. virgin = false;
  20187. }
  20188. state.lencode = lenfix;
  20189. state.lenbits = 9;
  20190. state.distcode = distfix;
  20191. state.distbits = 5;
  20192. }
  20193. /*
  20194. Update the window with the last wsize (normally 32K) bytes written before
  20195. returning. If window does not exist yet, create it. This is only called
  20196. when a window is already in use, or when output has been written during this
  20197. inflate call, but the end of the deflate stream has not been reached yet.
  20198. It is also called to create a window for dictionary data when a dictionary
  20199. is loaded.
  20200. Providing output buffers larger than 32K to inflate() should provide a speed
  20201. advantage, since only the last 32K of output is copied to the sliding window
  20202. upon return from inflate(), and since all distances after the first 32K of
  20203. output will fall in the output data, making match copies simpler and faster.
  20204. The advantage may be dependent on the size of the processor's data caches.
  20205. */
  20206. function updatewindow(strm, src, end, copy) {
  20207. var dist;
  20208. var state = strm.state;
  20209. /* if it hasn't been done already, allocate space for the window */
  20210. if (state.window === null) {
  20211. state.wsize = 1 << state.wbits;
  20212. state.wnext = 0;
  20213. state.whave = 0;
  20214. state.window = new utils.Buf8(state.wsize);
  20215. }
  20216. /* copy state->wsize or less output bytes into the circular window */
  20217. if (copy >= state.wsize) {
  20218. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  20219. state.wnext = 0;
  20220. state.whave = state.wsize;
  20221. }
  20222. else {
  20223. dist = state.wsize - state.wnext;
  20224. if (dist > copy) {
  20225. dist = copy;
  20226. }
  20227. //zmemcpy(state->window + state->wnext, end - copy, dist);
  20228. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  20229. copy -= dist;
  20230. if (copy) {
  20231. //zmemcpy(state->window, end - copy, copy);
  20232. utils.arraySet(state.window,src, end - copy, copy, 0);
  20233. state.wnext = copy;
  20234. state.whave = state.wsize;
  20235. }
  20236. else {
  20237. state.wnext += dist;
  20238. if (state.wnext === state.wsize) { state.wnext = 0; }
  20239. if (state.whave < state.wsize) { state.whave += dist; }
  20240. }
  20241. }
  20242. return 0;
  20243. }
  20244. function inflate(strm, flush) {
  20245. var state;
  20246. var input, output; // input/output buffers
  20247. var next; /* next input INDEX */
  20248. var put; /* next output INDEX */
  20249. var have, left; /* available input and output */
  20250. var hold; /* bit buffer */
  20251. var bits; /* bits in bit buffer */
  20252. var _in, _out; /* save starting available input and output */
  20253. var copy; /* number of stored or match bytes to copy */
  20254. var from; /* where to copy match bytes from */
  20255. var from_source;
  20256. var here = 0; /* current decoding table entry */
  20257. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  20258. //var last; /* parent table entry */
  20259. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  20260. var len; /* length to copy for repeats, bits to drop */
  20261. var ret; /* return code */
  20262. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  20263. var opts;
  20264. var n; // temporary var for NEED_BITS
  20265. var order = /* permutation of code lengths */
  20266. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  20267. if (!strm || !strm.state || !strm.output ||
  20268. (!strm.input && strm.avail_in !== 0)) {
  20269. return Z_STREAM_ERROR;
  20270. }
  20271. state = strm.state;
  20272. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  20273. //--- LOAD() ---
  20274. put = strm.next_out;
  20275. output = strm.output;
  20276. left = strm.avail_out;
  20277. next = strm.next_in;
  20278. input = strm.input;
  20279. have = strm.avail_in;
  20280. hold = state.hold;
  20281. bits = state.bits;
  20282. //---
  20283. _in = have;
  20284. _out = left;
  20285. ret = Z_OK;
  20286. inf_leave: // goto emulation
  20287. for (;;) {
  20288. switch (state.mode) {
  20289. case HEAD:
  20290. if (state.wrap === 0) {
  20291. state.mode = TYPEDO;
  20292. break;
  20293. }
  20294. //=== NEEDBITS(16);
  20295. while (bits < 16) {
  20296. if (have === 0) { break inf_leave; }
  20297. have--;
  20298. hold += input[next++] << bits;
  20299. bits += 8;
  20300. }
  20301. //===//
  20302. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  20303. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  20304. //=== CRC2(state.check, hold);
  20305. hbuf[0] = hold & 0xff;
  20306. hbuf[1] = (hold >>> 8) & 0xff;
  20307. state.check = crc32(state.check, hbuf, 2, 0);
  20308. //===//
  20309. //=== INITBITS();
  20310. hold = 0;
  20311. bits = 0;
  20312. //===//
  20313. state.mode = FLAGS;
  20314. break;
  20315. }
  20316. state.flags = 0; /* expect zlib header */
  20317. if (state.head) {
  20318. state.head.done = false;
  20319. }
  20320. if (!(state.wrap & 1) || /* check if zlib header allowed */
  20321. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  20322. strm.msg = 'incorrect header check';
  20323. state.mode = BAD;
  20324. break;
  20325. }
  20326. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  20327. strm.msg = 'unknown compression method';
  20328. state.mode = BAD;
  20329. break;
  20330. }
  20331. //--- DROPBITS(4) ---//
  20332. hold >>>= 4;
  20333. bits -= 4;
  20334. //---//
  20335. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  20336. if (state.wbits === 0) {
  20337. state.wbits = len;
  20338. }
  20339. else if (len > state.wbits) {
  20340. strm.msg = 'invalid window size';
  20341. state.mode = BAD;
  20342. break;
  20343. }
  20344. state.dmax = 1 << len;
  20345. //Tracev((stderr, "inflate: zlib header ok\n"));
  20346. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20347. state.mode = hold & 0x200 ? DICTID : TYPE;
  20348. //=== INITBITS();
  20349. hold = 0;
  20350. bits = 0;
  20351. //===//
  20352. break;
  20353. case FLAGS:
  20354. //=== NEEDBITS(16); */
  20355. while (bits < 16) {
  20356. if (have === 0) { break inf_leave; }
  20357. have--;
  20358. hold += input[next++] << bits;
  20359. bits += 8;
  20360. }
  20361. //===//
  20362. state.flags = hold;
  20363. if ((state.flags & 0xff) !== Z_DEFLATED) {
  20364. strm.msg = 'unknown compression method';
  20365. state.mode = BAD;
  20366. break;
  20367. }
  20368. if (state.flags & 0xe000) {
  20369. strm.msg = 'unknown header flags set';
  20370. state.mode = BAD;
  20371. break;
  20372. }
  20373. if (state.head) {
  20374. state.head.text = ((hold >> 8) & 1);
  20375. }
  20376. if (state.flags & 0x0200) {
  20377. //=== CRC2(state.check, hold);
  20378. hbuf[0] = hold & 0xff;
  20379. hbuf[1] = (hold >>> 8) & 0xff;
  20380. state.check = crc32(state.check, hbuf, 2, 0);
  20381. //===//
  20382. }
  20383. //=== INITBITS();
  20384. hold = 0;
  20385. bits = 0;
  20386. //===//
  20387. state.mode = TIME;
  20388. /* falls through */
  20389. case TIME:
  20390. //=== NEEDBITS(32); */
  20391. while (bits < 32) {
  20392. if (have === 0) { break inf_leave; }
  20393. have--;
  20394. hold += input[next++] << bits;
  20395. bits += 8;
  20396. }
  20397. //===//
  20398. if (state.head) {
  20399. state.head.time = hold;
  20400. }
  20401. if (state.flags & 0x0200) {
  20402. //=== CRC4(state.check, hold)
  20403. hbuf[0] = hold & 0xff;
  20404. hbuf[1] = (hold >>> 8) & 0xff;
  20405. hbuf[2] = (hold >>> 16) & 0xff;
  20406. hbuf[3] = (hold >>> 24) & 0xff;
  20407. state.check = crc32(state.check, hbuf, 4, 0);
  20408. //===
  20409. }
  20410. //=== INITBITS();
  20411. hold = 0;
  20412. bits = 0;
  20413. //===//
  20414. state.mode = OS;
  20415. /* falls through */
  20416. case OS:
  20417. //=== NEEDBITS(16); */
  20418. while (bits < 16) {
  20419. if (have === 0) { break inf_leave; }
  20420. have--;
  20421. hold += input[next++] << bits;
  20422. bits += 8;
  20423. }
  20424. //===//
  20425. if (state.head) {
  20426. state.head.xflags = (hold & 0xff);
  20427. state.head.os = (hold >> 8);
  20428. }
  20429. if (state.flags & 0x0200) {
  20430. //=== CRC2(state.check, hold);
  20431. hbuf[0] = hold & 0xff;
  20432. hbuf[1] = (hold >>> 8) & 0xff;
  20433. state.check = crc32(state.check, hbuf, 2, 0);
  20434. //===//
  20435. }
  20436. //=== INITBITS();
  20437. hold = 0;
  20438. bits = 0;
  20439. //===//
  20440. state.mode = EXLEN;
  20441. /* falls through */
  20442. case EXLEN:
  20443. if (state.flags & 0x0400) {
  20444. //=== NEEDBITS(16); */
  20445. while (bits < 16) {
  20446. if (have === 0) { break inf_leave; }
  20447. have--;
  20448. hold += input[next++] << bits;
  20449. bits += 8;
  20450. }
  20451. //===//
  20452. state.length = hold;
  20453. if (state.head) {
  20454. state.head.extra_len = hold;
  20455. }
  20456. if (state.flags & 0x0200) {
  20457. //=== CRC2(state.check, hold);
  20458. hbuf[0] = hold & 0xff;
  20459. hbuf[1] = (hold >>> 8) & 0xff;
  20460. state.check = crc32(state.check, hbuf, 2, 0);
  20461. //===//
  20462. }
  20463. //=== INITBITS();
  20464. hold = 0;
  20465. bits = 0;
  20466. //===//
  20467. }
  20468. else if (state.head) {
  20469. state.head.extra = null/*Z_NULL*/;
  20470. }
  20471. state.mode = EXTRA;
  20472. /* falls through */
  20473. case EXTRA:
  20474. if (state.flags & 0x0400) {
  20475. copy = state.length;
  20476. if (copy > have) { copy = have; }
  20477. if (copy) {
  20478. if (state.head) {
  20479. len = state.head.extra_len - state.length;
  20480. if (!state.head.extra) {
  20481. // Use untyped array for more conveniend processing later
  20482. state.head.extra = new Array(state.head.extra_len);
  20483. }
  20484. utils.arraySet(
  20485. state.head.extra,
  20486. input,
  20487. next,
  20488. // extra field is limited to 65536 bytes
  20489. // - no need for additional size check
  20490. copy,
  20491. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  20492. len
  20493. );
  20494. //zmemcpy(state.head.extra + len, next,
  20495. // len + copy > state.head.extra_max ?
  20496. // state.head.extra_max - len : copy);
  20497. }
  20498. if (state.flags & 0x0200) {
  20499. state.check = crc32(state.check, input, copy, next);
  20500. }
  20501. have -= copy;
  20502. next += copy;
  20503. state.length -= copy;
  20504. }
  20505. if (state.length) { break inf_leave; }
  20506. }
  20507. state.length = 0;
  20508. state.mode = NAME;
  20509. /* falls through */
  20510. case NAME:
  20511. if (state.flags & 0x0800) {
  20512. if (have === 0) { break inf_leave; }
  20513. copy = 0;
  20514. do {
  20515. // TODO: 2 or 1 bytes?
  20516. len = input[next + copy++];
  20517. /* use constant limit because in js we should not preallocate memory */
  20518. if (state.head && len &&
  20519. (state.length < 65536 /*state.head.name_max*/)) {
  20520. state.head.name += String.fromCharCode(len);
  20521. }
  20522. } while (len && copy < have);
  20523. if (state.flags & 0x0200) {
  20524. state.check = crc32(state.check, input, copy, next);
  20525. }
  20526. have -= copy;
  20527. next += copy;
  20528. if (len) { break inf_leave; }
  20529. }
  20530. else if (state.head) {
  20531. state.head.name = null;
  20532. }
  20533. state.length = 0;
  20534. state.mode = COMMENT;
  20535. /* falls through */
  20536. case COMMENT:
  20537. if (state.flags & 0x1000) {
  20538. if (have === 0) { break inf_leave; }
  20539. copy = 0;
  20540. do {
  20541. len = input[next + copy++];
  20542. /* use constant limit because in js we should not preallocate memory */
  20543. if (state.head && len &&
  20544. (state.length < 65536 /*state.head.comm_max*/)) {
  20545. state.head.comment += String.fromCharCode(len);
  20546. }
  20547. } while (len && copy < have);
  20548. if (state.flags & 0x0200) {
  20549. state.check = crc32(state.check, input, copy, next);
  20550. }
  20551. have -= copy;
  20552. next += copy;
  20553. if (len) { break inf_leave; }
  20554. }
  20555. else if (state.head) {
  20556. state.head.comment = null;
  20557. }
  20558. state.mode = HCRC;
  20559. /* falls through */
  20560. case HCRC:
  20561. if (state.flags & 0x0200) {
  20562. //=== NEEDBITS(16); */
  20563. while (bits < 16) {
  20564. if (have === 0) { break inf_leave; }
  20565. have--;
  20566. hold += input[next++] << bits;
  20567. bits += 8;
  20568. }
  20569. //===//
  20570. if (hold !== (state.check & 0xffff)) {
  20571. strm.msg = 'header crc mismatch';
  20572. state.mode = BAD;
  20573. break;
  20574. }
  20575. //=== INITBITS();
  20576. hold = 0;
  20577. bits = 0;
  20578. //===//
  20579. }
  20580. if (state.head) {
  20581. state.head.hcrc = ((state.flags >> 9) & 1);
  20582. state.head.done = true;
  20583. }
  20584. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  20585. state.mode = TYPE;
  20586. break;
  20587. case DICTID:
  20588. //=== NEEDBITS(32); */
  20589. while (bits < 32) {
  20590. if (have === 0) { break inf_leave; }
  20591. have--;
  20592. hold += input[next++] << bits;
  20593. bits += 8;
  20594. }
  20595. //===//
  20596. strm.adler = state.check = ZSWAP32(hold);
  20597. //=== INITBITS();
  20598. hold = 0;
  20599. bits = 0;
  20600. //===//
  20601. state.mode = DICT;
  20602. /* falls through */
  20603. case DICT:
  20604. if (state.havedict === 0) {
  20605. //--- RESTORE() ---
  20606. strm.next_out = put;
  20607. strm.avail_out = left;
  20608. strm.next_in = next;
  20609. strm.avail_in = have;
  20610. state.hold = hold;
  20611. state.bits = bits;
  20612. //---
  20613. return Z_NEED_DICT;
  20614. }
  20615. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20616. state.mode = TYPE;
  20617. /* falls through */
  20618. case TYPE:
  20619. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  20620. /* falls through */
  20621. case TYPEDO:
  20622. if (state.last) {
  20623. //--- BYTEBITS() ---//
  20624. hold >>>= bits & 7;
  20625. bits -= bits & 7;
  20626. //---//
  20627. state.mode = CHECK;
  20628. break;
  20629. }
  20630. //=== NEEDBITS(3); */
  20631. while (bits < 3) {
  20632. if (have === 0) { break inf_leave; }
  20633. have--;
  20634. hold += input[next++] << bits;
  20635. bits += 8;
  20636. }
  20637. //===//
  20638. state.last = (hold & 0x01)/*BITS(1)*/;
  20639. //--- DROPBITS(1) ---//
  20640. hold >>>= 1;
  20641. bits -= 1;
  20642. //---//
  20643. switch ((hold & 0x03)/*BITS(2)*/) {
  20644. case 0: /* stored block */
  20645. //Tracev((stderr, "inflate: stored block%s\n",
  20646. // state.last ? " (last)" : ""));
  20647. state.mode = STORED;
  20648. break;
  20649. case 1: /* fixed block */
  20650. fixedtables(state);
  20651. //Tracev((stderr, "inflate: fixed codes block%s\n",
  20652. // state.last ? " (last)" : ""));
  20653. state.mode = LEN_; /* decode codes */
  20654. if (flush === Z_TREES) {
  20655. //--- DROPBITS(2) ---//
  20656. hold >>>= 2;
  20657. bits -= 2;
  20658. //---//
  20659. break inf_leave;
  20660. }
  20661. break;
  20662. case 2: /* dynamic block */
  20663. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  20664. // state.last ? " (last)" : ""));
  20665. state.mode = TABLE;
  20666. break;
  20667. case 3:
  20668. strm.msg = 'invalid block type';
  20669. state.mode = BAD;
  20670. }
  20671. //--- DROPBITS(2) ---//
  20672. hold >>>= 2;
  20673. bits -= 2;
  20674. //---//
  20675. break;
  20676. case STORED:
  20677. //--- BYTEBITS() ---// /* go to byte boundary */
  20678. hold >>>= bits & 7;
  20679. bits -= bits & 7;
  20680. //---//
  20681. //=== NEEDBITS(32); */
  20682. while (bits < 32) {
  20683. if (have === 0) { break inf_leave; }
  20684. have--;
  20685. hold += input[next++] << bits;
  20686. bits += 8;
  20687. }
  20688. //===//
  20689. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  20690. strm.msg = 'invalid stored block lengths';
  20691. state.mode = BAD;
  20692. break;
  20693. }
  20694. state.length = hold & 0xffff;
  20695. //Tracev((stderr, "inflate: stored length %u\n",
  20696. // state.length));
  20697. //=== INITBITS();
  20698. hold = 0;
  20699. bits = 0;
  20700. //===//
  20701. state.mode = COPY_;
  20702. if (flush === Z_TREES) { break inf_leave; }
  20703. /* falls through */
  20704. case COPY_:
  20705. state.mode = COPY;
  20706. /* falls through */
  20707. case COPY:
  20708. copy = state.length;
  20709. if (copy) {
  20710. if (copy > have) { copy = have; }
  20711. if (copy > left) { copy = left; }
  20712. if (copy === 0) { break inf_leave; }
  20713. //--- zmemcpy(put, next, copy); ---
  20714. utils.arraySet(output, input, next, copy, put);
  20715. //---//
  20716. have -= copy;
  20717. next += copy;
  20718. left -= copy;
  20719. put += copy;
  20720. state.length -= copy;
  20721. break;
  20722. }
  20723. //Tracev((stderr, "inflate: stored end\n"));
  20724. state.mode = TYPE;
  20725. break;
  20726. case TABLE:
  20727. //=== NEEDBITS(14); */
  20728. while (bits < 14) {
  20729. if (have === 0) { break inf_leave; }
  20730. have--;
  20731. hold += input[next++] << bits;
  20732. bits += 8;
  20733. }
  20734. //===//
  20735. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  20736. //--- DROPBITS(5) ---//
  20737. hold >>>= 5;
  20738. bits -= 5;
  20739. //---//
  20740. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  20741. //--- DROPBITS(5) ---//
  20742. hold >>>= 5;
  20743. bits -= 5;
  20744. //---//
  20745. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  20746. //--- DROPBITS(4) ---//
  20747. hold >>>= 4;
  20748. bits -= 4;
  20749. //---//
  20750. //#ifndef PKZIP_BUG_WORKAROUND
  20751. if (state.nlen > 286 || state.ndist > 30) {
  20752. strm.msg = 'too many length or distance symbols';
  20753. state.mode = BAD;
  20754. break;
  20755. }
  20756. //#endif
  20757. //Tracev((stderr, "inflate: table sizes ok\n"));
  20758. state.have = 0;
  20759. state.mode = LENLENS;
  20760. /* falls through */
  20761. case LENLENS:
  20762. while (state.have < state.ncode) {
  20763. //=== NEEDBITS(3);
  20764. while (bits < 3) {
  20765. if (have === 0) { break inf_leave; }
  20766. have--;
  20767. hold += input[next++] << bits;
  20768. bits += 8;
  20769. }
  20770. //===//
  20771. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  20772. //--- DROPBITS(3) ---//
  20773. hold >>>= 3;
  20774. bits -= 3;
  20775. //---//
  20776. }
  20777. while (state.have < 19) {
  20778. state.lens[order[state.have++]] = 0;
  20779. }
  20780. // We have separate tables & no pointers. 2 commented lines below not needed.
  20781. //state.next = state.codes;
  20782. //state.lencode = state.next;
  20783. // Switch to use dynamic table
  20784. state.lencode = state.lendyn;
  20785. state.lenbits = 7;
  20786. opts = {bits: state.lenbits};
  20787. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  20788. state.lenbits = opts.bits;
  20789. if (ret) {
  20790. strm.msg = 'invalid code lengths set';
  20791. state.mode = BAD;
  20792. break;
  20793. }
  20794. //Tracev((stderr, "inflate: code lengths ok\n"));
  20795. state.have = 0;
  20796. state.mode = CODELENS;
  20797. /* falls through */
  20798. case CODELENS:
  20799. while (state.have < state.nlen + state.ndist) {
  20800. for (;;) {
  20801. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  20802. here_bits = here >>> 24;
  20803. here_op = (here >>> 16) & 0xff;
  20804. here_val = here & 0xffff;
  20805. if ((here_bits) <= bits) { break; }
  20806. //--- PULLBYTE() ---//
  20807. if (have === 0) { break inf_leave; }
  20808. have--;
  20809. hold += input[next++] << bits;
  20810. bits += 8;
  20811. //---//
  20812. }
  20813. if (here_val < 16) {
  20814. //--- DROPBITS(here.bits) ---//
  20815. hold >>>= here_bits;
  20816. bits -= here_bits;
  20817. //---//
  20818. state.lens[state.have++] = here_val;
  20819. }
  20820. else {
  20821. if (here_val === 16) {
  20822. //=== NEEDBITS(here.bits + 2);
  20823. n = here_bits + 2;
  20824. while (bits < n) {
  20825. if (have === 0) { break inf_leave; }
  20826. have--;
  20827. hold += input[next++] << bits;
  20828. bits += 8;
  20829. }
  20830. //===//
  20831. //--- DROPBITS(here.bits) ---//
  20832. hold >>>= here_bits;
  20833. bits -= here_bits;
  20834. //---//
  20835. if (state.have === 0) {
  20836. strm.msg = 'invalid bit length repeat';
  20837. state.mode = BAD;
  20838. break;
  20839. }
  20840. len = state.lens[state.have - 1];
  20841. copy = 3 + (hold & 0x03);//BITS(2);
  20842. //--- DROPBITS(2) ---//
  20843. hold >>>= 2;
  20844. bits -= 2;
  20845. //---//
  20846. }
  20847. else if (here_val === 17) {
  20848. //=== NEEDBITS(here.bits + 3);
  20849. n = here_bits + 3;
  20850. while (bits < n) {
  20851. if (have === 0) { break inf_leave; }
  20852. have--;
  20853. hold += input[next++] << bits;
  20854. bits += 8;
  20855. }
  20856. //===//
  20857. //--- DROPBITS(here.bits) ---//
  20858. hold >>>= here_bits;
  20859. bits -= here_bits;
  20860. //---//
  20861. len = 0;
  20862. copy = 3 + (hold & 0x07);//BITS(3);
  20863. //--- DROPBITS(3) ---//
  20864. hold >>>= 3;
  20865. bits -= 3;
  20866. //---//
  20867. }
  20868. else {
  20869. //=== NEEDBITS(here.bits + 7);
  20870. n = here_bits + 7;
  20871. while (bits < n) {
  20872. if (have === 0) { break inf_leave; }
  20873. have--;
  20874. hold += input[next++] << bits;
  20875. bits += 8;
  20876. }
  20877. //===//
  20878. //--- DROPBITS(here.bits) ---//
  20879. hold >>>= here_bits;
  20880. bits -= here_bits;
  20881. //---//
  20882. len = 0;
  20883. copy = 11 + (hold & 0x7f);//BITS(7);
  20884. //--- DROPBITS(7) ---//
  20885. hold >>>= 7;
  20886. bits -= 7;
  20887. //---//
  20888. }
  20889. if (state.have + copy > state.nlen + state.ndist) {
  20890. strm.msg = 'invalid bit length repeat';
  20891. state.mode = BAD;
  20892. break;
  20893. }
  20894. while (copy--) {
  20895. state.lens[state.have++] = len;
  20896. }
  20897. }
  20898. }
  20899. /* handle error breaks in while */
  20900. if (state.mode === BAD) { break; }
  20901. /* check for end-of-block code (better have one) */
  20902. if (state.lens[256] === 0) {
  20903. strm.msg = 'invalid code -- missing end-of-block';
  20904. state.mode = BAD;
  20905. break;
  20906. }
  20907. /* build code tables -- note: do not change the lenbits or distbits
  20908. values here (9 and 6) without reading the comments in inftrees.h
  20909. concerning the ENOUGH constants, which depend on those values */
  20910. state.lenbits = 9;
  20911. opts = {bits: state.lenbits};
  20912. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  20913. // We have separate tables & no pointers. 2 commented lines below not needed.
  20914. // state.next_index = opts.table_index;
  20915. state.lenbits = opts.bits;
  20916. // state.lencode = state.next;
  20917. if (ret) {
  20918. strm.msg = 'invalid literal/lengths set';
  20919. state.mode = BAD;
  20920. break;
  20921. }
  20922. state.distbits = 6;
  20923. //state.distcode.copy(state.codes);
  20924. // Switch to use dynamic table
  20925. state.distcode = state.distdyn;
  20926. opts = {bits: state.distbits};
  20927. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  20928. // We have separate tables & no pointers. 2 commented lines below not needed.
  20929. // state.next_index = opts.table_index;
  20930. state.distbits = opts.bits;
  20931. // state.distcode = state.next;
  20932. if (ret) {
  20933. strm.msg = 'invalid distances set';
  20934. state.mode = BAD;
  20935. break;
  20936. }
  20937. //Tracev((stderr, 'inflate: codes ok\n'));
  20938. state.mode = LEN_;
  20939. if (flush === Z_TREES) { break inf_leave; }
  20940. /* falls through */
  20941. case LEN_:
  20942. state.mode = LEN;
  20943. /* falls through */
  20944. case LEN:
  20945. if (have >= 6 && left >= 258) {
  20946. //--- RESTORE() ---
  20947. strm.next_out = put;
  20948. strm.avail_out = left;
  20949. strm.next_in = next;
  20950. strm.avail_in = have;
  20951. state.hold = hold;
  20952. state.bits = bits;
  20953. //---
  20954. inflate_fast(strm, _out);
  20955. //--- LOAD() ---
  20956. put = strm.next_out;
  20957. output = strm.output;
  20958. left = strm.avail_out;
  20959. next = strm.next_in;
  20960. input = strm.input;
  20961. have = strm.avail_in;
  20962. hold = state.hold;
  20963. bits = state.bits;
  20964. //---
  20965. if (state.mode === TYPE) {
  20966. state.back = -1;
  20967. }
  20968. break;
  20969. }
  20970. state.back = 0;
  20971. for (;;) {
  20972. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  20973. here_bits = here >>> 24;
  20974. here_op = (here >>> 16) & 0xff;
  20975. here_val = here & 0xffff;
  20976. if (here_bits <= bits) { break; }
  20977. //--- PULLBYTE() ---//
  20978. if (have === 0) { break inf_leave; }
  20979. have--;
  20980. hold += input[next++] << bits;
  20981. bits += 8;
  20982. //---//
  20983. }
  20984. if (here_op && (here_op & 0xf0) === 0) {
  20985. last_bits = here_bits;
  20986. last_op = here_op;
  20987. last_val = here_val;
  20988. for (;;) {
  20989. here = state.lencode[last_val +
  20990. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20991. here_bits = here >>> 24;
  20992. here_op = (here >>> 16) & 0xff;
  20993. here_val = here & 0xffff;
  20994. if ((last_bits + here_bits) <= bits) { break; }
  20995. //--- PULLBYTE() ---//
  20996. if (have === 0) { break inf_leave; }
  20997. have--;
  20998. hold += input[next++] << bits;
  20999. bits += 8;
  21000. //---//
  21001. }
  21002. //--- DROPBITS(last.bits) ---//
  21003. hold >>>= last_bits;
  21004. bits -= last_bits;
  21005. //---//
  21006. state.back += last_bits;
  21007. }
  21008. //--- DROPBITS(here.bits) ---//
  21009. hold >>>= here_bits;
  21010. bits -= here_bits;
  21011. //---//
  21012. state.back += here_bits;
  21013. state.length = here_val;
  21014. if (here_op === 0) {
  21015. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  21016. // "inflate: literal '%c'\n" :
  21017. // "inflate: literal 0x%02x\n", here.val));
  21018. state.mode = LIT;
  21019. break;
  21020. }
  21021. if (here_op & 32) {
  21022. //Tracevv((stderr, "inflate: end of block\n"));
  21023. state.back = -1;
  21024. state.mode = TYPE;
  21025. break;
  21026. }
  21027. if (here_op & 64) {
  21028. strm.msg = 'invalid literal/length code';
  21029. state.mode = BAD;
  21030. break;
  21031. }
  21032. state.extra = here_op & 15;
  21033. state.mode = LENEXT;
  21034. /* falls through */
  21035. case LENEXT:
  21036. if (state.extra) {
  21037. //=== NEEDBITS(state.extra);
  21038. n = state.extra;
  21039. while (bits < n) {
  21040. if (have === 0) { break inf_leave; }
  21041. have--;
  21042. hold += input[next++] << bits;
  21043. bits += 8;
  21044. }
  21045. //===//
  21046. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  21047. //--- DROPBITS(state.extra) ---//
  21048. hold >>>= state.extra;
  21049. bits -= state.extra;
  21050. //---//
  21051. state.back += state.extra;
  21052. }
  21053. //Tracevv((stderr, "inflate: length %u\n", state.length));
  21054. state.was = state.length;
  21055. state.mode = DIST;
  21056. /* falls through */
  21057. case DIST:
  21058. for (;;) {
  21059. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  21060. here_bits = here >>> 24;
  21061. here_op = (here >>> 16) & 0xff;
  21062. here_val = here & 0xffff;
  21063. if ((here_bits) <= bits) { break; }
  21064. //--- PULLBYTE() ---//
  21065. if (have === 0) { break inf_leave; }
  21066. have--;
  21067. hold += input[next++] << bits;
  21068. bits += 8;
  21069. //---//
  21070. }
  21071. if ((here_op & 0xf0) === 0) {
  21072. last_bits = here_bits;
  21073. last_op = here_op;
  21074. last_val = here_val;
  21075. for (;;) {
  21076. here = state.distcode[last_val +
  21077. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  21078. here_bits = here >>> 24;
  21079. here_op = (here >>> 16) & 0xff;
  21080. here_val = here & 0xffff;
  21081. if ((last_bits + here_bits) <= bits) { break; }
  21082. //--- PULLBYTE() ---//
  21083. if (have === 0) { break inf_leave; }
  21084. have--;
  21085. hold += input[next++] << bits;
  21086. bits += 8;
  21087. //---//
  21088. }
  21089. //--- DROPBITS(last.bits) ---//
  21090. hold >>>= last_bits;
  21091. bits -= last_bits;
  21092. //---//
  21093. state.back += last_bits;
  21094. }
  21095. //--- DROPBITS(here.bits) ---//
  21096. hold >>>= here_bits;
  21097. bits -= here_bits;
  21098. //---//
  21099. state.back += here_bits;
  21100. if (here_op & 64) {
  21101. strm.msg = 'invalid distance code';
  21102. state.mode = BAD;
  21103. break;
  21104. }
  21105. state.offset = here_val;
  21106. state.extra = (here_op) & 15;
  21107. state.mode = DISTEXT;
  21108. /* falls through */
  21109. case DISTEXT:
  21110. if (state.extra) {
  21111. //=== NEEDBITS(state.extra);
  21112. n = state.extra;
  21113. while (bits < n) {
  21114. if (have === 0) { break inf_leave; }
  21115. have--;
  21116. hold += input[next++] << bits;
  21117. bits += 8;
  21118. }
  21119. //===//
  21120. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  21121. //--- DROPBITS(state.extra) ---//
  21122. hold >>>= state.extra;
  21123. bits -= state.extra;
  21124. //---//
  21125. state.back += state.extra;
  21126. }
  21127. //#ifdef INFLATE_STRICT
  21128. if (state.offset > state.dmax) {
  21129. strm.msg = 'invalid distance too far back';
  21130. state.mode = BAD;
  21131. break;
  21132. }
  21133. //#endif
  21134. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  21135. state.mode = MATCH;
  21136. /* falls through */
  21137. case MATCH:
  21138. if (left === 0) { break inf_leave; }
  21139. copy = _out - left;
  21140. if (state.offset > copy) { /* copy from window */
  21141. copy = state.offset - copy;
  21142. if (copy > state.whave) {
  21143. if (state.sane) {
  21144. strm.msg = 'invalid distance too far back';
  21145. state.mode = BAD;
  21146. break;
  21147. }
  21148. // (!) This block is disabled in zlib defailts,
  21149. // don't enable it for binary compatibility
  21150. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  21151. // Trace((stderr, "inflate.c too far\n"));
  21152. // copy -= state.whave;
  21153. // if (copy > state.length) { copy = state.length; }
  21154. // if (copy > left) { copy = left; }
  21155. // left -= copy;
  21156. // state.length -= copy;
  21157. // do {
  21158. // output[put++] = 0;
  21159. // } while (--copy);
  21160. // if (state.length === 0) { state.mode = LEN; }
  21161. // break;
  21162. //#endif
  21163. }
  21164. if (copy > state.wnext) {
  21165. copy -= state.wnext;
  21166. from = state.wsize - copy;
  21167. }
  21168. else {
  21169. from = state.wnext - copy;
  21170. }
  21171. if (copy > state.length) { copy = state.length; }
  21172. from_source = state.window;
  21173. }
  21174. else { /* copy from output */
  21175. from_source = output;
  21176. from = put - state.offset;
  21177. copy = state.length;
  21178. }
  21179. if (copy > left) { copy = left; }
  21180. left -= copy;
  21181. state.length -= copy;
  21182. do {
  21183. output[put++] = from_source[from++];
  21184. } while (--copy);
  21185. if (state.length === 0) { state.mode = LEN; }
  21186. break;
  21187. case LIT:
  21188. if (left === 0) { break inf_leave; }
  21189. output[put++] = state.length;
  21190. left--;
  21191. state.mode = LEN;
  21192. break;
  21193. case CHECK:
  21194. if (state.wrap) {
  21195. //=== NEEDBITS(32);
  21196. while (bits < 32) {
  21197. if (have === 0) { break inf_leave; }
  21198. have--;
  21199. // Use '|' insdead of '+' to make sure that result is signed
  21200. hold |= input[next++] << bits;
  21201. bits += 8;
  21202. }
  21203. //===//
  21204. _out -= left;
  21205. strm.total_out += _out;
  21206. state.total += _out;
  21207. if (_out) {
  21208. strm.adler = state.check =
  21209. /*UPDATE(state.check, put - _out, _out);*/
  21210. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  21211. }
  21212. _out = left;
  21213. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  21214. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  21215. strm.msg = 'incorrect data check';
  21216. state.mode = BAD;
  21217. break;
  21218. }
  21219. //=== INITBITS();
  21220. hold = 0;
  21221. bits = 0;
  21222. //===//
  21223. //Tracev((stderr, "inflate: check matches trailer\n"));
  21224. }
  21225. state.mode = LENGTH;
  21226. /* falls through */
  21227. case LENGTH:
  21228. if (state.wrap && state.flags) {
  21229. //=== NEEDBITS(32);
  21230. while (bits < 32) {
  21231. if (have === 0) { break inf_leave; }
  21232. have--;
  21233. hold += input[next++] << bits;
  21234. bits += 8;
  21235. }
  21236. //===//
  21237. if (hold !== (state.total & 0xffffffff)) {
  21238. strm.msg = 'incorrect length check';
  21239. state.mode = BAD;
  21240. break;
  21241. }
  21242. //=== INITBITS();
  21243. hold = 0;
  21244. bits = 0;
  21245. //===//
  21246. //Tracev((stderr, "inflate: length matches trailer\n"));
  21247. }
  21248. state.mode = DONE;
  21249. /* falls through */
  21250. case DONE:
  21251. ret = Z_STREAM_END;
  21252. break inf_leave;
  21253. case BAD:
  21254. ret = Z_DATA_ERROR;
  21255. break inf_leave;
  21256. case MEM:
  21257. return Z_MEM_ERROR;
  21258. case SYNC:
  21259. /* falls through */
  21260. default:
  21261. return Z_STREAM_ERROR;
  21262. }
  21263. }
  21264. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  21265. /*
  21266. Return from inflate(), updating the total counts and the check value.
  21267. If there was no progress during the inflate() call, return a buffer
  21268. error. Call updatewindow() to create and/or update the window state.
  21269. Note: a memory error from inflate() is non-recoverable.
  21270. */
  21271. //--- RESTORE() ---
  21272. strm.next_out = put;
  21273. strm.avail_out = left;
  21274. strm.next_in = next;
  21275. strm.avail_in = have;
  21276. state.hold = hold;
  21277. state.bits = bits;
  21278. //---
  21279. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  21280. (state.mode < CHECK || flush !== Z_FINISH))) {
  21281. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  21282. state.mode = MEM;
  21283. return Z_MEM_ERROR;
  21284. }
  21285. }
  21286. _in -= strm.avail_in;
  21287. _out -= strm.avail_out;
  21288. strm.total_in += _in;
  21289. strm.total_out += _out;
  21290. state.total += _out;
  21291. if (state.wrap && _out) {
  21292. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  21293. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  21294. }
  21295. strm.data_type = state.bits + (state.last ? 64 : 0) +
  21296. (state.mode === TYPE ? 128 : 0) +
  21297. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  21298. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  21299. ret = Z_BUF_ERROR;
  21300. }
  21301. return ret;
  21302. }
  21303. function inflateEnd(strm) {
  21304. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  21305. return Z_STREAM_ERROR;
  21306. }
  21307. var state = strm.state;
  21308. if (state.window) {
  21309. state.window = null;
  21310. }
  21311. strm.state = null;
  21312. return Z_OK;
  21313. }
  21314. function inflateGetHeader(strm, head) {
  21315. var state;
  21316. /* check state */
  21317. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21318. state = strm.state;
  21319. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  21320. /* save header structure */
  21321. state.head = head;
  21322. head.done = false;
  21323. return Z_OK;
  21324. }
  21325. exports.inflateReset = inflateReset;
  21326. exports.inflateReset2 = inflateReset2;
  21327. exports.inflateResetKeep = inflateResetKeep;
  21328. exports.inflateInit = inflateInit;
  21329. exports.inflateInit2 = inflateInit2;
  21330. exports.inflate = inflate;
  21331. exports.inflateEnd = inflateEnd;
  21332. exports.inflateGetHeader = inflateGetHeader;
  21333. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  21334. /* Not implemented
  21335. exports.inflateCopy = inflateCopy;
  21336. exports.inflateGetDictionary = inflateGetDictionary;
  21337. exports.inflateMark = inflateMark;
  21338. exports.inflatePrime = inflatePrime;
  21339. exports.inflateSetDictionary = inflateSetDictionary;
  21340. exports.inflateSync = inflateSync;
  21341. exports.inflateSyncPoint = inflateSyncPoint;
  21342. exports.inflateUndermine = inflateUndermine;
  21343. */
  21344. },{"../utils/common":66,"./adler32":68,"./crc32":70,"./inffast":73,"./inftrees":75}],75:[function(require,module,exports){
  21345. 'use strict';
  21346. var utils = require('../utils/common');
  21347. var MAXBITS = 15;
  21348. var ENOUGH_LENS = 852;
  21349. var ENOUGH_DISTS = 592;
  21350. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  21351. var CODES = 0;
  21352. var LENS = 1;
  21353. var DISTS = 2;
  21354. var lbase = [ /* Length codes 257..285 base */
  21355. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  21356. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  21357. ];
  21358. var lext = [ /* Length codes 257..285 extra */
  21359. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  21360. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  21361. ];
  21362. var dbase = [ /* Distance codes 0..29 base */
  21363. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  21364. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  21365. 8193, 12289, 16385, 24577, 0, 0
  21366. ];
  21367. var dext = [ /* Distance codes 0..29 extra */
  21368. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  21369. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  21370. 28, 28, 29, 29, 64, 64
  21371. ];
  21372. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  21373. {
  21374. var bits = opts.bits;
  21375. //here = opts.here; /* table entry for duplication */
  21376. var len = 0; /* a code's length in bits */
  21377. var sym = 0; /* index of code symbols */
  21378. var min = 0, max = 0; /* minimum and maximum code lengths */
  21379. var root = 0; /* number of index bits for root table */
  21380. var curr = 0; /* number of index bits for current table */
  21381. var drop = 0; /* code bits to drop for sub-table */
  21382. var left = 0; /* number of prefix codes available */
  21383. var used = 0; /* code entries in table used */
  21384. var huff = 0; /* Huffman code */
  21385. var incr; /* for incrementing code, index */
  21386. var fill; /* index for replicating entries */
  21387. var low; /* low bits for current root entry */
  21388. var mask; /* mask for low root bits */
  21389. var next; /* next available space in table */
  21390. var base = null; /* base value table to use */
  21391. var base_index = 0;
  21392. // var shoextra; /* extra bits table to use */
  21393. var end; /* use base and extra for symbol > end */
  21394. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  21395. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  21396. var extra = null;
  21397. var extra_index = 0;
  21398. var here_bits, here_op, here_val;
  21399. /*
  21400. Process a set of code lengths to create a canonical Huffman code. The
  21401. code lengths are lens[0..codes-1]. Each length corresponds to the
  21402. symbols 0..codes-1. The Huffman code is generated by first sorting the
  21403. symbols by length from short to long, and retaining the symbol order
  21404. for codes with equal lengths. Then the code starts with all zero bits
  21405. for the first code of the shortest length, and the codes are integer
  21406. increments for the same length, and zeros are appended as the length
  21407. increases. For the deflate format, these bits are stored backwards
  21408. from their more natural integer increment ordering, and so when the
  21409. decoding tables are built in the large loop below, the integer codes
  21410. are incremented backwards.
  21411. This routine assumes, but does not check, that all of the entries in
  21412. lens[] are in the range 0..MAXBITS. The caller must assure this.
  21413. 1..MAXBITS is interpreted as that code length. zero means that that
  21414. symbol does not occur in this code.
  21415. The codes are sorted by computing a count of codes for each length,
  21416. creating from that a table of starting indices for each length in the
  21417. sorted table, and then entering the symbols in order in the sorted
  21418. table. The sorted table is work[], with that space being provided by
  21419. the caller.
  21420. The length counts are used for other purposes as well, i.e. finding
  21421. the minimum and maximum length codes, determining if there are any
  21422. codes at all, checking for a valid set of lengths, and looking ahead
  21423. at length counts to determine sub-table sizes when building the
  21424. decoding tables.
  21425. */
  21426. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  21427. for (len = 0; len <= MAXBITS; len++) {
  21428. count[len] = 0;
  21429. }
  21430. for (sym = 0; sym < codes; sym++) {
  21431. count[lens[lens_index + sym]]++;
  21432. }
  21433. /* bound code lengths, force root to be within code lengths */
  21434. root = bits;
  21435. for (max = MAXBITS; max >= 1; max--) {
  21436. if (count[max] !== 0) { break; }
  21437. }
  21438. if (root > max) {
  21439. root = max;
  21440. }
  21441. if (max === 0) { /* no symbols to code at all */
  21442. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  21443. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  21444. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  21445. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21446. //table.op[opts.table_index] = 64;
  21447. //table.bits[opts.table_index] = 1;
  21448. //table.val[opts.table_index++] = 0;
  21449. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21450. opts.bits = 1;
  21451. return 0; /* no symbols, but wait for decoding to report error */
  21452. }
  21453. for (min = 1; min < max; min++) {
  21454. if (count[min] !== 0) { break; }
  21455. }
  21456. if (root < min) {
  21457. root = min;
  21458. }
  21459. /* check for an over-subscribed or incomplete set of lengths */
  21460. left = 1;
  21461. for (len = 1; len <= MAXBITS; len++) {
  21462. left <<= 1;
  21463. left -= count[len];
  21464. if (left < 0) {
  21465. return -1;
  21466. } /* over-subscribed */
  21467. }
  21468. if (left > 0 && (type === CODES || max !== 1)) {
  21469. return -1; /* incomplete set */
  21470. }
  21471. /* generate offsets into symbol table for each length for sorting */
  21472. offs[1] = 0;
  21473. for (len = 1; len < MAXBITS; len++) {
  21474. offs[len + 1] = offs[len] + count[len];
  21475. }
  21476. /* sort symbols by length, by symbol order within each length */
  21477. for (sym = 0; sym < codes; sym++) {
  21478. if (lens[lens_index + sym] !== 0) {
  21479. work[offs[lens[lens_index + sym]]++] = sym;
  21480. }
  21481. }
  21482. /*
  21483. Create and fill in decoding tables. In this loop, the table being
  21484. filled is at next and has curr index bits. The code being used is huff
  21485. with length len. That code is converted to an index by dropping drop
  21486. bits off of the bottom. For codes where len is less than drop + curr,
  21487. those top drop + curr - len bits are incremented through all values to
  21488. fill the table with replicated entries.
  21489. root is the number of index bits for the root table. When len exceeds
  21490. root, sub-tables are created pointed to by the root entry with an index
  21491. of the low root bits of huff. This is saved in low to check for when a
  21492. new sub-table should be started. drop is zero when the root table is
  21493. being filled, and drop is root when sub-tables are being filled.
  21494. When a new sub-table is needed, it is necessary to look ahead in the
  21495. code lengths to determine what size sub-table is needed. The length
  21496. counts are used for this, and so count[] is decremented as codes are
  21497. entered in the tables.
  21498. used keeps track of how many table entries have been allocated from the
  21499. provided *table space. It is checked for LENS and DIST tables against
  21500. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  21501. the initial root table size constants. See the comments in inftrees.h
  21502. for more information.
  21503. sym increments through all symbols, and the loop terminates when
  21504. all codes of length max, i.e. all codes, have been processed. This
  21505. routine permits incomplete codes, so another loop after this one fills
  21506. in the rest of the decoding tables with invalid code markers.
  21507. */
  21508. /* set up for code type */
  21509. // poor man optimization - use if-else instead of switch,
  21510. // to avoid deopts in old v8
  21511. if (type === CODES) {
  21512. base = extra = work; /* dummy value--not used */
  21513. end = 19;
  21514. } else if (type === LENS) {
  21515. base = lbase;
  21516. base_index -= 257;
  21517. extra = lext;
  21518. extra_index -= 257;
  21519. end = 256;
  21520. } else { /* DISTS */
  21521. base = dbase;
  21522. extra = dext;
  21523. end = -1;
  21524. }
  21525. /* initialize opts for loop */
  21526. huff = 0; /* starting code */
  21527. sym = 0; /* starting code symbol */
  21528. len = min; /* starting code length */
  21529. next = table_index; /* current table to fill in */
  21530. curr = root; /* current table index bits */
  21531. drop = 0; /* current bits to drop from code for index */
  21532. low = -1; /* trigger new sub-table when len > root */
  21533. used = 1 << root; /* use root table entries */
  21534. mask = used - 1; /* mask for comparing low */
  21535. /* check available table space */
  21536. if ((type === LENS && used > ENOUGH_LENS) ||
  21537. (type === DISTS && used > ENOUGH_DISTS)) {
  21538. return 1;
  21539. }
  21540. var i=0;
  21541. /* process all codes and make table entries */
  21542. for (;;) {
  21543. i++;
  21544. /* create table entry */
  21545. here_bits = len - drop;
  21546. if (work[sym] < end) {
  21547. here_op = 0;
  21548. here_val = work[sym];
  21549. }
  21550. else if (work[sym] > end) {
  21551. here_op = extra[extra_index + work[sym]];
  21552. here_val = base[base_index + work[sym]];
  21553. }
  21554. else {
  21555. here_op = 32 + 64; /* end of block */
  21556. here_val = 0;
  21557. }
  21558. /* replicate for those indices with low len bits equal to huff */
  21559. incr = 1 << (len - drop);
  21560. fill = 1 << curr;
  21561. min = fill; /* save offset to next table */
  21562. do {
  21563. fill -= incr;
  21564. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  21565. } while (fill !== 0);
  21566. /* backwards increment the len-bit code huff */
  21567. incr = 1 << (len - 1);
  21568. while (huff & incr) {
  21569. incr >>= 1;
  21570. }
  21571. if (incr !== 0) {
  21572. huff &= incr - 1;
  21573. huff += incr;
  21574. } else {
  21575. huff = 0;
  21576. }
  21577. /* go to next symbol, update count, len */
  21578. sym++;
  21579. if (--count[len] === 0) {
  21580. if (len === max) { break; }
  21581. len = lens[lens_index + work[sym]];
  21582. }
  21583. /* create new sub-table if needed */
  21584. if (len > root && (huff & mask) !== low) {
  21585. /* if first time, transition to sub-tables */
  21586. if (drop === 0) {
  21587. drop = root;
  21588. }
  21589. /* increment past last table */
  21590. next += min; /* here min is 1 << curr */
  21591. /* determine length of next table */
  21592. curr = len - drop;
  21593. left = 1 << curr;
  21594. while (curr + drop < max) {
  21595. left -= count[curr + drop];
  21596. if (left <= 0) { break; }
  21597. curr++;
  21598. left <<= 1;
  21599. }
  21600. /* check for enough space */
  21601. used += 1 << curr;
  21602. if ((type === LENS && used > ENOUGH_LENS) ||
  21603. (type === DISTS && used > ENOUGH_DISTS)) {
  21604. return 1;
  21605. }
  21606. /* point entry in root table to sub-table */
  21607. low = huff & mask;
  21608. /*table.op[low] = curr;
  21609. table.bits[low] = root;
  21610. table.val[low] = next - opts.table_index;*/
  21611. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  21612. }
  21613. }
  21614. /* fill in remaining table entry if code is incomplete (guaranteed to have
  21615. at most one remaining entry, since if the code is incomplete, the
  21616. maximum code length that was allowed to get this far is one bit) */
  21617. if (huff !== 0) {
  21618. //table.op[next + huff] = 64; /* invalid code marker */
  21619. //table.bits[next + huff] = len - drop;
  21620. //table.val[next + huff] = 0;
  21621. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  21622. }
  21623. /* set return parameters */
  21624. //opts.table_index += used;
  21625. opts.bits = root;
  21626. return 0;
  21627. };
  21628. },{"../utils/common":66}],76:[function(require,module,exports){
  21629. 'use strict';
  21630. module.exports = {
  21631. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  21632. '1': 'stream end', /* Z_STREAM_END 1 */
  21633. '0': '', /* Z_OK 0 */
  21634. '-1': 'file error', /* Z_ERRNO (-1) */
  21635. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  21636. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  21637. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  21638. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  21639. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  21640. };
  21641. },{}],77:[function(require,module,exports){
  21642. 'use strict';
  21643. var utils = require('../utils/common');
  21644. /* Public constants ==========================================================*/
  21645. /* ===========================================================================*/
  21646. //var Z_FILTERED = 1;
  21647. //var Z_HUFFMAN_ONLY = 2;
  21648. //var Z_RLE = 3;
  21649. var Z_FIXED = 4;
  21650. //var Z_DEFAULT_STRATEGY = 0;
  21651. /* Possible values of the data_type field (though see inflate()) */
  21652. var Z_BINARY = 0;
  21653. var Z_TEXT = 1;
  21654. //var Z_ASCII = 1; // = Z_TEXT
  21655. var Z_UNKNOWN = 2;
  21656. /*============================================================================*/
  21657. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  21658. // From zutil.h
  21659. var STORED_BLOCK = 0;
  21660. var STATIC_TREES = 1;
  21661. var DYN_TREES = 2;
  21662. /* The three kinds of block type */
  21663. var MIN_MATCH = 3;
  21664. var MAX_MATCH = 258;
  21665. /* The minimum and maximum match lengths */
  21666. // From deflate.h
  21667. /* ===========================================================================
  21668. * Internal compression state.
  21669. */
  21670. var LENGTH_CODES = 29;
  21671. /* number of length codes, not counting the special END_BLOCK code */
  21672. var LITERALS = 256;
  21673. /* number of literal bytes 0..255 */
  21674. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  21675. /* number of Literal or Length codes, including the END_BLOCK code */
  21676. var D_CODES = 30;
  21677. /* number of distance codes */
  21678. var BL_CODES = 19;
  21679. /* number of codes used to transfer the bit lengths */
  21680. var HEAP_SIZE = 2*L_CODES + 1;
  21681. /* maximum heap size */
  21682. var MAX_BITS = 15;
  21683. /* All codes must not exceed MAX_BITS bits */
  21684. var Buf_size = 16;
  21685. /* size of bit buffer in bi_buf */
  21686. /* ===========================================================================
  21687. * Constants
  21688. */
  21689. var MAX_BL_BITS = 7;
  21690. /* Bit length codes must not exceed MAX_BL_BITS bits */
  21691. var END_BLOCK = 256;
  21692. /* end of block literal code */
  21693. var REP_3_6 = 16;
  21694. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  21695. var REPZ_3_10 = 17;
  21696. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  21697. var REPZ_11_138 = 18;
  21698. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  21699. var extra_lbits = /* extra bits for each length code */
  21700. [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];
  21701. var extra_dbits = /* extra bits for each distance code */
  21702. [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];
  21703. var extra_blbits = /* extra bits for each bit length code */
  21704. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  21705. var bl_order =
  21706. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  21707. /* The lengths of the bit length codes are sent in order of decreasing
  21708. * probability, to avoid transmitting the lengths for unused bit length codes.
  21709. */
  21710. /* ===========================================================================
  21711. * Local data. These are initialized only once.
  21712. */
  21713. // We pre-fill arrays with 0 to avoid uninitialized gaps
  21714. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  21715. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  21716. var static_ltree = new Array((L_CODES+2) * 2);
  21717. zero(static_ltree);
  21718. /* The static literal tree. Since the bit lengths are imposed, there is no
  21719. * need for the L_CODES extra codes used during heap construction. However
  21720. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  21721. * below).
  21722. */
  21723. var static_dtree = new Array(D_CODES * 2);
  21724. zero(static_dtree);
  21725. /* The static distance tree. (Actually a trivial tree since all codes use
  21726. * 5 bits.)
  21727. */
  21728. var _dist_code = new Array(DIST_CODE_LEN);
  21729. zero(_dist_code);
  21730. /* Distance codes. The first 256 values correspond to the distances
  21731. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  21732. * the 15 bit distances.
  21733. */
  21734. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  21735. zero(_length_code);
  21736. /* length code for each normalized match length (0 == MIN_MATCH) */
  21737. var base_length = new Array(LENGTH_CODES);
  21738. zero(base_length);
  21739. /* First normalized length for each code (0 = MIN_MATCH) */
  21740. var base_dist = new Array(D_CODES);
  21741. zero(base_dist);
  21742. /* First normalized distance for each code (0 = distance of 1) */
  21743. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  21744. this.static_tree = static_tree; /* static tree or NULL */
  21745. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  21746. this.extra_base = extra_base; /* base index for extra_bits */
  21747. this.elems = elems; /* max number of elements in the tree */
  21748. this.max_length = max_length; /* max bit length for the codes */
  21749. // show if `static_tree` has data or dummy - needed for monomorphic objects
  21750. this.has_stree = static_tree && static_tree.length;
  21751. };
  21752. var static_l_desc;
  21753. var static_d_desc;
  21754. var static_bl_desc;
  21755. var TreeDesc = function(dyn_tree, stat_desc) {
  21756. this.dyn_tree = dyn_tree; /* the dynamic tree */
  21757. this.max_code = 0; /* largest code with non zero frequency */
  21758. this.stat_desc = stat_desc; /* the corresponding static tree */
  21759. };
  21760. function d_code(dist) {
  21761. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  21762. }
  21763. /* ===========================================================================
  21764. * Output a short LSB first on the stream.
  21765. * IN assertion: there is enough room in pendingBuf.
  21766. */
  21767. function put_short (s, w) {
  21768. // put_byte(s, (uch)((w) & 0xff));
  21769. // put_byte(s, (uch)((ush)(w) >> 8));
  21770. s.pending_buf[s.pending++] = (w) & 0xff;
  21771. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  21772. }
  21773. /* ===========================================================================
  21774. * Send a value on a given number of bits.
  21775. * IN assertion: length <= 16 and value fits in length bits.
  21776. */
  21777. function send_bits(s, value, length) {
  21778. if (s.bi_valid > (Buf_size - length)) {
  21779. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21780. put_short(s, s.bi_buf);
  21781. s.bi_buf = value >> (Buf_size - s.bi_valid);
  21782. s.bi_valid += length - Buf_size;
  21783. } else {
  21784. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21785. s.bi_valid += length;
  21786. }
  21787. }
  21788. function send_code(s, c, tree) {
  21789. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  21790. }
  21791. /* ===========================================================================
  21792. * Reverse the first len bits of a code, using straightforward code (a faster
  21793. * method would use a table)
  21794. * IN assertion: 1 <= len <= 15
  21795. */
  21796. function bi_reverse(code, len) {
  21797. var res = 0;
  21798. do {
  21799. res |= code & 1;
  21800. code >>>= 1;
  21801. res <<= 1;
  21802. } while (--len > 0);
  21803. return res >>> 1;
  21804. }
  21805. /* ===========================================================================
  21806. * Flush the bit buffer, keeping at most 7 bits in it.
  21807. */
  21808. function bi_flush(s) {
  21809. if (s.bi_valid === 16) {
  21810. put_short(s, s.bi_buf);
  21811. s.bi_buf = 0;
  21812. s.bi_valid = 0;
  21813. } else if (s.bi_valid >= 8) {
  21814. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  21815. s.bi_buf >>= 8;
  21816. s.bi_valid -= 8;
  21817. }
  21818. }
  21819. /* ===========================================================================
  21820. * Compute the optimal bit lengths for a tree and update the total bit length
  21821. * for the current block.
  21822. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  21823. * above are the tree nodes sorted by increasing frequency.
  21824. * OUT assertions: the field len is set to the optimal bit length, the
  21825. * array bl_count contains the frequencies for each bit length.
  21826. * The length opt_len is updated; static_len is also updated if stree is
  21827. * not null.
  21828. */
  21829. function gen_bitlen(s, desc)
  21830. // deflate_state *s;
  21831. // tree_desc *desc; /* the tree descriptor */
  21832. {
  21833. var tree = desc.dyn_tree;
  21834. var max_code = desc.max_code;
  21835. var stree = desc.stat_desc.static_tree;
  21836. var has_stree = desc.stat_desc.has_stree;
  21837. var extra = desc.stat_desc.extra_bits;
  21838. var base = desc.stat_desc.extra_base;
  21839. var max_length = desc.stat_desc.max_length;
  21840. var h; /* heap index */
  21841. var n, m; /* iterate over the tree elements */
  21842. var bits; /* bit length */
  21843. var xbits; /* extra bits */
  21844. var f; /* frequency */
  21845. var overflow = 0; /* number of elements with bit length too large */
  21846. for (bits = 0; bits <= MAX_BITS; bits++) {
  21847. s.bl_count[bits] = 0;
  21848. }
  21849. /* In a first pass, compute the optimal bit lengths (which may
  21850. * overflow in the case of the bit length tree).
  21851. */
  21852. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  21853. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  21854. n = s.heap[h];
  21855. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  21856. if (bits > max_length) {
  21857. bits = max_length;
  21858. overflow++;
  21859. }
  21860. tree[n*2 + 1]/*.Len*/ = bits;
  21861. /* We overwrite tree[n].Dad which is no longer needed */
  21862. if (n > max_code) { continue; } /* not a leaf node */
  21863. s.bl_count[bits]++;
  21864. xbits = 0;
  21865. if (n >= base) {
  21866. xbits = extra[n-base];
  21867. }
  21868. f = tree[n * 2]/*.Freq*/;
  21869. s.opt_len += f * (bits + xbits);
  21870. if (has_stree) {
  21871. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  21872. }
  21873. }
  21874. if (overflow === 0) { return; }
  21875. // Trace((stderr,"\nbit length overflow\n"));
  21876. /* This happens for example on obj2 and pic of the Calgary corpus */
  21877. /* Find the first bit length which could increase: */
  21878. do {
  21879. bits = max_length-1;
  21880. while (s.bl_count[bits] === 0) { bits--; }
  21881. s.bl_count[bits]--; /* move one leaf down the tree */
  21882. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  21883. s.bl_count[max_length]--;
  21884. /* The brother of the overflow item also moves one step up,
  21885. * but this does not affect bl_count[max_length]
  21886. */
  21887. overflow -= 2;
  21888. } while (overflow > 0);
  21889. /* Now recompute all bit lengths, scanning in increasing frequency.
  21890. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  21891. * lengths instead of fixing only the wrong ones. This idea is taken
  21892. * from 'ar' written by Haruhiko Okumura.)
  21893. */
  21894. for (bits = max_length; bits !== 0; bits--) {
  21895. n = s.bl_count[bits];
  21896. while (n !== 0) {
  21897. m = s.heap[--h];
  21898. if (m > max_code) { continue; }
  21899. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  21900. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  21901. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  21902. tree[m*2 + 1]/*.Len*/ = bits;
  21903. }
  21904. n--;
  21905. }
  21906. }
  21907. }
  21908. /* ===========================================================================
  21909. * Generate the codes for a given tree and bit counts (which need not be
  21910. * optimal).
  21911. * IN assertion: the array bl_count contains the bit length statistics for
  21912. * the given tree and the field len is set for all tree elements.
  21913. * OUT assertion: the field code is set for all tree elements of non
  21914. * zero code length.
  21915. */
  21916. function gen_codes(tree, max_code, bl_count)
  21917. // ct_data *tree; /* the tree to decorate */
  21918. // int max_code; /* largest code with non zero frequency */
  21919. // ushf *bl_count; /* number of codes at each bit length */
  21920. {
  21921. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  21922. var code = 0; /* running code value */
  21923. var bits; /* bit index */
  21924. var n; /* code index */
  21925. /* The distribution counts are first used to generate the code values
  21926. * without bit reversal.
  21927. */
  21928. for (bits = 1; bits <= MAX_BITS; bits++) {
  21929. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  21930. }
  21931. /* Check that the bit counts in bl_count are consistent. The last code
  21932. * must be all ones.
  21933. */
  21934. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  21935. // "inconsistent bit counts");
  21936. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  21937. for (n = 0; n <= max_code; n++) {
  21938. var len = tree[n*2 + 1]/*.Len*/;
  21939. if (len === 0) { continue; }
  21940. /* Now reverse the bits */
  21941. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  21942. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  21943. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  21944. }
  21945. }
  21946. /* ===========================================================================
  21947. * Initialize the various 'constant' tables.
  21948. */
  21949. function tr_static_init() {
  21950. var n; /* iterates over tree elements */
  21951. var bits; /* bit counter */
  21952. var length; /* length value */
  21953. var code; /* code value */
  21954. var dist; /* distance index */
  21955. var bl_count = new Array(MAX_BITS+1);
  21956. /* number of codes at each bit length for an optimal tree */
  21957. // do check in _tr_init()
  21958. //if (static_init_done) return;
  21959. /* For some embedded targets, global variables are not initialized: */
  21960. /*#ifdef NO_INIT_GLOBAL_POINTERS
  21961. static_l_desc.static_tree = static_ltree;
  21962. static_l_desc.extra_bits = extra_lbits;
  21963. static_d_desc.static_tree = static_dtree;
  21964. static_d_desc.extra_bits = extra_dbits;
  21965. static_bl_desc.extra_bits = extra_blbits;
  21966. #endif*/
  21967. /* Initialize the mapping length (0..255) -> length code (0..28) */
  21968. length = 0;
  21969. for (code = 0; code < LENGTH_CODES-1; code++) {
  21970. base_length[code] = length;
  21971. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  21972. _length_code[length++] = code;
  21973. }
  21974. }
  21975. //Assert (length == 256, "tr_static_init: length != 256");
  21976. /* Note that the length 255 (match length 258) can be represented
  21977. * in two different ways: code 284 + 5 bits or code 285, so we
  21978. * overwrite length_code[255] to use the best encoding:
  21979. */
  21980. _length_code[length-1] = code;
  21981. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  21982. dist = 0;
  21983. for (code = 0 ; code < 16; code++) {
  21984. base_dist[code] = dist;
  21985. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  21986. _dist_code[dist++] = code;
  21987. }
  21988. }
  21989. //Assert (dist == 256, "tr_static_init: dist != 256");
  21990. dist >>= 7; /* from now on, all distances are divided by 128 */
  21991. for ( ; code < D_CODES; code++) {
  21992. base_dist[code] = dist << 7;
  21993. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  21994. _dist_code[256 + dist++] = code;
  21995. }
  21996. }
  21997. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  21998. /* Construct the codes of the static literal tree */
  21999. for (bits = 0; bits <= MAX_BITS; bits++) {
  22000. bl_count[bits] = 0;
  22001. }
  22002. n = 0;
  22003. while (n <= 143) {
  22004. static_ltree[n*2 + 1]/*.Len*/ = 8;
  22005. n++;
  22006. bl_count[8]++;
  22007. }
  22008. while (n <= 255) {
  22009. static_ltree[n*2 + 1]/*.Len*/ = 9;
  22010. n++;
  22011. bl_count[9]++;
  22012. }
  22013. while (n <= 279) {
  22014. static_ltree[n*2 + 1]/*.Len*/ = 7;
  22015. n++;
  22016. bl_count[7]++;
  22017. }
  22018. while (n <= 287) {
  22019. static_ltree[n*2 + 1]/*.Len*/ = 8;
  22020. n++;
  22021. bl_count[8]++;
  22022. }
  22023. /* Codes 286 and 287 do not exist, but we must include them in the
  22024. * tree construction to get a canonical Huffman tree (longest code
  22025. * all ones)
  22026. */
  22027. gen_codes(static_ltree, L_CODES+1, bl_count);
  22028. /* The static distance tree is trivial: */
  22029. for (n = 0; n < D_CODES; n++) {
  22030. static_dtree[n*2 + 1]/*.Len*/ = 5;
  22031. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  22032. }
  22033. // Now data ready and we can init static trees
  22034. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  22035. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  22036. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  22037. //static_init_done = true;
  22038. }
  22039. /* ===========================================================================
  22040. * Initialize a new block.
  22041. */
  22042. function init_block(s) {
  22043. var n; /* iterates over tree elements */
  22044. /* Initialize the trees. */
  22045. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  22046. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  22047. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  22048. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  22049. s.opt_len = s.static_len = 0;
  22050. s.last_lit = s.matches = 0;
  22051. }
  22052. /* ===========================================================================
  22053. * Flush the bit buffer and align the output on a byte boundary
  22054. */
  22055. function bi_windup(s)
  22056. {
  22057. if (s.bi_valid > 8) {
  22058. put_short(s, s.bi_buf);
  22059. } else if (s.bi_valid > 0) {
  22060. //put_byte(s, (Byte)s->bi_buf);
  22061. s.pending_buf[s.pending++] = s.bi_buf;
  22062. }
  22063. s.bi_buf = 0;
  22064. s.bi_valid = 0;
  22065. }
  22066. /* ===========================================================================
  22067. * Copy a stored block, storing first the length and its
  22068. * one's complement if requested.
  22069. */
  22070. function copy_block(s, buf, len, header)
  22071. //DeflateState *s;
  22072. //charf *buf; /* the input data */
  22073. //unsigned len; /* its length */
  22074. //int header; /* true if block header must be written */
  22075. {
  22076. bi_windup(s); /* align on byte boundary */
  22077. if (header) {
  22078. put_short(s, len);
  22079. put_short(s, ~len);
  22080. }
  22081. // while (len--) {
  22082. // put_byte(s, *buf++);
  22083. // }
  22084. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  22085. s.pending += len;
  22086. }
  22087. /* ===========================================================================
  22088. * Compares to subtrees, using the tree depth as tie breaker when
  22089. * the subtrees have equal frequency. This minimizes the worst case length.
  22090. */
  22091. function smaller(tree, n, m, depth) {
  22092. var _n2 = n*2;
  22093. var _m2 = m*2;
  22094. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  22095. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  22096. }
  22097. /* ===========================================================================
  22098. * Restore the heap property by moving down the tree starting at node k,
  22099. * exchanging a node with the smallest of its two sons if necessary, stopping
  22100. * when the heap property is re-established (each father smaller than its
  22101. * two sons).
  22102. */
  22103. function pqdownheap(s, tree, k)
  22104. // deflate_state *s;
  22105. // ct_data *tree; /* the tree to restore */
  22106. // int k; /* node to move down */
  22107. {
  22108. var v = s.heap[k];
  22109. var j = k << 1; /* left son of k */
  22110. while (j <= s.heap_len) {
  22111. /* Set j to the smallest of the two sons: */
  22112. if (j < s.heap_len &&
  22113. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  22114. j++;
  22115. }
  22116. /* Exit if v is smaller than both sons */
  22117. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  22118. /* Exchange v with the smallest son */
  22119. s.heap[k] = s.heap[j];
  22120. k = j;
  22121. /* And continue down the tree, setting j to the left son of k */
  22122. j <<= 1;
  22123. }
  22124. s.heap[k] = v;
  22125. }
  22126. // inlined manually
  22127. // var SMALLEST = 1;
  22128. /* ===========================================================================
  22129. * Send the block data compressed using the given Huffman trees
  22130. */
  22131. function compress_block(s, ltree, dtree)
  22132. // deflate_state *s;
  22133. // const ct_data *ltree; /* literal tree */
  22134. // const ct_data *dtree; /* distance tree */
  22135. {
  22136. var dist; /* distance of matched string */
  22137. var lc; /* match length or unmatched char (if dist == 0) */
  22138. var lx = 0; /* running index in l_buf */
  22139. var code; /* the code to send */
  22140. var extra; /* number of extra bits to send */
  22141. if (s.last_lit !== 0) {
  22142. do {
  22143. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  22144. lc = s.pending_buf[s.l_buf + lx];
  22145. lx++;
  22146. if (dist === 0) {
  22147. send_code(s, lc, ltree); /* send a literal byte */
  22148. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  22149. } else {
  22150. /* Here, lc is the match length - MIN_MATCH */
  22151. code = _length_code[lc];
  22152. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  22153. extra = extra_lbits[code];
  22154. if (extra !== 0) {
  22155. lc -= base_length[code];
  22156. send_bits(s, lc, extra); /* send the extra length bits */
  22157. }
  22158. dist--; /* dist is now the match distance - 1 */
  22159. code = d_code(dist);
  22160. //Assert (code < D_CODES, "bad d_code");
  22161. send_code(s, code, dtree); /* send the distance code */
  22162. extra = extra_dbits[code];
  22163. if (extra !== 0) {
  22164. dist -= base_dist[code];
  22165. send_bits(s, dist, extra); /* send the extra distance bits */
  22166. }
  22167. } /* literal or match pair ? */
  22168. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  22169. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  22170. // "pendingBuf overflow");
  22171. } while (lx < s.last_lit);
  22172. }
  22173. send_code(s, END_BLOCK, ltree);
  22174. }
  22175. /* ===========================================================================
  22176. * Construct one Huffman tree and assigns the code bit strings and lengths.
  22177. * Update the total bit length for the current block.
  22178. * IN assertion: the field freq is set for all tree elements.
  22179. * OUT assertions: the fields len and code are set to the optimal bit length
  22180. * and corresponding code. The length opt_len is updated; static_len is
  22181. * also updated if stree is not null. The field max_code is set.
  22182. */
  22183. function build_tree(s, desc)
  22184. // deflate_state *s;
  22185. // tree_desc *desc; /* the tree descriptor */
  22186. {
  22187. var tree = desc.dyn_tree;
  22188. var stree = desc.stat_desc.static_tree;
  22189. var has_stree = desc.stat_desc.has_stree;
  22190. var elems = desc.stat_desc.elems;
  22191. var n, m; /* iterate over heap elements */
  22192. var max_code = -1; /* largest code with non zero frequency */
  22193. var node; /* new node being created */
  22194. /* Construct the initial heap, with least frequent element in
  22195. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  22196. * heap[0] is not used.
  22197. */
  22198. s.heap_len = 0;
  22199. s.heap_max = HEAP_SIZE;
  22200. for (n = 0; n < elems; n++) {
  22201. if (tree[n * 2]/*.Freq*/ !== 0) {
  22202. s.heap[++s.heap_len] = max_code = n;
  22203. s.depth[n] = 0;
  22204. } else {
  22205. tree[n*2 + 1]/*.Len*/ = 0;
  22206. }
  22207. }
  22208. /* The pkzip format requires that at least one distance code exists,
  22209. * and that at least one bit should be sent even if there is only one
  22210. * possible code. So to avoid special checks later on we force at least
  22211. * two codes of non zero frequency.
  22212. */
  22213. while (s.heap_len < 2) {
  22214. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  22215. tree[node * 2]/*.Freq*/ = 1;
  22216. s.depth[node] = 0;
  22217. s.opt_len--;
  22218. if (has_stree) {
  22219. s.static_len -= stree[node*2 + 1]/*.Len*/;
  22220. }
  22221. /* node is 0 or 1 so it does not have extra bits */
  22222. }
  22223. desc.max_code = max_code;
  22224. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  22225. * establish sub-heaps of increasing lengths:
  22226. */
  22227. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  22228. /* Construct the Huffman tree by repeatedly combining the least two
  22229. * frequent nodes.
  22230. */
  22231. node = elems; /* next internal node of the tree */
  22232. do {
  22233. //pqremove(s, tree, n); /* n = node of least frequency */
  22234. /*** pqremove ***/
  22235. n = s.heap[1/*SMALLEST*/];
  22236. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  22237. pqdownheap(s, tree, 1/*SMALLEST*/);
  22238. /***/
  22239. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  22240. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  22241. s.heap[--s.heap_max] = m;
  22242. /* Create a new node father of n and m */
  22243. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  22244. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  22245. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  22246. /* and insert the new node in the heap */
  22247. s.heap[1/*SMALLEST*/] = node++;
  22248. pqdownheap(s, tree, 1/*SMALLEST*/);
  22249. } while (s.heap_len >= 2);
  22250. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  22251. /* At this point, the fields freq and dad are set. We can now
  22252. * generate the bit lengths.
  22253. */
  22254. gen_bitlen(s, desc);
  22255. /* The field len is now set, we can generate the bit codes */
  22256. gen_codes(tree, max_code, s.bl_count);
  22257. }
  22258. /* ===========================================================================
  22259. * Scan a literal or distance tree to determine the frequencies of the codes
  22260. * in the bit length tree.
  22261. */
  22262. function scan_tree(s, tree, max_code)
  22263. // deflate_state *s;
  22264. // ct_data *tree; /* the tree to be scanned */
  22265. // int max_code; /* and its largest code of non zero frequency */
  22266. {
  22267. var n; /* iterates over all tree elements */
  22268. var prevlen = -1; /* last emitted length */
  22269. var curlen; /* length of current code */
  22270. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  22271. var count = 0; /* repeat count of the current code */
  22272. var max_count = 7; /* max repeat count */
  22273. var min_count = 4; /* min repeat count */
  22274. if (nextlen === 0) {
  22275. max_count = 138;
  22276. min_count = 3;
  22277. }
  22278. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  22279. for (n = 0; n <= max_code; n++) {
  22280. curlen = nextlen;
  22281. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  22282. if (++count < max_count && curlen === nextlen) {
  22283. continue;
  22284. } else if (count < min_count) {
  22285. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  22286. } else if (curlen !== 0) {
  22287. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  22288. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  22289. } else if (count <= 10) {
  22290. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  22291. } else {
  22292. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  22293. }
  22294. count = 0;
  22295. prevlen = curlen;
  22296. if (nextlen === 0) {
  22297. max_count = 138;
  22298. min_count = 3;
  22299. } else if (curlen === nextlen) {
  22300. max_count = 6;
  22301. min_count = 3;
  22302. } else {
  22303. max_count = 7;
  22304. min_count = 4;
  22305. }
  22306. }
  22307. }
  22308. /* ===========================================================================
  22309. * Send a literal or distance tree in compressed form, using the codes in
  22310. * bl_tree.
  22311. */
  22312. function send_tree(s, tree, max_code)
  22313. // deflate_state *s;
  22314. // ct_data *tree; /* the tree to be scanned */
  22315. // int max_code; /* and its largest code of non zero frequency */
  22316. {
  22317. var n; /* iterates over all tree elements */
  22318. var prevlen = -1; /* last emitted length */
  22319. var curlen; /* length of current code */
  22320. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  22321. var count = 0; /* repeat count of the current code */
  22322. var max_count = 7; /* max repeat count */
  22323. var min_count = 4; /* min repeat count */
  22324. /* tree[max_code+1].Len = -1; */ /* guard already set */
  22325. if (nextlen === 0) {
  22326. max_count = 138;
  22327. min_count = 3;
  22328. }
  22329. for (n = 0; n <= max_code; n++) {
  22330. curlen = nextlen;
  22331. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  22332. if (++count < max_count && curlen === nextlen) {
  22333. continue;
  22334. } else if (count < min_count) {
  22335. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  22336. } else if (curlen !== 0) {
  22337. if (curlen !== prevlen) {
  22338. send_code(s, curlen, s.bl_tree);
  22339. count--;
  22340. }
  22341. //Assert(count >= 3 && count <= 6, " 3_6?");
  22342. send_code(s, REP_3_6, s.bl_tree);
  22343. send_bits(s, count-3, 2);
  22344. } else if (count <= 10) {
  22345. send_code(s, REPZ_3_10, s.bl_tree);
  22346. send_bits(s, count-3, 3);
  22347. } else {
  22348. send_code(s, REPZ_11_138, s.bl_tree);
  22349. send_bits(s, count-11, 7);
  22350. }
  22351. count = 0;
  22352. prevlen = curlen;
  22353. if (nextlen === 0) {
  22354. max_count = 138;
  22355. min_count = 3;
  22356. } else if (curlen === nextlen) {
  22357. max_count = 6;
  22358. min_count = 3;
  22359. } else {
  22360. max_count = 7;
  22361. min_count = 4;
  22362. }
  22363. }
  22364. }
  22365. /* ===========================================================================
  22366. * Construct the Huffman tree for the bit lengths and return the index in
  22367. * bl_order of the last bit length code to send.
  22368. */
  22369. function build_bl_tree(s) {
  22370. var max_blindex; /* index of last bit length code of non zero freq */
  22371. /* Determine the bit length frequencies for literal and distance trees */
  22372. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  22373. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  22374. /* Build the bit length tree: */
  22375. build_tree(s, s.bl_desc);
  22376. /* opt_len now includes the length of the tree representations, except
  22377. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  22378. */
  22379. /* Determine the number of bit length codes to send. The pkzip format
  22380. * requires that at least 4 bit length codes be sent. (appnote.txt says
  22381. * 3 but the actual value used is 4.)
  22382. */
  22383. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  22384. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  22385. break;
  22386. }
  22387. }
  22388. /* Update opt_len to include the bit length tree and counts */
  22389. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  22390. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  22391. // s->opt_len, s->static_len));
  22392. return max_blindex;
  22393. }
  22394. /* ===========================================================================
  22395. * Send the header for a block using dynamic Huffman trees: the counts, the
  22396. * lengths of the bit length codes, the literal tree and the distance tree.
  22397. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  22398. */
  22399. function send_all_trees(s, lcodes, dcodes, blcodes)
  22400. // deflate_state *s;
  22401. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  22402. {
  22403. var rank; /* index in bl_order */
  22404. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  22405. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  22406. // "too many codes");
  22407. //Tracev((stderr, "\nbl counts: "));
  22408. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  22409. send_bits(s, dcodes-1, 5);
  22410. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  22411. for (rank = 0; rank < blcodes; rank++) {
  22412. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  22413. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  22414. }
  22415. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  22416. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  22417. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  22418. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  22419. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  22420. }
  22421. /* ===========================================================================
  22422. * Check if the data type is TEXT or BINARY, using the following algorithm:
  22423. * - TEXT if the two conditions below are satisfied:
  22424. * a) There are no non-portable control characters belonging to the
  22425. * "black list" (0..6, 14..25, 28..31).
  22426. * b) There is at least one printable character belonging to the
  22427. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  22428. * - BINARY otherwise.
  22429. * - The following partially-portable control characters form a
  22430. * "gray list" that is ignored in this detection algorithm:
  22431. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  22432. * IN assertion: the fields Freq of dyn_ltree are set.
  22433. */
  22434. function detect_data_type(s) {
  22435. /* black_mask is the bit mask of black-listed bytes
  22436. * set bits 0..6, 14..25, and 28..31
  22437. * 0xf3ffc07f = binary 11110011111111111100000001111111
  22438. */
  22439. var black_mask = 0xf3ffc07f;
  22440. var n;
  22441. /* Check for non-textual ("black-listed") bytes. */
  22442. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  22443. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  22444. return Z_BINARY;
  22445. }
  22446. }
  22447. /* Check for textual ("white-listed") bytes. */
  22448. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  22449. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  22450. return Z_TEXT;
  22451. }
  22452. for (n = 32; n < LITERALS; n++) {
  22453. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  22454. return Z_TEXT;
  22455. }
  22456. }
  22457. /* There are no "black-listed" or "white-listed" bytes:
  22458. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  22459. */
  22460. return Z_BINARY;
  22461. }
  22462. var static_init_done = false;
  22463. /* ===========================================================================
  22464. * Initialize the tree data structures for a new zlib stream.
  22465. */
  22466. function _tr_init(s)
  22467. {
  22468. if (!static_init_done) {
  22469. tr_static_init();
  22470. static_init_done = true;
  22471. }
  22472. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  22473. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  22474. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  22475. s.bi_buf = 0;
  22476. s.bi_valid = 0;
  22477. /* Initialize the first block of the first file: */
  22478. init_block(s);
  22479. }
  22480. /* ===========================================================================
  22481. * Send a stored block
  22482. */
  22483. function _tr_stored_block(s, buf, stored_len, last)
  22484. //DeflateState *s;
  22485. //charf *buf; /* input block */
  22486. //ulg stored_len; /* length of input block */
  22487. //int last; /* one if this is the last block for a file */
  22488. {
  22489. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  22490. copy_block(s, buf, stored_len, true); /* with header */
  22491. }
  22492. /* ===========================================================================
  22493. * Send one empty static block to give enough lookahead for inflate.
  22494. * This takes 10 bits, of which 7 may remain in the bit buffer.
  22495. */
  22496. function _tr_align(s) {
  22497. send_bits(s, STATIC_TREES<<1, 3);
  22498. send_code(s, END_BLOCK, static_ltree);
  22499. bi_flush(s);
  22500. }
  22501. /* ===========================================================================
  22502. * Determine the best encoding for the current block: dynamic trees, static
  22503. * trees or store, and output the encoded block to the zip file.
  22504. */
  22505. function _tr_flush_block(s, buf, stored_len, last)
  22506. //DeflateState *s;
  22507. //charf *buf; /* input block, or NULL if too old */
  22508. //ulg stored_len; /* length of input block */
  22509. //int last; /* one if this is the last block for a file */
  22510. {
  22511. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  22512. var max_blindex = 0; /* index of last bit length code of non zero freq */
  22513. /* Build the Huffman trees unless a stored block is forced */
  22514. if (s.level > 0) {
  22515. /* Check if the file is binary or text */
  22516. if (s.strm.data_type === Z_UNKNOWN) {
  22517. s.strm.data_type = detect_data_type(s);
  22518. }
  22519. /* Construct the literal and distance trees */
  22520. build_tree(s, s.l_desc);
  22521. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  22522. // s->static_len));
  22523. build_tree(s, s.d_desc);
  22524. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  22525. // s->static_len));
  22526. /* At this point, opt_len and static_len are the total bit lengths of
  22527. * the compressed block data, excluding the tree representations.
  22528. */
  22529. /* Build the bit length tree for the above two trees, and get the index
  22530. * in bl_order of the last bit length code to send.
  22531. */
  22532. max_blindex = build_bl_tree(s);
  22533. /* Determine the best encoding. Compute the block lengths in bytes. */
  22534. opt_lenb = (s.opt_len+3+7) >>> 3;
  22535. static_lenb = (s.static_len+3+7) >>> 3;
  22536. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  22537. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  22538. // s->last_lit));
  22539. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  22540. } else {
  22541. // Assert(buf != (char*)0, "lost buf");
  22542. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  22543. }
  22544. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  22545. /* 4: two words for the lengths */
  22546. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  22547. * Otherwise we can't have processed more than WSIZE input bytes since
  22548. * the last block flush, because compression would have been
  22549. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  22550. * transform a block into a stored block.
  22551. */
  22552. _tr_stored_block(s, buf, stored_len, last);
  22553. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  22554. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  22555. compress_block(s, static_ltree, static_dtree);
  22556. } else {
  22557. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  22558. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  22559. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  22560. }
  22561. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  22562. /* The above check is made mod 2^32, for files larger than 512 MB
  22563. * and uLong implemented on 32 bits.
  22564. */
  22565. init_block(s);
  22566. if (last) {
  22567. bi_windup(s);
  22568. }
  22569. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  22570. // s->compressed_len-7*last));
  22571. }
  22572. /* ===========================================================================
  22573. * Save the match info and tally the frequency counts. Return true if
  22574. * the current block must be flushed.
  22575. */
  22576. function _tr_tally(s, dist, lc)
  22577. // deflate_state *s;
  22578. // unsigned dist; /* distance of matched string */
  22579. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  22580. {
  22581. //var out_length, in_length, dcode;
  22582. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  22583. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  22584. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  22585. s.last_lit++;
  22586. if (dist === 0) {
  22587. /* lc is the unmatched char */
  22588. s.dyn_ltree[lc*2]/*.Freq*/++;
  22589. } else {
  22590. s.matches++;
  22591. /* Here, lc is the match length - MIN_MATCH */
  22592. dist--; /* dist = match distance - 1 */
  22593. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  22594. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  22595. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  22596. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  22597. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  22598. }
  22599. // (!) This block is disabled in zlib defailts,
  22600. // don't enable it for binary compatibility
  22601. //#ifdef TRUNCATE_BLOCK
  22602. // /* Try to guess if it is profitable to stop the current block here */
  22603. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  22604. // /* Compute an upper bound for the compressed length */
  22605. // out_length = s.last_lit*8;
  22606. // in_length = s.strstart - s.block_start;
  22607. //
  22608. // for (dcode = 0; dcode < D_CODES; dcode++) {
  22609. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  22610. // }
  22611. // out_length >>>= 3;
  22612. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  22613. // // s->last_lit, in_length, out_length,
  22614. // // 100L - out_length*100L/in_length));
  22615. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  22616. // return true;
  22617. // }
  22618. // }
  22619. //#endif
  22620. return (s.last_lit === s.lit_bufsize-1);
  22621. /* We avoid equality with lit_bufsize because of wraparound at 64K
  22622. * on 16 bit machines and because stored blocks are restricted to
  22623. * 64K-1 bytes.
  22624. */
  22625. }
  22626. exports._tr_init = _tr_init;
  22627. exports._tr_stored_block = _tr_stored_block;
  22628. exports._tr_flush_block = _tr_flush_block;
  22629. exports._tr_tally = _tr_tally;
  22630. exports._tr_align = _tr_align;
  22631. },{"../utils/common":66}],78:[function(require,module,exports){
  22632. 'use strict';
  22633. function ZStream() {
  22634. /* next input byte */
  22635. this.input = null; // JS specific, because we have no pointers
  22636. this.next_in = 0;
  22637. /* number of bytes available at input */
  22638. this.avail_in = 0;
  22639. /* total number of input bytes read so far */
  22640. this.total_in = 0;
  22641. /* next output byte should be put there */
  22642. this.output = null; // JS specific, because we have no pointers
  22643. this.next_out = 0;
  22644. /* remaining free space at output */
  22645. this.avail_out = 0;
  22646. /* total number of bytes output so far */
  22647. this.total_out = 0;
  22648. /* last error message, NULL if no error */
  22649. this.msg = ''/*Z_NULL*/;
  22650. /* not visible by applications */
  22651. this.state = null;
  22652. /* best guess about the data type: binary or text */
  22653. this.data_type = 2/*Z_UNKNOWN*/;
  22654. /* adler32 value of the uncompressed data */
  22655. this.adler = 0;
  22656. }
  22657. module.exports = ZStream;
  22658. },{}],79:[function(require,module,exports){
  22659. module.exports = function arrayEquals(array) {
  22660. // if the other array is a falsy value, return
  22661. if (!array)
  22662. return false;
  22663. // compare lengths - can save a lot of time
  22664. if (this.length != array.length)
  22665. return false;
  22666. for (var i = 0, l = this.length; i < l; i++) {
  22667. // Check if we have nested arrays
  22668. if (this[i] instanceof Array && array[i] instanceof Array) {
  22669. // recurse into the nested arrays
  22670. if (!arrayEquals.apply(this[i], [array[i]]))
  22671. return false;
  22672. } else if (this[i] != array[i]) {
  22673. // Warning - two different object instances will never be equal:
  22674. // {x:20} != {x:20}
  22675. return false;
  22676. }
  22677. }
  22678. return true;
  22679. }
  22680. },{}],80:[function(require,module,exports){
  22681. exports.Interop = require('./interop');
  22682. },{"./interop":81}],81:[function(require,module,exports){
  22683. var transform = require('./transform');
  22684. var arrayEquals = require('./array-equals');
  22685. function Interop() { }
  22686. module.exports = Interop;
  22687. /**
  22688. * This map holds the most recent Plan A offer/answer SDP that was converted
  22689. * to Plan B, with the SDP type ('offer' or 'answer') as keys and the SDP
  22690. * string as values.
  22691. *
  22692. * @type {{}}
  22693. */
  22694. var cache = {};
  22695. /**
  22696. * This method transforms a Plan A SDP to an equivalent Plan B SDP. A
  22697. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  22698. * application.
  22699. *
  22700. * @param desc
  22701. * @returns {*}
  22702. */
  22703. Interop.prototype.toPlanB = function(desc) {
  22704. //#region Preliminary input validation.
  22705. if (typeof desc !== 'object' || desc === null ||
  22706. typeof desc.sdp !== 'string') {
  22707. console.warn('An empty description was passed as an argument.');
  22708. return desc;
  22709. }
  22710. // Objectify the SDP for easier manipulation.
  22711. var session = transform.parse(desc.sdp);
  22712. // If the SDP contains no media, there's nothing to transform.
  22713. if (typeof session.media === 'undefined' ||
  22714. !Array.isArray(session.media) || session.media.length === 0) {
  22715. console.warn('The description has no media.');
  22716. return desc;
  22717. }
  22718. // Try some heuristics to "make sure" this is a Plan A SDP. Plan B SDP has
  22719. // a video, an audio and a data "channel" at most.
  22720. if (session.media.length <= 3 && session.media.every(function(m) {
  22721. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  22722. })) {
  22723. console.warn('This description does not look like Plan A.');
  22724. return desc;
  22725. }
  22726. //#endregion
  22727. // Plan A SDP is our "precious". Cache it for later use in the Plan B ->
  22728. // Plan A transformation.
  22729. cache[desc.type] = desc.sdp;
  22730. //#region Convert from Plan A to Plan B.
  22731. // We rebuild the session.media array.
  22732. var media = session.media;
  22733. session.media = [];
  22734. // Associative array that maps channel types to channel objects for fast
  22735. // access to channel objects by their type, e.g. channels['audio']->channel
  22736. // obj.
  22737. var channels = {};
  22738. // Used to build the group:BUNDLE value after the channels construction
  22739. // loop.
  22740. var types = [];
  22741. // Implode the Plan A m-lines/tracks into Plan B "channels".
  22742. media.forEach(function(mLine) {
  22743. // rtcp-mux is required in the Plan B SDP.
  22744. if (typeof mLine.rtcpMux !== 'string' ||
  22745. mLine.rtcpMux !== 'rtcp-mux') {
  22746. throw new Error('Cannot convert to Plan B because m-lines ' +
  22747. 'without the rtcp-mux attribute were found.');
  22748. }
  22749. // If we don't have a channel for this mLine.type, then use this mLine
  22750. // as the channel basis.
  22751. if (typeof channels[mLine.type] === 'undefined') {
  22752. channels[mLine.type] = mLine;
  22753. }
  22754. // Add sources to the channel and handle a=msid.
  22755. if (typeof mLine.sources === 'object') {
  22756. Object.keys(mLine.sources).forEach(function(ssrc) {
  22757. // Assign the sources to the channel.
  22758. channels[mLine.type].sources[ssrc] = mLine.sources[ssrc];
  22759. // In Plan B the msid is an SSRC attribute. Also, we don't care
  22760. // about the obsolete label and mslabel attributes.
  22761. channels[mLine.type].sources[ssrc].msid = mLine.msid;
  22762. // NOTE ssrcs in ssrc groups will share msids, as
  22763. // draft-uberti-rtcweb-plan-00 mandates.
  22764. });
  22765. }
  22766. // Add ssrc groups to the channel.
  22767. if (typeof mLine.ssrcGroups !== 'undefined' &&
  22768. Array.isArray(mLine.ssrcGroups)) {
  22769. // Create the ssrcGroups array, if it's not defined.
  22770. if (typeof channel.ssrcGroups === 'undefined' ||
  22771. !Array.isArray(channel.ssrcGroups)) {
  22772. channel.ssrcGroups = [];
  22773. }
  22774. channel.ssrcGroups = channel.ssrcGroups.concat(mLine.ssrcGroups);
  22775. }
  22776. if (channels[mLine.type] === mLine) {
  22777. // Copy ICE related stuff from the principal media line.
  22778. mLine.candidates = media[0].candidates;
  22779. mLine.iceUfrag = media[0].iceUfrag;
  22780. mLine.icePwd = media[0].icePwd;
  22781. mLine.fingerprint = media[0].fingerprint;
  22782. // Plan B mids are in ['audio', 'video', 'data']
  22783. mLine.mid = mLine.type;
  22784. // Plan B doesn't support/need the bundle-only attribute.
  22785. delete mLine.bundleOnly;
  22786. // In Plan B the msid is an SSRC attribute.
  22787. delete mLine.msid;
  22788. // Used to build the group:BUNDLE value after this loop.
  22789. types.push(mLine.type);
  22790. // Add the channel to the new media array.
  22791. session.media.push(mLine);
  22792. }
  22793. });
  22794. // We regenerate the BUNDLE group with the new mids.
  22795. session.groups.every(function(group) {
  22796. if (group.type === 'BUNDLE') {
  22797. group.mids = types.join(' ');
  22798. return false;
  22799. } else {
  22800. return true;
  22801. }
  22802. });
  22803. // msid semantic
  22804. session.msidSemantic = {
  22805. semantic: 'WMS',
  22806. token: '*'
  22807. };
  22808. var resStr = transform.write(session);
  22809. return new RTCSessionDescription({
  22810. type: desc.type,
  22811. sdp: resStr
  22812. });
  22813. //#endregion
  22814. };
  22815. /**
  22816. * This method transforms a Plan B SDP to an equivalent Plan A SDP. A
  22817. * PeerConnection wrapper transforms the SDP to Plan A before passing it to FF.
  22818. *
  22819. * @param desc
  22820. * @returns {*}
  22821. */
  22822. Interop.prototype.toPlanA = function(desc) {
  22823. //#region Preliminary input validation.
  22824. if (typeof desc !== 'object' || desc === null ||
  22825. typeof desc.sdp !== 'string') {
  22826. console.warn('An empty description was passed as an argument.');
  22827. return desc;
  22828. }
  22829. var session = transform.parse(desc.sdp);
  22830. // If the SDP contains no media, there's nothing to transform.
  22831. if (typeof session.media === 'undefined' ||
  22832. !Array.isArray(session.media) || session.media.length === 0) {
  22833. console.warn('The description has no media.');
  22834. return desc;
  22835. }
  22836. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  22837. // a video, an audio and a data "channel" at most.
  22838. if (session.media.length > 3 || !session.media.every(function(m) {
  22839. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  22840. })) {
  22841. console.warn('This description does not look like Plan B.');
  22842. return desc;
  22843. }
  22844. // Make sure this Plan B SDP can be converted to a Plan A SDP.
  22845. var mids = [];
  22846. session.media.forEach(function(m) {
  22847. mids.push(m.mid);
  22848. });
  22849. var hasBundle = false;
  22850. if (typeof session.groups !== 'undefined' &&
  22851. Array.isArray(session.groups)) {
  22852. hasBundle = session.groups.every(function(g) {
  22853. return g.type !== 'BUNDLE' ||
  22854. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  22855. });
  22856. }
  22857. if (!hasBundle) {
  22858. throw new Error("Cannot convert to Plan A because m-lines that are " +
  22859. "not bundled were found.");
  22860. }
  22861. //#endregion
  22862. //#region Convert from Plan B to Plan A.
  22863. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  22864. // rebuild an equivalent Plan A offer/answer.
  22865. //
  22866. // For example, if this is a local answer (in Plan A style) that we convert
  22867. // to Plan B prior to handing it over to the application (the
  22868. // PeerConnection wrapper called us, for instance, after a successful
  22869. // createAnswer), we want to remember the m-line at which we've seen the
  22870. // (local) SSRC. That's because when the application wants to do call the
  22871. // SLD method, forcing us to do the inverse transformation (from Plan B to
  22872. // Plan A), we need to know to which m-line to assign the (local) SSRC. We
  22873. // also need to know all the other m-lines that the original answer had and
  22874. // include them in the transformed answer as well.
  22875. //
  22876. // Another example is if this is a remote offer that we convert to Plan B
  22877. // prior to giving it to the application, we want to remember the mid at
  22878. // which we've seen the (remote) SSRC.
  22879. //
  22880. // In the iteration that follows, we use the cached Plan A (if it exists)
  22881. // to assign mids to ssrcs.
  22882. var cached;
  22883. if (typeof cache[desc.type] !== 'undefined') {
  22884. cached = transform.parse(cache[desc.type]);
  22885. }
  22886. // A helper map that sends mids to m-line objects. We use it later to
  22887. // rebuild the Plan A style session.media array.
  22888. var media = {};
  22889. session.media.forEach(function(channel) {
  22890. if (typeof channel.rtcpMux !== 'string' ||
  22891. channel.rtcpMux !== 'rtcp-mux') {
  22892. throw new Error("Cannot convert to Plan A because m-lines " +
  22893. "without the rtcp-mux attribute were found.");
  22894. }
  22895. // With rtcp-mux and bundle all the channels should have the same ICE
  22896. // stuff.
  22897. var sources = channel.sources;
  22898. var ssrcGroups = channel.ssrcGroups;
  22899. var candidates = channel.candidates;
  22900. var iceUfrag = channel.iceUfrag;
  22901. var icePwd = channel.icePwd;
  22902. var fingerprint = channel.fingerprint;
  22903. var port = channel.port;
  22904. // We'll use the "channel" object as a prototype for each new "mLine"
  22905. // that we create, but first we need to clean it up a bit.
  22906. delete channel.sources;
  22907. delete channel.ssrcGroups;
  22908. delete channel.candidates;
  22909. delete channel.iceUfrag;
  22910. delete channel.icePwd;
  22911. delete channel.fingerprint;
  22912. delete channel.port;
  22913. delete channel.mid;
  22914. // inverted ssrc group map
  22915. var invertedGroups = {};
  22916. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  22917. ssrcGroups.forEach(function (ssrcGroup) {
  22918. // TODO(gp) find out how to receive simulcast with FF. For the
  22919. // time being, hide it.
  22920. if (ssrcGroup.semantics === 'SIM') {
  22921. return;
  22922. }
  22923. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  22924. Array.isArray(ssrcGroup.ssrcs)) {
  22925. ssrcGroup.ssrcs.forEach(function (ssrc) {
  22926. if (typeof invertedGroups[ssrc] === 'undefined') {
  22927. invertedGroups[ssrc] = [];
  22928. }
  22929. invertedGroups[ssrc].push(ssrcGroup);
  22930. });
  22931. }
  22932. });
  22933. }
  22934. // ssrc to m-line index.
  22935. var mLines = {};
  22936. if (typeof sources === 'object') {
  22937. // Explode the Plan B channel sources with one m-line per source.
  22938. Object.keys(sources).forEach(function(ssrc) {
  22939. var mLine;
  22940. if (typeof invertedGroups[ssrc] !== 'undefined' &&
  22941. Array.isArray(invertedGroups[ssrc])) {
  22942. invertedGroups[ssrc].every(function (ssrcGroup) {
  22943. // ssrcGroup.ssrcs *is* an Array, no need to check
  22944. // again here.
  22945. return ssrcGroup.ssrcs.every(function (related) {
  22946. if (typeof mLines[related] === 'object') {
  22947. mLine = mLines[related];
  22948. return false;
  22949. } else {
  22950. return true;
  22951. }
  22952. });
  22953. });
  22954. }
  22955. if (typeof mLine === 'object') {
  22956. // the m-line already exists. Just add the source.
  22957. mLine.sources[ssrc] = sources[ssrc];
  22958. delete sources[ssrc].msid;
  22959. } else {
  22960. // Use the "channel" as a prototype for the "mLine".
  22961. mLine = Object.create(channel);
  22962. mLines[ssrc] = mLine;
  22963. // Assign the msid of the source to the m-line.
  22964. mLine.msid = sources[ssrc].msid;
  22965. delete sources[ssrc].msid;
  22966. // We assign one SSRC per media line.
  22967. mLine.sources = {};
  22968. mLine.sources[ssrc] = sources[ssrc];
  22969. mLine.ssrcGroups = invertedGroups[ssrc];
  22970. // Use the cached Plan A SDP (if it exists) to assign SSRCs to
  22971. // mids.
  22972. if (typeof cached !== 'undefined' &&
  22973. typeof cached.media !== 'undefined' &&
  22974. Array.isArray(cached.media)) {
  22975. cached.media.forEach(function(m) {
  22976. if (typeof m.sources === 'object') {
  22977. Object.keys(m.sources).forEach(function(s) {
  22978. if (s === ssrc) {
  22979. mLine.mid = m.mid;
  22980. }
  22981. });
  22982. }
  22983. });
  22984. }
  22985. if (typeof mLine.mid === 'undefined') {
  22986. // If this is an SSRC that we see for the first time assign
  22987. // it a new mid. This is typically the case when this
  22988. // method is called to transform a remote description for
  22989. // the first time or when there is a new SSRC in the remote
  22990. // description because a new peer has joined the
  22991. // conference. Local SSRCs should have already been added
  22992. // to the map in the toPlanB method.
  22993. //
  22994. // Because FF generates answers in Plan A style, we MUST
  22995. // already have a cached answer with all the local SSRCs
  22996. // mapped to some mLine/mid.
  22997. if (desc.type === 'answer') {
  22998. throw new Error("An unmapped SSRC was found.");
  22999. }
  23000. mLine.mid = [channel.type, '-', ssrc].join('');
  23001. }
  23002. // Include the candidates in the 1st media line.
  23003. mLine.candidates = candidates;
  23004. mLine.iceUfrag = iceUfrag;
  23005. mLine.icePwd = icePwd;
  23006. mLine.fingerprint = fingerprint;
  23007. mLine.port = port;
  23008. media[mLine.mid] = mLine;
  23009. }
  23010. });
  23011. }
  23012. });
  23013. // Rebuild the media array in the right order and add the missing mLines
  23014. // (missing from the Plan B SDP).
  23015. session.media = [];
  23016. mids = []; // reuse
  23017. if (desc.type === 'answer') {
  23018. // The media lines in the answer must match the media lines in the
  23019. // offer. The order is important too. Here we use the cached offer to
  23020. // find the m-lines that are missing (from the converted answer), and
  23021. // use the cached answer to complete the converted answer.
  23022. if (typeof cache['offer'] === 'undefined') {
  23023. throw new Error("An answer is being processed but we couldn't " +
  23024. "find a cached offer.");
  23025. }
  23026. var cachedOffer = transform.parse(cache['offer']);
  23027. if (typeof cachedOffer === 'undefined' ||
  23028. typeof cachedOffer.media === 'undefined' ||
  23029. !Array.isArray(cachedOffer.media)) {
  23030. // FIXME(gp) is this really a problem in the general case?
  23031. throw new Error("The cached offer has no media.");
  23032. }
  23033. cachedOffer.media.forEach(function(mo) {
  23034. var mLine;
  23035. if (typeof media[mo.mid] === 'undefined') {
  23036. // This is probably an m-line containing a remote track only.
  23037. // It MUST exist in the cached answer as a remote track only
  23038. // mLine.
  23039. cached.media.every(function(ma) {
  23040. if (mo.mid == ma.mid) {
  23041. mLine = ma;
  23042. return false;
  23043. } else {
  23044. return true;
  23045. }
  23046. });
  23047. } else {
  23048. mLine = media[mo.mid];
  23049. }
  23050. if (typeof mLine === 'undefined') {
  23051. throw new Error("The cached offer contains an m-line that " +
  23052. "doesn't exist neither in the cached answer nor in " +
  23053. "the converted answer.");
  23054. }
  23055. session.media.push(mLine);
  23056. mids.push(mLine.mid);
  23057. });
  23058. } else {
  23059. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  23060. // under any circumstances. If we are no longer interested in sending a
  23061. // track, we just remove the msid and ssrc attributes and set it to
  23062. // either a=recvonly (as the reofferer, we must use recvonly if the
  23063. // other side was previously sending on the m-section, but we can also
  23064. // leave the possibility open if it wasn't previously in use), or
  23065. // a=inacive.
  23066. if (typeof cached !== 'undefined' &&
  23067. typeof cached.media !== 'undefined' &&
  23068. Array.isArray(cached.media)) {
  23069. cached.media.forEach(function(pm) {
  23070. mids.push(pm.mid);
  23071. if (typeof media[pm.mid] !== 'undefined') {
  23072. session.media.push(media[pm.mid]);
  23073. } else {
  23074. delete pm.msid;
  23075. delete pm.sources;
  23076. delete pm.ssrcGroups;
  23077. pm.direction = 'recvonly';
  23078. session.media.push(pm);
  23079. }
  23080. });
  23081. }
  23082. // Add all the remaining (new) m-lines of the transformed SDP.
  23083. Object.keys(media).forEach(function(mid) {
  23084. if (mids.indexOf(mid) === -1) {
  23085. mids.push(mid);
  23086. session.media.push(media[mid]);
  23087. }
  23088. });
  23089. }
  23090. // We regenerate the BUNDLE group (since we regenerated the mids)
  23091. session.groups.every(function(group) {
  23092. if (group.type === 'BUNDLE') {
  23093. group.mids = mids.join(' ');
  23094. return false;
  23095. } else {
  23096. return true;
  23097. }
  23098. });
  23099. // msid semantic
  23100. session.msidSemantic = {
  23101. semantic: 'WMS',
  23102. token: '*'
  23103. };
  23104. var resStr = transform.write(session);
  23105. // Cache the transformed SDP (Plan A) for later re-use in this function.
  23106. cache[desc.type] = resStr;
  23107. return new RTCSessionDescription({
  23108. type: desc.type,
  23109. sdp: resStr
  23110. });
  23111. //#endregion
  23112. };
  23113. },{"./array-equals":79,"./transform":82}],82:[function(require,module,exports){
  23114. var transform = require('sdp-transform');
  23115. exports.write = function(session, opts) {
  23116. if (typeof session !== 'undefined' &&
  23117. typeof session.media !== 'undefined' &&
  23118. Array.isArray(session.media)) {
  23119. session.media.forEach(function (mLine) {
  23120. // expand sources to ssrcs
  23121. if (typeof mLine.sources !== 'undefined' &&
  23122. Object.keys(mLine.sources).length !== 0) {
  23123. mLine.ssrcs = [];
  23124. Object.keys(mLine.sources).forEach(function (ssrc) {
  23125. var source = mLine.sources[ssrc];
  23126. Object.keys(source).forEach(function (attribute) {
  23127. mLine.ssrcs.push({
  23128. id: ssrc,
  23129. attribute: attribute,
  23130. value: source[attribute]
  23131. });
  23132. });
  23133. });
  23134. delete mLine.sources;
  23135. }
  23136. // join ssrcs in ssrc groups
  23137. if (typeof mLine.ssrcGroups !== 'undefined' &&
  23138. Array.isArray(mLine.ssrcGroups)) {
  23139. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  23140. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  23141. Array.isArray(ssrcGroup.ssrcs)) {
  23142. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  23143. }
  23144. });
  23145. }
  23146. });
  23147. }
  23148. // join group mids
  23149. if (typeof session !== 'undefined' &&
  23150. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  23151. session.groups.forEach(function (g) {
  23152. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  23153. g.mids = g.mids.join(' ');
  23154. }
  23155. });
  23156. }
  23157. return transform.write(session, opts);
  23158. };
  23159. exports.parse = function(sdp) {
  23160. var session = transform.parse(sdp);
  23161. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  23162. Array.isArray(session.media)) {
  23163. session.media.forEach(function (mLine) {
  23164. // group sources attributes by ssrc
  23165. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  23166. mLine.sources = {};
  23167. mLine.ssrcs.forEach(function (ssrc) {
  23168. if (!mLine.sources[ssrc.id])
  23169. mLine.sources[ssrc.id] = {};
  23170. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  23171. });
  23172. delete mLine.ssrcs;
  23173. }
  23174. // split ssrcs in ssrc groups
  23175. if (typeof mLine.ssrcGroups !== 'undefined' &&
  23176. Array.isArray(mLine.ssrcGroups)) {
  23177. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  23178. if (typeof ssrcGroup.ssrcs === 'string') {
  23179. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  23180. }
  23181. });
  23182. }
  23183. });
  23184. }
  23185. // split group mids
  23186. if (typeof session !== 'undefined' &&
  23187. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  23188. session.groups.forEach(function (g) {
  23189. if (typeof g.mids === 'string') {
  23190. g.mids = g.mids.split(' ');
  23191. }
  23192. });
  23193. }
  23194. return session;
  23195. };
  23196. },{"sdp-transform":84}],83:[function(require,module,exports){
  23197. var grammar = module.exports = {
  23198. v: [{
  23199. name: 'version',
  23200. reg: /^(\d*)$/
  23201. }],
  23202. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  23203. // NB: sessionId will be a String in most cases because it is huge
  23204. name: 'origin',
  23205. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  23206. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  23207. format: "%s %s %d %s IP%d %s"
  23208. }],
  23209. // default parsing of these only (though some of these feel outdated)
  23210. s: [{ name: 'name' }],
  23211. i: [{ name: 'description' }],
  23212. u: [{ name: 'uri' }],
  23213. e: [{ name: 'email' }],
  23214. p: [{ name: 'phone' }],
  23215. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  23216. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  23217. //k: [{}], // outdated thing ignored
  23218. t: [{ //t=0 0
  23219. name: 'timing',
  23220. reg: /^(\d*) (\d*)/,
  23221. names: ['start', 'stop'],
  23222. format: "%d %d"
  23223. }],
  23224. c: [{ //c=IN IP4 10.47.197.26
  23225. name: 'connection',
  23226. reg: /^IN IP(\d) (\S*)/,
  23227. names: ['version', 'ip'],
  23228. format: "IN IP%d %s"
  23229. }],
  23230. b: [{ //b=AS:4000
  23231. push: 'bandwidth',
  23232. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  23233. names: ['type', 'limit'],
  23234. format: "%s:%s"
  23235. }],
  23236. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  23237. // NB: special - pushes to session
  23238. // TODO: rtp/fmtp should be filtered by the payloads found here?
  23239. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  23240. names: ['type', 'port', 'protocol', 'payloads'],
  23241. format: "%s %d %s %s"
  23242. }],
  23243. a: [
  23244. { //a=rtpmap:110 opus/48000/2
  23245. push: 'rtp',
  23246. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  23247. names: ['payload', 'codec', 'rate', 'encoding'],
  23248. format: function (o) {
  23249. return (o.encoding) ?
  23250. "rtpmap:%d %s/%s/%s":
  23251. "rtpmap:%d %s/%s";
  23252. }
  23253. },
  23254. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  23255. push: 'fmtp',
  23256. reg: /^fmtp:(\d*) (\S*)/,
  23257. names: ['payload', 'config'],
  23258. format: "fmtp:%d %s"
  23259. },
  23260. { //a=control:streamid=0
  23261. name: 'control',
  23262. reg: /^control:(.*)/,
  23263. format: "control:%s"
  23264. },
  23265. { //a=rtcp:65179 IN IP4 193.84.77.194
  23266. name: 'rtcp',
  23267. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  23268. names: ['port', 'netType', 'ipVer', 'address'],
  23269. format: function (o) {
  23270. return (o.address != null) ?
  23271. "rtcp:%d %s IP%d %s":
  23272. "rtcp:%d";
  23273. }
  23274. },
  23275. { //a=rtcp-fb:98 trr-int 100
  23276. push: 'rtcpFbTrrInt',
  23277. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  23278. names: ['payload', 'value'],
  23279. format: "rtcp-fb:%d trr-int %d"
  23280. },
  23281. { //a=rtcp-fb:98 nack rpsi
  23282. push: 'rtcpFb',
  23283. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  23284. names: ['payload', 'type', 'subtype'],
  23285. format: function (o) {
  23286. return (o.subtype != null) ?
  23287. "rtcp-fb:%s %s %s":
  23288. "rtcp-fb:%s %s";
  23289. }
  23290. },
  23291. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  23292. //a=extmap:1/recvonly URI-gps-string
  23293. push: 'ext',
  23294. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  23295. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  23296. format: function (o) {
  23297. return (o.config != null) ?
  23298. "extmap:%s %s %s":
  23299. "extmap:%s %s";
  23300. }
  23301. },
  23302. {
  23303. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  23304. push: 'crypto',
  23305. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  23306. names: ['id', 'suite', 'config', 'sessionConfig'],
  23307. format: function (o) {
  23308. return (o.sessionConfig != null) ?
  23309. "crypto:%d %s %s %s":
  23310. "crypto:%d %s %s";
  23311. }
  23312. },
  23313. { //a=setup:actpass
  23314. name: 'setup',
  23315. reg: /^setup:(\w*)/,
  23316. format: "setup:%s"
  23317. },
  23318. { //a=mid:1
  23319. name: 'mid',
  23320. reg: /^mid:([^\s]*)/,
  23321. format: "mid:%s"
  23322. },
  23323. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  23324. name: 'msid',
  23325. reg: /^msid:(.*)/,
  23326. format: "msid:%s"
  23327. },
  23328. { //a=ptime:20
  23329. name: 'ptime',
  23330. reg: /^ptime:(\d*)/,
  23331. format: "ptime:%d"
  23332. },
  23333. { //a=maxptime:60
  23334. name: 'maxptime',
  23335. reg: /^maxptime:(\d*)/,
  23336. format: "maxptime:%d"
  23337. },
  23338. { //a=sendrecv
  23339. name: 'direction',
  23340. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  23341. },
  23342. { //a=ice-lite
  23343. name: 'icelite',
  23344. reg: /^(ice-lite)/
  23345. },
  23346. { //a=ice-ufrag:F7gI
  23347. name: 'iceUfrag',
  23348. reg: /^ice-ufrag:(\S*)/,
  23349. format: "ice-ufrag:%s"
  23350. },
  23351. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  23352. name: 'icePwd',
  23353. reg: /^ice-pwd:(\S*)/,
  23354. format: "ice-pwd:%s"
  23355. },
  23356. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  23357. name: 'fingerprint',
  23358. reg: /^fingerprint:(\S*) (\S*)/,
  23359. names: ['type', 'hash'],
  23360. format: "fingerprint:%s %s"
  23361. },
  23362. {
  23363. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  23364. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  23365. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  23366. push:'candidates',
  23367. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  23368. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  23369. format: function (o) {
  23370. var str = "candidate:%s %d %s %d %s %d typ %s";
  23371. // NB: candidate has two optional chunks, so %void middle one if it's missing
  23372. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  23373. if (o.generation != null) {
  23374. str += " generation %d";
  23375. }
  23376. return str;
  23377. }
  23378. },
  23379. { //a=end-of-candidates (keep after the candidates line for readability)
  23380. name: 'endOfCandidates',
  23381. reg: /^(end-of-candidates)/
  23382. },
  23383. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  23384. name: 'remoteCandidates',
  23385. reg: /^remote-candidates:(.*)/,
  23386. format: "remote-candidates:%s"
  23387. },
  23388. { //a=ice-options:google-ice
  23389. name: 'iceOptions',
  23390. reg: /^ice-options:(\S*)/,
  23391. format: "ice-options:%s"
  23392. },
  23393. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  23394. push: "ssrcs",
  23395. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  23396. names: ['id', 'attribute', 'value'],
  23397. format: "ssrc:%d %s:%s"
  23398. },
  23399. { //a=ssrc-group:FEC 1 2
  23400. push: "ssrcGroups",
  23401. reg: /^ssrc-group:(\w*) (.*)/,
  23402. names: ['semantics', 'ssrcs'],
  23403. format: "ssrc-group:%s %s"
  23404. },
  23405. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  23406. name: "msidSemantic",
  23407. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  23408. names: ['semantic', 'token'],
  23409. format: "msid-semantic: %s %s" // space after ":" is not accidental
  23410. },
  23411. { //a=group:BUNDLE audio video
  23412. push: 'groups',
  23413. reg: /^group:(\w*) (.*)/,
  23414. names: ['type', 'mids'],
  23415. format: "group:%s %s"
  23416. },
  23417. { //a=rtcp-mux
  23418. name: 'rtcpMux',
  23419. reg: /^(rtcp-mux)/
  23420. },
  23421. { // any a= that we don't understand is kepts verbatim on media.invalid
  23422. push: 'invalid',
  23423. names: ["value"]
  23424. }
  23425. ]
  23426. };
  23427. // set sensible defaults to avoid polluting the grammar with boring details
  23428. Object.keys(grammar).forEach(function (key) {
  23429. var objs = grammar[key];
  23430. objs.forEach(function (obj) {
  23431. if (!obj.reg) {
  23432. obj.reg = /(.*)/;
  23433. }
  23434. if (!obj.format) {
  23435. obj.format = "%s";
  23436. }
  23437. });
  23438. });
  23439. },{}],84:[function(require,module,exports){
  23440. var parser = require('./parser');
  23441. var writer = require('./writer');
  23442. exports.write = writer;
  23443. exports.parse = parser.parse;
  23444. exports.parseFmtpConfig = parser.parseFmtpConfig;
  23445. exports.parsePayloads = parser.parsePayloads;
  23446. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  23447. },{"./parser":85,"./writer":86}],85:[function(require,module,exports){
  23448. var toIntIfInt = function (v) {
  23449. return String(Number(v)) === v ? Number(v) : v;
  23450. };
  23451. var attachProperties = function (match, location, names, rawName) {
  23452. if (rawName && !names) {
  23453. location[rawName] = toIntIfInt(match[1]);
  23454. }
  23455. else {
  23456. for (var i = 0; i < names.length; i += 1) {
  23457. if (match[i+1] != null) {
  23458. location[names[i]] = toIntIfInt(match[i+1]);
  23459. }
  23460. }
  23461. }
  23462. };
  23463. var parseReg = function (obj, location, content) {
  23464. var needsBlank = obj.name && obj.names;
  23465. if (obj.push && !location[obj.push]) {
  23466. location[obj.push] = [];
  23467. }
  23468. else if (needsBlank && !location[obj.name]) {
  23469. location[obj.name] = {};
  23470. }
  23471. var keyLocation = obj.push ?
  23472. {} : // blank object that will be pushed
  23473. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  23474. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  23475. if (obj.push) {
  23476. location[obj.push].push(keyLocation);
  23477. }
  23478. };
  23479. var grammar = require('./grammar');
  23480. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  23481. exports.parse = function (sdp) {
  23482. var session = {}
  23483. , media = []
  23484. , location = session; // points at where properties go under (one of the above)
  23485. // parse lines we understand
  23486. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  23487. var type = l[0];
  23488. var content = l.slice(2);
  23489. if (type === 'm') {
  23490. media.push({rtp: [], fmtp: []});
  23491. location = media[media.length-1]; // point at latest media line
  23492. }
  23493. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  23494. var obj = grammar[type][j];
  23495. if (obj.reg.test(content)) {
  23496. return parseReg(obj, location, content);
  23497. }
  23498. }
  23499. });
  23500. session.media = media; // link it up
  23501. return session;
  23502. };
  23503. var fmtpReducer = function (acc, expr) {
  23504. var s = expr.split('=');
  23505. if (s.length === 2) {
  23506. acc[s[0]] = toIntIfInt(s[1]);
  23507. }
  23508. return acc;
  23509. };
  23510. exports.parseFmtpConfig = function (str) {
  23511. return str.split(';').reduce(fmtpReducer, {});
  23512. };
  23513. exports.parsePayloads = function (str) {
  23514. return str.split(' ').map(Number);
  23515. };
  23516. exports.parseRemoteCandidates = function (str) {
  23517. var candidates = [];
  23518. var parts = str.split(' ').map(toIntIfInt);
  23519. for (var i = 0; i < parts.length; i += 3) {
  23520. candidates.push({
  23521. component: parts[i],
  23522. ip: parts[i + 1],
  23523. port: parts[i + 2]
  23524. });
  23525. }
  23526. return candidates;
  23527. };
  23528. },{"./grammar":83}],86:[function(require,module,exports){
  23529. var grammar = require('./grammar');
  23530. // customized util.format - discards excess arguments and can void middle ones
  23531. var formatRegExp = /%[sdv%]/g;
  23532. var format = function (formatStr) {
  23533. var i = 1;
  23534. var args = arguments;
  23535. var len = args.length;
  23536. return formatStr.replace(formatRegExp, function (x) {
  23537. if (i >= len) {
  23538. return x; // missing argument
  23539. }
  23540. var arg = args[i];
  23541. i += 1;
  23542. switch (x) {
  23543. case '%%':
  23544. return '%';
  23545. case '%s':
  23546. return String(arg);
  23547. case '%d':
  23548. return Number(arg);
  23549. case '%v':
  23550. return '';
  23551. }
  23552. });
  23553. // NB: we discard excess arguments - they are typically undefined from makeLine
  23554. };
  23555. var makeLine = function (type, obj, location) {
  23556. var str = obj.format instanceof Function ?
  23557. (obj.format(obj.push ? location : location[obj.name])) :
  23558. obj.format;
  23559. var args = [type + '=' + str];
  23560. if (obj.names) {
  23561. for (var i = 0; i < obj.names.length; i += 1) {
  23562. var n = obj.names[i];
  23563. if (obj.name) {
  23564. args.push(location[obj.name][n]);
  23565. }
  23566. else { // for mLine and push attributes
  23567. args.push(location[obj.names[i]]);
  23568. }
  23569. }
  23570. }
  23571. else {
  23572. args.push(location[obj.name]);
  23573. }
  23574. return format.apply(null, args);
  23575. };
  23576. // RFC specified order
  23577. // TODO: extend this with all the rest
  23578. var defaultOuterOrder = [
  23579. 'v', 'o', 's', 'i',
  23580. 'u', 'e', 'p', 'c',
  23581. 'b', 't', 'r', 'z', 'a'
  23582. ];
  23583. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  23584. module.exports = function (session, opts) {
  23585. opts = opts || {};
  23586. // ensure certain properties exist
  23587. if (session.version == null) {
  23588. session.version = 0; // "v=0" must be there (only defined version atm)
  23589. }
  23590. if (session.name == null) {
  23591. session.name = " "; // "s= " must be there if no meaningful name set
  23592. }
  23593. session.media.forEach(function (mLine) {
  23594. if (mLine.payloads == null) {
  23595. mLine.payloads = "";
  23596. }
  23597. });
  23598. var outerOrder = opts.outerOrder || defaultOuterOrder;
  23599. var innerOrder = opts.innerOrder || defaultInnerOrder;
  23600. var sdp = [];
  23601. // loop through outerOrder for matching properties on session
  23602. outerOrder.forEach(function (type) {
  23603. grammar[type].forEach(function (obj) {
  23604. if (obj.name in session && session[obj.name] != null) {
  23605. sdp.push(makeLine(type, obj, session));
  23606. }
  23607. else if (obj.push in session && session[obj.push] != null) {
  23608. session[obj.push].forEach(function (el) {
  23609. sdp.push(makeLine(type, obj, el));
  23610. });
  23611. }
  23612. });
  23613. });
  23614. // then for each media line, follow the innerOrder
  23615. session.media.forEach(function (mLine) {
  23616. sdp.push(makeLine('m', grammar.m[0], mLine));
  23617. innerOrder.forEach(function (type) {
  23618. grammar[type].forEach(function (obj) {
  23619. if (obj.name in mLine && mLine[obj.name] != null) {
  23620. sdp.push(makeLine(type, obj, mLine));
  23621. }
  23622. else if (obj.push in mLine && mLine[obj.push] != null) {
  23623. mLine[obj.push].forEach(function (el) {
  23624. sdp.push(makeLine(type, obj, el));
  23625. });
  23626. }
  23627. });
  23628. });
  23629. });
  23630. return sdp.join('\r\n') + '\r\n';
  23631. };
  23632. },{"./grammar":83}],87:[function(require,module,exports){
  23633. var MediaStreamType = {
  23634. VIDEO_TYPE: "Video",
  23635. AUDIO_TYPE: "Audio"
  23636. };
  23637. module.exports = MediaStreamType;
  23638. },{}],88:[function(require,module,exports){
  23639. var RTCBrowserType = {
  23640. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  23641. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  23642. };
  23643. module.exports = RTCBrowserType;
  23644. },{}],89:[function(require,module,exports){
  23645. var RTCEvents = {
  23646. LASTN_CHANGED: "rtc.lastn_changed",
  23647. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  23648. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  23649. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  23650. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  23651. SIMULCAST_START: "rtc.simlcast_start",
  23652. SIMULCAST_STOP: "rtc.simlcast_stop",
  23653. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  23654. };
  23655. module.exports = RTCEvents;
  23656. },{}],90:[function(require,module,exports){
  23657. var Resolutions = {
  23658. "1080": {
  23659. width: 1920,
  23660. height: 1080,
  23661. order: 7
  23662. },
  23663. "fullhd": {
  23664. width: 1920,
  23665. height: 1080,
  23666. order: 7
  23667. },
  23668. "720": {
  23669. width: 1280,
  23670. height: 720,
  23671. order: 6
  23672. },
  23673. "hd": {
  23674. width: 1280,
  23675. height: 720,
  23676. order: 6
  23677. },
  23678. "960": {
  23679. width: 960,
  23680. height: 720,
  23681. order: 5
  23682. },
  23683. "640": {
  23684. width: 640,
  23685. height: 480,
  23686. order: 4
  23687. },
  23688. "vga": {
  23689. width: 640,
  23690. height: 480,
  23691. order: 4
  23692. },
  23693. "360": {
  23694. width: 640,
  23695. height: 360,
  23696. order: 3
  23697. },
  23698. "320": {
  23699. width: 320,
  23700. height: 240,
  23701. order: 2
  23702. },
  23703. "180": {
  23704. width: 320,
  23705. height: 180,
  23706. order: 1
  23707. }
  23708. };
  23709. module.exports = Resolutions;
  23710. },{}],91:[function(require,module,exports){
  23711. var StreamEventTypes = {
  23712. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  23713. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  23714. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  23715. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  23716. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  23717. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  23718. };
  23719. module.exports = StreamEventTypes;
  23720. },{}],92:[function(require,module,exports){
  23721. var UIEvents = {
  23722. NICKNAME_CHANGED: "UI.nickname_changed",
  23723. SELECTED_ENDPOINT: "UI.selected_endpoint",
  23724. PINNED_ENDPOINT: "UI.pinned_endpoint"
  23725. };
  23726. module.exports = UIEvents;
  23727. },{}],93:[function(require,module,exports){
  23728. var AuthenticationEvents = {
  23729. /**
  23730. * Event callback arguments:
  23731. * function(authenticationEnabled, userIdentity)
  23732. * authenticationEnabled - indicates whether authentication has been enabled
  23733. * in this session
  23734. * userIdentity - if user has been logged in then it contains user name. If
  23735. * contains 'null' or 'undefined' then user is not logged in.
  23736. */
  23737. IDENTITY_UPDATED: "authentication.identity_updated"
  23738. };
  23739. module.exports = AuthenticationEvents;
  23740. },{}],94:[function(require,module,exports){
  23741. var CQEvents = {
  23742. LOCALSTATS_UPDATED: "cq.localstats_updated",
  23743. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  23744. STOP: "cq.stop"
  23745. };
  23746. module.exports = CQEvents;
  23747. },{}],95:[function(require,module,exports){
  23748. var DesktopSharingEventTypes = {
  23749. INIT: "ds.init",
  23750. SWITCHING_DONE: "ds.switching_done",
  23751. NEW_STREAM_CREATED: "ds.new_stream_created"
  23752. };
  23753. module.exports = DesktopSharingEventTypes;
  23754. },{}],96:[function(require,module,exports){
  23755. module.exports = {
  23756. getLanguages : function () {
  23757. var languages = [];
  23758. for(var lang in this)
  23759. {
  23760. if(typeof this[lang] === "string")
  23761. languages.push(this[lang]);
  23762. }
  23763. return languages;
  23764. },
  23765. EN: "en",
  23766. BG: "bg",
  23767. DE: "de",
  23768. TR: "tr"
  23769. }
  23770. },{}],97:[function(require,module,exports){
  23771. var XMPPEvents = {
  23772. CONFERENCE_CERATED: "xmpp.conferenceCreated.jingle",
  23773. CALL_TERMINATED: "xmpp.callterminated.jingle",
  23774. CALL_INCOMING: "xmpp.callincoming.jingle",
  23775. DISPOSE_CONFERENCE: "xmpp.dispoce_confernce",
  23776. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  23777. KICKED: "xmpp.kicked",
  23778. BRIDGE_DOWN: "xmpp.bridge_down",
  23779. USER_ID_CHANGED: "xmpp.user_id_changed",
  23780. CHANGED_STREAMS: "xmpp.changed_streams",
  23781. MUC_JOINED: "xmpp.muc_joined",
  23782. MUC_ENTER: "xmpp.muc_enter",
  23783. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  23784. MUC_LEFT: "xmpp.muc_left",
  23785. MUC_DESTROYED: "xmpp.muc_destroyed",
  23786. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  23787. REMOTE_STATS: "xmpp.remote_stats",
  23788. LOCALROLE_CHANGED: "xmpp.localrole_changed",
  23789. PRESENCE_STATUS: "xmpp.presence_status",
  23790. RESERVATION_ERROR: "xmpp.room_reservation_error",
  23791. SUBJECT_CHANGED: "xmpp.subject_changed",
  23792. MESSAGE_RECEIVED: "xmpp.message_received",
  23793. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  23794. PASSWORD_REQUIRED: "xmpp.password_required",
  23795. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  23796. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  23797. ETHERPAD: "xmpp.etherpad",
  23798. DEVICE_AVAILABLE: "xmpp.device_available"
  23799. };
  23800. module.exports = XMPPEvents;
  23801. },{}],98:[function(require,module,exports){
  23802. // Copyright Joyent, Inc. and other Node contributors.
  23803. //
  23804. // Permission is hereby granted, free of charge, to any person obtaining a
  23805. // copy of this software and associated documentation files (the
  23806. // "Software"), to deal in the Software without restriction, including
  23807. // without limitation the rights to use, copy, modify, merge, publish,
  23808. // distribute, sublicense, and/or sell copies of the Software, and to permit
  23809. // persons to whom the Software is furnished to do so, subject to the
  23810. // following conditions:
  23811. //
  23812. // The above copyright notice and this permission notice shall be included
  23813. // in all copies or substantial portions of the Software.
  23814. //
  23815. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  23816. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23817. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  23818. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  23819. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  23820. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  23821. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  23822. function EventEmitter() {
  23823. this._events = this._events || {};
  23824. this._maxListeners = this._maxListeners || undefined;
  23825. }
  23826. module.exports = EventEmitter;
  23827. // Backwards-compat with node 0.10.x
  23828. EventEmitter.EventEmitter = EventEmitter;
  23829. EventEmitter.prototype._events = undefined;
  23830. EventEmitter.prototype._maxListeners = undefined;
  23831. // By default EventEmitters will print a warning if more than 10 listeners are
  23832. // added to it. This is a useful default which helps finding memory leaks.
  23833. EventEmitter.defaultMaxListeners = 10;
  23834. // Obviously not all Emitters should be limited to 10. This function allows
  23835. // that to be increased. Set to zero for unlimited.
  23836. EventEmitter.prototype.setMaxListeners = function(n) {
  23837. if (!isNumber(n) || n < 0 || isNaN(n))
  23838. throw TypeError('n must be a positive number');
  23839. this._maxListeners = n;
  23840. return this;
  23841. };
  23842. EventEmitter.prototype.emit = function(type) {
  23843. var er, handler, len, args, i, listeners;
  23844. if (!this._events)
  23845. this._events = {};
  23846. // If there is no 'error' event listener then throw.
  23847. if (type === 'error') {
  23848. if (!this._events.error ||
  23849. (isObject(this._events.error) && !this._events.error.length)) {
  23850. er = arguments[1];
  23851. if (er instanceof Error) {
  23852. throw er; // Unhandled 'error' event
  23853. }
  23854. throw TypeError('Uncaught, unspecified "error" event.');
  23855. }
  23856. }
  23857. handler = this._events[type];
  23858. if (isUndefined(handler))
  23859. return false;
  23860. if (isFunction(handler)) {
  23861. switch (arguments.length) {
  23862. // fast cases
  23863. case 1:
  23864. handler.call(this);
  23865. break;
  23866. case 2:
  23867. handler.call(this, arguments[1]);
  23868. break;
  23869. case 3:
  23870. handler.call(this, arguments[1], arguments[2]);
  23871. break;
  23872. // slower
  23873. default:
  23874. len = arguments.length;
  23875. args = new Array(len - 1);
  23876. for (i = 1; i < len; i++)
  23877. args[i - 1] = arguments[i];
  23878. handler.apply(this, args);
  23879. }
  23880. } else if (isObject(handler)) {
  23881. len = arguments.length;
  23882. args = new Array(len - 1);
  23883. for (i = 1; i < len; i++)
  23884. args[i - 1] = arguments[i];
  23885. listeners = handler.slice();
  23886. len = listeners.length;
  23887. for (i = 0; i < len; i++)
  23888. listeners[i].apply(this, args);
  23889. }
  23890. return true;
  23891. };
  23892. EventEmitter.prototype.addListener = function(type, listener) {
  23893. var m;
  23894. if (!isFunction(listener))
  23895. throw TypeError('listener must be a function');
  23896. if (!this._events)
  23897. this._events = {};
  23898. // To avoid recursion in the case that type === "newListener"! Before
  23899. // adding it to the listeners, first emit "newListener".
  23900. if (this._events.newListener)
  23901. this.emit('newListener', type,
  23902. isFunction(listener.listener) ?
  23903. listener.listener : listener);
  23904. if (!this._events[type])
  23905. // Optimize the case of one listener. Don't need the extra array object.
  23906. this._events[type] = listener;
  23907. else if (isObject(this._events[type]))
  23908. // If we've already got an array, just append.
  23909. this._events[type].push(listener);
  23910. else
  23911. // Adding the second element, need to change to array.
  23912. this._events[type] = [this._events[type], listener];
  23913. // Check for listener leak
  23914. if (isObject(this._events[type]) && !this._events[type].warned) {
  23915. var m;
  23916. if (!isUndefined(this._maxListeners)) {
  23917. m = this._maxListeners;
  23918. } else {
  23919. m = EventEmitter.defaultMaxListeners;
  23920. }
  23921. if (m && m > 0 && this._events[type].length > m) {
  23922. this._events[type].warned = true;
  23923. console.error('(node) warning: possible EventEmitter memory ' +
  23924. 'leak detected. %d listeners added. ' +
  23925. 'Use emitter.setMaxListeners() to increase limit.',
  23926. this._events[type].length);
  23927. if (typeof console.trace === 'function') {
  23928. // not supported in IE 10
  23929. console.trace();
  23930. }
  23931. }
  23932. }
  23933. return this;
  23934. };
  23935. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  23936. EventEmitter.prototype.once = function(type, listener) {
  23937. if (!isFunction(listener))
  23938. throw TypeError('listener must be a function');
  23939. var fired = false;
  23940. function g() {
  23941. this.removeListener(type, g);
  23942. if (!fired) {
  23943. fired = true;
  23944. listener.apply(this, arguments);
  23945. }
  23946. }
  23947. g.listener = listener;
  23948. this.on(type, g);
  23949. return this;
  23950. };
  23951. // emits a 'removeListener' event iff the listener was removed
  23952. EventEmitter.prototype.removeListener = function(type, listener) {
  23953. var list, position, length, i;
  23954. if (!isFunction(listener))
  23955. throw TypeError('listener must be a function');
  23956. if (!this._events || !this._events[type])
  23957. return this;
  23958. list = this._events[type];
  23959. length = list.length;
  23960. position = -1;
  23961. if (list === listener ||
  23962. (isFunction(list.listener) && list.listener === listener)) {
  23963. delete this._events[type];
  23964. if (this._events.removeListener)
  23965. this.emit('removeListener', type, listener);
  23966. } else if (isObject(list)) {
  23967. for (i = length; i-- > 0;) {
  23968. if (list[i] === listener ||
  23969. (list[i].listener && list[i].listener === listener)) {
  23970. position = i;
  23971. break;
  23972. }
  23973. }
  23974. if (position < 0)
  23975. return this;
  23976. if (list.length === 1) {
  23977. list.length = 0;
  23978. delete this._events[type];
  23979. } else {
  23980. list.splice(position, 1);
  23981. }
  23982. if (this._events.removeListener)
  23983. this.emit('removeListener', type, listener);
  23984. }
  23985. return this;
  23986. };
  23987. EventEmitter.prototype.removeAllListeners = function(type) {
  23988. var key, listeners;
  23989. if (!this._events)
  23990. return this;
  23991. // not listening for removeListener, no need to emit
  23992. if (!this._events.removeListener) {
  23993. if (arguments.length === 0)
  23994. this._events = {};
  23995. else if (this._events[type])
  23996. delete this._events[type];
  23997. return this;
  23998. }
  23999. // emit removeListener for all listeners on all events
  24000. if (arguments.length === 0) {
  24001. for (key in this._events) {
  24002. if (key === 'removeListener') continue;
  24003. this.removeAllListeners(key);
  24004. }
  24005. this.removeAllListeners('removeListener');
  24006. this._events = {};
  24007. return this;
  24008. }
  24009. listeners = this._events[type];
  24010. if (isFunction(listeners)) {
  24011. this.removeListener(type, listeners);
  24012. } else {
  24013. // LIFO order
  24014. while (listeners.length)
  24015. this.removeListener(type, listeners[listeners.length - 1]);
  24016. }
  24017. delete this._events[type];
  24018. return this;
  24019. };
  24020. EventEmitter.prototype.listeners = function(type) {
  24021. var ret;
  24022. if (!this._events || !this._events[type])
  24023. ret = [];
  24024. else if (isFunction(this._events[type]))
  24025. ret = [this._events[type]];
  24026. else
  24027. ret = this._events[type].slice();
  24028. return ret;
  24029. };
  24030. EventEmitter.listenerCount = function(emitter, type) {
  24031. var ret;
  24032. if (!emitter._events || !emitter._events[type])
  24033. ret = 0;
  24034. else if (isFunction(emitter._events[type]))
  24035. ret = 1;
  24036. else
  24037. ret = emitter._events[type].length;
  24038. return ret;
  24039. };
  24040. function isFunction(arg) {
  24041. return typeof arg === 'function';
  24042. }
  24043. function isNumber(arg) {
  24044. return typeof arg === 'number';
  24045. }
  24046. function isObject(arg) {
  24047. return typeof arg === 'object' && arg !== null;
  24048. }
  24049. function isUndefined(arg) {
  24050. return arg === void 0;
  24051. }
  24052. },{}]},{},[1])(1)
  24053. });