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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458
  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. if(!devices)
  823. return;
  824. if(devices.audio === true || devices.audio === false)
  825. this.devices.audio = devices.audio;
  826. if(devices.video === true || devices.video === false)
  827. this.devices.video = devices.video;
  828. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  829. }
  830. };
  831. module.exports = RTC;
  832. },{"../../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){
  833. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  834. var Resolutions = require("../../service/RTC/Resolutions");
  835. var currentResolution = null;
  836. function getPreviousResolution(resolution) {
  837. if(!Resolutions[resolution])
  838. return null;
  839. var order = Resolutions[resolution].order;
  840. var res = null;
  841. var resName = null;
  842. for(var i in Resolutions)
  843. {
  844. var tmp = Resolutions[i];
  845. if(res == null || (res.order < tmp.order && tmp.order < order))
  846. {
  847. resName = i;
  848. res = tmp;
  849. }
  850. }
  851. return resName;
  852. }
  853. function setResolutionConstraints(constraints, resolution, isAndroid)
  854. {
  855. if (resolution && !constraints.video || isAndroid) {
  856. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  857. }
  858. if(Resolutions[resolution])
  859. {
  860. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  861. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  862. }
  863. else
  864. {
  865. if (isAndroid) {
  866. constraints.video.mandatory.minWidth = 320;
  867. constraints.video.mandatory.minHeight = 240;
  868. constraints.video.mandatory.maxFrameRate = 15;
  869. }
  870. }
  871. if (constraints.video.mandatory.minWidth)
  872. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  873. if (constraints.video.mandatory.minHeight)
  874. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  875. }
  876. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  877. {
  878. var constraints = {audio: false, video: false};
  879. if (um.indexOf('video') >= 0) {
  880. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  881. }
  882. if (um.indexOf('audio') >= 0) {
  883. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  884. }
  885. if (um.indexOf('screen') >= 0) {
  886. constraints.video = {
  887. mandatory: {
  888. chromeMediaSource: "screen",
  889. googLeakyBucket: true,
  890. maxWidth: window.screen.width,
  891. maxHeight: window.screen.height,
  892. maxFrameRate: 3
  893. },
  894. optional: []
  895. };
  896. }
  897. if (um.indexOf('desktop') >= 0) {
  898. constraints.video = {
  899. mandatory: {
  900. chromeMediaSource: "desktop",
  901. chromeMediaSourceId: desktopStream,
  902. googLeakyBucket: true,
  903. maxWidth: window.screen.width,
  904. maxHeight: window.screen.height,
  905. maxFrameRate: 3
  906. },
  907. optional: []
  908. };
  909. }
  910. if (constraints.audio) {
  911. // if it is good enough for hangouts...
  912. constraints.audio.optional.push(
  913. {googEchoCancellation: true},
  914. {googAutoGainControl: true},
  915. {googNoiseSupression: true},
  916. {googHighpassFilter: true},
  917. {googNoisesuppression2: true},
  918. {googEchoCancellation2: true},
  919. {googAutoGainControl2: true}
  920. );
  921. }
  922. if (constraints.video) {
  923. constraints.video.optional.push(
  924. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  925. );
  926. if (um.indexOf('video') >= 0) {
  927. constraints.video.optional.push(
  928. {googLeakyBucket: true}
  929. );
  930. }
  931. }
  932. if (um.indexOf('video') >= 0) {
  933. setResolutionConstraints(constraints, resolution, isAndroid);
  934. }
  935. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  936. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  937. constraints.video.optional.push({bandwidth: bandwidth});
  938. }
  939. if (fps) { // for some cameras it might be necessary to request 30fps
  940. // so they choose 30fps mjpg over 10fps yuy2
  941. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  942. constraints.video.mandatory.minFrameRate = fps;
  943. }
  944. return constraints;
  945. }
  946. function RTCUtils(RTCService)
  947. {
  948. this.service = RTCService;
  949. if (navigator.mozGetUserMedia) {
  950. console.log('This appears to be Firefox');
  951. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  952. if (version >= 39) {
  953. this.peerconnection = mozRTCPeerConnection;
  954. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  955. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  956. this.pc_constraints = {};
  957. this.attachMediaStream = function (element, stream) {
  958. // srcObject is being standardized and FF will eventually
  959. // support that unprefixed. FF also supports the
  960. // "element.src = URL.createObjectURL(...)" combo, but that
  961. // will be deprecated in favour of srcObject.
  962. //
  963. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  964. // https://github.com/webrtc/samples/issues/302
  965. element[0].mozSrcObject = stream;
  966. element[0].play();
  967. };
  968. this.getStreamID = function (stream) {
  969. var tracks = stream.getVideoTracks();
  970. if(!tracks || tracks.length == 0)
  971. {
  972. tracks = stream.getAudioTracks();
  973. }
  974. return tracks[0].id.replace(/[\{,\}]/g,"");
  975. };
  976. this.getVideoSrc = function (element) {
  977. return element.mozSrcObject;
  978. };
  979. this.setVideoSrc = function (element, src) {
  980. element.mozSrcObject = src;
  981. };
  982. RTCSessionDescription = mozRTCSessionDescription;
  983. RTCIceCandidate = mozRTCIceCandidate;
  984. } else {
  985. window.location.href = 'unsupported_browser.html';
  986. return;
  987. }
  988. } else if (navigator.webkitGetUserMedia) {
  989. console.log('This appears to be Chrome');
  990. this.peerconnection = webkitRTCPeerConnection;
  991. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  992. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  993. this.attachMediaStream = function (element, stream) {
  994. element.attr('src', webkitURL.createObjectURL(stream));
  995. };
  996. this.getStreamID = function (stream) {
  997. // streams from FF endpoints have the characters '{' and '}'
  998. // that make jQuery choke.
  999. return stream.id.replace(/[\{,\}]/g,"");
  1000. };
  1001. this.getVideoSrc = function (element) {
  1002. return element.getAttribute("src");
  1003. };
  1004. this.setVideoSrc = function (element, src) {
  1005. element.setAttribute("src", src);
  1006. };
  1007. // DTLS should now be enabled by default but..
  1008. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1009. if (navigator.userAgent.indexOf('Android') != -1) {
  1010. this.pc_constraints = {}; // disable DTLS on Android
  1011. }
  1012. if (!webkitMediaStream.prototype.getVideoTracks) {
  1013. webkitMediaStream.prototype.getVideoTracks = function () {
  1014. return this.videoTracks;
  1015. };
  1016. }
  1017. if (!webkitMediaStream.prototype.getAudioTracks) {
  1018. webkitMediaStream.prototype.getAudioTracks = function () {
  1019. return this.audioTracks;
  1020. };
  1021. }
  1022. }
  1023. else
  1024. {
  1025. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  1026. window.location.href = 'unsupported_browser.html';
  1027. return;
  1028. }
  1029. }
  1030. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1031. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1032. desktopStream)
  1033. {
  1034. currentResolution = resolution;
  1035. // Check if we are running on Android device
  1036. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1037. var constraints = getConstraints(
  1038. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1039. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  1040. var self = this;
  1041. try {
  1042. if (config.enableSimulcast
  1043. && constraints.video
  1044. && constraints.video.chromeMediaSource !== 'screen'
  1045. && constraints.video.chromeMediaSource !== 'desktop'
  1046. && !isAndroid
  1047. // We currently do not support FF, as it doesn't have multistream support.
  1048. && !isFF) {
  1049. APP.simulcast.getUserMedia(constraints, function (stream) {
  1050. console.log('onUserMediaSuccess');
  1051. self.setAvailableDevices(um, true);
  1052. success_callback(stream);
  1053. },
  1054. function (error) {
  1055. console.warn('Failed to get access to local media. Error ', error);
  1056. self.setAvailableDevices(um, false);
  1057. if (failure_callback) {
  1058. failure_callback(error);
  1059. }
  1060. });
  1061. } else {
  1062. this.getUserMedia(constraints,
  1063. function (stream) {
  1064. console.log('onUserMediaSuccess');
  1065. self.setAvailableDevices(um, true);
  1066. success_callback(stream);
  1067. },
  1068. function (error) {
  1069. self.setAvailableDevices(um, false);
  1070. console.warn('Failed to get access to local media. Error ',
  1071. error, constraints);
  1072. if (failure_callback) {
  1073. failure_callback(error);
  1074. }
  1075. });
  1076. }
  1077. } catch (e) {
  1078. console.error('GUM failed: ', e);
  1079. if(failure_callback) {
  1080. failure_callback(e);
  1081. }
  1082. }
  1083. };
  1084. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1085. var devices = {};
  1086. if(um.indexOf("video") != -1)
  1087. {
  1088. devices.video = available;
  1089. }
  1090. if(um.indexOf("audio") != -1)
  1091. {
  1092. devices.audio = available;
  1093. }
  1094. this.service.setDeviceAvailability(devices);
  1095. }
  1096. /**
  1097. * We ask for audio and video combined stream in order to get permissions and
  1098. * not to ask twice.
  1099. */
  1100. RTCUtils.prototype.obtainAudioAndVideoPermissions = function(devices, callback) {
  1101. var self = this;
  1102. // Get AV
  1103. if(!devices)
  1104. devices = ['audio', 'video'];
  1105. this.getUserMediaWithConstraints(
  1106. devices,
  1107. function (stream) {
  1108. if(callback)
  1109. callback(stream);
  1110. else
  1111. self.successCallback(stream);
  1112. },
  1113. function (error) {
  1114. self.errorCallback(error);
  1115. },
  1116. config.resolution || '360');
  1117. }
  1118. RTCUtils.prototype.successCallback = function (stream) {
  1119. if(stream)
  1120. console.log('got', stream, stream.getAudioTracks().length,
  1121. stream.getVideoTracks().length);
  1122. this.handleLocalStream(stream);
  1123. };
  1124. RTCUtils.prototype.errorCallback = function (error) {
  1125. var self = this;
  1126. console.error('failed to obtain audio/video stream - trying audio only', error);
  1127. var resolution = getPreviousResolution(currentResolution);
  1128. if(typeof error == "object" && error.constraintName && error.name
  1129. && (error.name == "ConstraintNotSatisfiedError" ||
  1130. error.name == "OverconstrainedError") &&
  1131. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1132. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1133. && resolution != null)
  1134. {
  1135. self.getUserMediaWithConstraints(['audio', 'video'],
  1136. function (stream) {
  1137. return self.successCallback(stream);
  1138. }, function (error) {
  1139. return self.errorCallback(error);
  1140. }, resolution);
  1141. }
  1142. else
  1143. {
  1144. self.getUserMediaWithConstraints(
  1145. ['audio'],
  1146. function (stream) {
  1147. return self.successCallback(stream);
  1148. },
  1149. function (error) {
  1150. console.error('failed to obtain audio/video stream - stop',
  1151. error);
  1152. return self.successCallback(null);
  1153. }
  1154. );
  1155. }
  1156. }
  1157. RTCUtils.prototype.handleLocalStream = function(stream)
  1158. {
  1159. if(window.webkitMediaStream)
  1160. {
  1161. var audioStream = new webkitMediaStream();
  1162. var videoStream = new webkitMediaStream();
  1163. if(stream) {
  1164. var audioTracks = stream.getAudioTracks();
  1165. for (var i = 0; i < audioTracks.length; i++) {
  1166. audioStream.addTrack(audioTracks[i]);
  1167. }
  1168. var videoTracks = stream.getVideoTracks();
  1169. for (i = 0; i < videoTracks.length; i++) {
  1170. videoStream.addTrack(videoTracks[i]);
  1171. }
  1172. }
  1173. this.service.createLocalStream(audioStream, "audio");
  1174. this.service.createLocalStream(videoStream, "video");
  1175. }
  1176. else
  1177. {//firefox
  1178. this.service.createLocalStream(stream, "stream");
  1179. }
  1180. };
  1181. RTCUtils.prototype.createVideoStream = function(stream)
  1182. {
  1183. var videoStream = null;
  1184. if(window.webkitMediaStream)
  1185. {
  1186. videoStream = new webkitMediaStream();
  1187. if(stream)
  1188. {
  1189. var videoTracks = stream.getVideoTracks();
  1190. for (i = 0; i < videoTracks.length; i++) {
  1191. videoStream.addTrack(videoTracks[i]);
  1192. }
  1193. }
  1194. }
  1195. else
  1196. videoStream = stream;
  1197. return videoStream;
  1198. };
  1199. module.exports = RTCUtils;
  1200. },{"../../service/RTC/RTCBrowserType.js":88,"../../service/RTC/Resolutions":90}],8:[function(require,module,exports){
  1201. var UI = {};
  1202. var VideoLayout = require("./videolayout/VideoLayout.js");
  1203. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1204. var Prezi = require("./prezi/Prezi.js");
  1205. var Etherpad = require("./etherpad/Etherpad.js");
  1206. var Chat = require("./side_pannels/chat/Chat.js");
  1207. var Toolbar = require("./toolbars/Toolbar");
  1208. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1209. var BottomToolbar = require("./toolbars/BottomToolbar");
  1210. var ContactList = require("./side_pannels/contactlist/ContactList");
  1211. var Avatar = require("./avatar/Avatar");
  1212. var EventEmitter = require("events");
  1213. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1214. var Settings = require("./../settings/Settings");
  1215. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1216. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1217. UI.messageHandler = require("./util/MessageHandler");
  1218. var messageHandler = UI.messageHandler;
  1219. var Authentication = require("./authentication/Authentication");
  1220. var UIUtil = require("./util/UIUtil");
  1221. var NicknameHandler = require("./util/NicknameHandler");
  1222. var CQEvents = require("../../service/connectionquality/CQEvents");
  1223. var DesktopSharingEventTypes
  1224. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1225. var RTCEvents = require("../../service/RTC/RTCEvents");
  1226. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1227. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1228. var eventEmitter = new EventEmitter();
  1229. var roomName = null;
  1230. function setupPrezi()
  1231. {
  1232. $("#reloadPresentationLink").click(function()
  1233. {
  1234. Prezi.reloadPresentation();
  1235. });
  1236. }
  1237. function setupChat()
  1238. {
  1239. Chat.init();
  1240. $("#toggle_smileys").click(function() {
  1241. Chat.toggleSmileys();
  1242. });
  1243. }
  1244. function setupToolbars() {
  1245. Toolbar.init(UI);
  1246. Toolbar.setupButtonsFromConfig();
  1247. BottomToolbar.init();
  1248. }
  1249. function streamHandler(stream) {
  1250. switch (stream.type)
  1251. {
  1252. case "audio":
  1253. VideoLayout.changeLocalAudio(stream);
  1254. break;
  1255. case "video":
  1256. VideoLayout.changeLocalVideo(stream);
  1257. break;
  1258. case "stream":
  1259. VideoLayout.changeLocalStream(stream);
  1260. break;
  1261. }
  1262. }
  1263. function onDisposeConference(unload) {
  1264. Toolbar.showAuthenticateButton(false);
  1265. };
  1266. function onDisplayNameChanged(jid, displayName) {
  1267. ContactList.onDisplayNameChange(jid, displayName);
  1268. SettingsMenu.onDisplayNameChange(jid, displayName);
  1269. VideoLayout.onDisplayNameChanged(jid, displayName);
  1270. }
  1271. function registerListeners() {
  1272. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1273. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1274. APP.RTC.addStreamListener(function (stream) {
  1275. VideoLayout.onRemoteStreamAdded(stream);
  1276. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1277. APP.RTC.addStreamListener(function (jid) {
  1278. VideoLayout.onVideoTypeChanged(jid);
  1279. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  1280. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1281. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1282. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1283. });
  1284. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1285. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1286. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1287. endpointsEnteringLastN, stream);
  1288. });
  1289. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  1290. function (endpointSimulcastLayers) {
  1291. VideoLayout.onSimulcastLayersChanged(endpointSimulcastLayers);
  1292. });
  1293. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGING,
  1294. function (endpointSimulcastLayers) {
  1295. VideoLayout.onSimulcastLayersChanging(endpointSimulcastLayers);
  1296. });
  1297. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  1298. function (devices) {
  1299. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  1300. })
  1301. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1302. {
  1303. var resourceJid;
  1304. if(jid === APP.statistics.LOCAL_JID)
  1305. {
  1306. resourceJid = AudioLevels.LOCAL_LEVEL;
  1307. if(APP.RTC.localAudio.isMuted())
  1308. {
  1309. audioLevel = 0;
  1310. }
  1311. }
  1312. else
  1313. {
  1314. resourceJid = Strophe.getResourceFromJid(jid);
  1315. }
  1316. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1317. UI.getLargeVideoState().userResourceJid);
  1318. });
  1319. APP.desktopsharing.addListener(function () {
  1320. ToolbarToggler.showDesktopSharingButton();
  1321. }, DesktopSharingEventTypes.INIT);
  1322. APP.desktopsharing.addListener(
  1323. Toolbar.changeDesktopSharingButtonState,
  1324. DesktopSharingEventTypes.SWITCHING_DONE);
  1325. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1326. VideoLayout.updateLocalConnectionStats);
  1327. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1328. VideoLayout.updateConnectionStats);
  1329. APP.connectionquality.addListener(CQEvents.STOP,
  1330. VideoLayout.onStatsStop);
  1331. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1332. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  1333. messageHandler.openMessageDialog(
  1334. 'dialog.serviceUnavailable',
  1335. 'dialog.gracefulShutdown'
  1336. );
  1337. });
  1338. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  1339. var title = APP.translation.generateTranslatonHTML(
  1340. "dialog.reservationError");
  1341. var message = APP.translation.generateTranslatonHTML(
  1342. "dialog.reservationErrorMsg", {code: code, msg: msg});
  1343. messageHandler.openDialog(
  1344. title,
  1345. message,
  1346. true, {},
  1347. function (event, value, message, formVals)
  1348. {
  1349. return false;
  1350. }
  1351. );
  1352. });
  1353. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1354. messageHandler.openMessageDialog("dialog.sessTerminated",
  1355. "dialog.kickMessage");
  1356. });
  1357. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1358. //FIXME: use Session Terminated from translation, but
  1359. // 'reason' text comes from XMPP packet and is not translated
  1360. var title = APP.translation.generateTranslatonHTML("dialog.sessTerminated");
  1361. messageHandler.openDialog(
  1362. title, reason, true, {},
  1363. function (event, value, message, formVals)
  1364. {
  1365. return false;
  1366. }
  1367. );
  1368. });
  1369. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1370. messageHandler.showError("dialog.error",
  1371. "dialog.bridgeUnavailable");
  1372. });
  1373. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1374. Avatar.setUserAvatar(from, id);
  1375. });
  1376. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  1377. for(stream in changedStreams)
  1378. {
  1379. // might need to update the direction if participant just went from sendrecv to recvonly
  1380. if (stream.type === 'video' || stream.type === 'screen') {
  1381. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1382. switch (stream.direction) {
  1383. case 'sendrecv':
  1384. el.show();
  1385. break;
  1386. case 'recvonly':
  1387. el.hide();
  1388. // FIXME: Check if we have to change large video
  1389. //VideoLayout.updateLargeVideo(el);
  1390. break;
  1391. }
  1392. }
  1393. }
  1394. });
  1395. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1396. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1397. APP.xmpp.addListener(XMPPEvents.LOCALROLE_CHANGED, onLocalRoleChange);
  1398. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, onMucEntered);
  1399. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1400. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1401. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1402. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1403. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1404. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordReqiured);
  1405. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1406. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1407. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  1408. onAuthenticationRequired);
  1409. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  1410. function (resource, devices) {
  1411. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  1412. });
  1413. }
  1414. /**
  1415. * Mutes/unmutes the local video.
  1416. *
  1417. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1418. * @param options an object which specifies optional arguments such as the
  1419. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1420. * specifies whether the method was initiated in response to a user command (in
  1421. * contrast to an automatic decision taken by the application logic)
  1422. */
  1423. function setVideoMute(mute, options) {
  1424. APP.RTC.setVideoMute(mute,
  1425. UI.setVideoMuteButtonsState,
  1426. options);
  1427. }
  1428. function bindEvents()
  1429. {
  1430. /**
  1431. * Resizes and repositions videos in full screen mode.
  1432. */
  1433. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1434. function () {
  1435. VideoLayout.resizeLargeVideoContainer();
  1436. VideoLayout.positionLarge();
  1437. }
  1438. );
  1439. $(window).resize(function () {
  1440. VideoLayout.resizeLargeVideoContainer();
  1441. VideoLayout.positionLarge();
  1442. });
  1443. }
  1444. UI.start = function (init) {
  1445. document.title = interfaceConfig.APP_NAME;
  1446. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1447. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1448. {
  1449. $("#videoconference_page").hide();
  1450. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1451. setupWelcomePage();
  1452. return;
  1453. }
  1454. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1455. var leftWatermarkDiv
  1456. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1457. leftWatermarkDiv.css({display: 'block'});
  1458. leftWatermarkDiv.parent().get(0).href
  1459. = interfaceConfig.JITSI_WATERMARK_LINK;
  1460. }
  1461. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1462. var rightWatermarkDiv
  1463. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1464. rightWatermarkDiv.css({display: 'block'});
  1465. rightWatermarkDiv.parent().get(0).href
  1466. = interfaceConfig.BRAND_WATERMARK_LINK;
  1467. rightWatermarkDiv.get(0).style.backgroundImage
  1468. = "url(images/rightwatermark.png)";
  1469. }
  1470. if (interfaceConfig.SHOW_POWERED_BY) {
  1471. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1472. }
  1473. $("#welcome_page").hide();
  1474. VideoLayout.resizeLargeVideoContainer();
  1475. $("#videospace").mousemove(function () {
  1476. return ToolbarToggler.showToolbar();
  1477. });
  1478. // Set the defaults for prompt dialogs.
  1479. jQuery.prompt.setDefaults({persistent: false});
  1480. VideoLayout.init(eventEmitter);
  1481. AudioLevels.init();
  1482. NicknameHandler.init(eventEmitter);
  1483. registerListeners();
  1484. bindEvents();
  1485. setupPrezi();
  1486. setupToolbars();
  1487. setupChat();
  1488. document.title = interfaceConfig.APP_NAME;
  1489. $("#downloadlog").click(function (event) {
  1490. dump(event.target);
  1491. });
  1492. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1493. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1494. {
  1495. $("#videoconference_page").hide();
  1496. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1497. setupWelcomePage();
  1498. return;
  1499. }
  1500. $("#welcome_page").hide();
  1501. // Display notice message at the top of the toolbar
  1502. if (config.noticeMessage) {
  1503. $('#noticeText').text(config.noticeMessage);
  1504. $('#notice').css({display: 'block'});
  1505. }
  1506. document.getElementById('largeVideo').volume = 0;
  1507. if (!$('#settings').is(':visible')) {
  1508. console.log('init');
  1509. init();
  1510. } else {
  1511. loginInfo.onsubmit = function (e) {
  1512. if (e.preventDefault) e.preventDefault();
  1513. $('#settings').hide();
  1514. init();
  1515. };
  1516. }
  1517. toastr.options = {
  1518. "closeButton": true,
  1519. "debug": false,
  1520. "positionClass": "notification-bottom-right",
  1521. "onclick": null,
  1522. "showDuration": "300",
  1523. "hideDuration": "1000",
  1524. "timeOut": "2000",
  1525. "extendedTimeOut": "1000",
  1526. "showEasing": "swing",
  1527. "hideEasing": "linear",
  1528. "showMethod": "fadeIn",
  1529. "hideMethod": "fadeOut",
  1530. "reposition": function() {
  1531. if(PanelToggler.isVisible()) {
  1532. $("#toast-container").addClass("notification-bottom-right-center");
  1533. } else {
  1534. $("#toast-container").removeClass("notification-bottom-right-center");
  1535. }
  1536. },
  1537. "newestOnTop": false
  1538. };
  1539. SettingsMenu.init();
  1540. };
  1541. function chatAddError(errorMessage, originalText)
  1542. {
  1543. return Chat.chatAddError(errorMessage, originalText);
  1544. };
  1545. function chatSetSubject(text)
  1546. {
  1547. return Chat.chatSetSubject(text);
  1548. };
  1549. function updateChatConversation(from, displayName, message) {
  1550. return Chat.updateChatConversation(from, displayName, message);
  1551. };
  1552. function onMucJoined(jid, info) {
  1553. Toolbar.updateRoomUrl(window.location.href);
  1554. var meHTML = APP.translation.generateTranslatonHTML("me");
  1555. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  1556. var settings = Settings.getSettings();
  1557. // Add myself to the contact list.
  1558. ContactList.addContact(jid, settings.email || settings.uid);
  1559. // Once we've joined the muc show the toolbar
  1560. ToolbarToggler.showToolbar();
  1561. var displayName = !config.displayJids
  1562. ? info.displayName : Strophe.getResourceFromJid(jid);
  1563. if (displayName)
  1564. onDisplayNameChanged('localVideoContainer', displayName);
  1565. }
  1566. function initEtherpad(name) {
  1567. Etherpad.init(name);
  1568. };
  1569. function onMucLeft(jid) {
  1570. console.log('left.muc', jid);
  1571. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1572. '>.displayname').html();
  1573. messageHandler.notify(displayName,'notify.somebody',
  1574. 'disconnected',
  1575. 'notify.disconnected');
  1576. // Need to call this with a slight delay, otherwise the element couldn't be
  1577. // found for some reason.
  1578. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1579. window.setTimeout(function () {
  1580. var container = document.getElementById(
  1581. 'participant_' + Strophe.getResourceFromJid(jid));
  1582. if (container) {
  1583. ContactList.removeContact(jid);
  1584. VideoLayout.removeConnectionIndicator(jid);
  1585. // hide here, wait for video to close before removing
  1586. $(container).hide();
  1587. VideoLayout.resizeThumbnails();
  1588. }
  1589. }, 10);
  1590. VideoLayout.participantLeft(jid);
  1591. };
  1592. function onLocalRoleChange(jid, info, pres, isModerator)
  1593. {
  1594. console.info("My role changed, new role: " + info.role);
  1595. onModeratorStatusChanged(isModerator);
  1596. VideoLayout.showModeratorIndicator();
  1597. if (isModerator) {
  1598. Authentication.closeAuthenticationWindow();
  1599. messageHandler.notify(null, "notify.me",
  1600. 'connected', "notify.moderator");
  1601. }
  1602. }
  1603. function onModeratorStatusChanged(isModerator) {
  1604. Toolbar.showSipCallButton(isModerator);
  1605. Toolbar.showRecordingButton(
  1606. isModerator); //&&
  1607. // FIXME:
  1608. // Recording visible if
  1609. // there are at least 2(+ 1 focus) participants
  1610. //Object.keys(connection.emuc.members).length >= 3);
  1611. if (isModerator && config.etherpad_base) {
  1612. Etherpad.init();
  1613. }
  1614. };
  1615. function onPasswordReqiured(callback) {
  1616. // password is required
  1617. Toolbar.lockLockButton();
  1618. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1619. message += APP.translation.translateString(
  1620. "dialog.passwordRequired");
  1621. message += '</h2>' +
  1622. '<input name="lockKey" type="text" data-i18n=' +
  1623. '"[placeholder]dialog.password" placeholder="' +
  1624. APP.translation.translateString("dialog.password") +
  1625. '" autofocus>';
  1626. messageHandler.openTwoButtonDialog(null, null, null, message,
  1627. true,
  1628. "dialog.Ok",
  1629. function (e, v, m, f) {},
  1630. null,
  1631. function (e, v, m, f) {
  1632. if (v) {
  1633. var lockKey = f.lockKey;
  1634. if (lockKey) {
  1635. Toolbar.setSharedKey(lockKey);
  1636. callback(lockKey);
  1637. }
  1638. }
  1639. },
  1640. ':input:first'
  1641. );
  1642. }
  1643. function onMucEntered(jid, id, displayName) {
  1644. messageHandler.notify(displayName,'notify.somebody',
  1645. 'connected',
  1646. 'notify.connected');
  1647. // Add Peer's container
  1648. VideoLayout.ensurePeerContainerExists(jid,id);
  1649. }
  1650. function onMucPresenceStatus( jid, info) {
  1651. VideoLayout.setPresenceStatus(
  1652. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1653. }
  1654. function onMucRoleChanged(role, displayName) {
  1655. VideoLayout.showModeratorIndicator();
  1656. if (role === 'moderator') {
  1657. var messageKey, messageOptions = {};
  1658. if (!displayName) {
  1659. messageKey = "notify.grantedToUnknown";
  1660. }
  1661. else
  1662. {
  1663. messageKey = "notify.grantedTo";
  1664. messageOptions = {to: displayName};
  1665. }
  1666. messageHandler.notify(
  1667. displayName,'notify.somebody',
  1668. 'connected', messageKey,
  1669. messageOptions);
  1670. }
  1671. }
  1672. function onAuthenticationRequired(intervalCallback) {
  1673. Authentication.openAuthenticationDialog(
  1674. roomName, intervalCallback, function () {
  1675. Toolbar.authenticateClicked();
  1676. });
  1677. };
  1678. function onLastNChanged(oldValue, newValue) {
  1679. if (config.muteLocalVideoIfNotInLastN) {
  1680. setVideoMute(!newValue, { 'byUser': false });
  1681. }
  1682. }
  1683. UI.toggleSmileys = function () {
  1684. Chat.toggleSmileys();
  1685. };
  1686. UI.getSettings = function () {
  1687. return Settings.getSettings();
  1688. };
  1689. UI.toggleFilmStrip = function () {
  1690. return BottomToolbar.toggleFilmStrip();
  1691. };
  1692. UI.toggleChat = function () {
  1693. return BottomToolbar.toggleChat();
  1694. };
  1695. UI.toggleContactList = function () {
  1696. return BottomToolbar.toggleContactList();
  1697. };
  1698. UI.inputDisplayNameHandler = function (value) {
  1699. VideoLayout.inputDisplayNameHandler(value);
  1700. };
  1701. UI.getLargeVideoState = function()
  1702. {
  1703. return VideoLayout.getLargeVideoState();
  1704. };
  1705. UI.generateRoomName = function() {
  1706. if(roomName)
  1707. return roomName;
  1708. var roomnode = null;
  1709. var path = window.location.pathname;
  1710. // determinde the room node from the url
  1711. // TODO: just the roomnode or the whole bare jid?
  1712. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1713. // custom function might be responsible for doing the pushstate
  1714. roomnode = config.getroomnode(path);
  1715. } else {
  1716. /* fall back to default strategy
  1717. * this is making assumptions about how the URL->room mapping happens.
  1718. * It currently assumes deployment at root, with a rewrite like the
  1719. * following one (for nginx):
  1720. location ~ ^/([a-zA-Z0-9]+)$ {
  1721. rewrite ^/(.*)$ / break;
  1722. }
  1723. */
  1724. if (path.length > 1) {
  1725. roomnode = path.substr(1).toLowerCase();
  1726. } else {
  1727. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1728. roomnode = word.toLowerCase();
  1729. window.history.pushState('VideoChat',
  1730. 'Room: ' + word, window.location.pathname + word);
  1731. }
  1732. }
  1733. roomName = roomnode + '@' + config.hosts.muc;
  1734. return roomName;
  1735. };
  1736. UI.connectionIndicatorShowMore = function(id)
  1737. {
  1738. return VideoLayout.connectionIndicators[id].showMore();
  1739. };
  1740. UI.showLoginPopup = function(callback)
  1741. {
  1742. console.log('password is required');
  1743. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1744. message += APP.translation.translateString(
  1745. "dialog.passwordRequired");
  1746. message += '</h2>' +
  1747. '<input name="username" type="text" ' +
  1748. 'placeholder="user@domain.net" autofocus>' +
  1749. '<input name="password" ' +
  1750. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  1751. ' placeholder="user password">';
  1752. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  1753. true,
  1754. "dialog.Ok",
  1755. function (e, v, m, f) {
  1756. if (v) {
  1757. if (f.username !== null && f.password != null) {
  1758. callback(f.username, f.password);
  1759. }
  1760. }
  1761. },
  1762. null, null, ':input:first'
  1763. );
  1764. }
  1765. UI.checkForNicknameAndJoin = function () {
  1766. Authentication.closeAuthenticationDialog();
  1767. Authentication.stopInterval();
  1768. var nick = null;
  1769. if (config.useNicks) {
  1770. nick = window.prompt('Your nickname (optional)');
  1771. }
  1772. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1773. };
  1774. function dump(elem, filename) {
  1775. elem = elem.parentNode;
  1776. elem.download = filename || 'meetlog.json';
  1777. elem.href = 'data:application/json;charset=utf-8,\n';
  1778. var data = APP.xmpp.populateData();
  1779. var metadata = {};
  1780. metadata.time = new Date();
  1781. metadata.url = window.location.href;
  1782. metadata.ua = navigator.userAgent;
  1783. var log = APP.xmpp.getLogger();
  1784. if (log) {
  1785. metadata.xmpp = log;
  1786. }
  1787. data.metadata = metadata;
  1788. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1789. return false;
  1790. }
  1791. UI.getRoomName = function () {
  1792. return roomName;
  1793. };
  1794. /**
  1795. * Mutes/unmutes the local video.
  1796. */
  1797. UI.toggleVideo = function () {
  1798. setVideoMute(!APP.RTC.localVideo.isMuted());
  1799. };
  1800. /**
  1801. * Mutes / unmutes audio for the local participant.
  1802. */
  1803. UI.toggleAudio = function() {
  1804. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  1805. };
  1806. /**
  1807. * Sets muted audio state for the local participant.
  1808. */
  1809. UI.setAudioMuted = function (mute) {
  1810. if(!APP.xmpp.setAudioMute(mute, function () {
  1811. VideoLayout.showLocalAudioIndicator(mute);
  1812. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1813. }))
  1814. {
  1815. // We still click the button.
  1816. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1817. return;
  1818. }
  1819. }
  1820. UI.addListener = function (type, listener) {
  1821. eventEmitter.on(type, listener);
  1822. }
  1823. UI.clickOnVideo = function (videoNumber) {
  1824. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  1825. if (remoteVideos.length > videoNumber) {
  1826. remoteVideos[videoNumber].click();
  1827. }
  1828. }
  1829. //Used by torture
  1830. UI.showToolbar = function () {
  1831. return ToolbarToggler.showToolbar();
  1832. }
  1833. //Used by torture
  1834. UI.dockToolbar = function (isDock) {
  1835. return ToolbarToggler.dockToolbar(isDock);
  1836. }
  1837. UI.setVideoMuteButtonsState = function (mute) {
  1838. var video = $('#video');
  1839. var communicativeClass = "icon-camera";
  1840. var muteClass = "icon-camera icon-camera-disabled";
  1841. if (mute) {
  1842. video.removeClass(communicativeClass);
  1843. video.addClass(muteClass);
  1844. } else {
  1845. video.removeClass(muteClass);
  1846. video.addClass(communicativeClass);
  1847. }
  1848. }
  1849. module.exports = UI;
  1850. },{"../../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){
  1851. var CanvasUtil = require("./CanvasUtils");
  1852. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  1853. function initActiveSpeakerAudioLevels() {
  1854. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  1855. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  1856. // Draw a circle.
  1857. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  1858. // Add a shadow around the circle
  1859. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  1860. ASDrawContext.shadowOffsetX = 0;
  1861. ASDrawContext.shadowOffsetY = 0;
  1862. }
  1863. /**
  1864. * The audio Levels plugin.
  1865. */
  1866. var AudioLevels = (function(my) {
  1867. var audioLevelCanvasCache = {};
  1868. my.LOCAL_LEVEL = 'local';
  1869. my.init = function () {
  1870. initActiveSpeakerAudioLevels();
  1871. }
  1872. /**
  1873. * Updates the audio level canvas for the given peerJid. If the canvas
  1874. * didn't exist we create it.
  1875. */
  1876. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  1877. var resourceJid = null;
  1878. var videoSpanId = null;
  1879. if (!peerJid)
  1880. videoSpanId = 'localVideoContainer';
  1881. else {
  1882. resourceJid = Strophe.getResourceFromJid(peerJid);
  1883. videoSpanId = 'participant_' + resourceJid;
  1884. }
  1885. var videoSpan = document.getElementById(videoSpanId);
  1886. if (!videoSpan) {
  1887. if (resourceJid)
  1888. console.error("No video element for jid", resourceJid);
  1889. else
  1890. console.error("No video element for local video.");
  1891. return;
  1892. }
  1893. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  1894. var videoSpaceWidth = $('#remoteVideos').width();
  1895. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  1896. var thumbnailWidth = thumbnailSize[0];
  1897. var thumbnailHeight = thumbnailSize[1];
  1898. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  1899. audioLevelCanvas = document.createElement('canvas');
  1900. audioLevelCanvas.className = "audiolevel";
  1901. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1902. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1903. resizeAudioLevelCanvas( audioLevelCanvas,
  1904. thumbnailWidth,
  1905. thumbnailHeight);
  1906. videoSpan.appendChild(audioLevelCanvas);
  1907. } else {
  1908. audioLevelCanvas = audioLevelCanvas.get(0);
  1909. resizeAudioLevelCanvas( audioLevelCanvas,
  1910. thumbnailWidth,
  1911. thumbnailHeight);
  1912. }
  1913. };
  1914. /**
  1915. * Updates the audio level UI for the given resourceJid.
  1916. *
  1917. * @param resourceJid the resource jid indicating the video element for
  1918. * which we draw the audio level
  1919. * @param audioLevel the newAudio level to render
  1920. */
  1921. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  1922. drawAudioLevelCanvas(resourceJid, audioLevel);
  1923. var videoSpanId = getVideoSpanId(resourceJid);
  1924. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  1925. if (!audioLevelCanvas)
  1926. return;
  1927. var drawContext = audioLevelCanvas.getContext('2d');
  1928. var canvasCache = audioLevelCanvasCache[resourceJid];
  1929. drawContext.clearRect (0, 0,
  1930. audioLevelCanvas.width, audioLevelCanvas.height);
  1931. drawContext.drawImage(canvasCache, 0, 0);
  1932. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  1933. if(!APP.xmpp.myJid()) {
  1934. return;
  1935. }
  1936. resourceJid = APP.xmpp.myResource();
  1937. }
  1938. if(resourceJid === largeVideoResourceJid) {
  1939. window.requestAnimationFrame(function () {
  1940. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  1941. });
  1942. }
  1943. };
  1944. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  1945. if($("#activeSpeaker").css("visibility") == "hidden")
  1946. return;
  1947. ASDrawContext.clearRect(0, 0, 300, 300);
  1948. if(audioLevel == 0)
  1949. return;
  1950. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  1951. // Fill the shape.
  1952. ASDrawContext.fill();
  1953. };
  1954. /**
  1955. * Resizes the given audio level canvas to match the given thumbnail size.
  1956. */
  1957. function resizeAudioLevelCanvas(audioLevelCanvas,
  1958. thumbnailWidth,
  1959. thumbnailHeight) {
  1960. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  1961. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  1962. }
  1963. /**
  1964. * Draws the audio level canvas into the cached canvas object.
  1965. *
  1966. * @param resourceJid the resource jid indicating the video element for
  1967. * which we draw the audio level
  1968. * @param audioLevel the newAudio level to render
  1969. */
  1970. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  1971. if (!audioLevelCanvasCache[resourceJid]) {
  1972. var videoSpanId = getVideoSpanId(resourceJid);
  1973. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  1974. /*
  1975. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  1976. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  1977. * error. Since audio levels are frequently updated, the errors have
  1978. * been observed to pile into the console, strain the CPU.
  1979. */
  1980. if (audioLevelCanvasOrig)
  1981. {
  1982. audioLevelCanvasCache[resourceJid]
  1983. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  1984. }
  1985. }
  1986. var canvas = audioLevelCanvasCache[resourceJid];
  1987. if (!canvas)
  1988. return;
  1989. var drawContext = canvas.getContext('2d');
  1990. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  1991. var shadowLevel = getShadowLevel(audioLevel);
  1992. if (shadowLevel > 0)
  1993. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  1994. CanvasUtil.drawRoundRectGlow( drawContext,
  1995. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  1996. canvas.width - interfaceConfig.CANVAS_EXTRA,
  1997. canvas.height - interfaceConfig.CANVAS_EXTRA,
  1998. interfaceConfig.CANVAS_RADIUS,
  1999. interfaceConfig.SHADOW_COLOR,
  2000. shadowLevel);
  2001. }
  2002. /**
  2003. * Returns the shadow/glow level for the given audio level.
  2004. *
  2005. * @param audioLevel the audio level from which we determine the shadow
  2006. * level
  2007. */
  2008. function getShadowLevel (audioLevel) {
  2009. var shadowLevel = 0;
  2010. if (audioLevel <= 0.3) {
  2011. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  2012. }
  2013. else if (audioLevel <= 0.6) {
  2014. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  2015. }
  2016. else {
  2017. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  2018. }
  2019. return shadowLevel;
  2020. }
  2021. /**
  2022. * Returns the video span id corresponding to the given resourceJid or local
  2023. * user.
  2024. */
  2025. function getVideoSpanId(resourceJid) {
  2026. var videoSpanId = null;
  2027. if (resourceJid === AudioLevels.LOCAL_LEVEL
  2028. || (APP.xmpp.myResource() && resourceJid
  2029. === APP.xmpp.myResource()))
  2030. videoSpanId = 'localVideoContainer';
  2031. else
  2032. videoSpanId = 'participant_' + resourceJid;
  2033. return videoSpanId;
  2034. }
  2035. /**
  2036. * Indicates that the remote video has been resized.
  2037. */
  2038. $(document).bind('remotevideo.resized', function (event, width, height) {
  2039. var resized = false;
  2040. $('#remoteVideos>span>canvas').each(function() {
  2041. var canvas = $(this).get(0);
  2042. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  2043. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  2044. resized = true;
  2045. }
  2046. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  2047. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  2048. resized = true;
  2049. }
  2050. });
  2051. if (resized)
  2052. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  2053. audioLevelCanvasCache[resourceJid].width
  2054. = width + interfaceConfig.CANVAS_EXTRA;
  2055. audioLevelCanvasCache[resourceJid].height
  2056. = height + interfaceConfig.CANVAS_EXTRA;
  2057. });
  2058. });
  2059. return my;
  2060. })(AudioLevels || {});
  2061. module.exports = AudioLevels;
  2062. },{"./CanvasUtils":10}],10:[function(require,module,exports){
  2063. /**
  2064. * Utility class for drawing canvas shapes.
  2065. */
  2066. var CanvasUtil = (function(my) {
  2067. /**
  2068. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  2069. * of the glow.
  2070. *
  2071. * @param drawContext the context of the canvas to draw to
  2072. * @param x the x coordinate of the round rectangle
  2073. * @param y the y coordinate of the round rectangle
  2074. * @param w the width of the round rectangle
  2075. * @param h the height of the round rectangle
  2076. * @param glowColor the color of the glow
  2077. * @param glowWidth the width of the glow
  2078. */
  2079. my.drawRoundRectGlow
  2080. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  2081. // Save the previous state of the context.
  2082. drawContext.save();
  2083. if (w < 2 * r) r = w / 2;
  2084. if (h < 2 * r) r = h / 2;
  2085. // Draw a round rectangle.
  2086. drawContext.beginPath();
  2087. drawContext.moveTo(x+r, y);
  2088. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2089. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2090. drawContext.arcTo(x, y+h, x, y, r);
  2091. drawContext.arcTo(x, y, x+w, y, r);
  2092. drawContext.closePath();
  2093. // Add a shadow around the rectangle
  2094. drawContext.shadowColor = glowColor;
  2095. drawContext.shadowBlur = glowWidth;
  2096. drawContext.shadowOffsetX = 0;
  2097. drawContext.shadowOffsetY = 0;
  2098. // Fill the shape.
  2099. drawContext.fill();
  2100. drawContext.save();
  2101. drawContext.restore();
  2102. // 1) Uncomment this line to use Composite Operation, which is doing the
  2103. // same as the clip function below and is also antialiasing the round
  2104. // border, but is said to be less fast performance wise.
  2105. // drawContext.globalCompositeOperation='destination-out';
  2106. drawContext.beginPath();
  2107. drawContext.moveTo(x+r, y);
  2108. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2109. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2110. drawContext.arcTo(x, y+h, x, y, r);
  2111. drawContext.arcTo(x, y, x+w, y, r);
  2112. drawContext.closePath();
  2113. // 2) Uncomment this line to use Composite Operation, which is doing the
  2114. // same as the clip function below and is also antialiasing the round
  2115. // border, but is said to be less fast performance wise.
  2116. // drawContext.fill();
  2117. // Comment these two lines if choosing to do the same with composite
  2118. // operation above 1 and 2.
  2119. drawContext.clip();
  2120. drawContext.clearRect(0, 0, 277, 200);
  2121. // Restore the previous context state.
  2122. drawContext.restore();
  2123. };
  2124. /**
  2125. * Clones the given canvas.
  2126. *
  2127. * @return the new cloned canvas.
  2128. */
  2129. my.cloneCanvas = function (oldCanvas) {
  2130. /*
  2131. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2132. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2133. * levels are frequently updated, the errors have been observed to pile
  2134. * into the console, strain the CPU.
  2135. */
  2136. if (!oldCanvas)
  2137. return oldCanvas;
  2138. //create a new canvas
  2139. var newCanvas = document.createElement('canvas');
  2140. var context = newCanvas.getContext('2d');
  2141. //set dimensions
  2142. newCanvas.width = oldCanvas.width;
  2143. newCanvas.height = oldCanvas.height;
  2144. //apply the old canvas to the new one
  2145. context.drawImage(oldCanvas, 0, 0);
  2146. //return the new canvas
  2147. return newCanvas;
  2148. };
  2149. return my;
  2150. })(CanvasUtil || {});
  2151. module.exports = CanvasUtil;
  2152. },{}],11:[function(require,module,exports){
  2153. /* global $, APP*/
  2154. var LoginDialog = require('./LoginDialog');
  2155. var Moderator = require('../../xmpp/moderator');
  2156. /* Initial "authentication required" dialog */
  2157. var authDialog = null;
  2158. /* Loop retry ID that wits for other user to create the room */
  2159. var authRetryId = null;
  2160. var authenticationWindow = null;
  2161. var Authentication = {
  2162. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2163. // This is the loop that will wait for the room to be created by
  2164. // someone else. 'auth_required.moderator' will bring us back here.
  2165. authRetryId = window.setTimeout(intervalCallback, 5000);
  2166. // Show prompt only if it's not open
  2167. if (authDialog !== null) {
  2168. return;
  2169. }
  2170. // extract room name from 'room@muc.server.net'
  2171. var room = roomName.substr(0, roomName.indexOf('@'));
  2172. var title = APP.translation.generateTranslatonHTML("dialog.Stop");
  2173. var msg = APP.translation.generateTranslatonHTML("dialog.AuthMsg",
  2174. {room: room});
  2175. var buttonTxt
  2176. = APP.translation.generateTranslatonHTML("dialog.Authenticate");
  2177. var buttons = [];
  2178. buttons.push({title: buttonTxt, value: "authNow"});
  2179. authDialog = APP.UI.messageHandler.openDialog(
  2180. title,
  2181. msg,
  2182. true,
  2183. buttons,
  2184. function (onSubmitEvent, submitValue) {
  2185. // Do not close the dialog yet
  2186. onSubmitEvent.preventDefault();
  2187. // Open login popup
  2188. if (submitValue === 'authNow') {
  2189. callback();
  2190. }
  2191. }
  2192. );
  2193. },
  2194. closeAuthenticationWindow: function () {
  2195. if (authenticationWindow) {
  2196. authenticationWindow.close();
  2197. authenticationWindow = null;
  2198. }
  2199. },
  2200. xmppAuthenticate: function () {
  2201. var loginDialog = LoginDialog.show(
  2202. function (connection, state) {
  2203. if (!state) {
  2204. // User cancelled
  2205. loginDialog.close();
  2206. return;
  2207. } else if (state == APP.xmpp.Status.CONNECTED) {
  2208. loginDialog.close();
  2209. Authentication.stopInterval();
  2210. Authentication.closeAuthenticationDialog();
  2211. // Close the connection as anonymous one will be used
  2212. // to create the conference. Session-id will authorize
  2213. // the request.
  2214. connection.disconnect();
  2215. var roomName = APP.UI.generateRoomName();
  2216. Moderator.allocateConferenceFocus(roomName, function () {
  2217. // If it's not "on the fly" authentication now join
  2218. // the conference room
  2219. if (!APP.xmpp.getMUCJoined()) {
  2220. APP.UI.checkForNicknameAndJoin();
  2221. }
  2222. });
  2223. }
  2224. }, true);
  2225. },
  2226. focusAuthenticationWindow: function () {
  2227. // If auth window exists just bring it to the front
  2228. if (authenticationWindow) {
  2229. authenticationWindow.focus();
  2230. return;
  2231. }
  2232. },
  2233. closeAuthenticationDialog: function () {
  2234. // Close authentication dialog if opened
  2235. if (authDialog) {
  2236. authDialog.close();
  2237. authDialog = null;
  2238. }
  2239. },
  2240. createAuthenticationWindow: function (callback, url) {
  2241. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2242. url, 910, 660,
  2243. // On closed
  2244. function () {
  2245. // Close authentication dialog if opened
  2246. Authentication.closeAuthenticationDialog();
  2247. callback();
  2248. authenticationWindow = null;
  2249. });
  2250. return authenticationWindow;
  2251. },
  2252. stopInterval: function () {
  2253. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2254. if (authRetryId) {
  2255. window.clearTimeout(authRetryId);
  2256. authRetryId = null;
  2257. }
  2258. }
  2259. };
  2260. module.exports = Authentication;
  2261. },{"../../xmpp/moderator":53,"./LoginDialog":12}],12:[function(require,module,exports){
  2262. /* global $, APP, config*/
  2263. var XMPP = require('../../xmpp/xmpp');
  2264. var Moderator = require('../../xmpp/moderator');
  2265. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  2266. // anonymous domain is not enabled
  2267. /**
  2268. * Creates new <tt>Dialog</tt> instance.
  2269. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  2270. * when we either fail to connect or succeed(check Strophe.Status).
  2271. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  2272. * in order to create session-id after the connection is established.
  2273. * @constructor
  2274. */
  2275. function Dialog(callback, obtainSession) {
  2276. var self = this;
  2277. var stop = false;
  2278. var connection = APP.xmpp.createConnection();
  2279. var message = '<h2 data-i18n="dialog.passwordRequired">';
  2280. message += APP.translation.translateString("dialog.passwordRequired");
  2281. message += '</h2>' +
  2282. '<input name="username" type="text" ' +
  2283. 'placeholder="user@domain.net" autofocus>' +
  2284. '<input name="password" ' +
  2285. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  2286. ' placeholder="user password">';
  2287. var okButton = APP.translation.generateTranslatonHTML("dialog.Ok");
  2288. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel");
  2289. var states = {
  2290. login: {
  2291. html: message,
  2292. buttons: [
  2293. { title: okButton, value: true},
  2294. { title: cancelButton, value: false}
  2295. ],
  2296. focus: ':input:first',
  2297. submit: function (e, v, m, f) {
  2298. e.preventDefault();
  2299. if (v) {
  2300. var jid = f.username;
  2301. var password = f.password;
  2302. if (jid && password) {
  2303. stop = false;
  2304. connection.reset();
  2305. connDialog.goToState('connecting');
  2306. connection.connect(jid, password, stateHandler);
  2307. }
  2308. } else {
  2309. // User cancelled
  2310. stop = true;
  2311. callback();
  2312. }
  2313. }
  2314. },
  2315. connecting: {
  2316. title: APP.translation.translateString('dialog.connecting'),
  2317. html: '<div id="connectionStatus"></div>',
  2318. buttons: [],
  2319. defaultButton: 0
  2320. },
  2321. finished: {
  2322. title: APP.translation.translateString('dialog.error'),
  2323. html: '<div id="errorMessage"></div>',
  2324. buttons: [
  2325. {
  2326. title: APP.translation.translateString('dialog.retry'),
  2327. value: 'retry'
  2328. },
  2329. {
  2330. title: APP.translation.translateString('dialog.Cancel'),
  2331. value: 'cancel'
  2332. },
  2333. ],
  2334. defaultButton: 0,
  2335. submit: function (e, v, m, f) {
  2336. e.preventDefault();
  2337. if (v === 'retry')
  2338. connDialog.goToState('login');
  2339. else
  2340. callback();
  2341. }
  2342. }
  2343. };
  2344. var connDialog
  2345. = APP.UI.messageHandler.openDialogWithStates(states,
  2346. { persistent: true, closeText: '' }, null);
  2347. var stateHandler = function (status, message) {
  2348. if (stop) {
  2349. return;
  2350. }
  2351. var translateKey = "connection." + XMPP.getStatusString(status);
  2352. var statusStr = APP.translation.translateString(translateKey);
  2353. // Display current state
  2354. var connectionStatus =
  2355. connDialog.getState('connecting').find('#connectionStatus');
  2356. connectionStatus.text(statusStr);
  2357. switch (status) {
  2358. case XMPP.Status.CONNECTED:
  2359. stop = true;
  2360. if (!obtainSession) {
  2361. callback(connection, status);
  2362. return;
  2363. }
  2364. // Obtaining session-id status
  2365. connectionStatus.text(
  2366. APP.translation.translateString(
  2367. 'connection.FETCH_SESSION_ID'));
  2368. // Authenticate with Jicofo and obtain session-id
  2369. var roomName = APP.UI.generateRoomName();
  2370. // Jicofo will return new session-id when connected
  2371. // from authenticated domain
  2372. connection.sendIQ(
  2373. Moderator.createConferenceIq(roomName),
  2374. function (result) {
  2375. connectionStatus.text(
  2376. APP.translation.translateString(
  2377. 'connection.GOT_SESSION_ID'));
  2378. stop = true;
  2379. // Parse session-id
  2380. Moderator.parseSessionId(result);
  2381. callback(connection, status);
  2382. },
  2383. function (error) {
  2384. console.error("Auth on the fly failed", error);
  2385. stop = true;
  2386. var errorMsg =
  2387. APP.translation.translateString(
  2388. 'connection.GET_SESSION_ID_ERROR') +
  2389. $(error).find('>error').attr('code');
  2390. self.displayError(errorMsg);
  2391. connection.disconnect();
  2392. });
  2393. break;
  2394. case XMPP.Status.AUTHFAIL:
  2395. case XMPP.Status.CONNFAIL:
  2396. case XMPP.Status.DISCONNECTED:
  2397. stop = true;
  2398. callback(connection, status);
  2399. var errorMessage = statusStr;
  2400. if (message)
  2401. {
  2402. errorMessage += ': ' + message;
  2403. }
  2404. self.displayError(errorMessage);
  2405. break;
  2406. default:
  2407. break;
  2408. }
  2409. };
  2410. /**
  2411. * Displays error message in 'finished' state which allows either to cancel
  2412. * or retry.
  2413. * @param message the final message to be displayed.
  2414. */
  2415. this.displayError = function (message) {
  2416. var finishedState = connDialog.getState('finished');
  2417. var errorMessageElem = finishedState.find('#errorMessage');
  2418. errorMessageElem.text(message);
  2419. connDialog.goToState('finished');
  2420. };
  2421. /**
  2422. * Closes LoginDialog.
  2423. */
  2424. this.close = function () {
  2425. stop = true;
  2426. connDialog.close();
  2427. };
  2428. }
  2429. var LoginDialog = {
  2430. /**
  2431. * Displays login prompt used to establish new XMPP connection. Given
  2432. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  2433. * called when we connect successfully(status === CONNECTED) or when we fail
  2434. * to do so. On connection failure program can call Dialog.close() method in
  2435. * order to cancel or do nothing to let the user retry.
  2436. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  2437. * called when we either fail to connect or succeed(check
  2438. * Strophe.Status).
  2439. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  2440. * Jicofo in order to create session-id after the connection is
  2441. * established.
  2442. * @returns {Dialog}
  2443. */
  2444. show: function (callback, obtainSession) {
  2445. return new Dialog(callback, obtainSession);
  2446. }
  2447. };
  2448. module.exports = LoginDialog;
  2449. },{"../../xmpp/moderator":53,"../../xmpp/xmpp":61}],13:[function(require,module,exports){
  2450. var Settings = require("../../settings/Settings");
  2451. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2452. var users = {};
  2453. var activeSpeakerJid;
  2454. function setVisibility(selector, show) {
  2455. if (selector && selector.length > 0) {
  2456. selector.css("visibility", show ? "visible" : "hidden");
  2457. }
  2458. }
  2459. function isUserMuted(jid) {
  2460. // XXX(gp) we may want to rename this method to something like
  2461. // isUserStreaming, for example.
  2462. if (jid && jid != APP.xmpp.myJid()) {
  2463. var resource = Strophe.getResourceFromJid(jid);
  2464. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2465. return true;
  2466. }
  2467. }
  2468. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2469. return null;
  2470. }
  2471. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2472. }
  2473. function getGravatarUrl(id, size) {
  2474. if(id === APP.xmpp.myJid() || !id) {
  2475. id = Settings.getSettings().uid;
  2476. }
  2477. return 'https://www.gravatar.com/avatar/' +
  2478. MD5.hexdigest(id.trim().toLowerCase()) +
  2479. "?d=wavatar&size=" + (size || "30");
  2480. }
  2481. var Avatar = {
  2482. /**
  2483. * Sets the user's avatar in the settings menu(if local user), contact list
  2484. * and thumbnail
  2485. * @param jid jid of the user
  2486. * @param id email or userID to be used as a hash
  2487. */
  2488. setUserAvatar: function (jid, id) {
  2489. if (id) {
  2490. if (users[jid] === id) {
  2491. return;
  2492. }
  2493. users[jid] = id;
  2494. }
  2495. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2496. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2497. var resourceJid = Strophe.getResourceFromJid(jid);
  2498. var thumbnail = $('#participant_' + resourceJid);
  2499. var avatar = $('#avatar_' + resourceJid);
  2500. // set the avatar in the settings menu if it is local user and get the
  2501. // local video container
  2502. if (jid === APP.xmpp.myJid()) {
  2503. $('#avatar').get(0).src = thumbUrl;
  2504. thumbnail = $('#localVideoContainer');
  2505. }
  2506. // set the avatar in the contact list
  2507. var contact = $('#' + resourceJid + '>img');
  2508. if (contact && contact.length > 0) {
  2509. contact.get(0).src = contactListUrl;
  2510. }
  2511. // set the avatar in the thumbnail
  2512. if (avatar && avatar.length > 0) {
  2513. avatar[0].src = thumbUrl;
  2514. } else {
  2515. if (thumbnail && thumbnail.length > 0) {
  2516. avatar = document.createElement('img');
  2517. avatar.id = 'avatar_' + resourceJid;
  2518. avatar.className = 'userAvatar';
  2519. avatar.src = thumbUrl;
  2520. thumbnail.append(avatar);
  2521. }
  2522. }
  2523. //if the user is the current active speaker - update the active speaker
  2524. // avatar
  2525. if (jid === activeSpeakerJid) {
  2526. this.updateActiveSpeakerAvatarSrc(jid);
  2527. }
  2528. },
  2529. /**
  2530. * Hides or shows the user's avatar
  2531. * @param jid jid of the user
  2532. * @param show whether we should show the avatar or not
  2533. * video because there is no dominant speaker and no focused speaker
  2534. */
  2535. showUserAvatar: function (jid, show) {
  2536. if (users[jid]) {
  2537. var resourceJid = Strophe.getResourceFromJid(jid);
  2538. var video = $('#participant_' + resourceJid + '>video');
  2539. var avatar = $('#avatar_' + resourceJid);
  2540. if (jid === APP.xmpp.myJid()) {
  2541. video = $('#localVideoWrapper>video');
  2542. }
  2543. if (show === undefined || show === null) {
  2544. show = isUserMuted(jid);
  2545. }
  2546. //if the user is the currently focused, the dominant speaker or if
  2547. //there is no focused and no dominant speaker and the large video is
  2548. //currently shown
  2549. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2550. setVisibility($("#largeVideo"), !show);
  2551. setVisibility($('#activeSpeaker'), show);
  2552. setVisibility(avatar, false);
  2553. setVisibility(video, false);
  2554. } else {
  2555. if (video && video.length > 0) {
  2556. setVisibility(video, !show);
  2557. setVisibility(avatar, show);
  2558. }
  2559. }
  2560. }
  2561. },
  2562. /**
  2563. * Updates the src of the active speaker avatar
  2564. * @param jid of the current active speaker
  2565. */
  2566. updateActiveSpeakerAvatarSrc: function (jid) {
  2567. if (!jid) {
  2568. jid = APP.xmpp.findJidFromResource(
  2569. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2570. }
  2571. var avatar = $("#activeSpeakerAvatar")[0];
  2572. var url = getGravatarUrl(users[jid],
  2573. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2574. if (jid === activeSpeakerJid && avatar.src === url) {
  2575. return;
  2576. }
  2577. activeSpeakerJid = jid;
  2578. var isMuted = isUserMuted(jid);
  2579. if (jid && isMuted !== null) {
  2580. avatar.src = url;
  2581. setVisibility($("#largeVideo"), !isMuted);
  2582. Avatar.showUserAvatar(jid, isMuted);
  2583. }
  2584. }
  2585. };
  2586. module.exports = Avatar;
  2587. },{"../../../service/RTC/MediaStreamTypes":87,"../../settings/Settings":38,"../videolayout/VideoLayout":32}],14:[function(require,module,exports){
  2588. /* global $, config,
  2589. setLargeVideoVisible, Util */
  2590. var VideoLayout = require("../videolayout/VideoLayout");
  2591. var Prezi = require("../prezi/Prezi");
  2592. var UIUtil = require("../util/UIUtil");
  2593. var etherpadName = null;
  2594. var etherpadIFrame = null;
  2595. var domain = null;
  2596. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2597. /**
  2598. * Resizes the etherpad.
  2599. */
  2600. function resize() {
  2601. if ($('#etherpad>iframe').length) {
  2602. var remoteVideos = $('#remoteVideos');
  2603. var availableHeight
  2604. = window.innerHeight - remoteVideos.outerHeight();
  2605. var availableWidth = UIUtil.getAvailableVideoWidth();
  2606. $('#etherpad>iframe').width(availableWidth);
  2607. $('#etherpad>iframe').height(availableHeight);
  2608. }
  2609. }
  2610. /**
  2611. * Shares the Etherpad name with other participants.
  2612. */
  2613. function shareEtherpad() {
  2614. APP.xmpp.addToPresence("etherpad", etherpadName);
  2615. }
  2616. /**
  2617. * Creates the Etherpad button and adds it to the toolbar.
  2618. */
  2619. function enableEtherpadButton() {
  2620. if (!$('#etherpadButton').is(":visible"))
  2621. $('#etherpadButton').css({display: 'inline-block'});
  2622. }
  2623. /**
  2624. * Creates the IFrame for the etherpad.
  2625. */
  2626. function createIFrame() {
  2627. etherpadIFrame = document.createElement('iframe');
  2628. etherpadIFrame.src = domain + etherpadName + options;
  2629. etherpadIFrame.frameBorder = 0;
  2630. etherpadIFrame.scrolling = "no";
  2631. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2632. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2633. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2634. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2635. etherpadIFrame.onload = function() {
  2636. document.domain = document.domain;
  2637. bubbleIframeMouseMove(etherpadIFrame);
  2638. setTimeout(function() {
  2639. // the iframes inside of the etherpad are
  2640. // not yet loaded when the etherpad iframe is loaded
  2641. var outer = etherpadIFrame.
  2642. contentDocument.getElementsByName("ace_outer")[0];
  2643. bubbleIframeMouseMove(outer);
  2644. var inner = outer.
  2645. contentDocument.getElementsByName("ace_inner")[0];
  2646. bubbleIframeMouseMove(inner);
  2647. }, 2000);
  2648. };
  2649. }
  2650. function bubbleIframeMouseMove(iframe){
  2651. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2652. iframe.contentWindow.onmousemove = function(e){
  2653. if(existingOnMouseMove) existingOnMouseMove(e);
  2654. var evt = document.createEvent("MouseEvents");
  2655. var boundingClientRect = iframe.getBoundingClientRect();
  2656. evt.initMouseEvent(
  2657. "mousemove",
  2658. true, // bubbles
  2659. false, // not cancelable
  2660. window,
  2661. e.detail,
  2662. e.screenX,
  2663. e.screenY,
  2664. e.clientX + boundingClientRect.left,
  2665. e.clientY + boundingClientRect.top,
  2666. e.ctrlKey,
  2667. e.altKey,
  2668. e.shiftKey,
  2669. e.metaKey,
  2670. e.button,
  2671. null // no related element
  2672. );
  2673. iframe.dispatchEvent(evt);
  2674. };
  2675. }
  2676. /**
  2677. * On video selected event.
  2678. */
  2679. $(document).bind('video.selected', function (event, isPresentation) {
  2680. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2681. Etherpad.toggleEtherpad(isPresentation);
  2682. });
  2683. var Etherpad = {
  2684. /**
  2685. * Initializes the etherpad.
  2686. */
  2687. init: function (name) {
  2688. if (config.etherpad_base && !etherpadName) {
  2689. domain = config.etherpad_base;
  2690. if (!name) {
  2691. // In case we're the focus we generate the name.
  2692. etherpadName = Math.random().toString(36).substring(7) +
  2693. '_' + (new Date().getTime()).toString();
  2694. shareEtherpad();
  2695. }
  2696. else
  2697. etherpadName = name;
  2698. enableEtherpadButton();
  2699. /**
  2700. * Resizes the etherpad, when the window is resized.
  2701. */
  2702. $(window).resize(function () {
  2703. resize();
  2704. });
  2705. }
  2706. },
  2707. /**
  2708. * Opens/hides the Etherpad.
  2709. */
  2710. toggleEtherpad: function (isPresentation) {
  2711. if (!etherpadIFrame)
  2712. createIFrame();
  2713. var largeVideo = null;
  2714. if (Prezi.isPresentationVisible())
  2715. largeVideo = $('#presentation>iframe');
  2716. else
  2717. largeVideo = $('#largeVideo');
  2718. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2719. $('#activeSpeaker').css('visibility', 'hidden');
  2720. largeVideo.fadeOut(300, function () {
  2721. if (Prezi.isPresentationVisible()) {
  2722. largeVideo.css({opacity: '0'});
  2723. } else {
  2724. VideoLayout.setLargeVideoVisible(false);
  2725. }
  2726. });
  2727. $('#etherpad>iframe').fadeIn(300, function () {
  2728. document.body.style.background = '#eeeeee';
  2729. $('#etherpad>iframe').css({visibility: 'visible'});
  2730. $('#etherpad').css({zIndex: 2});
  2731. });
  2732. }
  2733. else if ($('#etherpad>iframe')) {
  2734. $('#etherpad>iframe').fadeOut(300, function () {
  2735. $('#etherpad>iframe').css({visibility: 'hidden'});
  2736. $('#etherpad').css({zIndex: 0});
  2737. document.body.style.background = 'black';
  2738. });
  2739. if (!isPresentation) {
  2740. $('#largeVideo').fadeIn(300, function () {
  2741. VideoLayout.setLargeVideoVisible(true);
  2742. });
  2743. }
  2744. }
  2745. resize();
  2746. },
  2747. isVisible: function() {
  2748. var etherpadIframe = $('#etherpad>iframe');
  2749. return etherpadIframe && etherpadIframe.is(':visible');
  2750. }
  2751. };
  2752. module.exports = Etherpad;
  2753. },{"../prezi/Prezi":15,"../util/UIUtil":30,"../videolayout/VideoLayout":32}],15:[function(require,module,exports){
  2754. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2755. var UIUtil = require("../util/UIUtil");
  2756. var VideoLayout = require("../videolayout/VideoLayout");
  2757. var messageHandler = require("../util/MessageHandler");
  2758. var PreziPlayer = require("./PreziPlayer");
  2759. var preziPlayer = null;
  2760. var Prezi = {
  2761. /**
  2762. * Reloads the current presentation.
  2763. */
  2764. reloadPresentation: function() {
  2765. var iframe = document.getElementById(preziPlayer.options.preziId);
  2766. iframe.src = iframe.src;
  2767. },
  2768. /**
  2769. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2770. * otherwise.
  2771. */
  2772. isPresentationVisible: function () {
  2773. return ($('#presentation>iframe') != null
  2774. && $('#presentation>iframe').css('opacity') == 1);
  2775. },
  2776. /**
  2777. * Opens the Prezi dialog, from which the user could choose a presentation
  2778. * to load.
  2779. */
  2780. openPreziDialog: function() {
  2781. var myprezi = APP.xmpp.getPrezi();
  2782. if (myprezi) {
  2783. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  2784. null,
  2785. "dialog.removePreziMsg",
  2786. null,
  2787. false,
  2788. "dialog.Remove",
  2789. function(e,v,m,f) {
  2790. if(v) {
  2791. APP.xmpp.removePreziFromPresence();
  2792. }
  2793. }
  2794. );
  2795. }
  2796. else if (preziPlayer != null) {
  2797. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  2798. null, "dialog.sharePreziMsg",
  2799. null,
  2800. false,
  2801. "dialog.Ok",
  2802. function(e,v,m,f) {
  2803. $.prompt.close();
  2804. }
  2805. );
  2806. }
  2807. else {
  2808. var html = APP.translation.generateTranslatonHTML(
  2809. "dialog.sharePreziTitle");
  2810. var cancelButton = APP.translation.generateTranslatonHTML(
  2811. "dialog.Cancel");
  2812. var shareButton = APP.translation.generateTranslatonHTML(
  2813. "dialog.Share");
  2814. var backButton = APP.translation.generateTranslatonHTML(
  2815. "dialog.Back");
  2816. var buttons = [];
  2817. var buttons1 = [];
  2818. // Cancel button to both states
  2819. buttons.push({title: cancelButton, value: false});
  2820. buttons1.push({title: cancelButton, value: false});
  2821. // Share button
  2822. buttons.push({title: shareButton, value: true});
  2823. // Back button
  2824. buttons1.push({title: backButton, value: true});
  2825. var linkError = APP.translation.generateTranslatonHTML(
  2826. "dialog.preziLinkError");
  2827. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  2828. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  2829. var openPreziState = {
  2830. state0: {
  2831. html: '<h2>' + html + '</h2>' +
  2832. '<input name="preziUrl" type="text" ' +
  2833. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  2834. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  2835. '\' placeholder="' + defaultUrl + '" autofocus>',
  2836. persistent: false,
  2837. buttons: buttons,
  2838. focus: ':input:first',
  2839. defaultButton: 0,
  2840. submit: function (e, v, m, f) {
  2841. e.preventDefault();
  2842. if(v)
  2843. {
  2844. var preziUrl = f.preziUrl;
  2845. if (preziUrl)
  2846. {
  2847. var urlValue
  2848. = encodeURI(UIUtil.escapeHtml(preziUrl));
  2849. if (urlValue.indexOf('http://prezi.com/') != 0
  2850. && urlValue.indexOf('https://prezi.com/') != 0)
  2851. {
  2852. $.prompt.goToState('state1');
  2853. return false;
  2854. }
  2855. else {
  2856. var presIdTmp = urlValue.substring(
  2857. urlValue.indexOf("prezi.com/") + 10);
  2858. if (!isAlphanumeric(presIdTmp)
  2859. || presIdTmp.indexOf('/') < 2) {
  2860. $.prompt.goToState('state1');
  2861. return false;
  2862. }
  2863. else {
  2864. APP.xmpp.addToPresence("prezi", urlValue);
  2865. $.prompt.close();
  2866. }
  2867. }
  2868. }
  2869. }
  2870. else
  2871. $.prompt.close();
  2872. }
  2873. },
  2874. state1: {
  2875. html: '<h2>' + html + '</h2>' +
  2876. linkError,
  2877. persistent: false,
  2878. buttons: buttons1,
  2879. focus: ':input:first',
  2880. defaultButton: 1,
  2881. submit: function (e, v, m, f) {
  2882. e.preventDefault();
  2883. if (v === 0)
  2884. $.prompt.close();
  2885. else
  2886. $.prompt.goToState('state0');
  2887. }
  2888. }
  2889. };
  2890. messageHandler.openDialogWithStates(openPreziState);
  2891. }
  2892. }
  2893. };
  2894. /**
  2895. * A new presentation has been added.
  2896. *
  2897. * @param event the event indicating the add of a presentation
  2898. * @param jid the jid from which the presentation was added
  2899. * @param presUrl url of the presentation
  2900. * @param currentSlide the current slide to which we should move
  2901. */
  2902. function presentationAdded(event, jid, presUrl, currentSlide) {
  2903. console.log("presentation added", presUrl);
  2904. var presId = getPresentationId(presUrl);
  2905. var elementId = 'participant_'
  2906. + Strophe.getResourceFromJid(jid)
  2907. + '_' + presId;
  2908. // We explicitly don't specify the peer jid here, because we don't want
  2909. // this video to be dealt with as a peer related one (for example we
  2910. // don't want to show a mute/kick menu for this one, etc.).
  2911. VideoLayout.addRemoteVideoContainer(null, elementId);
  2912. VideoLayout.resizeThumbnails();
  2913. var controlsEnabled = false;
  2914. if (jid === APP.xmpp.myJid())
  2915. controlsEnabled = true;
  2916. setPresentationVisible(true);
  2917. $('#largeVideoContainer').hover(
  2918. function (event) {
  2919. if (Prezi.isPresentationVisible()) {
  2920. var reloadButtonRight = window.innerWidth
  2921. - $('#presentation>iframe').offset().left
  2922. - $('#presentation>iframe').width();
  2923. $('#reloadPresentation').css({ right: reloadButtonRight,
  2924. display:'inline-block'});
  2925. }
  2926. },
  2927. function (event) {
  2928. if (!Prezi.isPresentationVisible())
  2929. $('#reloadPresentation').css({display:'none'});
  2930. else {
  2931. var e = event.toElement || event.relatedTarget;
  2932. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  2933. $('#reloadPresentation').css({display:'none'});
  2934. }
  2935. });
  2936. preziPlayer = new PreziPlayer(
  2937. 'presentation',
  2938. {preziId: presId,
  2939. width: getPresentationWidth(),
  2940. height: getPresentationHeihgt(),
  2941. controls: controlsEnabled,
  2942. debug: true
  2943. });
  2944. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  2945. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  2946. console.log("prezi status", event.value);
  2947. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  2948. if (jid != APP.xmpp.myJid())
  2949. preziPlayer.flyToStep(currentSlide);
  2950. }
  2951. });
  2952. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  2953. console.log("event value", event.value);
  2954. APP.xmpp.addToPresence("preziSlide", event.value);
  2955. });
  2956. $("#" + elementId).css( 'background-image',
  2957. 'url(../images/avatarprezi.png)');
  2958. $("#" + elementId).click(
  2959. function () {
  2960. setPresentationVisible(true);
  2961. }
  2962. );
  2963. };
  2964. /**
  2965. * A presentation has been removed.
  2966. *
  2967. * @param event the event indicating the remove of a presentation
  2968. * @param jid the jid for which the presentation was removed
  2969. * @param the url of the presentation
  2970. */
  2971. function presentationRemoved(event, jid, presUrl) {
  2972. console.log('presentation removed', presUrl);
  2973. var presId = getPresentationId(presUrl);
  2974. setPresentationVisible(false);
  2975. $('#participant_'
  2976. + Strophe.getResourceFromJid(jid)
  2977. + '_' + presId).remove();
  2978. $('#presentation>iframe').remove();
  2979. if (preziPlayer != null) {
  2980. preziPlayer.destroy();
  2981. preziPlayer = null;
  2982. }
  2983. };
  2984. /**
  2985. * Indicates if the given string is an alphanumeric string.
  2986. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  2987. * purpose of checking URIs.
  2988. */
  2989. function isAlphanumeric(unsafeText) {
  2990. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  2991. return regex.test(unsafeText);
  2992. }
  2993. /**
  2994. * Returns the presentation id from the given url.
  2995. */
  2996. function getPresentationId (presUrl) {
  2997. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  2998. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  2999. }
  3000. /**
  3001. * Returns the presentation width.
  3002. */
  3003. function getPresentationWidth() {
  3004. var availableWidth = UIUtil.getAvailableVideoWidth();
  3005. var availableHeight = getPresentationHeihgt();
  3006. var aspectRatio = 16.0 / 9.0;
  3007. if (availableHeight < availableWidth / aspectRatio) {
  3008. availableWidth = Math.floor(availableHeight * aspectRatio);
  3009. }
  3010. return availableWidth;
  3011. }
  3012. /**
  3013. * Returns the presentation height.
  3014. */
  3015. function getPresentationHeihgt() {
  3016. var remoteVideos = $('#remoteVideos');
  3017. return window.innerHeight - remoteVideos.outerHeight();
  3018. }
  3019. /**
  3020. * Resizes the presentation iframe.
  3021. */
  3022. function resize() {
  3023. if ($('#presentation>iframe')) {
  3024. $('#presentation>iframe').width(getPresentationWidth());
  3025. $('#presentation>iframe').height(getPresentationHeihgt());
  3026. }
  3027. }
  3028. /**
  3029. * Shows/hides a presentation.
  3030. */
  3031. function setPresentationVisible(visible) {
  3032. var prezi = $('#presentation>iframe');
  3033. if (visible) {
  3034. // Trigger the video.selected event to indicate a change in the
  3035. // large video.
  3036. $(document).trigger("video.selected", [true]);
  3037. $('#largeVideo').fadeOut(300);
  3038. prezi.fadeIn(300, function() {
  3039. prezi.css({opacity:'1'});
  3040. ToolbarToggler.dockToolbar(true);
  3041. VideoLayout.setLargeVideoVisible(false);
  3042. });
  3043. $('#activeSpeaker').css('visibility', 'hidden');
  3044. }
  3045. else {
  3046. if (prezi.css('opacity') == '1') {
  3047. prezi.fadeOut(300, function () {
  3048. prezi.css({opacity:'0'});
  3049. $('#reloadPresentation').css({display:'none'});
  3050. $('#largeVideo').fadeIn(300, function() {
  3051. VideoLayout.setLargeVideoVisible(true);
  3052. ToolbarToggler.dockToolbar(false);
  3053. });
  3054. });
  3055. }
  3056. }
  3057. }
  3058. /**
  3059. * Presentation has been removed.
  3060. */
  3061. $(document).bind('presentationremoved.muc', presentationRemoved);
  3062. /**
  3063. * Presentation has been added.
  3064. */
  3065. $(document).bind('presentationadded.muc', presentationAdded);
  3066. /*
  3067. * Indicates presentation slide change.
  3068. */
  3069. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  3070. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  3071. preziPlayer.flyToStep(current);
  3072. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  3073. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  3074. preziPlayer.flyToStep(current, i);
  3075. }
  3076. }
  3077. });
  3078. /**
  3079. * On video selected event.
  3080. */
  3081. $(document).bind('video.selected', function (event, isPresentation) {
  3082. if (!isPresentation && $('#presentation>iframe')) {
  3083. setPresentationVisible(false);
  3084. }
  3085. });
  3086. $(window).resize(function () {
  3087. resize();
  3088. });
  3089. module.exports = Prezi;
  3090. },{"../toolbars/ToolbarToggler":26,"../util/MessageHandler":28,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./PreziPlayer":16}],16:[function(require,module,exports){
  3091. (function() {
  3092. "use strict";
  3093. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  3094. window.PreziPlayer = (function() {
  3095. PreziPlayer.API_VERSION = 1;
  3096. PreziPlayer.CURRENT_STEP = 'currentStep';
  3097. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  3098. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  3099. PreziPlayer.STATUS_LOADING = 'loading';
  3100. PreziPlayer.STATUS_READY = 'ready';
  3101. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  3102. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  3103. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  3104. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  3105. PreziPlayer.EVENT_STATUS = "statusChange";
  3106. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  3107. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  3108. PreziPlayer.domain = "https://prezi.com";
  3109. PreziPlayer.path = "/player/";
  3110. PreziPlayer.players = {};
  3111. PreziPlayer.binded_methods = ['changesHandler'];
  3112. PreziPlayer.createMultiplePlayers = function(optionArray){
  3113. for(var i=0; i<optionArray.length; i++) {
  3114. var optionSet = optionArray[i];
  3115. new PreziPlayer(optionSet.id, optionSet);
  3116. };
  3117. };
  3118. PreziPlayer.messageReceived = function(event){
  3119. var message, item, player;
  3120. try {
  3121. message = JSON.parse(event.data);
  3122. if (message.id && (player = PreziPlayer.players[message.id])) {
  3123. if (player.options.debug === true) {
  3124. if (console && console.log)
  3125. console.log('received', message);
  3126. }
  3127. if (message.type === "changes") {
  3128. player.changesHandler(message);
  3129. }
  3130. for (var i = 0; i < player.callbacks.length; i++) {
  3131. item = player.callbacks[i];
  3132. if (item && message.type === item.event) {
  3133. item.callback(message);
  3134. }
  3135. }
  3136. }
  3137. } catch (e) { }
  3138. };
  3139. function PreziPlayer(id, options) {
  3140. var params, paramString = "", _this = this;
  3141. if (PreziPlayer.players[id]){
  3142. PreziPlayer.players[id].destroy();
  3143. }
  3144. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  3145. var method_name = PreziPlayer.binded_methods[i];
  3146. _this[method_name] = __bind(_this[method_name], _this);
  3147. };
  3148. options = options || {};
  3149. this.options = options;
  3150. this.values = {'status': PreziPlayer.STATUS_LOADING};
  3151. this.values[PreziPlayer.CURRENT_STEP] = 0;
  3152. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  3153. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  3154. this.callbacks = [];
  3155. this.id = id;
  3156. this.embedTo = document.getElementById(id);
  3157. if (!this.embedTo) {
  3158. throw "The element id is not available.";
  3159. }
  3160. this.iframe = document.createElement('iframe');
  3161. params = [
  3162. { name: 'oid', value: options.preziId },
  3163. { name: 'explorable', value: options.explorable ? 1 : 0 },
  3164. { name: 'controls', value: options.controls ? 1 : 0 }
  3165. ];
  3166. for(var i=0; i<params.length; i++) {
  3167. var param = params[i];
  3168. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  3169. };
  3170. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  3171. this.iframe.frameBorder = 0;
  3172. this.iframe.scrolling = "no";
  3173. this.iframe.width = options.width || 640;
  3174. this.iframe.height = options.height || 480;
  3175. this.embedTo.innerHTML = '';
  3176. // JITSI: IN CASE SOMETHING GOES WRONG.
  3177. try {
  3178. this.embedTo.appendChild(this.iframe);
  3179. }
  3180. catch (err) {
  3181. console.log("CATCH ERROR");
  3182. }
  3183. // JITSI: Increase interval from 200 to 500, which fixes prezi
  3184. // crashes for us.
  3185. this.initPollInterval = setInterval(function(){
  3186. _this.sendMessage({'action': 'init'});
  3187. }, 500);
  3188. PreziPlayer.players[id] = this;
  3189. }
  3190. PreziPlayer.prototype.changesHandler = function(message) {
  3191. var key, value, j, item;
  3192. if (this.initPollInterval) {
  3193. clearInterval(this.initPollInterval);
  3194. this.initPollInterval = false;
  3195. }
  3196. for (key in message.data) {
  3197. if (message.data.hasOwnProperty(key)){
  3198. value = message.data[key];
  3199. this.values[key] = value;
  3200. for (j=0; j<this.callbacks.length; j++) {
  3201. item = this.callbacks[j];
  3202. if (item && item.event === key + "Change"){
  3203. item.callback({type: item.event, value: value});
  3204. }
  3205. }
  3206. }
  3207. }
  3208. };
  3209. PreziPlayer.prototype.destroy = function() {
  3210. if (this.initPollInterval) {
  3211. clearInterval(this.initPollInterval);
  3212. this.initPollInterval = false;
  3213. }
  3214. this.embedTo.innerHTML = '';
  3215. };
  3216. PreziPlayer.prototype.sendMessage = function(message) {
  3217. if (this.options.debug === true) {
  3218. if (console && console.log) console.log('sent', message);
  3219. }
  3220. message.version = PreziPlayer.API_VERSION;
  3221. message.id = this.id;
  3222. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  3223. };
  3224. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  3225. PreziPlayer.prototype.flyToNextStep = function() {
  3226. return this.sendMessage({
  3227. 'action': 'present',
  3228. 'data': ['moveToNextStep']
  3229. });
  3230. };
  3231. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  3232. PreziPlayer.prototype.flyToPreviousStep = function() {
  3233. return this.sendMessage({
  3234. 'action': 'present',
  3235. 'data': ['moveToPrevStep']
  3236. });
  3237. };
  3238. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  3239. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  3240. var obj = this;
  3241. // check animation_step
  3242. if (animation_step > 0 &&
  3243. obj.values.animationCountOnSteps &&
  3244. obj.values.animationCountOnSteps[step] <= animation_step) {
  3245. animation_step = obj.values.animationCountOnSteps[step];
  3246. }
  3247. // jump to animation steps by calling flyToNextStep()
  3248. function doAnimationSteps() {
  3249. if (obj.values.isMoving == true) {
  3250. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  3251. return;
  3252. }
  3253. while (animation_step-- > 0) {
  3254. obj.flyToNextStep(); // do the animation steps
  3255. }
  3256. }
  3257. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  3258. // jump to the step
  3259. return this.sendMessage({
  3260. 'action': 'present',
  3261. 'data': ['moveToStep', step]
  3262. });
  3263. };
  3264. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  3265. PreziPlayer.prototype.flyToObject = function(objectId) {
  3266. return this.sendMessage({
  3267. 'action': 'present',
  3268. 'data': ['moveToObject', objectId]
  3269. });
  3270. };
  3271. PreziPlayer.prototype.play = function(defaultDelay) {
  3272. return this.sendMessage({
  3273. 'action': 'present',
  3274. 'data': ['startAutoPlay', defaultDelay]
  3275. });
  3276. };
  3277. PreziPlayer.prototype.stop = function() {
  3278. return this.sendMessage({
  3279. 'action': 'present',
  3280. 'data': ['stopAutoPlay']
  3281. });
  3282. };
  3283. PreziPlayer.prototype.pause = function(defaultDelay) {
  3284. return this.sendMessage({
  3285. 'action': 'present',
  3286. 'data': ['pauseAutoPlay', defaultDelay]
  3287. });
  3288. };
  3289. PreziPlayer.prototype.getCurrentStep = function() {
  3290. return this.values.currentStep;
  3291. };
  3292. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  3293. return this.values.currentAnimationStep;
  3294. };
  3295. PreziPlayer.prototype.getCurrentObject = function() {
  3296. return this.values.currentObject;
  3297. };
  3298. PreziPlayer.prototype.getStatus = function() {
  3299. return this.values.status;
  3300. };
  3301. PreziPlayer.prototype.isPlaying = function() {
  3302. return this.values.isAutoPlaying;
  3303. };
  3304. PreziPlayer.prototype.getStepCount = function() {
  3305. return this.values.stepCount;
  3306. };
  3307. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  3308. return this.values.animationCountOnSteps;
  3309. };
  3310. PreziPlayer.prototype.getTitle = function() {
  3311. return this.values.title;
  3312. };
  3313. PreziPlayer.prototype.setDimensions = function(dims) {
  3314. for (var parameter in dims) {
  3315. this.iframe[parameter] = dims[parameter];
  3316. }
  3317. }
  3318. PreziPlayer.prototype.getDimensions = function() {
  3319. return {
  3320. width: parseInt(this.iframe.width, 10),
  3321. height: parseInt(this.iframe.height, 10)
  3322. }
  3323. }
  3324. PreziPlayer.prototype.on = function(event, callback) {
  3325. this.callbacks.push({
  3326. event: event,
  3327. callback: callback
  3328. });
  3329. };
  3330. PreziPlayer.prototype.off = function(event, callback) {
  3331. var j, item;
  3332. if (event === undefined) {
  3333. this.callbacks = [];
  3334. }
  3335. j = this.callbacks.length;
  3336. while (j--) {
  3337. item = this.callbacks[j];
  3338. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3339. this.callbacks.splice(j, 1);
  3340. }
  3341. }
  3342. };
  3343. if (window.addEventListener) {
  3344. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3345. } else {
  3346. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3347. }
  3348. return PreziPlayer;
  3349. })();
  3350. })();
  3351. module.exports = PreziPlayer;
  3352. },{}],17:[function(require,module,exports){
  3353. var Chat = require("./chat/Chat");
  3354. var ContactList = require("./contactlist/ContactList");
  3355. var Settings = require("./../../settings/Settings");
  3356. var SettingsMenu = require("./settings/SettingsMenu");
  3357. var VideoLayout = require("../videolayout/VideoLayout");
  3358. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3359. var UIUtil = require("../util/UIUtil");
  3360. /**
  3361. * Toggler for the chat, contact list, settings menu, etc..
  3362. */
  3363. var PanelToggler = (function(my) {
  3364. var currentlyOpen = null;
  3365. var buttons = {
  3366. '#chatspace': '#chatBottomButton',
  3367. '#contactlist': '#contactListButton',
  3368. '#settingsmenu': '#settingsButton'
  3369. };
  3370. /**
  3371. * Resizes the video area
  3372. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3373. * @param completeFunction a function to be called when the video space is resized
  3374. */
  3375. var resizeVideoArea = function(isClosing, completeFunction) {
  3376. var videospace = $('#videospace');
  3377. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3378. var videospaceWidth = window.innerWidth - panelSize[0];
  3379. var videospaceHeight = window.innerHeight;
  3380. var videoSize
  3381. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3382. var videoWidth = videoSize[0];
  3383. var videoHeight = videoSize[1];
  3384. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3385. videoHeight,
  3386. videospaceWidth,
  3387. videospaceHeight);
  3388. var horizontalIndent = videoPosition[0];
  3389. var verticalIndent = videoPosition[1];
  3390. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3391. var thumbnailsWidth = thumbnailSize[0];
  3392. var thumbnailsHeight = thumbnailSize[1];
  3393. //for chat
  3394. videospace.animate({
  3395. right: panelSize[0],
  3396. width: videospaceWidth,
  3397. height: videospaceHeight
  3398. },
  3399. {
  3400. queue: false,
  3401. duration: 500,
  3402. complete: completeFunction
  3403. });
  3404. $('#remoteVideos').animate({
  3405. height: thumbnailsHeight
  3406. },
  3407. {
  3408. queue: false,
  3409. duration: 500
  3410. });
  3411. $('#remoteVideos>span').animate({
  3412. height: thumbnailsHeight,
  3413. width: thumbnailsWidth
  3414. },
  3415. {
  3416. queue: false,
  3417. duration: 500,
  3418. complete: function () {
  3419. $(document).trigger(
  3420. "remotevideo.resized",
  3421. [thumbnailsWidth,
  3422. thumbnailsHeight]);
  3423. }
  3424. });
  3425. $('#largeVideoContainer').animate({
  3426. width: videospaceWidth,
  3427. height: videospaceHeight
  3428. },
  3429. {
  3430. queue: false,
  3431. duration: 500
  3432. });
  3433. $('#largeVideo').animate({
  3434. width: videoWidth,
  3435. height: videoHeight,
  3436. top: verticalIndent,
  3437. bottom: verticalIndent,
  3438. left: horizontalIndent,
  3439. right: horizontalIndent
  3440. },
  3441. {
  3442. queue: false,
  3443. duration: 500
  3444. });
  3445. };
  3446. /**
  3447. * Toggles the windows in the side panel
  3448. * @param object the window that should be shown
  3449. * @param selector the selector for the element containing the panel
  3450. * @param onOpenComplete function to be called when the panel is opened
  3451. * @param onOpen function to be called if the window is going to be opened
  3452. * @param onClose function to be called if the window is going to be closed
  3453. */
  3454. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3455. UIUtil.buttonClick(buttons[selector], "active");
  3456. if (object.isVisible()) {
  3457. $("#toast-container").animate({
  3458. right: '5px'
  3459. },
  3460. {
  3461. queue: false,
  3462. duration: 500
  3463. });
  3464. $(selector).hide("slide", {
  3465. direction: "right",
  3466. queue: false,
  3467. duration: 500
  3468. });
  3469. if(typeof onClose === "function") {
  3470. onClose();
  3471. }
  3472. currentlyOpen = null;
  3473. }
  3474. else {
  3475. // Undock the toolbar when the chat is shown and if we're in a
  3476. // video mode.
  3477. if (VideoLayout.isLargeVideoVisible()) {
  3478. ToolbarToggler.dockToolbar(false);
  3479. }
  3480. if(currentlyOpen) {
  3481. var current = $(currentlyOpen);
  3482. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3483. current.css('z-index', 4);
  3484. setTimeout(function () {
  3485. current.css('display', 'none');
  3486. current.css('z-index', 5);
  3487. }, 500);
  3488. }
  3489. $("#toast-container").animate({
  3490. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3491. },
  3492. {
  3493. queue: false,
  3494. duration: 500
  3495. });
  3496. $(selector).show("slide", {
  3497. direction: "right",
  3498. queue: false,
  3499. duration: 500,
  3500. complete: onOpenComplete
  3501. });
  3502. if(typeof onOpen === "function") {
  3503. onOpen();
  3504. }
  3505. currentlyOpen = selector;
  3506. }
  3507. };
  3508. /**
  3509. * Opens / closes the chat area.
  3510. */
  3511. my.toggleChat = function() {
  3512. var chatCompleteFunction = Chat.isVisible() ?
  3513. function() {} : function () {
  3514. Chat.scrollChatToBottom();
  3515. $('#chatspace').trigger('shown');
  3516. };
  3517. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3518. toggle(Chat,
  3519. '#chatspace',
  3520. function () {
  3521. // Request the focus in the nickname field or the chat input field.
  3522. if ($('#nickname').css('visibility') === 'visible') {
  3523. $('#nickinput').focus();
  3524. } else {
  3525. $('#usermsg').focus();
  3526. }
  3527. },
  3528. null,
  3529. Chat.resizeChat,
  3530. null);
  3531. };
  3532. /**
  3533. * Opens / closes the contact list area.
  3534. */
  3535. my.toggleContactList = function () {
  3536. var completeFunction = ContactList.isVisible() ?
  3537. function() {} : function () { $('#contactlist').trigger('shown');};
  3538. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3539. toggle(ContactList,
  3540. '#contactlist',
  3541. null,
  3542. function() {
  3543. ContactList.setVisualNotification(false);
  3544. },
  3545. null);
  3546. };
  3547. /**
  3548. * Opens / closes the settings menu
  3549. */
  3550. my.toggleSettingsMenu = function() {
  3551. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3552. toggle(SettingsMenu,
  3553. '#settingsmenu',
  3554. null,
  3555. function() {
  3556. var settings = Settings.getSettings();
  3557. $('#setDisplayName').get(0).value = settings.displayName;
  3558. $('#setEmail').get(0).value = settings.email;
  3559. },
  3560. null);
  3561. };
  3562. /**
  3563. * Returns the size of the side panel.
  3564. */
  3565. my.getPanelSize = function () {
  3566. var availableHeight = window.innerHeight;
  3567. var availableWidth = window.innerWidth;
  3568. var panelWidth = 200;
  3569. if (availableWidth * 0.2 < 200) {
  3570. panelWidth = availableWidth * 0.2;
  3571. }
  3572. return [panelWidth, availableHeight];
  3573. };
  3574. my.isVisible = function() {
  3575. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3576. };
  3577. return my;
  3578. }(PanelToggler || {}));
  3579. module.exports = PanelToggler;
  3580. },{"../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){
  3581. /* global $, Util, nickname:true */
  3582. var Replacement = require("./Replacement");
  3583. var CommandsProcessor = require("./Commands");
  3584. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3585. var smileys = require("./smileys.json").smileys;
  3586. var NicknameHandler = require("../../util/NicknameHandler");
  3587. var UIUtil = require("../../util/UIUtil");
  3588. var UIEvents = require("../../../../service/UI/UIEvents");
  3589. var notificationInterval = false;
  3590. var unreadMessages = 0;
  3591. /**
  3592. * Shows/hides a visual notification, indicating that a message has arrived.
  3593. */
  3594. function setVisualNotification(show) {
  3595. var unreadMsgElement = document.getElementById('unreadMessages');
  3596. var unreadMsgBottomElement
  3597. = document.getElementById('bottomUnreadMessages');
  3598. var glower = $('#chatButton');
  3599. var bottomGlower = $('#chatBottomButton');
  3600. if (unreadMessages) {
  3601. unreadMsgElement.innerHTML = unreadMessages.toString();
  3602. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3603. ToolbarToggler.dockToolbar(true);
  3604. var chatButtonElement
  3605. = document.getElementById('chatButton').parentNode;
  3606. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3607. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3608. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3609. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3610. unreadMsgElement.setAttribute(
  3611. 'style',
  3612. 'top:' + topIndent +
  3613. '; left:' + leftIndent + ';');
  3614. var chatBottomButtonElement
  3615. = document.getElementById('chatBottomButton').parentNode;
  3616. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3617. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3618. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3619. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3620. unreadMsgBottomElement.setAttribute(
  3621. 'style',
  3622. 'top:' + bottomTopIndent +
  3623. '; left:' + bottomLeftIndent + ';');
  3624. if (!glower.hasClass('icon-chat-simple')) {
  3625. glower.removeClass('icon-chat');
  3626. glower.addClass('icon-chat-simple');
  3627. }
  3628. }
  3629. else {
  3630. unreadMsgElement.innerHTML = '';
  3631. unreadMsgBottomElement.innerHTML = '';
  3632. glower.removeClass('icon-chat-simple');
  3633. glower.addClass('icon-chat');
  3634. }
  3635. if (show && !notificationInterval) {
  3636. notificationInterval = window.setInterval(function () {
  3637. glower.toggleClass('active');
  3638. bottomGlower.toggleClass('active glowing');
  3639. }, 800);
  3640. }
  3641. else if (!show && notificationInterval) {
  3642. window.clearInterval(notificationInterval);
  3643. notificationInterval = false;
  3644. glower.removeClass('active');
  3645. bottomGlower.removeClass('glowing');
  3646. bottomGlower.addClass('active');
  3647. }
  3648. }
  3649. /**
  3650. * Returns the current time in the format it is shown to the user
  3651. * @returns {string}
  3652. */
  3653. function getCurrentTime() {
  3654. var now = new Date();
  3655. var hour = now.getHours();
  3656. var minute = now.getMinutes();
  3657. var second = now.getSeconds();
  3658. if(hour.toString().length === 1) {
  3659. hour = '0'+hour;
  3660. }
  3661. if(minute.toString().length === 1) {
  3662. minute = '0'+minute;
  3663. }
  3664. if(second.toString().length === 1) {
  3665. second = '0'+second;
  3666. }
  3667. return hour+':'+minute+':'+second;
  3668. }
  3669. function toggleSmileys()
  3670. {
  3671. var smileys = $('#smileysContainer');
  3672. if(!smileys.is(':visible')) {
  3673. smileys.show("slide", { direction: "down", duration: 300});
  3674. } else {
  3675. smileys.hide("slide", { direction: "down", duration: 300});
  3676. }
  3677. $('#usermsg').focus();
  3678. }
  3679. function addClickFunction(smiley, number) {
  3680. smiley.onclick = function addSmileyToMessage() {
  3681. var usermsg = $('#usermsg');
  3682. var message = usermsg.val();
  3683. message += smileys['smiley' + number];
  3684. usermsg.val(message);
  3685. usermsg.get(0).setSelectionRange(message.length, message.length);
  3686. toggleSmileys();
  3687. usermsg.focus();
  3688. };
  3689. }
  3690. /**
  3691. * Adds the smileys container to the chat
  3692. */
  3693. function addSmileys() {
  3694. var smileysContainer = document.createElement('div');
  3695. smileysContainer.id = 'smileysContainer';
  3696. for(var i = 1; i <= 21; i++) {
  3697. var smileyContainer = document.createElement('div');
  3698. smileyContainer.id = 'smiley' + i;
  3699. smileyContainer.className = 'smileyContainer';
  3700. var smiley = document.createElement('img');
  3701. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3702. smiley.className = 'smiley';
  3703. addClickFunction(smiley, i);
  3704. smileyContainer.appendChild(smiley);
  3705. smileysContainer.appendChild(smileyContainer);
  3706. }
  3707. $("#chatspace").append(smileysContainer);
  3708. }
  3709. /**
  3710. * Resizes the chat conversation.
  3711. */
  3712. function resizeChatConversation() {
  3713. var msgareaHeight = $('#usermsg').outerHeight();
  3714. var chatspace = $('#chatspace');
  3715. var width = chatspace.width();
  3716. var chat = $('#chatconversation');
  3717. var smileys = $('#smileysarea');
  3718. smileys.height(msgareaHeight);
  3719. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3720. $('#smileysContainer').css('bottom', msgareaHeight);
  3721. chat.width(width - 10);
  3722. chat.height(window.innerHeight - 15 - msgareaHeight);
  3723. }
  3724. /**
  3725. * Chat related user interface.
  3726. */
  3727. var Chat = (function (my) {
  3728. /**
  3729. * Initializes chat related interface.
  3730. */
  3731. my.init = function () {
  3732. if(NicknameHandler.getNickname())
  3733. Chat.setChatConversationMode(true);
  3734. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3735. function (nickname) {
  3736. Chat.setChatConversationMode(true);
  3737. });
  3738. $('#nickinput').keydown(function (event) {
  3739. if (event.keyCode === 13) {
  3740. event.preventDefault();
  3741. var val = UIUtil.escapeHtml(this.value);
  3742. this.value = '';
  3743. if (!NicknameHandler.getNickname()) {
  3744. NicknameHandler.setNickname(val);
  3745. return;
  3746. }
  3747. }
  3748. });
  3749. $('#usermsg').keydown(function (event) {
  3750. if (event.keyCode === 13) {
  3751. event.preventDefault();
  3752. var value = this.value;
  3753. $('#usermsg').val('').trigger('autosize.resize');
  3754. this.focus();
  3755. var command = new CommandsProcessor(value);
  3756. if(command.isCommand())
  3757. {
  3758. command.processCommand();
  3759. }
  3760. else
  3761. {
  3762. var message = UIUtil.escapeHtml(value);
  3763. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3764. }
  3765. }
  3766. });
  3767. var onTextAreaResize = function () {
  3768. resizeChatConversation();
  3769. Chat.scrollChatToBottom();
  3770. };
  3771. $('#usermsg').autosize({callback: onTextAreaResize});
  3772. $("#chatspace").bind("shown",
  3773. function () {
  3774. unreadMessages = 0;
  3775. setVisualNotification(false);
  3776. });
  3777. addSmileys();
  3778. };
  3779. /**
  3780. * Appends the given message to the chat conversation.
  3781. */
  3782. my.updateChatConversation = function (from, displayName, message) {
  3783. var divClassName = '';
  3784. if (APP.xmpp.myJid() === from) {
  3785. divClassName = "localuser";
  3786. }
  3787. else {
  3788. divClassName = "remoteuser";
  3789. if (!Chat.isVisible()) {
  3790. unreadMessages++;
  3791. UIUtil.playSoundNotification('chatNotification');
  3792. setVisualNotification(true);
  3793. }
  3794. }
  3795. // replace links and smileys
  3796. // Strophe already escapes special symbols on sending,
  3797. // so we escape here only tags to avoid double &amp;
  3798. var escMessage = message.replace(/</g, '&lt;').
  3799. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  3800. var escDisplayName = UIUtil.escapeHtml(displayName);
  3801. message = Replacement.processReplacements(escMessage);
  3802. var messageContainer =
  3803. '<div class="chatmessage">'+
  3804. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  3805. '<div class="username ' + divClassName +'">' + escDisplayName +
  3806. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  3807. '</div>' + '<div class="usermessage">' + message + '</div>' +
  3808. '</div>';
  3809. $('#chatconversation').append(messageContainer);
  3810. $('#chatconversation').animate(
  3811. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3812. };
  3813. /**
  3814. * Appends error message to the conversation
  3815. * @param errorMessage the received error message.
  3816. * @param originalText the original message.
  3817. */
  3818. my.chatAddError = function(errorMessage, originalText)
  3819. {
  3820. errorMessage = UIUtil.escapeHtml(errorMessage);
  3821. originalText = UIUtil.escapeHtml(originalText);
  3822. $('#chatconversation').append(
  3823. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  3824. (originalText? (' \"'+ originalText + '\"') : "") +
  3825. ' was not sent.' +
  3826. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  3827. $('#chatconversation').animate(
  3828. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3829. };
  3830. /**
  3831. * Sets the subject to the UI
  3832. * @param subject the subject
  3833. */
  3834. my.chatSetSubject = function(subject)
  3835. {
  3836. if(subject)
  3837. subject = subject.trim();
  3838. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  3839. if(subject === "")
  3840. {
  3841. $("#subject").css({display: "none"});
  3842. }
  3843. else
  3844. {
  3845. $("#subject").css({display: "block"});
  3846. }
  3847. };
  3848. /**
  3849. * Sets the chat conversation mode.
  3850. */
  3851. my.setChatConversationMode = function (isConversationMode) {
  3852. if (isConversationMode) {
  3853. $('#nickname').css({visibility: 'hidden'});
  3854. $('#chatconversation').css({visibility: 'visible'});
  3855. $('#usermsg').css({visibility: 'visible'});
  3856. $('#smileysarea').css({visibility: 'visible'});
  3857. $('#usermsg').focus();
  3858. }
  3859. };
  3860. /**
  3861. * Resizes the chat area.
  3862. */
  3863. my.resizeChat = function () {
  3864. var chatSize = require("../SidePanelToggler").getPanelSize();
  3865. $('#chatspace').width(chatSize[0]);
  3866. $('#chatspace').height(chatSize[1]);
  3867. resizeChatConversation();
  3868. };
  3869. /**
  3870. * Indicates if the chat is currently visible.
  3871. */
  3872. my.isVisible = function () {
  3873. return $('#chatspace').is(":visible");
  3874. };
  3875. /**
  3876. * Shows and hides the window with the smileys
  3877. */
  3878. my.toggleSmileys = toggleSmileys;
  3879. /**
  3880. * Scrolls chat to the bottom.
  3881. */
  3882. my.scrollChatToBottom = function() {
  3883. setTimeout(function () {
  3884. $('#chatconversation').scrollTop(
  3885. $('#chatconversation')[0].scrollHeight);
  3886. }, 5);
  3887. };
  3888. return my;
  3889. }(Chat || {}));
  3890. module.exports = Chat;
  3891. },{"../../../../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){
  3892. var UIUtil = require("../../util/UIUtil");
  3893. /**
  3894. * List with supported commands. The keys are the names of the commands and
  3895. * the value is the function that processes the message.
  3896. * @type {{String: function}}
  3897. */
  3898. var commands = {
  3899. "topic" : processTopic
  3900. };
  3901. /**
  3902. * Extracts the command from the message.
  3903. * @param message the received message
  3904. * @returns {string} the command
  3905. */
  3906. function getCommand(message)
  3907. {
  3908. if(message)
  3909. {
  3910. for(var command in commands)
  3911. {
  3912. if(message.indexOf("/" + command) == 0)
  3913. return command;
  3914. }
  3915. }
  3916. return "";
  3917. };
  3918. /**
  3919. * Processes the data for topic command.
  3920. * @param commandArguments the arguments of the topic command.
  3921. */
  3922. function processTopic(commandArguments)
  3923. {
  3924. var topic = UIUtil.escapeHtml(commandArguments);
  3925. APP.xmpp.setSubject(topic);
  3926. }
  3927. /**
  3928. * Constructs new CommandProccessor instance from a message that
  3929. * handles commands received via chat messages.
  3930. * @param message the message
  3931. * @constructor
  3932. */
  3933. function CommandsProcessor(message)
  3934. {
  3935. var command = getCommand(message);
  3936. /**
  3937. * Returns the name of the command.
  3938. * @returns {String} the command
  3939. */
  3940. this.getCommand = function()
  3941. {
  3942. return command;
  3943. };
  3944. var messageArgument = message.substr(command.length + 2);
  3945. /**
  3946. * Returns the arguments of the command.
  3947. * @returns {string}
  3948. */
  3949. this.getArgument = function()
  3950. {
  3951. return messageArgument;
  3952. };
  3953. }
  3954. /**
  3955. * Checks whether this instance is valid command or not.
  3956. * @returns {boolean}
  3957. */
  3958. CommandsProcessor.prototype.isCommand = function()
  3959. {
  3960. if(this.getCommand())
  3961. return true;
  3962. return false;
  3963. };
  3964. /**
  3965. * Processes the command.
  3966. */
  3967. CommandsProcessor.prototype.processCommand = function()
  3968. {
  3969. if(!this.isCommand())
  3970. return;
  3971. commands[this.getCommand()](this.getArgument());
  3972. };
  3973. module.exports = CommandsProcessor;
  3974. },{"../../util/UIUtil":30}],20:[function(require,module,exports){
  3975. var Smileys = require("./smileys.json");
  3976. /**
  3977. * Processes links and smileys in "body"
  3978. */
  3979. function processReplacements(body)
  3980. {
  3981. //make links clickable
  3982. body = linkify(body);
  3983. //add smileys
  3984. body = smilify(body);
  3985. return body;
  3986. }
  3987. /**
  3988. * Finds and replaces all links in the links in "body"
  3989. * with their <a href=""></a>
  3990. */
  3991. function linkify(inputText)
  3992. {
  3993. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  3994. //URLs starting with http://, https://, or ftp://
  3995. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  3996. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  3997. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  3998. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  3999. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  4000. //Change email addresses to mailto:: links.
  4001. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  4002. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  4003. return replacedText;
  4004. }
  4005. /**
  4006. * Replaces common smiley strings with images
  4007. */
  4008. function smilify(body)
  4009. {
  4010. if(!body) {
  4011. return body;
  4012. }
  4013. var regexs = Smileys["regexs"];
  4014. for(var smiley in regexs) {
  4015. if(regexs.hasOwnProperty(smiley)) {
  4016. body = body.replace(regexs[smiley],
  4017. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  4018. }
  4019. }
  4020. return body;
  4021. }
  4022. module.exports = {
  4023. processReplacements: processReplacements,
  4024. linkify: linkify
  4025. };
  4026. },{"./smileys.json":21}],21:[function(require,module,exports){
  4027. module.exports={
  4028. "smileys": {
  4029. "smiley1": ":)",
  4030. "smiley2": ":(",
  4031. "smiley3": ":D",
  4032. "smiley4": "(y)",
  4033. "smiley5": " :P",
  4034. "smiley6": "(wave)",
  4035. "smiley7": "(blush)",
  4036. "smiley8": "(chuckle)",
  4037. "smiley9": "(shocked)",
  4038. "smiley10": ":*",
  4039. "smiley11": "(n)",
  4040. "smiley12": "(search)",
  4041. "smiley13": " <3",
  4042. "smiley14": "(oops)",
  4043. "smiley15": "(angry)",
  4044. "smiley16": "(angel)",
  4045. "smiley17": "(sick)",
  4046. "smiley18": ";(",
  4047. "smiley19": "(bomb)",
  4048. "smiley20": "(clap)",
  4049. "smiley21": " ;)"
  4050. },
  4051. "regexs": {
  4052. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  4053. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  4054. "smiley1": /(:-\)|:\))/gi,
  4055. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  4056. "smiley5": /(:-P|:P|:-p|:p)/gi,
  4057. "smiley6": /(\(wave\))/gi,
  4058. "smiley7": /(\(blush\))/gi,
  4059. "smiley8": /(\(chuckle\))/gi,
  4060. "smiley9": /(:-0|\(shocked\))/gi,
  4061. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  4062. "smiley11": /(\(n\))/gi,
  4063. "smiley12": /(\(search\))/g,
  4064. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  4065. "smiley14": /(\(oops\))/gi,
  4066. "smiley15": /(\(angry\))/gi,
  4067. "smiley16": /(\(angel\))/gi,
  4068. "smiley17": /(\(sick\))/gi,
  4069. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  4070. "smiley19": /(\(bomb\))/gi,
  4071. "smiley20": /(\(clap\))/gi,
  4072. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  4073. }
  4074. }
  4075. },{}],22:[function(require,module,exports){
  4076. var numberOfContacts = 0;
  4077. var notificationInterval;
  4078. /**
  4079. * Updates the number of participants in the contact list button and sets
  4080. * the glow
  4081. * @param delta indicates whether a new user has joined (1) or someone has
  4082. * left(-1)
  4083. */
  4084. function updateNumberOfParticipants(delta) {
  4085. //when the user is alone we don't show the number of participants
  4086. if(numberOfContacts === 0) {
  4087. $("#numberOfParticipants").text('');
  4088. numberOfContacts += delta;
  4089. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  4090. ContactList.setVisualNotification(true);
  4091. numberOfContacts += delta;
  4092. $("#numberOfParticipants").text(numberOfContacts);
  4093. }
  4094. }
  4095. /**
  4096. * Creates the avatar element.
  4097. *
  4098. * @return the newly created avatar element
  4099. */
  4100. function createAvatar(id) {
  4101. var avatar = document.createElement('img');
  4102. avatar.className = "icon-avatar avatar";
  4103. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  4104. return avatar;
  4105. }
  4106. /**
  4107. * Creates the display name paragraph.
  4108. *
  4109. * @param displayName the display name to set
  4110. */
  4111. function createDisplayNameParagraph(key, displayName) {
  4112. var p = document.createElement('p');
  4113. if(displayName)
  4114. p.innerText = displayName;
  4115. else if(key)
  4116. {
  4117. p.setAttribute("data-i18n",key);
  4118. p.innerText = APP.translation.translateString(key);
  4119. }
  4120. return p;
  4121. }
  4122. function stopGlowing(glower) {
  4123. window.clearInterval(notificationInterval);
  4124. notificationInterval = false;
  4125. glower.removeClass('glowing');
  4126. if (!ContactList.isVisible()) {
  4127. glower.removeClass('active');
  4128. }
  4129. }
  4130. /**
  4131. * Contact list.
  4132. */
  4133. var ContactList = {
  4134. /**
  4135. * Indicates if the chat is currently visible.
  4136. *
  4137. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  4138. * otherwise
  4139. */
  4140. isVisible: function () {
  4141. return $('#contactlist').is(":visible");
  4142. },
  4143. /**
  4144. * Adds a contact for the given peerJid if such doesn't yet exist.
  4145. *
  4146. * @param peerJid the peerJid corresponding to the contact
  4147. * @param id the user's email or userId used to get the user's avatar
  4148. */
  4149. ensureAddContact: function (peerJid, id) {
  4150. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4151. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4152. if (!contact || contact.length <= 0)
  4153. ContactList.addContact(peerJid, id);
  4154. },
  4155. /**
  4156. * Adds a contact for the given peer jid.
  4157. *
  4158. * @param peerJid the jid of the contact to add
  4159. * @param id the email or userId of the user
  4160. */
  4161. addContact: function (peerJid, id) {
  4162. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4163. var contactlist = $('#contactlist>ul');
  4164. var newContact = document.createElement('li');
  4165. newContact.id = resourceJid;
  4166. newContact.className = "clickable";
  4167. newContact.onclick = function (event) {
  4168. if (event.currentTarget.className === "clickable") {
  4169. $(ContactList).trigger('contactclicked', [peerJid]);
  4170. }
  4171. };
  4172. newContact.appendChild(createAvatar(id));
  4173. newContact.appendChild(createDisplayNameParagraph("participant"));
  4174. var clElement = contactlist.get(0);
  4175. if (resourceJid === APP.xmpp.myResource()
  4176. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  4177. clElement.insertBefore(newContact,
  4178. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  4179. }
  4180. else {
  4181. clElement.appendChild(newContact);
  4182. }
  4183. updateNumberOfParticipants(1);
  4184. },
  4185. /**
  4186. * Removes a contact for the given peer jid.
  4187. *
  4188. * @param peerJid the peerJid corresponding to the contact to remove
  4189. */
  4190. removeContact: function (peerJid) {
  4191. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4192. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4193. if (contact && contact.length > 0) {
  4194. var contactlist = $('#contactlist>ul');
  4195. contactlist.get(0).removeChild(contact.get(0));
  4196. updateNumberOfParticipants(-1);
  4197. }
  4198. },
  4199. setVisualNotification: function (show, stopGlowingIn) {
  4200. var glower = $('#contactListButton');
  4201. if (show && !notificationInterval) {
  4202. notificationInterval = window.setInterval(function () {
  4203. glower.toggleClass('active glowing');
  4204. }, 800);
  4205. }
  4206. else if (!show && notificationInterval) {
  4207. stopGlowing(glower);
  4208. }
  4209. if (stopGlowingIn) {
  4210. setTimeout(function () {
  4211. stopGlowing(glower);
  4212. }, stopGlowingIn);
  4213. }
  4214. },
  4215. setClickable: function (resourceJid, isClickable) {
  4216. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4217. if (isClickable) {
  4218. contact.addClass('clickable');
  4219. } else {
  4220. contact.removeClass('clickable');
  4221. }
  4222. },
  4223. onDisplayNameChange: function (peerJid, displayName) {
  4224. if (peerJid === 'localVideoContainer')
  4225. peerJid = APP.xmpp.myJid();
  4226. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4227. var contactName = $('#contactlist #' + resourceJid + '>p');
  4228. if (contactName && displayName && displayName.length > 0)
  4229. contactName.html(displayName);
  4230. }
  4231. };
  4232. module.exports = ContactList;
  4233. },{}],23:[function(require,module,exports){
  4234. var Avatar = require("../../avatar/Avatar");
  4235. var Settings = require("./../../../settings/Settings");
  4236. var UIUtil = require("../../util/UIUtil");
  4237. var languages = require("../../../../service/translation/languages");
  4238. function generateLanguagesSelectBox()
  4239. {
  4240. var currentLang = APP.translation.getCurrentLanguage();
  4241. var html = "<select id=\"languages_selectbox\">";
  4242. var langArray = languages.getLanguages();
  4243. for(var i = 0; i < langArray.length; i++)
  4244. {
  4245. var lang = langArray[i];
  4246. html += "<option ";
  4247. if(lang === currentLang)
  4248. html += "selected ";
  4249. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  4250. html += "</option>";
  4251. }
  4252. return html + "</select>";
  4253. }
  4254. var SettingsMenu = {
  4255. init: function () {
  4256. $("#updateSettings").before(generateLanguagesSelectBox());
  4257. APP.translation.translateElement($("#languages_selectbox"));
  4258. $('#settingsmenu>input').keyup(function(event){
  4259. if(event.keyCode === 13) {//enter
  4260. SettingsMenu.update();
  4261. }
  4262. });
  4263. $("#updateSettings").click(function () {
  4264. SettingsMenu.update();
  4265. });
  4266. },
  4267. update: function() {
  4268. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  4269. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  4270. if(newDisplayName) {
  4271. var displayName = Settings.setDisplayName(newDisplayName);
  4272. APP.xmpp.addToPresence("displayName", displayName, true);
  4273. }
  4274. var language = $("#languages_selectbox").val();
  4275. APP.translation.setLanguage(language);
  4276. Settings.setLanguage(language);
  4277. APP.xmpp.addToPresence("email", newEmail);
  4278. var email = Settings.setEmail(newEmail);
  4279. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  4280. },
  4281. isVisible: function() {
  4282. return $('#settingsmenu').is(':visible');
  4283. },
  4284. setDisplayName: function(newDisplayName) {
  4285. var displayName = Settings.setDisplayName(newDisplayName);
  4286. $('#setDisplayName').get(0).value = displayName;
  4287. },
  4288. onDisplayNameChange: function(peerJid, newDisplayName) {
  4289. if(peerJid === 'localVideoContainer' ||
  4290. peerJid === APP.xmpp.myJid()) {
  4291. this.setDisplayName(newDisplayName);
  4292. }
  4293. }
  4294. };
  4295. module.exports = SettingsMenu;
  4296. },{"../../../../service/translation/languages":96,"../../avatar/Avatar":13,"../../util/UIUtil":30,"./../../../settings/Settings":38}],24:[function(require,module,exports){
  4297. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4298. var buttonHandlers = {
  4299. "bottom_toolbar_contact_list": function () {
  4300. BottomToolbar.toggleContactList();
  4301. },
  4302. "bottom_toolbar_film_strip": function () {
  4303. BottomToolbar.toggleFilmStrip();
  4304. },
  4305. "bottom_toolbar_chat": function () {
  4306. BottomToolbar.toggleChat();
  4307. }
  4308. };
  4309. var BottomToolbar = (function (my) {
  4310. my.init = function () {
  4311. for(var k in buttonHandlers)
  4312. $("#" + k).click(buttonHandlers[k]);
  4313. };
  4314. my.toggleChat = function() {
  4315. PanelToggler.toggleChat();
  4316. };
  4317. my.toggleContactList = function() {
  4318. PanelToggler.toggleContactList();
  4319. };
  4320. my.toggleFilmStrip = function() {
  4321. var filmstrip = $("#remoteVideos");
  4322. filmstrip.toggleClass("hidden");
  4323. };
  4324. $(document).bind("remotevideo.resized", function (event, width, height) {
  4325. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  4326. $('#bottomToolbar').css({bottom: bottom + 'px'});
  4327. });
  4328. return my;
  4329. }(BottomToolbar || {}));
  4330. module.exports = BottomToolbar;
  4331. },{"../side_pannels/SidePanelToggler":17}],25:[function(require,module,exports){
  4332. /* global APP,$, buttonClick, config, lockRoom,
  4333. setSharedKey, Util */
  4334. var messageHandler = require("../util/MessageHandler");
  4335. var BottomToolbar = require("./BottomToolbar");
  4336. var Prezi = require("../prezi/Prezi");
  4337. var Etherpad = require("../etherpad/Etherpad");
  4338. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4339. var Authentication = require("../authentication/Authentication");
  4340. var UIUtil = require("../util/UIUtil");
  4341. var AuthenticationEvents
  4342. = require("../../../service/authentication/AuthenticationEvents");
  4343. var roomUrl = null;
  4344. var sharedKey = '';
  4345. var UI = null;
  4346. var buttonHandlers =
  4347. {
  4348. "toolbar_button_mute": function () {
  4349. return APP.UI.toggleAudio();
  4350. },
  4351. "toolbar_button_camera": function () {
  4352. return APP.UI.toggleVideo();
  4353. },
  4354. /*"toolbar_button_authentication": function () {
  4355. return Toolbar.authenticateClicked();
  4356. },*/
  4357. "toolbar_button_record": function () {
  4358. return toggleRecording();
  4359. },
  4360. "toolbar_button_security": function () {
  4361. return Toolbar.openLockDialog();
  4362. },
  4363. "toolbar_button_link": function () {
  4364. return Toolbar.openLinkDialog();
  4365. },
  4366. "toolbar_button_chat": function () {
  4367. return BottomToolbar.toggleChat();
  4368. },
  4369. "toolbar_button_prezi": function () {
  4370. return Prezi.openPreziDialog();
  4371. },
  4372. "toolbar_button_etherpad": function () {
  4373. return Etherpad.toggleEtherpad(0);
  4374. },
  4375. "toolbar_button_desktopsharing": function () {
  4376. return APP.desktopsharing.toggleScreenSharing();
  4377. },
  4378. "toolbar_button_fullScreen": function()
  4379. {
  4380. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4381. return Toolbar.toggleFullScreen();
  4382. },
  4383. "toolbar_button_sip": function () {
  4384. return callSipButtonClicked();
  4385. },
  4386. "toolbar_button_settings": function () {
  4387. PanelToggler.toggleSettingsMenu();
  4388. },
  4389. "toolbar_button_hangup": function () {
  4390. return hangup();
  4391. },
  4392. "toolbar_button_login": function () {
  4393. Toolbar.authenticateClicked();
  4394. },
  4395. "toolbar_button_logout": function () {
  4396. // Ask for confirmation
  4397. messageHandler.openTwoButtonDialog(
  4398. "dialog.logoutTitle",
  4399. null,
  4400. "dialog.logoutQuestion",
  4401. null,
  4402. false,
  4403. "dialog.Yes",
  4404. function (evt, yes) {
  4405. if (yes) {
  4406. APP.xmpp.logout(function (url) {
  4407. if (url) {
  4408. window.location.href = url;
  4409. } else {
  4410. hangup();
  4411. }
  4412. });
  4413. }
  4414. });
  4415. }
  4416. };
  4417. function hangup() {
  4418. APP.xmpp.disposeConference();
  4419. if(config.enableWelcomePage)
  4420. {
  4421. setTimeout(function()
  4422. {
  4423. window.localStorage.welcomePageDisabled = false;
  4424. window.location.pathname = "/";
  4425. }, 10000);
  4426. }
  4427. var title = APP.translation.generateTranslatonHTML(
  4428. "dialog.sessTerminated");
  4429. var msg = APP.translation.generateTranslatonHTML(
  4430. "dialog.hungUp");
  4431. var button = APP.translation.generateTranslatonHTML(
  4432. "dialog.joinAgain");
  4433. var buttons = [];
  4434. buttons.push({title: button, value: true});
  4435. UI.messageHandler.openDialog(
  4436. title,
  4437. msg,
  4438. true,
  4439. buttons,
  4440. function(event, value, message, formVals)
  4441. {
  4442. window.location.reload();
  4443. return false;
  4444. }
  4445. );
  4446. }
  4447. /**
  4448. * Starts or stops the recording for the conference.
  4449. */
  4450. function toggleRecording() {
  4451. APP.xmpp.toggleRecording(function (callback) {
  4452. var msg = APP.translation.generateTranslatonHTML(
  4453. "dialog.recordingToken");
  4454. var token = APP.translation.translateString("dialog.token");
  4455. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  4456. '<h2>' + msg + '</h2>' +
  4457. '<input name="recordingToken" type="text" ' +
  4458. ' data-i18n="[placeholder]dialog.token" ' +
  4459. 'placeholder="' + token + '" autofocus>',
  4460. false,
  4461. "dialog.Save",
  4462. function (e, v, m, f) {
  4463. if (v) {
  4464. var token = f.recordingToken;
  4465. if (token) {
  4466. callback(UIUtil.escapeHtml(token));
  4467. }
  4468. }
  4469. },
  4470. null,
  4471. function () { },
  4472. ':input:first'
  4473. );
  4474. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4475. }
  4476. /**
  4477. * Locks / unlocks the room.
  4478. */
  4479. function lockRoom(lock) {
  4480. var currentSharedKey = '';
  4481. if (lock)
  4482. currentSharedKey = sharedKey;
  4483. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4484. // password is required
  4485. if (sharedKey)
  4486. {
  4487. console.log('set room password');
  4488. Toolbar.lockLockButton();
  4489. }
  4490. else
  4491. {
  4492. console.log('removed room password');
  4493. Toolbar.unlockLockButton();
  4494. }
  4495. }, function (err) {
  4496. console.warn('setting password failed', err);
  4497. messageHandler.showError("dialog.lockTitle",
  4498. "dialog.lockMessage");
  4499. Toolbar.setSharedKey('');
  4500. }, function () {
  4501. console.warn('room passwords not supported');
  4502. messageHandler.showError("dialog.warning",
  4503. "dialog.passwordNotSupported");
  4504. Toolbar.setSharedKey('');
  4505. });
  4506. };
  4507. /**
  4508. * Invite participants to conference.
  4509. */
  4510. function inviteParticipants() {
  4511. if (roomUrl === null)
  4512. return;
  4513. var sharedKeyText = "";
  4514. if (sharedKey && sharedKey.length > 0) {
  4515. sharedKeyText =
  4516. APP.translation.translateString("email.sharedKey",
  4517. {sharedKey: sharedKey});
  4518. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  4519. }
  4520. var supportedBrowsers = "Chromium, Google Chrome " +
  4521. APP.translation.translateString("email.and") + " Opera";
  4522. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4523. var subject = APP.translation.translateString("email.subject",
  4524. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  4525. var body = APP.translation.translateString("email.body",
  4526. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  4527. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  4528. body = body.replace(/\n/g, "%0D%0A");
  4529. if (window.localStorage.displayname) {
  4530. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4531. }
  4532. if (interfaceConfig.INVITATION_POWERED_BY) {
  4533. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4534. }
  4535. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4536. }
  4537. function callSipButtonClicked()
  4538. {
  4539. var defaultNumber
  4540. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4541. var sipMsg = APP.translation.generateTranslatonHTML(
  4542. "dialog.sipMsg");
  4543. messageHandler.openTwoButtonDialog(null, null, null,
  4544. '<h2>' + sipMsg + '</h2>' +
  4545. '<input name="sipNumber" type="text"' +
  4546. ' value="' + defaultNumber + '" autofocus>',
  4547. false,
  4548. "dialog.Dial",
  4549. function (e, v, m, f) {
  4550. if (v) {
  4551. var numberInput = f.sipNumber;
  4552. if (numberInput) {
  4553. APP.xmpp.dial(
  4554. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  4555. }
  4556. }
  4557. },
  4558. null, null, ':input:first'
  4559. );
  4560. }
  4561. var Toolbar = (function (my) {
  4562. my.init = function (ui) {
  4563. for(var k in buttonHandlers)
  4564. $("#" + k).click(buttonHandlers[k]);
  4565. UI = ui;
  4566. // Update login info
  4567. APP.xmpp.addListener(
  4568. AuthenticationEvents.IDENTITY_UPDATED,
  4569. function (authenticationEnabled, userIdentity) {
  4570. var loggedIn = false;
  4571. if (userIdentity) {
  4572. loggedIn = true;
  4573. }
  4574. Toolbar.showAuthenticateButton(authenticationEnabled);
  4575. if (authenticationEnabled) {
  4576. Toolbar.setAuthenticatedIdentity(userIdentity);
  4577. Toolbar.showLoginButton(!loggedIn);
  4578. Toolbar.showLogoutButton(loggedIn);
  4579. }
  4580. }
  4581. );
  4582. },
  4583. /**
  4584. * Sets shared key
  4585. * @param sKey the shared key
  4586. */
  4587. my.setSharedKey = function (sKey) {
  4588. sharedKey = sKey;
  4589. };
  4590. my.authenticateClicked = function () {
  4591. Authentication.focusAuthenticationWindow();
  4592. if (!APP.xmpp.isExternalAuthEnabled()) {
  4593. Authentication.xmppAuthenticate();
  4594. return;
  4595. }
  4596. // Get authentication URL
  4597. if (!APP.xmpp.getMUCJoined()) {
  4598. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4599. // If conference has not been started yet - redirect to login page
  4600. window.location.href = url;
  4601. });
  4602. } else {
  4603. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4604. // Otherwise - open popup with authentication URL
  4605. var authenticationWindow = Authentication.createAuthenticationWindow(
  4606. function () {
  4607. // On popup closed - retry room allocation
  4608. APP.xmpp.allocateConferenceFocus(
  4609. APP.UI.getRoomName(),
  4610. function () { console.info("AUTH DONE"); }
  4611. );
  4612. }, url);
  4613. if (!authenticationWindow) {
  4614. messageHandler.openMessageDialog(
  4615. null, "dialog.popupError");
  4616. }
  4617. });
  4618. }
  4619. };
  4620. /**
  4621. * Updates the room invite url.
  4622. */
  4623. my.updateRoomUrl = function (newRoomUrl) {
  4624. roomUrl = newRoomUrl;
  4625. // If the invite dialog has been already opened we update the information.
  4626. var inviteLink = document.getElementById('inviteLinkRef');
  4627. if (inviteLink) {
  4628. inviteLink.value = roomUrl;
  4629. inviteLink.select();
  4630. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  4631. }
  4632. };
  4633. /**
  4634. * Disables and enables some of the buttons.
  4635. */
  4636. my.setupButtonsFromConfig = function () {
  4637. if (config.disablePrezi)
  4638. {
  4639. $("#prezi_button").css({display: "none"});
  4640. }
  4641. };
  4642. /**
  4643. * Opens the lock room dialog.
  4644. */
  4645. my.openLockDialog = function () {
  4646. // Only the focus is able to set a shared key.
  4647. if (!APP.xmpp.isModerator()) {
  4648. if (sharedKey) {
  4649. messageHandler.openMessageDialog(null,
  4650. "dialog.passwordError");
  4651. } else {
  4652. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  4653. }
  4654. } else {
  4655. if (sharedKey) {
  4656. messageHandler.openTwoButtonDialog(null, null,
  4657. "dialog.passwordCheck",
  4658. null,
  4659. false,
  4660. "dialog.Remove",
  4661. function (e, v) {
  4662. if (v) {
  4663. Toolbar.setSharedKey('');
  4664. lockRoom(false);
  4665. }
  4666. });
  4667. } else {
  4668. var msg = APP.translation.generateTranslatonHTML(
  4669. "dialog.passwordMsg");
  4670. var yourPassword = APP.translation.translateString(
  4671. "dialog.yourPassword");
  4672. messageHandler.openTwoButtonDialog(null, null, null,
  4673. '<h2>' + msg + '</h2>' +
  4674. '<input name="lockKey" type="text"' +
  4675. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  4676. 'placeholder="' + yourPassword + '" autofocus>',
  4677. false,
  4678. "dialog.Save",
  4679. function (e, v, m, f) {
  4680. if (v) {
  4681. var lockKey = f.lockKey;
  4682. if (lockKey) {
  4683. Toolbar.setSharedKey(
  4684. UIUtil.escapeHtml(lockKey));
  4685. lockRoom(true);
  4686. }
  4687. }
  4688. },
  4689. null, null, 'input:first'
  4690. );
  4691. }
  4692. }
  4693. };
  4694. /**
  4695. * Opens the invite link dialog.
  4696. */
  4697. my.openLinkDialog = function () {
  4698. var inviteAttreibutes;
  4699. if (roomUrl === null) {
  4700. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  4701. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  4702. } else {
  4703. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  4704. }
  4705. messageHandler.openTwoButtonDialog("dialog.shareLink",
  4706. null, null,
  4707. '<input id="inviteLinkRef" type="text" ' +
  4708. inviteAttreibutes + ' onclick="this.select();" readonly>',
  4709. false,
  4710. "dialog.Invite",
  4711. function (e, v) {
  4712. if (v) {
  4713. if (roomUrl) {
  4714. inviteParticipants();
  4715. }
  4716. }
  4717. },
  4718. function () {
  4719. if (roomUrl) {
  4720. document.getElementById('inviteLinkRef').select();
  4721. } else {
  4722. document.getElementById('jqi_state0_buttonInvite')
  4723. .disabled = true;
  4724. }
  4725. }
  4726. );
  4727. };
  4728. /**
  4729. * Opens the settings dialog.
  4730. * FIXME: not used ?
  4731. */
  4732. my.openSettingsDialog = function () {
  4733. var settings1 = APP.translation.generateTranslatonHTML(
  4734. "dialog.settings1");
  4735. var settings2 = APP.translation.generateTranslatonHTML(
  4736. "dialog.settings2");
  4737. var settings3 = APP.translation.generateTranslatonHTML(
  4738. "dialog.settings3");
  4739. var yourPassword = APP.translation.translateString(
  4740. "dialog.yourPassword");
  4741. messageHandler.openTwoButtonDialog(null,
  4742. '<h2>' + settings1 + '</h2>' +
  4743. '<input type="checkbox" id="initMuted">' +
  4744. settings2 + '<br/>' +
  4745. '<input type="checkbox" id="requireNicknames">' +
  4746. settings3 +
  4747. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  4748. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  4749. null,
  4750. null,
  4751. false,
  4752. "dialog.Save",
  4753. function () {
  4754. document.getElementById('lockKey').focus();
  4755. },
  4756. function (e, v) {
  4757. if (v) {
  4758. if ($('#initMuted').is(":checked")) {
  4759. // it is checked
  4760. }
  4761. if ($('#requireNicknames').is(":checked")) {
  4762. // it is checked
  4763. }
  4764. /*
  4765. var lockKey = document.getElementById('lockKey');
  4766. if (lockKey.value) {
  4767. setSharedKey(lockKey.value);
  4768. lockRoom(true);
  4769. }
  4770. */
  4771. }
  4772. }
  4773. );
  4774. };
  4775. /**
  4776. * Toggles the application in and out of full screen mode
  4777. * (a.k.a. presentation mode in Chrome).
  4778. */
  4779. my.toggleFullScreen = function () {
  4780. var fsElement = document.documentElement;
  4781. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  4782. //Enter Full Screen
  4783. if (fsElement.mozRequestFullScreen) {
  4784. fsElement.mozRequestFullScreen();
  4785. }
  4786. else {
  4787. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  4788. }
  4789. } else {
  4790. //Exit Full Screen
  4791. if (document.mozCancelFullScreen) {
  4792. document.mozCancelFullScreen();
  4793. } else {
  4794. document.webkitCancelFullScreen();
  4795. }
  4796. }
  4797. };
  4798. /**
  4799. * Unlocks the lock button state.
  4800. */
  4801. my.unlockLockButton = function () {
  4802. if ($("#lockIcon").hasClass("icon-security-locked"))
  4803. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4804. };
  4805. /**
  4806. * Updates the lock button state to locked.
  4807. */
  4808. my.lockLockButton = function () {
  4809. if ($("#lockIcon").hasClass("icon-security"))
  4810. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4811. };
  4812. /**
  4813. * Shows or hides authentication button
  4814. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  4815. */
  4816. my.showAuthenticateButton = function (show) {
  4817. if (show) {
  4818. $('#authentication').css({display: "inline"});
  4819. }
  4820. else {
  4821. $('#authentication').css({display: "none"});
  4822. }
  4823. };
  4824. // Shows or hides the 'recording' button.
  4825. my.showRecordingButton = function (show) {
  4826. if (!config.enableRecording) {
  4827. return;
  4828. }
  4829. if (show) {
  4830. $('#recording').css({display: "inline"});
  4831. }
  4832. else {
  4833. $('#recording').css({display: "none"});
  4834. }
  4835. };
  4836. // Sets the state of the recording button
  4837. my.setRecordingButtonState = function (isRecording) {
  4838. if (isRecording) {
  4839. $('#recordButton').removeClass("icon-recEnable");
  4840. $('#recordButton').addClass("icon-recEnable active");
  4841. } else {
  4842. $('#recordButton').removeClass("icon-recEnable active");
  4843. $('#recordButton').addClass("icon-recEnable");
  4844. }
  4845. };
  4846. // Shows or hides SIP calls button
  4847. my.showSipCallButton = function (show) {
  4848. if (APP.xmpp.isSipGatewayEnabled() && show) {
  4849. $('#sipCallButton').css({display: "inline-block"});
  4850. } else {
  4851. $('#sipCallButton').css({display: "none"});
  4852. }
  4853. };
  4854. /**
  4855. * Displays user authenticated identity name(login).
  4856. * @param authIdentity identity name to be displayed.
  4857. */
  4858. my.setAuthenticatedIdentity = function (authIdentity) {
  4859. if (authIdentity) {
  4860. $('#toolbar_auth_identity').css({display: "list-item"});
  4861. $('#toolbar_auth_identity').text(authIdentity);
  4862. } else {
  4863. $('#toolbar_auth_identity').css({display: "none"});
  4864. }
  4865. };
  4866. /**
  4867. * Shows/hides login button.
  4868. * @param show <tt>true</tt> to show
  4869. */
  4870. my.showLoginButton = function (show) {
  4871. if (show) {
  4872. $('#toolbar_button_login').css({display: "list-item"});
  4873. } else {
  4874. $('#toolbar_button_login').css({display: "none"});
  4875. }
  4876. };
  4877. /**
  4878. * Shows/hides logout button.
  4879. * @param show <tt>true</tt> to show
  4880. */
  4881. my.showLogoutButton = function (show) {
  4882. if (show) {
  4883. $('#toolbar_button_logout').css({display: "list-item"});
  4884. } else {
  4885. $('#toolbar_button_logout').css({display: "none"});
  4886. }
  4887. };
  4888. /**
  4889. * Sets the state of the button. The button has blue glow if desktop
  4890. * streaming is active.
  4891. * @param active the state of the desktop streaming.
  4892. */
  4893. my.changeDesktopSharingButtonState = function (active) {
  4894. var button = $("#desktopsharing > a");
  4895. if (active)
  4896. {
  4897. button.addClass("glow");
  4898. }
  4899. else
  4900. {
  4901. button.removeClass("glow");
  4902. }
  4903. };
  4904. return my;
  4905. }(Toolbar || {}));
  4906. module.exports = Toolbar;
  4907. },{"../../../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){
  4908. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  4909. var toolbarTimeoutObject,
  4910. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  4911. function showDesktopSharingButton() {
  4912. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  4913. $('#desktopsharing').css({display: "inline"});
  4914. } else {
  4915. $('#desktopsharing').css({display: "none"});
  4916. }
  4917. }
  4918. /**
  4919. * Hides the toolbar.
  4920. */
  4921. function hideToolbar() {
  4922. var header = $("#header"),
  4923. bottomToolbar = $("#bottomToolbar");
  4924. var isToolbarHover = false;
  4925. header.find('*').each(function () {
  4926. var id = $(this).attr('id');
  4927. if ($("#" + id + ":hover").length > 0) {
  4928. isToolbarHover = true;
  4929. }
  4930. });
  4931. if ($("#bottomToolbar:hover").length > 0) {
  4932. isToolbarHover = true;
  4933. }
  4934. clearTimeout(toolbarTimeoutObject);
  4935. toolbarTimeoutObject = null;
  4936. if (!isToolbarHover) {
  4937. header.hide("slide", { direction: "up", duration: 300});
  4938. $('#subject').animate({top: "-=40"}, 300);
  4939. if ($("#remoteVideos").hasClass("hidden")) {
  4940. bottomToolbar.hide(
  4941. "slide", {direction: "right", duration: 300});
  4942. }
  4943. }
  4944. else {
  4945. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4946. }
  4947. }
  4948. var ToolbarToggler = {
  4949. /**
  4950. * Shows the main toolbar.
  4951. */
  4952. showToolbar: function () {
  4953. var header = $("#header"),
  4954. bottomToolbar = $("#bottomToolbar");
  4955. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  4956. header.show("slide", { direction: "up", duration: 300});
  4957. $('#subject').animate({top: "+=40"}, 300);
  4958. if (!bottomToolbar.is(":visible")) {
  4959. bottomToolbar.show(
  4960. "slide", {direction: "right", duration: 300});
  4961. }
  4962. if (toolbarTimeoutObject) {
  4963. clearTimeout(toolbarTimeoutObject);
  4964. toolbarTimeoutObject = null;
  4965. }
  4966. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4967. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  4968. }
  4969. if (APP.xmpp.isModerator())
  4970. {
  4971. // TODO: Enable settings functionality.
  4972. // Need to uncomment the settings button in index.html.
  4973. // $('#settingsButton').css({visibility:"visible"});
  4974. }
  4975. // Show/hide desktop sharing button
  4976. showDesktopSharingButton();
  4977. },
  4978. /**
  4979. * Docks/undocks the toolbar.
  4980. *
  4981. * @param isDock indicates what operation to perform
  4982. */
  4983. dockToolbar: function (isDock) {
  4984. if (isDock) {
  4985. // First make sure the toolbar is shown.
  4986. if (!$('#header').is(':visible')) {
  4987. this.showToolbar();
  4988. }
  4989. // Then clear the time out, to dock the toolbar.
  4990. if (toolbarTimeoutObject) {
  4991. clearTimeout(toolbarTimeoutObject);
  4992. toolbarTimeoutObject = null;
  4993. }
  4994. }
  4995. else {
  4996. if (!$('#header').is(':visible')) {
  4997. this.showToolbar();
  4998. }
  4999. else {
  5000. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5001. }
  5002. }
  5003. },
  5004. showDesktopSharingButton: showDesktopSharingButton
  5005. };
  5006. module.exports = ToolbarToggler;
  5007. },{}],27:[function(require,module,exports){
  5008. var JitsiPopover = (function () {
  5009. /**
  5010. * Constructs new JitsiPopover and attaches it to the element
  5011. * @param element jquery selector
  5012. * @param options the options for the popover.
  5013. * @constructor
  5014. */
  5015. function JitsiPopover(element, options)
  5016. {
  5017. this.options = {
  5018. skin: "white",
  5019. content: ""
  5020. };
  5021. if(options)
  5022. {
  5023. if(options.skin)
  5024. this.options.skin = options.skin;
  5025. if(options.content)
  5026. this.options.content = options.content;
  5027. }
  5028. this.elementIsHovered = false;
  5029. this.popoverIsHovered = false;
  5030. this.popoverShown = false;
  5031. element.data("jitsi_popover", this);
  5032. this.element = element;
  5033. this.template = ' <div class="jitsipopover ' + this.options.skin +
  5034. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  5035. '<div class="jitsiPopupmenuPadding"></div></div>';
  5036. var self = this;
  5037. this.element.on("mouseenter", function () {
  5038. self.elementIsHovered = true;
  5039. self.show();
  5040. }).on("mouseleave", function () {
  5041. self.elementIsHovered = false;
  5042. setTimeout(function () {
  5043. self.hide();
  5044. }, 10);
  5045. });
  5046. }
  5047. /**
  5048. * Shows the popover
  5049. */
  5050. JitsiPopover.prototype.show = function () {
  5051. this.createPopover();
  5052. this.popoverShown = true;
  5053. };
  5054. /**
  5055. * Hides the popover
  5056. */
  5057. JitsiPopover.prototype.hide = function () {
  5058. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  5059. {
  5060. this.forceHide();
  5061. }
  5062. };
  5063. /**
  5064. * Hides the popover
  5065. */
  5066. JitsiPopover.prototype.forceHide = function () {
  5067. $(".jitsipopover").remove();
  5068. this.popoverShown = false;
  5069. };
  5070. /**
  5071. * Creates the popover html
  5072. */
  5073. JitsiPopover.prototype.createPopover = function () {
  5074. $("body").append(this.template);
  5075. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  5076. var self = this;
  5077. $(".jitsipopover").on("mouseenter", function () {
  5078. self.popoverIsHovered = true;
  5079. }).on("mouseleave", function () {
  5080. self.popoverIsHovered = false;
  5081. self.hide();
  5082. });
  5083. this.refreshPosition();
  5084. };
  5085. /**
  5086. * Refreshes the position of the popover
  5087. */
  5088. JitsiPopover.prototype.refreshPosition = function () {
  5089. $(".jitsipopover").position({
  5090. my: "bottom",
  5091. at: "top",
  5092. collision: "fit",
  5093. of: this.element,
  5094. using: function (position, elements) {
  5095. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  5096. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  5097. $(".jitsipopover > .arrow").css({left: calcLeft});
  5098. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  5099. }
  5100. });
  5101. };
  5102. /**
  5103. * Updates the content of popover.
  5104. * @param content new content
  5105. */
  5106. JitsiPopover.prototype.updateContent = function (content) {
  5107. this.options.content = content;
  5108. if(!this.popoverShown)
  5109. return;
  5110. $(".jitsipopover").remove();
  5111. this.createPopover();
  5112. };
  5113. return JitsiPopover;
  5114. })();
  5115. module.exports = JitsiPopover;
  5116. },{}],28:[function(require,module,exports){
  5117. /* global $, APP, jQuery, toastr */
  5118. var messageHandler = (function(my) {
  5119. /**
  5120. * Shows a message to the user.
  5121. *
  5122. * @param titleString the title of the message
  5123. * @param messageString the text of the message
  5124. */
  5125. my.openMessageDialog = function(titleKey, messageKey) {
  5126. var title = null;
  5127. if(titleKey)
  5128. {
  5129. title = APP.translation.generateTranslatonHTML(titleKey);
  5130. }
  5131. var message = APP.translation.generateTranslatonHTML(messageKey);
  5132. $.prompt(message,
  5133. {
  5134. title: title,
  5135. persistent: false
  5136. }
  5137. );
  5138. };
  5139. /**
  5140. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5141. *
  5142. * @param titleString the title of the message
  5143. * @param msgString the text of the message
  5144. * @param persistent boolean value which determines whether the message is persistent or not
  5145. * @param leftButton the fist button's text
  5146. * @param submitFunction function to be called on submit
  5147. * @param loadedFunction function to be called after the prompt is fully loaded
  5148. * @param closeFunction function to be called after the prompt is closed
  5149. * @param focus optional focus selector or button index to be focused after
  5150. * the dialog is opened
  5151. * @param defaultButton index of default button which will be activated when
  5152. * the user press 'enter'. Indexed from 0.
  5153. */
  5154. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  5155. persistent, leftButtonKey, submitFunction, loadedFunction,
  5156. closeFunction, focus, defaultButton)
  5157. {
  5158. var buttons = [];
  5159. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  5160. buttons.push({ title: leftButton, value: true});
  5161. var cancelButton
  5162. = APP.translation.generateTranslatonHTML("dialog.Cancel");
  5163. buttons.push({title: cancelButton, value: false});
  5164. var message = msgString, title = titleString;
  5165. if (titleKey)
  5166. {
  5167. title = APP.translation.generateTranslatonHTML(titleKey);
  5168. }
  5169. if (msgKey) {
  5170. message = APP.translation.generateTranslatonHTML(msgKey);
  5171. }
  5172. $.prompt(message, {
  5173. title: title,
  5174. persistent: false,
  5175. buttons: buttons,
  5176. defaultButton: defaultButton,
  5177. focus: focus,
  5178. loaded: loadedFunction,
  5179. submit: submitFunction,
  5180. close: closeFunction
  5181. });
  5182. };
  5183. /**
  5184. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5185. *
  5186. * @param titleString the title of the message
  5187. * @param msgString the text of the message
  5188. * @param persistent boolean value which determines whether the message is persistent or not
  5189. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  5190. * that will be passed to submitFunction
  5191. * @param submitFunction function to be called on submit
  5192. * @param loadedFunction function to be called after the prompt is fully loaded
  5193. */
  5194. my.openDialog = function (titleString, msgString, persistent, buttons,
  5195. submitFunction, loadedFunction) {
  5196. var args = {
  5197. title: titleString,
  5198. persistent: persistent,
  5199. buttons: buttons,
  5200. defaultButton: 1,
  5201. loaded: loadedFunction,
  5202. submit: submitFunction
  5203. };
  5204. if (persistent) {
  5205. args.closeText = '';
  5206. }
  5207. return new Impromptu(msgString, args);
  5208. };
  5209. /**
  5210. * Closes currently opened dialog.
  5211. */
  5212. my.closeDialog = function () {
  5213. $.prompt.close();
  5214. };
  5215. /**
  5216. * Shows a dialog with different states to the user.
  5217. *
  5218. * @param statesObject object containing all the states of the dialog
  5219. */
  5220. my.openDialogWithStates = function (statesObject, options) {
  5221. return new Impromptu(statesObject, options);
  5222. };
  5223. /**
  5224. * Opens new popup window for given <tt>url</tt> centered over current
  5225. * window.
  5226. *
  5227. * @param url the URL to be displayed in the popup window
  5228. * @param w the width of the popup window
  5229. * @param h the height of the popup window
  5230. * @param onPopupClosed optional callback function called when popup window
  5231. * has been closed.
  5232. *
  5233. * @returns popup window object if opened successfully or undefined
  5234. * in case we failed to open it(popup blocked)
  5235. */
  5236. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  5237. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  5238. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  5239. var popup = window.open(
  5240. url, '_blank',
  5241. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  5242. if (popup && onPopupClosed) {
  5243. var pollTimer = window.setInterval(function () {
  5244. if (popup.closed !== false) {
  5245. window.clearInterval(pollTimer);
  5246. onPopupClosed();
  5247. }
  5248. }, 200);
  5249. }
  5250. return popup;
  5251. };
  5252. /**
  5253. * Shows a dialog prompting the user to send an error report.
  5254. *
  5255. * @param titleString the title of the message
  5256. * @param msgString the text of the message
  5257. * @param error the error that is being reported
  5258. */
  5259. my.openReportDialog = function(titleKey, msgKey, error) {
  5260. my.openMessageDialog(titleKey, msgKey);
  5261. console.log(error);
  5262. //FIXME send the error to the server
  5263. };
  5264. /**
  5265. * Shows an error dialog to the user.
  5266. * @param title the title of the message
  5267. * @param message the text of the messafe
  5268. */
  5269. my.showError = function(titleKey, msgKey) {
  5270. if(!titleKey) {
  5271. titleKey = "dialog.oops";
  5272. }
  5273. if(!msgKey)
  5274. {
  5275. msgKey = "dialog.defaultError";
  5276. }
  5277. messageHandler.openMessageDialog(titleKey, msgKey);
  5278. };
  5279. my.notify = function(displayName, displayNameKey,
  5280. cls, messageKey, messageArguments) {
  5281. var displayNameSpan = '<span class="nickname" ';
  5282. if(displayName)
  5283. {
  5284. displayNameSpan += ">" + displayName;
  5285. }
  5286. else
  5287. {
  5288. displayNameSpan += "data-i18n='" + displayNameKey +
  5289. "'>" + APP.translation.translateString(displayNameKey);
  5290. }
  5291. displayNameSpan += "</span>";
  5292. toastr.info(
  5293. displayNameSpan + '<br>' +
  5294. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  5295. (messageArguments?
  5296. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  5297. : "") + ">" +
  5298. APP.translation.translateString(messageKey,
  5299. messageArguments) +
  5300. '</span>');
  5301. };
  5302. return my;
  5303. }(messageHandler || {}));
  5304. module.exports = messageHandler;
  5305. },{}],29:[function(require,module,exports){
  5306. var UIEvents = require("../../../service/UI/UIEvents");
  5307. var nickname = null;
  5308. var eventEmitter = null;
  5309. var NickanameHandler = {
  5310. init: function (emitter) {
  5311. eventEmitter = emitter;
  5312. var storedDisplayName = window.localStorage.displayname;
  5313. if (storedDisplayName) {
  5314. nickname = storedDisplayName;
  5315. }
  5316. },
  5317. setNickname: function (newNickname) {
  5318. if (!newNickname || nickname === newNickname)
  5319. return;
  5320. nickname = newNickname;
  5321. window.localStorage.displayname = nickname;
  5322. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  5323. },
  5324. getNickname: function () {
  5325. return nickname;
  5326. },
  5327. addListener: function (type, listener) {
  5328. eventEmitter.on(type, listener);
  5329. }
  5330. };
  5331. module.exports = NickanameHandler;
  5332. },{"../../../service/UI/UIEvents":92}],30:[function(require,module,exports){
  5333. /**
  5334. * Created by hristo on 12/22/14.
  5335. */
  5336. module.exports = {
  5337. /**
  5338. * Returns the available video width.
  5339. */
  5340. getAvailableVideoWidth: function () {
  5341. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5342. var rightPanelWidth
  5343. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5344. return window.innerWidth - rightPanelWidth;
  5345. },
  5346. /**
  5347. * Changes the style class of the element given by id.
  5348. */
  5349. buttonClick: function(id, classname) {
  5350. $(id).toggleClass(classname); // add the class to the clicked element
  5351. },
  5352. /**
  5353. * Returns the text width for the given element.
  5354. *
  5355. * @param el the element
  5356. */
  5357. getTextWidth: function (el) {
  5358. return (el.clientWidth + 1);
  5359. },
  5360. /**
  5361. * Returns the text height for the given element.
  5362. *
  5363. * @param el the element
  5364. */
  5365. getTextHeight: function (el) {
  5366. return (el.clientHeight + 1);
  5367. },
  5368. /**
  5369. * Plays the sound given by id.
  5370. *
  5371. * @param id the identifier of the audio element.
  5372. */
  5373. playSoundNotification: function (id) {
  5374. document.getElementById(id).play();
  5375. },
  5376. /**
  5377. * Escapes the given text.
  5378. */
  5379. escapeHtml: function (unsafeText) {
  5380. return $('<div/>').text(unsafeText).html();
  5381. },
  5382. imageToGrayScale: function (canvas) {
  5383. var context = canvas.getContext('2d');
  5384. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5385. var pixels = imgData.data;
  5386. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5387. var grayscale
  5388. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5389. pixels[i ] = grayscale; // red
  5390. pixels[i+1] = grayscale; // green
  5391. pixels[i+2] = grayscale; // blue
  5392. // pixels[i+3] is alpha
  5393. }
  5394. // redraw the image in black & white
  5395. context.putImageData(imgData, 0, 0);
  5396. },
  5397. setTooltip: function (element, key, position) {
  5398. element.setAttribute("data-i18n", "[data-content]" + key);
  5399. element.setAttribute("data-toggle", "popover");
  5400. element.setAttribute("data-placement", position);
  5401. element.setAttribute("data-html", true);
  5402. element.setAttribute("data-container", "body");
  5403. }
  5404. };
  5405. },{"../side_pannels/SidePanelToggler":17}],31:[function(require,module,exports){
  5406. var JitsiPopover = require("../util/JitsiPopover");
  5407. /**
  5408. * Constructs new connection indicator.
  5409. * @param videoContainer the video container associated with the indicator.
  5410. * @constructor
  5411. */
  5412. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5413. {
  5414. this.videoContainer = videoContainer;
  5415. this.bandwidth = null;
  5416. this.packetLoss = null;
  5417. this.bitrate = null;
  5418. this.showMoreValue = false;
  5419. this.resolution = null;
  5420. this.transport = [];
  5421. this.popover = null;
  5422. this.jid = jid;
  5423. this.create();
  5424. this.videoLayout = VideoLayout;
  5425. }
  5426. /**
  5427. * Values for the connection quality
  5428. * @type {{98: string,
  5429. * 81: string,
  5430. * 64: string,
  5431. * 47: string,
  5432. * 30: string,
  5433. * 0: string}}
  5434. */
  5435. ConnectionIndicator.connectionQualityValues = {
  5436. 98: "18px", //full
  5437. 81: "15px",//4 bars
  5438. 64: "11px",//3 bars
  5439. 47: "7px",//2 bars
  5440. 30: "3px",//1 bar
  5441. 0: "0px"//empty
  5442. };
  5443. ConnectionIndicator.getIP = function(value)
  5444. {
  5445. return value.substring(0, value.lastIndexOf(":"));
  5446. };
  5447. ConnectionIndicator.getPort = function(value)
  5448. {
  5449. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5450. };
  5451. ConnectionIndicator.getStringFromArray = function (array) {
  5452. var res = "";
  5453. for(var i = 0; i < array.length; i++)
  5454. {
  5455. res += (i === 0? "" : ", ") + array[i];
  5456. }
  5457. return res;
  5458. };
  5459. /**
  5460. * Generates the html content.
  5461. * @returns {string} the html content.
  5462. */
  5463. ConnectionIndicator.prototype.generateText = function () {
  5464. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5465. var translate = APP.translation.translateString;
  5466. if(this.bitrate === null)
  5467. {
  5468. downloadBitrate = "N/A";
  5469. uploadBitrate = "N/A";
  5470. }
  5471. else
  5472. {
  5473. downloadBitrate =
  5474. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5475. uploadBitrate =
  5476. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5477. }
  5478. if(this.packetLoss === null)
  5479. {
  5480. packetLoss = "N/A";
  5481. }
  5482. else
  5483. {
  5484. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5485. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5486. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5487. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5488. }
  5489. var resolutionValue = null;
  5490. if(this.resolution && this.jid != null)
  5491. {
  5492. var keys = Object.keys(this.resolution);
  5493. if(keys.length == 1)
  5494. {
  5495. for(var ssrc in this.resolution)
  5496. {
  5497. resolutionValue = this.resolution[ssrc];
  5498. }
  5499. }
  5500. else if(keys.length > 1)
  5501. {
  5502. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  5503. resolutionValue = this.resolution[displayedSsrc];
  5504. }
  5505. }
  5506. if(this.jid === null)
  5507. {
  5508. resolution = "";
  5509. if(this.resolution === null || !Object.keys(this.resolution) ||
  5510. Object.keys(this.resolution).length === 0)
  5511. {
  5512. resolution = "N/A";
  5513. }
  5514. else
  5515. for(i in this.resolution)
  5516. {
  5517. resolutionValue = this.resolution[i];
  5518. if(resolutionValue)
  5519. {
  5520. if(resolutionValue.height &&
  5521. resolutionValue.width)
  5522. {
  5523. resolution += (resolution === ""? "" : ", ") +
  5524. resolutionValue.width + "x" +
  5525. resolutionValue.height;
  5526. }
  5527. }
  5528. }
  5529. }
  5530. else if(!resolutionValue ||
  5531. !resolutionValue.height ||
  5532. !resolutionValue.width)
  5533. {
  5534. resolution = "N/A";
  5535. }
  5536. else
  5537. {
  5538. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5539. }
  5540. var result = "<table style='width:100%'>" +
  5541. "<tr>" +
  5542. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5543. translate("connectionindicator.bitrate") + "</span></td>" +
  5544. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5545. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5546. uploadBitrate + "</td>" +
  5547. "</tr><tr>" +
  5548. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5549. translate("connectionindicator.packetloss") + "</span></td>" +
  5550. "<td>" + packetLoss + "</td>" +
  5551. "</tr><tr>" +
  5552. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5553. translate("connectionindicator.resolution") + "</span></td>" +
  5554. "<td>" + resolution + "</td></tr></table>";
  5555. if(this.videoContainer.id == "localVideoContainer") {
  5556. result += "<div class=\"jitsipopover_showmore\" " +
  5557. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5558. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5559. (this.showMoreValue ? "less" : "more") + "'>" +
  5560. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5561. "</div><br />";
  5562. }
  5563. if(this.showMoreValue)
  5564. {
  5565. var downloadBandwidth, uploadBandwidth, transport;
  5566. if(this.bandwidth === null)
  5567. {
  5568. downloadBandwidth = "N/A";
  5569. uploadBandwidth = "N/A";
  5570. }
  5571. else
  5572. {
  5573. downloadBandwidth = this.bandwidth.download?
  5574. this.bandwidth.download + " Kbps" :
  5575. "N/A";
  5576. uploadBandwidth = this.bandwidth.upload?
  5577. this.bandwidth.upload + " Kbps" :
  5578. "N/A";
  5579. }
  5580. if(!this.transport || this.transport.length === 0)
  5581. {
  5582. transport = "<tr>" +
  5583. "<td><span class='jitsipopover_blue' " +
  5584. "data-i18n='connectionindicator.address'>" +
  5585. translate("connectionindicator.address") + "</span></td>" +
  5586. "<td> N/A</td></tr>";
  5587. }
  5588. else
  5589. {
  5590. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5591. for(i = 0; i < this.transport.length; i++)
  5592. {
  5593. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5594. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5595. var localIP =
  5596. ConnectionIndicator.getIP(this.transport[i].localip);
  5597. var localPort =
  5598. ConnectionIndicator.getPort(this.transport[i].localip);
  5599. if(data.remoteIP.indexOf(ip) == -1)
  5600. {
  5601. data.remoteIP.push(ip);
  5602. }
  5603. if(data.remotePort.indexOf(port) == -1)
  5604. {
  5605. data.remotePort.push(port);
  5606. }
  5607. if(data.localIP.indexOf(localIP) == -1)
  5608. {
  5609. data.localIP.push(localIP);
  5610. }
  5611. if(data.localPort.indexOf(localPort) == -1)
  5612. {
  5613. data.localPort.push(localPort);
  5614. }
  5615. }
  5616. var local_address_key = "connectionindicator.localaddress";
  5617. var remote_address_key = "connectionindicator.remoteaddress";
  5618. var localTransport =
  5619. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5620. local_address_key +"' data-i18n-options='" +
  5621. JSON.stringify({count: data.localIP.length}) + "'>" +
  5622. translate(local_address_key, {count: data.localIP.length}) +
  5623. "</span></td><td> " +
  5624. ConnectionIndicator.getStringFromArray(data.localIP) +
  5625. "</td></tr>";
  5626. transport =
  5627. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5628. remote_address_key + "' data-i18n-options='" +
  5629. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  5630. translate(remote_address_key,
  5631. {count: data.remoteIP.length}) +
  5632. "</span></td><td> " +
  5633. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5634. "</td></tr>";
  5635. var key_remote = "connectionindicator.remoteport",
  5636. key_local = "connectionindicator.localport";
  5637. transport += "<tr>" +
  5638. "<td>" +
  5639. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5640. "' data-i18n-options='" +
  5641. JSON.stringify({count: this.transport.length}) + "'>" +
  5642. translate(key_remote, {count: this.transport.length}) +
  5643. "</span></td><td>";
  5644. localTransport += "<tr>" +
  5645. "<td>" +
  5646. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5647. "' data-i18n-options='" +
  5648. JSON.stringify({count: this.transport.length}) + "'>" +
  5649. translate(key_local, {count: this.transport.length}) +
  5650. "</span></td><td>";
  5651. transport +=
  5652. ConnectionIndicator.getStringFromArray(data.remotePort);
  5653. localTransport +=
  5654. ConnectionIndicator.getStringFromArray(data.localPort);
  5655. transport += "</td></tr>";
  5656. transport += localTransport + "</td></tr>";
  5657. transport +="<tr>" +
  5658. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5659. translate("connectionindicator.transport") + "</span></td>" +
  5660. "<td>" + this.transport[0].type + "</td></tr>";
  5661. }
  5662. result += "<table style='width:100%'>" +
  5663. "<tr>" +
  5664. "<td>" +
  5665. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5666. translate("connectionindicator.bandwidth") + "</span>" +
  5667. "</td><td>" +
  5668. "<span class='jitsipopover_green'>&darr;</span>" +
  5669. downloadBandwidth +
  5670. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5671. uploadBandwidth + "</td></tr>";
  5672. result += transport + "</table>";
  5673. }
  5674. return result;
  5675. };
  5676. /**
  5677. * Shows or hide the additional information.
  5678. */
  5679. ConnectionIndicator.prototype.showMore = function () {
  5680. this.showMoreValue = !this.showMoreValue;
  5681. this.updatePopoverData();
  5682. };
  5683. function createIcon(classes)
  5684. {
  5685. var icon = document.createElement("span");
  5686. for(var i in classes)
  5687. {
  5688. icon.classList.add(classes[i]);
  5689. }
  5690. icon.appendChild(
  5691. document.createElement("i")).classList.add("icon-connection");
  5692. return icon;
  5693. }
  5694. /**
  5695. * Creates the indicator
  5696. */
  5697. ConnectionIndicator.prototype.create = function () {
  5698. this.connectionIndicatorContainer = document.createElement("div");
  5699. this.connectionIndicatorContainer.className = "connectionindicator";
  5700. this.connectionIndicatorContainer.style.display = "none";
  5701. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5702. this.popover = new JitsiPopover(
  5703. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5704. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5705. APP.translation.translateString("connectionindicator.na") + "</div>",
  5706. skin: "black"});
  5707. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5708. createIcon(["connection", "connection_empty"]));
  5709. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5710. createIcon(["connection", "connection_full"]));
  5711. };
  5712. /**
  5713. * Removes the indicator
  5714. */
  5715. ConnectionIndicator.prototype.remove = function()
  5716. {
  5717. this.connectionIndicatorContainer.remove();
  5718. this.popover.forceHide();
  5719. };
  5720. /**
  5721. * Updates the data of the indicator
  5722. * @param percent the percent of connection quality
  5723. * @param object the statistics data.
  5724. */
  5725. ConnectionIndicator.prototype.updateConnectionQuality =
  5726. function (percent, object) {
  5727. if(percent === null)
  5728. {
  5729. this.connectionIndicatorContainer.style.display = "none";
  5730. this.popover.forceHide();
  5731. return;
  5732. }
  5733. else
  5734. {
  5735. if(this.connectionIndicatorContainer.style.display == "none") {
  5736. this.connectionIndicatorContainer.style.display = "block";
  5737. this.videoLayout.updateMutePosition(this.videoContainer.id);
  5738. }
  5739. }
  5740. this.bandwidth = object.bandwidth;
  5741. this.bitrate = object.bitrate;
  5742. this.packetLoss = object.packetLoss;
  5743. this.transport = object.transport;
  5744. if(object.resolution)
  5745. {
  5746. this.resolution = object.resolution;
  5747. }
  5748. for(var quality in ConnectionIndicator.connectionQualityValues)
  5749. {
  5750. if(percent >= quality)
  5751. {
  5752. this.fullIcon.style.width =
  5753. ConnectionIndicator.connectionQualityValues[quality];
  5754. }
  5755. }
  5756. this.updatePopoverData();
  5757. };
  5758. /**
  5759. * Updates the resolution
  5760. * @param resolution the new resolution
  5761. */
  5762. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  5763. this.resolution = resolution;
  5764. this.updatePopoverData();
  5765. };
  5766. /**
  5767. * Updates the content of the popover
  5768. */
  5769. ConnectionIndicator.prototype.updatePopoverData = function () {
  5770. this.popover.updateContent(
  5771. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  5772. APP.translation.translateElement($(".connection_info"));
  5773. };
  5774. /**
  5775. * Hides the popover
  5776. */
  5777. ConnectionIndicator.prototype.hide = function () {
  5778. this.popover.forceHide();
  5779. };
  5780. /**
  5781. * Hides the indicator
  5782. */
  5783. ConnectionIndicator.prototype.hideIndicator = function () {
  5784. this.connectionIndicatorContainer.style.display = "none";
  5785. if(this.popover)
  5786. this.popover.forceHide();
  5787. };
  5788. module.exports = ConnectionIndicator;
  5789. },{"../util/JitsiPopover":27}],32:[function(require,module,exports){
  5790. var AudioLevels = require("../audio_levels/AudioLevels");
  5791. var Avatar = require("../avatar/Avatar");
  5792. var Chat = require("../side_pannels/chat/Chat");
  5793. var ContactList = require("../side_pannels/contactlist/ContactList");
  5794. var UIUtil = require("../util/UIUtil");
  5795. var ConnectionIndicator = require("./ConnectionIndicator");
  5796. var NicknameHandler = require("../util/NicknameHandler");
  5797. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  5798. var UIEvents = require("../../../service/UI/UIEvents");
  5799. var currentDominantSpeaker = null;
  5800. var lastNCount = config.channelLastN;
  5801. var localLastNCount = config.channelLastN;
  5802. var localLastNSet = [];
  5803. var lastNEndpointsCache = [];
  5804. var lastNPickupJid = null;
  5805. var largeVideoState = {
  5806. updateInProgress: false,
  5807. newSrc: ''
  5808. };
  5809. var eventEmitter = null;
  5810. /**
  5811. * Currently focused video "src"(displayed in large video).
  5812. * @type {String}
  5813. */
  5814. var focusedVideoInfo = null;
  5815. /**
  5816. * Indicates if we have muted our audio before the conference has started.
  5817. * @type {boolean}
  5818. */
  5819. var preMuted = false;
  5820. var mutedAudios = {};
  5821. var flipXLocalVideo = true;
  5822. var currentVideoWidth = null;
  5823. var currentVideoHeight = null;
  5824. var localVideoSrc = null;
  5825. function videoactive( videoelem) {
  5826. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  5827. // ignore mixedmslabela0 and v0
  5828. videoelem.show();
  5829. VideoLayout.resizeThumbnails();
  5830. var videoParent = videoelem.parent();
  5831. var parentResourceJid = null;
  5832. if (videoParent)
  5833. parentResourceJid
  5834. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  5835. // Update the large video to the last added video only if there's no
  5836. // current dominant, focused speaker or prezi playing or update it to
  5837. // the current dominant speaker.
  5838. if ((!focusedVideoInfo &&
  5839. !VideoLayout.getDominantSpeakerResourceJid() &&
  5840. !require("../prezi/Prezi").isPresentationVisible()) ||
  5841. (parentResourceJid &&
  5842. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  5843. VideoLayout.updateLargeVideo(
  5844. APP.RTC.getVideoSrc(videoelem[0]),
  5845. 1,
  5846. parentResourceJid);
  5847. }
  5848. VideoLayout.showModeratorIndicator();
  5849. }
  5850. }
  5851. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  5852. // XXX(gp) so, every call to this function is *always* preceded by a call
  5853. // to the RTC.attachMediaStream() function but that call is *not* followed
  5854. // by an update to the videoSrcToSsrc map!
  5855. //
  5856. // The above way of doing things results in video SRCs that don't correspond
  5857. // to any SSRC for a short period of time (to be more precise, for as long
  5858. // the waitForRemoteVideo takes to complete). This causes problems (see
  5859. // bellow).
  5860. //
  5861. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  5862. // a second time in here and only then update the videoSrcToSsrc map? Why
  5863. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  5864. // is called the first time? I actually do that in the lastN changed event
  5865. // handler because the "orphan" video SRC is causing troubles there. The
  5866. // purpose of this method would then be to fire the "videoactive.jingle".
  5867. //
  5868. // Food for though I guess :-)
  5869. if (selector.removed || !selector.parent().is(":visible")) {
  5870. console.warn("Media removed before had started", selector);
  5871. return;
  5872. }
  5873. if (stream.id === 'mixedmslabel') return;
  5874. if (selector[0].currentTime > 0) {
  5875. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  5876. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  5877. videoactive(selector);
  5878. } else {
  5879. setTimeout(function () {
  5880. waitForRemoteVideo(selector, ssrc, stream, jid);
  5881. }, 250);
  5882. }
  5883. }
  5884. /**
  5885. * Returns an array of the video horizontal and vertical indents,
  5886. * so that if fits its parent.
  5887. *
  5888. * @return an array with 2 elements, the horizontal indent and the vertical
  5889. * indent
  5890. */
  5891. function getCameraVideoPosition(videoWidth,
  5892. videoHeight,
  5893. videoSpaceWidth,
  5894. videoSpaceHeight) {
  5895. // Parent height isn't completely calculated when we position the video in
  5896. // full screen mode and this is why we use the screen height in this case.
  5897. // Need to think it further at some point and implement it properly.
  5898. var isFullScreen = document.fullScreen ||
  5899. document.mozFullScreen ||
  5900. document.webkitIsFullScreen;
  5901. if (isFullScreen)
  5902. videoSpaceHeight = window.innerHeight;
  5903. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5904. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  5905. return [horizontalIndent, verticalIndent];
  5906. }
  5907. /**
  5908. * Returns an array of the video horizontal and vertical indents.
  5909. * Centers horizontally and top aligns vertically.
  5910. *
  5911. * @return an array with 2 elements, the horizontal indent and the vertical
  5912. * indent
  5913. */
  5914. function getDesktopVideoPosition(videoWidth,
  5915. videoHeight,
  5916. videoSpaceWidth,
  5917. videoSpaceHeight) {
  5918. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5919. var verticalIndent = 0;// Top aligned
  5920. return [horizontalIndent, verticalIndent];
  5921. }
  5922. /**
  5923. * Returns an array of the video dimensions, so that it covers the screen.
  5924. * It leaves no empty areas, but some parts of the video might not be visible.
  5925. *
  5926. * @return an array with 2 elements, the video width and the video height
  5927. */
  5928. function getCameraVideoSize(videoWidth,
  5929. videoHeight,
  5930. videoSpaceWidth,
  5931. videoSpaceHeight) {
  5932. if (!videoWidth)
  5933. videoWidth = currentVideoWidth;
  5934. if (!videoHeight)
  5935. videoHeight = currentVideoHeight;
  5936. var aspectRatio = videoWidth / videoHeight;
  5937. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5938. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5939. if (availableWidth / aspectRatio < videoSpaceHeight) {
  5940. availableHeight = videoSpaceHeight;
  5941. availableWidth = availableHeight * aspectRatio;
  5942. }
  5943. if (availableHeight * aspectRatio < videoSpaceWidth) {
  5944. availableWidth = videoSpaceWidth;
  5945. availableHeight = availableWidth / aspectRatio;
  5946. }
  5947. return [availableWidth, availableHeight];
  5948. }
  5949. /**
  5950. * Sets the display name for the given video span id.
  5951. */
  5952. function setDisplayName(videoSpanId, displayName, key) {
  5953. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  5954. var defaultLocalDisplayName = APP.translation.generateTranslatonHTML(
  5955. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  5956. // If we already have a display name for this video.
  5957. if (nameSpan.length > 0) {
  5958. var nameSpanElement = nameSpan.get(0);
  5959. if (nameSpanElement.id === 'localDisplayName' &&
  5960. $('#localDisplayName').text() !== displayName) {
  5961. if (displayName && displayName.length > 0)
  5962. {
  5963. var meHTML = APP.translation.generateTranslatonHTML("me");
  5964. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  5965. }
  5966. else
  5967. $('#localDisplayName').html(defaultLocalDisplayName);
  5968. } else {
  5969. if (displayName && displayName.length > 0)
  5970. {
  5971. $('#' + videoSpanId + '_name').html(displayName);
  5972. }
  5973. else if (key && key.length > 0)
  5974. {
  5975. var nameHtml = APP.translation.generateTranslatonHTML(key);
  5976. $('#' + videoSpanId + '_name').html(nameHtml);
  5977. }
  5978. else
  5979. $('#' + videoSpanId + '_name').text(
  5980. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  5981. }
  5982. } else {
  5983. var editButton = null;
  5984. nameSpan = document.createElement('span');
  5985. nameSpan.className = 'displayname';
  5986. $('#' + videoSpanId)[0].appendChild(nameSpan);
  5987. if (videoSpanId === 'localVideoContainer') {
  5988. editButton = createEditDisplayNameButton();
  5989. if (displayName && displayName.length > 0) {
  5990. var meHTML = APP.translation.generateTranslatonHTML("me");
  5991. nameSpan.innerHTML = displayName + meHTML;
  5992. }
  5993. else
  5994. nameSpan.innerHTML = defaultLocalDisplayName;
  5995. }
  5996. else {
  5997. if (displayName && displayName.length > 0) {
  5998. nameSpan.innerText = displayName;
  5999. }
  6000. else
  6001. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  6002. }
  6003. if (!editButton) {
  6004. nameSpan.id = videoSpanId + '_name';
  6005. } else {
  6006. nameSpan.id = 'localDisplayName';
  6007. $('#' + videoSpanId)[0].appendChild(editButton);
  6008. //translates popover of edit button
  6009. APP.translation.translateElement($("a.displayname"));
  6010. var editableText = document.createElement('input');
  6011. editableText.className = 'displayname';
  6012. editableText.type = 'text';
  6013. editableText.id = 'editDisplayName';
  6014. if (displayName && displayName.length) {
  6015. editableText.value
  6016. = displayName;
  6017. }
  6018. var defaultNickname = APP.translation.translateString(
  6019. "defaultNickname", {name: "Jane Pink"});
  6020. editableText.setAttribute('style', 'display:none;');
  6021. editableText.setAttribute('data-18n',
  6022. '[placeholder]defaultNickname');
  6023. editableText.setAttribute("data-i18n-options",
  6024. JSON.stringify({name: "Jane Pink"}));
  6025. editableText.setAttribute("placeholder", defaultNickname);
  6026. $('#' + videoSpanId)[0].appendChild(editableText);
  6027. $('#localVideoContainer .displayname')
  6028. .bind("click", function (e) {
  6029. e.preventDefault();
  6030. e.stopPropagation();
  6031. $('#localDisplayName').hide();
  6032. $('#editDisplayName').show();
  6033. $('#editDisplayName').focus();
  6034. $('#editDisplayName').select();
  6035. $('#editDisplayName').one("focusout", function (e) {
  6036. VideoLayout.inputDisplayNameHandler(this.value);
  6037. });
  6038. $('#editDisplayName').on('keydown', function (e) {
  6039. if (e.keyCode === 13) {
  6040. e.preventDefault();
  6041. VideoLayout.inputDisplayNameHandler(this.value);
  6042. }
  6043. });
  6044. });
  6045. }
  6046. }
  6047. }
  6048. /**
  6049. * Gets the selector of video thumbnail container for the user identified by
  6050. * given <tt>userJid</tt>
  6051. * @param resourceJid user's Jid for whom we want to get the video container.
  6052. */
  6053. function getParticipantContainer(resourceJid)
  6054. {
  6055. if (!resourceJid)
  6056. return null;
  6057. if (resourceJid === APP.xmpp.myResource())
  6058. return $("#localVideoContainer");
  6059. else
  6060. return $("#participant_" + resourceJid);
  6061. }
  6062. /**
  6063. * Sets the size and position of the given video element.
  6064. *
  6065. * @param video the video element to position
  6066. * @param width the desired video width
  6067. * @param height the desired video height
  6068. * @param horizontalIndent the left and right indent
  6069. * @param verticalIndent the top and bottom indent
  6070. */
  6071. function positionVideo(video,
  6072. width,
  6073. height,
  6074. horizontalIndent,
  6075. verticalIndent) {
  6076. video.width(width);
  6077. video.height(height);
  6078. video.css({ top: verticalIndent + 'px',
  6079. bottom: verticalIndent + 'px',
  6080. left: horizontalIndent + 'px',
  6081. right: horizontalIndent + 'px'});
  6082. }
  6083. /**
  6084. * Adds the remote video menu element for the given <tt>jid</tt> in the
  6085. * given <tt>parentElement</tt>.
  6086. *
  6087. * @param jid the jid indicating the video for which we're adding a menu.
  6088. * @param parentElement the parent element where this menu will be added
  6089. */
  6090. function addRemoteVideoMenu(jid, parentElement) {
  6091. var spanElement = document.createElement('span');
  6092. spanElement.className = 'remotevideomenu';
  6093. parentElement.appendChild(spanElement);
  6094. var menuElement = document.createElement('i');
  6095. menuElement.className = 'fa fa-angle-down';
  6096. menuElement.title = 'Remote user controls';
  6097. spanElement.appendChild(menuElement);
  6098. // <ul class="popupmenu">
  6099. // <li><a href="#">Mute</a></li>
  6100. // <li><a href="#">Eject</a></li>
  6101. // </ul>
  6102. var popupmenuElement = document.createElement('ul');
  6103. popupmenuElement.className = 'popupmenu';
  6104. popupmenuElement.id
  6105. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  6106. spanElement.appendChild(popupmenuElement);
  6107. var muteMenuItem = document.createElement('li');
  6108. var muteLinkItem = document.createElement('a');
  6109. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  6110. if (!mutedAudios[jid]) {
  6111. muteLinkItem.innerHTML = mutedIndicator +
  6112. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6113. muteLinkItem.className = 'mutelink';
  6114. }
  6115. else {
  6116. muteLinkItem.innerHTML = mutedIndicator +
  6117. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6118. muteLinkItem.className = 'mutelink disabled';
  6119. }
  6120. muteLinkItem.onclick = function(){
  6121. if ($(this).attr('disabled') != undefined) {
  6122. event.preventDefault();
  6123. }
  6124. var isMute = mutedAudios[jid] == true;
  6125. APP.xmpp.setMute(jid, !isMute);
  6126. popupmenuElement.setAttribute('style', 'display:none;');
  6127. if (isMute) {
  6128. this.innerHTML = mutedIndicator +
  6129. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6130. this.className = 'mutelink disabled';
  6131. }
  6132. else {
  6133. this.innerHTML = mutedIndicator +
  6134. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6135. this.className = 'mutelink';
  6136. }
  6137. };
  6138. muteMenuItem.appendChild(muteLinkItem);
  6139. popupmenuElement.appendChild(muteMenuItem);
  6140. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  6141. var ejectMenuItem = document.createElement('li');
  6142. var ejectLinkItem = document.createElement('a');
  6143. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  6144. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  6145. ejectLinkItem.onclick = function(){
  6146. APP.xmpp.eject(jid);
  6147. popupmenuElement.setAttribute('style', 'display:none;');
  6148. };
  6149. ejectMenuItem.appendChild(ejectLinkItem);
  6150. popupmenuElement.appendChild(ejectMenuItem);
  6151. var paddingSpan = document.createElement('span');
  6152. paddingSpan.className = 'popupmenuPadding';
  6153. popupmenuElement.appendChild(paddingSpan);
  6154. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  6155. }
  6156. /**
  6157. * Removes remote video menu element from video element identified by
  6158. * given <tt>videoElementId</tt>.
  6159. *
  6160. * @param videoElementId the id of local or remote video element.
  6161. */
  6162. function removeRemoteVideoMenu(videoElementId) {
  6163. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  6164. if (menuSpan.length) {
  6165. menuSpan.remove();
  6166. }
  6167. }
  6168. /**
  6169. * Updates the data for the indicator
  6170. * @param id the id of the indicator
  6171. * @param percent the percent for connection quality
  6172. * @param object the data
  6173. */
  6174. function updateStatsIndicator(id, percent, object) {
  6175. if(VideoLayout.connectionIndicators[id])
  6176. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  6177. }
  6178. /**
  6179. * Returns an array of the video dimensions, so that it keeps it's aspect
  6180. * ratio and fits available area with it's larger dimension. This method
  6181. * ensures that whole video will be visible and can leave empty areas.
  6182. *
  6183. * @return an array with 2 elements, the video width and the video height
  6184. */
  6185. function getDesktopVideoSize(videoWidth,
  6186. videoHeight,
  6187. videoSpaceWidth,
  6188. videoSpaceHeight) {
  6189. if (!videoWidth)
  6190. videoWidth = currentVideoWidth;
  6191. if (!videoHeight)
  6192. videoHeight = currentVideoHeight;
  6193. var aspectRatio = videoWidth / videoHeight;
  6194. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6195. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6196. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  6197. if (availableWidth / aspectRatio >= videoSpaceHeight)
  6198. {
  6199. availableHeight = videoSpaceHeight;
  6200. availableWidth = availableHeight * aspectRatio;
  6201. }
  6202. if (availableHeight * aspectRatio >= videoSpaceWidth)
  6203. {
  6204. availableWidth = videoSpaceWidth;
  6205. availableHeight = availableWidth / aspectRatio;
  6206. }
  6207. return [availableWidth, availableHeight];
  6208. }
  6209. /**
  6210. * Creates the edit display name button.
  6211. *
  6212. * @returns the edit button
  6213. */
  6214. function createEditDisplayNameButton() {
  6215. var editButton = document.createElement('a');
  6216. editButton.className = 'displayname';
  6217. UIUtil.setTooltip(editButton,
  6218. "videothumbnail.editnickname",
  6219. "top");
  6220. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  6221. return editButton;
  6222. }
  6223. /**
  6224. * Creates the element indicating the moderator(owner) of the conference.
  6225. *
  6226. * @param parentElement the parent element where the owner indicator will
  6227. * be added
  6228. */
  6229. function createModeratorIndicatorElement(parentElement) {
  6230. var moderatorIndicator = document.createElement('i');
  6231. moderatorIndicator.className = 'fa fa-star';
  6232. parentElement.appendChild(moderatorIndicator);
  6233. UIUtil.setTooltip(parentElement,
  6234. "videothumbnail.moderator",
  6235. "top");
  6236. }
  6237. var VideoLayout = (function (my) {
  6238. my.connectionIndicators = {};
  6239. // By default we use camera
  6240. my.getVideoSize = getCameraVideoSize;
  6241. my.getVideoPosition = getCameraVideoPosition;
  6242. my.init = function (emitter) {
  6243. // Listen for large video size updates
  6244. document.getElementById('largeVideo')
  6245. .addEventListener('loadedmetadata', function (e) {
  6246. currentVideoWidth = this.videoWidth;
  6247. currentVideoHeight = this.videoHeight;
  6248. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6249. });
  6250. eventEmitter = emitter;
  6251. };
  6252. my.isInLastN = function(resource) {
  6253. return lastNCount < 0 // lastN is disabled, return true
  6254. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  6255. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  6256. };
  6257. my.changeLocalStream = function (stream) {
  6258. VideoLayout.changeLocalVideo(stream);
  6259. };
  6260. my.changeLocalAudio = function(stream) {
  6261. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  6262. document.getElementById('localAudio').autoplay = true;
  6263. document.getElementById('localAudio').volume = 0;
  6264. if (preMuted) {
  6265. if(!APP.UI.setAudioMuted(true))
  6266. {
  6267. preMuted = mute;
  6268. }
  6269. preMuted = false;
  6270. }
  6271. };
  6272. my.changeLocalVideo = function(stream) {
  6273. var flipX = true;
  6274. if(stream.videoType == "screen")
  6275. flipX = false;
  6276. var localVideo = document.createElement('video');
  6277. localVideo.id = 'localVideo_' +
  6278. APP.RTC.getStreamID(stream.getOriginalStream());
  6279. localVideo.autoplay = true;
  6280. localVideo.volume = 0; // is it required if audio is separated ?
  6281. localVideo.oncontextmenu = function () { return false; };
  6282. var localVideoContainer = document.getElementById('localVideoWrapper');
  6283. localVideoContainer.appendChild(localVideo);
  6284. // Set default display name.
  6285. setDisplayName('localVideoContainer');
  6286. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  6287. VideoLayout.connectionIndicators["localVideoContainer"]
  6288. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  6289. }
  6290. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  6291. var localVideoSelector = $('#' + localVideo.id);
  6292. function localVideoClick(event) {
  6293. event.stopPropagation();
  6294. VideoLayout.handleVideoThumbClicked(
  6295. APP.RTC.getVideoSrc(localVideo),
  6296. false,
  6297. APP.xmpp.myResource());
  6298. }
  6299. // Add click handler to both video and video wrapper elements in case
  6300. // there's no video.
  6301. localVideoSelector.click(localVideoClick);
  6302. $('#localVideoContainer').click(localVideoClick);
  6303. // Add hover handler
  6304. $('#localVideoContainer').hover(
  6305. function() {
  6306. VideoLayout.showDisplayName('localVideoContainer', true);
  6307. },
  6308. function() {
  6309. if (!VideoLayout.isLargeVideoVisible()
  6310. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6311. VideoLayout.showDisplayName('localVideoContainer', false);
  6312. }
  6313. );
  6314. // Add stream ended handler
  6315. stream.getOriginalStream().onended = function () {
  6316. localVideoContainer.removeChild(localVideo);
  6317. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  6318. };
  6319. // Flip video x axis if needed
  6320. flipXLocalVideo = flipX;
  6321. if (flipX) {
  6322. localVideoSelector.addClass("flipVideoX");
  6323. }
  6324. // Attach WebRTC stream
  6325. var videoStream = APP.simulcast.getLocalVideoStream();
  6326. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  6327. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  6328. var myResourceJid = APP.xmpp.myResource();
  6329. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  6330. myResourceJid);
  6331. };
  6332. /**
  6333. * Adds or removes icons for not available camera and microphone.
  6334. * @param resourceJid the jid of user
  6335. * @param devices available devices
  6336. */
  6337. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  6338. if(!devices)
  6339. return;
  6340. var container = null
  6341. if(!resourceJid)
  6342. {
  6343. container = $("#localVideoContainer")[0];
  6344. }
  6345. else
  6346. {
  6347. container = $("#participant_" + resourceJid)[0];
  6348. }
  6349. if(!container)
  6350. return;
  6351. $("#" + container.id + " > .noMic").remove();
  6352. $("#" + container.id + " > .noVideo").remove();
  6353. if(!devices.audio)
  6354. {
  6355. container.appendChild(document.createElement("div")).setAttribute("class","noMic");
  6356. }
  6357. if(!devices.video)
  6358. {
  6359. container.appendChild(document.createElement("div")).setAttribute("class","noVideo");
  6360. }
  6361. if(!devices.audio && !devices.video)
  6362. {
  6363. $("#" + container.id + " > .noMic").css("background-position", "75%");
  6364. $("#" + container.id + " > .noVideo").css("background-position", "25%");
  6365. $("#" + container.id + " > .noVideo").css("background-color", "transparent");
  6366. }
  6367. }
  6368. /**
  6369. * Checks if removed video is currently displayed and tries to display
  6370. * another one instead.
  6371. * @param removedVideoSrc src stream identifier of the video.
  6372. */
  6373. my.updateRemovedVideo = function(removedVideoSrc) {
  6374. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  6375. // this is currently displayed as large
  6376. // pick the last visible video in the row
  6377. // if nobody else is left, this picks the local video
  6378. var pick
  6379. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  6380. .get(0);
  6381. if (!pick) {
  6382. console.info("Last visible video no longer exists");
  6383. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  6384. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  6385. // Try local video
  6386. console.info("Fallback to local video...");
  6387. pick = $('#remoteVideos>span>span>video').get(0);
  6388. }
  6389. }
  6390. // mute if localvideo
  6391. if (pick) {
  6392. var container = pick.parentNode;
  6393. var jid = null;
  6394. if(container)
  6395. {
  6396. if(container.id == "localVideoWrapper")
  6397. {
  6398. jid = APP.xmpp.myResource();
  6399. }
  6400. else
  6401. {
  6402. jid = VideoLayout.getPeerContainerResourceJid(container);
  6403. }
  6404. }
  6405. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(pick), pick.volume, jid);
  6406. } else {
  6407. console.warn("Failed to elect large video");
  6408. }
  6409. }
  6410. };
  6411. my.onRemoteStreamAdded = function (stream) {
  6412. var container;
  6413. var remotes = document.getElementById('remoteVideos');
  6414. if (stream.peerjid) {
  6415. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6416. container = document.getElementById(
  6417. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6418. } else {
  6419. var id = stream.getOriginalStream().id;
  6420. if (id !== 'mixedmslabel'
  6421. // FIXME: default stream is added always with new focus
  6422. // (to be investigated)
  6423. && id !== 'default') {
  6424. console.error('can not associate stream',
  6425. id,
  6426. 'with a participant');
  6427. // We don't want to add it here since it will cause troubles
  6428. return;
  6429. }
  6430. // FIXME: for the mixed ms we dont need a video -- currently
  6431. container = document.createElement('span');
  6432. container.id = 'mixedstream';
  6433. container.className = 'videocontainer';
  6434. remotes.appendChild(container);
  6435. UIUtil.playSoundNotification('userJoined');
  6436. }
  6437. if (container) {
  6438. VideoLayout.addRemoteStreamElement( container,
  6439. stream.sid,
  6440. stream.getOriginalStream(),
  6441. stream.peerjid,
  6442. stream.ssrc);
  6443. }
  6444. }
  6445. my.getLargeVideoState = function () {
  6446. return largeVideoState;
  6447. };
  6448. /**
  6449. * Updates the large video with the given new video source.
  6450. */
  6451. my.updateLargeVideo = function(newSrc, vol, resourceJid) {
  6452. console.log('hover in', newSrc);
  6453. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc) {
  6454. $('#activeSpeaker').css('visibility', 'hidden');
  6455. // Due to the simulcast the localVideoSrc may have changed when the
  6456. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6457. // isVideoSrcDesktop methods will not function correctly.
  6458. //
  6459. // Also, again due to the simulcast, the updateLargeVideo method can
  6460. // be called multiple times almost simultaneously. Therefore, we
  6461. // store the state here and update only once.
  6462. largeVideoState.newSrc = newSrc;
  6463. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6464. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(
  6465. APP.xmpp.findJidFromResource(resourceJid));
  6466. if(largeVideoState.userResourceJid) {
  6467. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6468. } else {
  6469. largeVideoState.oldResourceJid = null;
  6470. }
  6471. largeVideoState.userResourceJid = resourceJid;
  6472. // Screen stream is already rotated
  6473. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6474. var userChanged = false;
  6475. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6476. userChanged = true;
  6477. // we want the notification to trigger even if userJid is undefined,
  6478. // or null.
  6479. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6480. largeVideoState.userResourceJid);
  6481. }
  6482. if (!largeVideoState.updateInProgress) {
  6483. largeVideoState.updateInProgress = true;
  6484. var doUpdate = function () {
  6485. Avatar.updateActiveSpeakerAvatarSrc(
  6486. APP.xmpp.findJidFromResource(
  6487. largeVideoState.userResourceJid));
  6488. if (!userChanged && largeVideoState.preload &&
  6489. largeVideoState.preload !== null &&
  6490. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  6491. {
  6492. console.info('Switching to preloaded video');
  6493. var attributes = $('#largeVideo').prop("attributes");
  6494. // loop through largeVideo attributes and apply them on
  6495. // preload.
  6496. $.each(attributes, function () {
  6497. if (this.name !== 'id' && this.name !== 'src') {
  6498. largeVideoState.preload.attr(this.name, this.value);
  6499. }
  6500. });
  6501. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  6502. $('#largeVideo').attr('id', 'previousLargeVideo');
  6503. largeVideoState.preload.attr('id', 'largeVideo');
  6504. $('#previousLargeVideo').remove();
  6505. largeVideoState.preload.on('loadedmetadata', function (e) {
  6506. currentVideoWidth = this.videoWidth;
  6507. currentVideoHeight = this.videoHeight;
  6508. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6509. });
  6510. largeVideoState.preload = null;
  6511. largeVideoState.preload_ssrc = 0;
  6512. } else {
  6513. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6514. }
  6515. var videoTransform = document.getElementById('largeVideo')
  6516. .style.webkitTransform;
  6517. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6518. document.getElementById('largeVideo').style.webkitTransform
  6519. = "scaleX(-1)";
  6520. }
  6521. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6522. document.getElementById('largeVideo').style.webkitTransform
  6523. = "none";
  6524. }
  6525. // Change the way we'll be measuring and positioning large video
  6526. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6527. ? getDesktopVideoSize
  6528. : getCameraVideoSize;
  6529. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6530. ? getDesktopVideoPosition
  6531. : getCameraVideoPosition;
  6532. // Only if the large video is currently visible.
  6533. // Disable previous dominant speaker video.
  6534. if (largeVideoState.oldResourceJid) {
  6535. VideoLayout.enableDominantSpeaker(
  6536. largeVideoState.oldResourceJid,
  6537. false);
  6538. }
  6539. // Enable new dominant speaker in the remote videos section.
  6540. if (largeVideoState.userResourceJid) {
  6541. VideoLayout.enableDominantSpeaker(
  6542. largeVideoState.userResourceJid,
  6543. true);
  6544. }
  6545. if (userChanged && largeVideoState.isVisible) {
  6546. // using "this" should be ok because we're called
  6547. // from within the fadeOut event.
  6548. $(this).fadeIn(300);
  6549. }
  6550. if(userChanged) {
  6551. Avatar.showUserAvatar(
  6552. APP.xmpp.findJidFromResource(
  6553. largeVideoState.oldResourceJid));
  6554. }
  6555. largeVideoState.updateInProgress = false;
  6556. };
  6557. if (userChanged) {
  6558. $('#largeVideo').fadeOut(300, doUpdate);
  6559. } else {
  6560. doUpdate();
  6561. }
  6562. }
  6563. } else {
  6564. Avatar.showUserAvatar(
  6565. APP.xmpp.findJidFromResource(
  6566. largeVideoState.userResourceJid));
  6567. }
  6568. };
  6569. my.handleVideoThumbClicked = function(videoSrc,
  6570. noPinnedEndpointChangedEvent,
  6571. resourceJid) {
  6572. // Restore style for previously focused video
  6573. var oldContainer = null;
  6574. if(focusedVideoInfo) {
  6575. var focusResourceJid = focusedVideoInfo.resourceJid;
  6576. oldContainer = getParticipantContainer(focusResourceJid);
  6577. }
  6578. if (oldContainer) {
  6579. oldContainer.removeClass("videoContainerFocused");
  6580. }
  6581. // Unlock current focused.
  6582. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6583. {
  6584. focusedVideoInfo = null;
  6585. var dominantSpeakerVideo = null;
  6586. // Enable the currently set dominant speaker.
  6587. if (currentDominantSpeaker) {
  6588. dominantSpeakerVideo
  6589. = $('#participant_' + currentDominantSpeaker + '>video')
  6590. .get(0);
  6591. if (dominantSpeakerVideo) {
  6592. VideoLayout.updateLargeVideo(
  6593. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6594. 1,
  6595. currentDominantSpeaker);
  6596. }
  6597. }
  6598. if (!noPinnedEndpointChangedEvent) {
  6599. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6600. }
  6601. return;
  6602. }
  6603. // Lock new video
  6604. focusedVideoInfo = {
  6605. src: videoSrc,
  6606. resourceJid: resourceJid
  6607. };
  6608. // Update focused/pinned interface.
  6609. if (resourceJid)
  6610. {
  6611. var container = getParticipantContainer(resourceJid);
  6612. container.addClass("videoContainerFocused");
  6613. if (!noPinnedEndpointChangedEvent) {
  6614. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6615. }
  6616. }
  6617. if ($('#largeVideo').attr('src') === videoSrc &&
  6618. VideoLayout.isLargeVideoOnTop()) {
  6619. return;
  6620. }
  6621. // Triggers a "video.selected" event. The "false" parameter indicates
  6622. // this isn't a prezi.
  6623. $(document).trigger("video.selected", [false]);
  6624. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6625. $('audio').each(function (idx, el) {
  6626. if (el.id.indexOf('mixedmslabel') !== -1) {
  6627. el.volume = 0;
  6628. el.volume = 1;
  6629. }
  6630. });
  6631. };
  6632. /**
  6633. * Positions the large video.
  6634. *
  6635. * @param videoWidth the stream video width
  6636. * @param videoHeight the stream video height
  6637. */
  6638. my.positionLarge = function (videoWidth, videoHeight) {
  6639. var videoSpaceWidth = $('#videospace').width();
  6640. var videoSpaceHeight = window.innerHeight;
  6641. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6642. videoHeight,
  6643. videoSpaceWidth,
  6644. videoSpaceHeight);
  6645. var largeVideoWidth = videoSize[0];
  6646. var largeVideoHeight = videoSize[1];
  6647. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6648. largeVideoHeight,
  6649. videoSpaceWidth,
  6650. videoSpaceHeight);
  6651. var horizontalIndent = videoPosition[0];
  6652. var verticalIndent = videoPosition[1];
  6653. positionVideo($('#largeVideo'),
  6654. largeVideoWidth,
  6655. largeVideoHeight,
  6656. horizontalIndent, verticalIndent);
  6657. };
  6658. /**
  6659. * Shows/hides the large video.
  6660. */
  6661. my.setLargeVideoVisible = function(isVisible) {
  6662. var resourceJid = largeVideoState.userResourceJid;
  6663. if (isVisible) {
  6664. $('#largeVideo').css({visibility: 'visible'});
  6665. $('.watermark').css({visibility: 'visible'});
  6666. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6667. }
  6668. else {
  6669. $('#largeVideo').css({visibility: 'hidden'});
  6670. $('#activeSpeaker').css('visibility', 'hidden');
  6671. $('.watermark').css({visibility: 'hidden'});
  6672. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6673. if(focusedVideoInfo) {
  6674. var focusResourceJid = focusedVideoInfo.resourceJid;
  6675. var oldContainer = getParticipantContainer(focusResourceJid);
  6676. if (oldContainer && oldContainer.length > 0) {
  6677. oldContainer.removeClass("videoContainerFocused");
  6678. }
  6679. focusedVideoInfo = null;
  6680. if(focusResourceJid) {
  6681. Avatar.showUserAvatar(
  6682. APP.xmpp.findJidFromResource(focusResourceJid));
  6683. }
  6684. }
  6685. }
  6686. };
  6687. /**
  6688. * Indicates if the large video is currently visible.
  6689. *
  6690. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6691. */
  6692. my.isLargeVideoVisible = function() {
  6693. return $('#largeVideo').is(':visible');
  6694. };
  6695. my.isLargeVideoOnTop = function () {
  6696. var Etherpad = require("../etherpad/Etherpad");
  6697. var Prezi = require("../prezi/Prezi");
  6698. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6699. };
  6700. /**
  6701. * Checks if container for participant identified by given peerJid exists
  6702. * in the document and creates it eventually.
  6703. *
  6704. * @param peerJid peer Jid to check.
  6705. * @param userId user email or id for setting the avatar
  6706. *
  6707. * @return Returns <tt>true</tt> if the peer container exists,
  6708. * <tt>false</tt> - otherwise
  6709. */
  6710. my.ensurePeerContainerExists = function(peerJid, userId) {
  6711. ContactList.ensureAddContact(peerJid, userId);
  6712. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6713. var videoSpanId = 'participant_' + resourceJid;
  6714. if (!$('#' + videoSpanId).length) {
  6715. var container =
  6716. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6717. Avatar.setUserAvatar(peerJid, userId);
  6718. // Set default display name.
  6719. setDisplayName(videoSpanId);
  6720. VideoLayout.connectionIndicators[videoSpanId] =
  6721. new ConnectionIndicator(container, peerJid, VideoLayout);
  6722. var nickfield = document.createElement('span');
  6723. nickfield.className = "nick";
  6724. nickfield.appendChild(document.createTextNode(resourceJid));
  6725. container.appendChild(nickfield);
  6726. // In case this is not currently in the last n we don't show it.
  6727. if (localLastNCount
  6728. && localLastNCount > 0
  6729. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  6730. showPeerContainer(resourceJid, 'hide');
  6731. }
  6732. else
  6733. VideoLayout.resizeThumbnails();
  6734. }
  6735. };
  6736. my.addRemoteVideoContainer = function(peerJid, spanId) {
  6737. var container = document.createElement('span');
  6738. container.id = spanId;
  6739. container.className = 'videocontainer';
  6740. var remotes = document.getElementById('remoteVideos');
  6741. remotes.appendChild(container);
  6742. // If the peerJid is null then this video span couldn't be directly
  6743. // associated with a participant (this could happen in the case of prezi).
  6744. if (APP.xmpp.isModerator() && peerJid !== null)
  6745. addRemoteVideoMenu(peerJid, container);
  6746. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  6747. return container;
  6748. };
  6749. /**
  6750. * Creates an audio or video stream element.
  6751. */
  6752. my.createStreamElement = function (sid, stream) {
  6753. var isVideo = stream.getVideoTracks().length > 0;
  6754. var element = isVideo
  6755. ? document.createElement('video')
  6756. : document.createElement('audio');
  6757. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  6758. + sid + '_' + APP.RTC.getStreamID(stream);
  6759. element.id = id;
  6760. element.autoplay = true;
  6761. element.oncontextmenu = function () { return false; };
  6762. return element;
  6763. };
  6764. my.addRemoteStreamElement
  6765. = function (container, sid, stream, peerJid, thessrc) {
  6766. var newElementId = null;
  6767. var isVideo = stream.getVideoTracks().length > 0;
  6768. if (container) {
  6769. var streamElement = VideoLayout.createStreamElement(sid, stream);
  6770. newElementId = streamElement.id;
  6771. container.appendChild(streamElement);
  6772. var sel = $('#' + newElementId);
  6773. sel.hide();
  6774. // If the container is currently visible we attach the stream.
  6775. if (!isVideo
  6776. || (container.offsetParent !== null && isVideo)) {
  6777. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6778. APP.RTC.attachMediaStream(sel, videoStream);
  6779. if (isVideo)
  6780. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  6781. }
  6782. stream.onended = function () {
  6783. console.log('stream ended', this);
  6784. VideoLayout.removeRemoteStreamElement(
  6785. stream, isVideo, container);
  6786. // NOTE(gp) it seems that under certain circumstances, the
  6787. // onended event is not fired and thus the contact list is not
  6788. // updated.
  6789. //
  6790. // The onended event of a stream should be fired when the SSRCs
  6791. // corresponding to that stream are removed from the SDP; but
  6792. // this doesn't seem to always be the case, resulting in ghost
  6793. // contacts.
  6794. //
  6795. // In an attempt to fix the ghost contacts problem, I'm moving
  6796. // the removeContact() method call in app.js, inside the
  6797. // 'muc.left' event handler.
  6798. //if (peerJid)
  6799. // ContactList.removeContact(peerJid);
  6800. };
  6801. // Add click handler.
  6802. container.onclick = function (event) {
  6803. /*
  6804. * FIXME It turns out that videoThumb may not exist (if there is
  6805. * no actual video).
  6806. */
  6807. var videoThumb = $('#' + container.id + '>video').get(0);
  6808. if (videoThumb) {
  6809. VideoLayout.handleVideoThumbClicked(
  6810. APP.RTC.getVideoSrc(videoThumb),
  6811. false,
  6812. Strophe.getResourceFromJid(peerJid));
  6813. }
  6814. event.stopPropagation();
  6815. event.preventDefault();
  6816. return false;
  6817. };
  6818. // Add hover handler
  6819. $(container).hover(
  6820. function() {
  6821. VideoLayout.showDisplayName(container.id, true);
  6822. },
  6823. function() {
  6824. var videoSrc = null;
  6825. if ($('#' + container.id + '>video')
  6826. && $('#' + container.id + '>video').length > 0) {
  6827. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  6828. }
  6829. // If the video has been "pinned" by the user we want to
  6830. // keep the display name on place.
  6831. if (!VideoLayout.isLargeVideoVisible()
  6832. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6833. VideoLayout.showDisplayName(container.id, false);
  6834. }
  6835. );
  6836. }
  6837. return newElementId;
  6838. };
  6839. /**
  6840. * Removes the remote stream element corresponding to the given stream and
  6841. * parent container.
  6842. *
  6843. * @param stream the stream
  6844. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  6845. * @param container
  6846. */
  6847. my.removeRemoteStreamElement = function (stream, isVideo, container) {
  6848. if (!container)
  6849. return;
  6850. var select = null;
  6851. var removedVideoSrc = null;
  6852. if (isVideo) {
  6853. select = $('#' + container.id + '>video');
  6854. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  6855. }
  6856. else
  6857. select = $('#' + container.id + '>audio');
  6858. // Mark video as removed to cancel waiting loop(if video is removed
  6859. // before has started)
  6860. select.removed = true;
  6861. select.remove();
  6862. var audioCount = $('#' + container.id + '>audio').length;
  6863. var videoCount = $('#' + container.id + '>video').length;
  6864. if (!audioCount && !videoCount) {
  6865. console.log("Remove whole user", container.id);
  6866. if(VideoLayout.connectionIndicators[container.id])
  6867. VideoLayout.connectionIndicators[container.id].remove();
  6868. // Remove whole container
  6869. container.remove();
  6870. UIUtil.playSoundNotification('userLeft');
  6871. VideoLayout.resizeThumbnails();
  6872. }
  6873. if (removedVideoSrc)
  6874. VideoLayout.updateRemovedVideo(removedVideoSrc);
  6875. };
  6876. /**
  6877. * Show/hide peer container for the given resourceJid.
  6878. */
  6879. function showPeerContainer(resourceJid, state) {
  6880. var peerContainer = $('#participant_' + resourceJid);
  6881. if (!peerContainer)
  6882. return;
  6883. var isHide = state === 'hide';
  6884. var resizeThumbnails = false;
  6885. if (!isHide) {
  6886. if (!peerContainer.is(':visible')) {
  6887. resizeThumbnails = true;
  6888. peerContainer.show();
  6889. }
  6890. var jid = APP.xmpp.findJidFromResource(resourceJid);
  6891. if (state == 'show')
  6892. {
  6893. // peerContainer.css('-webkit-filter', '');
  6894. Avatar.showUserAvatar(jid, false);
  6895. }
  6896. else // if (state == 'avatar')
  6897. {
  6898. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  6899. Avatar.showUserAvatar(jid, true);
  6900. }
  6901. }
  6902. else if (peerContainer.is(':visible') && isHide)
  6903. {
  6904. resizeThumbnails = true;
  6905. peerContainer.hide();
  6906. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  6907. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  6908. }
  6909. if (resizeThumbnails) {
  6910. VideoLayout.resizeThumbnails();
  6911. }
  6912. // We want to be able to pin a participant from the contact list, even
  6913. // if he's not in the lastN set!
  6914. // ContactList.setClickable(resourceJid, !isHide);
  6915. };
  6916. my.inputDisplayNameHandler = function (name) {
  6917. NicknameHandler.setNickname(name);
  6918. if (!$('#localDisplayName').is(":visible")) {
  6919. if (NicknameHandler.getNickname())
  6920. {
  6921. var meHTML = APP.translation.generateTranslatonHTML("me");
  6922. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  6923. }
  6924. else
  6925. {
  6926. var defaultHTML = APP.translation.generateTranslatonHTML(
  6927. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6928. $('#localDisplayName')
  6929. .html(defaultHTML);
  6930. }
  6931. $('#localDisplayName').show();
  6932. }
  6933. $('#editDisplayName').hide();
  6934. };
  6935. /**
  6936. * Shows/hides the display name on the remote video.
  6937. * @param videoSpanId the identifier of the video span element
  6938. * @param isShow indicates if the display name should be shown or hidden
  6939. */
  6940. my.showDisplayName = function(videoSpanId, isShow) {
  6941. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  6942. if (isShow) {
  6943. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  6944. nameSpan.setAttribute("style", "display:inline-block;");
  6945. }
  6946. else {
  6947. if (nameSpan)
  6948. nameSpan.setAttribute("style", "display:none;");
  6949. }
  6950. };
  6951. /**
  6952. * Shows the presence status message for the given video.
  6953. */
  6954. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  6955. if (!$('#' + videoSpanId).length) {
  6956. // No container
  6957. return;
  6958. }
  6959. var statusSpan = $('#' + videoSpanId + '>span.status');
  6960. if (!statusSpan.length) {
  6961. //Add status span
  6962. statusSpan = document.createElement('span');
  6963. statusSpan.className = 'status';
  6964. statusSpan.id = videoSpanId + '_status';
  6965. $('#' + videoSpanId)[0].appendChild(statusSpan);
  6966. statusSpan = $('#' + videoSpanId + '>span.status');
  6967. }
  6968. // Display status
  6969. if (statusMsg && statusMsg.length) {
  6970. $('#' + videoSpanId + '_status').text(statusMsg);
  6971. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  6972. }
  6973. else {
  6974. // Hide
  6975. statusSpan.get(0).setAttribute("style", "display:none;");
  6976. }
  6977. };
  6978. /**
  6979. * Shows a visual indicator for the moderator of the conference.
  6980. */
  6981. my.showModeratorIndicator = function () {
  6982. var isModerator = APP.xmpp.isModerator();
  6983. if (isModerator) {
  6984. var indicatorSpan = $('#localVideoContainer .focusindicator');
  6985. if (indicatorSpan.children().length === 0)
  6986. {
  6987. createModeratorIndicatorElement(indicatorSpan[0]);
  6988. //translates text in focus indicator
  6989. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  6990. }
  6991. }
  6992. var members = APP.xmpp.getMembers();
  6993. Object.keys(members).forEach(function (jid) {
  6994. if (Strophe.getResourceFromJid(jid) === 'focus') {
  6995. // Skip server side focus
  6996. return;
  6997. }
  6998. var resourceJid = Strophe.getResourceFromJid(jid);
  6999. var videoSpanId = 'participant_' + resourceJid;
  7000. var videoContainer = document.getElementById(videoSpanId);
  7001. if (!videoContainer) {
  7002. console.error("No video container for " + jid);
  7003. return;
  7004. }
  7005. var member = members[jid];
  7006. if (member.role === 'moderator') {
  7007. // Remove menu if peer is moderator
  7008. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  7009. if (menuSpan.length) {
  7010. removeRemoteVideoMenu(videoSpanId);
  7011. }
  7012. // Show moderator indicator
  7013. var indicatorSpan
  7014. = $('#' + videoSpanId + ' .focusindicator');
  7015. if (!indicatorSpan || indicatorSpan.length === 0) {
  7016. indicatorSpan = document.createElement('span');
  7017. indicatorSpan.className = 'focusindicator';
  7018. videoContainer.appendChild(indicatorSpan);
  7019. createModeratorIndicatorElement(indicatorSpan);
  7020. //translates text in focus indicators
  7021. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  7022. }
  7023. } else if (isModerator) {
  7024. // We are moderator, but user is not - add menu
  7025. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  7026. addRemoteVideoMenu(
  7027. jid,
  7028. document.getElementById('participant_' + resourceJid));
  7029. }
  7030. }
  7031. });
  7032. };
  7033. /**
  7034. * Shows video muted indicator over small videos.
  7035. */
  7036. my.showVideoIndicator = function(videoSpanId, isMuted) {
  7037. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  7038. if (isMuted === 'false') {
  7039. if (videoMutedSpan.length > 0) {
  7040. videoMutedSpan.remove();
  7041. }
  7042. }
  7043. else {
  7044. if(videoMutedSpan.length == 0) {
  7045. videoMutedSpan = document.createElement('span');
  7046. videoMutedSpan.className = 'videoMuted';
  7047. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  7048. var mutedIndicator = document.createElement('i');
  7049. mutedIndicator.className = 'icon-camera-disabled';
  7050. UIUtil.setTooltip(mutedIndicator,
  7051. "videothumbnail.videomute",
  7052. "top");
  7053. videoMutedSpan.appendChild(mutedIndicator);
  7054. //translate texts for muted indicator
  7055. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  7056. }
  7057. VideoLayout.updateMutePosition(videoSpanId);
  7058. }
  7059. };
  7060. my.updateMutePosition = function (videoSpanId) {
  7061. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  7062. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  7063. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  7064. if(connectionIndicator.length > 0
  7065. && connectionIndicator[0].style.display != "none") {
  7066. audioMutedSpan.css({right: "23px"});
  7067. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  7068. }
  7069. else
  7070. {
  7071. audioMutedSpan.css({right: "0px"});
  7072. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  7073. }
  7074. }
  7075. /**
  7076. * Shows audio muted indicator over small videos.
  7077. * @param {string} isMuted
  7078. */
  7079. my.showAudioIndicator = function(videoSpanId, isMuted) {
  7080. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  7081. if (isMuted === 'false') {
  7082. if (audioMutedSpan.length > 0) {
  7083. audioMutedSpan.popover('hide');
  7084. audioMutedSpan.remove();
  7085. }
  7086. }
  7087. else {
  7088. if(audioMutedSpan.length == 0 ) {
  7089. audioMutedSpan = document.createElement('span');
  7090. audioMutedSpan.className = 'audioMuted';
  7091. UIUtil.setTooltip(audioMutedSpan,
  7092. "videothumbnail.mute",
  7093. "top");
  7094. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  7095. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  7096. var mutedIndicator = document.createElement('i');
  7097. mutedIndicator.className = 'icon-mic-disabled';
  7098. audioMutedSpan.appendChild(mutedIndicator);
  7099. }
  7100. VideoLayout.updateMutePosition(videoSpanId);
  7101. }
  7102. };
  7103. /*
  7104. * Shows or hides the audio muted indicator over the local thumbnail video.
  7105. * @param {boolean} isMuted
  7106. */
  7107. my.showLocalAudioIndicator = function(isMuted) {
  7108. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  7109. };
  7110. /**
  7111. * Resizes the large video container.
  7112. */
  7113. my.resizeLargeVideoContainer = function () {
  7114. Chat.resizeChat();
  7115. var availableHeight = window.innerHeight;
  7116. var availableWidth = UIUtil.getAvailableVideoWidth();
  7117. if (availableWidth < 0 || availableHeight < 0) return;
  7118. $('#videospace').width(availableWidth);
  7119. $('#videospace').height(availableHeight);
  7120. $('#largeVideoContainer').width(availableWidth);
  7121. $('#largeVideoContainer').height(availableHeight);
  7122. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7123. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7124. $('#activeSpeaker').css('top', top);
  7125. VideoLayout.resizeThumbnails();
  7126. };
  7127. /**
  7128. * Resizes thumbnails.
  7129. */
  7130. my.resizeThumbnails = function() {
  7131. var videoSpaceWidth = $('#remoteVideos').width();
  7132. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  7133. var width = thumbnailSize[0];
  7134. var height = thumbnailSize[1];
  7135. // size videos so that while keeping AR and max height, we have a
  7136. // nice fit
  7137. $('#remoteVideos').height(height);
  7138. $('#remoteVideos>span').width(width);
  7139. $('#remoteVideos>span').height(height);
  7140. $('.userAvatar').css('left', (width - height) / 2);
  7141. $(document).trigger("remotevideo.resized", [width, height]);
  7142. };
  7143. /**
  7144. * Enables the dominant speaker UI.
  7145. *
  7146. * @param resourceJid the jid indicating the video element to
  7147. * activate/deactivate
  7148. * @param isEnable indicates if the dominant speaker should be enabled or
  7149. * disabled
  7150. */
  7151. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  7152. var videoSpanId = null;
  7153. var videoContainerId = null;
  7154. if (resourceJid
  7155. === APP.xmpp.myResource()) {
  7156. videoSpanId = 'localVideoWrapper';
  7157. videoContainerId = 'localVideoContainer';
  7158. }
  7159. else {
  7160. videoSpanId = 'participant_' + resourceJid;
  7161. videoContainerId = videoSpanId;
  7162. }
  7163. var displayName = resourceJid;
  7164. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  7165. if (nameSpan.length > 0)
  7166. displayName = nameSpan.html();
  7167. console.log("UI enable dominant speaker",
  7168. displayName,
  7169. resourceJid,
  7170. isEnable);
  7171. videoSpan = document.getElementById(videoContainerId);
  7172. if (!videoSpan) {
  7173. return;
  7174. }
  7175. var video = $('#' + videoSpanId + '>video');
  7176. if (video && video.length > 0) {
  7177. if (isEnable) {
  7178. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  7179. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  7180. if (!videoSpan.classList.contains("dominantspeaker"))
  7181. videoSpan.classList.add("dominantspeaker");
  7182. }
  7183. else {
  7184. VideoLayout.showDisplayName(videoContainerId, false);
  7185. if (videoSpan.classList.contains("dominantspeaker"))
  7186. videoSpan.classList.remove("dominantspeaker");
  7187. }
  7188. Avatar.showUserAvatar(
  7189. APP.xmpp.findJidFromResource(resourceJid));
  7190. }
  7191. };
  7192. /**
  7193. * Calculates the thumbnail size.
  7194. *
  7195. * @param videoSpaceWidth the width of the video space
  7196. */
  7197. my.calculateThumbnailSize = function (videoSpaceWidth) {
  7198. // Calculate the available height, which is the inner window height minus
  7199. // 39px for the header minus 2px for the delimiter lines on the top and
  7200. // bottom of the large video, minus the 36px space inside the remoteVideos
  7201. // container used for highlighting shadow.
  7202. var availableHeight = 100;
  7203. var numvids = $('#remoteVideos>span:visible').length;
  7204. if (localLastNCount && localLastNCount > 0) {
  7205. numvids = Math.min(localLastNCount + 1, numvids);
  7206. }
  7207. // Remove the 3px borders arround videos and border around the remote
  7208. // videos area and the 4 pixels between the local video and the others
  7209. //TODO: Find out where the 4 pixels come from and remove them
  7210. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  7211. var availableWidth = availableWinWidth / numvids;
  7212. var aspectRatio = 16.0 / 9.0;
  7213. var maxHeight = Math.min(160, availableHeight);
  7214. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  7215. if (availableHeight < availableWidth / aspectRatio) {
  7216. availableWidth = Math.floor(availableHeight * aspectRatio);
  7217. }
  7218. return [availableWidth, availableHeight];
  7219. };
  7220. /**
  7221. * Updates the remote video menu.
  7222. *
  7223. * @param jid the jid indicating the video for which we're adding a menu.
  7224. * @param isMuted indicates the current mute state
  7225. */
  7226. my.updateRemoteVideoMenu = function(jid, isMuted) {
  7227. var muteMenuItem
  7228. = $('#remote_popupmenu_'
  7229. + Strophe.getResourceFromJid(jid)
  7230. + '>li>a.mutelink');
  7231. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  7232. if (muteMenuItem.length) {
  7233. var muteLink = muteMenuItem.get(0);
  7234. if (isMuted === 'true') {
  7235. muteLink.innerHTML = mutedIndicator + ' Muted';
  7236. muteLink.className = 'mutelink disabled';
  7237. }
  7238. else {
  7239. muteLink.innerHTML = mutedIndicator + ' Mute';
  7240. muteLink.className = 'mutelink';
  7241. }
  7242. }
  7243. };
  7244. /**
  7245. * Returns the current dominant speaker resource jid.
  7246. */
  7247. my.getDominantSpeakerResourceJid = function () {
  7248. return currentDominantSpeaker;
  7249. };
  7250. /**
  7251. * Returns the corresponding resource jid to the given peer container
  7252. * DOM element.
  7253. *
  7254. * @return the corresponding resource jid to the given peer container
  7255. * DOM element
  7256. */
  7257. my.getPeerContainerResourceJid = function (containerElement) {
  7258. var i = containerElement.id.indexOf('participant_');
  7259. if (i >= 0)
  7260. return containerElement.id.substring(i + 12);
  7261. };
  7262. /**
  7263. * On contact list item clicked.
  7264. */
  7265. $(ContactList).bind('contactclicked', function(event, jid) {
  7266. if (!jid) {
  7267. return;
  7268. }
  7269. var resource = Strophe.getResourceFromJid(jid);
  7270. var videoContainer = $("#participant_" + resource);
  7271. if (videoContainer.length > 0) {
  7272. var videoThumb = $('video', videoContainer).get(0);
  7273. // It is not always the case that a videoThumb exists (if there is
  7274. // no actual video).
  7275. if (videoThumb) {
  7276. if (videoThumb.src && videoThumb.src != '') {
  7277. // We have a video src, great! Let's update the large video
  7278. // now.
  7279. VideoLayout.handleVideoThumbClicked(
  7280. videoThumb.src,
  7281. false,
  7282. Strophe.getResourceFromJid(jid));
  7283. } else {
  7284. // If we don't have a video src for jid, there's absolutely
  7285. // no point in calling handleVideoThumbClicked; Quite
  7286. // simply, it won't work because it needs an src to attach
  7287. // to the large video.
  7288. //
  7289. // Instead, we trigger the pinned endpoint changed event to
  7290. // let the bridge adjust its lastN set for myjid and store
  7291. // the pinned user in the lastNPickupJid variable to be
  7292. // picked up later by the lastN changed event handler.
  7293. lastNPickupJid = jid;
  7294. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  7295. Strophe.getResourceFromJid(jid));
  7296. }
  7297. } else if (jid == APP.xmpp.myJid()) {
  7298. $("#localVideoContainer").click();
  7299. }
  7300. }
  7301. });
  7302. /**
  7303. * On audio muted event.
  7304. */
  7305. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  7306. /*
  7307. // FIXME: but focus can not mute in this case ? - check
  7308. if (jid === xmpp.myJid()) {
  7309. // The local mute indicator is controlled locally
  7310. return;
  7311. }*/
  7312. var videoSpanId = null;
  7313. if (jid === APP.xmpp.myJid()) {
  7314. videoSpanId = 'localVideoContainer';
  7315. } else {
  7316. VideoLayout.ensurePeerContainerExists(jid);
  7317. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7318. }
  7319. mutedAudios[jid] = isMuted;
  7320. if (APP.xmpp.isModerator()) {
  7321. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  7322. }
  7323. if (videoSpanId)
  7324. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  7325. });
  7326. /**
  7327. * On video muted event.
  7328. */
  7329. $(document).bind('videomuted.muc', function (event, jid, value) {
  7330. var isMuted = (value === "true");
  7331. if(jid !== APP.xmpp.myJid() && !APP.RTC.muteRemoteVideoStream(jid, isMuted))
  7332. return;
  7333. Avatar.showUserAvatar(jid, isMuted);
  7334. var videoSpanId = null;
  7335. if (jid === APP.xmpp.myJid()) {
  7336. videoSpanId = 'localVideoContainer';
  7337. } else {
  7338. VideoLayout.ensurePeerContainerExists(jid);
  7339. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7340. }
  7341. if (videoSpanId)
  7342. VideoLayout.showVideoIndicator(videoSpanId, value);
  7343. });
  7344. /**
  7345. * Display name changed.
  7346. */
  7347. my.onDisplayNameChanged =
  7348. function (jid, displayName, status) {
  7349. if (jid === 'localVideoContainer'
  7350. || jid === APP.xmpp.myJid()) {
  7351. setDisplayName('localVideoContainer',
  7352. displayName);
  7353. } else {
  7354. VideoLayout.ensurePeerContainerExists(jid);
  7355. setDisplayName(
  7356. 'participant_' + Strophe.getResourceFromJid(jid),
  7357. displayName,
  7358. status);
  7359. }
  7360. };
  7361. /**
  7362. * On dominant speaker changed event.
  7363. */
  7364. my.onDominantSpeakerChanged = function (resourceJid) {
  7365. // We ignore local user events.
  7366. if (resourceJid
  7367. === APP.xmpp.myResource())
  7368. return;
  7369. var members = APP.xmpp.getMembers();
  7370. // Update the current dominant speaker.
  7371. if (resourceJid !== currentDominantSpeaker) {
  7372. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  7373. newSpeakerVideoSpanId = "participant_" + resourceJid;
  7374. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  7375. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  7376. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  7377. !members[currentJID].displayName)) {
  7378. setDisplayName(oldSpeakerVideoSpanId, null);
  7379. }
  7380. if(resourceJid && (!members || !members[newJID] ||
  7381. !members[newJID].displayName)) {
  7382. setDisplayName(newSpeakerVideoSpanId, null,
  7383. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  7384. }
  7385. currentDominantSpeaker = resourceJid;
  7386. } else {
  7387. return;
  7388. }
  7389. // Obtain container for new dominant speaker.
  7390. var container = document.getElementById(
  7391. 'participant_' + resourceJid);
  7392. // Local video will not have container found, but that's ok
  7393. // since we don't want to switch to local video.
  7394. if (container && !focusedVideoInfo)
  7395. {
  7396. var video = container.getElementsByTagName("video");
  7397. // Update the large video if the video source is already available,
  7398. // otherwise wait for the "videoactive.jingle" event.
  7399. if (video.length && video[0].currentTime > 0)
  7400. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  7401. }
  7402. };
  7403. /**
  7404. * On last N change event.
  7405. *
  7406. * @param lastNEndpoints the list of last N endpoints
  7407. * @param endpointsEnteringLastN the list currently entering last N
  7408. * endpoints
  7409. */
  7410. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7411. endpointsEnteringLastN,
  7412. stream) {
  7413. if (lastNCount !== lastNEndpoints.length)
  7414. lastNCount = lastNEndpoints.length;
  7415. lastNEndpointsCache = lastNEndpoints;
  7416. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7417. //
  7418. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7419. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7420. // so E sees them. C is only in E's local LastN set.
  7421. //
  7422. // If F starts talking and LastN = 3, then E should see thumbnails for
  7423. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7424. // enters E's local LastN ejecting C.
  7425. // Increase the local LastN set size, if necessary.
  7426. if (lastNCount > localLastNCount) {
  7427. localLastNCount = lastNCount;
  7428. }
  7429. // Update the local LastN set preserving the order in which the
  7430. // endpoints appeared in the LastN/local LastN set.
  7431. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7432. for (var i = 0; i < localLastNSet.length; i++) {
  7433. if (nextLocalLastNSet.length >= localLastNCount) {
  7434. break;
  7435. }
  7436. var resourceJid = localLastNSet[i];
  7437. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7438. nextLocalLastNSet.push(resourceJid);
  7439. }
  7440. }
  7441. localLastNSet = nextLocalLastNSet;
  7442. var updateLargeVideo = false;
  7443. // Handle LastN/local LastN changes.
  7444. $('#remoteVideos>span').each(function( index, element ) {
  7445. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7446. var isReceived = true;
  7447. if (resourceJid
  7448. && lastNEndpoints.indexOf(resourceJid) < 0
  7449. && localLastNSet.indexOf(resourceJid) < 0) {
  7450. console.log("Remove from last N", resourceJid);
  7451. showPeerContainer(resourceJid, 'hide');
  7452. isReceived = false;
  7453. } else if (resourceJid
  7454. && $('#participant_' + resourceJid).is(':visible')
  7455. && lastNEndpoints.indexOf(resourceJid) < 0
  7456. && localLastNSet.indexOf(resourceJid) >= 0) {
  7457. showPeerContainer(resourceJid, 'avatar');
  7458. isReceived = false;
  7459. }
  7460. if (!isReceived) {
  7461. // resourceJid has dropped out of the server side lastN set, so
  7462. // it is no longer being received. If resourceJid was being
  7463. // displayed in the large video we have to switch to another
  7464. // user.
  7465. var largeVideoResource = largeVideoState.userResourceJid;
  7466. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7467. updateLargeVideo = true;
  7468. }
  7469. }
  7470. });
  7471. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7472. endpointsEnteringLastN = lastNEndpoints;
  7473. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7474. endpointsEnteringLastN.forEach(function (resourceJid) {
  7475. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7476. showPeerContainer(resourceJid, 'show');
  7477. if (!isVisible) {
  7478. console.log("Add to last N", resourceJid);
  7479. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7480. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7481. var sel = $('#participant_' + resourceJid + '>video');
  7482. var videoStream = APP.simulcast.getReceivingVideoStream(
  7483. mediaStream.stream);
  7484. APP.RTC.attachMediaStream(sel, videoStream);
  7485. if (lastNPickupJid == mediaStream.peerjid) {
  7486. // Clean up the lastN pickup jid.
  7487. lastNPickupJid = null;
  7488. // Don't fire the events again, they've already
  7489. // been fired in the contact list click handler.
  7490. VideoLayout.handleVideoThumbClicked(
  7491. $(sel).attr('src'),
  7492. false,
  7493. Strophe.getResourceFromJid(mediaStream.peerjid));
  7494. updateLargeVideo = false;
  7495. }
  7496. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7497. }
  7498. })
  7499. }
  7500. // The endpoint that was being shown in the large video has dropped out
  7501. // of the lastN set and there was no lastN pickup jid. We need to update
  7502. // the large video now.
  7503. if (updateLargeVideo) {
  7504. var resource, container, src;
  7505. var myResource
  7506. = APP.xmpp.myResource();
  7507. // Find out which endpoint to show in the large video.
  7508. for (var i = 0; i < lastNEndpoints.length; i++) {
  7509. resource = lastNEndpoints[i];
  7510. if (!resource || resource === myResource)
  7511. continue;
  7512. container = $("#participant_" + resource);
  7513. if (container.length == 0)
  7514. continue;
  7515. src = $('video', container).attr('src');
  7516. if (!src)
  7517. continue;
  7518. // videoSrcToSsrc needs to be update for this call to succeed.
  7519. VideoLayout.updateLargeVideo(src);
  7520. break;
  7521. }
  7522. }
  7523. };
  7524. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  7525. endpointSimulcastLayers.forEach(function (esl) {
  7526. var resource = esl.endpoint;
  7527. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7528. // then ignore the event (= do not preload anything).
  7529. //
  7530. // The bridge could probably stop sending this message if it's for
  7531. // an endpoint that's not in lastN.
  7532. if (lastNCount != -1
  7533. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7534. return;
  7535. }
  7536. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7537. // Get session and stream from primary ssrc.
  7538. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7539. var sid = res.sid;
  7540. var electedStream = res.stream;
  7541. if (sid && electedStream) {
  7542. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7543. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7544. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  7545. if (preload) {
  7546. if (largeVideoState.preload)
  7547. {
  7548. $(largeVideoState.preload).remove();
  7549. }
  7550. console.info('Preloading remote video');
  7551. largeVideoState.preload = $('<video autoplay></video>');
  7552. // ssrcs are unique in an rtp session
  7553. largeVideoState.preload_ssrc = primarySSRC;
  7554. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  7555. }
  7556. } else {
  7557. console.error('Could not find a stream or a session.', sid, electedStream);
  7558. }
  7559. });
  7560. };
  7561. /**
  7562. * On simulcast layers changed event.
  7563. */
  7564. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  7565. endpointSimulcastLayers.forEach(function (esl) {
  7566. var resource = esl.endpoint;
  7567. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7568. // then ignore the event (= do not change large video/thumbnail
  7569. // SRCs).
  7570. //
  7571. // Note that even if we ignore the "changed" event in this event
  7572. // handler, the bridge must continue sending these events because
  7573. // the simulcast code in simulcast.js uses it to know what's going
  7574. // to be streamed by the bridge when/if the endpoint gets back into
  7575. // the lastN set.
  7576. if (lastNCount != -1
  7577. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7578. return;
  7579. }
  7580. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7581. // Get session and stream from primary ssrc.
  7582. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7583. var sid = res.sid;
  7584. var electedStream = res.stream;
  7585. if (sid && electedStream) {
  7586. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7587. console.info('Switching simulcast substream.');
  7588. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7589. var msidParts = msid.split(' ');
  7590. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  7591. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  7592. == largeVideoState.userResourceJid);
  7593. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  7594. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  7595. var electedStreamUrl;
  7596. if (largeVideoState.preload_ssrc == primarySSRC)
  7597. {
  7598. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  7599. }
  7600. else
  7601. {
  7602. if (largeVideoState.preload
  7603. && largeVideoState.preload != null) {
  7604. $(largeVideoState.preload).remove();
  7605. }
  7606. largeVideoState.preload_ssrc = 0;
  7607. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  7608. }
  7609. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  7610. if (updateLargeVideo) {
  7611. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  7612. Strophe.getResourceFromJid(jid));
  7613. }
  7614. if (updateFocusedVideoSrc) {
  7615. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  7616. }
  7617. var videoId;
  7618. if(resource == APP.xmpp.myResource())
  7619. {
  7620. videoId = "localVideoContainer";
  7621. }
  7622. else
  7623. {
  7624. videoId = "participant_" + resource;
  7625. }
  7626. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  7627. if(connectionIndicator)
  7628. connectionIndicator.updatePopoverData();
  7629. } else {
  7630. console.error('Could not find a stream or a sid.', sid, electedStream);
  7631. }
  7632. });
  7633. };
  7634. /**
  7635. * Updates local stats
  7636. * @param percent
  7637. * @param object
  7638. */
  7639. my.updateLocalConnectionStats = function (percent, object) {
  7640. var resolution = null;
  7641. if(object.resolution !== null)
  7642. {
  7643. resolution = object.resolution;
  7644. object.resolution = resolution[APP.xmpp.myJid()];
  7645. delete resolution[APP.xmpp.myJid()];
  7646. }
  7647. updateStatsIndicator("localVideoContainer", percent, object);
  7648. for(var jid in resolution)
  7649. {
  7650. if(resolution[jid] === null)
  7651. continue;
  7652. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7653. if(VideoLayout.connectionIndicators[id])
  7654. {
  7655. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7656. }
  7657. }
  7658. };
  7659. /**
  7660. * Updates remote stats.
  7661. * @param jid the jid associated with the stats
  7662. * @param percent the connection quality percent
  7663. * @param object the stats data
  7664. */
  7665. my.updateConnectionStats = function (jid, percent, object) {
  7666. var resourceJid = Strophe.getResourceFromJid(jid);
  7667. var videoSpanId = 'participant_' + resourceJid;
  7668. updateStatsIndicator(videoSpanId, percent, object);
  7669. };
  7670. /**
  7671. * Removes the connection
  7672. * @param jid
  7673. */
  7674. my.removeConnectionIndicator = function (jid) {
  7675. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7676. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7677. };
  7678. /**
  7679. * Hides the connection indicator
  7680. * @param jid
  7681. */
  7682. my.hideConnectionIndicator = function (jid) {
  7683. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7684. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7685. };
  7686. /**
  7687. * Hides all the indicators
  7688. */
  7689. my.onStatsStop = function () {
  7690. for(var indicator in VideoLayout.connectionIndicators)
  7691. {
  7692. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7693. }
  7694. };
  7695. my.participantLeft = function (jid) {
  7696. // Unlock large video
  7697. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7698. {
  7699. console.info("Focused video owner has left the conference");
  7700. focusedVideoInfo = null;
  7701. }
  7702. }
  7703. my.onVideoTypeChanged = function (jid) {
  7704. if(jid &&
  7705. Strophe.getResourceFromJid(jid) === largeVideoState.userResourceJid)
  7706. {
  7707. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  7708. VideoLayout.getVideoSize = largeVideoState.isDesktop
  7709. ? getDesktopVideoSize
  7710. : getCameraVideoSize;
  7711. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  7712. ? getDesktopVideoPosition
  7713. : getCameraVideoPosition;
  7714. VideoLayout.positionLarge(null, null);
  7715. }
  7716. }
  7717. return my;
  7718. }(VideoLayout || {}));
  7719. module.exports = VideoLayout;
  7720. },{"../../../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){
  7721. //var nouns = [
  7722. //];
  7723. var pluralNouns = [
  7724. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7725. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  7726. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  7727. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  7728. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  7729. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  7730. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  7731. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  7732. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  7733. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  7734. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  7735. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  7736. ];
  7737. //var places = [
  7738. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  7739. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  7740. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  7741. // "Bridge"
  7742. //];
  7743. var verbs = [
  7744. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  7745. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  7746. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  7747. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  7748. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  7749. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  7750. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  7751. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  7752. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  7753. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  7754. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  7755. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  7756. ];
  7757. var adverbs = [
  7758. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  7759. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  7760. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  7761. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  7762. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  7763. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  7764. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  7765. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  7766. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  7767. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  7768. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  7769. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  7770. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  7771. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  7772. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  7773. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  7774. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  7775. ];
  7776. var adjectives = [
  7777. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  7778. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  7779. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  7780. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  7781. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  7782. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  7783. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  7784. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  7785. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  7786. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  7787. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  7788. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  7789. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  7790. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  7791. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  7792. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  7793. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  7794. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  7795. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  7796. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  7797. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  7798. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  7799. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  7800. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  7801. "Zealous"
  7802. ];
  7803. //var pronouns = [
  7804. //];
  7805. //var conjunctions = [
  7806. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  7807. //];
  7808. /*
  7809. * Maps a string (category name) to the array of words from that category.
  7810. */
  7811. var CATEGORIES =
  7812. {
  7813. //"_NOUN_": nouns,
  7814. "_PLURALNOUN_": pluralNouns,
  7815. //"_PLACE_": places,
  7816. "_VERB_": verbs,
  7817. "_ADVERB_": adverbs,
  7818. "_ADJECTIVE_": adjectives
  7819. //"_PRONOUN_": pronouns,
  7820. //"_CONJUNCTION_": conjunctions,
  7821. };
  7822. var PATTERNS = [
  7823. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  7824. // BeautifulFungiOrSpaghetti
  7825. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  7826. // AmazinglyScaryToy
  7827. //"_ADVERB__ADJECTIVE__NOUN_",
  7828. // NeitherTrashNorRifle
  7829. //"Neither_NOUN_Nor_NOUN_",
  7830. //"Either_NOUN_Or_NOUN_",
  7831. // EitherCopulateOrInvestigate
  7832. //"Either_VERB_Or_VERB_",
  7833. //"Neither_VERB_Nor_VERB_",
  7834. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  7835. //"The_ADVERB__ADJECTIVE__NOUN_",
  7836. //"The_ADVERB__ADJECTIVE__NOUN_s",
  7837. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  7838. // WolvesComputeBadly
  7839. //"_PLURALNOUN__VERB__ADVERB_",
  7840. // UniteFacilitateAndMerge
  7841. //"_VERB__VERB_And_VERB_",
  7842. //NastyWitchesAtThePub
  7843. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  7844. ];
  7845. /*
  7846. * Returns a random element from the array 'arr'
  7847. */
  7848. function randomElement(arr)
  7849. {
  7850. return arr[Math.floor(Math.random() * arr.length)];
  7851. }
  7852. /*
  7853. * Returns true if the string 's' contains one of the
  7854. * template strings.
  7855. */
  7856. function hasTemplate(s)
  7857. {
  7858. for (var template in CATEGORIES){
  7859. if (s.indexOf(template) >= 0){
  7860. return true;
  7861. }
  7862. }
  7863. }
  7864. /**
  7865. * Generates new room name.
  7866. */
  7867. var RoomNameGenerator = {
  7868. generateRoomWithoutSeparator: function()
  7869. {
  7870. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  7871. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  7872. var name = randomElement(PATTERNS);
  7873. var word;
  7874. while (hasTemplate(name)){
  7875. for (var template in CATEGORIES){
  7876. word = randomElement(CATEGORIES[template]);
  7877. name = name.replace(template, word);
  7878. }
  7879. }
  7880. return name;
  7881. }
  7882. }
  7883. module.exports = RoomNameGenerator;
  7884. },{}],34:[function(require,module,exports){
  7885. var animateTimeout, updateTimeout;
  7886. var RoomNameGenerator = require("./RoomnameGenerator");
  7887. function enter_room()
  7888. {
  7889. var val = $("#enter_room_field").val();
  7890. if(!val) {
  7891. val = $("#enter_room_field").attr("room_name");
  7892. }
  7893. if (val) {
  7894. window.location.pathname = "/" + val;
  7895. }
  7896. }
  7897. function animate(word) {
  7898. var currentVal = $("#enter_room_field").attr("placeholder");
  7899. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  7900. animateTimeout = setTimeout(function() {
  7901. animate(word.substring(1, word.length))
  7902. }, 70);
  7903. }
  7904. function update_roomname()
  7905. {
  7906. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  7907. $("#enter_room_field").attr("room_name", word);
  7908. $("#enter_room_field").attr("placeholder", "");
  7909. clearTimeout(animateTimeout);
  7910. animate(word);
  7911. updateTimeout = setTimeout(update_roomname, 10000);
  7912. }
  7913. function setupWelcomePage()
  7914. {
  7915. $("#videoconference_page").hide();
  7916. $("#domain_name").text(
  7917. window.location.protocol + "//" + window.location.host + "/");
  7918. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7919. var leftWatermarkDiv
  7920. = $("#welcome_page_header div[class='watermark leftwatermark']");
  7921. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  7922. {
  7923. leftWatermarkDiv.css({display: 'block'});
  7924. leftWatermarkDiv.parent().get(0).href
  7925. = interfaceConfig.JITSI_WATERMARK_LINK;
  7926. }
  7927. }
  7928. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7929. var rightWatermarkDiv
  7930. = $("#welcome_page_header div[class='watermark rightwatermark']");
  7931. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  7932. rightWatermarkDiv.css({display: 'block'});
  7933. rightWatermarkDiv.parent().get(0).href
  7934. = interfaceConfig.BRAND_WATERMARK_LINK;
  7935. rightWatermarkDiv.get(0).style.backgroundImage
  7936. = "url(images/rightwatermark.png)";
  7937. }
  7938. }
  7939. if (interfaceConfig.SHOW_POWERED_BY) {
  7940. $("#welcome_page_header>a[class='poweredby']")
  7941. .css({display: 'block'});
  7942. }
  7943. $("#enter_room_button").click(function()
  7944. {
  7945. enter_room();
  7946. });
  7947. $("#enter_room_field").keydown(function (event) {
  7948. if (event.keyCode === 13 /* enter */) {
  7949. enter_room();
  7950. }
  7951. });
  7952. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  7953. var updateTimeout;
  7954. var animateTimeout;
  7955. $("#reload_roomname").click(function () {
  7956. clearTimeout(updateTimeout);
  7957. clearTimeout(animateTimeout);
  7958. update_roomname();
  7959. });
  7960. $("#reload_roomname").show();
  7961. update_roomname();
  7962. }
  7963. $("#disable_welcome").click(function () {
  7964. window.localStorage.welcomePageDisabled
  7965. = $("#disable_welcome").is(":checked");
  7966. });
  7967. }
  7968. module.exports = setupWelcomePage;
  7969. },{"./RoomnameGenerator":33}],35:[function(require,module,exports){
  7970. var EventEmitter = require("events");
  7971. var eventEmitter = new EventEmitter();
  7972. var CQEvents = require("../../service/connectionquality/CQEvents");
  7973. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7974. /**
  7975. * local stats
  7976. * @type {{}}
  7977. */
  7978. var stats = {};
  7979. /**
  7980. * remote stats
  7981. * @type {{}}
  7982. */
  7983. var remoteStats = {};
  7984. /**
  7985. * Interval for sending statistics to other participants
  7986. * @type {null}
  7987. */
  7988. var sendIntervalId = null;
  7989. /**
  7990. * Start statistics sending.
  7991. */
  7992. function startSendingStats() {
  7993. sendStats();
  7994. sendIntervalId = setInterval(sendStats, 10000);
  7995. }
  7996. /**
  7997. * Sends statistics to other participants
  7998. */
  7999. function sendStats() {
  8000. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  8001. }
  8002. /**
  8003. * Converts statistics to format for sending through XMPP
  8004. * @param stats the statistics
  8005. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  8006. */
  8007. function convertToMUCStats(stats) {
  8008. return {
  8009. "bitrate_download": stats.bitrate.download,
  8010. "bitrate_upload": stats.bitrate.upload,
  8011. "packetLoss_total": stats.packetLoss.total,
  8012. "packetLoss_download": stats.packetLoss.download,
  8013. "packetLoss_upload": stats.packetLoss.upload
  8014. };
  8015. }
  8016. /**
  8017. * Converts statitistics to format used by VideoLayout
  8018. * @param stats
  8019. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  8020. */
  8021. function parseMUCStats(stats) {
  8022. return {
  8023. bitrate: {
  8024. download: stats.bitrate_download,
  8025. upload: stats.bitrate_upload
  8026. },
  8027. packetLoss: {
  8028. total: stats.packetLoss_total,
  8029. download: stats.packetLoss_download,
  8030. upload: stats.packetLoss_upload
  8031. }
  8032. };
  8033. }
  8034. var ConnectionQuality = {
  8035. init: function () {
  8036. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  8037. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  8038. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  8039. },
  8040. /**
  8041. * Updates the local statistics
  8042. * @param data new statistics
  8043. */
  8044. updateLocalStats: function (data) {
  8045. stats = data;
  8046. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  8047. if (sendIntervalId == null) {
  8048. startSendingStats();
  8049. }
  8050. },
  8051. /**
  8052. * Updates remote statistics
  8053. * @param jid the jid associated with the statistics
  8054. * @param data the statistics
  8055. */
  8056. updateRemoteStats: function (jid, data) {
  8057. if (data == null || data.packetLoss_total == null) {
  8058. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  8059. return;
  8060. }
  8061. remoteStats[jid] = parseMUCStats(data);
  8062. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  8063. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  8064. },
  8065. /**
  8066. * Stops statistics sending.
  8067. */
  8068. stopSendingStats: function () {
  8069. clearInterval(sendIntervalId);
  8070. sendIntervalId = null;
  8071. //notify UI about stopping statistics gathering
  8072. eventEmitter.emit(CQEvents.STOP);
  8073. },
  8074. /**
  8075. * Returns the local statistics.
  8076. */
  8077. getStats: function () {
  8078. return stats;
  8079. },
  8080. addListener: function (type, listener) {
  8081. eventEmitter.on(type, listener);
  8082. }
  8083. };
  8084. module.exports = ConnectionQuality;
  8085. },{"../../service/connectionquality/CQEvents":94,"../../service/xmpp/XMPPEvents":97,"events":98}],36:[function(require,module,exports){
  8086. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  8087. getUserMediaWithConstraints */
  8088. /**
  8089. * Indicates that desktop stream is currently in use(for toggle purpose).
  8090. * @type {boolean}
  8091. */
  8092. var isUsingScreenStream = false;
  8093. /**
  8094. * Indicates that switch stream operation is in progress and prevent from
  8095. * triggering new events.
  8096. * @type {boolean}
  8097. */
  8098. var switchInProgress = false;
  8099. /**
  8100. * Method used to get screen sharing stream.
  8101. *
  8102. * @type {function (stream_callback, failure_callback}
  8103. */
  8104. var obtainDesktopStream = null;
  8105. /**
  8106. * Indicates whether desktop sharing extension is installed.
  8107. * @type {boolean}
  8108. */
  8109. var extInstalled = false;
  8110. /**
  8111. * Indicates whether update of desktop sharing extension is required.
  8112. * @type {boolean}
  8113. */
  8114. var extUpdateRequired = false;
  8115. /**
  8116. * Flag used to cache desktop sharing enabled state. Do not use directly as
  8117. * it can be <tt>null</tt>.
  8118. *
  8119. * @type {null|boolean}
  8120. */
  8121. var _desktopSharingEnabled = null;
  8122. var EventEmitter = require("events");
  8123. var eventEmitter = new EventEmitter();
  8124. var DesktopSharingEventTypes
  8125. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  8126. /**
  8127. * Method obtains desktop stream from WebRTC 'screen' source.
  8128. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  8129. */
  8130. function obtainWebRTCScreen(streamCallback, failCallback) {
  8131. APP.RTC.getUserMediaWithConstraints(
  8132. ['screen'],
  8133. streamCallback,
  8134. failCallback
  8135. );
  8136. }
  8137. /**
  8138. * Constructs inline install URL for Chrome desktop streaming extension.
  8139. * The 'chromeExtensionId' must be defined in config.js.
  8140. * @returns {string}
  8141. */
  8142. function getWebStoreInstallUrl()
  8143. {
  8144. return "https://chrome.google.com/webstore/detail/" +
  8145. config.chromeExtensionId;
  8146. }
  8147. /**
  8148. * Checks whether extension update is required.
  8149. * @param minVersion minimal required version
  8150. * @param extVersion current extension version
  8151. * @returns {boolean}
  8152. */
  8153. function isUpdateRequired(minVersion, extVersion)
  8154. {
  8155. try
  8156. {
  8157. var s1 = minVersion.split('.');
  8158. var s2 = extVersion.split('.');
  8159. var len = Math.max(s1.length, s2.length);
  8160. for (var i = 0; i < len; i++)
  8161. {
  8162. var n1 = 0,
  8163. n2 = 0;
  8164. if (i < s1.length)
  8165. n1 = parseInt(s1[i]);
  8166. if (i < s2.length)
  8167. n2 = parseInt(s2[i]);
  8168. if (isNaN(n1) || isNaN(n2))
  8169. {
  8170. return true;
  8171. }
  8172. else if (n1 !== n2)
  8173. {
  8174. return n1 > n2;
  8175. }
  8176. }
  8177. // will happen if boths version has identical numbers in
  8178. // their components (even if one of them is longer, has more components)
  8179. return false;
  8180. }
  8181. catch (e)
  8182. {
  8183. console.error("Failed to parse extension version", e);
  8184. APP.UI.messageHandler.showError("dialog.error",
  8185. "dialog.detectext");
  8186. return true;
  8187. }
  8188. }
  8189. function checkExtInstalled(callback) {
  8190. if (!chrome.runtime) {
  8191. // No API, so no extension for sure
  8192. callback(false, false);
  8193. return;
  8194. }
  8195. chrome.runtime.sendMessage(
  8196. config.chromeExtensionId,
  8197. { getVersion: true },
  8198. function (response) {
  8199. if (!response || !response.version) {
  8200. // Communication failure - assume that no endpoint exists
  8201. console.warn(
  8202. "Extension not installed?: ", chrome.runtime.lastError);
  8203. callback(false, false);
  8204. return;
  8205. }
  8206. // Check installed extension version
  8207. var extVersion = response.version;
  8208. console.log('Extension version is: ' + extVersion);
  8209. var updateRequired
  8210. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  8211. callback(!updateRequired, updateRequired);
  8212. }
  8213. );
  8214. }
  8215. function doGetStreamFromExtension(streamCallback, failCallback) {
  8216. // Sends 'getStream' msg to the extension.
  8217. // Extension id must be defined in the config.
  8218. chrome.runtime.sendMessage(
  8219. config.chromeExtensionId,
  8220. { getStream: true, sources: config.desktopSharingSources },
  8221. function (response) {
  8222. if (!response) {
  8223. failCallback(chrome.runtime.lastError);
  8224. return;
  8225. }
  8226. console.log("Response from extension: " + response);
  8227. if (response.streamId) {
  8228. APP.RTC.getUserMediaWithConstraints(
  8229. ['desktop'],
  8230. function (stream) {
  8231. streamCallback(stream);
  8232. },
  8233. failCallback,
  8234. null, null, null,
  8235. response.streamId);
  8236. } else {
  8237. failCallback("Extension failed to get the stream");
  8238. }
  8239. }
  8240. );
  8241. }
  8242. /**
  8243. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  8244. * stream for returned stream token.
  8245. */
  8246. function obtainScreenFromExtension(streamCallback, failCallback) {
  8247. if (extInstalled) {
  8248. doGetStreamFromExtension(streamCallback, failCallback);
  8249. } else {
  8250. if (extUpdateRequired) {
  8251. alert(
  8252. 'Jitsi Desktop Streamer requires update. ' +
  8253. 'Changes will take effect after next Chrome restart.');
  8254. }
  8255. chrome.webstore.install(
  8256. getWebStoreInstallUrl(),
  8257. function (arg) {
  8258. console.log("Extension installed successfully", arg);
  8259. // We need to reload the page in order to get the access to
  8260. // chrome.runtime
  8261. window.location.reload(false);
  8262. },
  8263. function (arg) {
  8264. console.log("Failed to install the extension", arg);
  8265. failCallback(arg);
  8266. APP.UI.messageHandler.showError("dialog.error",
  8267. "dialog.failtoinstall");
  8268. }
  8269. );
  8270. }
  8271. }
  8272. /**
  8273. * Call this method to toggle desktop sharing feature.
  8274. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  8275. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  8276. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  8277. * enabled), pass any other string or nothing in order to disable this
  8278. * feature completely.
  8279. */
  8280. function setDesktopSharing(method) {
  8281. // Check if we are running chrome
  8282. if (!navigator.webkitGetUserMedia) {
  8283. obtainDesktopStream = null;
  8284. console.info("Desktop sharing disabled");
  8285. } else if (method == "ext") {
  8286. obtainDesktopStream = obtainScreenFromExtension;
  8287. console.info("Using Chrome extension for desktop sharing");
  8288. } else if (method == "webrtc") {
  8289. obtainDesktopStream = obtainWebRTCScreen;
  8290. console.info("Using Chrome WebRTC for desktop sharing");
  8291. }
  8292. // Reset enabled cache
  8293. _desktopSharingEnabled = null;
  8294. }
  8295. /**
  8296. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  8297. * config.js to support inline installs. Host site must be selected as main
  8298. * website of published extension.
  8299. */
  8300. function initInlineInstalls()
  8301. {
  8302. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  8303. }
  8304. function getSwitchStreamFailed(error) {
  8305. console.error("Failed to obtain the stream to switch to", error);
  8306. switchInProgress = false;
  8307. isUsingScreenStream = false;
  8308. newStreamCreated(null);
  8309. }
  8310. function streamSwitchDone() {
  8311. switchInProgress = false;
  8312. eventEmitter.emit(
  8313. DesktopSharingEventTypes.SWITCHING_DONE,
  8314. isUsingScreenStream);
  8315. }
  8316. function newStreamCreated(stream)
  8317. {
  8318. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  8319. stream, isUsingScreenStream, streamSwitchDone);
  8320. }
  8321. module.exports = {
  8322. isUsingScreenStream: function () {
  8323. return isUsingScreenStream;
  8324. },
  8325. /**
  8326. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  8327. * and enabled.
  8328. */
  8329. isDesktopSharingEnabled: function () {
  8330. if (_desktopSharingEnabled === null) {
  8331. if (obtainDesktopStream === obtainScreenFromExtension) {
  8332. // Parse chrome version
  8333. var userAgent = navigator.userAgent.toLowerCase();
  8334. // We can assume that user agent is chrome, because it's
  8335. // enforced when 'ext' streaming method is set
  8336. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  8337. console.log("Chrome version" + userAgent, ver);
  8338. _desktopSharingEnabled = ver >= 34;
  8339. } else {
  8340. _desktopSharingEnabled =
  8341. obtainDesktopStream === obtainWebRTCScreen;
  8342. }
  8343. }
  8344. return _desktopSharingEnabled;
  8345. },
  8346. init: function () {
  8347. setDesktopSharing(config.desktopSharing);
  8348. // Initialize Chrome extension inline installs
  8349. if (config.chromeExtensionId) {
  8350. initInlineInstalls();
  8351. // Check if extension is installed
  8352. checkExtInstalled(function (installed, updateRequired) {
  8353. extInstalled = installed;
  8354. extUpdateRequired = updateRequired;
  8355. console.info(
  8356. "Chrome extension installed: " + extInstalled +
  8357. " updateRequired: " + extUpdateRequired);
  8358. });
  8359. }
  8360. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  8361. },
  8362. addListener: function (listener, type)
  8363. {
  8364. eventEmitter.on(type, listener);
  8365. },
  8366. removeListener: function (listener, type) {
  8367. eventEmitter.removeListener(type, listener);
  8368. },
  8369. /*
  8370. * Toggles screen sharing.
  8371. */
  8372. toggleScreenSharing: function () {
  8373. if (switchInProgress || !obtainDesktopStream) {
  8374. console.warn("Switch in progress or no method defined");
  8375. return;
  8376. }
  8377. switchInProgress = true;
  8378. if (!isUsingScreenStream)
  8379. {
  8380. // Switch to desktop stream
  8381. obtainDesktopStream(
  8382. function (stream) {
  8383. // We now use screen stream
  8384. isUsingScreenStream = true;
  8385. // Hook 'ended' event to restore camera
  8386. // when screen stream stops
  8387. stream.addEventListener('ended',
  8388. function (e) {
  8389. if (!switchInProgress && isUsingScreenStream) {
  8390. APP.desktopsharing.toggleScreenSharing();
  8391. }
  8392. }
  8393. );
  8394. newStreamCreated(stream);
  8395. },
  8396. getSwitchStreamFailed);
  8397. } else {
  8398. // Disable screen stream
  8399. APP.RTC.getUserMediaWithConstraints(
  8400. ['video'],
  8401. function (stream) {
  8402. // We are now using camera stream
  8403. isUsingScreenStream = false;
  8404. newStreamCreated(stream);
  8405. },
  8406. getSwitchStreamFailed, config.resolution || '360'
  8407. );
  8408. }
  8409. }
  8410. };
  8411. },{"../../service/desktopsharing/DesktopSharingEventTypes":95,"events":98}],37:[function(require,module,exports){
  8412. //maps keycode to character, id of popover for given function and function
  8413. var shortcuts = {
  8414. 67: {
  8415. character: "C",
  8416. id: "toggleChatPopover",
  8417. function: APP.UI.toggleChat
  8418. },
  8419. 70: {
  8420. character: "F",
  8421. id: "filmstripPopover",
  8422. function: APP.UI.toggleFilmStrip
  8423. },
  8424. 77: {
  8425. character: "M",
  8426. id: "mutePopover",
  8427. function: APP.UI.toggleAudio
  8428. },
  8429. 84: {
  8430. character: "T",
  8431. function: function() {
  8432. if(!APP.RTC.localAudio.isMuted()) {
  8433. APP.UI.toggleAudio();
  8434. }
  8435. }
  8436. },
  8437. 86: {
  8438. character: "V",
  8439. id: "toggleVideoPopover",
  8440. function: APP.UI.toggleVideo
  8441. }
  8442. };
  8443. var KeyboardShortcut = {
  8444. init: function () {
  8445. window.onkeyup = function(e) {
  8446. var keycode = e.which;
  8447. if(!($(":focus").is("input[type=text]") ||
  8448. $(":focus").is("input[type=password]") ||
  8449. $(":focus").is("textarea"))) {
  8450. if (typeof shortcuts[keycode] === "object") {
  8451. shortcuts[keycode].function();
  8452. }
  8453. else if (keycode >= "0".charCodeAt(0) &&
  8454. keycode <= "9".charCodeAt(0)) {
  8455. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8456. }
  8457. //esc while the smileys are visible hides them
  8458. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8459. APP.UI.toggleSmileys();
  8460. }
  8461. };
  8462. window.onkeydown = function(e) {
  8463. if(!($(":focus").is("input[type=text]") ||
  8464. $(":focus").is("input[type=password]") ||
  8465. $(":focus").is("textarea"))) {
  8466. if(e.which === "T".charCodeAt(0)) {
  8467. if(APP.RTC.localAudio.isMuted()) {
  8468. APP.UI.toggleAudio();
  8469. }
  8470. }
  8471. }
  8472. };
  8473. var self = this;
  8474. $('body').popover({ selector: '[data-toggle=popover]',
  8475. trigger: 'click hover',
  8476. content: function() {
  8477. return this.getAttribute("content") +
  8478. self.getShortcut(this.getAttribute("shortcut"));
  8479. }
  8480. });
  8481. },
  8482. /**
  8483. *
  8484. * @param id indicates the popover associated with the shortcut
  8485. * @returns {string} the keyboard shortcut used for the id given
  8486. */
  8487. getShortcut: function (id) {
  8488. for (var keycode in shortcuts) {
  8489. if (shortcuts.hasOwnProperty(keycode)) {
  8490. if (shortcuts[keycode].id === id) {
  8491. return " (" + shortcuts[keycode].character + ")";
  8492. }
  8493. }
  8494. }
  8495. return "";
  8496. }
  8497. };
  8498. module.exports = KeyboardShortcut;
  8499. },{}],38:[function(require,module,exports){
  8500. var email = '';
  8501. var displayName = '';
  8502. var userId;
  8503. var language = null;
  8504. function supportsLocalStorage() {
  8505. try {
  8506. return 'localStorage' in window && window.localStorage !== null;
  8507. } catch (e) {
  8508. console.log("localstorage is not supported");
  8509. return false;
  8510. }
  8511. }
  8512. function generateUniqueId() {
  8513. function _p8() {
  8514. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8515. }
  8516. return _p8() + _p8() + _p8() + _p8();
  8517. }
  8518. if (supportsLocalStorage()) {
  8519. if (!window.localStorage.jitsiMeetId) {
  8520. window.localStorage.jitsiMeetId = generateUniqueId();
  8521. console.log("generated id", window.localStorage.jitsiMeetId);
  8522. }
  8523. userId = window.localStorage.jitsiMeetId || '';
  8524. email = window.localStorage.email || '';
  8525. displayName = window.localStorage.displayname || '';
  8526. language = window.localStorage.language;
  8527. } else {
  8528. console.log("local storage is not supported");
  8529. userId = generateUniqueId();
  8530. }
  8531. var Settings =
  8532. {
  8533. setDisplayName: function (newDisplayName) {
  8534. displayName = newDisplayName;
  8535. window.localStorage.displayname = displayName;
  8536. return displayName;
  8537. },
  8538. setEmail: function (newEmail)
  8539. {
  8540. email = newEmail;
  8541. window.localStorage.email = newEmail;
  8542. return email;
  8543. },
  8544. getSettings: function () {
  8545. return {
  8546. email: email,
  8547. displayName: displayName,
  8548. uid: userId,
  8549. language: language
  8550. };
  8551. },
  8552. setLanguage: function (lang) {
  8553. language = lang;
  8554. window.localStorage.language = lang;
  8555. }
  8556. };
  8557. module.exports = Settings;
  8558. },{}],39:[function(require,module,exports){
  8559. /**
  8560. *
  8561. * @constructor
  8562. */
  8563. function SimulcastLogger(name, lvl) {
  8564. this.name = name;
  8565. this.lvl = lvl;
  8566. }
  8567. SimulcastLogger.prototype.log = function (text) {
  8568. if (this.lvl) {
  8569. console.log(text);
  8570. }
  8571. };
  8572. SimulcastLogger.prototype.info = function (text) {
  8573. if (this.lvl > 1) {
  8574. console.info(text);
  8575. }
  8576. };
  8577. SimulcastLogger.prototype.fine = function (text) {
  8578. if (this.lvl > 2) {
  8579. console.log(text);
  8580. }
  8581. };
  8582. SimulcastLogger.prototype.error = function (text) {
  8583. console.error(text);
  8584. };
  8585. module.exports = SimulcastLogger;
  8586. },{}],40:[function(require,module,exports){
  8587. var SimulcastLogger = require("./SimulcastLogger");
  8588. var SimulcastUtils = require("./SimulcastUtils");
  8589. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  8590. function SimulcastReceiver() {
  8591. this.simulcastUtils = new SimulcastUtils();
  8592. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  8593. }
  8594. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  8595. SimulcastReceiver.prototype._remoteMaps = {
  8596. msid2Quality: {},
  8597. ssrc2Msid: {},
  8598. msid2ssrc: {},
  8599. receivingVideoStreams: {}
  8600. };
  8601. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  8602. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8603. };
  8604. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  8605. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  8606. };
  8607. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  8608. var sb;
  8609. this.logger.info('Ensuring x-google-conference flag...')
  8610. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8611. // TODO(gp) do that for the audio as well as suggested by fippo.
  8612. // Add the google conference flag
  8613. sb = this.simulcastUtils._getVideoSources(lines);
  8614. sb = ['a=x-google-flag:conference'].concat(sb);
  8615. this.simulcastUtils._replaceVideoSources(lines, sb);
  8616. }
  8617. };
  8618. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  8619. this._restoreRemoteVideoSources(sb);
  8620. };
  8621. /**
  8622. * Restores the simulcast groups of the remote description. In
  8623. * transformRemoteDescription we remove those in order for the set remote
  8624. * description to succeed. The focus needs the signal the groups to new
  8625. * participants.
  8626. *
  8627. * @param desc
  8628. * @returns {*}
  8629. */
  8630. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  8631. var sb;
  8632. if (!this.simulcastUtils.isValidDescription(desc)) {
  8633. return desc;
  8634. }
  8635. if (config.enableSimulcast) {
  8636. sb = desc.sdp.split('\r\n');
  8637. this._restoreSimulcastGroups(sb);
  8638. desc = new RTCSessionDescription({
  8639. type: desc.type,
  8640. sdp: sb.join('\r\n')
  8641. });
  8642. }
  8643. return desc;
  8644. };
  8645. SimulcastUtils.prototype._ensureOrder = function (lines) {
  8646. var videoSources, sb;
  8647. videoSources = this.parseMedia(lines, ['video'])[0];
  8648. sb = this._compileVideoSources(videoSources);
  8649. this._replaceVideoSources(lines, sb);
  8650. };
  8651. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  8652. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  8653. videoSource, quality;
  8654. // (re) initialize the remote maps.
  8655. this._remoteMaps.msid2Quality = {};
  8656. this._remoteMaps.ssrc2Msid = {};
  8657. this._remoteMaps.msid2ssrc = {};
  8658. var self = this;
  8659. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  8660. remoteVideoSources.groups.forEach(function (group) {
  8661. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  8662. quality = 0;
  8663. group.ssrcs.forEach(function (ssrc) {
  8664. videoSource = remoteVideoSources.sources[ssrc];
  8665. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  8666. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  8667. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  8668. });
  8669. }
  8670. });
  8671. }
  8672. };
  8673. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  8674. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  8675. };
  8676. /**
  8677. * Returns a stream with single video track, the one currently being
  8678. * received by this endpoint.
  8679. *
  8680. * @param stream the remote simulcast stream.
  8681. * @returns {webkitMediaStream}
  8682. */
  8683. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  8684. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  8685. var self = this;
  8686. if (config.enableSimulcast) {
  8687. stream.getVideoTracks().some(function (track) {
  8688. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  8689. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  8690. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  8691. if (msid == [stream.id, track.id].join(' ')) {
  8692. electedTrack = track;
  8693. return true;
  8694. }
  8695. });
  8696. });
  8697. if (!electedTrack) {
  8698. // we don't have an elected track, choose by initial quality.
  8699. tracks = stream.getVideoTracks();
  8700. for (i = 0; i < tracks.length; i++) {
  8701. msid = [stream.id, tracks[i].id].join(' ');
  8702. if (this._remoteMaps.msid2Quality[msid] === quality) {
  8703. electedTrack = tracks[i];
  8704. break;
  8705. }
  8706. }
  8707. // TODO(gp) if the initialQuality could not be satisfied, lower
  8708. // the requirement and try again.
  8709. }
  8710. }
  8711. return (electedTrack)
  8712. ? new webkitMediaStream([electedTrack])
  8713. : stream;
  8714. };
  8715. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  8716. var resource = Strophe.getResourceFromJid(jid);
  8717. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  8718. // If we haven't receiving a "changed" event yet, then we must be receiving
  8719. // low quality (that the sender always streams).
  8720. if(!ssrc)
  8721. {
  8722. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8723. var remoteStream = remoteStreamObject.getOriginalStream();
  8724. var tracks = remoteStream.getVideoTracks();
  8725. if (tracks) {
  8726. for (var k = 0; k < tracks.length; k++) {
  8727. var track = tracks[k];
  8728. var msid = [remoteStream.id, track.id].join(' ');
  8729. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  8730. var quality = this._remoteMaps.msid2Quality[msid];
  8731. if (quality == 0) {
  8732. ssrc = _ssrc;
  8733. }
  8734. }
  8735. }
  8736. }
  8737. return ssrc;
  8738. };
  8739. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  8740. {
  8741. var sid, electedStream;
  8742. var i, j, k;
  8743. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  8744. if(jid && APP.RTC.remoteStreams[jid])
  8745. {
  8746. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8747. var remoteStream = remoteStreamObject.getOriginalStream();
  8748. var tracks = remoteStream.getVideoTracks();
  8749. if (tracks) {
  8750. for (k = 0; k < tracks.length; k++) {
  8751. var track = tracks[k];
  8752. var msid = [remoteStream.id, track.id].join(' ');
  8753. var tmp = this._remoteMaps.msid2ssrc[msid];
  8754. if (tmp == ssrc) {
  8755. electedStream = new webkitMediaStream([track]);
  8756. sid = remoteStreamObject.sid;
  8757. // stream found, stop.
  8758. break;
  8759. }
  8760. }
  8761. }
  8762. }
  8763. else
  8764. {
  8765. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  8766. }
  8767. return {
  8768. sid: sid,
  8769. stream: electedStream
  8770. };
  8771. };
  8772. /**
  8773. * Gets the fully qualified msid (stream.id + track.id) associated to the
  8774. * SSRC.
  8775. *
  8776. * @param ssrc
  8777. * @returns {*}
  8778. */
  8779. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  8780. return this._remoteMaps.ssrc2Msid[ssrc];
  8781. };
  8782. /**
  8783. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  8784. * either gets confused and thinks this is an FID group or, if an FID group
  8785. * is already present, it fails to set the remote description.
  8786. *
  8787. * @param desc
  8788. * @returns {*}
  8789. */
  8790. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  8791. if (desc && desc.sdp) {
  8792. var sb = desc.sdp.split('\r\n');
  8793. this._updateRemoteMaps(sb);
  8794. this._cacheRemoteVideoSources(sb);
  8795. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  8796. // need the simulcast group in the _updateRemoteMaps() method.
  8797. this.simulcastUtils._removeSimulcastGroup(sb);
  8798. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  8799. // We don't need the goog conference flag if we're not doing
  8800. // simulcast.
  8801. this._ensureGoogConference(sb);
  8802. }
  8803. desc = new RTCSessionDescription({
  8804. type: desc.type,
  8805. sdp: sb.join('\r\n')
  8806. });
  8807. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  8808. }
  8809. return desc;
  8810. };
  8811. module.exports = SimulcastReceiver;
  8812. },{"../../service/RTC/MediaStreamTypes":87,"./SimulcastLogger":39,"./SimulcastUtils":42}],41:[function(require,module,exports){
  8813. var SimulcastLogger = require("./SimulcastLogger");
  8814. var SimulcastUtils = require("./SimulcastUtils");
  8815. function SimulcastSender() {
  8816. this.simulcastUtils = new SimulcastUtils();
  8817. this.logger = new SimulcastLogger('SimulcastSender', 1);
  8818. }
  8819. SimulcastSender.prototype.displayedLocalVideoStream = null;
  8820. SimulcastSender.prototype._generateGuid = (function () {
  8821. function s4() {
  8822. return Math.floor((1 + Math.random()) * 0x10000)
  8823. .toString(16)
  8824. .substring(1);
  8825. }
  8826. return function () {
  8827. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  8828. s4() + '-' + s4() + s4() + s4();
  8829. };
  8830. }());
  8831. // Returns a random integer between min (included) and max (excluded)
  8832. // Using Math.round() gives a non-uniform distribution!
  8833. SimulcastSender.prototype._generateRandomSSRC = function () {
  8834. var min = 0, max = 0xffffffff;
  8835. return Math.floor(Math.random() * (max - min)) + min;
  8836. };
  8837. SimulcastSender.prototype.getLocalVideoStream = function () {
  8838. return (this.displayedLocalVideoStream != null)
  8839. ? this.displayedLocalVideoStream
  8840. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  8841. : APP.RTC.localVideo.getOriginalStream();
  8842. };
  8843. function NativeSimulcastSender() {
  8844. SimulcastSender.call(this); // call the super constructor.
  8845. }
  8846. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8847. NativeSimulcastSender.prototype._localExplosionMap = {};
  8848. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  8849. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  8850. NativeSimulcastSender.prototype.reset = function () {
  8851. this._localExplosionMap = {};
  8852. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  8853. };
  8854. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  8855. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8856. };
  8857. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  8858. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  8859. };
  8860. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  8861. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  8862. this.logger.info('Appending simulcast group...');
  8863. // Get the primary SSRC information.
  8864. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8865. // Start building the SIM SSRC group.
  8866. ssrcGroup = ['a=ssrc-group:SIM'];
  8867. // The video source buffer.
  8868. sb = [];
  8869. // Create the simulcast sub-streams.
  8870. for (i = 0; i < numOfSubs; i++) {
  8871. // TODO(gp) prevent SSRC collision.
  8872. simSSRC = this._generateRandomSSRC();
  8873. ssrcGroup.push(simSSRC);
  8874. if (videoSources.base) {
  8875. sb.splice.apply(sb, [sb.length, 0].concat(
  8876. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  8877. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  8878. ));
  8879. }
  8880. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  8881. }
  8882. // Add the group sim layers.
  8883. sb.splice(0, 0, ssrcGroup.join(' '))
  8884. this.simulcastUtils._replaceVideoSources(lines, sb);
  8885. };
  8886. // Does the actual patching.
  8887. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  8888. this.logger.info('Ensuring simulcast group...');
  8889. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8890. this._appendSimulcastGroup(lines);
  8891. this._cacheLocalVideoSources(lines);
  8892. } else {
  8893. // verify that the ssrcs participating in the SIM group are present
  8894. // in the SDP (needed for presence).
  8895. this._restoreLocalVideoSources(lines);
  8896. }
  8897. };
  8898. /**
  8899. * Produces a single stream with multiple tracks for local video sources.
  8900. *
  8901. * @param lines
  8902. * @private
  8903. */
  8904. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  8905. var sb, msid, sid, tid, videoSources, self;
  8906. this.logger.info('Exploding local video sources...');
  8907. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8908. self = this;
  8909. if (videoSources.groups && videoSources.groups.length !== 0) {
  8910. videoSources.groups.forEach(function (group) {
  8911. if (group.semantics === 'SIM') {
  8912. group.ssrcs.forEach(function (ssrc) {
  8913. // Get the msid for this ssrc..
  8914. if (self._localExplosionMap[ssrc]) {
  8915. // .. either from the explosion map..
  8916. msid = self._localExplosionMap[ssrc];
  8917. } else {
  8918. // .. or generate a new one (msid).
  8919. sid = videoSources.sources[ssrc].msid
  8920. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  8921. tid = self._generateGuid();
  8922. msid = [sid, tid].join(' ');
  8923. self._localExplosionMap[ssrc] = msid;
  8924. }
  8925. // Assign it to the source object.
  8926. videoSources.sources[ssrc].msid = msid;
  8927. // TODO(gp) Change the msid of associated sources.
  8928. });
  8929. }
  8930. });
  8931. }
  8932. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8933. this.simulcastUtils._replaceVideoSources(lines, sb);
  8934. };
  8935. /**
  8936. * GUM for simulcast.
  8937. *
  8938. * @param constraints
  8939. * @param success
  8940. * @param err
  8941. */
  8942. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8943. // There's nothing special to do for native simulcast, so just do a normal GUM.
  8944. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8945. success(hqStream);
  8946. }, err);
  8947. };
  8948. /**
  8949. * Prepares the local description for public usage (i.e. to be signaled
  8950. * through Jingle to the focus).
  8951. *
  8952. * @param desc
  8953. * @returns {RTCSessionDescription}
  8954. */
  8955. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8956. var sb;
  8957. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8958. return desc;
  8959. }
  8960. sb = desc.sdp.split('\r\n');
  8961. this._explodeSimulcastSenderSources(sb);
  8962. desc = new RTCSessionDescription({
  8963. type: desc.type,
  8964. sdp: sb.join('\r\n')
  8965. });
  8966. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  8967. return desc;
  8968. };
  8969. /**
  8970. * Ensures that the simulcast group is present in the answer, _if_ native
  8971. * simulcast is enabled,
  8972. *
  8973. * @param desc
  8974. * @returns {*}
  8975. */
  8976. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  8977. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8978. return desc;
  8979. }
  8980. var sb = desc.sdp.split('\r\n');
  8981. // Even if we have enabled native simulcasting previously
  8982. // (with a call to SLD with an appropriate SDP, for example),
  8983. // createAnswer seems to consistently generate incomplete SDP
  8984. // with missing SSRCS.
  8985. //
  8986. // So, subsequent calls to SLD will have missing SSRCS and presence
  8987. // won't have the complete list of SRCs.
  8988. this._ensureSimulcastGroup(sb);
  8989. desc = new RTCSessionDescription({
  8990. type: desc.type,
  8991. sdp: sb.join('\r\n')
  8992. });
  8993. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  8994. return desc;
  8995. };
  8996. /**
  8997. *
  8998. *
  8999. * @param desc
  9000. * @returns {*}
  9001. */
  9002. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9003. return desc;
  9004. };
  9005. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9006. // Nothing to do here, native simulcast does that auto-magically.
  9007. };
  9008. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  9009. function SimpleSimulcastSender() {
  9010. SimulcastSender.call(this);
  9011. }
  9012. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9013. SimpleSimulcastSender.prototype.localStream = null;
  9014. SimpleSimulcastSender.prototype._localMaps = {
  9015. msids: [],
  9016. msid2ssrc: {}
  9017. };
  9018. /**
  9019. * Groups local video sources together in the ssrc-group:SIM group.
  9020. *
  9021. * @param lines
  9022. * @private
  9023. */
  9024. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  9025. var sb, videoSources, ssrcs = [], ssrc;
  9026. this.logger.info('Grouping local video sources...');
  9027. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  9028. for (ssrc in videoSources.sources) {
  9029. // jitsi-meet destroys/creates streams at various places causing
  9030. // the original local stream ids to change. The only thing that
  9031. // remains unchanged is the trackid.
  9032. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  9033. }
  9034. var self = this;
  9035. // TODO(gp) add only "free" sources.
  9036. this._localMaps.msids.forEach(function (msid) {
  9037. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  9038. });
  9039. if (!videoSources.groups) {
  9040. videoSources.groups = [];
  9041. }
  9042. videoSources.groups.push({
  9043. 'semantics': 'SIM',
  9044. 'ssrcs': ssrcs
  9045. });
  9046. sb = this.simulcastUtils._compileVideoSources(videoSources);
  9047. this.simulcastUtils._replaceVideoSources(lines, sb);
  9048. };
  9049. /**
  9050. * GUM for simulcast.
  9051. *
  9052. * @param constraints
  9053. * @param success
  9054. * @param err
  9055. */
  9056. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9057. // TODO(gp) what if we request a resolution not supported by the hardware?
  9058. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  9059. var lqConstraints = {
  9060. audio: false,
  9061. video: {
  9062. mandatory: {
  9063. maxWidth: 320,
  9064. maxHeight: 180,
  9065. maxFrameRate: 15
  9066. }
  9067. }
  9068. };
  9069. this.logger.info('HQ constraints: ', constraints);
  9070. this.logger.info('LQ constraints: ', lqConstraints);
  9071. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  9072. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  9073. // reason appears to be that Chrome only acquires the cam once and
  9074. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  9075. var self = this;
  9076. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9077. self.localStream = hqStream;
  9078. // reset local maps.
  9079. self._localMaps.msids = [];
  9080. self._localMaps.msid2ssrc = {};
  9081. // add hq trackid to local map
  9082. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  9083. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  9084. self.displayedLocalVideoStream = lqStream;
  9085. // NOTE(gp) The specification says Array.forEach() will visit
  9086. // the array elements in numeric order, and that it doesn't
  9087. // visit elements that don't exist.
  9088. // add lq trackid to local map
  9089. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  9090. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  9091. success(self.localStream);
  9092. }, err);
  9093. }, err);
  9094. };
  9095. /**
  9096. * Prepares the local description for public usage (i.e. to be signaled
  9097. * through Jingle to the focus).
  9098. *
  9099. * @param desc
  9100. * @returns {RTCSessionDescription}
  9101. */
  9102. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9103. var sb;
  9104. if (!this.simulcastUtils.isValidDescription(desc)) {
  9105. return desc;
  9106. }
  9107. sb = desc.sdp.split('\r\n');
  9108. this._groupLocalVideoSources(sb);
  9109. desc = new RTCSessionDescription({
  9110. type: desc.type,
  9111. sdp: sb.join('\r\n')
  9112. });
  9113. this.logger.fine('Grouped local video sources');
  9114. this.logger.fine(desc.sdp);
  9115. return desc;
  9116. };
  9117. /**
  9118. * Ensures that the simulcast group is present in the answer, _if_ native
  9119. * simulcast is enabled,
  9120. *
  9121. * @param desc
  9122. * @returns {*}
  9123. */
  9124. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  9125. return desc;
  9126. };
  9127. /**
  9128. *
  9129. *
  9130. * @param desc
  9131. * @returns {*}
  9132. */
  9133. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9134. var sb = desc.sdp.split('\r\n');
  9135. this.simulcastUtils._removeSimulcastGroup(sb);
  9136. desc = new RTCSessionDescription({
  9137. type: desc.type,
  9138. sdp: sb.join('\r\n')
  9139. });
  9140. this.logger.fine('Transformed local description');
  9141. this.logger.fine(desc.sdp);
  9142. return desc;
  9143. };
  9144. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9145. var trackid;
  9146. var self = this;
  9147. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  9148. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  9149. // Search for the track id that corresponds to the ssrc
  9150. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  9151. trackid = tid;
  9152. return true;
  9153. }
  9154. }) && self.localStream.getVideoTracks().some(function (track) {
  9155. // Start/stop the track that corresponds to the track id
  9156. if (track.id === trackid) {
  9157. track.enabled = enabled;
  9158. return true;
  9159. }
  9160. })) {
  9161. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  9162. $(document).trigger(enabled
  9163. ? 'simulcastlayerstarted'
  9164. : 'simulcastlayerstopped');
  9165. } else {
  9166. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  9167. }
  9168. };
  9169. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  9170. function NoSimulcastSender() {
  9171. SimulcastSender.call(this);
  9172. }
  9173. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9174. /**
  9175. * GUM for simulcast.
  9176. *
  9177. * @param constraints
  9178. * @param success
  9179. * @param err
  9180. */
  9181. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9182. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9183. success(hqStream);
  9184. }, err);
  9185. };
  9186. /**
  9187. * Prepares the local description for public usage (i.e. to be signaled
  9188. * through Jingle to the focus).
  9189. *
  9190. * @param desc
  9191. * @returns {RTCSessionDescription}
  9192. */
  9193. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9194. return desc;
  9195. };
  9196. /**
  9197. * Ensures that the simulcast group is present in the answer, _if_ native
  9198. * simulcast is enabled,
  9199. *
  9200. * @param desc
  9201. * @returns {*}
  9202. */
  9203. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  9204. return desc;
  9205. };
  9206. /**
  9207. *
  9208. *
  9209. * @param desc
  9210. * @returns {*}
  9211. */
  9212. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9213. return desc;
  9214. };
  9215. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9216. };
  9217. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  9218. module.exports = {
  9219. "native": NativeSimulcastSender,
  9220. "no": NoSimulcastSender
  9221. }
  9222. },{"./SimulcastLogger":39,"./SimulcastUtils":42}],42:[function(require,module,exports){
  9223. var SimulcastLogger = require("./SimulcastLogger");
  9224. /**
  9225. *
  9226. * @constructor
  9227. */
  9228. function SimulcastUtils() {
  9229. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  9230. }
  9231. /**
  9232. *
  9233. * @type {{}}
  9234. * @private
  9235. */
  9236. SimulcastUtils.prototype._emptyCompoundIndex = {};
  9237. /**
  9238. *
  9239. * @param lines
  9240. * @param videoSources
  9241. * @private
  9242. */
  9243. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  9244. var i, inVideo = false, index = -1, howMany = 0;
  9245. this.logger.info('Replacing video sources...');
  9246. for (i = 0; i < lines.length; i++) {
  9247. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9248. // Out of video.
  9249. break;
  9250. }
  9251. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9252. // In video.
  9253. inVideo = true;
  9254. }
  9255. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  9256. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  9257. if (index === -1) {
  9258. index = i;
  9259. }
  9260. howMany++;
  9261. }
  9262. }
  9263. // efficiency baby ;)
  9264. lines.splice.apply(lines,
  9265. [index, howMany].concat(videoSources));
  9266. };
  9267. SimulcastUtils.prototype.isValidDescription = function (desc)
  9268. {
  9269. return desc && desc != null
  9270. && desc.type && desc.type != ''
  9271. && desc.sdp && desc.sdp != '';
  9272. };
  9273. SimulcastUtils.prototype._getVideoSources = function (lines) {
  9274. var i, inVideo = false, sb = [];
  9275. this.logger.info('Getting video sources...');
  9276. for (i = 0; i < lines.length; i++) {
  9277. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9278. // Out of video.
  9279. break;
  9280. }
  9281. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9282. // In video.
  9283. inVideo = true;
  9284. }
  9285. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9286. // In SSRC.
  9287. sb.push(lines[i]);
  9288. }
  9289. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9290. sb.push(lines[i]);
  9291. }
  9292. }
  9293. return sb;
  9294. };
  9295. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  9296. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  9297. ssrc_attribute, group, semantics, skip = true;
  9298. this.logger.info('Parsing media sources...');
  9299. for (i = 0; i < lines.length; i++) {
  9300. if (lines[i].substring(0, 'm='.length) === 'm=') {
  9301. type = lines[i]
  9302. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  9303. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  9304. if (!skip) {
  9305. cur_media = {
  9306. 'type': type,
  9307. 'sources': {},
  9308. 'groups': []
  9309. };
  9310. res.push(cur_media);
  9311. }
  9312. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9313. idx = lines[i].indexOf(' ');
  9314. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  9315. if (cur_media.sources[ssrc] === undefined) {
  9316. cur_ssrc = {'ssrc': ssrc};
  9317. cur_media.sources[ssrc] = cur_ssrc;
  9318. }
  9319. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  9320. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  9321. if (cur_media.base === undefined) {
  9322. cur_media.base = cur_ssrc;
  9323. }
  9324. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9325. idx = lines[i].indexOf(' ');
  9326. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  9327. ssrcs = lines[i].substr(idx).trim().split(' ');
  9328. group = {
  9329. 'semantics': semantics,
  9330. 'ssrcs': ssrcs
  9331. };
  9332. cur_media.groups.push(group);
  9333. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  9334. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  9335. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  9336. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  9337. cur_media.direction = lines[i].substring('a='.length);
  9338. }
  9339. }
  9340. return res;
  9341. };
  9342. /**
  9343. * The _indexOfArray() method returns the first a CompoundIndex at which a
  9344. * given element can be found in the array, or _emptyCompoundIndex if it is
  9345. * not present.
  9346. *
  9347. * Example:
  9348. *
  9349. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  9350. *
  9351. * returns {row: 2, column: 14}
  9352. *
  9353. * @param needle
  9354. * @param haystack
  9355. * @param start
  9356. * @returns {}
  9357. * @private
  9358. */
  9359. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  9360. var length = haystack.length, idx, i;
  9361. if (!start) {
  9362. start = 0;
  9363. }
  9364. for (i = start; i < length; i++) {
  9365. idx = haystack[i].indexOf(needle);
  9366. if (idx !== -1) {
  9367. return {row: i, column: idx};
  9368. }
  9369. }
  9370. return this._emptyCompoundIndex;
  9371. };
  9372. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  9373. var i;
  9374. for (i = lines.length - 1; i >= 0; i--) {
  9375. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  9376. lines.splice(i, 1);
  9377. }
  9378. }
  9379. };
  9380. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  9381. var sb = [], ssrc, addedSSRCs = [];
  9382. this.logger.info('Compiling video sources...');
  9383. // Add the groups
  9384. if (videoSources.groups && videoSources.groups.length !== 0) {
  9385. videoSources.groups.forEach(function (group) {
  9386. if (group.ssrcs && group.ssrcs.length !== 0) {
  9387. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  9388. // if (group.semantics !== 'SIM') {
  9389. group.ssrcs.forEach(function (ssrc) {
  9390. addedSSRCs.push(ssrc);
  9391. sb.splice.apply(sb, [sb.length, 0].concat([
  9392. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9393. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9394. });
  9395. //}
  9396. }
  9397. });
  9398. }
  9399. // Then add any free sources.
  9400. if (videoSources.sources) {
  9401. for (ssrc in videoSources.sources) {
  9402. if (addedSSRCs.indexOf(ssrc) === -1) {
  9403. sb.splice.apply(sb, [sb.length, 0].concat([
  9404. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9405. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9406. }
  9407. }
  9408. }
  9409. return sb;
  9410. };
  9411. module.exports = SimulcastUtils;
  9412. },{"./SimulcastLogger":39}],43:[function(require,module,exports){
  9413. /*jslint plusplus: true */
  9414. /*jslint nomen: true*/
  9415. var SimulcastSender = require("./SimulcastSender");
  9416. var NoSimulcastSender = SimulcastSender["no"];
  9417. var NativeSimulcastSender = SimulcastSender["native"];
  9418. var SimulcastReceiver = require("./SimulcastReceiver");
  9419. var SimulcastUtils = require("./SimulcastUtils");
  9420. var RTCEvents = require("../../service/RTC/RTCEvents");
  9421. /**
  9422. *
  9423. * @constructor
  9424. */
  9425. function SimulcastManager() {
  9426. // Create the simulcast utilities.
  9427. this.simulcastUtils = new SimulcastUtils();
  9428. // Create remote simulcast.
  9429. this.simulcastReceiver = new SimulcastReceiver();
  9430. // Initialize local simulcast.
  9431. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  9432. // account constraints.
  9433. if (!config.enableSimulcast) {
  9434. this.simulcastSender = new NoSimulcastSender();
  9435. } else {
  9436. var isChromium = window.chrome,
  9437. vendorName = window.navigator.vendor;
  9438. if(isChromium !== null && isChromium !== undefined
  9439. /* skip opera */
  9440. && vendorName === "Google Inc."
  9441. /* skip Chromium as suggested by fippo */
  9442. && !window.navigator.appVersion.match(/Chromium\//) ) {
  9443. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  9444. if (ver > 37) {
  9445. this.simulcastSender = new NativeSimulcastSender();
  9446. } else {
  9447. this.simulcastSender = new NoSimulcastSender();
  9448. }
  9449. } else {
  9450. this.simulcastSender = new NoSimulcastSender();
  9451. }
  9452. }
  9453. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  9454. function (endpointSimulcastLayers) {
  9455. endpointSimulcastLayers.forEach(function (esl) {
  9456. var ssrc = esl.simulcastLayer.primarySSRC;
  9457. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  9458. });
  9459. });
  9460. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  9461. var ssrc = simulcastLayer.primarySSRC;
  9462. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  9463. });
  9464. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  9465. var ssrc = simulcastLayer.primarySSRC;
  9466. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  9467. });
  9468. }
  9469. /**
  9470. * Restores the simulcast groups of the remote description. In
  9471. * transformRemoteDescription we remove those in order for the set remote
  9472. * description to succeed. The focus needs the signal the groups to new
  9473. * participants.
  9474. *
  9475. * @param desc
  9476. * @returns {*}
  9477. */
  9478. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  9479. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  9480. };
  9481. /**
  9482. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9483. * either gets confused and thinks this is an FID group or, if an FID group
  9484. * is already present, it fails to set the remote description.
  9485. *
  9486. * @param desc
  9487. * @returns {*}
  9488. */
  9489. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  9490. return this.simulcastReceiver.transformRemoteDescription(desc);
  9491. };
  9492. /**
  9493. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9494. * SSRC.
  9495. *
  9496. * @param ssrc
  9497. * @returns {*}
  9498. */
  9499. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9500. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  9501. };
  9502. /**
  9503. * Returns a stream with single video track, the one currently being
  9504. * received by this endpoint.
  9505. *
  9506. * @param stream the remote simulcast stream.
  9507. * @returns {webkitMediaStream}
  9508. */
  9509. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  9510. return this.simulcastReceiver.getReceivingVideoStream(stream);
  9511. };
  9512. /**
  9513. *
  9514. *
  9515. * @param desc
  9516. * @returns {*}
  9517. */
  9518. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  9519. return this.simulcastSender.transformLocalDescription(desc);
  9520. };
  9521. /**
  9522. *
  9523. * @returns {*}
  9524. */
  9525. SimulcastManager.prototype.getLocalVideoStream = function() {
  9526. return this.simulcastSender.getLocalVideoStream();
  9527. };
  9528. /**
  9529. * GUM for simulcast.
  9530. *
  9531. * @param constraints
  9532. * @param success
  9533. * @param err
  9534. */
  9535. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  9536. this.simulcastSender.getUserMedia(constraints, success, err);
  9537. };
  9538. /**
  9539. * Prepares the local description for public usage (i.e. to be signaled
  9540. * through Jingle to the focus).
  9541. *
  9542. * @param desc
  9543. * @returns {RTCSessionDescription}
  9544. */
  9545. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  9546. return this.simulcastSender.reverseTransformLocalDescription(desc);
  9547. };
  9548. /**
  9549. * Ensures that the simulcast group is present in the answer, _if_ native
  9550. * simulcast is enabled,
  9551. *
  9552. * @param desc
  9553. * @returns {*}
  9554. */
  9555. SimulcastManager.prototype.transformAnswer = function (desc) {
  9556. return this.simulcastSender.transformAnswer(desc);
  9557. };
  9558. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  9559. return this.simulcastReceiver.getReceivingSSRC(jid);
  9560. };
  9561. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  9562. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  9563. };
  9564. /**
  9565. *
  9566. * @param lines
  9567. * @param mediatypes
  9568. * @returns {*}
  9569. */
  9570. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  9571. var sb = lines.sdp.split('\r\n');
  9572. return this.simulcastUtils.parseMedia(sb, mediatypes);
  9573. };
  9574. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  9575. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  9576. };
  9577. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  9578. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  9579. };
  9580. SimulcastManager.prototype.resetSender = function() {
  9581. if (typeof this.simulcastSender.reset === 'function'){
  9582. this.simulcastSender.reset();
  9583. }
  9584. };
  9585. var simulcast = new SimulcastManager();
  9586. module.exports = simulcast;
  9587. },{"../../service/RTC/RTCEvents":89,"./SimulcastReceiver":40,"./SimulcastSender":41,"./SimulcastUtils":42}],44:[function(require,module,exports){
  9588. /**
  9589. * Provides statistics for the local stream.
  9590. */
  9591. /**
  9592. * Size of the webaudio analizer buffer.
  9593. * @type {number}
  9594. */
  9595. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  9596. /**
  9597. * Value of the webaudio analizer smoothing time parameter.
  9598. * @type {number}
  9599. */
  9600. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  9601. /**
  9602. * Converts time domain data array to audio level.
  9603. * @param array the time domain data array.
  9604. * @returns {number} the audio level
  9605. */
  9606. function timeDomainDataToAudioLevel(samples) {
  9607. var maxVolume = 0;
  9608. var length = samples.length;
  9609. for (var i = 0; i < length; i++) {
  9610. if (maxVolume < samples[i])
  9611. maxVolume = samples[i];
  9612. }
  9613. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  9614. };
  9615. /**
  9616. * Animates audio level change
  9617. * @param newLevel the new audio level
  9618. * @param lastLevel the last audio level
  9619. * @returns {Number} the audio level to be set
  9620. */
  9621. function animateLevel(newLevel, lastLevel)
  9622. {
  9623. var value = 0;
  9624. var diff = lastLevel - newLevel;
  9625. if(diff > 0.2)
  9626. {
  9627. value = lastLevel - 0.2;
  9628. }
  9629. else if(diff < -0.4)
  9630. {
  9631. value = lastLevel + 0.4;
  9632. }
  9633. else
  9634. {
  9635. value = newLevel;
  9636. }
  9637. return parseFloat(value.toFixed(3));
  9638. }
  9639. /**
  9640. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  9641. *
  9642. * @param stream the local stream
  9643. * @param interval stats refresh interval given in ms.
  9644. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  9645. * update.
  9646. * @constructor
  9647. */
  9648. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  9649. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  9650. this.stream = stream;
  9651. this.intervalId = null;
  9652. this.intervalMilis = interval;
  9653. this.eventEmitter = eventEmitter;
  9654. this.audioLevel = 0;
  9655. this.statisticsService = statisticsService;
  9656. }
  9657. /**
  9658. * Starts the collecting the statistics.
  9659. */
  9660. LocalStatsCollector.prototype.start = function () {
  9661. if (config.disableAudioLevels || !window.AudioContext)
  9662. return;
  9663. var context = new AudioContext();
  9664. var analyser = context.createAnalyser();
  9665. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  9666. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  9667. var source = context.createMediaStreamSource(this.stream);
  9668. source.connect(analyser);
  9669. var self = this;
  9670. this.intervalId = setInterval(
  9671. function () {
  9672. var array = new Uint8Array(analyser.frequencyBinCount);
  9673. analyser.getByteTimeDomainData(array);
  9674. var audioLevel = timeDomainDataToAudioLevel(array);
  9675. if(audioLevel != self.audioLevel) {
  9676. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  9677. self.eventEmitter.emit(
  9678. "statistics.audioLevel",
  9679. self.statisticsService.LOCAL_JID,
  9680. self.audioLevel);
  9681. }
  9682. },
  9683. this.intervalMilis
  9684. );
  9685. };
  9686. /**
  9687. * Stops collecting the statistics.
  9688. */
  9689. LocalStatsCollector.prototype.stop = function () {
  9690. if (this.intervalId) {
  9691. clearInterval(this.intervalId);
  9692. this.intervalId = null;
  9693. }
  9694. };
  9695. module.exports = LocalStatsCollector;
  9696. },{}],45:[function(require,module,exports){
  9697. /* global ssrc2jid */
  9698. /* jshint -W117 */
  9699. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9700. /**
  9701. * Calculates packet lost percent using the number of lost packets and the
  9702. * number of all packet.
  9703. * @param lostPackets the number of lost packets
  9704. * @param totalPackets the number of all packets.
  9705. * @returns {number} packet loss percent
  9706. */
  9707. function calculatePacketLoss(lostPackets, totalPackets) {
  9708. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  9709. return 0;
  9710. return Math.round((lostPackets/totalPackets)*100);
  9711. }
  9712. function getStatValue(item, name) {
  9713. if(!keyMap[APP.RTC.getBrowserType()][name])
  9714. throw "The property isn't supported!";
  9715. var key = keyMap[APP.RTC.getBrowserType()][name];
  9716. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  9717. }
  9718. /**
  9719. * Peer statistics data holder.
  9720. * @constructor
  9721. */
  9722. function PeerStats()
  9723. {
  9724. this.ssrc2Loss = {};
  9725. this.ssrc2AudioLevel = {};
  9726. this.ssrc2bitrate = {};
  9727. this.ssrc2resolution = {};
  9728. }
  9729. /**
  9730. * The bandwidth
  9731. * @type {{}}
  9732. */
  9733. PeerStats.bandwidth = {};
  9734. /**
  9735. * The bit rate
  9736. * @type {{}}
  9737. */
  9738. PeerStats.bitrate = {};
  9739. /**
  9740. * The packet loss rate
  9741. * @type {{}}
  9742. */
  9743. PeerStats.packetLoss = null;
  9744. /**
  9745. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  9746. * represented by this instance.
  9747. * @param ssrc audio or video RTP stream SSRC.
  9748. * @param lossRate new packet loss rate value to be set.
  9749. */
  9750. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  9751. {
  9752. this.ssrc2Loss[ssrc] = lossRate;
  9753. };
  9754. /**
  9755. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  9756. * represented by this instance.
  9757. * @param ssrc audio or video RTP stream SSRC.
  9758. * @param resolution new resolution value to be set.
  9759. */
  9760. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  9761. {
  9762. if(resolution === null && this.ssrc2resolution[ssrc])
  9763. {
  9764. delete this.ssrc2resolution[ssrc];
  9765. }
  9766. else if(resolution !== null)
  9767. this.ssrc2resolution[ssrc] = resolution;
  9768. };
  9769. /**
  9770. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  9771. * represented by this instance.
  9772. * @param ssrc audio or video RTP stream SSRC.
  9773. * @param bitrate new bitrate value to be set.
  9774. */
  9775. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  9776. {
  9777. if(this.ssrc2bitrate[ssrc])
  9778. {
  9779. this.ssrc2bitrate[ssrc].download += bitrate.download;
  9780. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  9781. }
  9782. else {
  9783. this.ssrc2bitrate[ssrc] = bitrate;
  9784. }
  9785. };
  9786. /**
  9787. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  9788. * the stream which belongs to the peer represented by this instance.
  9789. * @param ssrc RTP stream SSRC for which current audio level value will be
  9790. * updated.
  9791. * @param audioLevel the new audio level value to be set. Value is truncated to
  9792. * fit the range from 0 to 1.
  9793. */
  9794. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  9795. {
  9796. // Range limit 0 - 1
  9797. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  9798. };
  9799. function formatAudioLevel(audioLevel) {
  9800. return Math.min(Math.max(audioLevel, 0), 1);
  9801. }
  9802. /**
  9803. * Array with the transport information.
  9804. * @type {Array}
  9805. */
  9806. PeerStats.transport = [];
  9807. /**
  9808. * <tt>StatsCollector</tt> registers for stats updates of given
  9809. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  9810. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  9811. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9812. * instance as an event source.
  9813. *
  9814. * @param peerconnection webRTC peer connection object.
  9815. * @param interval stats refresh interval given in ms.
  9816. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  9817. * called on stats update.
  9818. * @constructor
  9819. */
  9820. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  9821. {
  9822. this.peerconnection = peerconnection;
  9823. this.baselineAudioLevelsReport = null;
  9824. this.currentAudioLevelsReport = null;
  9825. this.currentStatsReport = null;
  9826. this.baselineStatsReport = null;
  9827. this.audioLevelsIntervalId = null;
  9828. this.eventEmitter = eventEmitter;
  9829. /**
  9830. * Gather PeerConnection stats once every this many milliseconds.
  9831. */
  9832. this.GATHER_INTERVAL = 15000;
  9833. /**
  9834. * Log stats via the focus once every this many milliseconds.
  9835. */
  9836. this.LOG_INTERVAL = 60000;
  9837. /**
  9838. * Gather stats and store them in this.statsToBeLogged.
  9839. */
  9840. this.gatherStatsIntervalId = null;
  9841. /**
  9842. * Send the stats already saved in this.statsToBeLogged to be logged via
  9843. * the focus.
  9844. */
  9845. this.logStatsIntervalId = null;
  9846. /**
  9847. * Stores the statistics which will be send to the focus to be logged.
  9848. */
  9849. this.statsToBeLogged =
  9850. {
  9851. timestamps: [],
  9852. stats: {}
  9853. };
  9854. // Updates stats interval
  9855. this.audioLevelsIntervalMilis = audioLevelsInterval;
  9856. this.statsIntervalId = null;
  9857. this.statsIntervalMilis = statsInterval;
  9858. // Map of jids to PeerStats
  9859. this.jid2stats = {};
  9860. }
  9861. module.exports = StatsCollector;
  9862. /**
  9863. * Stops stats updates.
  9864. */
  9865. StatsCollector.prototype.stop = function () {
  9866. if (this.audioLevelsIntervalId) {
  9867. clearInterval(this.audioLevelsIntervalId);
  9868. this.audioLevelsIntervalId = null;
  9869. }
  9870. if (this.statsIntervalId)
  9871. {
  9872. clearInterval(this.statsIntervalId);
  9873. this.statsIntervalId = null;
  9874. }
  9875. if(this.logStatsIntervalId)
  9876. {
  9877. clearInterval(this.logStatsIntervalId);
  9878. this.logStatsIntervalId = null;
  9879. }
  9880. if(this.gatherStatsIntervalId)
  9881. {
  9882. clearInterval(this.gatherStatsIntervalId);
  9883. this.gatherStatsIntervalId = null;
  9884. }
  9885. };
  9886. /**
  9887. * Callback passed to <tt>getStats</tt> method.
  9888. * @param error an error that occurred on <tt>getStats</tt> call.
  9889. */
  9890. StatsCollector.prototype.errorCallback = function (error)
  9891. {
  9892. console.error("Get stats error", error);
  9893. this.stop();
  9894. };
  9895. /**
  9896. * Starts stats updates.
  9897. */
  9898. StatsCollector.prototype.start = function ()
  9899. {
  9900. var self = this;
  9901. if(!config.disableAudioLevels) {
  9902. this.audioLevelsIntervalId = setInterval(
  9903. function () {
  9904. // Interval updates
  9905. self.peerconnection.getStats(
  9906. function (report) {
  9907. var results = null;
  9908. if (!report || !report.result ||
  9909. typeof report.result != 'function') {
  9910. results = report;
  9911. }
  9912. else {
  9913. results = report.result();
  9914. }
  9915. //console.error("Got interval report", results);
  9916. self.currentAudioLevelsReport = results;
  9917. self.processAudioLevelReport();
  9918. self.baselineAudioLevelsReport =
  9919. self.currentAudioLevelsReport;
  9920. },
  9921. self.errorCallback
  9922. );
  9923. },
  9924. self.audioLevelsIntervalMilis
  9925. );
  9926. }
  9927. if(!config.disableStats) {
  9928. this.statsIntervalId = setInterval(
  9929. function () {
  9930. // Interval updates
  9931. self.peerconnection.getStats(
  9932. function (report) {
  9933. var results = null;
  9934. if (!report || !report.result ||
  9935. typeof report.result != 'function') {
  9936. //firefox
  9937. results = report;
  9938. }
  9939. else {
  9940. //chrome
  9941. results = report.result();
  9942. }
  9943. //console.error("Got interval report", results);
  9944. self.currentStatsReport = results;
  9945. try {
  9946. self.processStatsReport();
  9947. }
  9948. catch (e) {
  9949. console.error("Unsupported key:" + e, e);
  9950. }
  9951. self.baselineStatsReport = self.currentStatsReport;
  9952. },
  9953. self.errorCallback
  9954. );
  9955. },
  9956. self.statsIntervalMilis
  9957. );
  9958. }
  9959. if (config.logStats) {
  9960. this.gatherStatsIntervalId = setInterval(
  9961. function () {
  9962. self.peerconnection.getStats(
  9963. function (report) {
  9964. self.addStatsToBeLogged(report.result());
  9965. },
  9966. function () {
  9967. }
  9968. );
  9969. },
  9970. this.GATHER_INTERVAL
  9971. );
  9972. this.logStatsIntervalId = setInterval(
  9973. function() { self.logStats(); },
  9974. this.LOG_INTERVAL);
  9975. }
  9976. };
  9977. /**
  9978. * Checks whether a certain record should be included in the logged statistics.
  9979. */
  9980. function acceptStat(reportId, reportType, statName) {
  9981. if (reportType == "googCandidatePair" && statName == "googChannelId")
  9982. return false;
  9983. if (reportType == "ssrc") {
  9984. if (statName == "googTrackId" ||
  9985. statName == "transportId" ||
  9986. statName == "ssrc")
  9987. return false;
  9988. }
  9989. return true;
  9990. }
  9991. /**
  9992. * Checks whether a certain record should be included in the logged statistics.
  9993. */
  9994. function acceptReport(id, type) {
  9995. if (id.substring(0, 15) == "googCertificate" ||
  9996. id.substring(0, 9) == "googTrack" ||
  9997. id.substring(0, 20) == "googLibjingleSession")
  9998. return false;
  9999. if (type == "googComponent")
  10000. return false;
  10001. return true;
  10002. }
  10003. /**
  10004. * Converts the stats to the format used for logging, and saves the data in
  10005. * this.statsToBeLogged.
  10006. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  10007. */
  10008. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  10009. var self = this;
  10010. var num_records = this.statsToBeLogged.timestamps.length;
  10011. this.statsToBeLogged.timestamps.push(new Date().getTime());
  10012. reports.map(function (report) {
  10013. if (!acceptReport(report.id, report.type))
  10014. return;
  10015. var stat = self.statsToBeLogged.stats[report.id];
  10016. if (!stat) {
  10017. stat = self.statsToBeLogged.stats[report.id] = {};
  10018. }
  10019. stat.type = report.type;
  10020. report.names().map(function (name) {
  10021. if (!acceptStat(report.id, report.type, name))
  10022. return;
  10023. var values = stat[name];
  10024. if (!values) {
  10025. values = stat[name] = [];
  10026. }
  10027. while (values.length < num_records) {
  10028. values.push(null);
  10029. }
  10030. values.push(report.stat(name));
  10031. });
  10032. });
  10033. };
  10034. StatsCollector.prototype.logStats = function () {
  10035. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  10036. return;
  10037. // Reset the stats
  10038. this.statsToBeLogged.stats = {};
  10039. this.statsToBeLogged.timestamps = [];
  10040. };
  10041. var keyMap = {};
  10042. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  10043. "ssrc": "ssrc",
  10044. "packetsReceived": "packetsReceived",
  10045. "packetsLost": "packetsLost",
  10046. "packetsSent": "packetsSent",
  10047. "bytesReceived": "bytesReceived",
  10048. "bytesSent": "bytesSent"
  10049. };
  10050. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  10051. "receiveBandwidth": "googAvailableReceiveBandwidth",
  10052. "sendBandwidth": "googAvailableSendBandwidth",
  10053. "remoteAddress": "googRemoteAddress",
  10054. "transportType": "googTransportType",
  10055. "localAddress": "googLocalAddress",
  10056. "activeConnection": "googActiveConnection",
  10057. "ssrc": "ssrc",
  10058. "packetsReceived": "packetsReceived",
  10059. "packetsSent": "packetsSent",
  10060. "packetsLost": "packetsLost",
  10061. "bytesReceived": "bytesReceived",
  10062. "bytesSent": "bytesSent",
  10063. "googFrameHeightReceived": "googFrameHeightReceived",
  10064. "googFrameWidthReceived": "googFrameWidthReceived",
  10065. "googFrameHeightSent": "googFrameHeightSent",
  10066. "googFrameWidthSent": "googFrameWidthSent",
  10067. "audioInputLevel": "audioInputLevel",
  10068. "audioOutputLevel": "audioOutputLevel"
  10069. };
  10070. /**
  10071. * Stats processing logic.
  10072. */
  10073. StatsCollector.prototype.processStatsReport = function () {
  10074. if (!this.baselineStatsReport) {
  10075. return;
  10076. }
  10077. for (var idx in this.currentStatsReport) {
  10078. var now = this.currentStatsReport[idx];
  10079. try {
  10080. if (getStatValue(now, 'receiveBandwidth') ||
  10081. getStatValue(now, 'sendBandwidth')) {
  10082. PeerStats.bandwidth = {
  10083. "download": Math.round(
  10084. (getStatValue(now, 'receiveBandwidth')) / 1000),
  10085. "upload": Math.round(
  10086. (getStatValue(now, 'sendBandwidth')) / 1000)
  10087. };
  10088. }
  10089. }
  10090. catch(e){/*not supported*/}
  10091. if(now.type == 'googCandidatePair')
  10092. {
  10093. var ip, type, localIP, active;
  10094. try {
  10095. ip = getStatValue(now, 'remoteAddress');
  10096. type = getStatValue(now, "transportType");
  10097. localIP = getStatValue(now, "localAddress");
  10098. active = getStatValue(now, "activeConnection");
  10099. }
  10100. catch(e){/*not supported*/}
  10101. if(!ip || !type || !localIP || active != "true")
  10102. continue;
  10103. var addressSaved = false;
  10104. for(var i = 0; i < PeerStats.transport.length; i++)
  10105. {
  10106. if(PeerStats.transport[i].ip == ip &&
  10107. PeerStats.transport[i].type == type &&
  10108. PeerStats.transport[i].localip == localIP)
  10109. {
  10110. addressSaved = true;
  10111. }
  10112. }
  10113. if(addressSaved)
  10114. continue;
  10115. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  10116. continue;
  10117. }
  10118. if(now.type == "candidatepair")
  10119. {
  10120. if(now.state == "succeeded")
  10121. continue;
  10122. var local = this.currentStatsReport[now.localCandidateId];
  10123. var remote = this.currentStatsReport[now.remoteCandidateId];
  10124. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  10125. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  10126. }
  10127. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  10128. now.type != "inboundrtp") {
  10129. continue;
  10130. }
  10131. var before = this.baselineStatsReport[idx];
  10132. if (!before) {
  10133. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10134. continue;
  10135. }
  10136. var ssrc = getStatValue(now, 'ssrc');
  10137. if(!ssrc)
  10138. continue;
  10139. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10140. if (!jid && (Date.now() - now.timestamp) < 3000) {
  10141. console.warn("No jid for ssrc: " + ssrc);
  10142. continue;
  10143. }
  10144. var jidStats = this.jid2stats[jid];
  10145. if (!jidStats) {
  10146. jidStats = new PeerStats();
  10147. this.jid2stats[jid] = jidStats;
  10148. }
  10149. var isDownloadStream = true;
  10150. var key = 'packetsReceived';
  10151. if (!getStatValue(now, key))
  10152. {
  10153. isDownloadStream = false;
  10154. key = 'packetsSent';
  10155. if (!getStatValue(now, key))
  10156. {
  10157. console.warn("No packetsReceived nor packetSent stat found");
  10158. continue;
  10159. }
  10160. }
  10161. var packetsNow = getStatValue(now, key);
  10162. if(!packetsNow || packetsNow < 0)
  10163. packetsNow = 0;
  10164. var packetsBefore = getStatValue(before, key);
  10165. if(!packetsBefore || packetsBefore < 0)
  10166. packetsBefore = 0;
  10167. var packetRate = packetsNow - packetsBefore;
  10168. if(!packetRate || packetRate < 0)
  10169. packetRate = 0;
  10170. var currentLoss = getStatValue(now, 'packetsLost');
  10171. if(!currentLoss || currentLoss < 0)
  10172. currentLoss = 0;
  10173. var previousLoss = getStatValue(before, 'packetsLost');
  10174. if(!previousLoss || previousLoss < 0)
  10175. previousLoss = 0;
  10176. var lossRate = currentLoss - previousLoss;
  10177. if(!lossRate || lossRate < 0)
  10178. lossRate = 0;
  10179. var packetsTotal = (packetRate + lossRate);
  10180. jidStats.setSsrcLoss(ssrc,
  10181. {"packetsTotal": packetsTotal,
  10182. "packetsLost": lossRate,
  10183. "isDownloadStream": isDownloadStream});
  10184. var bytesReceived = 0, bytesSent = 0;
  10185. if(getStatValue(now, "bytesReceived"))
  10186. {
  10187. bytesReceived = getStatValue(now, "bytesReceived") -
  10188. getStatValue(before, "bytesReceived");
  10189. }
  10190. if(getStatValue(now, "bytesSent"))
  10191. {
  10192. bytesSent = getStatValue(now, "bytesSent") -
  10193. getStatValue(before, "bytesSent");
  10194. }
  10195. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  10196. if(bytesReceived <= 0 || time <= 0)
  10197. {
  10198. bytesReceived = 0;
  10199. }
  10200. else
  10201. {
  10202. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  10203. }
  10204. if(bytesSent <= 0 || time <= 0)
  10205. {
  10206. bytesSent = 0;
  10207. }
  10208. else
  10209. {
  10210. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  10211. }
  10212. jidStats.setSsrcBitrate(ssrc, {
  10213. "download": bytesReceived,
  10214. "upload": bytesSent});
  10215. var resolution = {height: null, width: null};
  10216. try {
  10217. if (getStatValue(now, "googFrameHeightReceived") &&
  10218. getStatValue(now, "googFrameWidthReceived")) {
  10219. resolution.height = getStatValue(now, "googFrameHeightReceived");
  10220. resolution.width = getStatValue(now, "googFrameWidthReceived");
  10221. }
  10222. else if (getStatValue(now, "googFrameHeightSent") &&
  10223. getStatValue(now, "googFrameWidthSent")) {
  10224. resolution.height = getStatValue(now, "googFrameHeightSent");
  10225. resolution.width = getStatValue(now, "googFrameWidthSent");
  10226. }
  10227. }
  10228. catch(e){/*not supported*/}
  10229. if(resolution.height && resolution.width)
  10230. {
  10231. jidStats.setSsrcResolution(ssrc, resolution);
  10232. }
  10233. else
  10234. {
  10235. jidStats.setSsrcResolution(ssrc, null);
  10236. }
  10237. }
  10238. var self = this;
  10239. // Jid stats
  10240. var totalPackets = {download: 0, upload: 0};
  10241. var lostPackets = {download: 0, upload: 0};
  10242. var bitrateDownload = 0;
  10243. var bitrateUpload = 0;
  10244. var resolutions = {};
  10245. Object.keys(this.jid2stats).forEach(
  10246. function (jid)
  10247. {
  10248. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  10249. function (ssrc)
  10250. {
  10251. var type = "upload";
  10252. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  10253. type = "download";
  10254. totalPackets[type] +=
  10255. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  10256. lostPackets[type] +=
  10257. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  10258. }
  10259. );
  10260. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  10261. function (ssrc) {
  10262. bitrateDownload +=
  10263. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  10264. bitrateUpload +=
  10265. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  10266. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  10267. }
  10268. );
  10269. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  10270. }
  10271. );
  10272. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  10273. PeerStats.packetLoss = {
  10274. total:
  10275. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  10276. totalPackets.download + totalPackets.upload),
  10277. download:
  10278. calculatePacketLoss(lostPackets.download, totalPackets.download),
  10279. upload:
  10280. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  10281. };
  10282. this.eventEmitter.emit("statistics.connectionstats",
  10283. {
  10284. "bitrate": PeerStats.bitrate,
  10285. "packetLoss": PeerStats.packetLoss,
  10286. "bandwidth": PeerStats.bandwidth,
  10287. "resolution": resolutions,
  10288. "transport": PeerStats.transport
  10289. });
  10290. PeerStats.transport = [];
  10291. };
  10292. /**
  10293. * Stats processing logic.
  10294. */
  10295. StatsCollector.prototype.processAudioLevelReport = function ()
  10296. {
  10297. if (!this.baselineAudioLevelsReport)
  10298. {
  10299. return;
  10300. }
  10301. for (var idx in this.currentAudioLevelsReport)
  10302. {
  10303. var now = this.currentAudioLevelsReport[idx];
  10304. if (now.type != 'ssrc')
  10305. {
  10306. continue;
  10307. }
  10308. var before = this.baselineAudioLevelsReport[idx];
  10309. if (!before)
  10310. {
  10311. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10312. continue;
  10313. }
  10314. var ssrc = getStatValue(now, 'ssrc');
  10315. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10316. if (!jid && (Date.now() - now.timestamp) < 3000)
  10317. {
  10318. console.warn("No jid for ssrc: " + ssrc);
  10319. continue;
  10320. }
  10321. var jidStats = this.jid2stats[jid];
  10322. if (!jidStats)
  10323. {
  10324. jidStats = new PeerStats();
  10325. this.jid2stats[jid] = jidStats;
  10326. }
  10327. // Audio level
  10328. var audioLevel = null;
  10329. try {
  10330. audioLevel = getStatValue(now, 'audioInputLevel');
  10331. if (!audioLevel)
  10332. audioLevel = getStatValue(now, 'audioOutputLevel');
  10333. }
  10334. catch(e) {/*not supported*/
  10335. console.warn("Audio Levels are not available in the statistics.");
  10336. clearInterval(this.audioLevelsIntervalId);
  10337. return;
  10338. }
  10339. if (audioLevel)
  10340. {
  10341. // TODO: can't find specs about what this value really is,
  10342. // but it seems to vary between 0 and around 32k.
  10343. audioLevel = audioLevel / 32767;
  10344. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  10345. if(jid != APP.xmpp.myJid())
  10346. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  10347. }
  10348. }
  10349. };
  10350. },{"../../service/RTC/RTCBrowserType":88}],46:[function(require,module,exports){
  10351. /**
  10352. * Created by hristo on 8/4/14.
  10353. */
  10354. var LocalStats = require("./LocalStatsCollector.js");
  10355. var RTPStats = require("./RTPStatsCollector.js");
  10356. var EventEmitter = require("events");
  10357. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  10358. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10359. var eventEmitter = new EventEmitter();
  10360. var localStats = null;
  10361. var rtpStats = null;
  10362. function stopLocal()
  10363. {
  10364. if(localStats)
  10365. {
  10366. localStats.stop();
  10367. localStats = null;
  10368. }
  10369. }
  10370. function stopRemote()
  10371. {
  10372. if(rtpStats)
  10373. {
  10374. rtpStats.stop();
  10375. eventEmitter.emit("statistics.stop");
  10376. rtpStats = null;
  10377. }
  10378. }
  10379. function startRemoteStats (peerconnection) {
  10380. if(rtpStats)
  10381. {
  10382. rtpStats.stop();
  10383. rtpStats = null;
  10384. }
  10385. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  10386. rtpStats.start();
  10387. }
  10388. function onStreamCreated(stream)
  10389. {
  10390. if(stream.getOriginalStream().getAudioTracks().length === 0)
  10391. return;
  10392. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  10393. eventEmitter);
  10394. localStats.start();
  10395. }
  10396. function onDisposeConference(onUnload) {
  10397. stopRemote();
  10398. if(onUnload) {
  10399. stopLocal();
  10400. eventEmitter.removeAllListeners();
  10401. }
  10402. }
  10403. var statistics =
  10404. {
  10405. /**
  10406. * Indicates that this audio level is for local jid.
  10407. * @type {string}
  10408. */
  10409. LOCAL_JID: 'local',
  10410. addAudioLevelListener: function(listener)
  10411. {
  10412. eventEmitter.on("statistics.audioLevel", listener);
  10413. },
  10414. removeAudioLevelListener: function(listener)
  10415. {
  10416. eventEmitter.removeListener("statistics.audioLevel", listener);
  10417. },
  10418. addConnectionStatsListener: function(listener)
  10419. {
  10420. eventEmitter.on("statistics.connectionstats", listener);
  10421. },
  10422. removeConnectionStatsListener: function(listener)
  10423. {
  10424. eventEmitter.removeListener("statistics.connectionstats", listener);
  10425. },
  10426. addRemoteStatsStopListener: function(listener)
  10427. {
  10428. eventEmitter.on("statistics.stop", listener);
  10429. },
  10430. removeRemoteStatsStopListener: function(listener)
  10431. {
  10432. eventEmitter.removeListener("statistics.stop", listener);
  10433. },
  10434. stop: function () {
  10435. stopLocal();
  10436. stopRemote();
  10437. if(eventEmitter)
  10438. {
  10439. eventEmitter.removeAllListeners();
  10440. }
  10441. },
  10442. stopRemoteStatistics: function()
  10443. {
  10444. stopRemote();
  10445. },
  10446. start: function () {
  10447. APP.RTC.addStreamListener(onStreamCreated,
  10448. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10449. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10450. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10451. startRemoteStats(event.peerconnection);
  10452. });
  10453. }
  10454. };
  10455. module.exports = statistics;
  10456. },{"../../service/RTC/StreamEventTypes.js":91,"../../service/xmpp/XMPPEvents":97,"./LocalStatsCollector.js":44,"./RTPStatsCollector.js":45,"events":98}],47:[function(require,module,exports){
  10457. var i18n = require("i18next-client");
  10458. var languages = require("../../service/translation/languages");
  10459. var Settings = require("../settings/Settings");
  10460. var DEFAULT_LANG = languages.EN;
  10461. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10462. return value.replace("__app__", interfaceConfig.APP_NAME);
  10463. });
  10464. var defaultOptions = {
  10465. detectLngQS: "lang",
  10466. useCookie: false,
  10467. fallbackLng: DEFAULT_LANG,
  10468. load: "unspecific",
  10469. resGetPath: 'lang/__ns__-__lng__.json',
  10470. ns: {
  10471. namespaces: ['main', 'languages'],
  10472. defaultNs: 'main'
  10473. },
  10474. lngWhitelist : languages.getLanguages(),
  10475. fallbackOnNull: true,
  10476. fallbackOnEmpty: true,
  10477. useDataAttrOptions: true,
  10478. defaultValueFromContent: false,
  10479. app: interfaceConfig.APP_NAME,
  10480. getAsync: false,
  10481. defaultValueFromContent: false,
  10482. customLoad: function(lng, ns, options, done) {
  10483. var resPath = "lang/__ns__-__lng__.json";
  10484. if(lng === languages.EN)
  10485. resPath = "lang/__ns__.json";
  10486. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10487. i18n.functions.ajax({
  10488. url: url,
  10489. success: function(data, status, xhr) {
  10490. i18n.functions.log('loaded: ' + url);
  10491. done(null, data);
  10492. },
  10493. error : function(xhr, status, error) {
  10494. if ((status && status == 200) ||
  10495. (xhr && xhr.status && xhr.status == 200)) {
  10496. // file loaded but invalid json, stop waste time !
  10497. i18n.functions.error('There is a typo in: ' + url);
  10498. } else if ((status && status == 404) ||
  10499. (xhr && xhr.status && xhr.status == 404)) {
  10500. i18n.functions.log('Does not exist: ' + url);
  10501. } else {
  10502. var theStatus = status ? status :
  10503. ((xhr && xhr.status) ? xhr.status : null);
  10504. i18n.functions.log(theStatus + ' when loading ' + url);
  10505. }
  10506. done(error, {});
  10507. },
  10508. dataType: "json",
  10509. async : options.getAsync
  10510. });
  10511. }
  10512. // options for caching
  10513. // useLocalStorage: true,
  10514. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10515. };
  10516. function initCompleted(t)
  10517. {
  10518. $("[data-i18n]").i18n();
  10519. }
  10520. function checkForParameter() {
  10521. var query = window.location.search.substring(1);
  10522. var vars = query.split("&");
  10523. for (var i=0;i<vars.length;i++) {
  10524. var pair = vars[i].split("=");
  10525. if(pair[0] == "lang")
  10526. {
  10527. return pair[1];
  10528. }
  10529. }
  10530. return null;
  10531. }
  10532. module.exports = {
  10533. init: function (lang) {
  10534. var options = defaultOptions;
  10535. if(!lang)
  10536. {
  10537. lang = checkForParameter();
  10538. if(!lang)
  10539. {
  10540. var settings = Settings.getSettings();
  10541. if(settings)
  10542. lang = settings.language;
  10543. }
  10544. }
  10545. if(lang) {
  10546. options.lng = lang;
  10547. }
  10548. i18n.init(options, initCompleted);
  10549. },
  10550. translateString: function (key, options) {
  10551. return i18n.t(key, options);
  10552. },
  10553. setLanguage: function (lang) {
  10554. if(!lang)
  10555. lang = DEFAULT_LANG;
  10556. i18n.setLng(lang, defaultOptions, initCompleted);
  10557. },
  10558. getCurrentLanguage: function () {
  10559. return i18n.lng();
  10560. },
  10561. translateElement: function (selector) {
  10562. selector.i18n();
  10563. },
  10564. generateTranslatonHTML: function (key, options) {
  10565. var str = "<span data-i18n=\"" + key + "\"";
  10566. if(options)
  10567. {
  10568. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10569. }
  10570. str += ">";
  10571. str += this.translateString(key, options);
  10572. str += "</span>";
  10573. return str;
  10574. }
  10575. };
  10576. },{"../../service/translation/languages":96,"../settings/Settings":38,"i18next-client":62}],48:[function(require,module,exports){
  10577. /* jshint -W117 */
  10578. var TraceablePeerConnection = require("./TraceablePeerConnection");
  10579. var SDPDiffer = require("./SDPDiffer");
  10580. var SDPUtil = require("./SDPUtil");
  10581. var SDP = require("./SDP");
  10582. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10583. // Jingle stuff
  10584. function JingleSession(me, sid, connection, service) {
  10585. this.me = me;
  10586. this.sid = sid;
  10587. this.connection = connection;
  10588. this.initiator = null;
  10589. this.responder = null;
  10590. this.isInitiator = null;
  10591. this.peerjid = null;
  10592. this.state = null;
  10593. this.localSDP = null;
  10594. this.remoteSDP = null;
  10595. this.relayedStreams = [];
  10596. this.startTime = null;
  10597. this.stopTime = null;
  10598. this.media_constraints = null;
  10599. this.pc_constraints = null;
  10600. this.ice_config = {};
  10601. this.drip_container = [];
  10602. this.service = service;
  10603. this.usetrickle = true;
  10604. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  10605. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  10606. this.hadstuncandidate = false;
  10607. this.hadturncandidate = false;
  10608. this.lasticecandidate = false;
  10609. this.statsinterval = null;
  10610. this.reason = null;
  10611. this.addssrc = [];
  10612. this.removessrc = [];
  10613. this.pendingop = null;
  10614. this.switchstreams = false;
  10615. this.wait = true;
  10616. this.localStreamsSSRC = null;
  10617. /**
  10618. * The indicator which determines whether the (local) video has been muted
  10619. * in response to a user command in contrast to an automatic decision made
  10620. * by the application logic.
  10621. */
  10622. this.videoMuteByUser = false;
  10623. }
  10624. //TODO: this array must be removed when firefox implement multistream support
  10625. JingleSession.notReceivedSSRCs = [];
  10626. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  10627. var self = this;
  10628. if (this.state !== null) {
  10629. console.error('attempt to initiate on session ' + this.sid +
  10630. 'in state ' + this.state);
  10631. return;
  10632. }
  10633. this.isInitiator = isInitiator;
  10634. this.state = 'pending';
  10635. this.initiator = isInitiator ? this.me : peerjid;
  10636. this.responder = !isInitiator ? this.me : peerjid;
  10637. this.peerjid = peerjid;
  10638. this.hadstuncandidate = false;
  10639. this.hadturncandidate = false;
  10640. this.lasticecandidate = false;
  10641. this.peerconnection
  10642. = new TraceablePeerConnection(
  10643. this.connection.jingle.ice_config,
  10644. this.connection.jingle.pc_constraints );
  10645. this.peerconnection.onicecandidate = function (event) {
  10646. self.sendIceCandidate(event.candidate);
  10647. };
  10648. this.peerconnection.onaddstream = function (event) {
  10649. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  10650. self.remoteStreamAdded(event);
  10651. };
  10652. this.peerconnection.onremovestream = function (event) {
  10653. // Remove the stream from remoteStreams
  10654. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  10655. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  10656. };
  10657. this.peerconnection.onsignalingstatechange = function (event) {
  10658. if (!(self && self.peerconnection)) return;
  10659. };
  10660. this.peerconnection.oniceconnectionstatechange = function (event) {
  10661. if (!(self && self.peerconnection)) return;
  10662. switch (self.peerconnection.iceConnectionState) {
  10663. case 'connected':
  10664. this.startTime = new Date();
  10665. break;
  10666. case 'disconnected':
  10667. this.stopTime = new Date();
  10668. break;
  10669. }
  10670. onIceConnectionStateChange(self.sid, self);
  10671. };
  10672. // add any local and relayed stream
  10673. APP.RTC.localStreams.forEach(function(stream) {
  10674. self.peerconnection.addStream(stream.getOriginalStream());
  10675. });
  10676. this.relayedStreams.forEach(function(stream) {
  10677. self.peerconnection.addStream(stream);
  10678. });
  10679. };
  10680. function onIceConnectionStateChange(sid, session) {
  10681. switch (session.peerconnection.iceConnectionState) {
  10682. case 'checking':
  10683. session.timeChecking = (new Date()).getTime();
  10684. session.firstconnect = true;
  10685. break;
  10686. case 'completed': // on caller side
  10687. case 'connected':
  10688. if (session.firstconnect) {
  10689. session.firstconnect = false;
  10690. var metadata = {};
  10691. metadata.setupTime
  10692. = (new Date()).getTime() - session.timeChecking;
  10693. session.peerconnection.getStats(function (res) {
  10694. if(res && res.result) {
  10695. res.result().forEach(function (report) {
  10696. if (report.type == 'googCandidatePair' &&
  10697. report.stat('googActiveConnection') == 'true') {
  10698. metadata.localCandidateType
  10699. = report.stat('googLocalCandidateType');
  10700. metadata.remoteCandidateType
  10701. = report.stat('googRemoteCandidateType');
  10702. // log pair as well so we can get nice pie
  10703. // charts
  10704. metadata.candidatePair
  10705. = report.stat('googLocalCandidateType') +
  10706. ';' +
  10707. report.stat('googRemoteCandidateType');
  10708. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  10709. {
  10710. metadata.ipv6 = true;
  10711. }
  10712. }
  10713. });
  10714. }
  10715. });
  10716. }
  10717. break;
  10718. }
  10719. }
  10720. JingleSession.prototype.accept = function () {
  10721. var self = this;
  10722. this.state = 'active';
  10723. var pranswer = this.peerconnection.localDescription;
  10724. if (!pranswer || pranswer.type != 'pranswer') {
  10725. return;
  10726. }
  10727. console.log('going from pranswer to answer');
  10728. if (this.usetrickle) {
  10729. // remove candidates already sent from session-accept
  10730. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  10731. for (var i = 0; i < lines.length; i++) {
  10732. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  10733. }
  10734. }
  10735. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  10736. // FIXME: change any inactive to sendrecv or whatever they were originally
  10737. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  10738. }
  10739. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  10740. var prsdp = new SDP(pranswer.sdp);
  10741. var accept = $iq({to: this.peerjid,
  10742. type: 'set'})
  10743. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10744. action: 'session-accept',
  10745. initiator: this.initiator,
  10746. responder: this.responder,
  10747. sid: this.sid });
  10748. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10749. var sdp = this.peerconnection.localDescription.sdp;
  10750. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  10751. // FIXME: change any inactive to sendrecv or whatever they were originally
  10752. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  10753. }
  10754. var self = this;
  10755. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  10756. function () {
  10757. //console.log('setLocalDescription success');
  10758. self.setLocalDescription();
  10759. self.connection.sendIQ(accept,
  10760. function () {
  10761. var ack = {};
  10762. ack.source = 'answer';
  10763. $(document).trigger('ack.jingle', [self.sid, ack]);
  10764. },
  10765. function (stanza) {
  10766. var error = ($(stanza).find('error').length) ? {
  10767. code: $(stanza).find('error').attr('code'),
  10768. reason: $(stanza).find('error :first')[0].tagName
  10769. }:{};
  10770. error.source = 'answer';
  10771. JingleSession.onJingleError(self.sid, error);
  10772. },
  10773. 10000);
  10774. },
  10775. function (e) {
  10776. console.error('setLocalDescription failed', e);
  10777. }
  10778. );
  10779. };
  10780. JingleSession.prototype.terminate = function (reason) {
  10781. this.state = 'ended';
  10782. this.reason = reason;
  10783. this.peerconnection.close();
  10784. if (this.statsinterval !== null) {
  10785. window.clearInterval(this.statsinterval);
  10786. this.statsinterval = null;
  10787. }
  10788. };
  10789. JingleSession.prototype.active = function () {
  10790. return this.state == 'active';
  10791. };
  10792. JingleSession.prototype.sendIceCandidate = function (candidate) {
  10793. var self = this;
  10794. if (candidate && !this.lasticecandidate) {
  10795. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  10796. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  10797. if (!(ice && jcand)) {
  10798. console.error('failed to get ice && jcand');
  10799. return;
  10800. }
  10801. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10802. if (jcand.type === 'srflx') {
  10803. this.hadstuncandidate = true;
  10804. } else if (jcand.type === 'relay') {
  10805. this.hadturncandidate = true;
  10806. }
  10807. if (this.usetrickle) {
  10808. if (this.usedrip) {
  10809. if (this.drip_container.length === 0) {
  10810. // start 20ms callout
  10811. window.setTimeout(function () {
  10812. if (self.drip_container.length === 0) return;
  10813. self.sendIceCandidates(self.drip_container);
  10814. self.drip_container = [];
  10815. }, 20);
  10816. }
  10817. this.drip_container.push(candidate);
  10818. return;
  10819. } else {
  10820. self.sendIceCandidate([candidate]);
  10821. }
  10822. }
  10823. } else {
  10824. //console.log('sendIceCandidate: last candidate.');
  10825. if (!this.usetrickle) {
  10826. //console.log('should send full offer now...');
  10827. var init = $iq({to: this.peerjid,
  10828. type: 'set'})
  10829. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10830. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  10831. initiator: this.initiator,
  10832. sid: this.sid});
  10833. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  10834. var self = this;
  10835. var sendJingle = function (ssrc) {
  10836. if(!ssrc)
  10837. ssrc = {};
  10838. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  10839. self.connection.sendIQ(init,
  10840. function () {
  10841. //console.log('session initiate ack');
  10842. var ack = {};
  10843. ack.source = 'offer';
  10844. $(document).trigger('ack.jingle', [self.sid, ack]);
  10845. },
  10846. function (stanza) {
  10847. self.state = 'error';
  10848. self.peerconnection.close();
  10849. var error = ($(stanza).find('error').length) ? {
  10850. code: $(stanza).find('error').attr('code'),
  10851. reason: $(stanza).find('error :first')[0].tagName,
  10852. }:{};
  10853. error.source = 'offer';
  10854. JingleSession.onJingleError(self.sid, error);
  10855. },
  10856. 10000);
  10857. }
  10858. sendJingle();
  10859. }
  10860. this.lasticecandidate = true;
  10861. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  10862. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  10863. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  10864. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  10865. }
  10866. }
  10867. };
  10868. JingleSession.prototype.sendIceCandidates = function (candidates) {
  10869. console.log('sendIceCandidates', candidates);
  10870. var cand = $iq({to: this.peerjid, type: 'set'})
  10871. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10872. action: 'transport-info',
  10873. initiator: this.initiator,
  10874. sid: this.sid});
  10875. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  10876. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  10877. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  10878. if (cands.length > 0) {
  10879. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  10880. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10881. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  10882. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  10883. }).c('transport', ice);
  10884. for (var i = 0; i < cands.length; i++) {
  10885. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  10886. }
  10887. // add fingerprint
  10888. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  10889. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  10890. tmp.required = true;
  10891. cand.c(
  10892. 'fingerprint',
  10893. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  10894. .t(tmp.fingerprint);
  10895. delete tmp.fingerprint;
  10896. cand.attrs(tmp);
  10897. cand.up();
  10898. }
  10899. cand.up(); // transport
  10900. cand.up(); // content
  10901. }
  10902. }
  10903. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  10904. //console.log('was this the last candidate', this.lasticecandidate);
  10905. this.connection.sendIQ(cand,
  10906. function () {
  10907. var ack = {};
  10908. ack.source = 'transportinfo';
  10909. $(document).trigger('ack.jingle', [this.sid, ack]);
  10910. },
  10911. function (stanza) {
  10912. var error = ($(stanza).find('error').length) ? {
  10913. code: $(stanza).find('error').attr('code'),
  10914. reason: $(stanza).find('error :first')[0].tagName,
  10915. }:{};
  10916. error.source = 'transportinfo';
  10917. JingleSession.onJingleError(this.sid, error);
  10918. },
  10919. 10000);
  10920. };
  10921. JingleSession.prototype.sendOffer = function () {
  10922. //console.log('sendOffer...');
  10923. var self = this;
  10924. this.peerconnection.createOffer(function (sdp) {
  10925. self.createdOffer(sdp);
  10926. },
  10927. function (e) {
  10928. console.error('createOffer failed', e);
  10929. },
  10930. this.media_constraints
  10931. );
  10932. };
  10933. JingleSession.prototype.createdOffer = function (sdp) {
  10934. //console.log('createdOffer', sdp);
  10935. var self = this;
  10936. this.localSDP = new SDP(sdp.sdp);
  10937. //this.localSDP.mangle();
  10938. var sendJingle = function () {
  10939. var init = $iq({to: this.peerjid,
  10940. type: 'set'})
  10941. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10942. action: 'session-initiate',
  10943. initiator: this.initiator,
  10944. sid: this.sid});
  10945. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10946. self.connection.sendIQ(init,
  10947. function () {
  10948. var ack = {};
  10949. ack.source = 'offer';
  10950. $(document).trigger('ack.jingle', [self.sid, ack]);
  10951. },
  10952. function (stanza) {
  10953. self.state = 'error';
  10954. self.peerconnection.close();
  10955. var error = ($(stanza).find('error').length) ? {
  10956. code: $(stanza).find('error').attr('code'),
  10957. reason: $(stanza).find('error :first')[0].tagName,
  10958. }:{};
  10959. error.source = 'offer';
  10960. JingleSession.onJingleError(self.sid, error);
  10961. },
  10962. 10000);
  10963. }
  10964. sdp.sdp = this.localSDP.raw;
  10965. this.peerconnection.setLocalDescription(sdp,
  10966. function () {
  10967. if(self.usetrickle)
  10968. {
  10969. sendJingle();
  10970. }
  10971. self.setLocalDescription();
  10972. //console.log('setLocalDescription success');
  10973. },
  10974. function (e) {
  10975. console.error('setLocalDescription failed', e);
  10976. }
  10977. );
  10978. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10979. for (var i = 0; i < cands.length; i++) {
  10980. var cand = SDPUtil.parse_icecandidate(cands[i]);
  10981. if (cand.type == 'srflx') {
  10982. this.hadstuncandidate = true;
  10983. } else if (cand.type == 'relay') {
  10984. this.hadturncandidate = true;
  10985. }
  10986. }
  10987. };
  10988. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  10989. //console.log('setting remote description... ', desctype);
  10990. this.remoteSDP = new SDP('');
  10991. this.remoteSDP.fromJingle(elem);
  10992. if (this.peerconnection.remoteDescription !== null) {
  10993. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  10994. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  10995. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  10996. for (var i = 0; i < pranswer.media.length; i++) {
  10997. // make sure we have ice ufrag and pwd
  10998. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  10999. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  11000. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  11001. } else {
  11002. console.warn('no ice ufrag?');
  11003. }
  11004. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  11005. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  11006. } else {
  11007. console.warn('no ice pwd?');
  11008. }
  11009. }
  11010. // copy over candidates
  11011. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  11012. for (var j = 0; j < lines.length; j++) {
  11013. this.remoteSDP.media[i] += lines[j] + '\r\n';
  11014. }
  11015. }
  11016. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11017. }
  11018. }
  11019. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  11020. this.peerconnection.setRemoteDescription(remotedesc,
  11021. function () {
  11022. //console.log('setRemoteDescription success');
  11023. },
  11024. function (e) {
  11025. console.error('setRemoteDescription error', e);
  11026. JingleSession.onJingleFatalError(self, e);
  11027. }
  11028. );
  11029. };
  11030. JingleSession.prototype.addIceCandidate = function (elem) {
  11031. var self = this;
  11032. if (this.peerconnection.signalingState == 'closed') {
  11033. return;
  11034. }
  11035. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  11036. console.log('trickle ice candidate arriving before session accept...');
  11037. // create a PRANSWER for setRemoteDescription
  11038. if (!this.remoteSDP) {
  11039. var cobbled = 'v=0\r\n' +
  11040. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11041. 's=-\r\n' +
  11042. 't=0 0\r\n';
  11043. // first, take some things from the local description
  11044. for (var i = 0; i < this.localSDP.media.length; i++) {
  11045. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  11046. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  11047. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  11048. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  11049. }
  11050. cobbled += 'a=inactive\r\n';
  11051. }
  11052. this.remoteSDP = new SDP(cobbled);
  11053. }
  11054. // then add things like ice and dtls from remote candidate
  11055. elem.each(function () {
  11056. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  11057. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11058. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11059. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  11060. var tmp = $(this).find('transport');
  11061. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  11062. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  11063. tmp = $(this).find('transport>fingerprint');
  11064. if (tmp.length) {
  11065. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  11066. } else {
  11067. console.log('no dtls fingerprint (webrtc issue #1718?)');
  11068. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  11069. }
  11070. break;
  11071. }
  11072. }
  11073. }
  11074. });
  11075. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11076. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  11077. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  11078. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  11079. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  11080. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  11081. }).length == this.remoteSDP.media.length;
  11082. if (iscomplete) {
  11083. console.log('setting pranswer');
  11084. try {
  11085. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  11086. function() {
  11087. },
  11088. function(e) {
  11089. console.log('setRemoteDescription pranswer failed', e.toString());
  11090. });
  11091. } catch (e) {
  11092. console.error('setting pranswer failed', e);
  11093. }
  11094. } else {
  11095. //console.log('not yet setting pranswer');
  11096. }
  11097. }
  11098. // operate on each content element
  11099. elem.each(function () {
  11100. // would love to deactivate this, but firefox still requires it
  11101. var idx = -1;
  11102. var i;
  11103. for (i = 0; i < self.remoteSDP.media.length; i++) {
  11104. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11105. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11106. idx = i;
  11107. break;
  11108. }
  11109. }
  11110. if (idx == -1) { // fall back to localdescription
  11111. for (i = 0; i < self.localSDP.media.length; i++) {
  11112. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11113. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11114. idx = i;
  11115. break;
  11116. }
  11117. }
  11118. }
  11119. var name = $(this).attr('name');
  11120. // TODO: check ice-pwd and ice-ufrag?
  11121. $(this).find('transport>candidate').each(function () {
  11122. var line, candidate;
  11123. line = SDPUtil.candidateFromJingle(this);
  11124. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  11125. sdpMid: name,
  11126. candidate: line});
  11127. try {
  11128. self.peerconnection.addIceCandidate(candidate);
  11129. } catch (e) {
  11130. console.error('addIceCandidate failed', e.toString(), line);
  11131. }
  11132. });
  11133. });
  11134. };
  11135. JingleSession.prototype.sendAnswer = function (provisional) {
  11136. //console.log('createAnswer', provisional);
  11137. var self = this;
  11138. this.peerconnection.createAnswer(
  11139. function (sdp) {
  11140. self.createdAnswer(sdp, provisional);
  11141. },
  11142. function (e) {
  11143. console.error('createAnswer failed', e);
  11144. },
  11145. this.media_constraints
  11146. );
  11147. };
  11148. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  11149. //console.log('createAnswer callback');
  11150. var self = this;
  11151. this.localSDP = new SDP(sdp.sdp);
  11152. //this.localSDP.mangle();
  11153. this.usepranswer = provisional === true;
  11154. if (this.usetrickle) {
  11155. if (this.usepranswer) {
  11156. sdp.type = 'pranswer';
  11157. for (var i = 0; i < this.localSDP.media.length; i++) {
  11158. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  11159. }
  11160. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  11161. }
  11162. }
  11163. var self = this;
  11164. var sendJingle = function (ssrcs) {
  11165. var accept = $iq({to: self.peerjid,
  11166. type: 'set'})
  11167. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11168. action: 'session-accept',
  11169. initiator: self.initiator,
  11170. responder: self.responder,
  11171. sid: self.sid });
  11172. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  11173. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  11174. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  11175. self.connection.sendIQ(accept,
  11176. function () {
  11177. var ack = {};
  11178. ack.source = 'answer';
  11179. $(document).trigger('ack.jingle', [self.sid, ack]);
  11180. },
  11181. function (stanza) {
  11182. var error = ($(stanza).find('error').length) ? {
  11183. code: $(stanza).find('error').attr('code'),
  11184. reason: $(stanza).find('error :first')[0].tagName,
  11185. }:{};
  11186. error.source = 'answer';
  11187. JingleSession.onJingleError(self.sid, error);
  11188. },
  11189. 10000);
  11190. }
  11191. sdp.sdp = this.localSDP.raw;
  11192. this.peerconnection.setLocalDescription(sdp,
  11193. function () {
  11194. //console.log('setLocalDescription success');
  11195. if (self.usetrickle && !self.usepranswer) {
  11196. sendJingle();
  11197. }
  11198. self.setLocalDescription();
  11199. },
  11200. function (e) {
  11201. console.error('setLocalDescription failed', e);
  11202. }
  11203. );
  11204. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11205. for (var j = 0; j < cands.length; j++) {
  11206. var cand = SDPUtil.parse_icecandidate(cands[j]);
  11207. if (cand.type == 'srflx') {
  11208. this.hadstuncandidate = true;
  11209. } else if (cand.type == 'relay') {
  11210. this.hadturncandidate = true;
  11211. }
  11212. }
  11213. };
  11214. JingleSession.prototype.sendTerminate = function (reason, text) {
  11215. var self = this,
  11216. term = $iq({to: this.peerjid,
  11217. type: 'set'})
  11218. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11219. action: 'session-terminate',
  11220. initiator: this.initiator,
  11221. sid: this.sid})
  11222. .c('reason')
  11223. .c(reason || 'success');
  11224. if (text) {
  11225. term.up().c('text').t(text);
  11226. }
  11227. this.connection.sendIQ(term,
  11228. function () {
  11229. self.peerconnection.close();
  11230. self.peerconnection = null;
  11231. self.terminate();
  11232. var ack = {};
  11233. ack.source = 'terminate';
  11234. $(document).trigger('ack.jingle', [self.sid, ack]);
  11235. },
  11236. function (stanza) {
  11237. var error = ($(stanza).find('error').length) ? {
  11238. code: $(stanza).find('error').attr('code'),
  11239. reason: $(stanza).find('error :first')[0].tagName,
  11240. }:{};
  11241. $(document).trigger('ack.jingle', [self.sid, error]);
  11242. },
  11243. 10000);
  11244. if (this.statsinterval !== null) {
  11245. window.clearInterval(this.statsinterval);
  11246. this.statsinterval = null;
  11247. }
  11248. };
  11249. JingleSession.prototype.addSource = function (elem, fromJid) {
  11250. var self = this;
  11251. // FIXME: dirty waiting
  11252. if (!this.peerconnection.localDescription)
  11253. {
  11254. console.warn("addSource - localDescription not ready yet")
  11255. setTimeout(function()
  11256. {
  11257. self.addSource(elem, fromJid);
  11258. },
  11259. 200
  11260. );
  11261. return;
  11262. }
  11263. console.log('addssrc', new Date().getTime());
  11264. console.log('ice', this.peerconnection.iceConnectionState);
  11265. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11266. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11267. $(elem).each(function (idx, content) {
  11268. var name = $(content).attr('name');
  11269. var lines = '';
  11270. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11271. var semantics = this.getAttribute('semantics');
  11272. var ssrcs = $(this).find('>source').map(function () {
  11273. return this.getAttribute('ssrc');
  11274. }).get();
  11275. if (ssrcs.length != 0) {
  11276. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11277. }
  11278. });
  11279. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11280. tmp.each(function () {
  11281. var ssrc = $(this).attr('ssrc');
  11282. if(mySdp.containsSSRC(ssrc)){
  11283. /**
  11284. * This happens when multiple participants change their streams at the same time and
  11285. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  11286. * addssrc are scheduled for update IQ. See
  11287. */
  11288. console.warn("Got add stream request for my own ssrc: "+ssrc);
  11289. return;
  11290. }
  11291. $(this).find('>parameter').each(function () {
  11292. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11293. if ($(this).attr('value') && $(this).attr('value').length)
  11294. lines += ':' + $(this).attr('value');
  11295. lines += '\r\n';
  11296. });
  11297. });
  11298. sdp.media.forEach(function(media, idx) {
  11299. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11300. return;
  11301. sdp.media[idx] += lines;
  11302. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  11303. self.addssrc[idx] += lines;
  11304. });
  11305. sdp.raw = sdp.session + sdp.media.join('');
  11306. });
  11307. this.modifySources();
  11308. };
  11309. JingleSession.prototype.removeSource = function (elem, fromJid) {
  11310. var self = this;
  11311. // FIXME: dirty waiting
  11312. if (!this.peerconnection.localDescription)
  11313. {
  11314. console.warn("removeSource - localDescription not ready yet")
  11315. setTimeout(function()
  11316. {
  11317. self.removeSource(elem, fromJid);
  11318. },
  11319. 200
  11320. );
  11321. return;
  11322. }
  11323. console.log('removessrc', new Date().getTime());
  11324. console.log('ice', this.peerconnection.iceConnectionState);
  11325. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11326. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11327. $(elem).each(function (idx, content) {
  11328. var name = $(content).attr('name');
  11329. var lines = '';
  11330. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11331. var semantics = this.getAttribute('semantics');
  11332. var ssrcs = $(this).find('>source').map(function () {
  11333. return this.getAttribute('ssrc');
  11334. }).get();
  11335. if (ssrcs.length != 0) {
  11336. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11337. }
  11338. });
  11339. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11340. tmp.each(function () {
  11341. var ssrc = $(this).attr('ssrc');
  11342. // This should never happen, but can be useful for bug detection
  11343. if(mySdp.containsSSRC(ssrc)){
  11344. console.error("Got remove stream request for my own ssrc: "+ssrc);
  11345. return;
  11346. }
  11347. $(this).find('>parameter').each(function () {
  11348. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11349. if ($(this).attr('value') && $(this).attr('value').length)
  11350. lines += ':' + $(this).attr('value');
  11351. lines += '\r\n';
  11352. });
  11353. });
  11354. sdp.media.forEach(function(media, idx) {
  11355. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11356. return;
  11357. sdp.media[idx] += lines;
  11358. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  11359. self.removessrc[idx] += lines;
  11360. });
  11361. sdp.raw = sdp.session + sdp.media.join('');
  11362. });
  11363. this.modifySources();
  11364. };
  11365. JingleSession.prototype.modifySources = function (successCallback) {
  11366. var self = this;
  11367. if (this.peerconnection.signalingState == 'closed') return;
  11368. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  11369. // There is nothing to do since scheduled job might have been executed by another succeeding call
  11370. this.setLocalDescription();
  11371. if(successCallback){
  11372. successCallback();
  11373. }
  11374. return;
  11375. }
  11376. // FIXME: this is a big hack
  11377. // https://code.google.com/p/webrtc/issues/detail?id=2688
  11378. // ^ has been fixed.
  11379. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
  11380. console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
  11381. this.wait = true;
  11382. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  11383. return;
  11384. }
  11385. if (this.wait) {
  11386. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  11387. this.wait = false;
  11388. return;
  11389. }
  11390. // Reset switch streams flag
  11391. this.switchstreams = false;
  11392. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11393. // add sources
  11394. this.addssrc.forEach(function(lines, idx) {
  11395. sdp.media[idx] += lines;
  11396. });
  11397. this.addssrc = [];
  11398. // remove sources
  11399. this.removessrc.forEach(function(lines, idx) {
  11400. lines = lines.split('\r\n');
  11401. lines.pop(); // remove empty last element;
  11402. lines.forEach(function(line) {
  11403. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  11404. });
  11405. });
  11406. this.removessrc = [];
  11407. // FIXME:
  11408. // this was a hack for the situation when only one peer exists
  11409. // in the conference.
  11410. // check if still required and remove
  11411. if (sdp.media[0])
  11412. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  11413. if (sdp.media[1])
  11414. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11415. sdp.raw = sdp.session + sdp.media.join('');
  11416. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  11417. function() {
  11418. if(self.signalingState == 'closed') {
  11419. console.error("createAnswer attempt on closed state");
  11420. return;
  11421. }
  11422. self.peerconnection.createAnswer(
  11423. function(modifiedAnswer) {
  11424. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  11425. if (self.pendingop !== null) {
  11426. var sdp = new SDP(modifiedAnswer.sdp);
  11427. if (sdp.media.length > 1) {
  11428. switch(self.pendingop) {
  11429. case 'mute':
  11430. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  11431. break;
  11432. case 'unmute':
  11433. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11434. break;
  11435. }
  11436. sdp.raw = sdp.session + sdp.media.join('');
  11437. modifiedAnswer.sdp = sdp.raw;
  11438. }
  11439. self.pendingop = null;
  11440. }
  11441. // FIXME: pushing down an answer while ice connection state
  11442. // is still checking is bad...
  11443. //console.log(self.peerconnection.iceConnectionState);
  11444. // trying to work around another chrome bug
  11445. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11446. self.peerconnection.setLocalDescription(modifiedAnswer,
  11447. function() {
  11448. //console.log('modified setLocalDescription ok');
  11449. self.setLocalDescription();
  11450. if(successCallback){
  11451. successCallback();
  11452. }
  11453. },
  11454. function(error) {
  11455. console.error('modified setLocalDescription failed', error);
  11456. }
  11457. );
  11458. },
  11459. function(error) {
  11460. console.error('modified answer failed', error);
  11461. }
  11462. );
  11463. },
  11464. function(error) {
  11465. console.error('modify failed', error);
  11466. }
  11467. );
  11468. };
  11469. /**
  11470. * Switches video streams.
  11471. * @param new_stream new stream that will be used as video of this session.
  11472. * @param oldStream old video stream of this session.
  11473. * @param success_callback callback executed after successful stream switch.
  11474. */
  11475. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback) {
  11476. var self = this;
  11477. // Remember SDP to figure out added/removed SSRCs
  11478. var oldSdp = null;
  11479. if(self.peerconnection) {
  11480. if(self.peerconnection.localDescription) {
  11481. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11482. }
  11483. self.peerconnection.removeStream(oldStream, true);
  11484. if(new_stream)
  11485. self.peerconnection.addStream(new_stream);
  11486. }
  11487. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11488. // Conference is not active
  11489. if(!oldSdp || !self.peerconnection) {
  11490. success_callback();
  11491. return;
  11492. }
  11493. self.switchstreams = true;
  11494. self.modifySources(function() {
  11495. console.log('modify sources done');
  11496. success_callback();
  11497. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11498. console.log("SDPs", oldSdp, newSdp);
  11499. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11500. });
  11501. };
  11502. /**
  11503. * Figures out added/removed ssrcs and send update IQs.
  11504. * @param old_sdp SDP object for old description.
  11505. * @param new_sdp SDP object for new description.
  11506. */
  11507. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11508. if (!(this.peerconnection.signalingState == 'stable' &&
  11509. this.peerconnection.iceConnectionState == 'connected')){
  11510. console.log("Too early to send updates");
  11511. return;
  11512. }
  11513. // send source-remove IQ.
  11514. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11515. var remove = $iq({to: this.peerjid, type: 'set'})
  11516. .c('jingle', {
  11517. xmlns: 'urn:xmpp:jingle:1',
  11518. action: 'source-remove',
  11519. initiator: this.initiator,
  11520. sid: this.sid
  11521. }
  11522. );
  11523. var removed = sdpDiffer.toJingle(remove);
  11524. if (removed) {
  11525. this.connection.sendIQ(remove,
  11526. function (res) {
  11527. console.info('got remove result', res);
  11528. },
  11529. function (err) {
  11530. console.error('got remove error', err);
  11531. }
  11532. );
  11533. } else {
  11534. console.log('removal not necessary');
  11535. }
  11536. // send source-add IQ.
  11537. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11538. var add = $iq({to: this.peerjid, type: 'set'})
  11539. .c('jingle', {
  11540. xmlns: 'urn:xmpp:jingle:1',
  11541. action: 'source-add',
  11542. initiator: this.initiator,
  11543. sid: this.sid
  11544. }
  11545. );
  11546. var added = sdpDiffer.toJingle(add);
  11547. if (added) {
  11548. this.connection.sendIQ(add,
  11549. function (res) {
  11550. console.info('got add result', res);
  11551. },
  11552. function (err) {
  11553. console.error('got add error', err);
  11554. }
  11555. );
  11556. } else {
  11557. console.log('addition not necessary');
  11558. }
  11559. };
  11560. /**
  11561. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  11562. *
  11563. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  11564. * tracks; otherwise, <tt>false</tt>
  11565. * @param callback a function to be invoked with <tt>mute</tt> after all video
  11566. * tracks have been enabled/disabled. The function may, optionally, return
  11567. * another function which is to be invoked after the whole mute/unmute operation
  11568. * has completed successfully.
  11569. * @param options an object which specifies optional arguments such as the
  11570. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  11571. * specifies whether the method was initiated in response to a user command (in
  11572. * contrast to an automatic decision made by the application logic)
  11573. */
  11574. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  11575. var byUser;
  11576. if (options) {
  11577. byUser = options.byUser;
  11578. if (typeof byUser === 'undefined') {
  11579. byUser = true;
  11580. }
  11581. } else {
  11582. byUser = true;
  11583. }
  11584. // The user's command to mute the (local) video takes precedence over any
  11585. // automatic decision made by the application logic.
  11586. if (byUser) {
  11587. this.videoMuteByUser = mute;
  11588. } else if (this.videoMuteByUser) {
  11589. return;
  11590. }
  11591. this.hardMuteVideo(mute);
  11592. this.modifySources(callback(mute));
  11593. };
  11594. JingleSession.prototype.hardMuteVideo = function (muted) {
  11595. this.pendingop = muted ? 'mute' : 'unmute';
  11596. };
  11597. JingleSession.prototype.sendMute = function (muted, content) {
  11598. var info = $iq({to: this.peerjid,
  11599. type: 'set'})
  11600. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11601. action: 'session-info',
  11602. initiator: this.initiator,
  11603. sid: this.sid });
  11604. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11605. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  11606. if (content) {
  11607. info.attrs({'name': content});
  11608. }
  11609. this.connection.send(info);
  11610. };
  11611. JingleSession.prototype.sendRinging = function () {
  11612. var info = $iq({to: this.peerjid,
  11613. type: 'set'})
  11614. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11615. action: 'session-info',
  11616. initiator: this.initiator,
  11617. sid: this.sid });
  11618. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11619. this.connection.send(info);
  11620. };
  11621. JingleSession.prototype.getStats = function (interval) {
  11622. var self = this;
  11623. var recv = {audio: 0, video: 0};
  11624. var lost = {audio: 0, video: 0};
  11625. var lastrecv = {audio: 0, video: 0};
  11626. var lastlost = {audio: 0, video: 0};
  11627. var loss = {audio: 0, video: 0};
  11628. var delta = {audio: 0, video: 0};
  11629. this.statsinterval = window.setInterval(function () {
  11630. if (self && self.peerconnection && self.peerconnection.getStats) {
  11631. self.peerconnection.getStats(function (stats) {
  11632. var results = stats.result();
  11633. // TODO: there are so much statistics you can get from this..
  11634. for (var i = 0; i < results.length; ++i) {
  11635. if (results[i].type == 'ssrc') {
  11636. var packetsrecv = results[i].stat('packetsReceived');
  11637. var packetslost = results[i].stat('packetsLost');
  11638. if (packetsrecv && packetslost) {
  11639. packetsrecv = parseInt(packetsrecv, 10);
  11640. packetslost = parseInt(packetslost, 10);
  11641. if (results[i].stat('googFrameRateReceived')) {
  11642. lastlost.video = lost.video;
  11643. lastrecv.video = recv.video;
  11644. recv.video = packetsrecv;
  11645. lost.video = packetslost;
  11646. } else {
  11647. lastlost.audio = lost.audio;
  11648. lastrecv.audio = recv.audio;
  11649. recv.audio = packetsrecv;
  11650. lost.audio = packetslost;
  11651. }
  11652. }
  11653. }
  11654. }
  11655. delta.audio = recv.audio - lastrecv.audio;
  11656. delta.video = recv.video - lastrecv.video;
  11657. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  11658. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  11659. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  11660. });
  11661. }
  11662. }, interval || 3000);
  11663. return this.statsinterval;
  11664. };
  11665. JingleSession.onJingleError = function (session, error)
  11666. {
  11667. console.error("Jingle error", error);
  11668. }
  11669. JingleSession.onJingleFatalError = function (session, error)
  11670. {
  11671. this.service.sessionTerminated = true;
  11672. this.connection.emuc.doLeave();
  11673. APP.UI.messageHandler.showError("dialog.sorry",
  11674. "dialog.internalError");
  11675. }
  11676. JingleSession.prototype.setLocalDescription = function () {
  11677. // put our ssrcs into presence so other clients can identify our stream
  11678. var newssrcs = [];
  11679. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  11680. media.forEach(function (media) {
  11681. if(Object.keys(media.sources).length > 0) {
  11682. // TODO(gp) maybe exclude FID streams?
  11683. Object.keys(media.sources).forEach(function (ssrc) {
  11684. newssrcs.push({
  11685. 'ssrc': ssrc,
  11686. 'type': media.type,
  11687. 'direction': media.direction
  11688. });
  11689. });
  11690. }
  11691. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  11692. {
  11693. newssrcs.push({
  11694. 'ssrc': this.localStreamsSSRC[media.type],
  11695. 'type': media.type,
  11696. 'direction': media.direction
  11697. });
  11698. }
  11699. });
  11700. console.log('new ssrcs', newssrcs);
  11701. // Have to clear presence map to get rid of removed streams
  11702. this.connection.emuc.clearPresenceMedia();
  11703. if (newssrcs.length > 0) {
  11704. for (var i = 1; i <= newssrcs.length; i ++) {
  11705. // Change video type to screen
  11706. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  11707. newssrcs[i-1].type = 'screen';
  11708. }
  11709. this.connection.emuc.addMediaToPresence(i,
  11710. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  11711. }
  11712. this.connection.emuc.sendPresence();
  11713. }
  11714. }
  11715. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11716. function sendKeyframe(pc) {
  11717. console.log('sendkeyframe', pc.iceConnectionState);
  11718. if (pc.iceConnectionState !== 'connected') return; // safe...
  11719. pc.setRemoteDescription(
  11720. pc.remoteDescription,
  11721. function () {
  11722. pc.createAnswer(
  11723. function (modifiedAnswer) {
  11724. pc.setLocalDescription(
  11725. modifiedAnswer,
  11726. function () {
  11727. // noop
  11728. },
  11729. function (error) {
  11730. console.log('triggerKeyframe setLocalDescription failed', error);
  11731. APP.UI.messageHandler.showError();
  11732. }
  11733. );
  11734. },
  11735. function (error) {
  11736. console.log('triggerKeyframe createAnswer failed', error);
  11737. APP.UI.messageHandler.showError();
  11738. }
  11739. );
  11740. },
  11741. function (error) {
  11742. console.log('triggerKeyframe setRemoteDescription failed', error);
  11743. APP.UI.messageHandler.showError();
  11744. }
  11745. );
  11746. }
  11747. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  11748. var self = this;
  11749. var thessrc;
  11750. var ssrc2jid = this.connection.emuc.ssrc2jid;
  11751. // look up an associated JID for a stream id
  11752. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  11753. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  11754. var ssrclines
  11755. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  11756. ssrclines = ssrclines.filter(function (line) {
  11757. // NOTE(gp) previously we filtered on the mslabel, but that property
  11758. // is not always present.
  11759. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  11760. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  11761. });
  11762. if (ssrclines.length) {
  11763. thessrc = ssrclines[0].substring(7).split(' ')[0];
  11764. // We signal our streams (through Jingle to the focus) before we set
  11765. // our presence (through which peers associate remote streams to
  11766. // jids). So, it might arrive that a remote stream is added but
  11767. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  11768. // successfully set. Here we wait for up to a second for the
  11769. // presence to arrive.
  11770. if (!ssrc2jid[thessrc]) {
  11771. if (typeof times === 'undefined')
  11772. {
  11773. times = 0;
  11774. }
  11775. if (times > 10)
  11776. {
  11777. console.warning('Waiting for jid timed out', thessrc);
  11778. }
  11779. else
  11780. {
  11781. setTimeout(function(d) {
  11782. return function() {
  11783. self.remoteStreamAdded(d, times++);
  11784. }
  11785. }(data), 250);
  11786. }
  11787. return;
  11788. }
  11789. // ok to overwrite the one from focus? might save work in colibri.js
  11790. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  11791. if (ssrc2jid[thessrc]) {
  11792. data.peerjid = ssrc2jid[thessrc];
  11793. }
  11794. }
  11795. }
  11796. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  11797. var isVideo = data.stream.getVideoTracks().length > 0;
  11798. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11799. if (isVideo &&
  11800. data.peerjid && this.peerjid === data.peerjid &&
  11801. data.stream.getVideoTracks().length === 0 &&
  11802. APP.RTC.localVideo.getTracks().length > 0) {
  11803. window.setTimeout(function () {
  11804. sendKeyframe(self.peerconnection);
  11805. }, 3000);
  11806. }
  11807. }
  11808. module.exports = JingleSession;
  11809. },{"../../service/RTC/RTCBrowserType":88,"./SDP":49,"./SDPDiffer":50,"./SDPUtil":51,"./TraceablePeerConnection":52}],49:[function(require,module,exports){
  11810. /* jshint -W117 */
  11811. var SDPUtil = require("./SDPUtil");
  11812. // SDP STUFF
  11813. function SDP(sdp) {
  11814. this.media = sdp.split('\r\nm=');
  11815. for (var i = 1; i < this.media.length; i++) {
  11816. this.media[i] = 'm=' + this.media[i];
  11817. if (i != this.media.length - 1) {
  11818. this.media[i] += '\r\n';
  11819. }
  11820. }
  11821. this.session = this.media.shift() + '\r\n';
  11822. this.raw = this.session + this.media.join('');
  11823. }
  11824. /**
  11825. * Returns map of MediaChannel mapped per channel idx.
  11826. */
  11827. SDP.prototype.getMediaSsrcMap = function() {
  11828. var self = this;
  11829. var media_ssrcs = {};
  11830. var tmp;
  11831. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  11832. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  11833. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  11834. var media = {
  11835. mediaindex: mediaindex,
  11836. mid: mid,
  11837. ssrcs: {},
  11838. ssrcGroups: []
  11839. };
  11840. media_ssrcs[mediaindex] = media;
  11841. tmp.forEach(function (line) {
  11842. var linessrc = line.substring(7).split(' ')[0];
  11843. // allocate new ChannelSsrc
  11844. if(!media.ssrcs[linessrc]) {
  11845. media.ssrcs[linessrc] = {
  11846. ssrc: linessrc,
  11847. lines: []
  11848. };
  11849. }
  11850. media.ssrcs[linessrc].lines.push(line);
  11851. });
  11852. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  11853. tmp.forEach(function(line){
  11854. var semantics = line.substr(0, idx).substr(13);
  11855. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11856. if (ssrcs.length != 0) {
  11857. media.ssrcGroups.push({
  11858. semantics: semantics,
  11859. ssrcs: ssrcs
  11860. });
  11861. }
  11862. });
  11863. }
  11864. return media_ssrcs;
  11865. };
  11866. /**
  11867. * Returns <tt>true</tt> if this SDP contains given SSRC.
  11868. * @param ssrc the ssrc to check.
  11869. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  11870. */
  11871. SDP.prototype.containsSSRC = function(ssrc) {
  11872. var medias = this.getMediaSsrcMap();
  11873. var contains = false;
  11874. Object.keys(medias).forEach(function(mediaindex){
  11875. var media = medias[mediaindex];
  11876. //console.log("Check", channel, ssrc);
  11877. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  11878. contains = true;
  11879. }
  11880. });
  11881. return contains;
  11882. };
  11883. // remove iSAC and CN from SDP
  11884. SDP.prototype.mangle = function () {
  11885. var i, j, mline, lines, rtpmap, newdesc;
  11886. for (i = 0; i < this.media.length; i++) {
  11887. lines = this.media[i].split('\r\n');
  11888. lines.pop(); // remove empty last element
  11889. mline = SDPUtil.parse_mline(lines.shift());
  11890. if (mline.media != 'audio')
  11891. continue;
  11892. newdesc = '';
  11893. mline.fmt.length = 0;
  11894. for (j = 0; j < lines.length; j++) {
  11895. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  11896. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  11897. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  11898. continue;
  11899. mline.fmt.push(rtpmap.id);
  11900. newdesc += lines[j] + '\r\n';
  11901. } else {
  11902. newdesc += lines[j] + '\r\n';
  11903. }
  11904. }
  11905. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  11906. this.media[i] += newdesc;
  11907. }
  11908. this.raw = this.session + this.media.join('');
  11909. };
  11910. // remove lines matching prefix from session section
  11911. SDP.prototype.removeSessionLines = function(prefix) {
  11912. var self = this;
  11913. var lines = SDPUtil.find_lines(this.session, prefix);
  11914. lines.forEach(function(line) {
  11915. self.session = self.session.replace(line + '\r\n', '');
  11916. });
  11917. this.raw = this.session + this.media.join('');
  11918. return lines;
  11919. }
  11920. // remove lines matching prefix from a media section specified by mediaindex
  11921. // TODO: non-numeric mediaindex could match mid
  11922. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  11923. var self = this;
  11924. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  11925. lines.forEach(function(line) {
  11926. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  11927. });
  11928. this.raw = this.session + this.media.join('');
  11929. return lines;
  11930. }
  11931. // add content's to a jingle element
  11932. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  11933. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  11934. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  11935. var self = this;
  11936. // new bundle plan
  11937. if (SDPUtil.find_line(this.session, 'a=group:')) {
  11938. lines = SDPUtil.find_lines(this.session, 'a=group:');
  11939. for (i = 0; i < lines.length; i++) {
  11940. tmp = lines[i].split(' ');
  11941. var semantics = tmp.shift().substr(8);
  11942. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  11943. for (j = 0; j < tmp.length; j++) {
  11944. elem.c('content', {name: tmp[j]}).up();
  11945. }
  11946. elem.up();
  11947. }
  11948. }
  11949. for (i = 0; i < this.media.length; i++) {
  11950. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  11951. if (!(mline.media === 'audio' ||
  11952. mline.media === 'video' ||
  11953. mline.media === 'application'))
  11954. {
  11955. continue;
  11956. }
  11957. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  11958. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  11959. } else {
  11960. if(ssrcs && ssrcs[mline.media])
  11961. {
  11962. ssrc = ssrcs[mline.media];
  11963. }
  11964. else
  11965. ssrc = false;
  11966. }
  11967. elem.c('content', {creator: thecreator, name: mline.media});
  11968. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  11969. // prefer identifier from a=mid if present
  11970. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  11971. elem.attrs({ name: mid });
  11972. }
  11973. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  11974. {
  11975. elem.c('description',
  11976. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  11977. media: mline.media });
  11978. if (ssrc) {
  11979. elem.attrs({ssrc: ssrc});
  11980. }
  11981. for (j = 0; j < mline.fmt.length; j++) {
  11982. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  11983. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  11984. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  11985. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  11986. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  11987. for (k = 0; k < tmp.length; k++) {
  11988. elem.c('parameter', tmp[k]).up();
  11989. }
  11990. }
  11991. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  11992. elem.up();
  11993. }
  11994. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  11995. elem.c('encryption', {required: 1});
  11996. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  11997. crypto.forEach(function(line) {
  11998. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  11999. });
  12000. elem.up(); // end of encryption
  12001. }
  12002. if (ssrc) {
  12003. // new style mapping
  12004. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12005. // FIXME: group by ssrc and support multiple different ssrcs
  12006. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  12007. if(ssrclines.length > 0) {
  12008. ssrclines.forEach(function (line) {
  12009. idx = line.indexOf(' ');
  12010. var linessrc = line.substr(0, idx).substr(7);
  12011. if (linessrc != ssrc) {
  12012. elem.up();
  12013. ssrc = linessrc;
  12014. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12015. }
  12016. var kv = line.substr(idx + 1);
  12017. elem.c('parameter');
  12018. if (kv.indexOf(':') == -1) {
  12019. elem.attrs({ name: kv });
  12020. } else {
  12021. elem.attrs({ name: kv.split(':', 2)[0] });
  12022. elem.attrs({ value: kv.split(':', 2)[1] });
  12023. }
  12024. elem.up();
  12025. });
  12026. elem.up();
  12027. }
  12028. else
  12029. {
  12030. elem.up();
  12031. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12032. elem.c('parameter');
  12033. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  12034. elem.up();
  12035. var msid = null;
  12036. if(mline.media == "audio")
  12037. {
  12038. msid = APP.RTC.localAudio.getId();
  12039. }
  12040. else
  12041. {
  12042. msid = APP.RTC.localVideo.getId();
  12043. }
  12044. if(msid != null)
  12045. {
  12046. msid = msid.replace(/[\{,\}]/g,"");
  12047. elem.c('parameter');
  12048. elem.attrs({name: "msid", value:msid});
  12049. elem.up();
  12050. elem.c('parameter');
  12051. elem.attrs({name: "mslabel", value:msid});
  12052. elem.up();
  12053. elem.c('parameter');
  12054. elem.attrs({name: "label", value:msid});
  12055. elem.up();
  12056. elem.up();
  12057. }
  12058. }
  12059. // XEP-0339 handle ssrc-group attributes
  12060. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  12061. ssrc_group_lines.forEach(function(line) {
  12062. idx = line.indexOf(' ');
  12063. var semantics = line.substr(0, idx).substr(13);
  12064. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12065. if (ssrcs.length != 0) {
  12066. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12067. ssrcs.forEach(function(ssrc) {
  12068. elem.c('source', { ssrc: ssrc })
  12069. .up();
  12070. });
  12071. elem.up();
  12072. }
  12073. });
  12074. }
  12075. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  12076. elem.c('rtcp-mux').up();
  12077. }
  12078. // XEP-0293 -- map a=rtcp-fb:*
  12079. this.RtcpFbToJingle(i, elem, '*');
  12080. // XEP-0294
  12081. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  12082. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  12083. for (j = 0; j < lines.length; j++) {
  12084. tmp = SDPUtil.parse_extmap(lines[j]);
  12085. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  12086. uri: tmp.uri,
  12087. id: tmp.value });
  12088. if (tmp.hasOwnProperty('direction')) {
  12089. switch (tmp.direction) {
  12090. case 'sendonly':
  12091. elem.attrs({senders: 'responder'});
  12092. break;
  12093. case 'recvonly':
  12094. elem.attrs({senders: 'initiator'});
  12095. break;
  12096. case 'sendrecv':
  12097. elem.attrs({senders: 'both'});
  12098. break;
  12099. case 'inactive':
  12100. elem.attrs({senders: 'none'});
  12101. break;
  12102. }
  12103. }
  12104. // TODO: handle params
  12105. elem.up();
  12106. }
  12107. }
  12108. elem.up(); // end of description
  12109. }
  12110. // map ice-ufrag/pwd, dtls fingerprint, candidates
  12111. this.TransportToJingle(i, elem);
  12112. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  12113. elem.attrs({senders: 'both'});
  12114. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  12115. elem.attrs({senders: 'initiator'});
  12116. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  12117. elem.attrs({senders: 'responder'});
  12118. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  12119. elem.attrs({senders: 'none'});
  12120. }
  12121. if (mline.port == '0') {
  12122. // estos hack to reject an m-line
  12123. elem.attrs({senders: 'rejected'});
  12124. }
  12125. elem.up(); // end of content
  12126. }
  12127. elem.up();
  12128. return elem;
  12129. };
  12130. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  12131. var i = mediaindex;
  12132. var tmp;
  12133. var self = this;
  12134. elem.c('transport');
  12135. // XEP-0343 DTLS/SCTP
  12136. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  12137. {
  12138. var sctpmap = SDPUtil.find_line(
  12139. this.media[i], 'a=sctpmap:', self.session);
  12140. if (sctpmap)
  12141. {
  12142. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  12143. elem.c('sctpmap',
  12144. {
  12145. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  12146. number: sctpAttrs[0], /* SCTP port */
  12147. protocol: sctpAttrs[1], /* protocol */
  12148. });
  12149. // Optional stream count attribute
  12150. if (sctpAttrs.length > 2)
  12151. elem.attrs({ streams: sctpAttrs[2]});
  12152. elem.up();
  12153. }
  12154. }
  12155. // XEP-0320
  12156. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  12157. fingerprints.forEach(function(line) {
  12158. tmp = SDPUtil.parse_fingerprint(line);
  12159. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  12160. elem.c('fingerprint').t(tmp.fingerprint);
  12161. delete tmp.fingerprint;
  12162. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  12163. if (line) {
  12164. tmp.setup = line.substr(8);
  12165. }
  12166. elem.attrs(tmp);
  12167. elem.up(); // end of fingerprint
  12168. });
  12169. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  12170. if (tmp) {
  12171. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12172. elem.attrs(tmp);
  12173. // XEP-0176
  12174. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  12175. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  12176. lines.forEach(function (line) {
  12177. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  12178. });
  12179. }
  12180. }
  12181. elem.up(); // end of transport
  12182. }
  12183. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  12184. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  12185. lines.forEach(function (line) {
  12186. var tmp = SDPUtil.parse_rtcpfb(line);
  12187. if (tmp.type == 'trr-int') {
  12188. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  12189. elem.up();
  12190. } else {
  12191. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  12192. if (tmp.params.length > 0) {
  12193. elem.attrs({'subtype': tmp.params[0]});
  12194. }
  12195. elem.up();
  12196. }
  12197. });
  12198. };
  12199. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  12200. var media = '';
  12201. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12202. if (tmp.length) {
  12203. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  12204. if (tmp.attr('value')) {
  12205. media += tmp.attr('value');
  12206. } else {
  12207. media += '0';
  12208. }
  12209. media += '\r\n';
  12210. }
  12211. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12212. tmp.each(function () {
  12213. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  12214. if ($(this).attr('subtype')) {
  12215. media += ' ' + $(this).attr('subtype');
  12216. }
  12217. media += '\r\n';
  12218. });
  12219. return media;
  12220. };
  12221. // construct an SDP from a jingle stanza
  12222. SDP.prototype.fromJingle = function (jingle) {
  12223. var self = this;
  12224. this.raw = 'v=0\r\n' +
  12225. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12226. 's=-\r\n' +
  12227. 't=0 0\r\n';
  12228. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  12229. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  12230. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  12231. var contents = $(group).find('>content').map(function (idx, content) {
  12232. return content.getAttribute('name');
  12233. }).get();
  12234. if (contents.length > 0) {
  12235. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  12236. }
  12237. });
  12238. }
  12239. this.session = this.raw;
  12240. jingle.find('>content').each(function () {
  12241. var m = self.jingle2media($(this));
  12242. self.media.push(m);
  12243. });
  12244. // reconstruct msid-semantic -- apparently not necessary
  12245. /*
  12246. var msid = SDPUtil.parse_ssrc(this.raw);
  12247. if (msid.hasOwnProperty('mslabel')) {
  12248. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  12249. }
  12250. */
  12251. this.raw = this.session + this.media.join('');
  12252. };
  12253. // translate a jingle content element into an an SDP media part
  12254. SDP.prototype.jingle2media = function (content) {
  12255. var media = '',
  12256. desc = content.find('description'),
  12257. ssrc = desc.attr('ssrc'),
  12258. self = this,
  12259. tmp;
  12260. var sctp = content.find(
  12261. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  12262. tmp = { media: desc.attr('media') };
  12263. tmp.port = '1';
  12264. if (content.attr('senders') == 'rejected') {
  12265. // estos hack to reject an m-line.
  12266. tmp.port = '0';
  12267. }
  12268. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  12269. if (sctp.length)
  12270. tmp.proto = 'DTLS/SCTP';
  12271. else
  12272. tmp.proto = 'RTP/SAVPF';
  12273. } else {
  12274. tmp.proto = 'RTP/AVPF';
  12275. }
  12276. if (!sctp.length)
  12277. {
  12278. tmp.fmt = desc.find('payload-type').map(
  12279. function () { return this.getAttribute('id'); }).get();
  12280. media += SDPUtil.build_mline(tmp) + '\r\n';
  12281. }
  12282. else
  12283. {
  12284. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  12285. media += 'a=sctpmap:' + sctp.attr('number') +
  12286. ' ' + sctp.attr('protocol');
  12287. var streamCount = sctp.attr('streams');
  12288. if (streamCount)
  12289. media += ' ' + streamCount + '\r\n';
  12290. else
  12291. media += '\r\n';
  12292. }
  12293. media += 'c=IN IP4 0.0.0.0\r\n';
  12294. if (!sctp.length)
  12295. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  12296. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  12297. if (tmp.length) {
  12298. if (tmp.attr('ufrag')) {
  12299. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  12300. }
  12301. if (tmp.attr('pwd')) {
  12302. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  12303. }
  12304. tmp.find('>fingerprint').each(function () {
  12305. // FIXME: check namespace at some point
  12306. media += 'a=fingerprint:' + this.getAttribute('hash');
  12307. media += ' ' + $(this).text();
  12308. media += '\r\n';
  12309. if (this.getAttribute('setup')) {
  12310. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  12311. }
  12312. });
  12313. }
  12314. switch (content.attr('senders')) {
  12315. case 'initiator':
  12316. media += 'a=sendonly\r\n';
  12317. break;
  12318. case 'responder':
  12319. media += 'a=recvonly\r\n';
  12320. break;
  12321. case 'none':
  12322. media += 'a=inactive\r\n';
  12323. break;
  12324. case 'both':
  12325. media += 'a=sendrecv\r\n';
  12326. break;
  12327. }
  12328. media += 'a=mid:' + content.attr('name') + '\r\n';
  12329. // <description><rtcp-mux/></description>
  12330. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  12331. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  12332. if (desc.find('rtcp-mux').length) {
  12333. media += 'a=rtcp-mux\r\n';
  12334. }
  12335. if (desc.find('encryption').length) {
  12336. desc.find('encryption>crypto').each(function () {
  12337. media += 'a=crypto:' + this.getAttribute('tag');
  12338. media += ' ' + this.getAttribute('crypto-suite');
  12339. media += ' ' + this.getAttribute('key-params');
  12340. if (this.getAttribute('session-params')) {
  12341. media += ' ' + this.getAttribute('session-params');
  12342. }
  12343. media += '\r\n';
  12344. });
  12345. }
  12346. desc.find('payload-type').each(function () {
  12347. media += SDPUtil.build_rtpmap(this) + '\r\n';
  12348. if ($(this).find('>parameter').length) {
  12349. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  12350. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  12351. media += '\r\n';
  12352. }
  12353. // xep-0293
  12354. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  12355. });
  12356. // xep-0293
  12357. media += self.RtcpFbFromJingle(desc, '*');
  12358. // xep-0294
  12359. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  12360. tmp.each(function () {
  12361. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  12362. });
  12363. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  12364. media += SDPUtil.candidateFromJingle(this);
  12365. });
  12366. // XEP-0339 handle ssrc-group attributes
  12367. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12368. var semantics = this.getAttribute('semantics');
  12369. var ssrcs = $(this).find('>source').map(function() {
  12370. return this.getAttribute('ssrc');
  12371. }).get();
  12372. if (ssrcs.length != 0) {
  12373. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12374. }
  12375. });
  12376. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12377. tmp.each(function () {
  12378. var ssrc = this.getAttribute('ssrc');
  12379. $(this).find('>parameter').each(function () {
  12380. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  12381. if (this.getAttribute('value') && this.getAttribute('value').length)
  12382. media += ':' + this.getAttribute('value');
  12383. media += '\r\n';
  12384. });
  12385. });
  12386. return media;
  12387. };
  12388. module.exports = SDP;
  12389. },{"./SDPUtil":51}],50:[function(require,module,exports){
  12390. function SDPDiffer(mySDP, otherSDP) {
  12391. this.mySDP = mySDP;
  12392. this.otherSDP = otherSDP;
  12393. }
  12394. /**
  12395. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  12396. * @param otherSdp the other SDP to check ssrc with.
  12397. */
  12398. SDPDiffer.prototype.getNewMedia = function() {
  12399. // this could be useful in Array.prototype.
  12400. function arrayEquals(array) {
  12401. // if the other array is a falsy value, return
  12402. if (!array)
  12403. return false;
  12404. // compare lengths - can save a lot of time
  12405. if (this.length != array.length)
  12406. return false;
  12407. for (var i = 0, l=this.length; i < l; i++) {
  12408. // Check if we have nested arrays
  12409. if (this[i] instanceof Array && array[i] instanceof Array) {
  12410. // recurse into the nested arrays
  12411. if (!this[i].equals(array[i]))
  12412. return false;
  12413. }
  12414. else if (this[i] != array[i]) {
  12415. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12416. return false;
  12417. }
  12418. }
  12419. return true;
  12420. }
  12421. var myMedias = this.mySDP.getMediaSsrcMap();
  12422. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12423. var newMedia = {};
  12424. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12425. var myMedia = myMedias[othersMediaIdx];
  12426. var othersMedia = othersMedias[othersMediaIdx];
  12427. if(!myMedia && othersMedia) {
  12428. // Add whole channel
  12429. newMedia[othersMediaIdx] = othersMedia;
  12430. return;
  12431. }
  12432. // Look for new ssrcs accross the channel
  12433. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12434. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12435. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12436. if(!newMedia[othersMediaIdx]){
  12437. newMedia[othersMediaIdx] = {
  12438. mediaindex: othersMedia.mediaindex,
  12439. mid: othersMedia.mid,
  12440. ssrcs: {},
  12441. ssrcGroups: []
  12442. };
  12443. }
  12444. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12445. }
  12446. });
  12447. // Look for new ssrc groups across the channels
  12448. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12449. // try to match the other ssrc-group with an ssrc-group of ours
  12450. var matched = false;
  12451. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12452. var mySsrcGroup = myMedia.ssrcGroups[i];
  12453. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12454. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12455. matched = true;
  12456. break;
  12457. }
  12458. }
  12459. if (!matched) {
  12460. // Allocate channel if we've found an ssrc-group that doesn't
  12461. // exist in our channel
  12462. if(!newMedia[othersMediaIdx]){
  12463. newMedia[othersMediaIdx] = {
  12464. mediaindex: othersMedia.mediaindex,
  12465. mid: othersMedia.mid,
  12466. ssrcs: {},
  12467. ssrcGroups: []
  12468. };
  12469. }
  12470. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12471. }
  12472. });
  12473. });
  12474. return newMedia;
  12475. };
  12476. /**
  12477. * Sends SSRC update IQ.
  12478. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12479. * @param sid session identifier that will be put into the IQ.
  12480. * @param initiator initiator identifier.
  12481. * @param toJid destination Jid
  12482. * @param isAdd indicates if this is remove or add operation.
  12483. */
  12484. SDPDiffer.prototype.toJingle = function(modify) {
  12485. var sdpMediaSsrcs = this.getNewMedia();
  12486. var self = this;
  12487. // FIXME: only announce video ssrcs since we mix audio and dont need
  12488. // the audio ssrcs therefore
  12489. var modified = false;
  12490. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12491. modified = true;
  12492. var media = sdpMediaSsrcs[mediaindex];
  12493. modify.c('content', {name: media.mid});
  12494. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12495. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12496. // generate sources from lines
  12497. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12498. var mediaSsrc = media.ssrcs[ssrcNum];
  12499. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12500. modify.attrs({ssrc: mediaSsrc.ssrc});
  12501. // iterate over ssrc lines
  12502. mediaSsrc.lines.forEach(function (line) {
  12503. var idx = line.indexOf(' ');
  12504. var kv = line.substr(idx + 1);
  12505. modify.c('parameter');
  12506. if (kv.indexOf(':') == -1) {
  12507. modify.attrs({ name: kv });
  12508. } else {
  12509. modify.attrs({ name: kv.split(':', 2)[0] });
  12510. modify.attrs({ value: kv.split(':', 2)[1] });
  12511. }
  12512. modify.up(); // end of parameter
  12513. });
  12514. modify.up(); // end of source
  12515. });
  12516. // generate source groups from lines
  12517. media.ssrcGroups.forEach(function(ssrcGroup) {
  12518. if (ssrcGroup.ssrcs.length != 0) {
  12519. modify.c('ssrc-group', {
  12520. semantics: ssrcGroup.semantics,
  12521. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12522. });
  12523. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12524. modify.c('source', { ssrc: ssrc })
  12525. .up(); // end of source
  12526. });
  12527. modify.up(); // end of ssrc-group
  12528. }
  12529. });
  12530. modify.up(); // end of description
  12531. modify.up(); // end of content
  12532. });
  12533. return modified;
  12534. };
  12535. module.exports = SDPDiffer;
  12536. },{}],51:[function(require,module,exports){
  12537. SDPUtil = {
  12538. iceparams: function (mediadesc, sessiondesc) {
  12539. var data = null;
  12540. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  12541. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  12542. data = {
  12543. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  12544. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  12545. };
  12546. }
  12547. return data;
  12548. },
  12549. parse_iceufrag: function (line) {
  12550. return line.substring(12);
  12551. },
  12552. build_iceufrag: function (frag) {
  12553. return 'a=ice-ufrag:' + frag;
  12554. },
  12555. parse_icepwd: function (line) {
  12556. return line.substring(10);
  12557. },
  12558. build_icepwd: function (pwd) {
  12559. return 'a=ice-pwd:' + pwd;
  12560. },
  12561. parse_mid: function (line) {
  12562. return line.substring(6);
  12563. },
  12564. parse_mline: function (line) {
  12565. var parts = line.substring(2).split(' '),
  12566. data = {};
  12567. data.media = parts.shift();
  12568. data.port = parts.shift();
  12569. data.proto = parts.shift();
  12570. if (parts[parts.length - 1] === '') { // trailing whitespace
  12571. parts.pop();
  12572. }
  12573. data.fmt = parts;
  12574. return data;
  12575. },
  12576. build_mline: function (mline) {
  12577. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  12578. },
  12579. parse_rtpmap: function (line) {
  12580. var parts = line.substring(9).split(' '),
  12581. data = {};
  12582. data.id = parts.shift();
  12583. parts = parts[0].split('/');
  12584. data.name = parts.shift();
  12585. data.clockrate = parts.shift();
  12586. data.channels = parts.length ? parts.shift() : '1';
  12587. return data;
  12588. },
  12589. /**
  12590. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  12591. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  12592. * @returns [SCTP port number, protocol, streams]
  12593. */
  12594. parse_sctpmap: function (line)
  12595. {
  12596. var parts = line.substring(10).split(' ');
  12597. var sctpPort = parts[0];
  12598. var protocol = parts[1];
  12599. // Stream count is optional
  12600. var streamCount = parts.length > 2 ? parts[2] : null;
  12601. return [sctpPort, protocol, streamCount];// SCTP port
  12602. },
  12603. build_rtpmap: function (el) {
  12604. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  12605. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  12606. line += '/' + el.getAttribute('channels');
  12607. }
  12608. return line;
  12609. },
  12610. parse_crypto: function (line) {
  12611. var parts = line.substring(9).split(' '),
  12612. data = {};
  12613. data.tag = parts.shift();
  12614. data['crypto-suite'] = parts.shift();
  12615. data['key-params'] = parts.shift();
  12616. if (parts.length) {
  12617. data['session-params'] = parts.join(' ');
  12618. }
  12619. return data;
  12620. },
  12621. parse_fingerprint: function (line) { // RFC 4572
  12622. var parts = line.substring(14).split(' '),
  12623. data = {};
  12624. data.hash = parts.shift();
  12625. data.fingerprint = parts.shift();
  12626. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  12627. return data;
  12628. },
  12629. parse_fmtp: function (line) {
  12630. var parts = line.split(' '),
  12631. i, key, value,
  12632. data = [];
  12633. parts.shift();
  12634. parts = parts.join(' ').split(';');
  12635. for (i = 0; i < parts.length; i++) {
  12636. key = parts[i].split('=')[0];
  12637. while (key.length && key[0] == ' ') {
  12638. key = key.substring(1);
  12639. }
  12640. value = parts[i].split('=')[1];
  12641. if (key && value) {
  12642. data.push({name: key, value: value});
  12643. } else if (key) {
  12644. // rfc 4733 (DTMF) style stuff
  12645. data.push({name: '', value: key});
  12646. }
  12647. }
  12648. return data;
  12649. },
  12650. parse_icecandidate: function (line) {
  12651. var candidate = {},
  12652. elems = line.split(' ');
  12653. candidate.foundation = elems[0].substring(12);
  12654. candidate.component = elems[1];
  12655. candidate.protocol = elems[2].toLowerCase();
  12656. candidate.priority = elems[3];
  12657. candidate.ip = elems[4];
  12658. candidate.port = elems[5];
  12659. // elems[6] => "typ"
  12660. candidate.type = elems[7];
  12661. candidate.generation = 0; // default value, may be overwritten below
  12662. for (var i = 8; i < elems.length; i += 2) {
  12663. switch (elems[i]) {
  12664. case 'raddr':
  12665. candidate['rel-addr'] = elems[i + 1];
  12666. break;
  12667. case 'rport':
  12668. candidate['rel-port'] = elems[i + 1];
  12669. break;
  12670. case 'generation':
  12671. candidate.generation = elems[i + 1];
  12672. break;
  12673. case 'tcptype':
  12674. candidate.tcptype = elems[i + 1];
  12675. break;
  12676. default: // TODO
  12677. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12678. }
  12679. }
  12680. candidate.network = '1';
  12681. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12682. return candidate;
  12683. },
  12684. build_icecandidate: function (cand) {
  12685. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  12686. line += ' ';
  12687. switch (cand.type) {
  12688. case 'srflx':
  12689. case 'prflx':
  12690. case 'relay':
  12691. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  12692. line += 'raddr';
  12693. line += ' ';
  12694. line += cand['rel-addr'];
  12695. line += ' ';
  12696. line += 'rport';
  12697. line += ' ';
  12698. line += cand['rel-port'];
  12699. line += ' ';
  12700. }
  12701. break;
  12702. }
  12703. if (cand.hasOwnAttribute('tcptype')) {
  12704. line += 'tcptype';
  12705. line += ' ';
  12706. line += cand.tcptype;
  12707. line += ' ';
  12708. }
  12709. line += 'generation';
  12710. line += ' ';
  12711. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  12712. return line;
  12713. },
  12714. parse_ssrc: function (desc) {
  12715. // proprietary mapping of a=ssrc lines
  12716. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  12717. // and parse according to that
  12718. var lines = desc.split('\r\n'),
  12719. data = {};
  12720. for (var i = 0; i < lines.length; i++) {
  12721. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  12722. var idx = lines[i].indexOf(' ');
  12723. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  12724. }
  12725. }
  12726. return data;
  12727. },
  12728. parse_rtcpfb: function (line) {
  12729. var parts = line.substr(10).split(' ');
  12730. var data = {};
  12731. data.pt = parts.shift();
  12732. data.type = parts.shift();
  12733. data.params = parts;
  12734. return data;
  12735. },
  12736. parse_extmap: function (line) {
  12737. var parts = line.substr(9).split(' ');
  12738. var data = {};
  12739. data.value = parts.shift();
  12740. if (data.value.indexOf('/') != -1) {
  12741. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  12742. data.value = data.value.substr(0, data.value.indexOf('/'));
  12743. } else {
  12744. data.direction = 'both';
  12745. }
  12746. data.uri = parts.shift();
  12747. data.params = parts;
  12748. return data;
  12749. },
  12750. find_line: function (haystack, needle, sessionpart) {
  12751. var lines = haystack.split('\r\n');
  12752. for (var i = 0; i < lines.length; i++) {
  12753. if (lines[i].substring(0, needle.length) == needle) {
  12754. return lines[i];
  12755. }
  12756. }
  12757. if (!sessionpart) {
  12758. return false;
  12759. }
  12760. // search session part
  12761. lines = sessionpart.split('\r\n');
  12762. for (var j = 0; j < lines.length; j++) {
  12763. if (lines[j].substring(0, needle.length) == needle) {
  12764. return lines[j];
  12765. }
  12766. }
  12767. return false;
  12768. },
  12769. find_lines: function (haystack, needle, sessionpart) {
  12770. var lines = haystack.split('\r\n'),
  12771. needles = [];
  12772. for (var i = 0; i < lines.length; i++) {
  12773. if (lines[i].substring(0, needle.length) == needle)
  12774. needles.push(lines[i]);
  12775. }
  12776. if (needles.length || !sessionpart) {
  12777. return needles;
  12778. }
  12779. // search session part
  12780. lines = sessionpart.split('\r\n');
  12781. for (var j = 0; j < lines.length; j++) {
  12782. if (lines[j].substring(0, needle.length) == needle) {
  12783. needles.push(lines[j]);
  12784. }
  12785. }
  12786. return needles;
  12787. },
  12788. candidateToJingle: function (line) {
  12789. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  12790. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  12791. if (line.indexOf('candidate:') === 0) {
  12792. line = 'a=' + line;
  12793. } else if (line.substring(0, 12) != 'a=candidate:') {
  12794. console.log('parseCandidate called with a line that is not a candidate line');
  12795. console.log(line);
  12796. return null;
  12797. }
  12798. if (line.substring(line.length - 2) == '\r\n') // chomp it
  12799. line = line.substring(0, line.length - 2);
  12800. var candidate = {},
  12801. elems = line.split(' '),
  12802. i;
  12803. if (elems[6] != 'typ') {
  12804. console.log('did not find typ in the right place');
  12805. console.log(line);
  12806. return null;
  12807. }
  12808. candidate.foundation = elems[0].substring(12);
  12809. candidate.component = elems[1];
  12810. candidate.protocol = elems[2].toLowerCase();
  12811. candidate.priority = elems[3];
  12812. candidate.ip = elems[4];
  12813. candidate.port = elems[5];
  12814. // elems[6] => "typ"
  12815. candidate.type = elems[7];
  12816. candidate.generation = '0'; // default, may be overwritten below
  12817. for (i = 8; i < elems.length; i += 2) {
  12818. switch (elems[i]) {
  12819. case 'raddr':
  12820. candidate['rel-addr'] = elems[i + 1];
  12821. break;
  12822. case 'rport':
  12823. candidate['rel-port'] = elems[i + 1];
  12824. break;
  12825. case 'generation':
  12826. candidate.generation = elems[i + 1];
  12827. break;
  12828. case 'tcptype':
  12829. candidate.tcptype = elems[i + 1];
  12830. break;
  12831. default: // TODO
  12832. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12833. }
  12834. }
  12835. candidate.network = '1';
  12836. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12837. return candidate;
  12838. },
  12839. candidateFromJingle: function (cand) {
  12840. var line = 'a=candidate:';
  12841. line += cand.getAttribute('foundation');
  12842. line += ' ';
  12843. line += cand.getAttribute('component');
  12844. line += ' ';
  12845. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  12846. line += ' ';
  12847. line += cand.getAttribute('priority');
  12848. line += ' ';
  12849. line += cand.getAttribute('ip');
  12850. line += ' ';
  12851. line += cand.getAttribute('port');
  12852. line += ' ';
  12853. line += 'typ';
  12854. line += ' ' + cand.getAttribute('type');
  12855. line += ' ';
  12856. switch (cand.getAttribute('type')) {
  12857. case 'srflx':
  12858. case 'prflx':
  12859. case 'relay':
  12860. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  12861. line += 'raddr';
  12862. line += ' ';
  12863. line += cand.getAttribute('rel-addr');
  12864. line += ' ';
  12865. line += 'rport';
  12866. line += ' ';
  12867. line += cand.getAttribute('rel-port');
  12868. line += ' ';
  12869. }
  12870. break;
  12871. }
  12872. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  12873. line += 'tcptype';
  12874. line += ' ';
  12875. line += cand.getAttribute('tcptype');
  12876. line += ' ';
  12877. }
  12878. line += 'generation';
  12879. line += ' ';
  12880. line += cand.getAttribute('generation') || '0';
  12881. return line + '\r\n';
  12882. }
  12883. };
  12884. module.exports = SDPUtil;
  12885. },{}],52:[function(require,module,exports){
  12886. function TraceablePeerConnection(ice_config, constraints) {
  12887. var self = this;
  12888. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  12889. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  12890. this.updateLog = [];
  12891. this.stats = {};
  12892. this.statsinterval = null;
  12893. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  12894. var Interop = require('sdp-interop').Interop;
  12895. this.interop = new Interop();
  12896. // override as desired
  12897. this.trace = function (what, info) {
  12898. //console.warn('WTRACE', what, info);
  12899. self.updateLog.push({
  12900. time: new Date(),
  12901. type: what,
  12902. value: info || ""
  12903. });
  12904. };
  12905. this.onicecandidate = null;
  12906. this.peerconnection.onicecandidate = function (event) {
  12907. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  12908. if (self.onicecandidate !== null) {
  12909. self.onicecandidate(event);
  12910. }
  12911. };
  12912. this.onaddstream = null;
  12913. this.peerconnection.onaddstream = function (event) {
  12914. self.trace('onaddstream', event.stream.id);
  12915. if (self.onaddstream !== null) {
  12916. self.onaddstream(event);
  12917. }
  12918. };
  12919. this.onremovestream = null;
  12920. this.peerconnection.onremovestream = function (event) {
  12921. self.trace('onremovestream', event.stream.id);
  12922. if (self.onremovestream !== null) {
  12923. self.onremovestream(event);
  12924. }
  12925. };
  12926. this.onsignalingstatechange = null;
  12927. this.peerconnection.onsignalingstatechange = function (event) {
  12928. self.trace('onsignalingstatechange', self.signalingState);
  12929. if (self.onsignalingstatechange !== null) {
  12930. self.onsignalingstatechange(event);
  12931. }
  12932. };
  12933. this.oniceconnectionstatechange = null;
  12934. this.peerconnection.oniceconnectionstatechange = function (event) {
  12935. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12936. if (self.oniceconnectionstatechange !== null) {
  12937. self.oniceconnectionstatechange(event);
  12938. }
  12939. };
  12940. this.onnegotiationneeded = null;
  12941. this.peerconnection.onnegotiationneeded = function (event) {
  12942. self.trace('onnegotiationneeded');
  12943. if (self.onnegotiationneeded !== null) {
  12944. self.onnegotiationneeded(event);
  12945. }
  12946. };
  12947. self.ondatachannel = null;
  12948. this.peerconnection.ondatachannel = function (event) {
  12949. self.trace('ondatachannel', event);
  12950. if (self.ondatachannel !== null) {
  12951. self.ondatachannel(event);
  12952. }
  12953. };
  12954. if (!navigator.mozGetUserMedia && this.maxstats) {
  12955. this.statsinterval = window.setInterval(function() {
  12956. self.peerconnection.getStats(function(stats) {
  12957. var results = stats.result();
  12958. for (var i = 0; i < results.length; ++i) {
  12959. //console.log(results[i].type, results[i].id, results[i].names())
  12960. var now = new Date();
  12961. results[i].names().forEach(function (name) {
  12962. var id = results[i].id + '-' + name;
  12963. if (!self.stats[id]) {
  12964. self.stats[id] = {
  12965. startTime: now,
  12966. endTime: now,
  12967. values: [],
  12968. times: []
  12969. };
  12970. }
  12971. self.stats[id].values.push(results[i].stat(name));
  12972. self.stats[id].times.push(now.getTime());
  12973. if (self.stats[id].values.length > self.maxstats) {
  12974. self.stats[id].values.shift();
  12975. self.stats[id].times.shift();
  12976. }
  12977. self.stats[id].endTime = now;
  12978. });
  12979. }
  12980. });
  12981. }, 1000);
  12982. }
  12983. };
  12984. dumpSDP = function(description) {
  12985. if (typeof description === 'undefined' || description == null) {
  12986. return '';
  12987. }
  12988. return 'type: ' + description.type + '\r\n' + description.sdp;
  12989. };
  12990. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  12991. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  12992. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  12993. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  12994. this.trace('getLocalDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.localDescription));
  12995. // if we're running on FF, transform to Plan B first.
  12996. var desc = this.peerconnection.localDescription;
  12997. if (navigator.mozGetUserMedia) {
  12998. desc = this.interop.toPlanB(desc);
  12999. } else {
  13000. desc = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  13001. }
  13002. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  13003. return desc;
  13004. });
  13005. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  13006. this.trace('getRemoteDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.remoteDescription));
  13007. // if we're running on FF, transform to Plan B first.
  13008. var desc = this.peerconnection.remoteDescription;
  13009. if (navigator.mozGetUserMedia) {
  13010. desc = this.interop.toPlanB(desc);
  13011. } else {
  13012. desc = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  13013. }
  13014. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  13015. return desc;
  13016. });
  13017. }
  13018. TraceablePeerConnection.prototype.addStream = function (stream) {
  13019. this.trace('addStream', stream.id);
  13020. APP.simulcast.resetSender();
  13021. try
  13022. {
  13023. this.peerconnection.addStream(stream);
  13024. }
  13025. catch (e)
  13026. {
  13027. console.error(e);
  13028. return;
  13029. }
  13030. };
  13031. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  13032. this.trace('removeStream', stream.id);
  13033. APP.simulcast.resetSender();
  13034. if(stopStreams) {
  13035. stream.getAudioTracks().forEach(function (track) {
  13036. track.stop();
  13037. });
  13038. stream.getVideoTracks().forEach(function (track) {
  13039. track.stop();
  13040. });
  13041. }
  13042. try {
  13043. // FF doesn't support this yet.
  13044. this.peerconnection.removeStream(stream);
  13045. } catch (e) {
  13046. console.error(e);
  13047. }
  13048. };
  13049. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  13050. this.trace('createDataChannel', label, opts);
  13051. return this.peerconnection.createDataChannel(label, opts);
  13052. };
  13053. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  13054. this.trace('setLocalDescription::preTransform (Plan B)', dumpSDP(description));
  13055. // if we're running on FF, transform to Plan A first.
  13056. if (navigator.mozGetUserMedia) {
  13057. description = this.interop.toPlanA(description);
  13058. } else {
  13059. description = APP.simulcast.transformLocalDescription(description);
  13060. }
  13061. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  13062. var self = this;
  13063. this.peerconnection.setLocalDescription(description,
  13064. function () {
  13065. self.trace('setLocalDescriptionOnSuccess');
  13066. successCallback();
  13067. },
  13068. function (err) {
  13069. self.trace('setLocalDescriptionOnFailure', err);
  13070. failureCallback(err);
  13071. }
  13072. );
  13073. /*
  13074. if (this.statsinterval === null && this.maxstats > 0) {
  13075. // start gathering stats
  13076. }
  13077. */
  13078. };
  13079. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  13080. this.trace('setRemoteDescription::preTransform (Plan B)', dumpSDP(description));
  13081. // if we're running on FF, transform to Plan A first.
  13082. if (navigator.mozGetUserMedia) {
  13083. description = this.interop.toPlanA(description);
  13084. }
  13085. else {
  13086. description = APP.simulcast.transformRemoteDescription(description);
  13087. }
  13088. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  13089. var self = this;
  13090. this.peerconnection.setRemoteDescription(description,
  13091. function () {
  13092. self.trace('setRemoteDescriptionOnSuccess');
  13093. successCallback();
  13094. },
  13095. function (err) {
  13096. self.trace('setRemoteDescriptionOnFailure', err);
  13097. failureCallback(err);
  13098. }
  13099. );
  13100. /*
  13101. if (this.statsinterval === null && this.maxstats > 0) {
  13102. // start gathering stats
  13103. }
  13104. */
  13105. };
  13106. TraceablePeerConnection.prototype.close = function () {
  13107. this.trace('stop');
  13108. if (this.statsinterval !== null) {
  13109. window.clearInterval(this.statsinterval);
  13110. this.statsinterval = null;
  13111. }
  13112. this.peerconnection.close();
  13113. };
  13114. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  13115. var self = this;
  13116. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  13117. this.peerconnection.createOffer(
  13118. function (offer) {
  13119. self.trace('createOfferOnSuccess::preTransform (Plan A)', dumpSDP(offer));
  13120. // if we're running on FF, transform to Plan B first.
  13121. if (navigator.mozGetUserMedia) {
  13122. offer = self.interop.toPlanB(offer);
  13123. }
  13124. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  13125. successCallback(offer);
  13126. },
  13127. function(err) {
  13128. self.trace('createOfferOnFailure', err);
  13129. failureCallback(err);
  13130. },
  13131. constraints
  13132. );
  13133. };
  13134. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  13135. var self = this;
  13136. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  13137. this.peerconnection.createAnswer(
  13138. function (answer) {
  13139. self.trace('createAnswerOnSuccess::preTransfom (Plan A)', dumpSDP(answer));
  13140. // if we're running on FF, transform to Plan A first.
  13141. if (navigator.mozGetUserMedia) {
  13142. answer = self.interop.toPlanB(answer);
  13143. } else {
  13144. answer = APP.simulcast.transformAnswer(answer);
  13145. }
  13146. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  13147. successCallback(answer);
  13148. },
  13149. function(err) {
  13150. self.trace('createAnswerOnFailure', err);
  13151. failureCallback(err);
  13152. },
  13153. constraints
  13154. );
  13155. };
  13156. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  13157. var self = this;
  13158. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  13159. this.peerconnection.addIceCandidate(candidate);
  13160. /* maybe later
  13161. this.peerconnection.addIceCandidate(candidate,
  13162. function () {
  13163. self.trace('addIceCandidateOnSuccess');
  13164. successCallback();
  13165. },
  13166. function (err) {
  13167. self.trace('addIceCandidateOnFailure', err);
  13168. failureCallback(err);
  13169. }
  13170. );
  13171. */
  13172. };
  13173. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  13174. if (navigator.mozGetUserMedia) {
  13175. // ignore for now...
  13176. if(!errback)
  13177. errback = function () {
  13178. }
  13179. this.peerconnection.getStats(null,callback,errback);
  13180. } else {
  13181. this.peerconnection.getStats(callback);
  13182. }
  13183. };
  13184. module.exports = TraceablePeerConnection;
  13185. },{"sdp-interop":80}],53:[function(require,module,exports){
  13186. /* global $, $iq, APP, config, connection, UI, messageHandler,
  13187. roomName, sessionTerminated, Strophe, Util */
  13188. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13189. var Settings = require("../settings/Settings");
  13190. var AuthenticationEvents
  13191. = require("../../service/authentication/AuthenticationEvents");
  13192. /**
  13193. * Contains logic responsible for enabling/disabling functionality available
  13194. * only to moderator users.
  13195. */
  13196. var connection = null;
  13197. var focusUserJid;
  13198. function createExpBackoffTimer(step) {
  13199. var count = 1;
  13200. return function (reset) {
  13201. // Reset call
  13202. if (reset) {
  13203. count = 1;
  13204. return;
  13205. }
  13206. // Calculate next timeout
  13207. var timeout = Math.pow(2, count - 1);
  13208. count += 1;
  13209. return timeout * step;
  13210. };
  13211. }
  13212. var getNextTimeout = createExpBackoffTimer(1000);
  13213. var getNextErrorTimeout = createExpBackoffTimer(1000);
  13214. // External authentication stuff
  13215. var externalAuthEnabled = false;
  13216. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  13217. // it will be enabled automatically if focus detects the component through
  13218. // service discovery.
  13219. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  13220. var eventEmitter = null;
  13221. var Moderator = {
  13222. isModerator: function () {
  13223. return connection && connection.emuc.isModerator();
  13224. },
  13225. isPeerModerator: function (peerJid) {
  13226. return connection &&
  13227. connection.emuc.getMemberRole(peerJid) === 'moderator';
  13228. },
  13229. isExternalAuthEnabled: function () {
  13230. return externalAuthEnabled;
  13231. },
  13232. isSipGatewayEnabled: function () {
  13233. return sipGatewayEnabled;
  13234. },
  13235. setConnection: function (con) {
  13236. connection = con;
  13237. },
  13238. init: function (xmpp, emitter) {
  13239. this.xmppService = xmpp;
  13240. eventEmitter = emitter;
  13241. // Message listener that talks to POPUP window
  13242. function listener(event) {
  13243. if (event.data && event.data.sessionId) {
  13244. if (event.origin !== window.location.origin) {
  13245. console.warn(
  13246. "Ignoring sessionId from different origin: " + event.origin);
  13247. return;
  13248. }
  13249. localStorage.setItem('sessionId', event.data.sessionId);
  13250. // After popup is closed we will authenticate
  13251. }
  13252. }
  13253. // Register
  13254. if (window.addEventListener) {
  13255. window.addEventListener("message", listener, false);
  13256. } else {
  13257. window.attachEvent("onmessage", listener);
  13258. }
  13259. },
  13260. onMucLeft: function (jid) {
  13261. console.info("Someone left is it focus ? " + jid);
  13262. var resource = Strophe.getResourceFromJid(jid);
  13263. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  13264. console.info(
  13265. "Focus has left the room - leaving conference");
  13266. //hangUp();
  13267. // We'd rather reload to have everything re-initialized
  13268. // FIXME: show some message before reload
  13269. location.reload();
  13270. }
  13271. },
  13272. setFocusUserJid: function (focusJid) {
  13273. if (!focusUserJid) {
  13274. focusUserJid = focusJid;
  13275. console.info("Focus jid set to: " + focusUserJid);
  13276. }
  13277. },
  13278. getFocusUserJid: function () {
  13279. return focusUserJid;
  13280. },
  13281. getFocusComponent: function () {
  13282. // Get focus component address
  13283. var focusComponent = config.hosts.focus;
  13284. // If not specified use default: 'focus.domain'
  13285. if (!focusComponent) {
  13286. focusComponent = 'focus.' + config.hosts.domain;
  13287. }
  13288. return focusComponent;
  13289. },
  13290. createConferenceIq: function (roomName) {
  13291. // Generate create conference IQ
  13292. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13293. // Session Id used for authentication
  13294. var sessionId = localStorage.getItem('sessionId');
  13295. var machineUID = Settings.getSettings().uid;
  13296. console.info(
  13297. "Session ID: " + sessionId + " machine UID: " + machineUID);
  13298. elem.c('conference', {
  13299. xmlns: 'http://jitsi.org/protocol/focus',
  13300. room: roomName,
  13301. 'machine-uid': machineUID
  13302. });
  13303. if (sessionId) {
  13304. elem.attrs({ 'session-id': sessionId});
  13305. }
  13306. if (config.hosts.bridge !== undefined) {
  13307. elem.c(
  13308. 'property',
  13309. { name: 'bridge', value: config.hosts.bridge})
  13310. .up();
  13311. }
  13312. // Tell the focus we have Jigasi configured
  13313. if (config.hosts.call_control !== undefined) {
  13314. elem.c(
  13315. 'property',
  13316. { name: 'call_control', value: config.hosts.call_control})
  13317. .up();
  13318. }
  13319. if (config.channelLastN !== undefined) {
  13320. elem.c(
  13321. 'property',
  13322. { name: 'channelLastN', value: config.channelLastN})
  13323. .up();
  13324. }
  13325. if (config.adaptiveLastN !== undefined) {
  13326. elem.c(
  13327. 'property',
  13328. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  13329. .up();
  13330. }
  13331. if (config.adaptiveSimulcast !== undefined) {
  13332. elem.c(
  13333. 'property',
  13334. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  13335. .up();
  13336. }
  13337. if (config.openSctp !== undefined) {
  13338. elem.c(
  13339. 'property',
  13340. { name: 'openSctp', value: config.openSctp})
  13341. .up();
  13342. }
  13343. var roomName = APP.UI.generateRoomName();
  13344. if (typeof roomName !== 'string') roomName = '';
  13345. if (config.enableFirefoxSupport !== undefined && roomName.indexOf('rembson@') === -1) {
  13346. elem.c(
  13347. 'property',
  13348. { name: 'enableFirefoxHacks',
  13349. value: config.enableFirefoxSupport})
  13350. .up();
  13351. }
  13352. elem.up();
  13353. return elem;
  13354. },
  13355. parseSessionId: function (resultIq) {
  13356. var sessionId = $(resultIq).find('conference').attr('session-id');
  13357. if (sessionId) {
  13358. console.info('Received sessionId: ' + sessionId);
  13359. localStorage.setItem('sessionId', sessionId);
  13360. }
  13361. },
  13362. parseConfigOptions: function (resultIq) {
  13363. Moderator.setFocusUserJid(
  13364. $(resultIq).find('conference').attr('focusjid'));
  13365. var authenticationEnabled
  13366. = $(resultIq).find(
  13367. '>conference>property' +
  13368. '[name=\'authentication\'][value=\'true\']').length > 0;
  13369. console.info("Authentication enabled: " + authenticationEnabled);
  13370. externalAuthEnabled
  13371. = $(resultIq).find(
  13372. '>conference>property' +
  13373. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  13374. console.info('External authentication enabled: ' + externalAuthEnabled);
  13375. if (!externalAuthEnabled) {
  13376. // We expect to receive sessionId in 'internal' authentication mode
  13377. Moderator.parseSessionId(resultIq);
  13378. }
  13379. var authIdentity = $(resultIq).find('>conference').attr('identity');
  13380. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  13381. authenticationEnabled, authIdentity);
  13382. // Check if focus has auto-detected Jigasi component(this will be also
  13383. // included if we have passed our host from the config)
  13384. if ($(resultIq).find(
  13385. '>conference>property' +
  13386. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  13387. sipGatewayEnabled = true;
  13388. }
  13389. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  13390. },
  13391. // FIXME: we need to show the fact that we're waiting for the focus
  13392. // to the user(or that focus is not available)
  13393. allocateConferenceFocus: function (roomName, callback) {
  13394. // Try to use focus user JID from the config
  13395. Moderator.setFocusUserJid(config.focusUserJid);
  13396. // Send create conference IQ
  13397. var iq = Moderator.createConferenceIq(roomName);
  13398. var self = this;
  13399. connection.sendIQ(
  13400. iq,
  13401. function (result) {
  13402. // Setup config options
  13403. Moderator.parseConfigOptions(result);
  13404. if ('true' === $(result).find('conference').attr('ready')) {
  13405. // Reset both timers
  13406. getNextTimeout(true);
  13407. getNextErrorTimeout(true);
  13408. // Exec callback
  13409. callback();
  13410. } else {
  13411. var waitMs = getNextTimeout();
  13412. console.info("Waiting for the focus... " + waitMs);
  13413. // Reset error timeout
  13414. getNextErrorTimeout(true);
  13415. window.setTimeout(
  13416. function () {
  13417. Moderator.allocateConferenceFocus(
  13418. roomName, callback);
  13419. }, waitMs);
  13420. }
  13421. },
  13422. function (error) {
  13423. // Invalid session ? remove and try again
  13424. // without session ID to get a new one
  13425. var invalidSession
  13426. = $(error).find('>error>session-invalid').length;
  13427. if (invalidSession) {
  13428. console.info("Session expired! - removing");
  13429. localStorage.removeItem("sessionId");
  13430. }
  13431. if ($(error).find('>error>graceful-shutdown').length) {
  13432. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  13433. return;
  13434. }
  13435. // Check for error returned by the reservation system
  13436. var reservationErr = $(error).find('>error>reservation-error');
  13437. if (reservationErr.length) {
  13438. // Trigger error event
  13439. var errorCode = reservationErr.attr('error-code');
  13440. var errorMsg;
  13441. if ($(error).find('>error>text')) {
  13442. errorMsg = $(error).find('>error>text').text();
  13443. }
  13444. eventEmitter.emit(
  13445. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  13446. return;
  13447. }
  13448. // Not authorized to create new room
  13449. if ($(error).find('>error>not-authorized').length) {
  13450. console.warn("Unauthorized to start the conference", error);
  13451. var toDomain
  13452. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13453. if (toDomain !== config.hosts.anonymousdomain) {
  13454. // FIXME: "is external" should come either from
  13455. // the focus or config.js
  13456. externalAuthEnabled = true;
  13457. }
  13458. eventEmitter.emit(
  13459. XMPPEvents.AUTHENTICATION_REQUIRED,
  13460. function () {
  13461. Moderator.allocateConferenceFocus(
  13462. roomName, callback);
  13463. });
  13464. return;
  13465. }
  13466. var waitMs = getNextErrorTimeout();
  13467. console.error("Focus error, retry after " + waitMs, error);
  13468. // Show message
  13469. var focusComponent = Moderator.getFocusComponent();
  13470. var retrySec = waitMs / 1000;
  13471. // FIXME: message is duplicated ?
  13472. // Do not show in case of session invalid
  13473. // which means just a retry
  13474. if (!invalidSession) {
  13475. APP.UI.messageHandler.notify(
  13476. null, "notify.focus",
  13477. 'disconnected', "notify.focusFail",
  13478. {component: focusComponent, ms: retrySec});
  13479. }
  13480. // Reset response timeout
  13481. getNextTimeout(true);
  13482. window.setTimeout(
  13483. function () {
  13484. Moderator.allocateConferenceFocus(roomName, callback);
  13485. }, waitMs);
  13486. }
  13487. );
  13488. },
  13489. getLoginUrl: function (roomName, urlCallback) {
  13490. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13491. iq.c('login-url', {
  13492. xmlns: 'http://jitsi.org/protocol/focus',
  13493. room: roomName,
  13494. 'machine-uid': Settings.getSettings().uid
  13495. });
  13496. connection.sendIQ(
  13497. iq,
  13498. function (result) {
  13499. var url = $(result).find('login-url').attr('url');
  13500. url = url = decodeURIComponent(url);
  13501. if (url) {
  13502. console.info("Got auth url: " + url);
  13503. urlCallback(url);
  13504. } else {
  13505. console.error(
  13506. "Failed to get auth url from the focus", result);
  13507. }
  13508. },
  13509. function (error) {
  13510. console.error("Get auth url error", error);
  13511. }
  13512. );
  13513. },
  13514. getPopupLoginUrl: function (roomName, urlCallback) {
  13515. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13516. iq.c('login-url', {
  13517. xmlns: 'http://jitsi.org/protocol/focus',
  13518. room: roomName,
  13519. 'machine-uid': Settings.getSettings().uid,
  13520. popup: true
  13521. });
  13522. connection.sendIQ(
  13523. iq,
  13524. function (result) {
  13525. var url = $(result).find('login-url').attr('url');
  13526. url = url = decodeURIComponent(url);
  13527. if (url) {
  13528. console.info("Got POPUP auth url: " + url);
  13529. urlCallback(url);
  13530. } else {
  13531. console.error(
  13532. "Failed to get POPUP auth url from the focus", result);
  13533. }
  13534. },
  13535. function (error) {
  13536. console.error('Get POPUP auth url error', error);
  13537. }
  13538. );
  13539. },
  13540. logout: function (callback) {
  13541. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13542. var sessionId = localStorage.getItem('sessionId');
  13543. if (!sessionId) {
  13544. callback();
  13545. return;
  13546. }
  13547. iq.c('logout', {
  13548. xmlns: 'http://jitsi.org/protocol/focus',
  13549. 'session-id': sessionId
  13550. });
  13551. connection.sendIQ(
  13552. iq,
  13553. function (result) {
  13554. var logoutUrl = $(result).find('logout').attr('logout-url');
  13555. if (logoutUrl) {
  13556. logoutUrl = decodeURIComponent(logoutUrl);
  13557. }
  13558. console.info("Log out OK, url: " + logoutUrl, result);
  13559. localStorage.removeItem('sessionId');
  13560. callback(logoutUrl);
  13561. },
  13562. function (error) {
  13563. console.error("Logout error", error);
  13564. }
  13565. );
  13566. }
  13567. };
  13568. module.exports = Moderator;
  13569. },{"../../service/authentication/AuthenticationEvents":93,"../../service/xmpp/XMPPEvents":97,"../settings/Settings":38}],54:[function(require,module,exports){
  13570. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  13571. Toolbar, Util */
  13572. var Moderator = require("./moderator");
  13573. var recordingToken = null;
  13574. var recordingEnabled;
  13575. /**
  13576. * Whether to use a jirecon component for recording, or use the videobridge
  13577. * through COLIBRI.
  13578. */
  13579. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  13580. /**
  13581. * The ID of the jirecon recording session. Jirecon generates it when we
  13582. * initially start recording, and it needs to be used in subsequent requests
  13583. * to jirecon.
  13584. */
  13585. var jireconRid = null;
  13586. function setRecordingToken(token) {
  13587. recordingToken = token;
  13588. }
  13589. function setRecording(state, token, callback, connection) {
  13590. if (useJirecon){
  13591. setRecordingJirecon(state, token, callback, connection);
  13592. } else {
  13593. setRecordingColibri(state, token, callback, connection);
  13594. }
  13595. }
  13596. function setRecordingJirecon(state, token, callback, connection) {
  13597. if (state == recordingEnabled){
  13598. return;
  13599. }
  13600. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  13601. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  13602. action: state ? 'start' : 'stop',
  13603. mucjid: connection.emuc.roomjid});
  13604. if (!state){
  13605. iq.attrs({rid: jireconRid});
  13606. }
  13607. console.log('Start recording');
  13608. connection.sendIQ(
  13609. iq,
  13610. function (result) {
  13611. // TODO wait for an IQ with the real status, since this is
  13612. // provisional?
  13613. jireconRid = $(result).find('recording').attr('rid');
  13614. console.log('Recording ' + (state ? 'started' : 'stopped') +
  13615. '(jirecon)' + result);
  13616. recordingEnabled = state;
  13617. if (!state){
  13618. jireconRid = null;
  13619. }
  13620. callback(state);
  13621. },
  13622. function (error) {
  13623. console.log('Failed to start recording, error: ', error);
  13624. callback(recordingEnabled);
  13625. });
  13626. }
  13627. // Sends a COLIBRI message which enables or disables (according to 'state')
  13628. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  13629. // with the new recording state, according to the IQ.
  13630. function setRecordingColibri(state, token, callback, connection) {
  13631. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  13632. elem.c('conference', {
  13633. xmlns: 'http://jitsi.org/protocol/colibri'
  13634. });
  13635. elem.c('recording', {state: state, token: token});
  13636. connection.sendIQ(elem,
  13637. function (result) {
  13638. console.log('Set recording "', state, '". Result:', result);
  13639. var recordingElem = $(result).find('>conference>recording');
  13640. var newState = ('true' === recordingElem.attr('state'));
  13641. recordingEnabled = newState;
  13642. callback(newState);
  13643. },
  13644. function (error) {
  13645. console.warn(error);
  13646. callback(recordingEnabled);
  13647. }
  13648. );
  13649. }
  13650. var Recording = {
  13651. toggleRecording: function (tokenEmptyCallback,
  13652. startingCallback, startedCallback, connection) {
  13653. if (!Moderator.isModerator()) {
  13654. console.log(
  13655. 'non-focus, or conference not yet organized:' +
  13656. ' not enabling recording');
  13657. return;
  13658. }
  13659. var self = this;
  13660. // Jirecon does not (currently) support a token.
  13661. if (!recordingToken && !useJirecon) {
  13662. tokenEmptyCallback(function (value) {
  13663. setRecordingToken(value);
  13664. self.toggleRecording(tokenEmptyCallback,
  13665. startingCallback, startedCallback, connection);
  13666. });
  13667. return;
  13668. }
  13669. var oldState = recordingEnabled;
  13670. startingCallback(!oldState);
  13671. setRecording(!oldState,
  13672. recordingToken,
  13673. function (state) {
  13674. console.log("New recording state: ", state);
  13675. if (state === oldState) {
  13676. // FIXME: new focus:
  13677. // this will not work when moderator changes
  13678. // during active session. Then it will assume that
  13679. // recording status has changed to true, but it might have
  13680. // been already true(and we only received actual status from
  13681. // the focus).
  13682. //
  13683. // SO we start with status null, so that it is initialized
  13684. // here and will fail only after second click, so if invalid
  13685. // token was used we have to press the button twice before
  13686. // current status will be fetched and token will be reset.
  13687. //
  13688. // Reliable way would be to return authentication error.
  13689. // Or status update when moderator connects.
  13690. // Or we have to stop recording session when current
  13691. // moderator leaves the room.
  13692. // Failed to change, reset the token because it might
  13693. // have been wrong
  13694. setRecordingToken(null);
  13695. }
  13696. startedCallback(state);
  13697. },
  13698. connection
  13699. );
  13700. }
  13701. }
  13702. module.exports = Recording;
  13703. },{"./moderator":53}],55:[function(require,module,exports){
  13704. /* jshint -W117 */
  13705. /* a simple MUC connection plugin
  13706. * can only handle a single MUC room
  13707. */
  13708. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13709. var Moderator = require("./moderator");
  13710. var JingleSession = require("./JingleSession");
  13711. var bridgeIsDown = false;
  13712. module.exports = function(XMPP, eventEmitter) {
  13713. Strophe.addConnectionPlugin('emuc', {
  13714. connection: null,
  13715. roomjid: null,
  13716. myroomjid: null,
  13717. members: {},
  13718. list_members: [], // so we can elect a new focus
  13719. presMap: {},
  13720. preziMap: {},
  13721. joined: false,
  13722. isOwner: false,
  13723. role: null,
  13724. focusMucJid: null,
  13725. ssrc2jid: {},
  13726. init: function (conn) {
  13727. this.connection = conn;
  13728. },
  13729. initPresenceMap: function (myroomjid) {
  13730. this.presMap['to'] = myroomjid;
  13731. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  13732. },
  13733. doJoin: function (jid, password) {
  13734. this.myroomjid = jid;
  13735. console.info("Joined MUC as " + this.myroomjid);
  13736. this.initPresenceMap(this.myroomjid);
  13737. if (!this.roomjid) {
  13738. this.roomjid = Strophe.getBareJidFromJid(jid);
  13739. // add handlers (just once)
  13740. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  13741. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  13742. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  13743. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  13744. }
  13745. if (password !== undefined) {
  13746. this.presMap['password'] = password;
  13747. }
  13748. this.sendPresence();
  13749. },
  13750. doLeave: function () {
  13751. console.log("do leave", this.myroomjid);
  13752. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  13753. this.presMap.length = 0;
  13754. this.connection.send(pres);
  13755. },
  13756. createNonAnonymousRoom: function () {
  13757. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  13758. var getForm = $iq({type: 'get', to: this.roomjid})
  13759. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  13760. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13761. var self = this;
  13762. this.connection.sendIQ(getForm, function (form) {
  13763. if (!$(form).find(
  13764. '>query>x[xmlns="jabber:x:data"]' +
  13765. '>field[var="muc#roomconfig_whois"]').length) {
  13766. console.error('non-anonymous rooms not supported');
  13767. return;
  13768. }
  13769. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  13770. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13771. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13772. formSubmit.c('field', {'var': 'FORM_TYPE'})
  13773. .c('value')
  13774. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13775. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  13776. .c('value').t('anyone').up().up();
  13777. self.connection.sendIQ(formSubmit);
  13778. }, function (error) {
  13779. console.error("Error getting room configuration form");
  13780. });
  13781. },
  13782. onPresence: function (pres) {
  13783. var from = pres.getAttribute('from');
  13784. // What is this for? A workaround for something?
  13785. if (pres.getAttribute('type')) {
  13786. return true;
  13787. }
  13788. // Parse etherpad tag.
  13789. var etherpad = $(pres).find('>etherpad');
  13790. if (etherpad.length) {
  13791. if (config.etherpad_base && !Moderator.isModerator()) {
  13792. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  13793. }
  13794. }
  13795. // Parse prezi tag.
  13796. var presentation = $(pres).find('>prezi');
  13797. if (presentation.length) {
  13798. var url = presentation.attr('url');
  13799. var current = presentation.find('>current').text();
  13800. console.log('presentation info received from', from, url);
  13801. if (this.preziMap[from] == null) {
  13802. this.preziMap[from] = url;
  13803. $(document).trigger('presentationadded.muc', [from, url, current]);
  13804. }
  13805. else {
  13806. $(document).trigger('gotoslide.muc', [from, url, current]);
  13807. }
  13808. }
  13809. else if (this.preziMap[from] != null) {
  13810. var url = this.preziMap[from];
  13811. delete this.preziMap[from];
  13812. $(document).trigger('presentationremoved.muc', [from, url]);
  13813. }
  13814. // Parse audio info tag.
  13815. var audioMuted = $(pres).find('>audiomuted');
  13816. if (audioMuted.length) {
  13817. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  13818. }
  13819. // Parse video info tag.
  13820. var videoMuted = $(pres).find('>videomuted');
  13821. if (videoMuted.length) {
  13822. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  13823. }
  13824. var devices = $(pres).find('>devices');
  13825. if(devices.length)
  13826. {
  13827. var audio = devices.find('>audio');
  13828. var video = devices.find('>video');
  13829. var devicesValues = {audio: false, video: false};
  13830. if(audio.length && audio.text() === "true")
  13831. {
  13832. devicesValues.audio = true;
  13833. }
  13834. if(video.length && video.text() === "true")
  13835. {
  13836. devicesValues.video = true;
  13837. }
  13838. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  13839. Strophe.getResourceFromJid(from), devicesValues);
  13840. }
  13841. var stats = $(pres).find('>stats');
  13842. if (stats.length) {
  13843. var statsObj = {};
  13844. Strophe.forEachChild(stats[0], "stat", function (el) {
  13845. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  13846. });
  13847. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  13848. }
  13849. // Parse status.
  13850. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  13851. this.isOwner = true;
  13852. this.createNonAnonymousRoom();
  13853. }
  13854. // Parse roles.
  13855. var member = {};
  13856. member.show = $(pres).find('>show').text();
  13857. member.status = $(pres).find('>status').text();
  13858. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  13859. member.affiliation = tmp.attr('affiliation');
  13860. member.role = tmp.attr('role');
  13861. // Focus recognition
  13862. member.jid = tmp.attr('jid');
  13863. member.isFocus = false;
  13864. if (member.jid
  13865. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  13866. member.isFocus = true;
  13867. }
  13868. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  13869. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  13870. if (from == this.myroomjid) {
  13871. if (member.affiliation == 'owner') this.isOwner = true;
  13872. if (this.role !== member.role) {
  13873. this.role = member.role;
  13874. eventEmitter.emit(XMPPEvents.LOCALROLE_CHANGED,
  13875. from, member, pres, Moderator.isModerator());
  13876. }
  13877. if (!this.joined) {
  13878. this.joined = true;
  13879. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  13880. this.list_members.push(from);
  13881. }
  13882. } else if (this.members[from] === undefined) {
  13883. // new participant
  13884. this.members[from] = member;
  13885. this.list_members.push(from);
  13886. console.log('entered', from, member);
  13887. if (member.isFocus) {
  13888. this.focusMucJid = from;
  13889. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  13890. }
  13891. else {
  13892. var id = $(pres).find('>userID').text();
  13893. var email = $(pres).find('>email');
  13894. if (email.length > 0) {
  13895. id = email.text();
  13896. }
  13897. eventEmitter.emit(XMPPEvents.MUC_ENTER, from, id, member.displayName);
  13898. }
  13899. } else {
  13900. // Presence update for existing participant
  13901. // Watch role change:
  13902. if (this.members[from].role != member.role) {
  13903. this.members[from].role = member.role;
  13904. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  13905. member.role, member.displayName);
  13906. }
  13907. }
  13908. // Always trigger presence to update bindings
  13909. this.parsePresence(from, member, pres);
  13910. // Trigger status message update
  13911. if (member.status) {
  13912. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  13913. }
  13914. return true;
  13915. },
  13916. onPresenceUnavailable: function (pres) {
  13917. var from = pres.getAttribute('from');
  13918. // room destroyed ?
  13919. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13920. '>destroy').length) {
  13921. var reason;
  13922. var reasonSelect = $(pres).find(
  13923. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13924. '>destroy>reason');
  13925. if (reasonSelect.length) {
  13926. reason = reasonSelect.text();
  13927. }
  13928. XMPP.disposeConference(false);
  13929. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  13930. return true;
  13931. }
  13932. // Status code 110 indicates that this notification is "self-presence".
  13933. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  13934. delete this.members[from];
  13935. this.list_members.splice(this.list_members.indexOf(from), 1);
  13936. this.onParticipantLeft(from);
  13937. }
  13938. // If the status code is 110 this means we're leaving and we would like
  13939. // to remove everyone else from our view, so we trigger the event.
  13940. else if (this.list_members.length > 1) {
  13941. for (var i = 0; i < this.list_members.length; i++) {
  13942. var member = this.list_members[i];
  13943. delete this.members[i];
  13944. this.list_members.splice(i, 1);
  13945. this.onParticipantLeft(member);
  13946. }
  13947. }
  13948. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  13949. $(document).trigger('kicked.muc', [from]);
  13950. if (this.myroomjid === from) {
  13951. XMPP.disposeConference(false);
  13952. eventEmitter.emit(XMPPEvents.KICKED);
  13953. }
  13954. }
  13955. return true;
  13956. },
  13957. onPresenceError: function (pres) {
  13958. var from = pres.getAttribute('from');
  13959. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13960. console.log('on password required', from);
  13961. var self = this;
  13962. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  13963. self.doJoin(from, value);
  13964. });
  13965. } else if ($(pres).find(
  13966. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13967. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  13968. if (toDomain === config.hosts.anonymousdomain) {
  13969. // enter the room by replying with 'not-authorized'. This would
  13970. // result in reconnection from authorized domain.
  13971. // We're either missing Jicofo/Prosody config for anonymous
  13972. // domains or something is wrong.
  13973. // XMPP.promptLogin();
  13974. APP.UI.messageHandler.openReportDialog(null,
  13975. "dialog.joinError", pres);
  13976. } else {
  13977. console.warn('onPresError ', pres);
  13978. APP.UI.messageHandler.openReportDialog(null,
  13979. "dialog.connectError",
  13980. pres);
  13981. }
  13982. } else {
  13983. console.warn('onPresError ', pres);
  13984. APP.UI.messageHandler.openReportDialog(null,
  13985. "dialog.connectError",
  13986. pres);
  13987. }
  13988. return true;
  13989. },
  13990. sendMessage: function (body, nickname) {
  13991. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13992. msg.c('body', body).up();
  13993. if (nickname) {
  13994. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  13995. }
  13996. this.connection.send(msg);
  13997. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  13998. },
  13999. setSubject: function (subject) {
  14000. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  14001. msg.c('subject', subject);
  14002. this.connection.send(msg);
  14003. console.log("topic changed to " + subject);
  14004. },
  14005. onMessage: function (msg) {
  14006. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  14007. var from = msg.getAttribute('from');
  14008. var nick =
  14009. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  14010. .text() ||
  14011. Strophe.getResourceFromJid(from);
  14012. var txt = $(msg).find('>body').text();
  14013. var type = msg.getAttribute("type");
  14014. if (type == "error") {
  14015. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  14016. $(msg).find('>text').text(), txt);
  14017. return true;
  14018. }
  14019. var subject = $(msg).find('>subject');
  14020. if (subject.length) {
  14021. var subjectText = subject.text();
  14022. if (subjectText || subjectText == "") {
  14023. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  14024. console.log("Subject is changed to " + subjectText);
  14025. }
  14026. }
  14027. if (txt) {
  14028. console.log('chat', nick, txt);
  14029. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  14030. from, nick, txt, this.myroomjid);
  14031. }
  14032. return true;
  14033. },
  14034. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14035. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  14036. var ob = this;
  14037. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  14038. function (res) {
  14039. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  14040. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  14041. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14042. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  14043. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  14044. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  14045. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  14046. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  14047. ob.connection.sendIQ(formsubmit,
  14048. onSuccess,
  14049. onError);
  14050. } else {
  14051. onNotSupported();
  14052. }
  14053. }, onError);
  14054. },
  14055. kick: function (jid) {
  14056. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  14057. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  14058. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  14059. .c('reason').t('You have been kicked.').up().up().up();
  14060. this.connection.sendIQ(
  14061. kickIQ,
  14062. function (result) {
  14063. console.log('Kick participant with jid: ', jid, result);
  14064. },
  14065. function (error) {
  14066. console.log('Kick participant error: ', error);
  14067. });
  14068. },
  14069. sendPresence: function () {
  14070. var pres = $pres({to: this.presMap['to'] });
  14071. pres.c('x', {xmlns: this.presMap['xns']});
  14072. if (this.presMap['password']) {
  14073. pres.c('password').t(this.presMap['password']).up();
  14074. }
  14075. pres.up();
  14076. // Send XEP-0115 'c' stanza that contains our capabilities info
  14077. if (this.connection.caps) {
  14078. this.connection.caps.node = config.clientNode;
  14079. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  14080. }
  14081. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  14082. .t(navigator.userAgent).up();
  14083. if (this.presMap['bridgeIsDown']) {
  14084. pres.c('bridgeIsDown').up();
  14085. }
  14086. if (this.presMap['email']) {
  14087. pres.c('email').t(this.presMap['email']).up();
  14088. }
  14089. if (this.presMap['userId']) {
  14090. pres.c('userId').t(this.presMap['userId']).up();
  14091. }
  14092. if (this.presMap['displayName']) {
  14093. // XEP-0172
  14094. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  14095. .t(this.presMap['displayName']).up();
  14096. }
  14097. if(this.presMap["devices"])
  14098. {
  14099. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  14100. .c('video').t(this.presMap['devices'].video).up().up();
  14101. }
  14102. if (this.presMap['audions']) {
  14103. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  14104. .t(this.presMap['audiomuted']).up();
  14105. }
  14106. if (this.presMap['videons']) {
  14107. pres.c('videomuted', {xmlns: this.presMap['videons']})
  14108. .t(this.presMap['videomuted']).up();
  14109. }
  14110. if (this.presMap['statsns']) {
  14111. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  14112. for (var stat in this.presMap["stats"])
  14113. if (this.presMap["stats"][stat] != null)
  14114. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  14115. pres.up();
  14116. }
  14117. if (this.presMap['prezins']) {
  14118. pres.c('prezi',
  14119. {xmlns: this.presMap['prezins'],
  14120. 'url': this.presMap['preziurl']})
  14121. .c('current').t(this.presMap['prezicurrent']).up().up();
  14122. }
  14123. if (this.presMap['etherpadns']) {
  14124. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  14125. .t(this.presMap['etherpadname']).up();
  14126. }
  14127. if (this.presMap['medians']) {
  14128. pres.c('media', {xmlns: this.presMap['medians']});
  14129. var sourceNumber = 0;
  14130. Object.keys(this.presMap).forEach(function (key) {
  14131. if (key.indexOf('source') >= 0) {
  14132. sourceNumber++;
  14133. }
  14134. });
  14135. if (sourceNumber > 0)
  14136. for (var i = 1; i <= sourceNumber / 3; i++) {
  14137. pres.c('source',
  14138. {type: this.presMap['source' + i + '_type'],
  14139. ssrc: this.presMap['source' + i + '_ssrc'],
  14140. direction: this.presMap['source' + i + '_direction']
  14141. || 'sendrecv' }
  14142. ).up();
  14143. }
  14144. }
  14145. pres.up();
  14146. this.connection.send(pres);
  14147. },
  14148. addDisplayNameToPresence: function (displayName) {
  14149. this.presMap['displayName'] = displayName;
  14150. },
  14151. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  14152. if (!this.presMap['medians'])
  14153. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  14154. this.presMap['source' + sourceNumber + '_type'] = mtype;
  14155. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  14156. this.presMap['source' + sourceNumber + '_direction'] = direction;
  14157. },
  14158. addDevicesToPresence: function (devices) {
  14159. this.presMap['devices'] = devices;
  14160. },
  14161. clearPresenceMedia: function () {
  14162. var self = this;
  14163. Object.keys(this.presMap).forEach(function (key) {
  14164. if (key.indexOf('source') != -1) {
  14165. delete self.presMap[key];
  14166. }
  14167. });
  14168. },
  14169. addPreziToPresence: function (url, currentSlide) {
  14170. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  14171. this.presMap['preziurl'] = url;
  14172. this.presMap['prezicurrent'] = currentSlide;
  14173. },
  14174. removePreziFromPresence: function () {
  14175. delete this.presMap['prezins'];
  14176. delete this.presMap['preziurl'];
  14177. delete this.presMap['prezicurrent'];
  14178. },
  14179. addCurrentSlideToPresence: function (currentSlide) {
  14180. this.presMap['prezicurrent'] = currentSlide;
  14181. },
  14182. getPrezi: function (roomjid) {
  14183. return this.preziMap[roomjid];
  14184. },
  14185. addEtherpadToPresence: function (etherpadName) {
  14186. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  14187. this.presMap['etherpadname'] = etherpadName;
  14188. },
  14189. addAudioInfoToPresence: function (isMuted) {
  14190. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  14191. this.presMap['audiomuted'] = isMuted.toString();
  14192. },
  14193. addVideoInfoToPresence: function (isMuted) {
  14194. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  14195. this.presMap['videomuted'] = isMuted.toString();
  14196. },
  14197. addConnectionInfoToPresence: function (stats) {
  14198. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  14199. this.presMap['stats'] = stats;
  14200. },
  14201. findJidFromResource: function (resourceJid) {
  14202. if (resourceJid &&
  14203. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  14204. return this.myroomjid;
  14205. }
  14206. var peerJid = null;
  14207. Object.keys(this.members).some(function (jid) {
  14208. peerJid = jid;
  14209. return Strophe.getResourceFromJid(jid) === resourceJid;
  14210. });
  14211. return peerJid;
  14212. },
  14213. addBridgeIsDownToPresence: function () {
  14214. this.presMap['bridgeIsDown'] = true;
  14215. },
  14216. addEmailToPresence: function (email) {
  14217. this.presMap['email'] = email;
  14218. },
  14219. addUserIdToPresence: function (userId) {
  14220. this.presMap['userId'] = userId;
  14221. },
  14222. isModerator: function () {
  14223. return this.role === 'moderator';
  14224. },
  14225. getMemberRole: function (peerJid) {
  14226. if (this.members[peerJid]) {
  14227. return this.members[peerJid].role;
  14228. }
  14229. return null;
  14230. },
  14231. onParticipantLeft: function (jid) {
  14232. eventEmitter.emit(XMPPEvents.MUC_LEFT, jid);
  14233. this.connection.jingle.terminateByJid(jid);
  14234. if (this.getPrezi(jid)) {
  14235. $(document).trigger('presentationremoved.muc',
  14236. [jid, this.getPrezi(jid)]);
  14237. }
  14238. Moderator.onMucLeft(jid);
  14239. },
  14240. parsePresence: function (from, memeber, pres) {
  14241. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  14242. bridgeIsDown = true;
  14243. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  14244. }
  14245. if(memeber.isFocus)
  14246. return;
  14247. var self = this;
  14248. // Remove old ssrcs coming from the jid
  14249. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  14250. if (self.ssrc2jid[ssrc] == from) {
  14251. delete self.ssrc2jid[ssrc];
  14252. }
  14253. });
  14254. var changedStreams = [];
  14255. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  14256. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  14257. var ssrcV = ssrc.getAttribute('ssrc');
  14258. self.ssrc2jid[ssrcV] = from;
  14259. JingleSession.notReceivedSSRCs.push(ssrcV);
  14260. var type = ssrc.getAttribute('type');
  14261. var direction = ssrc.getAttribute('direction');
  14262. changedStreams.push({type: type, direction: direction});
  14263. });
  14264. eventEmitter.emit(XMPPEvents.CHANGED_STREAMS, from, changedStreams);
  14265. var displayName = !config.displayJids
  14266. ? memeber.displayName : Strophe.getResourceFromJid(from);
  14267. if (displayName && displayName.length > 0)
  14268. {
  14269. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  14270. }
  14271. var id = $(pres).find('>userID').text();
  14272. var email = $(pres).find('>email');
  14273. if(email.length > 0) {
  14274. id = email.text();
  14275. }
  14276. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  14277. }
  14278. });
  14279. };
  14280. },{"../../service/xmpp/XMPPEvents":97,"./JingleSession":48,"./moderator":53}],56:[function(require,module,exports){
  14281. /* jshint -W117 */
  14282. var JingleSession = require("./JingleSession");
  14283. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14284. module.exports = function(XMPP, eventEmitter)
  14285. {
  14286. function CallIncomingJingle(sid, connection) {
  14287. var sess = connection.jingle.sessions[sid];
  14288. // TODO: do we check activecall == null?
  14289. connection.jingle.activecall = sess;
  14290. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  14291. // TODO: check affiliation and/or role
  14292. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  14293. sess.usedrip = true; // not-so-naive trickle ice
  14294. sess.sendAnswer();
  14295. sess.accept();
  14296. };
  14297. Strophe.addConnectionPlugin('jingle', {
  14298. connection: null,
  14299. sessions: {},
  14300. jid2session: {},
  14301. ice_config: {iceServers: []},
  14302. pc_constraints: {},
  14303. activecall: null,
  14304. media_constraints: {
  14305. mandatory: {
  14306. 'OfferToReceiveAudio': true,
  14307. 'OfferToReceiveVideo': true
  14308. }
  14309. // MozDontOfferDataChannel: true when this is firefox
  14310. },
  14311. init: function (conn) {
  14312. this.connection = conn;
  14313. if (this.connection.disco) {
  14314. // http://xmpp.org/extensions/xep-0167.html#support
  14315. // http://xmpp.org/extensions/xep-0176.html#support
  14316. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  14317. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  14318. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  14319. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  14320. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  14321. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  14322. // this is dealt with by SDP O/A so we don't need to annouce this
  14323. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  14324. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  14325. if (config.useRtcpMux) {
  14326. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  14327. }
  14328. if (config.useBundle) {
  14329. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  14330. }
  14331. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  14332. }
  14333. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  14334. },
  14335. onJingle: function (iq) {
  14336. var sid = $(iq).find('jingle').attr('sid');
  14337. var action = $(iq).find('jingle').attr('action');
  14338. var fromJid = iq.getAttribute('from');
  14339. // send ack first
  14340. var ack = $iq({type: 'result',
  14341. to: fromJid,
  14342. id: iq.getAttribute('id')
  14343. });
  14344. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  14345. var sess = this.sessions[sid];
  14346. if ('session-initiate' != action) {
  14347. if (sess === null) {
  14348. ack.type = 'error';
  14349. ack.c('error', {type: 'cancel'})
  14350. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14351. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14352. this.connection.send(ack);
  14353. return true;
  14354. }
  14355. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  14356. // local jid is not checked
  14357. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  14358. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  14359. ack.type = 'error';
  14360. ack.c('error', {type: 'cancel'})
  14361. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14362. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14363. this.connection.send(ack);
  14364. return true;
  14365. }
  14366. } else if (sess !== undefined) {
  14367. // existing session with same session id
  14368. // this might be out-of-order if the sess.peerjid is the same as from
  14369. ack.type = 'error';
  14370. ack.c('error', {type: 'cancel'})
  14371. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  14372. console.warn('duplicate session id', sid);
  14373. this.connection.send(ack);
  14374. return true;
  14375. }
  14376. // FIXME: check for a defined action
  14377. this.connection.send(ack);
  14378. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  14379. switch (action) {
  14380. case 'session-initiate':
  14381. sess = new JingleSession(
  14382. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  14383. this.connection, XMPP);
  14384. // configure session
  14385. sess.media_constraints = this.media_constraints;
  14386. sess.pc_constraints = this.pc_constraints;
  14387. sess.ice_config = this.ice_config;
  14388. sess.initiate(fromJid, false);
  14389. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  14390. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  14391. this.sessions[sess.sid] = sess;
  14392. this.jid2session[sess.peerjid] = sess;
  14393. // the callback should either
  14394. // .sendAnswer and .accept
  14395. // or .sendTerminate -- not necessarily synchronus
  14396. CallIncomingJingle(sess.sid, this.connection);
  14397. break;
  14398. case 'session-accept':
  14399. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  14400. sess.accept();
  14401. $(document).trigger('callaccepted.jingle', [sess.sid]);
  14402. break;
  14403. case 'session-terminate':
  14404. // If this is not the focus sending the terminate, we have
  14405. // nothing more to do here.
  14406. if (Object.keys(this.sessions).length < 1
  14407. || !(this.sessions[Object.keys(this.sessions)[0]]
  14408. instanceof JingleSession))
  14409. {
  14410. break;
  14411. }
  14412. console.log('terminating...', sess.sid);
  14413. sess.terminate();
  14414. this.terminate(sess.sid);
  14415. if ($(iq).find('>jingle>reason').length) {
  14416. $(document).trigger('callterminated.jingle', [
  14417. sess.sid,
  14418. sess.peerjid,
  14419. $(iq).find('>jingle>reason>:first')[0].tagName,
  14420. $(iq).find('>jingle>reason>text').text()
  14421. ]);
  14422. } else {
  14423. $(document).trigger('callterminated.jingle',
  14424. [sess.sid, sess.peerjid]);
  14425. }
  14426. break;
  14427. case 'transport-info':
  14428. sess.addIceCandidate($(iq).find('>jingle>content'));
  14429. break;
  14430. case 'session-info':
  14431. var affected;
  14432. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14433. $(document).trigger('ringing.jingle', [sess.sid]);
  14434. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14435. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14436. $(document).trigger('mute.jingle', [sess.sid, affected]);
  14437. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14438. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14439. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  14440. }
  14441. break;
  14442. case 'addsource': // FIXME: proprietary, un-jingleish
  14443. case 'source-add': // FIXME: proprietary
  14444. sess.addSource($(iq).find('>jingle>content'), fromJid);
  14445. break;
  14446. case 'removesource': // FIXME: proprietary, un-jingleish
  14447. case 'source-remove': // FIXME: proprietary
  14448. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  14449. break;
  14450. default:
  14451. console.warn('jingle action not implemented', action);
  14452. break;
  14453. }
  14454. return true;
  14455. },
  14456. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  14457. var sess = new JingleSession(myjid || this.connection.jid,
  14458. Math.random().toString(36).substr(2, 12), // random string
  14459. this.connection, XMPP);
  14460. // configure session
  14461. sess.media_constraints = this.media_constraints;
  14462. sess.pc_constraints = this.pc_constraints;
  14463. sess.ice_config = this.ice_config;
  14464. sess.initiate(peerjid, true);
  14465. this.sessions[sess.sid] = sess;
  14466. this.jid2session[sess.peerjid] = sess;
  14467. sess.sendOffer();
  14468. return sess;
  14469. },
  14470. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  14471. if (sid === null || sid === undefined) {
  14472. for (sid in this.sessions) {
  14473. if (this.sessions[sid].state != 'ended') {
  14474. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14475. this.sessions[sid].terminate();
  14476. }
  14477. delete this.jid2session[this.sessions[sid].peerjid];
  14478. delete this.sessions[sid];
  14479. }
  14480. } else if (this.sessions.hasOwnProperty(sid)) {
  14481. if (this.sessions[sid].state != 'ended') {
  14482. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14483. this.sessions[sid].terminate();
  14484. }
  14485. delete this.jid2session[this.sessions[sid].peerjid];
  14486. delete this.sessions[sid];
  14487. }
  14488. },
  14489. // Used to terminate a session when an unavailable presence is received.
  14490. terminateByJid: function (jid) {
  14491. if (this.jid2session.hasOwnProperty(jid)) {
  14492. var sess = this.jid2session[jid];
  14493. if (sess) {
  14494. sess.terminate();
  14495. console.log('peer went away silently', jid);
  14496. delete this.sessions[sess.sid];
  14497. delete this.jid2session[jid];
  14498. $(document).trigger('callterminated.jingle',
  14499. [sess.sid, jid], 'gone');
  14500. }
  14501. }
  14502. },
  14503. terminateRemoteByJid: function (jid, reason) {
  14504. if (this.jid2session.hasOwnProperty(jid)) {
  14505. var sess = this.jid2session[jid];
  14506. if (sess) {
  14507. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  14508. sess.terminate();
  14509. console.log('terminate peer with jid', sess.sid, jid);
  14510. delete this.sessions[sess.sid];
  14511. delete this.jid2session[jid];
  14512. $(document).trigger('callterminated.jingle',
  14513. [sess.sid, jid, 'kicked']);
  14514. }
  14515. }
  14516. },
  14517. getStunAndTurnCredentials: function () {
  14518. // get stun and turn configuration from server via xep-0215
  14519. // uses time-limited credentials as described in
  14520. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  14521. //
  14522. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  14523. // for a prosody module which implements this
  14524. //
  14525. // currently, this doesn't work with updateIce and therefore credentials with a long
  14526. // validity have to be fetched before creating the peerconnection
  14527. // TODO: implement refresh via updateIce as described in
  14528. // https://code.google.com/p/webrtc/issues/detail?id=1650
  14529. var self = this;
  14530. this.connection.sendIQ(
  14531. $iq({type: 'get', to: this.connection.domain})
  14532. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  14533. function (res) {
  14534. var iceservers = [];
  14535. $(res).find('>services>service').each(function (idx, el) {
  14536. el = $(el);
  14537. var dict = {};
  14538. var type = el.attr('type');
  14539. switch (type) {
  14540. case 'stun':
  14541. dict.url = 'stun:' + el.attr('host');
  14542. if (el.attr('port')) {
  14543. dict.url += ':' + el.attr('port');
  14544. }
  14545. iceservers.push(dict);
  14546. break;
  14547. case 'turn':
  14548. case 'turns':
  14549. dict.url = type + ':';
  14550. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  14551. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  14552. dict.url += el.attr('username') + '@';
  14553. } else {
  14554. dict.username = el.attr('username'); // only works in M28
  14555. }
  14556. }
  14557. dict.url += el.attr('host');
  14558. if (el.attr('port') && el.attr('port') != '3478') {
  14559. dict.url += ':' + el.attr('port');
  14560. }
  14561. if (el.attr('transport') && el.attr('transport') != 'udp') {
  14562. dict.url += '?transport=' + el.attr('transport');
  14563. }
  14564. if (el.attr('password')) {
  14565. dict.credential = el.attr('password');
  14566. }
  14567. iceservers.push(dict);
  14568. break;
  14569. }
  14570. });
  14571. self.ice_config.iceServers = iceservers;
  14572. },
  14573. function (err) {
  14574. console.warn('getting turn credentials failed', err);
  14575. console.warn('is mod_turncredentials or similar installed?');
  14576. }
  14577. );
  14578. // implement push?
  14579. },
  14580. /**
  14581. * Populates the log data
  14582. */
  14583. populateData: function () {
  14584. var data = {};
  14585. Object.keys(this.sessions).forEach(function (sid) {
  14586. var session = this.sessions[sid];
  14587. if (session.peerconnection && session.peerconnection.updateLog) {
  14588. // FIXME: should probably be a .dump call
  14589. data["jingle_" + session.sid] = {
  14590. updateLog: session.peerconnection.updateLog,
  14591. stats: session.peerconnection.stats,
  14592. url: window.location.href
  14593. };
  14594. }
  14595. });
  14596. return data;
  14597. }
  14598. });
  14599. };
  14600. },{"../../service/xmpp/XMPPEvents":97,"./JingleSession":48}],57:[function(require,module,exports){
  14601. /* global Strophe */
  14602. module.exports = function () {
  14603. Strophe.addConnectionPlugin('logger', {
  14604. // logs raw stanzas and makes them available for download as JSON
  14605. connection: null,
  14606. log: [],
  14607. init: function (conn) {
  14608. this.connection = conn;
  14609. this.connection.rawInput = this.log_incoming.bind(this);
  14610. this.connection.rawOutput = this.log_outgoing.bind(this);
  14611. },
  14612. log_incoming: function (stanza) {
  14613. this.log.push([new Date().getTime(), 'incoming', stanza]);
  14614. },
  14615. log_outgoing: function (stanza) {
  14616. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  14617. }
  14618. });
  14619. };
  14620. },{}],58:[function(require,module,exports){
  14621. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  14622. setAudioMuted, Strophe */
  14623. /**
  14624. * Moderate connection plugin.
  14625. */
  14626. module.exports = function (XMPP) {
  14627. Strophe.addConnectionPlugin('moderate', {
  14628. connection: null,
  14629. init: function (conn) {
  14630. this.connection = conn;
  14631. this.connection.addHandler(this.onMute.bind(this),
  14632. 'http://jitsi.org/jitmeet/audio',
  14633. 'iq',
  14634. 'set',
  14635. null,
  14636. null);
  14637. },
  14638. setMute: function (jid, mute) {
  14639. console.info("set mute", mute);
  14640. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  14641. .c('mute', {
  14642. xmlns: 'http://jitsi.org/jitmeet/audio',
  14643. jid: jid
  14644. })
  14645. .t(mute.toString())
  14646. .up();
  14647. this.connection.sendIQ(
  14648. iqToFocus,
  14649. function (result) {
  14650. console.log('set mute', result);
  14651. },
  14652. function (error) {
  14653. console.log('set mute error', error);
  14654. });
  14655. },
  14656. onMute: function (iq) {
  14657. var from = iq.getAttribute('from');
  14658. if (from !== this.connection.emuc.focusMucJid) {
  14659. console.warn("Ignored mute from non focus peer");
  14660. return false;
  14661. }
  14662. var mute = $(iq).find('mute');
  14663. if (mute.length) {
  14664. var doMuteAudio = mute.text() === "true";
  14665. APP.UI.setAudioMuted(doMuteAudio);
  14666. XMPP.forceMuted = doMuteAudio;
  14667. }
  14668. return true;
  14669. },
  14670. eject: function (jid) {
  14671. // We're not the focus, so can't terminate
  14672. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  14673. this.connection.emuc.kick(jid);
  14674. }
  14675. });
  14676. }
  14677. },{}],59:[function(require,module,exports){
  14678. /* jshint -W117 */
  14679. module.exports = function() {
  14680. Strophe.addConnectionPlugin('rayo',
  14681. {
  14682. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  14683. connection: null,
  14684. init: function (conn) {
  14685. this.connection = conn;
  14686. if (this.connection.disco) {
  14687. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  14688. }
  14689. this.connection.addHandler(
  14690. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  14691. },
  14692. onRayo: function (iq) {
  14693. console.info("Rayo IQ", iq);
  14694. },
  14695. dial: function (to, from, roomName, roomPass) {
  14696. var self = this;
  14697. var req = $iq(
  14698. {
  14699. type: 'set',
  14700. to: this.connection.emuc.focusMucJid
  14701. }
  14702. );
  14703. req.c('dial',
  14704. {
  14705. xmlns: this.RAYO_XMLNS,
  14706. to: to,
  14707. from: from
  14708. });
  14709. req.c('header',
  14710. {
  14711. name: 'JvbRoomName',
  14712. value: roomName
  14713. }).up();
  14714. if (roomPass !== null && roomPass.length) {
  14715. req.c('header',
  14716. {
  14717. name: 'JvbRoomPassword',
  14718. value: roomPass
  14719. }).up();
  14720. }
  14721. this.connection.sendIQ(
  14722. req,
  14723. function (result) {
  14724. console.info('Dial result ', result);
  14725. var resource = $(result).find('ref').attr('uri');
  14726. this.call_resource = resource.substr('xmpp:'.length);
  14727. console.info(
  14728. "Received call resource: " + this.call_resource);
  14729. },
  14730. function (error) {
  14731. console.info('Dial error ', error);
  14732. }
  14733. );
  14734. },
  14735. hang_up: function () {
  14736. if (!this.call_resource) {
  14737. console.warn("No call in progress");
  14738. return;
  14739. }
  14740. var self = this;
  14741. var req = $iq(
  14742. {
  14743. type: 'set',
  14744. to: this.call_resource
  14745. }
  14746. );
  14747. req.c('hangup',
  14748. {
  14749. xmlns: this.RAYO_XMLNS
  14750. });
  14751. this.connection.sendIQ(
  14752. req,
  14753. function (result) {
  14754. console.info('Hangup result ', result);
  14755. self.call_resource = null;
  14756. },
  14757. function (error) {
  14758. console.info('Hangup error ', error);
  14759. self.call_resource = null;
  14760. }
  14761. );
  14762. }
  14763. }
  14764. );
  14765. };
  14766. },{}],60:[function(require,module,exports){
  14767. /**
  14768. * Strophe logger implementation. Logs from level WARN and above.
  14769. */
  14770. module.exports = function () {
  14771. Strophe.log = function (level, msg) {
  14772. switch (level) {
  14773. case Strophe.LogLevel.WARN:
  14774. console.warn("Strophe: " + msg);
  14775. break;
  14776. case Strophe.LogLevel.ERROR:
  14777. case Strophe.LogLevel.FATAL:
  14778. console.error("Strophe: " + msg);
  14779. break;
  14780. }
  14781. };
  14782. Strophe.getStatusString = function (status) {
  14783. switch (status) {
  14784. case Strophe.Status.ERROR:
  14785. return "ERROR";
  14786. case Strophe.Status.CONNECTING:
  14787. return "CONNECTING";
  14788. case Strophe.Status.CONNFAIL:
  14789. return "CONNFAIL";
  14790. case Strophe.Status.AUTHENTICATING:
  14791. return "AUTHENTICATING";
  14792. case Strophe.Status.AUTHFAIL:
  14793. return "AUTHFAIL";
  14794. case Strophe.Status.CONNECTED:
  14795. return "CONNECTED";
  14796. case Strophe.Status.DISCONNECTED:
  14797. return "DISCONNECTED";
  14798. case Strophe.Status.DISCONNECTING:
  14799. return "DISCONNECTING";
  14800. case Strophe.Status.ATTACHED:
  14801. return "ATTACHED";
  14802. default:
  14803. return "unknown";
  14804. }
  14805. };
  14806. };
  14807. },{}],61:[function(require,module,exports){
  14808. /* global $, APP, config, Strophe*/
  14809. var Moderator = require("./moderator");
  14810. var EventEmitter = require("events");
  14811. var Recording = require("./recording");
  14812. var SDP = require("./SDP");
  14813. var Settings = require("../settings/Settings");
  14814. var Pako = require("pako");
  14815. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  14816. var RTCEvents = require("../../service/RTC/RTCEvents");
  14817. var UIEvents = require("../../service/UI/UIEvents");
  14818. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14819. var eventEmitter = new EventEmitter();
  14820. var connection = null;
  14821. var authenticatedUser = false;
  14822. function connect(jid, password) {
  14823. connection = XMPP.createConnection();
  14824. Moderator.setConnection(connection);
  14825. if (connection.disco) {
  14826. // for chrome, add multistream cap
  14827. }
  14828. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  14829. if (config.useIPv6) {
  14830. // https://code.google.com/p/webrtc/issues/detail?id=2828
  14831. if (!connection.jingle.pc_constraints.optional)
  14832. connection.jingle.pc_constraints.optional = [];
  14833. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  14834. }
  14835. // Include user info in MUC presence
  14836. var settings = Settings.getSettings();
  14837. if (settings.email) {
  14838. connection.emuc.addEmailToPresence(settings.email);
  14839. }
  14840. if (settings.uid) {
  14841. connection.emuc.addUserIdToPresence(settings.uid);
  14842. }
  14843. if (settings.displayName) {
  14844. connection.emuc.addDisplayNameToPresence(settings.displayName);
  14845. }
  14846. var anonymousConnectionFailed = false;
  14847. connection.connect(jid, password, function (status, msg) {
  14848. console.log('Strophe status changed to',
  14849. Strophe.getStatusString(status));
  14850. if (status === Strophe.Status.CONNECTED) {
  14851. if (config.useStunTurn) {
  14852. connection.jingle.getStunAndTurnCredentials();
  14853. }
  14854. console.info("My Jabber ID: " + connection.jid);
  14855. if(password)
  14856. authenticatedUser = true;
  14857. maybeDoJoin();
  14858. } else if (status === Strophe.Status.CONNFAIL) {
  14859. if(msg === 'x-strophe-bad-non-anon-jid') {
  14860. anonymousConnectionFailed = true;
  14861. }
  14862. } else if (status === Strophe.Status.DISCONNECTED) {
  14863. if(anonymousConnectionFailed) {
  14864. // prompt user for username and password
  14865. XMPP.promptLogin();
  14866. }
  14867. } else if (status === Strophe.Status.AUTHFAIL) {
  14868. // wrong password or username, prompt user
  14869. XMPP.promptLogin();
  14870. }
  14871. });
  14872. }
  14873. function maybeDoJoin() {
  14874. if (connection && connection.connected &&
  14875. Strophe.getResourceFromJid(connection.jid)
  14876. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  14877. // .connected is true while connecting?
  14878. doJoin();
  14879. }
  14880. }
  14881. function doJoin() {
  14882. var roomName = APP.UI.generateRoomName();
  14883. Moderator.allocateConferenceFocus(
  14884. roomName, APP.UI.checkForNicknameAndJoin);
  14885. }
  14886. function initStrophePlugins()
  14887. {
  14888. require("./strophe.emuc")(XMPP, eventEmitter);
  14889. require("./strophe.jingle")(XMPP, eventEmitter);
  14890. require("./strophe.moderate")(XMPP);
  14891. require("./strophe.util")();
  14892. require("./strophe.rayo")();
  14893. require("./strophe.logger")();
  14894. }
  14895. function registerListeners() {
  14896. APP.RTC.addStreamListener(maybeDoJoin,
  14897. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  14898. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  14899. XMPP.addToPresence("devices", devices);
  14900. })
  14901. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  14902. XMPP.addToPresence("displayName", nickname);
  14903. });
  14904. }
  14905. function setupEvents() {
  14906. $(window).bind('beforeunload', function () {
  14907. if (connection && connection.connected) {
  14908. // ensure signout
  14909. $.ajax({
  14910. type: 'POST',
  14911. url: config.bosh,
  14912. async: false,
  14913. cache: false,
  14914. contentType: 'application/xml',
  14915. data: "<body rid='" + (connection.rid || connection._proto.rid)
  14916. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  14917. + (connection.sid || connection._proto.sid)
  14918. + "' type='terminate'>" +
  14919. "<presence xmlns='jabber:client' type='unavailable'/>" +
  14920. "</body>",
  14921. success: function (data) {
  14922. console.log('signed out');
  14923. console.log(data);
  14924. },
  14925. error: function (XMLHttpRequest, textStatus, errorThrown) {
  14926. console.log('signout error',
  14927. textStatus + ' (' + errorThrown + ')');
  14928. }
  14929. });
  14930. }
  14931. XMPP.disposeConference(true);
  14932. });
  14933. }
  14934. var XMPP = {
  14935. sessionTerminated: false,
  14936. /**
  14937. * XMPP connection status
  14938. */
  14939. Status: Strophe.Status,
  14940. /**
  14941. * Remembers if we were muted by the focus.
  14942. * @type {boolean}
  14943. */
  14944. forceMuted: false,
  14945. start: function () {
  14946. setupEvents();
  14947. initStrophePlugins();
  14948. registerListeners();
  14949. Moderator.init(this, eventEmitter);
  14950. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  14951. // Force authenticated domain if room is appended with '?login=true'
  14952. if (config.hosts.anonymousdomain &&
  14953. window.location.search.indexOf("login=true") !== -1) {
  14954. configDomain = config.hosts.domain;
  14955. }
  14956. var jid = configDomain || window.location.hostname;
  14957. connect(jid, null);
  14958. },
  14959. createConnection: function () {
  14960. var bosh = config.bosh || '/http-bind';
  14961. return new Strophe.Connection(bosh);
  14962. },
  14963. getStatusString: function (status) {
  14964. return Strophe.getStatusString(status);
  14965. },
  14966. promptLogin: function () {
  14967. // FIXME: re-use LoginDialog which supports retries
  14968. APP.UI.showLoginPopup(connect);
  14969. },
  14970. joinRoom: function(roomName, useNicks, nick)
  14971. {
  14972. var roomjid;
  14973. roomjid = roomName;
  14974. if (useNicks) {
  14975. if (nick) {
  14976. roomjid += '/' + nick;
  14977. } else {
  14978. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  14979. }
  14980. } else {
  14981. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  14982. if(!authenticatedUser)
  14983. tmpJid = tmpJid.substr(0, 8);
  14984. roomjid += '/' + tmpJid;
  14985. }
  14986. connection.emuc.doJoin(roomjid);
  14987. },
  14988. myJid: function () {
  14989. if(!connection)
  14990. return null;
  14991. return connection.emuc.myroomjid;
  14992. },
  14993. myResource: function () {
  14994. if(!connection || ! connection.emuc.myroomjid)
  14995. return null;
  14996. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  14997. },
  14998. disposeConference: function (onUnload) {
  14999. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  15000. var handler = connection.jingle.activecall;
  15001. if (handler && handler.peerconnection) {
  15002. // FIXME: probably removing streams is not required and close() should
  15003. // be enough
  15004. if (APP.RTC.localAudio) {
  15005. handler.peerconnection.removeStream(
  15006. APP.RTC.localAudio.getOriginalStream(), onUnload);
  15007. }
  15008. if (APP.RTC.localVideo) {
  15009. handler.peerconnection.removeStream(
  15010. APP.RTC.localVideo.getOriginalStream(), onUnload);
  15011. }
  15012. handler.peerconnection.close();
  15013. }
  15014. connection.jingle.activecall = null;
  15015. if(!onUnload)
  15016. {
  15017. this.sessionTerminated = true;
  15018. connection.emuc.doLeave();
  15019. }
  15020. },
  15021. addListener: function(type, listener)
  15022. {
  15023. eventEmitter.on(type, listener);
  15024. },
  15025. removeListener: function (type, listener) {
  15026. eventEmitter.removeListener(type, listener);
  15027. },
  15028. allocateConferenceFocus: function(roomName, callback) {
  15029. Moderator.allocateConferenceFocus(roomName, callback);
  15030. },
  15031. getLoginUrl: function (roomName, callback) {
  15032. Moderator.getLoginUrl(roomName, callback);
  15033. },
  15034. getPopupLoginUrl: function (roomName, callback) {
  15035. Moderator.getPopupLoginUrl(roomName, callback);
  15036. },
  15037. isModerator: function () {
  15038. return Moderator.isModerator();
  15039. },
  15040. isSipGatewayEnabled: function () {
  15041. return Moderator.isSipGatewayEnabled();
  15042. },
  15043. isExternalAuthEnabled: function () {
  15044. return Moderator.isExternalAuthEnabled();
  15045. },
  15046. switchStreams: function (stream, oldStream, callback) {
  15047. if (connection && connection.jingle.activecall) {
  15048. // FIXME: will block switchInProgress on true value in case of exception
  15049. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  15050. } else {
  15051. // We are done immediately
  15052. console.warn("No conference handler or conference not started yet");
  15053. callback();
  15054. }
  15055. },
  15056. sendVideoInfoPresence: function (mute) {
  15057. connection.emuc.addVideoInfoToPresence(mute);
  15058. connection.emuc.sendPresence();
  15059. },
  15060. setVideoMute: function (mute, callback, options) {
  15061. if(!connection)
  15062. return;
  15063. var self = this;
  15064. var localCallback = function (mute) {
  15065. self.sendVideoInfoPresence(mute);
  15066. return callback(mute);
  15067. };
  15068. if(connection.jingle.activecall)
  15069. {
  15070. connection.jingle.activecall.setVideoMute(
  15071. mute, localCallback, options);
  15072. }
  15073. else {
  15074. localCallback(mute);
  15075. }
  15076. },
  15077. setAudioMute: function (mute, callback) {
  15078. if (!(connection && APP.RTC.localAudio)) {
  15079. return false;
  15080. }
  15081. if (this.forceMuted && !mute) {
  15082. console.info("Asking focus for unmute");
  15083. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  15084. // FIXME: wait for result before resetting muted status
  15085. this.forceMuted = false;
  15086. }
  15087. if (mute == APP.RTC.localAudio.isMuted()) {
  15088. // Nothing to do
  15089. return true;
  15090. }
  15091. // It is not clear what is the right way to handle multiple tracks.
  15092. // So at least make sure that they are all muted or all unmuted and
  15093. // that we send presence just once.
  15094. APP.RTC.localAudio.mute();
  15095. // isMuted is the opposite of audioEnabled
  15096. connection.emuc.addAudioInfoToPresence(mute);
  15097. connection.emuc.sendPresence();
  15098. callback();
  15099. return true;
  15100. },
  15101. // Really mute video, i.e. dont even send black frames
  15102. muteVideo: function (pc, unmute) {
  15103. // FIXME: this probably needs another of those lovely state safeguards...
  15104. // which checks for iceconn == connected and sigstate == stable
  15105. pc.setRemoteDescription(pc.remoteDescription,
  15106. function () {
  15107. pc.createAnswer(
  15108. function (answer) {
  15109. var sdp = new SDP(answer.sdp);
  15110. if (sdp.media.length > 1) {
  15111. if (unmute)
  15112. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  15113. else
  15114. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  15115. sdp.raw = sdp.session + sdp.media.join('');
  15116. answer.sdp = sdp.raw;
  15117. }
  15118. pc.setLocalDescription(answer,
  15119. function () {
  15120. console.log('mute SLD ok');
  15121. },
  15122. function (error) {
  15123. console.log('mute SLD error');
  15124. APP.UI.messageHandler.showError("dialog.error",
  15125. "dialog.SLDFailure");
  15126. }
  15127. );
  15128. },
  15129. function (error) {
  15130. console.log(error);
  15131. APP.UI.messageHandler.showError();
  15132. }
  15133. );
  15134. },
  15135. function (error) {
  15136. console.log('muteVideo SRD error');
  15137. APP.UI.messageHandler.showError("dialog.error",
  15138. "dialog.SRDFailure");
  15139. }
  15140. );
  15141. },
  15142. toggleRecording: function (tokenEmptyCallback,
  15143. startingCallback, startedCallback) {
  15144. Recording.toggleRecording(tokenEmptyCallback,
  15145. startingCallback, startedCallback, connection);
  15146. },
  15147. addToPresence: function (name, value, dontSend) {
  15148. switch (name)
  15149. {
  15150. case "displayName":
  15151. connection.emuc.addDisplayNameToPresence(value);
  15152. break;
  15153. case "etherpad":
  15154. connection.emuc.addEtherpadToPresence(value);
  15155. break;
  15156. case "prezi":
  15157. connection.emuc.addPreziToPresence(value, 0);
  15158. break;
  15159. case "preziSlide":
  15160. connection.emuc.addCurrentSlideToPresence(value);
  15161. break;
  15162. case "connectionQuality":
  15163. connection.emuc.addConnectionInfoToPresence(value);
  15164. break;
  15165. case "email":
  15166. connection.emuc.addEmailToPresence(value);
  15167. break;
  15168. case "devices":
  15169. connection.emuc.addDevicesToPresence(value);
  15170. break;
  15171. default :
  15172. console.log("Unknown tag for presence: " + name);
  15173. return;
  15174. }
  15175. if (!dontSend)
  15176. connection.emuc.sendPresence();
  15177. },
  15178. /**
  15179. * Sends 'data' as a log message to the focus. Returns true iff a message
  15180. * was sent.
  15181. * @param data
  15182. * @returns {boolean} true iff a message was sent.
  15183. */
  15184. sendLogs: function (data) {
  15185. if(!connection.emuc.focusMucJid)
  15186. return false;
  15187. var deflate = true;
  15188. var content = JSON.stringify(data);
  15189. if (deflate) {
  15190. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  15191. }
  15192. content = Base64.encode(content);
  15193. // XEP-0337-ish
  15194. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  15195. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  15196. id: 'PeerConnectionStats'});
  15197. message.c('message').t(content).up();
  15198. if (deflate) {
  15199. message.c('tag', {name: "deflated", value: "true"}).up();
  15200. }
  15201. message.up();
  15202. connection.send(message);
  15203. return true;
  15204. },
  15205. populateData: function () {
  15206. var data = {};
  15207. if (connection.jingle) {
  15208. data = connection.jingle.populateData();
  15209. }
  15210. return data;
  15211. },
  15212. getLogger: function () {
  15213. if(connection.logger)
  15214. return connection.logger.log;
  15215. return null;
  15216. },
  15217. getPrezi: function () {
  15218. return connection.emuc.getPrezi(this.myJid());
  15219. },
  15220. removePreziFromPresence: function () {
  15221. connection.emuc.removePreziFromPresence();
  15222. connection.emuc.sendPresence();
  15223. },
  15224. sendChatMessage: function (message, nickname) {
  15225. connection.emuc.sendMessage(message, nickname);
  15226. },
  15227. setSubject: function (topic) {
  15228. connection.emuc.setSubject(topic);
  15229. },
  15230. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15231. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  15232. },
  15233. dial: function (to, from, roomName,roomPass) {
  15234. connection.rayo.dial(to, from, roomName,roomPass);
  15235. },
  15236. setMute: function (jid, mute) {
  15237. connection.moderate.setMute(jid, mute);
  15238. },
  15239. eject: function (jid) {
  15240. connection.moderate.eject(jid);
  15241. },
  15242. logout: function (callback) {
  15243. Moderator.logout(callback);
  15244. },
  15245. findJidFromResource: function (resource) {
  15246. return connection.emuc.findJidFromResource(resource);
  15247. },
  15248. getMembers: function () {
  15249. return connection.emuc.members;
  15250. },
  15251. getJidFromSSRC: function (ssrc) {
  15252. if(!connection)
  15253. return null;
  15254. return connection.emuc.ssrc2jid[ssrc];
  15255. },
  15256. getMUCJoined: function () {
  15257. return connection.emuc.joined;
  15258. },
  15259. getSessions: function () {
  15260. return connection.jingle.sessions;
  15261. },
  15262. removeStream: function (stream) {
  15263. if(!connection || !connection.jingle.activecall ||
  15264. !connection.jingle.activecall.peerconnection)
  15265. return;
  15266. connection.jingle.activecall.peerconnection.removeStream(stream);
  15267. }
  15268. };
  15269. module.exports = XMPP;
  15270. },{"../../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){
  15271. // i18next, v1.7.7
  15272. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  15273. // Distributed under MIT license
  15274. // http://i18next.com
  15275. (function() {
  15276. // add indexOf to non ECMA-262 standard compliant browsers
  15277. if (!Array.prototype.indexOf) {
  15278. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  15279. "use strict";
  15280. if (this == null) {
  15281. throw new TypeError();
  15282. }
  15283. var t = Object(this);
  15284. var len = t.length >>> 0;
  15285. if (len === 0) {
  15286. return -1;
  15287. }
  15288. var n = 0;
  15289. if (arguments.length > 0) {
  15290. n = Number(arguments[1]);
  15291. if (n != n) { // shortcut for verifying if it's NaN
  15292. n = 0;
  15293. } else if (n != 0 && n != Infinity && n != -Infinity) {
  15294. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  15295. }
  15296. }
  15297. if (n >= len) {
  15298. return -1;
  15299. }
  15300. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  15301. for (; k < len; k++) {
  15302. if (k in t && t[k] === searchElement) {
  15303. return k;
  15304. }
  15305. }
  15306. return -1;
  15307. }
  15308. }
  15309. // add lastIndexOf to non ECMA-262 standard compliant browsers
  15310. if (!Array.prototype.lastIndexOf) {
  15311. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  15312. "use strict";
  15313. if (this == null) {
  15314. throw new TypeError();
  15315. }
  15316. var t = Object(this);
  15317. var len = t.length >>> 0;
  15318. if (len === 0) {
  15319. return -1;
  15320. }
  15321. var n = len;
  15322. if (arguments.length > 1) {
  15323. n = Number(arguments[1]);
  15324. if (n != n) {
  15325. n = 0;
  15326. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  15327. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  15328. }
  15329. }
  15330. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  15331. for (; k >= 0; k--) {
  15332. if (k in t && t[k] === searchElement) {
  15333. return k;
  15334. }
  15335. }
  15336. return -1;
  15337. };
  15338. }
  15339. // Add string trim for IE8.
  15340. if (typeof String.prototype.trim !== 'function') {
  15341. String.prototype.trim = function() {
  15342. return this.replace(/^\s+|\s+$/g, '');
  15343. }
  15344. }
  15345. var root = this
  15346. , $ = root.jQuery || root.Zepto
  15347. , i18n = {}
  15348. , resStore = {}
  15349. , currentLng
  15350. , replacementCounter = 0
  15351. , languages = []
  15352. , initialized = false
  15353. , sync = {};
  15354. // Export the i18next object for **CommonJS**.
  15355. // If we're not in CommonJS, add `i18n` to the
  15356. // global object or to jquery.
  15357. if (typeof module !== 'undefined' && module.exports) {
  15358. if (!$) {
  15359. try {
  15360. $ = require('jquery');
  15361. } catch(e) {
  15362. // just ignore
  15363. }
  15364. }
  15365. if ($) {
  15366. $.i18n = $.i18n || i18n;
  15367. }
  15368. module.exports = i18n;
  15369. } else {
  15370. if ($) {
  15371. $.i18n = $.i18n || i18n;
  15372. }
  15373. root.i18n = root.i18n || i18n;
  15374. }
  15375. sync = {
  15376. load: function(lngs, options, cb) {
  15377. if (options.useLocalStorage) {
  15378. sync._loadLocal(lngs, options, function(err, store) {
  15379. var missingLngs = [];
  15380. for (var i = 0, len = lngs.length; i < len; i++) {
  15381. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  15382. }
  15383. if (missingLngs.length > 0) {
  15384. sync._fetch(missingLngs, options, function(err, fetched) {
  15385. f.extend(store, fetched);
  15386. sync._storeLocal(fetched);
  15387. cb(null, store);
  15388. });
  15389. } else {
  15390. cb(null, store);
  15391. }
  15392. });
  15393. } else {
  15394. sync._fetch(lngs, options, function(err, store){
  15395. cb(null, store);
  15396. });
  15397. }
  15398. },
  15399. _loadLocal: function(lngs, options, cb) {
  15400. var store = {}
  15401. , nowMS = new Date().getTime();
  15402. if(window.localStorage) {
  15403. var todo = lngs.length;
  15404. f.each(lngs, function(key, lng) {
  15405. var local = window.localStorage.getItem('res_' + lng);
  15406. if (local) {
  15407. local = JSON.parse(local);
  15408. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  15409. store[lng] = local;
  15410. }
  15411. }
  15412. todo--; // wait for all done befor callback
  15413. if (todo === 0) cb(null, store);
  15414. });
  15415. }
  15416. },
  15417. _storeLocal: function(store) {
  15418. if(window.localStorage) {
  15419. for (var m in store) {
  15420. store[m].i18nStamp = new Date().getTime();
  15421. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  15422. }
  15423. }
  15424. return;
  15425. },
  15426. _fetch: function(lngs, options, cb) {
  15427. var ns = options.ns
  15428. , store = {};
  15429. if (!options.dynamicLoad) {
  15430. var todo = ns.namespaces.length * lngs.length
  15431. , errors;
  15432. // load each file individual
  15433. f.each(ns.namespaces, function(nsIndex, nsValue) {
  15434. f.each(lngs, function(lngIndex, lngValue) {
  15435. // Call this once our translation has returned.
  15436. var loadComplete = function(err, data) {
  15437. if (err) {
  15438. errors = errors || [];
  15439. errors.push(err);
  15440. }
  15441. store[lngValue] = store[lngValue] || {};
  15442. store[lngValue][nsValue] = data;
  15443. todo--; // wait for all done befor callback
  15444. if (todo === 0) cb(errors, store);
  15445. };
  15446. if(typeof options.customLoad == 'function'){
  15447. // Use the specified custom callback.
  15448. options.customLoad(lngValue, nsValue, options, loadComplete);
  15449. } else {
  15450. //~ // Use our inbuilt sync.
  15451. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  15452. }
  15453. });
  15454. });
  15455. } else {
  15456. // Call this once our translation has returned.
  15457. var loadComplete = function(err, data) {
  15458. cb(null, data);
  15459. };
  15460. if(typeof options.customLoad == 'function'){
  15461. // Use the specified custom callback.
  15462. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  15463. } else {
  15464. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  15465. // load all needed stuff once
  15466. f.ajax({
  15467. url: url,
  15468. success: function(data, status, xhr) {
  15469. f.log('loaded: ' + url);
  15470. loadComplete(null, data);
  15471. },
  15472. error : function(xhr, status, error) {
  15473. f.log('failed loading: ' + url);
  15474. loadComplete('failed loading resource.json error: ' + error);
  15475. },
  15476. dataType: "json",
  15477. async : options.getAsync
  15478. });
  15479. }
  15480. }
  15481. },
  15482. _fetchOne: function(lng, ns, options, done) {
  15483. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  15484. f.ajax({
  15485. url: url,
  15486. success: function(data, status, xhr) {
  15487. f.log('loaded: ' + url);
  15488. done(null, data);
  15489. },
  15490. error : function(xhr, status, error) {
  15491. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  15492. // file loaded but invalid json, stop waste time !
  15493. f.error('There is a typo in: ' + url);
  15494. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  15495. f.log('Does not exist: ' + url);
  15496. } else {
  15497. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  15498. f.log(theStatus + ' when loading ' + url);
  15499. }
  15500. done(error, {});
  15501. },
  15502. dataType: "json",
  15503. async : options.getAsync
  15504. });
  15505. },
  15506. postMissing: function(lng, ns, key, defaultValue, lngs) {
  15507. var payload = {};
  15508. payload[key] = defaultValue;
  15509. var urls = [];
  15510. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  15511. for (var i = 0; i < o.fallbackLng.length; i++) {
  15512. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  15513. }
  15514. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  15515. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  15516. } else if (o.sendMissingTo === 'all') {
  15517. for (var i = 0, l = lngs.length; i < l; i++) {
  15518. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  15519. }
  15520. }
  15521. for (var y = 0, len = urls.length; y < len; y++) {
  15522. var item = urls[y];
  15523. f.ajax({
  15524. url: item.url,
  15525. type: o.sendType,
  15526. data: payload,
  15527. success: function(data, status, xhr) {
  15528. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  15529. // add key to resStore
  15530. var keys = key.split('.');
  15531. var x = 0;
  15532. var value = resStore[item.lng][ns];
  15533. while (keys[x]) {
  15534. if (x === keys.length - 1) {
  15535. value = value[keys[x]] = defaultValue;
  15536. } else {
  15537. value = value[keys[x]] = value[keys[x]] || {};
  15538. }
  15539. x++;
  15540. }
  15541. },
  15542. error : function(xhr, status, error) {
  15543. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  15544. },
  15545. dataType: "json",
  15546. async : o.postAsync
  15547. });
  15548. }
  15549. },
  15550. reload: reload
  15551. };
  15552. // defaults
  15553. var o = {
  15554. lng: undefined,
  15555. load: 'all',
  15556. preload: [],
  15557. lowerCaseLng: false,
  15558. returnObjectTrees: false,
  15559. fallbackLng: ['dev'],
  15560. fallbackNS: [],
  15561. detectLngQS: 'setLng',
  15562. detectLngFromLocalStorage: false,
  15563. ns: 'translation',
  15564. fallbackOnNull: true,
  15565. fallbackOnEmpty: false,
  15566. fallbackToDefaultNS: false,
  15567. nsseparator: ':',
  15568. keyseparator: '.',
  15569. selectorAttr: 'data-i18n',
  15570. debug: false,
  15571. resGetPath: 'locales/__lng__/__ns__.json',
  15572. resPostPath: 'locales/add/__lng__/__ns__',
  15573. getAsync: true,
  15574. postAsync: true,
  15575. resStore: undefined,
  15576. useLocalStorage: false,
  15577. localStorageExpirationTime: 7*24*60*60*1000,
  15578. dynamicLoad: false,
  15579. sendMissing: false,
  15580. sendMissingTo: 'fallback', // current | all
  15581. sendType: 'POST',
  15582. interpolationPrefix: '__',
  15583. interpolationSuffix: '__',
  15584. defaultVariables: false,
  15585. reusePrefix: '$t(',
  15586. reuseSuffix: ')',
  15587. pluralSuffix: '_plural',
  15588. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  15589. contextNotFound: ['context_not_found', Math.random()].join(''),
  15590. escapeInterpolation: false,
  15591. indefiniteSuffix: '_indefinite',
  15592. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  15593. setJqueryExt: true,
  15594. defaultValueFromContent: true,
  15595. useDataAttrOptions: false,
  15596. cookieExpirationTime: undefined,
  15597. useCookie: true,
  15598. cookieName: 'i18next',
  15599. cookieDomain: undefined,
  15600. objectTreeKeyHandler: undefined,
  15601. postProcess: undefined,
  15602. parseMissingKey: undefined,
  15603. missingKeyHandler: sync.postMissing,
  15604. shortcutFunction: 'sprintf' // or: defaultValue
  15605. };
  15606. function _extend(target, source) {
  15607. if (!source || typeof source === 'function') {
  15608. return target;
  15609. }
  15610. for (var attr in source) { target[attr] = source[attr]; }
  15611. return target;
  15612. }
  15613. function _deepExtend(target, source) {
  15614. for (var prop in source)
  15615. if (prop in target)
  15616. _deepExtend(target[prop], source[prop]);
  15617. else
  15618. target[prop] = source[prop];
  15619. return target;
  15620. }
  15621. function _each(object, callback, args) {
  15622. var name, i = 0,
  15623. length = object.length,
  15624. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  15625. if (args) {
  15626. if (isObj) {
  15627. for (name in object) {
  15628. if (callback.apply(object[name], args) === false) {
  15629. break;
  15630. }
  15631. }
  15632. } else {
  15633. for ( ; i < length; ) {
  15634. if (callback.apply(object[i++], args) === false) {
  15635. break;
  15636. }
  15637. }
  15638. }
  15639. // A special, fast, case for the most common use of each
  15640. } else {
  15641. if (isObj) {
  15642. for (name in object) {
  15643. if (callback.call(object[name], name, object[name]) === false) {
  15644. break;
  15645. }
  15646. }
  15647. } else {
  15648. for ( ; i < length; ) {
  15649. if (callback.call(object[i], i, object[i++]) === false) {
  15650. break;
  15651. }
  15652. }
  15653. }
  15654. }
  15655. return object;
  15656. }
  15657. var _entityMap = {
  15658. "&": "&amp;",
  15659. "<": "&lt;",
  15660. ">": "&gt;",
  15661. '"': '&quot;',
  15662. "'": '&#39;',
  15663. "/": '&#x2F;'
  15664. };
  15665. function _escape(data) {
  15666. if (typeof data === 'string') {
  15667. return data.replace(/[&<>"'\/]/g, function (s) {
  15668. return _entityMap[s];
  15669. });
  15670. }else{
  15671. return data;
  15672. }
  15673. }
  15674. function _ajax(options) {
  15675. // v0.5.0 of https://github.com/goloroden/http.js
  15676. var getXhr = function (callback) {
  15677. // Use the native XHR object if the browser supports it.
  15678. if (window.XMLHttpRequest) {
  15679. return callback(null, new XMLHttpRequest());
  15680. } else if (window.ActiveXObject) {
  15681. // In Internet Explorer check for ActiveX versions of the XHR object.
  15682. try {
  15683. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  15684. } catch (e) {
  15685. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  15686. }
  15687. }
  15688. // If no XHR support was found, throw an error.
  15689. return callback(new Error());
  15690. };
  15691. var encodeUsingUrlEncoding = function (data) {
  15692. if(typeof data === 'string') {
  15693. return data;
  15694. }
  15695. var result = [];
  15696. for(var dataItem in data) {
  15697. if(data.hasOwnProperty(dataItem)) {
  15698. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  15699. }
  15700. }
  15701. return result.join('&');
  15702. };
  15703. var utf8 = function (text) {
  15704. text = text.replace(/\r\n/g, '\n');
  15705. var result = '';
  15706. for(var i = 0; i < text.length; i++) {
  15707. var c = text.charCodeAt(i);
  15708. if(c < 128) {
  15709. result += String.fromCharCode(c);
  15710. } else if((c > 127) && (c < 2048)) {
  15711. result += String.fromCharCode((c >> 6) | 192);
  15712. result += String.fromCharCode((c & 63) | 128);
  15713. } else {
  15714. result += String.fromCharCode((c >> 12) | 224);
  15715. result += String.fromCharCode(((c >> 6) & 63) | 128);
  15716. result += String.fromCharCode((c & 63) | 128);
  15717. }
  15718. }
  15719. return result;
  15720. };
  15721. var base64 = function (text) {
  15722. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15723. text = utf8(text);
  15724. var result = '',
  15725. chr1, chr2, chr3,
  15726. enc1, enc2, enc3, enc4,
  15727. i = 0;
  15728. do {
  15729. chr1 = text.charCodeAt(i++);
  15730. chr2 = text.charCodeAt(i++);
  15731. chr3 = text.charCodeAt(i++);
  15732. enc1 = chr1 >> 2;
  15733. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  15734. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  15735. enc4 = chr3 & 63;
  15736. if(isNaN(chr2)) {
  15737. enc3 = enc4 = 64;
  15738. } else if(isNaN(chr3)) {
  15739. enc4 = 64;
  15740. }
  15741. result +=
  15742. keyStr.charAt(enc1) +
  15743. keyStr.charAt(enc2) +
  15744. keyStr.charAt(enc3) +
  15745. keyStr.charAt(enc4);
  15746. chr1 = chr2 = chr3 = '';
  15747. enc1 = enc2 = enc3 = enc4 = '';
  15748. } while(i < text.length);
  15749. return result;
  15750. };
  15751. var mergeHeaders = function () {
  15752. // Use the first header object as base.
  15753. var result = arguments[0];
  15754. // Iterate through the remaining header objects and add them.
  15755. for(var i = 1; i < arguments.length; i++) {
  15756. var currentHeaders = arguments[i];
  15757. for(var header in currentHeaders) {
  15758. if(currentHeaders.hasOwnProperty(header)) {
  15759. result[header] = currentHeaders[header];
  15760. }
  15761. }
  15762. }
  15763. // Return the merged headers.
  15764. return result;
  15765. };
  15766. var ajax = function (method, url, options, callback) {
  15767. // Adjust parameters.
  15768. if(typeof options === 'function') {
  15769. callback = options;
  15770. options = {};
  15771. }
  15772. // Set default parameter values.
  15773. options.cache = options.cache || false;
  15774. options.data = options.data || {};
  15775. options.headers = options.headers || {};
  15776. options.jsonp = options.jsonp || false;
  15777. options.async = options.async === undefined ? true : options.async;
  15778. // Merge the various header objects.
  15779. var headers = mergeHeaders({
  15780. 'accept': '*/*',
  15781. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  15782. }, ajax.headers, options.headers);
  15783. // Encode the data according to the content-type.
  15784. var payload;
  15785. if (headers['content-type'] === 'application/json') {
  15786. payload = JSON.stringify(options.data);
  15787. } else {
  15788. payload = encodeUsingUrlEncoding(options.data);
  15789. }
  15790. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  15791. // if neccessary.
  15792. if(method === 'GET') {
  15793. // Setup the query string.
  15794. var queryString = [];
  15795. if(payload) {
  15796. queryString.push(payload);
  15797. payload = null;
  15798. }
  15799. // Handle caching.
  15800. if(!options.cache) {
  15801. queryString.push('_=' + (new Date()).getTime());
  15802. }
  15803. // If neccessary prepare the query string for a JSONP call.
  15804. if(options.jsonp) {
  15805. queryString.push('callback=' + options.jsonp);
  15806. queryString.push('jsonp=' + options.jsonp);
  15807. }
  15808. // Merge the query string and attach it to the url.
  15809. queryString = queryString.join('&');
  15810. if (queryString.length > 1) {
  15811. if (url.indexOf('?') > -1) {
  15812. url += '&' + queryString;
  15813. } else {
  15814. url += '?' + queryString;
  15815. }
  15816. }
  15817. // Make a JSONP call if neccessary.
  15818. if(options.jsonp) {
  15819. var head = document.getElementsByTagName('head')[0];
  15820. var script = document.createElement('script');
  15821. script.type = 'text/javascript';
  15822. script.src = url;
  15823. head.appendChild(script);
  15824. return;
  15825. }
  15826. }
  15827. // Since we got here, it is no JSONP request, so make a normal XHR request.
  15828. getXhr(function (err, xhr) {
  15829. if(err) return callback(err);
  15830. // Open the request.
  15831. xhr.open(method, url, options.async);
  15832. // Set the request headers.
  15833. for(var header in headers) {
  15834. if(headers.hasOwnProperty(header)) {
  15835. xhr.setRequestHeader(header, headers[header]);
  15836. }
  15837. }
  15838. // Handle the request events.
  15839. xhr.onreadystatechange = function () {
  15840. if(xhr.readyState === 4) {
  15841. var data = xhr.responseText || '';
  15842. // If no callback is given, return.
  15843. if(!callback) {
  15844. return;
  15845. }
  15846. // Return an object that provides access to the data as text and JSON.
  15847. callback(xhr.status, {
  15848. text: function () {
  15849. return data;
  15850. },
  15851. json: function () {
  15852. try {
  15853. return JSON.parse(data)
  15854. } catch (e) {
  15855. f.error('Can not parse JSON. URL: ' + url);
  15856. return {};
  15857. }
  15858. }
  15859. });
  15860. }
  15861. };
  15862. // Actually send the XHR request.
  15863. xhr.send(payload);
  15864. });
  15865. };
  15866. // Define the external interface.
  15867. var http = {
  15868. authBasic: function (username, password) {
  15869. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  15870. },
  15871. connect: function (url, options, callback) {
  15872. return ajax('CONNECT', url, options, callback);
  15873. },
  15874. del: function (url, options, callback) {
  15875. return ajax('DELETE', url, options, callback);
  15876. },
  15877. get: function (url, options, callback) {
  15878. return ajax('GET', url, options, callback);
  15879. },
  15880. head: function (url, options, callback) {
  15881. return ajax('HEAD', url, options, callback);
  15882. },
  15883. headers: function (headers) {
  15884. ajax.headers = headers || {};
  15885. },
  15886. isAllowed: function (url, verb, callback) {
  15887. this.options(url, function (status, data) {
  15888. callback(data.text().indexOf(verb) !== -1);
  15889. });
  15890. },
  15891. options: function (url, options, callback) {
  15892. return ajax('OPTIONS', url, options, callback);
  15893. },
  15894. patch: function (url, options, callback) {
  15895. return ajax('PATCH', url, options, callback);
  15896. },
  15897. post: function (url, options, callback) {
  15898. return ajax('POST', url, options, callback);
  15899. },
  15900. put: function (url, options, callback) {
  15901. return ajax('PUT', url, options, callback);
  15902. },
  15903. trace: function (url, options, callback) {
  15904. return ajax('TRACE', url, options, callback);
  15905. }
  15906. };
  15907. var methode = options.type ? options.type.toLowerCase() : 'get';
  15908. http[methode](options.url, options, function (status, data) {
  15909. // file: protocol always gives status code 0, so check for data
  15910. if (status === 200 || (status === 0 && data.text())) {
  15911. options.success(data.json(), status, null);
  15912. } else {
  15913. options.error(data.text(), status, null);
  15914. }
  15915. });
  15916. }
  15917. var _cookie = {
  15918. create: function(name,value,minutes,domain) {
  15919. var expires;
  15920. if (minutes) {
  15921. var date = new Date();
  15922. date.setTime(date.getTime()+(minutes*60*1000));
  15923. expires = "; expires="+date.toGMTString();
  15924. }
  15925. else expires = "";
  15926. domain = (domain)? "domain="+domain+";" : "";
  15927. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  15928. },
  15929. read: function(name) {
  15930. var nameEQ = name + "=";
  15931. var ca = document.cookie.split(';');
  15932. for(var i=0;i < ca.length;i++) {
  15933. var c = ca[i];
  15934. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  15935. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  15936. }
  15937. return null;
  15938. },
  15939. remove: function(name) {
  15940. this.create(name,"",-1);
  15941. }
  15942. };
  15943. var cookie_noop = {
  15944. create: function(name,value,minutes,domain) {},
  15945. read: function(name) { return null; },
  15946. remove: function(name) {}
  15947. };
  15948. // move dependent functions to a container so that
  15949. // they can be overriden easier in no jquery environment (node.js)
  15950. var f = {
  15951. extend: $ ? $.extend : _extend,
  15952. deepExtend: _deepExtend,
  15953. each: $ ? $.each : _each,
  15954. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  15955. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  15956. detectLanguage: detectLanguage,
  15957. escape: _escape,
  15958. log: function(str) {
  15959. if (o.debug && typeof console !== "undefined") console.log(str);
  15960. },
  15961. error: function(str) {
  15962. if (typeof console !== "undefined") console.error(str);
  15963. },
  15964. getCountyIndexOfLng: function(lng) {
  15965. var lng_index = 0;
  15966. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  15967. return lng_index;
  15968. },
  15969. toLanguages: function(lng) {
  15970. var log = this.log;
  15971. function applyCase(l) {
  15972. var ret = l;
  15973. if (typeof l === 'string' && l.indexOf('-') > -1) {
  15974. var parts = l.split('-');
  15975. ret = o.lowerCaseLng ?
  15976. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  15977. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  15978. } else {
  15979. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  15980. }
  15981. return ret;
  15982. }
  15983. var languages = [];
  15984. var whitelist = o.lngWhitelist || false;
  15985. var addLanguage = function(language){
  15986. //reject langs not whitelisted
  15987. if(!whitelist || whitelist.indexOf(language) > -1){
  15988. languages.push(language);
  15989. }else{
  15990. log('rejecting non-whitelisted language: ' + language);
  15991. }
  15992. };
  15993. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  15994. var parts = lng.split('-');
  15995. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  15996. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  15997. } else {
  15998. addLanguage(applyCase(lng));
  15999. }
  16000. for (var i = 0; i < o.fallbackLng.length; i++) {
  16001. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  16002. }
  16003. return languages;
  16004. },
  16005. regexEscape: function(str) {
  16006. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  16007. },
  16008. regexReplacementEscape: function(strOrFn) {
  16009. if (typeof strOrFn === 'string') {
  16010. return strOrFn.replace(/\$/g, "$$$$");
  16011. } else {
  16012. return strOrFn;
  16013. }
  16014. },
  16015. localStorage: {
  16016. setItem: function(key, value) {
  16017. if (window.localStorage) {
  16018. try {
  16019. window.localStorage.setItem(key, value);
  16020. } catch (e) {
  16021. f.log('failed to set value for key "' + key + '" to localStorage.');
  16022. }
  16023. }
  16024. }
  16025. }
  16026. };
  16027. function init(options, cb) {
  16028. if (typeof options === 'function') {
  16029. cb = options;
  16030. options = {};
  16031. }
  16032. options = options || {};
  16033. // override defaults with passed in options
  16034. f.extend(o, options);
  16035. delete o.fixLng; /* passed in each time */
  16036. // override functions: .log(), .detectLanguage(), etc
  16037. if (o.functions) {
  16038. delete o.functions;
  16039. f.extend(f, options.functions);
  16040. }
  16041. // create namespace object if namespace is passed in as string
  16042. if (typeof o.ns == 'string') {
  16043. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  16044. }
  16045. // fallback namespaces
  16046. if (typeof o.fallbackNS == 'string') {
  16047. o.fallbackNS = [o.fallbackNS];
  16048. }
  16049. // fallback languages
  16050. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  16051. o.fallbackLng = [o.fallbackLng];
  16052. }
  16053. // escape prefix/suffix
  16054. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  16055. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  16056. if (!o.lng) o.lng = f.detectLanguage();
  16057. languages = f.toLanguages(o.lng);
  16058. currentLng = languages[0];
  16059. f.log('currentLng set to: ' + currentLng);
  16060. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  16061. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  16062. }
  16063. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  16064. f.localStorage.setItem('i18next_lng', currentLng);
  16065. }
  16066. var lngTranslate = translate;
  16067. if (options.fixLng) {
  16068. lngTranslate = function(key, options) {
  16069. options = options || {};
  16070. options.lng = options.lng || lngTranslate.lng;
  16071. return translate(key, options);
  16072. };
  16073. lngTranslate.lng = currentLng;
  16074. }
  16075. pluralExtensions.setCurrentLng(currentLng);
  16076. // add JQuery extensions
  16077. if ($ && o.setJqueryExt) addJqueryFunct();
  16078. // jQuery deferred
  16079. var deferred;
  16080. if ($ && $.Deferred) {
  16081. deferred = $.Deferred();
  16082. }
  16083. // return immidiatly if res are passed in
  16084. if (o.resStore) {
  16085. resStore = o.resStore;
  16086. initialized = true;
  16087. if (cb) cb(lngTranslate);
  16088. if (deferred) deferred.resolve(lngTranslate);
  16089. if (deferred) return deferred.promise();
  16090. return;
  16091. }
  16092. // languages to load
  16093. var lngsToLoad = f.toLanguages(o.lng);
  16094. if (typeof o.preload === 'string') o.preload = [o.preload];
  16095. for (var i = 0, l = o.preload.length; i < l; i++) {
  16096. var pres = f.toLanguages(o.preload[i]);
  16097. for (var y = 0, len = pres.length; y < len; y++) {
  16098. if (lngsToLoad.indexOf(pres[y]) < 0) {
  16099. lngsToLoad.push(pres[y]);
  16100. }
  16101. }
  16102. }
  16103. // else load them
  16104. i18n.sync.load(lngsToLoad, o, function(err, store) {
  16105. resStore = store;
  16106. initialized = true;
  16107. if (cb) cb(lngTranslate);
  16108. if (deferred) deferred.resolve(lngTranslate);
  16109. });
  16110. if (deferred) return deferred.promise();
  16111. }
  16112. function preload(lngs, cb) {
  16113. if (typeof lngs === 'string') lngs = [lngs];
  16114. for (var i = 0, l = lngs.length; i < l; i++) {
  16115. if (o.preload.indexOf(lngs[i]) < 0) {
  16116. o.preload.push(lngs[i]);
  16117. }
  16118. }
  16119. return init(cb);
  16120. }
  16121. function addResourceBundle(lng, ns, resources, deep) {
  16122. if (typeof ns !== 'string') {
  16123. resources = ns;
  16124. ns = o.ns.defaultNs;
  16125. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  16126. o.ns.namespaces.push(ns);
  16127. }
  16128. resStore[lng] = resStore[lng] || {};
  16129. resStore[lng][ns] = resStore[lng][ns] || {};
  16130. if (deep) {
  16131. f.deepExtend(resStore[lng][ns], resources);
  16132. } else {
  16133. f.extend(resStore[lng][ns], resources);
  16134. }
  16135. }
  16136. function hasResourceBundle(lng, ns) {
  16137. if (typeof ns !== 'string') {
  16138. ns = o.ns.defaultNs;
  16139. }
  16140. resStore[lng] = resStore[lng] || {};
  16141. var res = resStore[lng][ns] || {};
  16142. var hasValues = false;
  16143. for(var prop in res) {
  16144. if (res.hasOwnProperty(prop)) {
  16145. hasValues = true;
  16146. }
  16147. }
  16148. return hasValues;
  16149. }
  16150. function removeResourceBundle(lng, ns) {
  16151. if (typeof ns !== 'string') {
  16152. ns = o.ns.defaultNs;
  16153. }
  16154. resStore[lng] = resStore[lng] || {};
  16155. resStore[lng][ns] = {};
  16156. }
  16157. function addResource(lng, ns, key, value) {
  16158. if (typeof ns !== 'string') {
  16159. resource = ns;
  16160. ns = o.ns.defaultNs;
  16161. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  16162. o.ns.namespaces.push(ns);
  16163. }
  16164. resStore[lng] = resStore[lng] || {};
  16165. resStore[lng][ns] = resStore[lng][ns] || {};
  16166. var keys = key.split(o.keyseparator);
  16167. var x = 0;
  16168. var node = resStore[lng][ns];
  16169. var origRef = node;
  16170. while (keys[x]) {
  16171. if (x == keys.length - 1)
  16172. node[keys[x]] = value;
  16173. else {
  16174. if (node[keys[x]] == null)
  16175. node[keys[x]] = {};
  16176. node = node[keys[x]];
  16177. }
  16178. x++;
  16179. }
  16180. }
  16181. function addResources(lng, ns, resources) {
  16182. if (typeof ns !== 'string') {
  16183. resource = ns;
  16184. ns = o.ns.defaultNs;
  16185. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  16186. o.ns.namespaces.push(ns);
  16187. }
  16188. for (var m in resources) {
  16189. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  16190. }
  16191. }
  16192. function setDefaultNamespace(ns) {
  16193. o.ns.defaultNs = ns;
  16194. }
  16195. function loadNamespace(namespace, cb) {
  16196. loadNamespaces([namespace], cb);
  16197. }
  16198. function loadNamespaces(namespaces, cb) {
  16199. var opts = {
  16200. dynamicLoad: o.dynamicLoad,
  16201. resGetPath: o.resGetPath,
  16202. getAsync: o.getAsync,
  16203. customLoad: o.customLoad,
  16204. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  16205. };
  16206. // languages to load
  16207. var lngsToLoad = f.toLanguages(o.lng);
  16208. if (typeof o.preload === 'string') o.preload = [o.preload];
  16209. for (var i = 0, l = o.preload.length; i < l; i++) {
  16210. var pres = f.toLanguages(o.preload[i]);
  16211. for (var y = 0, len = pres.length; y < len; y++) {
  16212. if (lngsToLoad.indexOf(pres[y]) < 0) {
  16213. lngsToLoad.push(pres[y]);
  16214. }
  16215. }
  16216. }
  16217. // check if we have to load
  16218. var lngNeedLoad = [];
  16219. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  16220. var needLoad = false;
  16221. var resSet = resStore[lngsToLoad[a]];
  16222. if (resSet) {
  16223. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  16224. if (!resSet[namespaces[b]]) needLoad = true;
  16225. }
  16226. } else {
  16227. needLoad = true;
  16228. }
  16229. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  16230. }
  16231. if (lngNeedLoad.length) {
  16232. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  16233. var todo = namespaces.length * lngNeedLoad.length;
  16234. // load each file individual
  16235. f.each(namespaces, function(nsIndex, nsValue) {
  16236. // append namespace to namespace array
  16237. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  16238. o.ns.namespaces.push(nsValue);
  16239. }
  16240. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  16241. resStore[lngValue] = resStore[lngValue] || {};
  16242. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  16243. todo--; // wait for all done befor callback
  16244. if (todo === 0 && cb) {
  16245. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  16246. cb();
  16247. }
  16248. });
  16249. });
  16250. });
  16251. } else {
  16252. if (cb) cb();
  16253. }
  16254. }
  16255. function setLng(lng, options, cb) {
  16256. if (typeof options === 'function') {
  16257. cb = options;
  16258. options = {};
  16259. } else if (!options) {
  16260. options = {};
  16261. }
  16262. options.lng = lng;
  16263. return init(options, cb);
  16264. }
  16265. function lng() {
  16266. return currentLng;
  16267. }
  16268. function reload(cb) {
  16269. resStore = {};
  16270. setLng(currentLng, cb);
  16271. }
  16272. function addJqueryFunct() {
  16273. // $.t shortcut
  16274. $.t = $.t || translate;
  16275. function parse(ele, key, options) {
  16276. if (key.length === 0) return;
  16277. var attr = 'text';
  16278. if (key.indexOf('[') === 0) {
  16279. var parts = key.split(']');
  16280. key = parts[1];
  16281. attr = parts[0].substr(1, parts[0].length-1);
  16282. }
  16283. if (key.indexOf(';') === key.length-1) {
  16284. key = key.substr(0, key.length-2);
  16285. }
  16286. var optionsToUse;
  16287. if (attr === 'html') {
  16288. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16289. ele.html($.t(key, optionsToUse));
  16290. } else if (attr === 'text') {
  16291. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  16292. ele.text($.t(key, optionsToUse));
  16293. } else if (attr === 'prepend') {
  16294. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16295. ele.prepend($.t(key, optionsToUse));
  16296. } else if (attr === 'append') {
  16297. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16298. ele.append($.t(key, optionsToUse));
  16299. } else if (attr.indexOf("data-") === 0) {
  16300. var dataAttr = attr.substr(("data-").length);
  16301. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  16302. var translated = $.t(key, optionsToUse);
  16303. //we change into the data cache
  16304. ele.data(dataAttr, translated);
  16305. //we change into the dom
  16306. ele.attr(attr, translated);
  16307. } else {
  16308. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  16309. ele.attr(attr, $.t(key, optionsToUse));
  16310. }
  16311. }
  16312. function localize(ele, options) {
  16313. var key = ele.attr(o.selectorAttr);
  16314. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  16315. if (!key) return;
  16316. var target = ele
  16317. , targetSelector = ele.data("i18n-target");
  16318. if (targetSelector) {
  16319. target = ele.find(targetSelector) || ele;
  16320. }
  16321. if (!options && o.useDataAttrOptions === true) {
  16322. options = ele.data("i18n-options");
  16323. }
  16324. options = options || {};
  16325. if (key.indexOf(';') >= 0) {
  16326. var keys = key.split(';');
  16327. $.each(keys, function(m, k) {
  16328. if (k !== '') parse(target, k, options);
  16329. });
  16330. } else {
  16331. parse(target, key, options);
  16332. }
  16333. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  16334. }
  16335. // fn
  16336. $.fn.i18n = function (options) {
  16337. return this.each(function() {
  16338. // localize element itself
  16339. localize($(this), options);
  16340. // localize childs
  16341. var elements = $(this).find('[' + o.selectorAttr + ']');
  16342. elements.each(function() {
  16343. localize($(this), options);
  16344. });
  16345. });
  16346. };
  16347. }
  16348. function applyReplacement(str, replacementHash, nestedKey, options) {
  16349. if (!str) return str;
  16350. options = options || replacementHash; // first call uses replacement hash combined with options
  16351. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  16352. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  16353. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  16354. , unEscapingSuffix = 'HTML'+suffix;
  16355. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  16356. f.each(hash, function(key, value) {
  16357. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  16358. if (typeof value === 'object' && value !== null) {
  16359. str = applyReplacement(str, value, nextKey, options);
  16360. } else {
  16361. if (options.escapeInterpolation || o.escapeInterpolation) {
  16362. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  16363. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  16364. } else {
  16365. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  16366. }
  16367. // str = options.escapeInterpolation;
  16368. }
  16369. });
  16370. return str;
  16371. }
  16372. // append it to functions
  16373. f.applyReplacement = applyReplacement;
  16374. function applyReuse(translated, options) {
  16375. var comma = ',';
  16376. var options_open = '{';
  16377. var options_close = '}';
  16378. var opts = f.extend({}, options);
  16379. delete opts.postProcess;
  16380. while (translated.indexOf(o.reusePrefix) != -1) {
  16381. replacementCounter++;
  16382. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  16383. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  16384. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  16385. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  16386. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  16387. if (index_of_end_of_closing <= index_of_opening) {
  16388. f.error('there is an missing closing in following translation value', translated);
  16389. return '';
  16390. }
  16391. if (token_without_symbols.indexOf(comma) != -1) {
  16392. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  16393. 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) {
  16394. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  16395. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  16396. try {
  16397. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  16398. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  16399. } catch (e) {
  16400. }
  16401. }
  16402. }
  16403. var translated_token = _translate(token_without_symbols, opts);
  16404. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  16405. }
  16406. return translated;
  16407. }
  16408. function hasContext(options) {
  16409. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  16410. }
  16411. function needsPlural(options, lng) {
  16412. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  16413. }
  16414. function needsIndefiniteArticle(options) {
  16415. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  16416. }
  16417. function exists(key, options) {
  16418. options = options || {};
  16419. var notFound = _getDefaultValue(key, options)
  16420. , found = _find(key, options);
  16421. return found !== undefined || found === notFound;
  16422. }
  16423. function translate(key, options) {
  16424. options = options || {};
  16425. if (!initialized) {
  16426. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  16427. return options.defaultValue || '';
  16428. };
  16429. replacementCounter = 0;
  16430. return _translate.apply(null, arguments);
  16431. }
  16432. function _getDefaultValue(key, options) {
  16433. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  16434. }
  16435. function _injectSprintfProcessor() {
  16436. var values = [];
  16437. // mh: build array from second argument onwards
  16438. for (var i = 1; i < arguments.length; i++) {
  16439. values.push(arguments[i]);
  16440. }
  16441. return {
  16442. postProcess: 'sprintf',
  16443. sprintf: values
  16444. };
  16445. }
  16446. function _translate(potentialKeys, options) {
  16447. if (options && typeof options !== 'object') {
  16448. if (o.shortcutFunction === 'sprintf') {
  16449. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  16450. options = _injectSprintfProcessor.apply(null, arguments);
  16451. } else if (o.shortcutFunction === 'defaultValue') {
  16452. options = {
  16453. defaultValue: options
  16454. }
  16455. }
  16456. } else {
  16457. options = options || {};
  16458. }
  16459. if (typeof o.defaultVariables === 'object') {
  16460. options = f.extend({}, o.defaultVariables, options);
  16461. }
  16462. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  16463. if (typeof potentialKeys === 'string') {
  16464. potentialKeys = [potentialKeys];
  16465. }
  16466. var key = potentialKeys[0];
  16467. if (potentialKeys.length > 1) {
  16468. for (var i = 0; i < potentialKeys.length; i++) {
  16469. key = potentialKeys[i];
  16470. if (exists(key, options)) {
  16471. break;
  16472. }
  16473. }
  16474. }
  16475. var notFound = _getDefaultValue(key, options)
  16476. , found = _find(key, options)
  16477. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  16478. , ns = options.ns || o.ns.defaultNs
  16479. , parts;
  16480. // split ns and key
  16481. if (key.indexOf(o.nsseparator) > -1) {
  16482. parts = key.split(o.nsseparator);
  16483. ns = parts[0];
  16484. key = parts[1];
  16485. }
  16486. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  16487. if (options.lng) {
  16488. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  16489. } else {
  16490. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  16491. }
  16492. }
  16493. var postProcessor = options.postProcess || o.postProcess;
  16494. if (found !== undefined && postProcessor) {
  16495. if (postProcessors[postProcessor]) {
  16496. found = postProcessors[postProcessor](found, key, options);
  16497. }
  16498. }
  16499. // process notFound if function exists
  16500. var splitNotFound = notFound;
  16501. if (notFound.indexOf(o.nsseparator) > -1) {
  16502. parts = notFound.split(o.nsseparator);
  16503. splitNotFound = parts[1];
  16504. }
  16505. if (splitNotFound === key && o.parseMissingKey) {
  16506. notFound = o.parseMissingKey(notFound);
  16507. }
  16508. if (found === undefined) {
  16509. notFound = applyReplacement(notFound, options);
  16510. notFound = applyReuse(notFound, options);
  16511. if (postProcessor && postProcessors[postProcessor]) {
  16512. var val = _getDefaultValue(key, options);
  16513. found = postProcessors[postProcessor](val, key, options);
  16514. }
  16515. }
  16516. return (found !== undefined) ? found : notFound;
  16517. }
  16518. function _find(key, options) {
  16519. options = options || {};
  16520. var optionWithoutCount, translated
  16521. , notFound = _getDefaultValue(key, options)
  16522. , lngs = languages;
  16523. if (!resStore) { return notFound; } // no resStore to translate from
  16524. // CI mode
  16525. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  16526. // passed in lng
  16527. if (options.lngs) lngs = options.lngs;
  16528. if (options.lng) {
  16529. lngs = f.toLanguages(options.lng, options.fallbackLng);
  16530. if (!resStore[lngs[0]]) {
  16531. var oldAsync = o.getAsync;
  16532. o.getAsync = false;
  16533. i18n.sync.load(lngs, o, function(err, store) {
  16534. f.extend(resStore, store);
  16535. o.getAsync = oldAsync;
  16536. });
  16537. }
  16538. }
  16539. var ns = options.ns || o.ns.defaultNs;
  16540. if (key.indexOf(o.nsseparator) > -1) {
  16541. var parts = key.split(o.nsseparator);
  16542. ns = parts[0];
  16543. key = parts[1];
  16544. }
  16545. if (hasContext(options)) {
  16546. optionWithoutCount = f.extend({}, options);
  16547. delete optionWithoutCount.context;
  16548. optionWithoutCount.defaultValue = o.contextNotFound;
  16549. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  16550. translated = translate(contextKey, optionWithoutCount);
  16551. if (translated != o.contextNotFound) {
  16552. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  16553. } // else continue translation with original/nonContext key
  16554. }
  16555. if (needsPlural(options, lngs[0])) {
  16556. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  16557. delete optionWithoutCount.count;
  16558. delete optionWithoutCount.lng;
  16559. optionWithoutCount.defaultValue = o.pluralNotFound;
  16560. var pluralKey;
  16561. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  16562. pluralKey = ns + o.nsseparator + key;
  16563. } else {
  16564. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  16565. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  16566. if (pluralExtension >= 0) {
  16567. pluralKey = pluralKey + '_' + pluralExtension;
  16568. } else if (pluralExtension === 1) {
  16569. pluralKey = ns + o.nsseparator + key; // singular
  16570. }
  16571. }
  16572. translated = translate(pluralKey, optionWithoutCount);
  16573. if (translated != o.pluralNotFound) {
  16574. return applyReplacement(translated, {
  16575. count: options.count,
  16576. interpolationPrefix: options.interpolationPrefix,
  16577. interpolationSuffix: options.interpolationSuffix
  16578. }); // apply replacement for count only
  16579. } else if (lngs.length > 1) {
  16580. // remove failed lng
  16581. var clone = lngs.slice();
  16582. clone.shift();
  16583. options = f.extend(options, { lngs: clone });
  16584. delete options.lng;
  16585. // retry with fallbacks
  16586. translated = translate(ns + o.nsseparator + key, options);
  16587. if (translated != o.pluralNotFound) return translated;
  16588. } else {
  16589. return translated;
  16590. }
  16591. }
  16592. if (needsIndefiniteArticle(options)) {
  16593. var optionsWithoutIndef = f.extend({}, options);
  16594. delete optionsWithoutIndef.indefinite_article;
  16595. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  16596. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  16597. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  16598. translated = translate(indefiniteKey, optionsWithoutIndef);
  16599. if (translated != o.indefiniteNotFound) {
  16600. return translated;
  16601. }
  16602. }
  16603. var found;
  16604. var keys = key.split(o.keyseparator);
  16605. for (var i = 0, len = lngs.length; i < len; i++ ) {
  16606. if (found !== undefined) break;
  16607. var l = lngs[i];
  16608. var x = 0;
  16609. var value = resStore[l] && resStore[l][ns];
  16610. while (keys[x]) {
  16611. value = value && value[keys[x]];
  16612. x++;
  16613. }
  16614. if (value !== undefined) {
  16615. var valueType = Object.prototype.toString.apply(value);
  16616. if (typeof value === 'string') {
  16617. value = applyReplacement(value, options);
  16618. value = applyReuse(value, options);
  16619. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  16620. value = value.join('\n');
  16621. value = applyReplacement(value, options);
  16622. value = applyReuse(value, options);
  16623. } else if (value === null && o.fallbackOnNull === true) {
  16624. value = undefined;
  16625. } else if (value !== null) {
  16626. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  16627. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  16628. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  16629. } else {
  16630. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  16631. 'returned an object instead of string.';
  16632. f.log(value);
  16633. }
  16634. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  16635. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  16636. f.each(value, function(m) {
  16637. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  16638. });
  16639. value = copy;
  16640. }
  16641. }
  16642. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  16643. value = undefined;
  16644. found = value;
  16645. }
  16646. }
  16647. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  16648. // set flag for fallback lookup - avoid recursion
  16649. options.isFallbackLookup = true;
  16650. if (o.fallbackNS.length) {
  16651. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  16652. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  16653. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  16654. /* compare value without namespace */
  16655. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  16656. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  16657. if (foundValue !== notFoundValue) break;
  16658. }
  16659. }
  16660. } else {
  16661. found = _find(key, options); // fallback to default NS
  16662. }
  16663. options.isFallbackLookup = false;
  16664. }
  16665. return found;
  16666. }
  16667. function detectLanguage() {
  16668. var detectedLng;
  16669. var whitelist = o.lngWhitelist || [];
  16670. var userLngChoices = [];
  16671. // get from qs
  16672. var qsParm = [];
  16673. if (typeof window !== 'undefined') {
  16674. (function() {
  16675. var query = window.location.search.substring(1);
  16676. var params = query.split('&');
  16677. for (var i=0; i<params.length; i++) {
  16678. var pos = params[i].indexOf('=');
  16679. if (pos > 0) {
  16680. var key = params[i].substring(0,pos);
  16681. if (key == o.detectLngQS) {
  16682. userLngChoices.push(params[i].substring(pos+1));
  16683. }
  16684. }
  16685. }
  16686. })();
  16687. }
  16688. // get from cookie
  16689. if (o.useCookie && typeof document !== 'undefined') {
  16690. var c = f.cookie.read(o.cookieName);
  16691. if (c) userLngChoices.push(c);
  16692. }
  16693. // get from localStorage
  16694. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  16695. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  16696. }
  16697. // get from navigator
  16698. if (typeof navigator !== 'undefined') {
  16699. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  16700. for (var i=0;i<navigator.languages.length;i++) {
  16701. userLngChoices.push(navigator.languages[i]);
  16702. }
  16703. }
  16704. if (navigator.userLanguage) {
  16705. userLngChoices.push(navigator.userLanguage);
  16706. }
  16707. if (navigator.language) {
  16708. userLngChoices.push(navigator.language);
  16709. }
  16710. }
  16711. (function() {
  16712. for (var i=0;i<userLngChoices.length;i++) {
  16713. var lng = userLngChoices[i];
  16714. if (lng.indexOf('-') > -1) {
  16715. var parts = lng.split('-');
  16716. lng = o.lowerCaseLng ?
  16717. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  16718. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  16719. }
  16720. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  16721. detectedLng = lng;
  16722. break;
  16723. }
  16724. }
  16725. })();
  16726. //fallback
  16727. if (!detectedLng){
  16728. detectedLng = o.fallbackLng[0];
  16729. }
  16730. return detectedLng;
  16731. }
  16732. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  16733. /* [code, name, numbers, pluralsType] */
  16734. var _rules = [
  16735. ["ach", "Acholi", [1,2], 1],
  16736. ["af", "Afrikaans",[1,2], 2],
  16737. ["ak", "Akan", [1,2], 1],
  16738. ["am", "Amharic", [1,2], 1],
  16739. ["an", "Aragonese",[1,2], 2],
  16740. ["ar", "Arabic", [0,1,2,3,11,100],5],
  16741. ["arn", "Mapudungun",[1,2], 1],
  16742. ["ast", "Asturian", [1,2], 2],
  16743. ["ay", "Aymará", [1], 3],
  16744. ["az", "Azerbaijani",[1,2],2],
  16745. ["be", "Belarusian",[1,2,5],4],
  16746. ["bg", "Bulgarian",[1,2], 2],
  16747. ["bn", "Bengali", [1,2], 2],
  16748. ["bo", "Tibetan", [1], 3],
  16749. ["br", "Breton", [1,2], 1],
  16750. ["bs", "Bosnian", [1,2,5],4],
  16751. ["ca", "Catalan", [1,2], 2],
  16752. ["cgg", "Chiga", [1], 3],
  16753. ["cs", "Czech", [1,2,5],6],
  16754. ["csb", "Kashubian",[1,2,5],7],
  16755. ["cy", "Welsh", [1,2,3,8],8],
  16756. ["da", "Danish", [1,2], 2],
  16757. ["de", "German", [1,2], 2],
  16758. ["dev", "Development Fallback", [1,2], 2],
  16759. ["dz", "Dzongkha", [1], 3],
  16760. ["el", "Greek", [1,2], 2],
  16761. ["en", "English", [1,2], 2],
  16762. ["eo", "Esperanto",[1,2], 2],
  16763. ["es", "Spanish", [1,2], 2],
  16764. ["es_ar","Argentinean Spanish", [1,2], 2],
  16765. ["et", "Estonian", [1,2], 2],
  16766. ["eu", "Basque", [1,2], 2],
  16767. ["fa", "Persian", [1], 3],
  16768. ["fi", "Finnish", [1,2], 2],
  16769. ["fil", "Filipino", [1,2], 1],
  16770. ["fo", "Faroese", [1,2], 2],
  16771. ["fr", "French", [1,2], 9],
  16772. ["fur", "Friulian", [1,2], 2],
  16773. ["fy", "Frisian", [1,2], 2],
  16774. ["ga", "Irish", [1,2,3,7,11],10],
  16775. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  16776. ["gl", "Galician", [1,2], 2],
  16777. ["gu", "Gujarati", [1,2], 2],
  16778. ["gun", "Gun", [1,2], 1],
  16779. ["ha", "Hausa", [1,2], 2],
  16780. ["he", "Hebrew", [1,2], 2],
  16781. ["hi", "Hindi", [1,2], 2],
  16782. ["hr", "Croatian", [1,2,5],4],
  16783. ["hu", "Hungarian",[1,2], 2],
  16784. ["hy", "Armenian", [1,2], 2],
  16785. ["ia", "Interlingua",[1,2],2],
  16786. ["id", "Indonesian",[1], 3],
  16787. ["is", "Icelandic",[1,2], 12],
  16788. ["it", "Italian", [1,2], 2],
  16789. ["ja", "Japanese", [1], 3],
  16790. ["jbo", "Lojban", [1], 3],
  16791. ["jv", "Javanese", [0,1], 13],
  16792. ["ka", "Georgian", [1], 3],
  16793. ["kk", "Kazakh", [1], 3],
  16794. ["km", "Khmer", [1], 3],
  16795. ["kn", "Kannada", [1,2], 2],
  16796. ["ko", "Korean", [1], 3],
  16797. ["ku", "Kurdish", [1,2], 2],
  16798. ["kw", "Cornish", [1,2,3,4],14],
  16799. ["ky", "Kyrgyz", [1], 3],
  16800. ["lb", "Letzeburgesch",[1,2],2],
  16801. ["ln", "Lingala", [1,2], 1],
  16802. ["lo", "Lao", [1], 3],
  16803. ["lt", "Lithuanian",[1,2,10],15],
  16804. ["lv", "Latvian", [1,2,0],16],
  16805. ["mai", "Maithili", [1,2], 2],
  16806. ["mfe", "Mauritian Creole",[1,2],1],
  16807. ["mg", "Malagasy", [1,2], 1],
  16808. ["mi", "Maori", [1,2], 1],
  16809. ["mk", "Macedonian",[1,2],17],
  16810. ["ml", "Malayalam",[1,2], 2],
  16811. ["mn", "Mongolian",[1,2], 2],
  16812. ["mnk", "Mandinka", [0,1,2],18],
  16813. ["mr", "Marathi", [1,2], 2],
  16814. ["ms", "Malay", [1], 3],
  16815. ["mt", "Maltese", [1,2,11,20],19],
  16816. ["nah", "Nahuatl", [1,2], 2],
  16817. ["nap", "Neapolitan",[1,2], 2],
  16818. ["nb", "Norwegian Bokmal",[1,2],2],
  16819. ["ne", "Nepali", [1,2], 2],
  16820. ["nl", "Dutch", [1,2], 2],
  16821. ["nn", "Norwegian Nynorsk",[1,2],2],
  16822. ["no", "Norwegian",[1,2], 2],
  16823. ["nso", "Northern Sotho",[1,2],2],
  16824. ["oc", "Occitan", [1,2], 1],
  16825. ["or", "Oriya", [2,1], 2],
  16826. ["pa", "Punjabi", [1,2], 2],
  16827. ["pap", "Papiamento",[1,2], 2],
  16828. ["pl", "Polish", [1,2,5],7],
  16829. ["pms", "Piemontese",[1,2], 2],
  16830. ["ps", "Pashto", [1,2], 2],
  16831. ["pt", "Portuguese",[1,2], 2],
  16832. ["pt_br","Brazilian Portuguese",[1,2], 2],
  16833. ["rm", "Romansh", [1,2], 2],
  16834. ["ro", "Romanian", [1,2,20],20],
  16835. ["ru", "Russian", [1,2,5],4],
  16836. ["sah", "Yakut", [1], 3],
  16837. ["sco", "Scots", [1,2], 2],
  16838. ["se", "Northern Sami",[1,2], 2],
  16839. ["si", "Sinhala", [1,2], 2],
  16840. ["sk", "Slovak", [1,2,5],6],
  16841. ["sl", "Slovenian",[5,1,2,3],21],
  16842. ["so", "Somali", [1,2], 2],
  16843. ["son", "Songhay", [1,2], 2],
  16844. ["sq", "Albanian", [1,2], 2],
  16845. ["sr", "Serbian", [1,2,5],4],
  16846. ["su", "Sundanese",[1], 3],
  16847. ["sv", "Swedish", [1,2], 2],
  16848. ["sw", "Swahili", [1,2], 2],
  16849. ["ta", "Tamil", [1,2], 2],
  16850. ["te", "Telugu", [1,2], 2],
  16851. ["tg", "Tajik", [1,2], 1],
  16852. ["th", "Thai", [1], 3],
  16853. ["ti", "Tigrinya", [1,2], 1],
  16854. ["tk", "Turkmen", [1,2], 2],
  16855. ["tr", "Turkish", [1,2], 1],
  16856. ["tt", "Tatar", [1], 3],
  16857. ["ug", "Uyghur", [1], 3],
  16858. ["uk", "Ukrainian",[1,2,5],4],
  16859. ["ur", "Urdu", [1,2], 2],
  16860. ["uz", "Uzbek", [1,2], 1],
  16861. ["vi", "Vietnamese",[1], 3],
  16862. ["wa", "Walloon", [1,2], 1],
  16863. ["wo", "Wolof", [1], 3],
  16864. ["yo", "Yoruba", [1,2], 2],
  16865. ["zh", "Chinese", [1], 3]
  16866. ];
  16867. var _rulesPluralsTypes = {
  16868. 1: function(n) {return Number(n > 1);},
  16869. 2: function(n) {return Number(n != 1);},
  16870. 3: function(n) {return 0;},
  16871. 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);},
  16872. 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);},
  16873. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  16874. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16875. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  16876. 9: function(n) {return Number(n >= 2);},
  16877. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  16878. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  16879. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  16880. 13: function(n) {return Number(n !== 0);},
  16881. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  16882. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16883. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  16884. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  16885. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  16886. 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);},
  16887. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  16888. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  16889. };
  16890. var pluralExtensions = {
  16891. rules: (function () {
  16892. var l, rules = {};
  16893. for (l=_rules.length; l-- ;) {
  16894. rules[_rules[l][0]] = {
  16895. name: _rules[l][1],
  16896. numbers: _rules[l][2],
  16897. plurals: _rulesPluralsTypes[_rules[l][3]]
  16898. }
  16899. }
  16900. return rules;
  16901. }()),
  16902. // you can add your own pluralExtensions
  16903. addRule: function(lng, obj) {
  16904. pluralExtensions.rules[lng] = obj;
  16905. },
  16906. setCurrentLng: function(lng) {
  16907. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  16908. var parts = lng.split('-');
  16909. pluralExtensions.currentRule = {
  16910. lng: lng,
  16911. rule: pluralExtensions.rules[parts[0]]
  16912. };
  16913. }
  16914. },
  16915. needsPlural: function(lng, count) {
  16916. var parts = lng.split('-');
  16917. var ext;
  16918. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16919. ext = pluralExtensions.currentRule.rule;
  16920. } else {
  16921. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  16922. }
  16923. if (ext && ext.numbers.length <= 1) {
  16924. return false;
  16925. } else {
  16926. return this.get(lng, count) !== 1;
  16927. }
  16928. },
  16929. get: function(lng, count) {
  16930. var parts = lng.split('-');
  16931. function getResult(l, c) {
  16932. var ext;
  16933. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16934. ext = pluralExtensions.currentRule.rule;
  16935. } else {
  16936. ext = pluralExtensions.rules[l];
  16937. }
  16938. if (ext) {
  16939. var i;
  16940. if (ext.noAbs) {
  16941. i = ext.plurals(c);
  16942. } else {
  16943. i = ext.plurals(Math.abs(c));
  16944. }
  16945. var number = ext.numbers[i];
  16946. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  16947. if (number === 2) {
  16948. number = -1; // regular plural
  16949. } else if (number === 1) {
  16950. number = 1; // singular
  16951. }
  16952. }//console.log(count + '-' + number);
  16953. return number;
  16954. } else {
  16955. return c === 1 ? '1' : '-1';
  16956. }
  16957. }
  16958. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  16959. }
  16960. };
  16961. var postProcessors = {};
  16962. var addPostProcessor = function(name, fc) {
  16963. postProcessors[name] = fc;
  16964. };
  16965. // sprintf support
  16966. var sprintf = (function() {
  16967. function get_type(variable) {
  16968. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  16969. }
  16970. function str_repeat(input, multiplier) {
  16971. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  16972. return output.join('');
  16973. }
  16974. var str_format = function() {
  16975. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  16976. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  16977. }
  16978. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  16979. };
  16980. str_format.format = function(parse_tree, argv) {
  16981. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  16982. for (i = 0; i < tree_length; i++) {
  16983. node_type = get_type(parse_tree[i]);
  16984. if (node_type === 'string') {
  16985. output.push(parse_tree[i]);
  16986. }
  16987. else if (node_type === 'array') {
  16988. match = parse_tree[i]; // convenience purposes only
  16989. if (match[2]) { // keyword argument
  16990. arg = argv[cursor];
  16991. for (k = 0; k < match[2].length; k++) {
  16992. if (!arg.hasOwnProperty(match[2][k])) {
  16993. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  16994. }
  16995. arg = arg[match[2][k]];
  16996. }
  16997. }
  16998. else if (match[1]) { // positional argument (explicit)
  16999. arg = argv[match[1]];
  17000. }
  17001. else { // positional argument (implicit)
  17002. arg = argv[cursor++];
  17003. }
  17004. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  17005. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  17006. }
  17007. switch (match[8]) {
  17008. case 'b': arg = arg.toString(2); break;
  17009. case 'c': arg = String.fromCharCode(arg); break;
  17010. case 'd': arg = parseInt(arg, 10); break;
  17011. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  17012. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  17013. case 'o': arg = arg.toString(8); break;
  17014. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  17015. case 'u': arg = Math.abs(arg); break;
  17016. case 'x': arg = arg.toString(16); break;
  17017. case 'X': arg = arg.toString(16).toUpperCase(); break;
  17018. }
  17019. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  17020. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  17021. pad_length = match[6] - String(arg).length;
  17022. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  17023. output.push(match[5] ? arg + pad : pad + arg);
  17024. }
  17025. }
  17026. return output.join('');
  17027. };
  17028. str_format.cache = {};
  17029. str_format.parse = function(fmt) {
  17030. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  17031. while (_fmt) {
  17032. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  17033. parse_tree.push(match[0]);
  17034. }
  17035. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  17036. parse_tree.push('%');
  17037. }
  17038. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  17039. if (match[2]) {
  17040. arg_names |= 1;
  17041. var field_list = [], replacement_field = match[2], field_match = [];
  17042. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  17043. field_list.push(field_match[1]);
  17044. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  17045. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  17046. field_list.push(field_match[1]);
  17047. }
  17048. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  17049. field_list.push(field_match[1]);
  17050. }
  17051. else {
  17052. throw('[sprintf] huh?');
  17053. }
  17054. }
  17055. }
  17056. else {
  17057. throw('[sprintf] huh?');
  17058. }
  17059. match[2] = field_list;
  17060. }
  17061. else {
  17062. arg_names |= 2;
  17063. }
  17064. if (arg_names === 3) {
  17065. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  17066. }
  17067. parse_tree.push(match);
  17068. }
  17069. else {
  17070. throw('[sprintf] huh?');
  17071. }
  17072. _fmt = _fmt.substring(match[0].length);
  17073. }
  17074. return parse_tree;
  17075. };
  17076. return str_format;
  17077. })();
  17078. var vsprintf = function(fmt, argv) {
  17079. argv.unshift(fmt);
  17080. return sprintf.apply(null, argv);
  17081. };
  17082. addPostProcessor("sprintf", function(val, key, opts) {
  17083. if (!opts.sprintf) return val;
  17084. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  17085. return vsprintf(val, opts.sprintf);
  17086. } else if (typeof opts.sprintf === 'object') {
  17087. return sprintf(val, opts.sprintf);
  17088. }
  17089. return val;
  17090. });
  17091. // public api interface
  17092. i18n.init = init;
  17093. i18n.setLng = setLng;
  17094. i18n.preload = preload;
  17095. i18n.addResourceBundle = addResourceBundle;
  17096. i18n.hasResourceBundle = hasResourceBundle;
  17097. i18n.addResource = addResource;
  17098. i18n.addResources = addResources;
  17099. i18n.removeResourceBundle = removeResourceBundle;
  17100. i18n.loadNamespace = loadNamespace;
  17101. i18n.loadNamespaces = loadNamespaces;
  17102. i18n.setDefaultNamespace = setDefaultNamespace;
  17103. i18n.t = translate;
  17104. i18n.translate = translate;
  17105. i18n.exists = exists;
  17106. i18n.detectLanguage = f.detectLanguage;
  17107. i18n.pluralExtensions = pluralExtensions;
  17108. i18n.sync = sync;
  17109. i18n.functions = f;
  17110. i18n.lng = lng;
  17111. i18n.addPostProcessor = addPostProcessor;
  17112. i18n.options = o;
  17113. })();
  17114. },{"jquery":"jquery"}],63:[function(require,module,exports){
  17115. // Top level file is just a mixin of submodules & constants
  17116. 'use strict';
  17117. var assign = require('./lib/utils/common').assign;
  17118. var deflate = require('./lib/deflate');
  17119. var inflate = require('./lib/inflate');
  17120. var constants = require('./lib/zlib/constants');
  17121. var pako = {};
  17122. assign(pako, deflate, inflate, constants);
  17123. module.exports = pako;
  17124. },{"./lib/deflate":64,"./lib/inflate":65,"./lib/utils/common":66,"./lib/zlib/constants":69}],64:[function(require,module,exports){
  17125. 'use strict';
  17126. var zlib_deflate = require('./zlib/deflate.js');
  17127. var utils = require('./utils/common');
  17128. var strings = require('./utils/strings');
  17129. var msg = require('./zlib/messages');
  17130. var zstream = require('./zlib/zstream');
  17131. var toString = Object.prototype.toString;
  17132. /* Public constants ==========================================================*/
  17133. /* ===========================================================================*/
  17134. var Z_NO_FLUSH = 0;
  17135. var Z_FINISH = 4;
  17136. var Z_OK = 0;
  17137. var Z_STREAM_END = 1;
  17138. var Z_DEFAULT_COMPRESSION = -1;
  17139. var Z_DEFAULT_STRATEGY = 0;
  17140. var Z_DEFLATED = 8;
  17141. /* ===========================================================================*/
  17142. /**
  17143. * class Deflate
  17144. *
  17145. * Generic JS-style wrapper for zlib calls. If you don't need
  17146. * streaming behaviour - use more simple functions: [[deflate]],
  17147. * [[deflateRaw]] and [[gzip]].
  17148. **/
  17149. /* internal
  17150. * Deflate.chunks -> Array
  17151. *
  17152. * Chunks of output data, if [[Deflate#onData]] not overriden.
  17153. **/
  17154. /**
  17155. * Deflate.result -> Uint8Array|Array
  17156. *
  17157. * Compressed result, generated by default [[Deflate#onData]]
  17158. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  17159. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  17160. **/
  17161. /**
  17162. * Deflate.err -> Number
  17163. *
  17164. * Error code after deflate finished. 0 (Z_OK) on success.
  17165. * You will not need it in real life, because deflate errors
  17166. * are possible only on wrong options or bad `onData` / `onEnd`
  17167. * custom handlers.
  17168. **/
  17169. /**
  17170. * Deflate.msg -> String
  17171. *
  17172. * Error message, if [[Deflate.err]] != 0
  17173. **/
  17174. /**
  17175. * new Deflate(options)
  17176. * - options (Object): zlib deflate options.
  17177. *
  17178. * Creates new deflator instance with specified params. Throws exception
  17179. * on bad params. Supported options:
  17180. *
  17181. * - `level`
  17182. * - `windowBits`
  17183. * - `memLevel`
  17184. * - `strategy`
  17185. *
  17186. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17187. * for more information on these.
  17188. *
  17189. * Additional options, for internal needs:
  17190. *
  17191. * - `chunkSize` - size of generated data chunks (16K by default)
  17192. * - `raw` (Boolean) - do raw deflate
  17193. * - `gzip` (Boolean) - create gzip wrapper
  17194. * - `to` (String) - if equal to 'string', then result will be "binary string"
  17195. * (each char code [0..255])
  17196. * - `header` (Object) - custom header for gzip
  17197. * - `text` (Boolean) - true if compressed data believed to be text
  17198. * - `time` (Number) - modification time, unix timestamp
  17199. * - `os` (Number) - operation system code
  17200. * - `extra` (Array) - array of bytes with extra data (max 65536)
  17201. * - `name` (String) - file name (binary string)
  17202. * - `comment` (String) - comment (binary string)
  17203. * - `hcrc` (Boolean) - true if header crc should be added
  17204. *
  17205. * ##### Example:
  17206. *
  17207. * ```javascript
  17208. * var pako = require('pako')
  17209. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17210. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17211. *
  17212. * var deflate = new pako.Deflate({ level: 3});
  17213. *
  17214. * deflate.push(chunk1, false);
  17215. * deflate.push(chunk2, true); // true -> last chunk
  17216. *
  17217. * if (deflate.err) { throw new Error(deflate.err); }
  17218. *
  17219. * console.log(deflate.result);
  17220. * ```
  17221. **/
  17222. var Deflate = function(options) {
  17223. this.options = utils.assign({
  17224. level: Z_DEFAULT_COMPRESSION,
  17225. method: Z_DEFLATED,
  17226. chunkSize: 16384,
  17227. windowBits: 15,
  17228. memLevel: 8,
  17229. strategy: Z_DEFAULT_STRATEGY,
  17230. to: ''
  17231. }, options || {});
  17232. var opt = this.options;
  17233. if (opt.raw && (opt.windowBits > 0)) {
  17234. opt.windowBits = -opt.windowBits;
  17235. }
  17236. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  17237. opt.windowBits += 16;
  17238. }
  17239. this.err = 0; // error code, if happens (0 = Z_OK)
  17240. this.msg = ''; // error message
  17241. this.ended = false; // used to avoid multiple onEnd() calls
  17242. this.chunks = []; // chunks of compressed data
  17243. this.strm = new zstream();
  17244. this.strm.avail_out = 0;
  17245. var status = zlib_deflate.deflateInit2(
  17246. this.strm,
  17247. opt.level,
  17248. opt.method,
  17249. opt.windowBits,
  17250. opt.memLevel,
  17251. opt.strategy
  17252. );
  17253. if (status !== Z_OK) {
  17254. throw new Error(msg[status]);
  17255. }
  17256. if (opt.header) {
  17257. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  17258. }
  17259. };
  17260. /**
  17261. * Deflate#push(data[, mode]) -> Boolean
  17262. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  17263. * converted to utf8 byte sequence.
  17264. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17265. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17266. *
  17267. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  17268. * new compressed chunks. Returns `true` on success. The last data block must have
  17269. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17270. * [[Deflate#onEnd]].
  17271. *
  17272. * On fail call [[Deflate#onEnd]] with error code and return false.
  17273. *
  17274. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17275. * array format is detected automatically). Also, don't skip last param and always
  17276. * use the same type in your code (boolean or number). That will improve JS speed.
  17277. *
  17278. * For regular `Array`-s make sure all elements are [0..255].
  17279. *
  17280. * ##### Example
  17281. *
  17282. * ```javascript
  17283. * push(chunk, false); // push one of data chunks
  17284. * ...
  17285. * push(chunk, true); // push last chunk
  17286. * ```
  17287. **/
  17288. Deflate.prototype.push = function(data, mode) {
  17289. var strm = this.strm;
  17290. var chunkSize = this.options.chunkSize;
  17291. var status, _mode;
  17292. if (this.ended) { return false; }
  17293. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  17294. // Convert data if needed
  17295. if (typeof data === 'string') {
  17296. // If we need to compress text, change encoding to utf8.
  17297. strm.input = strings.string2buf(data);
  17298. } else if (toString.call(data) === '[object ArrayBuffer]') {
  17299. strm.input = new Uint8Array(data);
  17300. } else {
  17301. strm.input = data;
  17302. }
  17303. strm.next_in = 0;
  17304. strm.avail_in = strm.input.length;
  17305. do {
  17306. if (strm.avail_out === 0) {
  17307. strm.output = new utils.Buf8(chunkSize);
  17308. strm.next_out = 0;
  17309. strm.avail_out = chunkSize;
  17310. }
  17311. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  17312. if (status !== Z_STREAM_END && status !== Z_OK) {
  17313. this.onEnd(status);
  17314. this.ended = true;
  17315. return false;
  17316. }
  17317. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  17318. if (this.options.to === 'string') {
  17319. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  17320. } else {
  17321. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17322. }
  17323. }
  17324. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  17325. // Finalize on the last chunk.
  17326. if (_mode === Z_FINISH) {
  17327. status = zlib_deflate.deflateEnd(this.strm);
  17328. this.onEnd(status);
  17329. this.ended = true;
  17330. return status === Z_OK;
  17331. }
  17332. return true;
  17333. };
  17334. /**
  17335. * Deflate#onData(chunk) -> Void
  17336. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17337. * on js engine support. When string output requested, each chunk
  17338. * will be string.
  17339. *
  17340. * By default, stores data blocks in `chunks[]` property and glue
  17341. * those in `onEnd`. Override this handler, if you need another behaviour.
  17342. **/
  17343. Deflate.prototype.onData = function(chunk) {
  17344. this.chunks.push(chunk);
  17345. };
  17346. /**
  17347. * Deflate#onEnd(status) -> Void
  17348. * - status (Number): deflate status. 0 (Z_OK) on success,
  17349. * other if not.
  17350. *
  17351. * Called once after you tell deflate that input stream complete
  17352. * or error happenned. By default - join collected chunks,
  17353. * free memory and fill `results` / `err` properties.
  17354. **/
  17355. Deflate.prototype.onEnd = function(status) {
  17356. // On success - join
  17357. if (status === Z_OK) {
  17358. if (this.options.to === 'string') {
  17359. this.result = this.chunks.join('');
  17360. } else {
  17361. this.result = utils.flattenChunks(this.chunks);
  17362. }
  17363. }
  17364. this.chunks = [];
  17365. this.err = status;
  17366. this.msg = this.strm.msg;
  17367. };
  17368. /**
  17369. * deflate(data[, options]) -> Uint8Array|Array|String
  17370. * - data (Uint8Array|Array|String): input data to compress.
  17371. * - options (Object): zlib deflate options.
  17372. *
  17373. * Compress `data` with deflate alrorythm and `options`.
  17374. *
  17375. * Supported options are:
  17376. *
  17377. * - level
  17378. * - windowBits
  17379. * - memLevel
  17380. * - strategy
  17381. *
  17382. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17383. * for more information on these.
  17384. *
  17385. * Sugar (options):
  17386. *
  17387. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17388. * negative windowBits implicitly.
  17389. * - `to` (String) - if equal to 'string', then result will be "binary string"
  17390. * (each char code [0..255])
  17391. *
  17392. * ##### Example:
  17393. *
  17394. * ```javascript
  17395. * var pako = require('pako')
  17396. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  17397. *
  17398. * console.log(pako.deflate(data));
  17399. * ```
  17400. **/
  17401. function deflate(input, options) {
  17402. var deflator = new Deflate(options);
  17403. deflator.push(input, true);
  17404. // That will never happens, if you don't cheat with options :)
  17405. if (deflator.err) { throw deflator.msg; }
  17406. return deflator.result;
  17407. }
  17408. /**
  17409. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  17410. * - data (Uint8Array|Array|String): input data to compress.
  17411. * - options (Object): zlib deflate options.
  17412. *
  17413. * The same as [[deflate]], but creates raw data, without wrapper
  17414. * (header and adler32 crc).
  17415. **/
  17416. function deflateRaw(input, options) {
  17417. options = options || {};
  17418. options.raw = true;
  17419. return deflate(input, options);
  17420. }
  17421. /**
  17422. * gzip(data[, options]) -> Uint8Array|Array|String
  17423. * - data (Uint8Array|Array|String): input data to compress.
  17424. * - options (Object): zlib deflate options.
  17425. *
  17426. * The same as [[deflate]], but create gzip wrapper instead of
  17427. * deflate one.
  17428. **/
  17429. function gzip(input, options) {
  17430. options = options || {};
  17431. options.gzip = true;
  17432. return deflate(input, options);
  17433. }
  17434. exports.Deflate = Deflate;
  17435. exports.deflate = deflate;
  17436. exports.deflateRaw = deflateRaw;
  17437. exports.gzip = gzip;
  17438. },{"./utils/common":66,"./utils/strings":67,"./zlib/deflate.js":71,"./zlib/messages":76,"./zlib/zstream":78}],65:[function(require,module,exports){
  17439. 'use strict';
  17440. var zlib_inflate = require('./zlib/inflate.js');
  17441. var utils = require('./utils/common');
  17442. var strings = require('./utils/strings');
  17443. var c = require('./zlib/constants');
  17444. var msg = require('./zlib/messages');
  17445. var zstream = require('./zlib/zstream');
  17446. var gzheader = require('./zlib/gzheader');
  17447. var toString = Object.prototype.toString;
  17448. /**
  17449. * class Inflate
  17450. *
  17451. * Generic JS-style wrapper for zlib calls. If you don't need
  17452. * streaming behaviour - use more simple functions: [[inflate]]
  17453. * and [[inflateRaw]].
  17454. **/
  17455. /* internal
  17456. * inflate.chunks -> Array
  17457. *
  17458. * Chunks of output data, if [[Inflate#onData]] not overriden.
  17459. **/
  17460. /**
  17461. * Inflate.result -> Uint8Array|Array|String
  17462. *
  17463. * Uncompressed result, generated by default [[Inflate#onData]]
  17464. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  17465. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  17466. **/
  17467. /**
  17468. * Inflate.err -> Number
  17469. *
  17470. * Error code after inflate finished. 0 (Z_OK) on success.
  17471. * Should be checked if broken data possible.
  17472. **/
  17473. /**
  17474. * Inflate.msg -> String
  17475. *
  17476. * Error message, if [[Inflate.err]] != 0
  17477. **/
  17478. /**
  17479. * new Inflate(options)
  17480. * - options (Object): zlib inflate options.
  17481. *
  17482. * Creates new inflator instance with specified params. Throws exception
  17483. * on bad params. Supported options:
  17484. *
  17485. * - `windowBits`
  17486. *
  17487. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17488. * for more information on these.
  17489. *
  17490. * Additional options, for internal needs:
  17491. *
  17492. * - `chunkSize` - size of generated data chunks (16K by default)
  17493. * - `raw` (Boolean) - do raw inflate
  17494. * - `to` (String) - if equal to 'string', then result will be converted
  17495. * from utf8 to utf16 (javascript) string. When string output requested,
  17496. * chunk length can differ from `chunkSize`, depending on content.
  17497. *
  17498. * By default, when no options set, autodetect deflate/gzip data format via
  17499. * wrapper header.
  17500. *
  17501. * ##### Example:
  17502. *
  17503. * ```javascript
  17504. * var pako = require('pako')
  17505. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17506. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17507. *
  17508. * var inflate = new pako.Inflate({ level: 3});
  17509. *
  17510. * inflate.push(chunk1, false);
  17511. * inflate.push(chunk2, true); // true -> last chunk
  17512. *
  17513. * if (inflate.err) { throw new Error(inflate.err); }
  17514. *
  17515. * console.log(inflate.result);
  17516. * ```
  17517. **/
  17518. var Inflate = function(options) {
  17519. this.options = utils.assign({
  17520. chunkSize: 16384,
  17521. windowBits: 0,
  17522. to: ''
  17523. }, options || {});
  17524. var opt = this.options;
  17525. // Force window size for `raw` data, if not set directly,
  17526. // because we have no header for autodetect.
  17527. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  17528. opt.windowBits = -opt.windowBits;
  17529. if (opt.windowBits === 0) { opt.windowBits = -15; }
  17530. }
  17531. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  17532. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  17533. !(options && options.windowBits)) {
  17534. opt.windowBits += 32;
  17535. }
  17536. // Gzip header has no info about windows size, we can do autodetect only
  17537. // for deflate. So, if window size not set, force it to max when gzip possible
  17538. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  17539. // bit 3 (16) -> gzipped data
  17540. // bit 4 (32) -> autodetect gzip/deflate
  17541. if ((opt.windowBits & 15) === 0) {
  17542. opt.windowBits |= 15;
  17543. }
  17544. }
  17545. this.err = 0; // error code, if happens (0 = Z_OK)
  17546. this.msg = ''; // error message
  17547. this.ended = false; // used to avoid multiple onEnd() calls
  17548. this.chunks = []; // chunks of compressed data
  17549. this.strm = new zstream();
  17550. this.strm.avail_out = 0;
  17551. var status = zlib_inflate.inflateInit2(
  17552. this.strm,
  17553. opt.windowBits
  17554. );
  17555. if (status !== c.Z_OK) {
  17556. throw new Error(msg[status]);
  17557. }
  17558. this.header = new gzheader();
  17559. zlib_inflate.inflateGetHeader(this.strm, this.header);
  17560. };
  17561. /**
  17562. * Inflate#push(data[, mode]) -> Boolean
  17563. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  17564. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17565. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17566. *
  17567. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  17568. * new output chunks. Returns `true` on success. The last data block must have
  17569. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17570. * [[Inflate#onEnd]].
  17571. *
  17572. * On fail call [[Inflate#onEnd]] with error code and return false.
  17573. *
  17574. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17575. * format is detected automatically). Also, don't skip last param and always
  17576. * use the same type in your code (boolean or number). That will improve JS speed.
  17577. *
  17578. * For regular `Array`-s make sure all elements are [0..255].
  17579. *
  17580. * ##### Example
  17581. *
  17582. * ```javascript
  17583. * push(chunk, false); // push one of data chunks
  17584. * ...
  17585. * push(chunk, true); // push last chunk
  17586. * ```
  17587. **/
  17588. Inflate.prototype.push = function(data, mode) {
  17589. var strm = this.strm;
  17590. var chunkSize = this.options.chunkSize;
  17591. var status, _mode;
  17592. var next_out_utf8, tail, utf8str;
  17593. if (this.ended) { return false; }
  17594. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  17595. // Convert data if needed
  17596. if (typeof data === 'string') {
  17597. // Only binary strings can be decompressed on practice
  17598. strm.input = strings.binstring2buf(data);
  17599. } else if (toString.call(data) === '[object ArrayBuffer]') {
  17600. strm.input = new Uint8Array(data);
  17601. } else {
  17602. strm.input = data;
  17603. }
  17604. strm.next_in = 0;
  17605. strm.avail_in = strm.input.length;
  17606. do {
  17607. if (strm.avail_out === 0) {
  17608. strm.output = new utils.Buf8(chunkSize);
  17609. strm.next_out = 0;
  17610. strm.avail_out = chunkSize;
  17611. }
  17612. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  17613. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  17614. this.onEnd(status);
  17615. this.ended = true;
  17616. return false;
  17617. }
  17618. if (strm.next_out) {
  17619. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  17620. if (this.options.to === 'string') {
  17621. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  17622. tail = strm.next_out - next_out_utf8;
  17623. utf8str = strings.buf2string(strm.output, next_out_utf8);
  17624. // move tail
  17625. strm.next_out = tail;
  17626. strm.avail_out = chunkSize - tail;
  17627. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  17628. this.onData(utf8str);
  17629. } else {
  17630. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17631. }
  17632. }
  17633. }
  17634. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  17635. if (status === c.Z_STREAM_END) {
  17636. _mode = c.Z_FINISH;
  17637. }
  17638. // Finalize on the last chunk.
  17639. if (_mode === c.Z_FINISH) {
  17640. status = zlib_inflate.inflateEnd(this.strm);
  17641. this.onEnd(status);
  17642. this.ended = true;
  17643. return status === c.Z_OK;
  17644. }
  17645. return true;
  17646. };
  17647. /**
  17648. * Inflate#onData(chunk) -> Void
  17649. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17650. * on js engine support. When string output requested, each chunk
  17651. * will be string.
  17652. *
  17653. * By default, stores data blocks in `chunks[]` property and glue
  17654. * those in `onEnd`. Override this handler, if you need another behaviour.
  17655. **/
  17656. Inflate.prototype.onData = function(chunk) {
  17657. this.chunks.push(chunk);
  17658. };
  17659. /**
  17660. * Inflate#onEnd(status) -> Void
  17661. * - status (Number): inflate status. 0 (Z_OK) on success,
  17662. * other if not.
  17663. *
  17664. * Called once after you tell inflate that input stream complete
  17665. * or error happenned. By default - join collected chunks,
  17666. * free memory and fill `results` / `err` properties.
  17667. **/
  17668. Inflate.prototype.onEnd = function(status) {
  17669. // On success - join
  17670. if (status === c.Z_OK) {
  17671. if (this.options.to === 'string') {
  17672. // Glue & convert here, until we teach pako to send
  17673. // utf8 alligned strings to onData
  17674. this.result = this.chunks.join('');
  17675. } else {
  17676. this.result = utils.flattenChunks(this.chunks);
  17677. }
  17678. }
  17679. this.chunks = [];
  17680. this.err = status;
  17681. this.msg = this.strm.msg;
  17682. };
  17683. /**
  17684. * inflate(data[, options]) -> Uint8Array|Array|String
  17685. * - data (Uint8Array|Array|String): input data to decompress.
  17686. * - options (Object): zlib inflate options.
  17687. *
  17688. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  17689. * format via wrapper header by default. That's why we don't provide
  17690. * separate `ungzip` method.
  17691. *
  17692. * Supported options are:
  17693. *
  17694. * - windowBits
  17695. *
  17696. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17697. * for more information.
  17698. *
  17699. * Sugar (options):
  17700. *
  17701. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17702. * negative windowBits implicitly.
  17703. * - `to` (String) - if equal to 'string', then result will be converted
  17704. * from utf8 to utf16 (javascript) string. When string output requested,
  17705. * chunk length can differ from `chunkSize`, depending on content.
  17706. *
  17707. *
  17708. * ##### Example:
  17709. *
  17710. * ```javascript
  17711. * var pako = require('pako')
  17712. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  17713. * , output;
  17714. *
  17715. * try {
  17716. * output = pako.inflate(input);
  17717. * } catch (err)
  17718. * console.log(err);
  17719. * }
  17720. * ```
  17721. **/
  17722. function inflate(input, options) {
  17723. var inflator = new Inflate(options);
  17724. inflator.push(input, true);
  17725. // That will never happens, if you don't cheat with options :)
  17726. if (inflator.err) { throw inflator.msg; }
  17727. return inflator.result;
  17728. }
  17729. /**
  17730. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  17731. * - data (Uint8Array|Array|String): input data to decompress.
  17732. * - options (Object): zlib inflate options.
  17733. *
  17734. * The same as [[inflate]], but creates raw data, without wrapper
  17735. * (header and adler32 crc).
  17736. **/
  17737. function inflateRaw(input, options) {
  17738. options = options || {};
  17739. options.raw = true;
  17740. return inflate(input, options);
  17741. }
  17742. /**
  17743. * ungzip(data[, options]) -> Uint8Array|Array|String
  17744. * - data (Uint8Array|Array|String): input data to decompress.
  17745. * - options (Object): zlib inflate options.
  17746. *
  17747. * Just shortcut to [[inflate]], because it autodetects format
  17748. * by header.content. Done for convenience.
  17749. **/
  17750. exports.Inflate = Inflate;
  17751. exports.inflate = inflate;
  17752. exports.inflateRaw = inflateRaw;
  17753. exports.ungzip = inflate;
  17754. },{"./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){
  17755. 'use strict';
  17756. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  17757. (typeof Uint16Array !== 'undefined') &&
  17758. (typeof Int32Array !== 'undefined');
  17759. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  17760. var sources = Array.prototype.slice.call(arguments, 1);
  17761. while (sources.length) {
  17762. var source = sources.shift();
  17763. if (!source) { continue; }
  17764. if (typeof(source) !== 'object') {
  17765. throw new TypeError(source + 'must be non-object');
  17766. }
  17767. for (var p in source) {
  17768. if (source.hasOwnProperty(p)) {
  17769. obj[p] = source[p];
  17770. }
  17771. }
  17772. }
  17773. return obj;
  17774. };
  17775. // reduce buffer size, avoiding mem copy
  17776. exports.shrinkBuf = function (buf, size) {
  17777. if (buf.length === size) { return buf; }
  17778. if (buf.subarray) { return buf.subarray(0, size); }
  17779. buf.length = size;
  17780. return buf;
  17781. };
  17782. var fnTyped = {
  17783. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17784. if (src.subarray && dest.subarray) {
  17785. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  17786. return;
  17787. }
  17788. // Fallback to ordinary array
  17789. for(var i=0; i<len; i++) {
  17790. dest[dest_offs + i] = src[src_offs + i];
  17791. }
  17792. },
  17793. // Join array of chunks to single array.
  17794. flattenChunks: function(chunks) {
  17795. var i, l, len, pos, chunk, result;
  17796. // calculate data length
  17797. len = 0;
  17798. for (i=0, l=chunks.length; i<l; i++) {
  17799. len += chunks[i].length;
  17800. }
  17801. // join chunks
  17802. result = new Uint8Array(len);
  17803. pos = 0;
  17804. for (i=0, l=chunks.length; i<l; i++) {
  17805. chunk = chunks[i];
  17806. result.set(chunk, pos);
  17807. pos += chunk.length;
  17808. }
  17809. return result;
  17810. }
  17811. };
  17812. var fnUntyped = {
  17813. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17814. for(var i=0; i<len; i++) {
  17815. dest[dest_offs + i] = src[src_offs + i];
  17816. }
  17817. },
  17818. // Join array of chunks to single array.
  17819. flattenChunks: function(chunks) {
  17820. return [].concat.apply([], chunks);
  17821. }
  17822. };
  17823. // Enable/Disable typed arrays use, for testing
  17824. //
  17825. exports.setTyped = function (on) {
  17826. if (on) {
  17827. exports.Buf8 = Uint8Array;
  17828. exports.Buf16 = Uint16Array;
  17829. exports.Buf32 = Int32Array;
  17830. exports.assign(exports, fnTyped);
  17831. } else {
  17832. exports.Buf8 = Array;
  17833. exports.Buf16 = Array;
  17834. exports.Buf32 = Array;
  17835. exports.assign(exports, fnUntyped);
  17836. }
  17837. };
  17838. exports.setTyped(TYPED_OK);
  17839. },{}],67:[function(require,module,exports){
  17840. // String encode/decode helpers
  17841. 'use strict';
  17842. var utils = require('./common');
  17843. // Quick check if we can use fast array to bin string conversion
  17844. //
  17845. // - apply(Array) can fail on Android 2.2
  17846. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  17847. //
  17848. var STR_APPLY_OK = true;
  17849. var STR_APPLY_UIA_OK = true;
  17850. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  17851. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  17852. // Table with utf8 lengths (calculated by first byte of sequence)
  17853. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  17854. // because max possible codepoint is 0x10ffff
  17855. var _utf8len = new utils.Buf8(256);
  17856. for (var i=0; i<256; i++) {
  17857. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  17858. }
  17859. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  17860. // convert string to array (typed, when possible)
  17861. exports.string2buf = function (str) {
  17862. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  17863. // count binary size
  17864. for (m_pos = 0; m_pos < str_len; m_pos++) {
  17865. c = str.charCodeAt(m_pos);
  17866. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17867. c2 = str.charCodeAt(m_pos+1);
  17868. if ((c2 & 0xfc00) === 0xdc00) {
  17869. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17870. m_pos++;
  17871. }
  17872. }
  17873. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  17874. }
  17875. // allocate buffer
  17876. buf = new utils.Buf8(buf_len);
  17877. // convert
  17878. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  17879. c = str.charCodeAt(m_pos);
  17880. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17881. c2 = str.charCodeAt(m_pos+1);
  17882. if ((c2 & 0xfc00) === 0xdc00) {
  17883. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17884. m_pos++;
  17885. }
  17886. }
  17887. if (c < 0x80) {
  17888. /* one byte */
  17889. buf[i++] = c;
  17890. } else if (c < 0x800) {
  17891. /* two bytes */
  17892. buf[i++] = 0xC0 | (c >>> 6);
  17893. buf[i++] = 0x80 | (c & 0x3f);
  17894. } else if (c < 0x10000) {
  17895. /* three bytes */
  17896. buf[i++] = 0xE0 | (c >>> 12);
  17897. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17898. buf[i++] = 0x80 | (c & 0x3f);
  17899. } else {
  17900. /* four bytes */
  17901. buf[i++] = 0xf0 | (c >>> 18);
  17902. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  17903. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17904. buf[i++] = 0x80 | (c & 0x3f);
  17905. }
  17906. }
  17907. return buf;
  17908. };
  17909. // Helper (used in 2 places)
  17910. function buf2binstring(buf, len) {
  17911. // use fallback for big arrays to avoid stack overflow
  17912. if (len < 65537) {
  17913. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  17914. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  17915. }
  17916. }
  17917. var result = '';
  17918. for(var i=0; i < len; i++) {
  17919. result += String.fromCharCode(buf[i]);
  17920. }
  17921. return result;
  17922. }
  17923. // Convert byte array to binary string
  17924. exports.buf2binstring = function(buf) {
  17925. return buf2binstring(buf, buf.length);
  17926. };
  17927. // Convert binary string (typed, when possible)
  17928. exports.binstring2buf = function(str) {
  17929. var buf = new utils.Buf8(str.length);
  17930. for(var i=0, len=buf.length; i < len; i++) {
  17931. buf[i] = str.charCodeAt(i);
  17932. }
  17933. return buf;
  17934. };
  17935. // convert array to string
  17936. exports.buf2string = function (buf, max) {
  17937. var i, out, c, c_len;
  17938. var len = max || buf.length;
  17939. // Reserve max possible length (2 words per char)
  17940. // NB: by unknown reasons, Array is significantly faster for
  17941. // String.fromCharCode.apply than Uint16Array.
  17942. var utf16buf = new Array(len*2);
  17943. for (out=0, i=0; i<len;) {
  17944. c = buf[i++];
  17945. // quick process ascii
  17946. if (c < 0x80) { utf16buf[out++] = c; continue; }
  17947. c_len = _utf8len[c];
  17948. // skip 5 & 6 byte codes
  17949. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  17950. // apply mask on first byte
  17951. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  17952. // join the rest
  17953. while (c_len > 1 && i < len) {
  17954. c = (c << 6) | (buf[i++] & 0x3f);
  17955. c_len--;
  17956. }
  17957. // terminated by end of string?
  17958. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  17959. if (c < 0x10000) {
  17960. utf16buf[out++] = c;
  17961. } else {
  17962. c -= 0x10000;
  17963. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  17964. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  17965. }
  17966. }
  17967. return buf2binstring(utf16buf, out);
  17968. };
  17969. // Calculate max possible position in utf8 buffer,
  17970. // that will not break sequence. If that's not possible
  17971. // - (very small limits) return max size as is.
  17972. //
  17973. // buf[] - utf8 bytes array
  17974. // max - length limit (mandatory);
  17975. exports.utf8border = function(buf, max) {
  17976. var pos;
  17977. max = max || buf.length;
  17978. if (max > buf.length) { max = buf.length; }
  17979. // go back from last position, until start of sequence found
  17980. pos = max-1;
  17981. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  17982. // Fuckup - very small and broken sequence,
  17983. // return max, because we should return something anyway.
  17984. if (pos < 0) { return max; }
  17985. // If we came to start of buffer - that means vuffer is too small,
  17986. // return max too.
  17987. if (pos === 0) { return max; }
  17988. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  17989. };
  17990. },{"./common":66}],68:[function(require,module,exports){
  17991. 'use strict';
  17992. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  17993. // It doesn't worth to make additional optimizationa as in original.
  17994. // Small size is preferable.
  17995. function adler32(adler, buf, len, pos) {
  17996. var s1 = (adler & 0xffff) |0
  17997. , s2 = ((adler >>> 16) & 0xffff) |0
  17998. , n = 0;
  17999. while (len !== 0) {
  18000. // Set limit ~ twice less than 5552, to keep
  18001. // s2 in 31-bits, because we force signed ints.
  18002. // in other case %= will fail.
  18003. n = len > 2000 ? 2000 : len;
  18004. len -= n;
  18005. do {
  18006. s1 = (s1 + buf[pos++]) |0;
  18007. s2 = (s2 + s1) |0;
  18008. } while (--n);
  18009. s1 %= 65521;
  18010. s2 %= 65521;
  18011. }
  18012. return (s1 | (s2 << 16)) |0;
  18013. }
  18014. module.exports = adler32;
  18015. },{}],69:[function(require,module,exports){
  18016. module.exports = {
  18017. /* Allowed flush values; see deflate() and inflate() below for details */
  18018. Z_NO_FLUSH: 0,
  18019. Z_PARTIAL_FLUSH: 1,
  18020. Z_SYNC_FLUSH: 2,
  18021. Z_FULL_FLUSH: 3,
  18022. Z_FINISH: 4,
  18023. Z_BLOCK: 5,
  18024. Z_TREES: 6,
  18025. /* Return codes for the compression/decompression functions. Negative values
  18026. * are errors, positive values are used for special but normal events.
  18027. */
  18028. Z_OK: 0,
  18029. Z_STREAM_END: 1,
  18030. Z_NEED_DICT: 2,
  18031. Z_ERRNO: -1,
  18032. Z_STREAM_ERROR: -2,
  18033. Z_DATA_ERROR: -3,
  18034. //Z_MEM_ERROR: -4,
  18035. Z_BUF_ERROR: -5,
  18036. //Z_VERSION_ERROR: -6,
  18037. /* compression levels */
  18038. Z_NO_COMPRESSION: 0,
  18039. Z_BEST_SPEED: 1,
  18040. Z_BEST_COMPRESSION: 9,
  18041. Z_DEFAULT_COMPRESSION: -1,
  18042. Z_FILTERED: 1,
  18043. Z_HUFFMAN_ONLY: 2,
  18044. Z_RLE: 3,
  18045. Z_FIXED: 4,
  18046. Z_DEFAULT_STRATEGY: 0,
  18047. /* Possible values of the data_type field (though see inflate()) */
  18048. Z_BINARY: 0,
  18049. Z_TEXT: 1,
  18050. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  18051. Z_UNKNOWN: 2,
  18052. /* The deflate compression method */
  18053. Z_DEFLATED: 8
  18054. //Z_NULL: null // Use -1 or null inline, depending on var type
  18055. };
  18056. },{}],70:[function(require,module,exports){
  18057. 'use strict';
  18058. // Note: we can't get significant speed boost here.
  18059. // So write code to minimize size - no pregenerated tables
  18060. // and array tools dependencies.
  18061. // Use ordinary array, since untyped makes no boost here
  18062. function makeTable() {
  18063. var c, table = [];
  18064. for(var n =0; n < 256; n++){
  18065. c = n;
  18066. for(var k =0; k < 8; k++){
  18067. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  18068. }
  18069. table[n] = c;
  18070. }
  18071. return table;
  18072. }
  18073. // Create table on load. Just 255 signed longs. Not a problem.
  18074. var crcTable = makeTable();
  18075. function crc32(crc, buf, len, pos) {
  18076. var t = crcTable
  18077. , end = pos + len;
  18078. crc = crc ^ (-1);
  18079. for (var i = pos; i < end; i++ ) {
  18080. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  18081. }
  18082. return (crc ^ (-1)); // >>> 0;
  18083. }
  18084. module.exports = crc32;
  18085. },{}],71:[function(require,module,exports){
  18086. 'use strict';
  18087. var utils = require('../utils/common');
  18088. var trees = require('./trees');
  18089. var adler32 = require('./adler32');
  18090. var crc32 = require('./crc32');
  18091. var msg = require('./messages');
  18092. /* Public constants ==========================================================*/
  18093. /* ===========================================================================*/
  18094. /* Allowed flush values; see deflate() and inflate() below for details */
  18095. var Z_NO_FLUSH = 0;
  18096. var Z_PARTIAL_FLUSH = 1;
  18097. //var Z_SYNC_FLUSH = 2;
  18098. var Z_FULL_FLUSH = 3;
  18099. var Z_FINISH = 4;
  18100. var Z_BLOCK = 5;
  18101. //var Z_TREES = 6;
  18102. /* Return codes for the compression/decompression functions. Negative values
  18103. * are errors, positive values are used for special but normal events.
  18104. */
  18105. var Z_OK = 0;
  18106. var Z_STREAM_END = 1;
  18107. //var Z_NEED_DICT = 2;
  18108. //var Z_ERRNO = -1;
  18109. var Z_STREAM_ERROR = -2;
  18110. var Z_DATA_ERROR = -3;
  18111. //var Z_MEM_ERROR = -4;
  18112. var Z_BUF_ERROR = -5;
  18113. //var Z_VERSION_ERROR = -6;
  18114. /* compression levels */
  18115. //var Z_NO_COMPRESSION = 0;
  18116. //var Z_BEST_SPEED = 1;
  18117. //var Z_BEST_COMPRESSION = 9;
  18118. var Z_DEFAULT_COMPRESSION = -1;
  18119. var Z_FILTERED = 1;
  18120. var Z_HUFFMAN_ONLY = 2;
  18121. var Z_RLE = 3;
  18122. var Z_FIXED = 4;
  18123. var Z_DEFAULT_STRATEGY = 0;
  18124. /* Possible values of the data_type field (though see inflate()) */
  18125. //var Z_BINARY = 0;
  18126. //var Z_TEXT = 1;
  18127. //var Z_ASCII = 1; // = Z_TEXT
  18128. var Z_UNKNOWN = 2;
  18129. /* The deflate compression method */
  18130. var Z_DEFLATED = 8;
  18131. /*============================================================================*/
  18132. var MAX_MEM_LEVEL = 9;
  18133. /* Maximum value for memLevel in deflateInit2 */
  18134. var MAX_WBITS = 15;
  18135. /* 32K LZ77 window */
  18136. var DEF_MEM_LEVEL = 8;
  18137. var LENGTH_CODES = 29;
  18138. /* number of length codes, not counting the special END_BLOCK code */
  18139. var LITERALS = 256;
  18140. /* number of literal bytes 0..255 */
  18141. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  18142. /* number of Literal or Length codes, including the END_BLOCK code */
  18143. var D_CODES = 30;
  18144. /* number of distance codes */
  18145. var BL_CODES = 19;
  18146. /* number of codes used to transfer the bit lengths */
  18147. var HEAP_SIZE = 2*L_CODES + 1;
  18148. /* maximum heap size */
  18149. var MAX_BITS = 15;
  18150. /* All codes must not exceed MAX_BITS bits */
  18151. var MIN_MATCH = 3;
  18152. var MAX_MATCH = 258;
  18153. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  18154. var PRESET_DICT = 0x20;
  18155. var INIT_STATE = 42;
  18156. var EXTRA_STATE = 69;
  18157. var NAME_STATE = 73;
  18158. var COMMENT_STATE = 91;
  18159. var HCRC_STATE = 103;
  18160. var BUSY_STATE = 113;
  18161. var FINISH_STATE = 666;
  18162. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  18163. var BS_BLOCK_DONE = 2; /* block flush performed */
  18164. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  18165. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  18166. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  18167. function err(strm, errorCode) {
  18168. strm.msg = msg[errorCode];
  18169. return errorCode;
  18170. }
  18171. function rank(f) {
  18172. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  18173. }
  18174. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  18175. /* =========================================================================
  18176. * Flush as much pending output as possible. All deflate() output goes
  18177. * through this function so some applications may wish to modify it
  18178. * to avoid allocating a large strm->output buffer and copying into it.
  18179. * (See also read_buf()).
  18180. */
  18181. function flush_pending(strm) {
  18182. var s = strm.state;
  18183. //_tr_flush_bits(s);
  18184. var len = s.pending;
  18185. if (len > strm.avail_out) {
  18186. len = strm.avail_out;
  18187. }
  18188. if (len === 0) { return; }
  18189. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  18190. strm.next_out += len;
  18191. s.pending_out += len;
  18192. strm.total_out += len;
  18193. strm.avail_out -= len;
  18194. s.pending -= len;
  18195. if (s.pending === 0) {
  18196. s.pending_out = 0;
  18197. }
  18198. }
  18199. function flush_block_only (s, last) {
  18200. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  18201. s.block_start = s.strstart;
  18202. flush_pending(s.strm);
  18203. }
  18204. function put_byte(s, b) {
  18205. s.pending_buf[s.pending++] = b;
  18206. }
  18207. /* =========================================================================
  18208. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  18209. * IN assertion: the stream state is correct and there is enough room in
  18210. * pending_buf.
  18211. */
  18212. function putShortMSB(s, b) {
  18213. // put_byte(s, (Byte)(b >> 8));
  18214. // put_byte(s, (Byte)(b & 0xff));
  18215. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  18216. s.pending_buf[s.pending++] = b & 0xff;
  18217. }
  18218. /* ===========================================================================
  18219. * Read a new buffer from the current input stream, update the adler32
  18220. * and total number of bytes read. All deflate() input goes through
  18221. * this function so some applications may wish to modify it to avoid
  18222. * allocating a large strm->input buffer and copying from it.
  18223. * (See also flush_pending()).
  18224. */
  18225. function read_buf(strm, buf, start, size) {
  18226. var len = strm.avail_in;
  18227. if (len > size) { len = size; }
  18228. if (len === 0) { return 0; }
  18229. strm.avail_in -= len;
  18230. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  18231. if (strm.state.wrap === 1) {
  18232. strm.adler = adler32(strm.adler, buf, len, start);
  18233. }
  18234. else if (strm.state.wrap === 2) {
  18235. strm.adler = crc32(strm.adler, buf, len, start);
  18236. }
  18237. strm.next_in += len;
  18238. strm.total_in += len;
  18239. return len;
  18240. }
  18241. /* ===========================================================================
  18242. * Set match_start to the longest match starting at the given string and
  18243. * return its length. Matches shorter or equal to prev_length are discarded,
  18244. * in which case the result is equal to prev_length and match_start is
  18245. * garbage.
  18246. * IN assertions: cur_match is the head of the hash chain for the current
  18247. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  18248. * OUT assertion: the match length is not greater than s->lookahead.
  18249. */
  18250. function longest_match(s, cur_match) {
  18251. var chain_length = s.max_chain_length; /* max hash chain length */
  18252. var scan = s.strstart; /* current string */
  18253. var match; /* matched string */
  18254. var len; /* length of current match */
  18255. var best_len = s.prev_length; /* best match length so far */
  18256. var nice_match = s.nice_match; /* stop if match long enough */
  18257. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  18258. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  18259. var _win = s.window; // shortcut
  18260. var wmask = s.w_mask;
  18261. var prev = s.prev;
  18262. /* Stop when cur_match becomes <= limit. To simplify the code,
  18263. * we prevent matches with the string of window index 0.
  18264. */
  18265. var strend = s.strstart + MAX_MATCH;
  18266. var scan_end1 = _win[scan + best_len - 1];
  18267. var scan_end = _win[scan + best_len];
  18268. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  18269. * It is easy to get rid of this optimization if necessary.
  18270. */
  18271. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  18272. /* Do not waste too much time if we already have a good match: */
  18273. if (s.prev_length >= s.good_match) {
  18274. chain_length >>= 2;
  18275. }
  18276. /* Do not look for matches beyond the end of the input. This is necessary
  18277. * to make deflate deterministic.
  18278. */
  18279. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  18280. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  18281. do {
  18282. // Assert(cur_match < s->strstart, "no future");
  18283. match = cur_match;
  18284. /* Skip to next match if the match length cannot increase
  18285. * or if the match length is less than 2. Note that the checks below
  18286. * for insufficient lookahead only occur occasionally for performance
  18287. * reasons. Therefore uninitialized memory will be accessed, and
  18288. * conditional jumps will be made that depend on those values.
  18289. * However the length of the match is limited to the lookahead, so
  18290. * the output of deflate is not affected by the uninitialized values.
  18291. */
  18292. if (_win[match + best_len] !== scan_end ||
  18293. _win[match + best_len - 1] !== scan_end1 ||
  18294. _win[match] !== _win[scan] ||
  18295. _win[++match] !== _win[scan + 1]) {
  18296. continue;
  18297. }
  18298. /* The check at best_len-1 can be removed because it will be made
  18299. * again later. (This heuristic is not always a win.)
  18300. * It is not necessary to compare scan[2] and match[2] since they
  18301. * are always equal when the other bytes match, given that
  18302. * the hash keys are equal and that HASH_BITS >= 8.
  18303. */
  18304. scan += 2;
  18305. match++;
  18306. // Assert(*scan == *match, "match[2]?");
  18307. /* We check for insufficient lookahead only every 8th comparison;
  18308. * the 256th check will be made at strstart+258.
  18309. */
  18310. do {
  18311. /*jshint noempty:false*/
  18312. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18313. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18314. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18315. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18316. scan < strend);
  18317. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  18318. len = MAX_MATCH - (strend - scan);
  18319. scan = strend - MAX_MATCH;
  18320. if (len > best_len) {
  18321. s.match_start = cur_match;
  18322. best_len = len;
  18323. if (len >= nice_match) {
  18324. break;
  18325. }
  18326. scan_end1 = _win[scan + best_len - 1];
  18327. scan_end = _win[scan + best_len];
  18328. }
  18329. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  18330. if (best_len <= s.lookahead) {
  18331. return best_len;
  18332. }
  18333. return s.lookahead;
  18334. }
  18335. /* ===========================================================================
  18336. * Fill the window when the lookahead becomes insufficient.
  18337. * Updates strstart and lookahead.
  18338. *
  18339. * IN assertion: lookahead < MIN_LOOKAHEAD
  18340. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  18341. * At least one byte has been read, or avail_in == 0; reads are
  18342. * performed for at least two bytes (required for the zip translate_eol
  18343. * option -- not supported here).
  18344. */
  18345. function fill_window(s) {
  18346. var _w_size = s.w_size;
  18347. var p, n, m, more, str;
  18348. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  18349. do {
  18350. more = s.window_size - s.lookahead - s.strstart;
  18351. // JS ints have 32 bit, block below not needed
  18352. /* Deal with !@#$% 64K limit: */
  18353. //if (sizeof(int) <= 2) {
  18354. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  18355. // more = wsize;
  18356. //
  18357. // } else if (more == (unsigned)(-1)) {
  18358. // /* Very unlikely, but possible on 16 bit machine if
  18359. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  18360. // */
  18361. // more--;
  18362. // }
  18363. //}
  18364. /* If the window is almost full and there is insufficient lookahead,
  18365. * move the upper half to the lower one to make room in the upper half.
  18366. */
  18367. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  18368. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  18369. s.match_start -= _w_size;
  18370. s.strstart -= _w_size;
  18371. /* we now have strstart >= MAX_DIST */
  18372. s.block_start -= _w_size;
  18373. /* Slide the hash table (could be avoided with 32 bit values
  18374. at the expense of memory usage). We slide even when level == 0
  18375. to keep the hash table consistent if we switch back to level > 0
  18376. later. (Using level 0 permanently is not an optimal usage of
  18377. zlib, so we don't care about this pathological case.)
  18378. */
  18379. n = s.hash_size;
  18380. p = n;
  18381. do {
  18382. m = s.head[--p];
  18383. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  18384. } while (--n);
  18385. n = _w_size;
  18386. p = n;
  18387. do {
  18388. m = s.prev[--p];
  18389. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  18390. /* If n is not on any hash chain, prev[n] is garbage but
  18391. * its value will never be used.
  18392. */
  18393. } while (--n);
  18394. more += _w_size;
  18395. }
  18396. if (s.strm.avail_in === 0) {
  18397. break;
  18398. }
  18399. /* If there was no sliding:
  18400. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  18401. * more == window_size - lookahead - strstart
  18402. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  18403. * => more >= window_size - 2*WSIZE + 2
  18404. * In the BIG_MEM or MMAP case (not yet supported),
  18405. * window_size == input_size + MIN_LOOKAHEAD &&
  18406. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  18407. * Otherwise, window_size == 2*WSIZE so more >= 2.
  18408. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  18409. */
  18410. //Assert(more >= 2, "more < 2");
  18411. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  18412. s.lookahead += n;
  18413. /* Initialize the hash value now that we have some input: */
  18414. if (s.lookahead + s.insert >= MIN_MATCH) {
  18415. str = s.strstart - s.insert;
  18416. s.ins_h = s.window[str];
  18417. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  18418. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  18419. //#if MIN_MATCH != 3
  18420. // Call update_hash() MIN_MATCH-3 more times
  18421. //#endif
  18422. while (s.insert) {
  18423. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  18424. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  18425. s.prev[str & s.w_mask] = s.head[s.ins_h];
  18426. s.head[s.ins_h] = str;
  18427. str++;
  18428. s.insert--;
  18429. if (s.lookahead + s.insert < MIN_MATCH) {
  18430. break;
  18431. }
  18432. }
  18433. }
  18434. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  18435. * but this is not important since only literal bytes will be emitted.
  18436. */
  18437. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  18438. /* If the WIN_INIT bytes after the end of the current data have never been
  18439. * written, then zero those bytes in order to avoid memory check reports of
  18440. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  18441. * the longest match routines. Update the high water mark for the next
  18442. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  18443. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  18444. */
  18445. // if (s.high_water < s.window_size) {
  18446. // var curr = s.strstart + s.lookahead;
  18447. // var init = 0;
  18448. //
  18449. // if (s.high_water < curr) {
  18450. // /* Previous high water mark below current data -- zero WIN_INIT
  18451. // * bytes or up to end of window, whichever is less.
  18452. // */
  18453. // init = s.window_size - curr;
  18454. // if (init > WIN_INIT)
  18455. // init = WIN_INIT;
  18456. // zmemzero(s->window + curr, (unsigned)init);
  18457. // s->high_water = curr + init;
  18458. // }
  18459. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  18460. // /* High water mark at or above current data, but below current data
  18461. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  18462. // * to end of window, whichever is less.
  18463. // */
  18464. // init = (ulg)curr + WIN_INIT - s->high_water;
  18465. // if (init > s->window_size - s->high_water)
  18466. // init = s->window_size - s->high_water;
  18467. // zmemzero(s->window + s->high_water, (unsigned)init);
  18468. // s->high_water += init;
  18469. // }
  18470. // }
  18471. //
  18472. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  18473. // "not enough room for search");
  18474. }
  18475. /* ===========================================================================
  18476. * Copy without compression as much as possible from the input stream, return
  18477. * the current block state.
  18478. * This function does not insert new strings in the dictionary since
  18479. * uncompressible data is probably not useful. This function is used
  18480. * only for the level=0 compression option.
  18481. * NOTE: this function should be optimized to avoid extra copying from
  18482. * window to pending_buf.
  18483. */
  18484. function deflate_stored(s, flush) {
  18485. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  18486. * to pending_buf_size, and each stored block has a 5 byte header:
  18487. */
  18488. var max_block_size = 0xffff;
  18489. if (max_block_size > s.pending_buf_size - 5) {
  18490. max_block_size = s.pending_buf_size - 5;
  18491. }
  18492. /* Copy as much as possible from input to output: */
  18493. for (;;) {
  18494. /* Fill the window as much as possible: */
  18495. if (s.lookahead <= 1) {
  18496. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  18497. // s->block_start >= (long)s->w_size, "slide too late");
  18498. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  18499. // s.block_start >= s.w_size)) {
  18500. // throw new Error("slide too late");
  18501. // }
  18502. fill_window(s);
  18503. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  18504. return BS_NEED_MORE;
  18505. }
  18506. if (s.lookahead === 0) {
  18507. break;
  18508. }
  18509. /* flush the current block */
  18510. }
  18511. //Assert(s->block_start >= 0L, "block gone");
  18512. // if (s.block_start < 0) throw new Error("block gone");
  18513. s.strstart += s.lookahead;
  18514. s.lookahead = 0;
  18515. /* Emit a stored block if pending_buf will be full: */
  18516. var max_start = s.block_start + max_block_size;
  18517. if (s.strstart === 0 || s.strstart >= max_start) {
  18518. /* strstart == 0 is possible when wraparound on 16-bit machine */
  18519. s.lookahead = s.strstart - max_start;
  18520. s.strstart = max_start;
  18521. /*** FLUSH_BLOCK(s, 0); ***/
  18522. flush_block_only(s, false);
  18523. if (s.strm.avail_out === 0) {
  18524. return BS_NEED_MORE;
  18525. }
  18526. /***/
  18527. }
  18528. /* Flush if we may have to slide, otherwise block_start may become
  18529. * negative and the data will be gone:
  18530. */
  18531. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  18532. /*** FLUSH_BLOCK(s, 0); ***/
  18533. flush_block_only(s, false);
  18534. if (s.strm.avail_out === 0) {
  18535. return BS_NEED_MORE;
  18536. }
  18537. /***/
  18538. }
  18539. }
  18540. s.insert = 0;
  18541. if (flush === Z_FINISH) {
  18542. /*** FLUSH_BLOCK(s, 1); ***/
  18543. flush_block_only(s, true);
  18544. if (s.strm.avail_out === 0) {
  18545. return BS_FINISH_STARTED;
  18546. }
  18547. /***/
  18548. return BS_FINISH_DONE;
  18549. }
  18550. if (s.strstart > s.block_start) {
  18551. /*** FLUSH_BLOCK(s, 0); ***/
  18552. flush_block_only(s, false);
  18553. if (s.strm.avail_out === 0) {
  18554. return BS_NEED_MORE;
  18555. }
  18556. /***/
  18557. }
  18558. return BS_NEED_MORE;
  18559. }
  18560. /* ===========================================================================
  18561. * Compress as much as possible from the input stream, return the current
  18562. * block state.
  18563. * This function does not perform lazy evaluation of matches and inserts
  18564. * new strings in the dictionary only for unmatched strings or for short
  18565. * matches. It is used only for the fast compression options.
  18566. */
  18567. function deflate_fast(s, flush) {
  18568. var hash_head; /* head of the hash chain */
  18569. var bflush; /* set if current block must be flushed */
  18570. for (;;) {
  18571. /* Make sure that we always have enough lookahead, except
  18572. * at the end of the input file. We need MAX_MATCH bytes
  18573. * for the next match, plus MIN_MATCH bytes to insert the
  18574. * string following the next match.
  18575. */
  18576. if (s.lookahead < MIN_LOOKAHEAD) {
  18577. fill_window(s);
  18578. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18579. return BS_NEED_MORE;
  18580. }
  18581. if (s.lookahead === 0) {
  18582. break; /* flush the current block */
  18583. }
  18584. }
  18585. /* Insert the string window[strstart .. strstart+2] in the
  18586. * dictionary, and set hash_head to the head of the hash chain:
  18587. */
  18588. hash_head = 0/*NIL*/;
  18589. if (s.lookahead >= MIN_MATCH) {
  18590. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18591. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18592. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18593. s.head[s.ins_h] = s.strstart;
  18594. /***/
  18595. }
  18596. /* Find the longest match, discarding those <= prev_length.
  18597. * At this point we have always match_length < MIN_MATCH
  18598. */
  18599. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  18600. /* To simplify the code, we prevent matches with the string
  18601. * of window index 0 (in particular we have to avoid a match
  18602. * of the string with itself at the start of the input file).
  18603. */
  18604. s.match_length = longest_match(s, hash_head);
  18605. /* longest_match() sets match_start */
  18606. }
  18607. if (s.match_length >= MIN_MATCH) {
  18608. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  18609. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  18610. s.match_length - MIN_MATCH, bflush); ***/
  18611. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  18612. s.lookahead -= s.match_length;
  18613. /* Insert new strings in the hash table only if the match length
  18614. * is not too large. This saves time but degrades compression.
  18615. */
  18616. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  18617. s.match_length--; /* string at strstart already in table */
  18618. do {
  18619. s.strstart++;
  18620. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18621. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18622. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18623. s.head[s.ins_h] = s.strstart;
  18624. /***/
  18625. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  18626. * always MIN_MATCH bytes ahead.
  18627. */
  18628. } while (--s.match_length !== 0);
  18629. s.strstart++;
  18630. } else
  18631. {
  18632. s.strstart += s.match_length;
  18633. s.match_length = 0;
  18634. s.ins_h = s.window[s.strstart];
  18635. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  18636. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  18637. //#if MIN_MATCH != 3
  18638. // Call UPDATE_HASH() MIN_MATCH-3 more times
  18639. //#endif
  18640. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  18641. * matter since it will be recomputed at next deflate call.
  18642. */
  18643. }
  18644. } else {
  18645. /* No match, output a literal byte */
  18646. //Tracevv((stderr,"%c", s.window[s.strstart]));
  18647. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18648. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18649. s.lookahead--;
  18650. s.strstart++;
  18651. }
  18652. if (bflush) {
  18653. /*** FLUSH_BLOCK(s, 0); ***/
  18654. flush_block_only(s, false);
  18655. if (s.strm.avail_out === 0) {
  18656. return BS_NEED_MORE;
  18657. }
  18658. /***/
  18659. }
  18660. }
  18661. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  18662. if (flush === Z_FINISH) {
  18663. /*** FLUSH_BLOCK(s, 1); ***/
  18664. flush_block_only(s, true);
  18665. if (s.strm.avail_out === 0) {
  18666. return BS_FINISH_STARTED;
  18667. }
  18668. /***/
  18669. return BS_FINISH_DONE;
  18670. }
  18671. if (s.last_lit) {
  18672. /*** FLUSH_BLOCK(s, 0); ***/
  18673. flush_block_only(s, false);
  18674. if (s.strm.avail_out === 0) {
  18675. return BS_NEED_MORE;
  18676. }
  18677. /***/
  18678. }
  18679. return BS_BLOCK_DONE;
  18680. }
  18681. /* ===========================================================================
  18682. * Same as above, but achieves better compression. We use a lazy
  18683. * evaluation for matches: a match is finally adopted only if there is
  18684. * no better match at the next window position.
  18685. */
  18686. function deflate_slow(s, flush) {
  18687. var hash_head; /* head of hash chain */
  18688. var bflush; /* set if current block must be flushed */
  18689. var max_insert;
  18690. /* Process the input block. */
  18691. for (;;) {
  18692. /* Make sure that we always have enough lookahead, except
  18693. * at the end of the input file. We need MAX_MATCH bytes
  18694. * for the next match, plus MIN_MATCH bytes to insert the
  18695. * string following the next match.
  18696. */
  18697. if (s.lookahead < MIN_LOOKAHEAD) {
  18698. fill_window(s);
  18699. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18700. return BS_NEED_MORE;
  18701. }
  18702. if (s.lookahead === 0) { break; } /* flush the current block */
  18703. }
  18704. /* Insert the string window[strstart .. strstart+2] in the
  18705. * dictionary, and set hash_head to the head of the hash chain:
  18706. */
  18707. hash_head = 0/*NIL*/;
  18708. if (s.lookahead >= MIN_MATCH) {
  18709. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18710. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18711. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18712. s.head[s.ins_h] = s.strstart;
  18713. /***/
  18714. }
  18715. /* Find the longest match, discarding those <= prev_length.
  18716. */
  18717. s.prev_length = s.match_length;
  18718. s.prev_match = s.match_start;
  18719. s.match_length = MIN_MATCH-1;
  18720. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  18721. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  18722. /* To simplify the code, we prevent matches with the string
  18723. * of window index 0 (in particular we have to avoid a match
  18724. * of the string with itself at the start of the input file).
  18725. */
  18726. s.match_length = longest_match(s, hash_head);
  18727. /* longest_match() sets match_start */
  18728. if (s.match_length <= 5 &&
  18729. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  18730. /* If prev_match is also MIN_MATCH, match_start is garbage
  18731. * but we will ignore the current match anyway.
  18732. */
  18733. s.match_length = MIN_MATCH-1;
  18734. }
  18735. }
  18736. /* If there was a match at the previous step and the current
  18737. * match is not better, output the previous match:
  18738. */
  18739. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  18740. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  18741. /* Do not insert strings in hash table beyond this. */
  18742. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  18743. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  18744. s.prev_length - MIN_MATCH, bflush);***/
  18745. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  18746. /* Insert in hash table all strings up to the end of the match.
  18747. * strstart-1 and strstart are already inserted. If there is not
  18748. * enough lookahead, the last two strings are not inserted in
  18749. * the hash table.
  18750. */
  18751. s.lookahead -= s.prev_length-1;
  18752. s.prev_length -= 2;
  18753. do {
  18754. if (++s.strstart <= max_insert) {
  18755. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18756. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18757. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18758. s.head[s.ins_h] = s.strstart;
  18759. /***/
  18760. }
  18761. } while (--s.prev_length !== 0);
  18762. s.match_available = 0;
  18763. s.match_length = MIN_MATCH-1;
  18764. s.strstart++;
  18765. if (bflush) {
  18766. /*** FLUSH_BLOCK(s, 0); ***/
  18767. flush_block_only(s, false);
  18768. if (s.strm.avail_out === 0) {
  18769. return BS_NEED_MORE;
  18770. }
  18771. /***/
  18772. }
  18773. } else if (s.match_available) {
  18774. /* If there was no match at the previous position, output a
  18775. * single literal. If there was a match but the current match
  18776. * is longer, truncate the previous match to a single literal.
  18777. */
  18778. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18779. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18780. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18781. if (bflush) {
  18782. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  18783. flush_block_only(s, false);
  18784. /***/
  18785. }
  18786. s.strstart++;
  18787. s.lookahead--;
  18788. if (s.strm.avail_out === 0) {
  18789. return BS_NEED_MORE;
  18790. }
  18791. } else {
  18792. /* There is no previous match to compare with, wait for
  18793. * the next step to decide.
  18794. */
  18795. s.match_available = 1;
  18796. s.strstart++;
  18797. s.lookahead--;
  18798. }
  18799. }
  18800. //Assert (flush != Z_NO_FLUSH, "no flush?");
  18801. if (s.match_available) {
  18802. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18803. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18804. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18805. s.match_available = 0;
  18806. }
  18807. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  18808. if (flush === Z_FINISH) {
  18809. /*** FLUSH_BLOCK(s, 1); ***/
  18810. flush_block_only(s, true);
  18811. if (s.strm.avail_out === 0) {
  18812. return BS_FINISH_STARTED;
  18813. }
  18814. /***/
  18815. return BS_FINISH_DONE;
  18816. }
  18817. if (s.last_lit) {
  18818. /*** FLUSH_BLOCK(s, 0); ***/
  18819. flush_block_only(s, false);
  18820. if (s.strm.avail_out === 0) {
  18821. return BS_NEED_MORE;
  18822. }
  18823. /***/
  18824. }
  18825. return BS_BLOCK_DONE;
  18826. }
  18827. /* ===========================================================================
  18828. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  18829. * one. Do not maintain a hash table. (It will be regenerated if this run of
  18830. * deflate switches away from Z_RLE.)
  18831. */
  18832. function deflate_rle(s, flush) {
  18833. var bflush; /* set if current block must be flushed */
  18834. var prev; /* byte at distance one to match */
  18835. var scan, strend; /* scan goes up to strend for length of run */
  18836. var _win = s.window;
  18837. for (;;) {
  18838. /* Make sure that we always have enough lookahead, except
  18839. * at the end of the input file. We need MAX_MATCH bytes
  18840. * for the longest run, plus one for the unrolled loop.
  18841. */
  18842. if (s.lookahead <= MAX_MATCH) {
  18843. fill_window(s);
  18844. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  18845. return BS_NEED_MORE;
  18846. }
  18847. if (s.lookahead === 0) { break; } /* flush the current block */
  18848. }
  18849. /* See how many times the previous byte repeats */
  18850. s.match_length = 0;
  18851. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  18852. scan = s.strstart - 1;
  18853. prev = _win[scan];
  18854. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  18855. strend = s.strstart + MAX_MATCH;
  18856. do {
  18857. /*jshint noempty:false*/
  18858. } while (prev === _win[++scan] && prev === _win[++scan] &&
  18859. prev === _win[++scan] && prev === _win[++scan] &&
  18860. prev === _win[++scan] && prev === _win[++scan] &&
  18861. prev === _win[++scan] && prev === _win[++scan] &&
  18862. scan < strend);
  18863. s.match_length = MAX_MATCH - (strend - scan);
  18864. if (s.match_length > s.lookahead) {
  18865. s.match_length = s.lookahead;
  18866. }
  18867. }
  18868. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  18869. }
  18870. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  18871. if (s.match_length >= MIN_MATCH) {
  18872. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  18873. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  18874. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  18875. s.lookahead -= s.match_length;
  18876. s.strstart += s.match_length;
  18877. s.match_length = 0;
  18878. } else {
  18879. /* No match, output a literal byte */
  18880. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18881. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18882. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18883. s.lookahead--;
  18884. s.strstart++;
  18885. }
  18886. if (bflush) {
  18887. /*** FLUSH_BLOCK(s, 0); ***/
  18888. flush_block_only(s, false);
  18889. if (s.strm.avail_out === 0) {
  18890. return BS_NEED_MORE;
  18891. }
  18892. /***/
  18893. }
  18894. }
  18895. s.insert = 0;
  18896. if (flush === Z_FINISH) {
  18897. /*** FLUSH_BLOCK(s, 1); ***/
  18898. flush_block_only(s, true);
  18899. if (s.strm.avail_out === 0) {
  18900. return BS_FINISH_STARTED;
  18901. }
  18902. /***/
  18903. return BS_FINISH_DONE;
  18904. }
  18905. if (s.last_lit) {
  18906. /*** FLUSH_BLOCK(s, 0); ***/
  18907. flush_block_only(s, false);
  18908. if (s.strm.avail_out === 0) {
  18909. return BS_NEED_MORE;
  18910. }
  18911. /***/
  18912. }
  18913. return BS_BLOCK_DONE;
  18914. }
  18915. /* ===========================================================================
  18916. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  18917. * (It will be regenerated if this run of deflate switches away from Huffman.)
  18918. */
  18919. function deflate_huff(s, flush) {
  18920. var bflush; /* set if current block must be flushed */
  18921. for (;;) {
  18922. /* Make sure that we have a literal to write. */
  18923. if (s.lookahead === 0) {
  18924. fill_window(s);
  18925. if (s.lookahead === 0) {
  18926. if (flush === Z_NO_FLUSH) {
  18927. return BS_NEED_MORE;
  18928. }
  18929. break; /* flush the current block */
  18930. }
  18931. }
  18932. /* Output a literal byte */
  18933. s.match_length = 0;
  18934. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18935. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18936. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18937. s.lookahead--;
  18938. s.strstart++;
  18939. if (bflush) {
  18940. /*** FLUSH_BLOCK(s, 0); ***/
  18941. flush_block_only(s, false);
  18942. if (s.strm.avail_out === 0) {
  18943. return BS_NEED_MORE;
  18944. }
  18945. /***/
  18946. }
  18947. }
  18948. s.insert = 0;
  18949. if (flush === Z_FINISH) {
  18950. /*** FLUSH_BLOCK(s, 1); ***/
  18951. flush_block_only(s, true);
  18952. if (s.strm.avail_out === 0) {
  18953. return BS_FINISH_STARTED;
  18954. }
  18955. /***/
  18956. return BS_FINISH_DONE;
  18957. }
  18958. if (s.last_lit) {
  18959. /*** FLUSH_BLOCK(s, 0); ***/
  18960. flush_block_only(s, false);
  18961. if (s.strm.avail_out === 0) {
  18962. return BS_NEED_MORE;
  18963. }
  18964. /***/
  18965. }
  18966. return BS_BLOCK_DONE;
  18967. }
  18968. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  18969. * the desired pack level (0..9). The values given below have been tuned to
  18970. * exclude worst case performance for pathological files. Better values may be
  18971. * found for specific files.
  18972. */
  18973. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  18974. this.good_length = good_length;
  18975. this.max_lazy = max_lazy;
  18976. this.nice_length = nice_length;
  18977. this.max_chain = max_chain;
  18978. this.func = func;
  18979. };
  18980. var configuration_table;
  18981. configuration_table = [
  18982. /* good lazy nice chain */
  18983. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  18984. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  18985. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  18986. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  18987. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  18988. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  18989. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  18990. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  18991. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  18992. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  18993. ];
  18994. /* ===========================================================================
  18995. * Initialize the "longest match" routines for a new zlib stream
  18996. */
  18997. function lm_init(s) {
  18998. s.window_size = 2 * s.w_size;
  18999. /*** CLEAR_HASH(s); ***/
  19000. zero(s.head); // Fill with NIL (= 0);
  19001. /* Set the default configuration parameters:
  19002. */
  19003. s.max_lazy_match = configuration_table[s.level].max_lazy;
  19004. s.good_match = configuration_table[s.level].good_length;
  19005. s.nice_match = configuration_table[s.level].nice_length;
  19006. s.max_chain_length = configuration_table[s.level].max_chain;
  19007. s.strstart = 0;
  19008. s.block_start = 0;
  19009. s.lookahead = 0;
  19010. s.insert = 0;
  19011. s.match_length = s.prev_length = MIN_MATCH - 1;
  19012. s.match_available = 0;
  19013. s.ins_h = 0;
  19014. }
  19015. function DeflateState() {
  19016. this.strm = null; /* pointer back to this zlib stream */
  19017. this.status = 0; /* as the name implies */
  19018. this.pending_buf = null; /* output still pending */
  19019. this.pending_buf_size = 0; /* size of pending_buf */
  19020. this.pending_out = 0; /* next pending byte to output to the stream */
  19021. this.pending = 0; /* nb of bytes in the pending buffer */
  19022. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  19023. this.gzhead = null; /* gzip header information to write */
  19024. this.gzindex = 0; /* where in extra, name, or comment */
  19025. this.method = Z_DEFLATED; /* can only be DEFLATED */
  19026. this.last_flush = -1; /* value of flush param for previous deflate call */
  19027. this.w_size = 0; /* LZ77 window size (32K by default) */
  19028. this.w_bits = 0; /* log2(w_size) (8..16) */
  19029. this.w_mask = 0; /* w_size - 1 */
  19030. this.window = null;
  19031. /* Sliding window. Input bytes are read into the second half of the window,
  19032. * and move to the first half later to keep a dictionary of at least wSize
  19033. * bytes. With this organization, matches are limited to a distance of
  19034. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  19035. * performed with a length multiple of the block size.
  19036. */
  19037. this.window_size = 0;
  19038. /* Actual size of window: 2*wSize, except when the user input buffer
  19039. * is directly used as sliding window.
  19040. */
  19041. this.prev = null;
  19042. /* Link to older string with same hash index. To limit the size of this
  19043. * array to 64K, this link is maintained only for the last 32K strings.
  19044. * An index in this array is thus a window index modulo 32K.
  19045. */
  19046. this.head = null; /* Heads of the hash chains or NIL. */
  19047. this.ins_h = 0; /* hash index of string to be inserted */
  19048. this.hash_size = 0; /* number of elements in hash table */
  19049. this.hash_bits = 0; /* log2(hash_size) */
  19050. this.hash_mask = 0; /* hash_size-1 */
  19051. this.hash_shift = 0;
  19052. /* Number of bits by which ins_h must be shifted at each input
  19053. * step. It must be such that after MIN_MATCH steps, the oldest
  19054. * byte no longer takes part in the hash key, that is:
  19055. * hash_shift * MIN_MATCH >= hash_bits
  19056. */
  19057. this.block_start = 0;
  19058. /* Window position at the beginning of the current output block. Gets
  19059. * negative when the window is moved backwards.
  19060. */
  19061. this.match_length = 0; /* length of best match */
  19062. this.prev_match = 0; /* previous match */
  19063. this.match_available = 0; /* set if previous match exists */
  19064. this.strstart = 0; /* start of string to insert */
  19065. this.match_start = 0; /* start of matching string */
  19066. this.lookahead = 0; /* number of valid bytes ahead in window */
  19067. this.prev_length = 0;
  19068. /* Length of the best match at previous step. Matches not greater than this
  19069. * are discarded. This is used in the lazy match evaluation.
  19070. */
  19071. this.max_chain_length = 0;
  19072. /* To speed up deflation, hash chains are never searched beyond this
  19073. * length. A higher limit improves compression ratio but degrades the
  19074. * speed.
  19075. */
  19076. this.max_lazy_match = 0;
  19077. /* Attempt to find a better match only when the current match is strictly
  19078. * smaller than this value. This mechanism is used only for compression
  19079. * levels >= 4.
  19080. */
  19081. // That's alias to max_lazy_match, don't use directly
  19082. //this.max_insert_length = 0;
  19083. /* Insert new strings in the hash table only if the match length is not
  19084. * greater than this length. This saves time but degrades compression.
  19085. * max_insert_length is used only for compression levels <= 3.
  19086. */
  19087. this.level = 0; /* compression level (1..9) */
  19088. this.strategy = 0; /* favor or force Huffman coding*/
  19089. this.good_match = 0;
  19090. /* Use a faster search when the previous match is longer than this */
  19091. this.nice_match = 0; /* Stop searching when current match exceeds this */
  19092. /* used by trees.c: */
  19093. /* Didn't use ct_data typedef below to suppress compiler warning */
  19094. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  19095. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  19096. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  19097. // Use flat array of DOUBLE size, with interleaved fata,
  19098. // because JS does not support effective
  19099. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  19100. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  19101. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  19102. zero(this.dyn_ltree);
  19103. zero(this.dyn_dtree);
  19104. zero(this.bl_tree);
  19105. this.l_desc = null; /* desc. for literal tree */
  19106. this.d_desc = null; /* desc. for distance tree */
  19107. this.bl_desc = null; /* desc. for bit length tree */
  19108. //ush bl_count[MAX_BITS+1];
  19109. this.bl_count = new utils.Buf16(MAX_BITS+1);
  19110. /* number of codes at each bit length for an optimal tree */
  19111. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  19112. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  19113. zero(this.heap);
  19114. this.heap_len = 0; /* number of elements in the heap */
  19115. this.heap_max = 0; /* element of largest frequency */
  19116. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  19117. * The same heap array is used to build all trees.
  19118. */
  19119. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  19120. zero(this.depth);
  19121. /* Depth of each subtree used as tie breaker for trees of equal frequency
  19122. */
  19123. this.l_buf = 0; /* buffer index for literals or lengths */
  19124. this.lit_bufsize = 0;
  19125. /* Size of match buffer for literals/lengths. There are 4 reasons for
  19126. * limiting lit_bufsize to 64K:
  19127. * - frequencies can be kept in 16 bit counters
  19128. * - if compression is not successful for the first block, all input
  19129. * data is still in the window so we can still emit a stored block even
  19130. * when input comes from standard input. (This can also be done for
  19131. * all blocks if lit_bufsize is not greater than 32K.)
  19132. * - if compression is not successful for a file smaller than 64K, we can
  19133. * even emit a stored file instead of a stored block (saving 5 bytes).
  19134. * This is applicable only for zip (not gzip or zlib).
  19135. * - creating new Huffman trees less frequently may not provide fast
  19136. * adaptation to changes in the input data statistics. (Take for
  19137. * example a binary file with poorly compressible code followed by
  19138. * a highly compressible string table.) Smaller buffer sizes give
  19139. * fast adaptation but have of course the overhead of transmitting
  19140. * trees more frequently.
  19141. * - I can't count above 4
  19142. */
  19143. this.last_lit = 0; /* running index in l_buf */
  19144. this.d_buf = 0;
  19145. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  19146. * the same number of elements. To use different lengths, an extra flag
  19147. * array would be necessary.
  19148. */
  19149. this.opt_len = 0; /* bit length of current block with optimal trees */
  19150. this.static_len = 0; /* bit length of current block with static trees */
  19151. this.matches = 0; /* number of string matches in current block */
  19152. this.insert = 0; /* bytes at end of window left to insert */
  19153. this.bi_buf = 0;
  19154. /* Output buffer. bits are inserted starting at the bottom (least
  19155. * significant bits).
  19156. */
  19157. this.bi_valid = 0;
  19158. /* Number of valid bits in bi_buf. All bits above the last valid bit
  19159. * are always zero.
  19160. */
  19161. // Used for window memory init. We safely ignore it for JS. That makes
  19162. // sense only for pointers and memory check tools.
  19163. //this.high_water = 0;
  19164. /* High water mark offset in window for initialized bytes -- bytes above
  19165. * this are set to zero in order to avoid memory check warnings when
  19166. * longest match routines access bytes past the input. This is then
  19167. * updated to the new high water mark.
  19168. */
  19169. }
  19170. function deflateResetKeep(strm) {
  19171. var s;
  19172. if (!strm || !strm.state) {
  19173. return err(strm, Z_STREAM_ERROR);
  19174. }
  19175. strm.total_in = strm.total_out = 0;
  19176. strm.data_type = Z_UNKNOWN;
  19177. s = strm.state;
  19178. s.pending = 0;
  19179. s.pending_out = 0;
  19180. if (s.wrap < 0) {
  19181. s.wrap = -s.wrap;
  19182. /* was made negative by deflate(..., Z_FINISH); */
  19183. }
  19184. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  19185. strm.adler = (s.wrap === 2) ?
  19186. 0 // crc32(0, Z_NULL, 0)
  19187. :
  19188. 1; // adler32(0, Z_NULL, 0)
  19189. s.last_flush = Z_NO_FLUSH;
  19190. trees._tr_init(s);
  19191. return Z_OK;
  19192. }
  19193. function deflateReset(strm) {
  19194. var ret = deflateResetKeep(strm);
  19195. if (ret === Z_OK) {
  19196. lm_init(strm.state);
  19197. }
  19198. return ret;
  19199. }
  19200. function deflateSetHeader(strm, head) {
  19201. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19202. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  19203. strm.state.gzhead = head;
  19204. return Z_OK;
  19205. }
  19206. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  19207. if (!strm) { // === Z_NULL
  19208. return Z_STREAM_ERROR;
  19209. }
  19210. var wrap = 1;
  19211. if (level === Z_DEFAULT_COMPRESSION) {
  19212. level = 6;
  19213. }
  19214. if (windowBits < 0) { /* suppress zlib wrapper */
  19215. wrap = 0;
  19216. windowBits = -windowBits;
  19217. }
  19218. else if (windowBits > 15) {
  19219. wrap = 2; /* write gzip wrapper instead */
  19220. windowBits -= 16;
  19221. }
  19222. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  19223. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  19224. strategy < 0 || strategy > Z_FIXED) {
  19225. return err(strm, Z_STREAM_ERROR);
  19226. }
  19227. if (windowBits === 8) {
  19228. windowBits = 9;
  19229. }
  19230. /* until 256-byte window bug fixed */
  19231. var s = new DeflateState();
  19232. strm.state = s;
  19233. s.strm = strm;
  19234. s.wrap = wrap;
  19235. s.gzhead = null;
  19236. s.w_bits = windowBits;
  19237. s.w_size = 1 << s.w_bits;
  19238. s.w_mask = s.w_size - 1;
  19239. s.hash_bits = memLevel + 7;
  19240. s.hash_size = 1 << s.hash_bits;
  19241. s.hash_mask = s.hash_size - 1;
  19242. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  19243. s.window = new utils.Buf8(s.w_size * 2);
  19244. s.head = new utils.Buf16(s.hash_size);
  19245. s.prev = new utils.Buf16(s.w_size);
  19246. // Don't need mem init magic for JS.
  19247. //s.high_water = 0; /* nothing written to s->window yet */
  19248. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  19249. s.pending_buf_size = s.lit_bufsize * 4;
  19250. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  19251. s.d_buf = s.lit_bufsize >> 1;
  19252. s.l_buf = (1 + 2) * s.lit_bufsize;
  19253. s.level = level;
  19254. s.strategy = strategy;
  19255. s.method = method;
  19256. return deflateReset(strm);
  19257. }
  19258. function deflateInit(strm, level) {
  19259. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  19260. }
  19261. function deflate(strm, flush) {
  19262. var old_flush, s;
  19263. var beg, val; // for gzip header write only
  19264. if (!strm || !strm.state ||
  19265. flush > Z_BLOCK || flush < 0) {
  19266. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  19267. }
  19268. s = strm.state;
  19269. if (!strm.output ||
  19270. (!strm.input && strm.avail_in !== 0) ||
  19271. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  19272. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  19273. }
  19274. s.strm = strm; /* just in case */
  19275. old_flush = s.last_flush;
  19276. s.last_flush = flush;
  19277. /* Write the header */
  19278. if (s.status === INIT_STATE) {
  19279. if (s.wrap === 2) { // GZIP header
  19280. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19281. put_byte(s, 31);
  19282. put_byte(s, 139);
  19283. put_byte(s, 8);
  19284. if (!s.gzhead) { // s->gzhead == Z_NULL
  19285. put_byte(s, 0);
  19286. put_byte(s, 0);
  19287. put_byte(s, 0);
  19288. put_byte(s, 0);
  19289. put_byte(s, 0);
  19290. put_byte(s, s.level === 9 ? 2 :
  19291. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  19292. 4 : 0));
  19293. put_byte(s, OS_CODE);
  19294. s.status = BUSY_STATE;
  19295. }
  19296. else {
  19297. put_byte(s, (s.gzhead.text ? 1 : 0) +
  19298. (s.gzhead.hcrc ? 2 : 0) +
  19299. (!s.gzhead.extra ? 0 : 4) +
  19300. (!s.gzhead.name ? 0 : 8) +
  19301. (!s.gzhead.comment ? 0 : 16)
  19302. );
  19303. put_byte(s, s.gzhead.time & 0xff);
  19304. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  19305. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  19306. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  19307. put_byte(s, s.level === 9 ? 2 :
  19308. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  19309. 4 : 0));
  19310. put_byte(s, s.gzhead.os & 0xff);
  19311. if (s.gzhead.extra && s.gzhead.extra.length) {
  19312. put_byte(s, s.gzhead.extra.length & 0xff);
  19313. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  19314. }
  19315. if (s.gzhead.hcrc) {
  19316. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  19317. }
  19318. s.gzindex = 0;
  19319. s.status = EXTRA_STATE;
  19320. }
  19321. }
  19322. else // DEFLATE header
  19323. {
  19324. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  19325. var level_flags = -1;
  19326. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  19327. level_flags = 0;
  19328. } else if (s.level < 6) {
  19329. level_flags = 1;
  19330. } else if (s.level === 6) {
  19331. level_flags = 2;
  19332. } else {
  19333. level_flags = 3;
  19334. }
  19335. header |= (level_flags << 6);
  19336. if (s.strstart !== 0) { header |= PRESET_DICT; }
  19337. header += 31 - (header % 31);
  19338. s.status = BUSY_STATE;
  19339. putShortMSB(s, header);
  19340. /* Save the adler32 of the preset dictionary: */
  19341. if (s.strstart !== 0) {
  19342. putShortMSB(s, strm.adler >>> 16);
  19343. putShortMSB(s, strm.adler & 0xffff);
  19344. }
  19345. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  19346. }
  19347. }
  19348. //#ifdef GZIP
  19349. if (s.status === EXTRA_STATE) {
  19350. if (s.gzhead.extra/* != Z_NULL*/) {
  19351. beg = s.pending; /* start of bytes to update crc */
  19352. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  19353. if (s.pending === s.pending_buf_size) {
  19354. if (s.gzhead.hcrc && s.pending > beg) {
  19355. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19356. }
  19357. flush_pending(strm);
  19358. beg = s.pending;
  19359. if (s.pending === s.pending_buf_size) {
  19360. break;
  19361. }
  19362. }
  19363. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  19364. s.gzindex++;
  19365. }
  19366. if (s.gzhead.hcrc && s.pending > beg) {
  19367. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19368. }
  19369. if (s.gzindex === s.gzhead.extra.length) {
  19370. s.gzindex = 0;
  19371. s.status = NAME_STATE;
  19372. }
  19373. }
  19374. else {
  19375. s.status = NAME_STATE;
  19376. }
  19377. }
  19378. if (s.status === NAME_STATE) {
  19379. if (s.gzhead.name/* != Z_NULL*/) {
  19380. beg = s.pending; /* start of bytes to update crc */
  19381. //int val;
  19382. do {
  19383. if (s.pending === s.pending_buf_size) {
  19384. if (s.gzhead.hcrc && s.pending > beg) {
  19385. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19386. }
  19387. flush_pending(strm);
  19388. beg = s.pending;
  19389. if (s.pending === s.pending_buf_size) {
  19390. val = 1;
  19391. break;
  19392. }
  19393. }
  19394. // JS specific: little magic to add zero terminator to end of string
  19395. if (s.gzindex < s.gzhead.name.length) {
  19396. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  19397. } else {
  19398. val = 0;
  19399. }
  19400. put_byte(s, val);
  19401. } while (val !== 0);
  19402. if (s.gzhead.hcrc && s.pending > beg){
  19403. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19404. }
  19405. if (val === 0) {
  19406. s.gzindex = 0;
  19407. s.status = COMMENT_STATE;
  19408. }
  19409. }
  19410. else {
  19411. s.status = COMMENT_STATE;
  19412. }
  19413. }
  19414. if (s.status === COMMENT_STATE) {
  19415. if (s.gzhead.comment/* != Z_NULL*/) {
  19416. beg = s.pending; /* start of bytes to update crc */
  19417. //int val;
  19418. do {
  19419. if (s.pending === s.pending_buf_size) {
  19420. if (s.gzhead.hcrc && s.pending > beg) {
  19421. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19422. }
  19423. flush_pending(strm);
  19424. beg = s.pending;
  19425. if (s.pending === s.pending_buf_size) {
  19426. val = 1;
  19427. break;
  19428. }
  19429. }
  19430. // JS specific: little magic to add zero terminator to end of string
  19431. if (s.gzindex < s.gzhead.comment.length) {
  19432. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  19433. } else {
  19434. val = 0;
  19435. }
  19436. put_byte(s, val);
  19437. } while (val !== 0);
  19438. if (s.gzhead.hcrc && s.pending > beg) {
  19439. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19440. }
  19441. if (val === 0) {
  19442. s.status = HCRC_STATE;
  19443. }
  19444. }
  19445. else {
  19446. s.status = HCRC_STATE;
  19447. }
  19448. }
  19449. if (s.status === HCRC_STATE) {
  19450. if (s.gzhead.hcrc) {
  19451. if (s.pending + 2 > s.pending_buf_size) {
  19452. flush_pending(strm);
  19453. }
  19454. if (s.pending + 2 <= s.pending_buf_size) {
  19455. put_byte(s, strm.adler & 0xff);
  19456. put_byte(s, (strm.adler >> 8) & 0xff);
  19457. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19458. s.status = BUSY_STATE;
  19459. }
  19460. }
  19461. else {
  19462. s.status = BUSY_STATE;
  19463. }
  19464. }
  19465. //#endif
  19466. /* Flush as much pending output as possible */
  19467. if (s.pending !== 0) {
  19468. flush_pending(strm);
  19469. if (strm.avail_out === 0) {
  19470. /* Since avail_out is 0, deflate will be called again with
  19471. * more output space, but possibly with both pending and
  19472. * avail_in equal to zero. There won't be anything to do,
  19473. * but this is not an error situation so make sure we
  19474. * return OK instead of BUF_ERROR at next call of deflate:
  19475. */
  19476. s.last_flush = -1;
  19477. return Z_OK;
  19478. }
  19479. /* Make sure there is something to do and avoid duplicate consecutive
  19480. * flushes. For repeated and useless calls with Z_FINISH, we keep
  19481. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  19482. */
  19483. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  19484. flush !== Z_FINISH) {
  19485. return err(strm, Z_BUF_ERROR);
  19486. }
  19487. /* User must not provide more input after the first FINISH: */
  19488. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  19489. return err(strm, Z_BUF_ERROR);
  19490. }
  19491. /* Start a new block or continue the current one.
  19492. */
  19493. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  19494. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  19495. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  19496. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  19497. configuration_table[s.level].func(s, flush));
  19498. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  19499. s.status = FINISH_STATE;
  19500. }
  19501. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  19502. if (strm.avail_out === 0) {
  19503. s.last_flush = -1;
  19504. /* avoid BUF_ERROR next call, see above */
  19505. }
  19506. return Z_OK;
  19507. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  19508. * of deflate should use the same flush parameter to make sure
  19509. * that the flush is complete. So we don't have to output an
  19510. * empty block here, this will be done at next call. This also
  19511. * ensures that for a very small output buffer, we emit at most
  19512. * one empty block.
  19513. */
  19514. }
  19515. if (bstate === BS_BLOCK_DONE) {
  19516. if (flush === Z_PARTIAL_FLUSH) {
  19517. trees._tr_align(s);
  19518. }
  19519. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  19520. trees._tr_stored_block(s, 0, 0, false);
  19521. /* For a full flush, this empty block will be recognized
  19522. * as a special marker by inflate_sync().
  19523. */
  19524. if (flush === Z_FULL_FLUSH) {
  19525. /*** CLEAR_HASH(s); ***/ /* forget history */
  19526. zero(s.head); // Fill with NIL (= 0);
  19527. if (s.lookahead === 0) {
  19528. s.strstart = 0;
  19529. s.block_start = 0;
  19530. s.insert = 0;
  19531. }
  19532. }
  19533. }
  19534. flush_pending(strm);
  19535. if (strm.avail_out === 0) {
  19536. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  19537. return Z_OK;
  19538. }
  19539. }
  19540. }
  19541. //Assert(strm->avail_out > 0, "bug2");
  19542. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  19543. if (flush !== Z_FINISH) { return Z_OK; }
  19544. if (s.wrap <= 0) { return Z_STREAM_END; }
  19545. /* Write the trailer */
  19546. if (s.wrap === 2) {
  19547. put_byte(s, strm.adler & 0xff);
  19548. put_byte(s, (strm.adler >> 8) & 0xff);
  19549. put_byte(s, (strm.adler >> 16) & 0xff);
  19550. put_byte(s, (strm.adler >> 24) & 0xff);
  19551. put_byte(s, strm.total_in & 0xff);
  19552. put_byte(s, (strm.total_in >> 8) & 0xff);
  19553. put_byte(s, (strm.total_in >> 16) & 0xff);
  19554. put_byte(s, (strm.total_in >> 24) & 0xff);
  19555. }
  19556. else
  19557. {
  19558. putShortMSB(s, strm.adler >>> 16);
  19559. putShortMSB(s, strm.adler & 0xffff);
  19560. }
  19561. flush_pending(strm);
  19562. /* If avail_out is zero, the application will call deflate again
  19563. * to flush the rest.
  19564. */
  19565. if (s.wrap > 0) { s.wrap = -s.wrap; }
  19566. /* write the trailer only once! */
  19567. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  19568. }
  19569. function deflateEnd(strm) {
  19570. var status;
  19571. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  19572. return Z_STREAM_ERROR;
  19573. }
  19574. status = strm.state.status;
  19575. if (status !== INIT_STATE &&
  19576. status !== EXTRA_STATE &&
  19577. status !== NAME_STATE &&
  19578. status !== COMMENT_STATE &&
  19579. status !== HCRC_STATE &&
  19580. status !== BUSY_STATE &&
  19581. status !== FINISH_STATE
  19582. ) {
  19583. return err(strm, Z_STREAM_ERROR);
  19584. }
  19585. strm.state = null;
  19586. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  19587. }
  19588. /* =========================================================================
  19589. * Copy the source state to the destination state
  19590. */
  19591. //function deflateCopy(dest, source) {
  19592. //
  19593. //}
  19594. exports.deflateInit = deflateInit;
  19595. exports.deflateInit2 = deflateInit2;
  19596. exports.deflateReset = deflateReset;
  19597. exports.deflateResetKeep = deflateResetKeep;
  19598. exports.deflateSetHeader = deflateSetHeader;
  19599. exports.deflate = deflate;
  19600. exports.deflateEnd = deflateEnd;
  19601. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  19602. /* Not implemented
  19603. exports.deflateBound = deflateBound;
  19604. exports.deflateCopy = deflateCopy;
  19605. exports.deflateSetDictionary = deflateSetDictionary;
  19606. exports.deflateParams = deflateParams;
  19607. exports.deflatePending = deflatePending;
  19608. exports.deflatePrime = deflatePrime;
  19609. exports.deflateTune = deflateTune;
  19610. */
  19611. },{"../utils/common":66,"./adler32":68,"./crc32":70,"./messages":76,"./trees":77}],72:[function(require,module,exports){
  19612. 'use strict';
  19613. function GZheader() {
  19614. /* true if compressed data believed to be text */
  19615. this.text = 0;
  19616. /* modification time */
  19617. this.time = 0;
  19618. /* extra flags (not used when writing a gzip file) */
  19619. this.xflags = 0;
  19620. /* operating system */
  19621. this.os = 0;
  19622. /* pointer to extra field or Z_NULL if none */
  19623. this.extra = null;
  19624. /* extra field length (valid if extra != Z_NULL) */
  19625. this.extra_len = 0; // Actually, we don't need it in JS,
  19626. // but leave for few code modifications
  19627. //
  19628. // Setup limits is not necessary because in js we should not preallocate memory
  19629. // for inflate use constant limit in 65536 bytes
  19630. //
  19631. /* space at extra (only when reading header) */
  19632. // this.extra_max = 0;
  19633. /* pointer to zero-terminated file name or Z_NULL */
  19634. this.name = '';
  19635. /* space at name (only when reading header) */
  19636. // this.name_max = 0;
  19637. /* pointer to zero-terminated comment or Z_NULL */
  19638. this.comment = '';
  19639. /* space at comment (only when reading header) */
  19640. // this.comm_max = 0;
  19641. /* true if there was or will be a header crc */
  19642. this.hcrc = 0;
  19643. /* true when done reading gzip header (not used when writing a gzip file) */
  19644. this.done = false;
  19645. }
  19646. module.exports = GZheader;
  19647. },{}],73:[function(require,module,exports){
  19648. 'use strict';
  19649. // See state defs from inflate.js
  19650. var BAD = 30; /* got a data error -- remain here until reset */
  19651. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19652. /*
  19653. Decode literal, length, and distance codes and write out the resulting
  19654. literal and match bytes until either not enough input or output is
  19655. available, an end-of-block is encountered, or a data error is encountered.
  19656. When large enough input and output buffers are supplied to inflate(), for
  19657. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  19658. inflate execution time is spent in this routine.
  19659. Entry assumptions:
  19660. state.mode === LEN
  19661. strm.avail_in >= 6
  19662. strm.avail_out >= 258
  19663. start >= strm.avail_out
  19664. state.bits < 8
  19665. On return, state.mode is one of:
  19666. LEN -- ran out of enough output space or enough available input
  19667. TYPE -- reached end of block code, inflate() to interpret next block
  19668. BAD -- error in block data
  19669. Notes:
  19670. - The maximum input bits used by a length/distance pair is 15 bits for the
  19671. length code, 5 bits for the length extra, 15 bits for the distance code,
  19672. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  19673. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  19674. checking for available input while decoding.
  19675. - The maximum bytes that a single length/distance pair can output is 258
  19676. bytes, which is the maximum length that can be coded. inflate_fast()
  19677. requires strm.avail_out >= 258 for each loop to avoid checking for
  19678. output space.
  19679. */
  19680. module.exports = function inflate_fast(strm, start) {
  19681. var state;
  19682. var _in; /* local strm.input */
  19683. var last; /* have enough input while in < last */
  19684. var _out; /* local strm.output */
  19685. var beg; /* inflate()'s initial strm.output */
  19686. var end; /* while out < end, enough space available */
  19687. //#ifdef INFLATE_STRICT
  19688. var dmax; /* maximum distance from zlib header */
  19689. //#endif
  19690. var wsize; /* window size or zero if not using window */
  19691. var whave; /* valid bytes in the window */
  19692. var wnext; /* window write index */
  19693. var window; /* allocated sliding window, if wsize != 0 */
  19694. var hold; /* local strm.hold */
  19695. var bits; /* local strm.bits */
  19696. var lcode; /* local strm.lencode */
  19697. var dcode; /* local strm.distcode */
  19698. var lmask; /* mask for first level of length codes */
  19699. var dmask; /* mask for first level of distance codes */
  19700. var here; /* retrieved table entry */
  19701. var op; /* code bits, operation, extra bits, or */
  19702. /* window position, window bytes to copy */
  19703. var len; /* match length, unused bytes */
  19704. var dist; /* match distance */
  19705. var from; /* where to copy match from */
  19706. var from_source;
  19707. var input, output; // JS specific, because we have no pointers
  19708. /* copy state to local variables */
  19709. state = strm.state;
  19710. //here = state.here;
  19711. _in = strm.next_in;
  19712. input = strm.input;
  19713. last = _in + (strm.avail_in - 5);
  19714. _out = strm.next_out;
  19715. output = strm.output;
  19716. beg = _out - (start - strm.avail_out);
  19717. end = _out + (strm.avail_out - 257);
  19718. //#ifdef INFLATE_STRICT
  19719. dmax = state.dmax;
  19720. //#endif
  19721. wsize = state.wsize;
  19722. whave = state.whave;
  19723. wnext = state.wnext;
  19724. window = state.window;
  19725. hold = state.hold;
  19726. bits = state.bits;
  19727. lcode = state.lencode;
  19728. dcode = state.distcode;
  19729. lmask = (1 << state.lenbits) - 1;
  19730. dmask = (1 << state.distbits) - 1;
  19731. /* decode literals and length/distances until end-of-block or not enough
  19732. input data or output space */
  19733. top:
  19734. do {
  19735. if (bits < 15) {
  19736. hold += input[_in++] << bits;
  19737. bits += 8;
  19738. hold += input[_in++] << bits;
  19739. bits += 8;
  19740. }
  19741. here = lcode[hold & lmask];
  19742. dolen:
  19743. for (;;) { // Goto emulation
  19744. op = here >>> 24/*here.bits*/;
  19745. hold >>>= op;
  19746. bits -= op;
  19747. op = (here >>> 16) & 0xff/*here.op*/;
  19748. if (op === 0) { /* literal */
  19749. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  19750. // "inflate: literal '%c'\n" :
  19751. // "inflate: literal 0x%02x\n", here.val));
  19752. output[_out++] = here & 0xffff/*here.val*/;
  19753. }
  19754. else if (op & 16) { /* length base */
  19755. len = here & 0xffff/*here.val*/;
  19756. op &= 15; /* number of extra bits */
  19757. if (op) {
  19758. if (bits < op) {
  19759. hold += input[_in++] << bits;
  19760. bits += 8;
  19761. }
  19762. len += hold & ((1 << op) - 1);
  19763. hold >>>= op;
  19764. bits -= op;
  19765. }
  19766. //Tracevv((stderr, "inflate: length %u\n", len));
  19767. if (bits < 15) {
  19768. hold += input[_in++] << bits;
  19769. bits += 8;
  19770. hold += input[_in++] << bits;
  19771. bits += 8;
  19772. }
  19773. here = dcode[hold & dmask];
  19774. dodist:
  19775. for (;;) { // goto emulation
  19776. op = here >>> 24/*here.bits*/;
  19777. hold >>>= op;
  19778. bits -= op;
  19779. op = (here >>> 16) & 0xff/*here.op*/;
  19780. if (op & 16) { /* distance base */
  19781. dist = here & 0xffff/*here.val*/;
  19782. op &= 15; /* number of extra bits */
  19783. if (bits < op) {
  19784. hold += input[_in++] << bits;
  19785. bits += 8;
  19786. if (bits < op) {
  19787. hold += input[_in++] << bits;
  19788. bits += 8;
  19789. }
  19790. }
  19791. dist += hold & ((1 << op) - 1);
  19792. //#ifdef INFLATE_STRICT
  19793. if (dist > dmax) {
  19794. strm.msg = 'invalid distance too far back';
  19795. state.mode = BAD;
  19796. break top;
  19797. }
  19798. //#endif
  19799. hold >>>= op;
  19800. bits -= op;
  19801. //Tracevv((stderr, "inflate: distance %u\n", dist));
  19802. op = _out - beg; /* max distance in output */
  19803. if (dist > op) { /* see if copy from window */
  19804. op = dist - op; /* distance back in window */
  19805. if (op > whave) {
  19806. if (state.sane) {
  19807. strm.msg = 'invalid distance too far back';
  19808. state.mode = BAD;
  19809. break top;
  19810. }
  19811. // (!) This block is disabled in zlib defailts,
  19812. // don't enable it for binary compatibility
  19813. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  19814. // if (len <= op - whave) {
  19815. // do {
  19816. // output[_out++] = 0;
  19817. // } while (--len);
  19818. // continue top;
  19819. // }
  19820. // len -= op - whave;
  19821. // do {
  19822. // output[_out++] = 0;
  19823. // } while (--op > whave);
  19824. // if (op === 0) {
  19825. // from = _out - dist;
  19826. // do {
  19827. // output[_out++] = output[from++];
  19828. // } while (--len);
  19829. // continue top;
  19830. // }
  19831. //#endif
  19832. }
  19833. from = 0; // window index
  19834. from_source = window;
  19835. if (wnext === 0) { /* very common case */
  19836. from += wsize - op;
  19837. if (op < len) { /* some from window */
  19838. len -= op;
  19839. do {
  19840. output[_out++] = window[from++];
  19841. } while (--op);
  19842. from = _out - dist; /* rest from output */
  19843. from_source = output;
  19844. }
  19845. }
  19846. else if (wnext < op) { /* wrap around window */
  19847. from += wsize + wnext - op;
  19848. op -= wnext;
  19849. if (op < len) { /* some from end of window */
  19850. len -= op;
  19851. do {
  19852. output[_out++] = window[from++];
  19853. } while (--op);
  19854. from = 0;
  19855. if (wnext < len) { /* some from start of window */
  19856. op = wnext;
  19857. len -= op;
  19858. do {
  19859. output[_out++] = window[from++];
  19860. } while (--op);
  19861. from = _out - dist; /* rest from output */
  19862. from_source = output;
  19863. }
  19864. }
  19865. }
  19866. else { /* contiguous in window */
  19867. from += wnext - op;
  19868. if (op < len) { /* some from window */
  19869. len -= op;
  19870. do {
  19871. output[_out++] = window[from++];
  19872. } while (--op);
  19873. from = _out - dist; /* rest from output */
  19874. from_source = output;
  19875. }
  19876. }
  19877. while (len > 2) {
  19878. output[_out++] = from_source[from++];
  19879. output[_out++] = from_source[from++];
  19880. output[_out++] = from_source[from++];
  19881. len -= 3;
  19882. }
  19883. if (len) {
  19884. output[_out++] = from_source[from++];
  19885. if (len > 1) {
  19886. output[_out++] = from_source[from++];
  19887. }
  19888. }
  19889. }
  19890. else {
  19891. from = _out - dist; /* copy direct from output */
  19892. do { /* minimum length is three */
  19893. output[_out++] = output[from++];
  19894. output[_out++] = output[from++];
  19895. output[_out++] = output[from++];
  19896. len -= 3;
  19897. } while (len > 2);
  19898. if (len) {
  19899. output[_out++] = output[from++];
  19900. if (len > 1) {
  19901. output[_out++] = output[from++];
  19902. }
  19903. }
  19904. }
  19905. }
  19906. else if ((op & 64) === 0) { /* 2nd level distance code */
  19907. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19908. continue dodist;
  19909. }
  19910. else {
  19911. strm.msg = 'invalid distance code';
  19912. state.mode = BAD;
  19913. break top;
  19914. }
  19915. break; // need to emulate goto via "continue"
  19916. }
  19917. }
  19918. else if ((op & 64) === 0) { /* 2nd level length code */
  19919. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19920. continue dolen;
  19921. }
  19922. else if (op & 32) { /* end-of-block */
  19923. //Tracevv((stderr, "inflate: end of block\n"));
  19924. state.mode = TYPE;
  19925. break top;
  19926. }
  19927. else {
  19928. strm.msg = 'invalid literal/length code';
  19929. state.mode = BAD;
  19930. break top;
  19931. }
  19932. break; // need to emulate goto via "continue"
  19933. }
  19934. } while (_in < last && _out < end);
  19935. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  19936. len = bits >> 3;
  19937. _in -= len;
  19938. bits -= len << 3;
  19939. hold &= (1 << bits) - 1;
  19940. /* update state and return */
  19941. strm.next_in = _in;
  19942. strm.next_out = _out;
  19943. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  19944. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  19945. state.hold = hold;
  19946. state.bits = bits;
  19947. return;
  19948. };
  19949. },{}],74:[function(require,module,exports){
  19950. 'use strict';
  19951. var utils = require('../utils/common');
  19952. var adler32 = require('./adler32');
  19953. var crc32 = require('./crc32');
  19954. var inflate_fast = require('./inffast');
  19955. var inflate_table = require('./inftrees');
  19956. var CODES = 0;
  19957. var LENS = 1;
  19958. var DISTS = 2;
  19959. /* Public constants ==========================================================*/
  19960. /* ===========================================================================*/
  19961. /* Allowed flush values; see deflate() and inflate() below for details */
  19962. //var Z_NO_FLUSH = 0;
  19963. //var Z_PARTIAL_FLUSH = 1;
  19964. //var Z_SYNC_FLUSH = 2;
  19965. //var Z_FULL_FLUSH = 3;
  19966. var Z_FINISH = 4;
  19967. var Z_BLOCK = 5;
  19968. var Z_TREES = 6;
  19969. /* Return codes for the compression/decompression functions. Negative values
  19970. * are errors, positive values are used for special but normal events.
  19971. */
  19972. var Z_OK = 0;
  19973. var Z_STREAM_END = 1;
  19974. var Z_NEED_DICT = 2;
  19975. //var Z_ERRNO = -1;
  19976. var Z_STREAM_ERROR = -2;
  19977. var Z_DATA_ERROR = -3;
  19978. var Z_MEM_ERROR = -4;
  19979. var Z_BUF_ERROR = -5;
  19980. //var Z_VERSION_ERROR = -6;
  19981. /* The deflate compression method */
  19982. var Z_DEFLATED = 8;
  19983. /* STATES ====================================================================*/
  19984. /* ===========================================================================*/
  19985. var HEAD = 1; /* i: waiting for magic header */
  19986. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  19987. var TIME = 3; /* i: waiting for modification time (gzip) */
  19988. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  19989. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  19990. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  19991. var NAME = 7; /* i: waiting for end of file name (gzip) */
  19992. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  19993. var HCRC = 9; /* i: waiting for header crc (gzip) */
  19994. var DICTID = 10; /* i: waiting for dictionary check value */
  19995. var DICT = 11; /* waiting for inflateSetDictionary() call */
  19996. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19997. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  19998. var STORED = 14; /* i: waiting for stored size (length and complement) */
  19999. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  20000. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  20001. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  20002. var LENLENS = 18; /* i: waiting for code length code lengths */
  20003. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  20004. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  20005. var LEN = 21; /* i: waiting for length/lit/eob code */
  20006. var LENEXT = 22; /* i: waiting for length extra bits */
  20007. var DIST = 23; /* i: waiting for distance code */
  20008. var DISTEXT = 24; /* i: waiting for distance extra bits */
  20009. var MATCH = 25; /* o: waiting for output space to copy string */
  20010. var LIT = 26; /* o: waiting for output space to write literal */
  20011. var CHECK = 27; /* i: waiting for 32-bit check value */
  20012. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  20013. var DONE = 29; /* finished check, done -- remain here until reset */
  20014. var BAD = 30; /* got a data error -- remain here until reset */
  20015. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  20016. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  20017. /* ===========================================================================*/
  20018. var ENOUGH_LENS = 852;
  20019. var ENOUGH_DISTS = 592;
  20020. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  20021. var MAX_WBITS = 15;
  20022. /* 32K LZ77 window */
  20023. var DEF_WBITS = MAX_WBITS;
  20024. function ZSWAP32(q) {
  20025. return (((q >>> 24) & 0xff) +
  20026. ((q >>> 8) & 0xff00) +
  20027. ((q & 0xff00) << 8) +
  20028. ((q & 0xff) << 24));
  20029. }
  20030. function InflateState() {
  20031. this.mode = 0; /* current inflate mode */
  20032. this.last = false; /* true if processing last block */
  20033. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  20034. this.havedict = false; /* true if dictionary provided */
  20035. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  20036. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  20037. this.check = 0; /* protected copy of check value */
  20038. this.total = 0; /* protected copy of output count */
  20039. // TODO: may be {}
  20040. this.head = null; /* where to save gzip header information */
  20041. /* sliding window */
  20042. this.wbits = 0; /* log base 2 of requested window size */
  20043. this.wsize = 0; /* window size or zero if not using window */
  20044. this.whave = 0; /* valid bytes in the window */
  20045. this.wnext = 0; /* window write index */
  20046. this.window = null; /* allocated sliding window, if needed */
  20047. /* bit accumulator */
  20048. this.hold = 0; /* input bit accumulator */
  20049. this.bits = 0; /* number of bits in "in" */
  20050. /* for string and stored block copying */
  20051. this.length = 0; /* literal or length of data to copy */
  20052. this.offset = 0; /* distance back to copy string from */
  20053. /* for table and code decoding */
  20054. this.extra = 0; /* extra bits needed */
  20055. /* fixed and dynamic code tables */
  20056. this.lencode = null; /* starting table for length/literal codes */
  20057. this.distcode = null; /* starting table for distance codes */
  20058. this.lenbits = 0; /* index bits for lencode */
  20059. this.distbits = 0; /* index bits for distcode */
  20060. /* dynamic table building */
  20061. this.ncode = 0; /* number of code length code lengths */
  20062. this.nlen = 0; /* number of length code lengths */
  20063. this.ndist = 0; /* number of distance code lengths */
  20064. this.have = 0; /* number of code lengths in lens[] */
  20065. this.next = null; /* next available space in codes[] */
  20066. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  20067. this.work = new utils.Buf16(288); /* work area for code table building */
  20068. /*
  20069. because we don't have pointers in js, we use lencode and distcode directly
  20070. as buffers so we don't need codes
  20071. */
  20072. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  20073. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  20074. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  20075. this.sane = 0; /* if false, allow invalid distance too far */
  20076. this.back = 0; /* bits back of last unprocessed length/lit */
  20077. this.was = 0; /* initial length of match */
  20078. }
  20079. function inflateResetKeep(strm) {
  20080. var state;
  20081. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20082. state = strm.state;
  20083. strm.total_in = strm.total_out = state.total = 0;
  20084. strm.msg = ''; /*Z_NULL*/
  20085. if (state.wrap) { /* to support ill-conceived Java test suite */
  20086. strm.adler = state.wrap & 1;
  20087. }
  20088. state.mode = HEAD;
  20089. state.last = 0;
  20090. state.havedict = 0;
  20091. state.dmax = 32768;
  20092. state.head = null/*Z_NULL*/;
  20093. state.hold = 0;
  20094. state.bits = 0;
  20095. //state.lencode = state.distcode = state.next = state.codes;
  20096. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  20097. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  20098. state.sane = 1;
  20099. state.back = -1;
  20100. //Tracev((stderr, "inflate: reset\n"));
  20101. return Z_OK;
  20102. }
  20103. function inflateReset(strm) {
  20104. var state;
  20105. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20106. state = strm.state;
  20107. state.wsize = 0;
  20108. state.whave = 0;
  20109. state.wnext = 0;
  20110. return inflateResetKeep(strm);
  20111. }
  20112. function inflateReset2(strm, windowBits) {
  20113. var wrap;
  20114. var state;
  20115. /* get the state */
  20116. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20117. state = strm.state;
  20118. /* extract wrap request from windowBits parameter */
  20119. if (windowBits < 0) {
  20120. wrap = 0;
  20121. windowBits = -windowBits;
  20122. }
  20123. else {
  20124. wrap = (windowBits >> 4) + 1;
  20125. if (windowBits < 48) {
  20126. windowBits &= 15;
  20127. }
  20128. }
  20129. /* set number of window bits, free window if different */
  20130. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  20131. return Z_STREAM_ERROR;
  20132. }
  20133. if (state.window !== null && state.wbits !== windowBits) {
  20134. state.window = null;
  20135. }
  20136. /* update state and reset the rest of it */
  20137. state.wrap = wrap;
  20138. state.wbits = windowBits;
  20139. return inflateReset(strm);
  20140. }
  20141. function inflateInit2(strm, windowBits) {
  20142. var ret;
  20143. var state;
  20144. if (!strm) { return Z_STREAM_ERROR; }
  20145. //strm.msg = Z_NULL; /* in case we return an error */
  20146. state = new InflateState();
  20147. //if (state === Z_NULL) return Z_MEM_ERROR;
  20148. //Tracev((stderr, "inflate: allocated\n"));
  20149. strm.state = state;
  20150. state.window = null/*Z_NULL*/;
  20151. ret = inflateReset2(strm, windowBits);
  20152. if (ret !== Z_OK) {
  20153. strm.state = null/*Z_NULL*/;
  20154. }
  20155. return ret;
  20156. }
  20157. function inflateInit(strm) {
  20158. return inflateInit2(strm, DEF_WBITS);
  20159. }
  20160. /*
  20161. Return state with length and distance decoding tables and index sizes set to
  20162. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  20163. If BUILDFIXED is defined, then instead this routine builds the tables the
  20164. first time it's called, and returns those tables the first time and
  20165. thereafter. This reduces the size of the code by about 2K bytes, in
  20166. exchange for a little execution time. However, BUILDFIXED should not be
  20167. used for threaded applications, since the rewriting of the tables and virgin
  20168. may not be thread-safe.
  20169. */
  20170. var virgin = true;
  20171. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  20172. function fixedtables(state) {
  20173. /* build fixed huffman tables if first call (may not be thread safe) */
  20174. if (virgin) {
  20175. var sym;
  20176. lenfix = new utils.Buf32(512);
  20177. distfix = new utils.Buf32(32);
  20178. /* literal/length table */
  20179. sym = 0;
  20180. while (sym < 144) { state.lens[sym++] = 8; }
  20181. while (sym < 256) { state.lens[sym++] = 9; }
  20182. while (sym < 280) { state.lens[sym++] = 7; }
  20183. while (sym < 288) { state.lens[sym++] = 8; }
  20184. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  20185. /* distance table */
  20186. sym = 0;
  20187. while (sym < 32) { state.lens[sym++] = 5; }
  20188. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  20189. /* do this just once */
  20190. virgin = false;
  20191. }
  20192. state.lencode = lenfix;
  20193. state.lenbits = 9;
  20194. state.distcode = distfix;
  20195. state.distbits = 5;
  20196. }
  20197. /*
  20198. Update the window with the last wsize (normally 32K) bytes written before
  20199. returning. If window does not exist yet, create it. This is only called
  20200. when a window is already in use, or when output has been written during this
  20201. inflate call, but the end of the deflate stream has not been reached yet.
  20202. It is also called to create a window for dictionary data when a dictionary
  20203. is loaded.
  20204. Providing output buffers larger than 32K to inflate() should provide a speed
  20205. advantage, since only the last 32K of output is copied to the sliding window
  20206. upon return from inflate(), and since all distances after the first 32K of
  20207. output will fall in the output data, making match copies simpler and faster.
  20208. The advantage may be dependent on the size of the processor's data caches.
  20209. */
  20210. function updatewindow(strm, src, end, copy) {
  20211. var dist;
  20212. var state = strm.state;
  20213. /* if it hasn't been done already, allocate space for the window */
  20214. if (state.window === null) {
  20215. state.wsize = 1 << state.wbits;
  20216. state.wnext = 0;
  20217. state.whave = 0;
  20218. state.window = new utils.Buf8(state.wsize);
  20219. }
  20220. /* copy state->wsize or less output bytes into the circular window */
  20221. if (copy >= state.wsize) {
  20222. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  20223. state.wnext = 0;
  20224. state.whave = state.wsize;
  20225. }
  20226. else {
  20227. dist = state.wsize - state.wnext;
  20228. if (dist > copy) {
  20229. dist = copy;
  20230. }
  20231. //zmemcpy(state->window + state->wnext, end - copy, dist);
  20232. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  20233. copy -= dist;
  20234. if (copy) {
  20235. //zmemcpy(state->window, end - copy, copy);
  20236. utils.arraySet(state.window,src, end - copy, copy, 0);
  20237. state.wnext = copy;
  20238. state.whave = state.wsize;
  20239. }
  20240. else {
  20241. state.wnext += dist;
  20242. if (state.wnext === state.wsize) { state.wnext = 0; }
  20243. if (state.whave < state.wsize) { state.whave += dist; }
  20244. }
  20245. }
  20246. return 0;
  20247. }
  20248. function inflate(strm, flush) {
  20249. var state;
  20250. var input, output; // input/output buffers
  20251. var next; /* next input INDEX */
  20252. var put; /* next output INDEX */
  20253. var have, left; /* available input and output */
  20254. var hold; /* bit buffer */
  20255. var bits; /* bits in bit buffer */
  20256. var _in, _out; /* save starting available input and output */
  20257. var copy; /* number of stored or match bytes to copy */
  20258. var from; /* where to copy match bytes from */
  20259. var from_source;
  20260. var here = 0; /* current decoding table entry */
  20261. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  20262. //var last; /* parent table entry */
  20263. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  20264. var len; /* length to copy for repeats, bits to drop */
  20265. var ret; /* return code */
  20266. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  20267. var opts;
  20268. var n; // temporary var for NEED_BITS
  20269. var order = /* permutation of code lengths */
  20270. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  20271. if (!strm || !strm.state || !strm.output ||
  20272. (!strm.input && strm.avail_in !== 0)) {
  20273. return Z_STREAM_ERROR;
  20274. }
  20275. state = strm.state;
  20276. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  20277. //--- LOAD() ---
  20278. put = strm.next_out;
  20279. output = strm.output;
  20280. left = strm.avail_out;
  20281. next = strm.next_in;
  20282. input = strm.input;
  20283. have = strm.avail_in;
  20284. hold = state.hold;
  20285. bits = state.bits;
  20286. //---
  20287. _in = have;
  20288. _out = left;
  20289. ret = Z_OK;
  20290. inf_leave: // goto emulation
  20291. for (;;) {
  20292. switch (state.mode) {
  20293. case HEAD:
  20294. if (state.wrap === 0) {
  20295. state.mode = TYPEDO;
  20296. break;
  20297. }
  20298. //=== NEEDBITS(16);
  20299. while (bits < 16) {
  20300. if (have === 0) { break inf_leave; }
  20301. have--;
  20302. hold += input[next++] << bits;
  20303. bits += 8;
  20304. }
  20305. //===//
  20306. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  20307. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  20308. //=== CRC2(state.check, hold);
  20309. hbuf[0] = hold & 0xff;
  20310. hbuf[1] = (hold >>> 8) & 0xff;
  20311. state.check = crc32(state.check, hbuf, 2, 0);
  20312. //===//
  20313. //=== INITBITS();
  20314. hold = 0;
  20315. bits = 0;
  20316. //===//
  20317. state.mode = FLAGS;
  20318. break;
  20319. }
  20320. state.flags = 0; /* expect zlib header */
  20321. if (state.head) {
  20322. state.head.done = false;
  20323. }
  20324. if (!(state.wrap & 1) || /* check if zlib header allowed */
  20325. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  20326. strm.msg = 'incorrect header check';
  20327. state.mode = BAD;
  20328. break;
  20329. }
  20330. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  20331. strm.msg = 'unknown compression method';
  20332. state.mode = BAD;
  20333. break;
  20334. }
  20335. //--- DROPBITS(4) ---//
  20336. hold >>>= 4;
  20337. bits -= 4;
  20338. //---//
  20339. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  20340. if (state.wbits === 0) {
  20341. state.wbits = len;
  20342. }
  20343. else if (len > state.wbits) {
  20344. strm.msg = 'invalid window size';
  20345. state.mode = BAD;
  20346. break;
  20347. }
  20348. state.dmax = 1 << len;
  20349. //Tracev((stderr, "inflate: zlib header ok\n"));
  20350. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20351. state.mode = hold & 0x200 ? DICTID : TYPE;
  20352. //=== INITBITS();
  20353. hold = 0;
  20354. bits = 0;
  20355. //===//
  20356. break;
  20357. case FLAGS:
  20358. //=== NEEDBITS(16); */
  20359. while (bits < 16) {
  20360. if (have === 0) { break inf_leave; }
  20361. have--;
  20362. hold += input[next++] << bits;
  20363. bits += 8;
  20364. }
  20365. //===//
  20366. state.flags = hold;
  20367. if ((state.flags & 0xff) !== Z_DEFLATED) {
  20368. strm.msg = 'unknown compression method';
  20369. state.mode = BAD;
  20370. break;
  20371. }
  20372. if (state.flags & 0xe000) {
  20373. strm.msg = 'unknown header flags set';
  20374. state.mode = BAD;
  20375. break;
  20376. }
  20377. if (state.head) {
  20378. state.head.text = ((hold >> 8) & 1);
  20379. }
  20380. if (state.flags & 0x0200) {
  20381. //=== CRC2(state.check, hold);
  20382. hbuf[0] = hold & 0xff;
  20383. hbuf[1] = (hold >>> 8) & 0xff;
  20384. state.check = crc32(state.check, hbuf, 2, 0);
  20385. //===//
  20386. }
  20387. //=== INITBITS();
  20388. hold = 0;
  20389. bits = 0;
  20390. //===//
  20391. state.mode = TIME;
  20392. /* falls through */
  20393. case TIME:
  20394. //=== NEEDBITS(32); */
  20395. while (bits < 32) {
  20396. if (have === 0) { break inf_leave; }
  20397. have--;
  20398. hold += input[next++] << bits;
  20399. bits += 8;
  20400. }
  20401. //===//
  20402. if (state.head) {
  20403. state.head.time = hold;
  20404. }
  20405. if (state.flags & 0x0200) {
  20406. //=== CRC4(state.check, hold)
  20407. hbuf[0] = hold & 0xff;
  20408. hbuf[1] = (hold >>> 8) & 0xff;
  20409. hbuf[2] = (hold >>> 16) & 0xff;
  20410. hbuf[3] = (hold >>> 24) & 0xff;
  20411. state.check = crc32(state.check, hbuf, 4, 0);
  20412. //===
  20413. }
  20414. //=== INITBITS();
  20415. hold = 0;
  20416. bits = 0;
  20417. //===//
  20418. state.mode = OS;
  20419. /* falls through */
  20420. case OS:
  20421. //=== NEEDBITS(16); */
  20422. while (bits < 16) {
  20423. if (have === 0) { break inf_leave; }
  20424. have--;
  20425. hold += input[next++] << bits;
  20426. bits += 8;
  20427. }
  20428. //===//
  20429. if (state.head) {
  20430. state.head.xflags = (hold & 0xff);
  20431. state.head.os = (hold >> 8);
  20432. }
  20433. if (state.flags & 0x0200) {
  20434. //=== CRC2(state.check, hold);
  20435. hbuf[0] = hold & 0xff;
  20436. hbuf[1] = (hold >>> 8) & 0xff;
  20437. state.check = crc32(state.check, hbuf, 2, 0);
  20438. //===//
  20439. }
  20440. //=== INITBITS();
  20441. hold = 0;
  20442. bits = 0;
  20443. //===//
  20444. state.mode = EXLEN;
  20445. /* falls through */
  20446. case EXLEN:
  20447. if (state.flags & 0x0400) {
  20448. //=== NEEDBITS(16); */
  20449. while (bits < 16) {
  20450. if (have === 0) { break inf_leave; }
  20451. have--;
  20452. hold += input[next++] << bits;
  20453. bits += 8;
  20454. }
  20455. //===//
  20456. state.length = hold;
  20457. if (state.head) {
  20458. state.head.extra_len = hold;
  20459. }
  20460. if (state.flags & 0x0200) {
  20461. //=== CRC2(state.check, hold);
  20462. hbuf[0] = hold & 0xff;
  20463. hbuf[1] = (hold >>> 8) & 0xff;
  20464. state.check = crc32(state.check, hbuf, 2, 0);
  20465. //===//
  20466. }
  20467. //=== INITBITS();
  20468. hold = 0;
  20469. bits = 0;
  20470. //===//
  20471. }
  20472. else if (state.head) {
  20473. state.head.extra = null/*Z_NULL*/;
  20474. }
  20475. state.mode = EXTRA;
  20476. /* falls through */
  20477. case EXTRA:
  20478. if (state.flags & 0x0400) {
  20479. copy = state.length;
  20480. if (copy > have) { copy = have; }
  20481. if (copy) {
  20482. if (state.head) {
  20483. len = state.head.extra_len - state.length;
  20484. if (!state.head.extra) {
  20485. // Use untyped array for more conveniend processing later
  20486. state.head.extra = new Array(state.head.extra_len);
  20487. }
  20488. utils.arraySet(
  20489. state.head.extra,
  20490. input,
  20491. next,
  20492. // extra field is limited to 65536 bytes
  20493. // - no need for additional size check
  20494. copy,
  20495. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  20496. len
  20497. );
  20498. //zmemcpy(state.head.extra + len, next,
  20499. // len + copy > state.head.extra_max ?
  20500. // state.head.extra_max - len : copy);
  20501. }
  20502. if (state.flags & 0x0200) {
  20503. state.check = crc32(state.check, input, copy, next);
  20504. }
  20505. have -= copy;
  20506. next += copy;
  20507. state.length -= copy;
  20508. }
  20509. if (state.length) { break inf_leave; }
  20510. }
  20511. state.length = 0;
  20512. state.mode = NAME;
  20513. /* falls through */
  20514. case NAME:
  20515. if (state.flags & 0x0800) {
  20516. if (have === 0) { break inf_leave; }
  20517. copy = 0;
  20518. do {
  20519. // TODO: 2 or 1 bytes?
  20520. len = input[next + copy++];
  20521. /* use constant limit because in js we should not preallocate memory */
  20522. if (state.head && len &&
  20523. (state.length < 65536 /*state.head.name_max*/)) {
  20524. state.head.name += String.fromCharCode(len);
  20525. }
  20526. } while (len && copy < have);
  20527. if (state.flags & 0x0200) {
  20528. state.check = crc32(state.check, input, copy, next);
  20529. }
  20530. have -= copy;
  20531. next += copy;
  20532. if (len) { break inf_leave; }
  20533. }
  20534. else if (state.head) {
  20535. state.head.name = null;
  20536. }
  20537. state.length = 0;
  20538. state.mode = COMMENT;
  20539. /* falls through */
  20540. case COMMENT:
  20541. if (state.flags & 0x1000) {
  20542. if (have === 0) { break inf_leave; }
  20543. copy = 0;
  20544. do {
  20545. len = input[next + copy++];
  20546. /* use constant limit because in js we should not preallocate memory */
  20547. if (state.head && len &&
  20548. (state.length < 65536 /*state.head.comm_max*/)) {
  20549. state.head.comment += String.fromCharCode(len);
  20550. }
  20551. } while (len && copy < have);
  20552. if (state.flags & 0x0200) {
  20553. state.check = crc32(state.check, input, copy, next);
  20554. }
  20555. have -= copy;
  20556. next += copy;
  20557. if (len) { break inf_leave; }
  20558. }
  20559. else if (state.head) {
  20560. state.head.comment = null;
  20561. }
  20562. state.mode = HCRC;
  20563. /* falls through */
  20564. case HCRC:
  20565. if (state.flags & 0x0200) {
  20566. //=== NEEDBITS(16); */
  20567. while (bits < 16) {
  20568. if (have === 0) { break inf_leave; }
  20569. have--;
  20570. hold += input[next++] << bits;
  20571. bits += 8;
  20572. }
  20573. //===//
  20574. if (hold !== (state.check & 0xffff)) {
  20575. strm.msg = 'header crc mismatch';
  20576. state.mode = BAD;
  20577. break;
  20578. }
  20579. //=== INITBITS();
  20580. hold = 0;
  20581. bits = 0;
  20582. //===//
  20583. }
  20584. if (state.head) {
  20585. state.head.hcrc = ((state.flags >> 9) & 1);
  20586. state.head.done = true;
  20587. }
  20588. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  20589. state.mode = TYPE;
  20590. break;
  20591. case DICTID:
  20592. //=== NEEDBITS(32); */
  20593. while (bits < 32) {
  20594. if (have === 0) { break inf_leave; }
  20595. have--;
  20596. hold += input[next++] << bits;
  20597. bits += 8;
  20598. }
  20599. //===//
  20600. strm.adler = state.check = ZSWAP32(hold);
  20601. //=== INITBITS();
  20602. hold = 0;
  20603. bits = 0;
  20604. //===//
  20605. state.mode = DICT;
  20606. /* falls through */
  20607. case DICT:
  20608. if (state.havedict === 0) {
  20609. //--- RESTORE() ---
  20610. strm.next_out = put;
  20611. strm.avail_out = left;
  20612. strm.next_in = next;
  20613. strm.avail_in = have;
  20614. state.hold = hold;
  20615. state.bits = bits;
  20616. //---
  20617. return Z_NEED_DICT;
  20618. }
  20619. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20620. state.mode = TYPE;
  20621. /* falls through */
  20622. case TYPE:
  20623. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  20624. /* falls through */
  20625. case TYPEDO:
  20626. if (state.last) {
  20627. //--- BYTEBITS() ---//
  20628. hold >>>= bits & 7;
  20629. bits -= bits & 7;
  20630. //---//
  20631. state.mode = CHECK;
  20632. break;
  20633. }
  20634. //=== NEEDBITS(3); */
  20635. while (bits < 3) {
  20636. if (have === 0) { break inf_leave; }
  20637. have--;
  20638. hold += input[next++] << bits;
  20639. bits += 8;
  20640. }
  20641. //===//
  20642. state.last = (hold & 0x01)/*BITS(1)*/;
  20643. //--- DROPBITS(1) ---//
  20644. hold >>>= 1;
  20645. bits -= 1;
  20646. //---//
  20647. switch ((hold & 0x03)/*BITS(2)*/) {
  20648. case 0: /* stored block */
  20649. //Tracev((stderr, "inflate: stored block%s\n",
  20650. // state.last ? " (last)" : ""));
  20651. state.mode = STORED;
  20652. break;
  20653. case 1: /* fixed block */
  20654. fixedtables(state);
  20655. //Tracev((stderr, "inflate: fixed codes block%s\n",
  20656. // state.last ? " (last)" : ""));
  20657. state.mode = LEN_; /* decode codes */
  20658. if (flush === Z_TREES) {
  20659. //--- DROPBITS(2) ---//
  20660. hold >>>= 2;
  20661. bits -= 2;
  20662. //---//
  20663. break inf_leave;
  20664. }
  20665. break;
  20666. case 2: /* dynamic block */
  20667. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  20668. // state.last ? " (last)" : ""));
  20669. state.mode = TABLE;
  20670. break;
  20671. case 3:
  20672. strm.msg = 'invalid block type';
  20673. state.mode = BAD;
  20674. }
  20675. //--- DROPBITS(2) ---//
  20676. hold >>>= 2;
  20677. bits -= 2;
  20678. //---//
  20679. break;
  20680. case STORED:
  20681. //--- BYTEBITS() ---// /* go to byte boundary */
  20682. hold >>>= bits & 7;
  20683. bits -= bits & 7;
  20684. //---//
  20685. //=== NEEDBITS(32); */
  20686. while (bits < 32) {
  20687. if (have === 0) { break inf_leave; }
  20688. have--;
  20689. hold += input[next++] << bits;
  20690. bits += 8;
  20691. }
  20692. //===//
  20693. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  20694. strm.msg = 'invalid stored block lengths';
  20695. state.mode = BAD;
  20696. break;
  20697. }
  20698. state.length = hold & 0xffff;
  20699. //Tracev((stderr, "inflate: stored length %u\n",
  20700. // state.length));
  20701. //=== INITBITS();
  20702. hold = 0;
  20703. bits = 0;
  20704. //===//
  20705. state.mode = COPY_;
  20706. if (flush === Z_TREES) { break inf_leave; }
  20707. /* falls through */
  20708. case COPY_:
  20709. state.mode = COPY;
  20710. /* falls through */
  20711. case COPY:
  20712. copy = state.length;
  20713. if (copy) {
  20714. if (copy > have) { copy = have; }
  20715. if (copy > left) { copy = left; }
  20716. if (copy === 0) { break inf_leave; }
  20717. //--- zmemcpy(put, next, copy); ---
  20718. utils.arraySet(output, input, next, copy, put);
  20719. //---//
  20720. have -= copy;
  20721. next += copy;
  20722. left -= copy;
  20723. put += copy;
  20724. state.length -= copy;
  20725. break;
  20726. }
  20727. //Tracev((stderr, "inflate: stored end\n"));
  20728. state.mode = TYPE;
  20729. break;
  20730. case TABLE:
  20731. //=== NEEDBITS(14); */
  20732. while (bits < 14) {
  20733. if (have === 0) { break inf_leave; }
  20734. have--;
  20735. hold += input[next++] << bits;
  20736. bits += 8;
  20737. }
  20738. //===//
  20739. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  20740. //--- DROPBITS(5) ---//
  20741. hold >>>= 5;
  20742. bits -= 5;
  20743. //---//
  20744. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  20745. //--- DROPBITS(5) ---//
  20746. hold >>>= 5;
  20747. bits -= 5;
  20748. //---//
  20749. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  20750. //--- DROPBITS(4) ---//
  20751. hold >>>= 4;
  20752. bits -= 4;
  20753. //---//
  20754. //#ifndef PKZIP_BUG_WORKAROUND
  20755. if (state.nlen > 286 || state.ndist > 30) {
  20756. strm.msg = 'too many length or distance symbols';
  20757. state.mode = BAD;
  20758. break;
  20759. }
  20760. //#endif
  20761. //Tracev((stderr, "inflate: table sizes ok\n"));
  20762. state.have = 0;
  20763. state.mode = LENLENS;
  20764. /* falls through */
  20765. case LENLENS:
  20766. while (state.have < state.ncode) {
  20767. //=== NEEDBITS(3);
  20768. while (bits < 3) {
  20769. if (have === 0) { break inf_leave; }
  20770. have--;
  20771. hold += input[next++] << bits;
  20772. bits += 8;
  20773. }
  20774. //===//
  20775. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  20776. //--- DROPBITS(3) ---//
  20777. hold >>>= 3;
  20778. bits -= 3;
  20779. //---//
  20780. }
  20781. while (state.have < 19) {
  20782. state.lens[order[state.have++]] = 0;
  20783. }
  20784. // We have separate tables & no pointers. 2 commented lines below not needed.
  20785. //state.next = state.codes;
  20786. //state.lencode = state.next;
  20787. // Switch to use dynamic table
  20788. state.lencode = state.lendyn;
  20789. state.lenbits = 7;
  20790. opts = {bits: state.lenbits};
  20791. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  20792. state.lenbits = opts.bits;
  20793. if (ret) {
  20794. strm.msg = 'invalid code lengths set';
  20795. state.mode = BAD;
  20796. break;
  20797. }
  20798. //Tracev((stderr, "inflate: code lengths ok\n"));
  20799. state.have = 0;
  20800. state.mode = CODELENS;
  20801. /* falls through */
  20802. case CODELENS:
  20803. while (state.have < state.nlen + state.ndist) {
  20804. for (;;) {
  20805. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  20806. here_bits = here >>> 24;
  20807. here_op = (here >>> 16) & 0xff;
  20808. here_val = here & 0xffff;
  20809. if ((here_bits) <= bits) { break; }
  20810. //--- PULLBYTE() ---//
  20811. if (have === 0) { break inf_leave; }
  20812. have--;
  20813. hold += input[next++] << bits;
  20814. bits += 8;
  20815. //---//
  20816. }
  20817. if (here_val < 16) {
  20818. //--- DROPBITS(here.bits) ---//
  20819. hold >>>= here_bits;
  20820. bits -= here_bits;
  20821. //---//
  20822. state.lens[state.have++] = here_val;
  20823. }
  20824. else {
  20825. if (here_val === 16) {
  20826. //=== NEEDBITS(here.bits + 2);
  20827. n = here_bits + 2;
  20828. while (bits < n) {
  20829. if (have === 0) { break inf_leave; }
  20830. have--;
  20831. hold += input[next++] << bits;
  20832. bits += 8;
  20833. }
  20834. //===//
  20835. //--- DROPBITS(here.bits) ---//
  20836. hold >>>= here_bits;
  20837. bits -= here_bits;
  20838. //---//
  20839. if (state.have === 0) {
  20840. strm.msg = 'invalid bit length repeat';
  20841. state.mode = BAD;
  20842. break;
  20843. }
  20844. len = state.lens[state.have - 1];
  20845. copy = 3 + (hold & 0x03);//BITS(2);
  20846. //--- DROPBITS(2) ---//
  20847. hold >>>= 2;
  20848. bits -= 2;
  20849. //---//
  20850. }
  20851. else if (here_val === 17) {
  20852. //=== NEEDBITS(here.bits + 3);
  20853. n = here_bits + 3;
  20854. while (bits < n) {
  20855. if (have === 0) { break inf_leave; }
  20856. have--;
  20857. hold += input[next++] << bits;
  20858. bits += 8;
  20859. }
  20860. //===//
  20861. //--- DROPBITS(here.bits) ---//
  20862. hold >>>= here_bits;
  20863. bits -= here_bits;
  20864. //---//
  20865. len = 0;
  20866. copy = 3 + (hold & 0x07);//BITS(3);
  20867. //--- DROPBITS(3) ---//
  20868. hold >>>= 3;
  20869. bits -= 3;
  20870. //---//
  20871. }
  20872. else {
  20873. //=== NEEDBITS(here.bits + 7);
  20874. n = here_bits + 7;
  20875. while (bits < n) {
  20876. if (have === 0) { break inf_leave; }
  20877. have--;
  20878. hold += input[next++] << bits;
  20879. bits += 8;
  20880. }
  20881. //===//
  20882. //--- DROPBITS(here.bits) ---//
  20883. hold >>>= here_bits;
  20884. bits -= here_bits;
  20885. //---//
  20886. len = 0;
  20887. copy = 11 + (hold & 0x7f);//BITS(7);
  20888. //--- DROPBITS(7) ---//
  20889. hold >>>= 7;
  20890. bits -= 7;
  20891. //---//
  20892. }
  20893. if (state.have + copy > state.nlen + state.ndist) {
  20894. strm.msg = 'invalid bit length repeat';
  20895. state.mode = BAD;
  20896. break;
  20897. }
  20898. while (copy--) {
  20899. state.lens[state.have++] = len;
  20900. }
  20901. }
  20902. }
  20903. /* handle error breaks in while */
  20904. if (state.mode === BAD) { break; }
  20905. /* check for end-of-block code (better have one) */
  20906. if (state.lens[256] === 0) {
  20907. strm.msg = 'invalid code -- missing end-of-block';
  20908. state.mode = BAD;
  20909. break;
  20910. }
  20911. /* build code tables -- note: do not change the lenbits or distbits
  20912. values here (9 and 6) without reading the comments in inftrees.h
  20913. concerning the ENOUGH constants, which depend on those values */
  20914. state.lenbits = 9;
  20915. opts = {bits: state.lenbits};
  20916. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  20917. // We have separate tables & no pointers. 2 commented lines below not needed.
  20918. // state.next_index = opts.table_index;
  20919. state.lenbits = opts.bits;
  20920. // state.lencode = state.next;
  20921. if (ret) {
  20922. strm.msg = 'invalid literal/lengths set';
  20923. state.mode = BAD;
  20924. break;
  20925. }
  20926. state.distbits = 6;
  20927. //state.distcode.copy(state.codes);
  20928. // Switch to use dynamic table
  20929. state.distcode = state.distdyn;
  20930. opts = {bits: state.distbits};
  20931. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  20932. // We have separate tables & no pointers. 2 commented lines below not needed.
  20933. // state.next_index = opts.table_index;
  20934. state.distbits = opts.bits;
  20935. // state.distcode = state.next;
  20936. if (ret) {
  20937. strm.msg = 'invalid distances set';
  20938. state.mode = BAD;
  20939. break;
  20940. }
  20941. //Tracev((stderr, 'inflate: codes ok\n'));
  20942. state.mode = LEN_;
  20943. if (flush === Z_TREES) { break inf_leave; }
  20944. /* falls through */
  20945. case LEN_:
  20946. state.mode = LEN;
  20947. /* falls through */
  20948. case LEN:
  20949. if (have >= 6 && left >= 258) {
  20950. //--- RESTORE() ---
  20951. strm.next_out = put;
  20952. strm.avail_out = left;
  20953. strm.next_in = next;
  20954. strm.avail_in = have;
  20955. state.hold = hold;
  20956. state.bits = bits;
  20957. //---
  20958. inflate_fast(strm, _out);
  20959. //--- LOAD() ---
  20960. put = strm.next_out;
  20961. output = strm.output;
  20962. left = strm.avail_out;
  20963. next = strm.next_in;
  20964. input = strm.input;
  20965. have = strm.avail_in;
  20966. hold = state.hold;
  20967. bits = state.bits;
  20968. //---
  20969. if (state.mode === TYPE) {
  20970. state.back = -1;
  20971. }
  20972. break;
  20973. }
  20974. state.back = 0;
  20975. for (;;) {
  20976. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  20977. here_bits = here >>> 24;
  20978. here_op = (here >>> 16) & 0xff;
  20979. here_val = here & 0xffff;
  20980. if (here_bits <= bits) { break; }
  20981. //--- PULLBYTE() ---//
  20982. if (have === 0) { break inf_leave; }
  20983. have--;
  20984. hold += input[next++] << bits;
  20985. bits += 8;
  20986. //---//
  20987. }
  20988. if (here_op && (here_op & 0xf0) === 0) {
  20989. last_bits = here_bits;
  20990. last_op = here_op;
  20991. last_val = here_val;
  20992. for (;;) {
  20993. here = state.lencode[last_val +
  20994. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20995. here_bits = here >>> 24;
  20996. here_op = (here >>> 16) & 0xff;
  20997. here_val = here & 0xffff;
  20998. if ((last_bits + here_bits) <= bits) { break; }
  20999. //--- PULLBYTE() ---//
  21000. if (have === 0) { break inf_leave; }
  21001. have--;
  21002. hold += input[next++] << bits;
  21003. bits += 8;
  21004. //---//
  21005. }
  21006. //--- DROPBITS(last.bits) ---//
  21007. hold >>>= last_bits;
  21008. bits -= last_bits;
  21009. //---//
  21010. state.back += last_bits;
  21011. }
  21012. //--- DROPBITS(here.bits) ---//
  21013. hold >>>= here_bits;
  21014. bits -= here_bits;
  21015. //---//
  21016. state.back += here_bits;
  21017. state.length = here_val;
  21018. if (here_op === 0) {
  21019. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  21020. // "inflate: literal '%c'\n" :
  21021. // "inflate: literal 0x%02x\n", here.val));
  21022. state.mode = LIT;
  21023. break;
  21024. }
  21025. if (here_op & 32) {
  21026. //Tracevv((stderr, "inflate: end of block\n"));
  21027. state.back = -1;
  21028. state.mode = TYPE;
  21029. break;
  21030. }
  21031. if (here_op & 64) {
  21032. strm.msg = 'invalid literal/length code';
  21033. state.mode = BAD;
  21034. break;
  21035. }
  21036. state.extra = here_op & 15;
  21037. state.mode = LENEXT;
  21038. /* falls through */
  21039. case LENEXT:
  21040. if (state.extra) {
  21041. //=== NEEDBITS(state.extra);
  21042. n = state.extra;
  21043. while (bits < n) {
  21044. if (have === 0) { break inf_leave; }
  21045. have--;
  21046. hold += input[next++] << bits;
  21047. bits += 8;
  21048. }
  21049. //===//
  21050. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  21051. //--- DROPBITS(state.extra) ---//
  21052. hold >>>= state.extra;
  21053. bits -= state.extra;
  21054. //---//
  21055. state.back += state.extra;
  21056. }
  21057. //Tracevv((stderr, "inflate: length %u\n", state.length));
  21058. state.was = state.length;
  21059. state.mode = DIST;
  21060. /* falls through */
  21061. case DIST:
  21062. for (;;) {
  21063. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  21064. here_bits = here >>> 24;
  21065. here_op = (here >>> 16) & 0xff;
  21066. here_val = here & 0xffff;
  21067. if ((here_bits) <= bits) { break; }
  21068. //--- PULLBYTE() ---//
  21069. if (have === 0) { break inf_leave; }
  21070. have--;
  21071. hold += input[next++] << bits;
  21072. bits += 8;
  21073. //---//
  21074. }
  21075. if ((here_op & 0xf0) === 0) {
  21076. last_bits = here_bits;
  21077. last_op = here_op;
  21078. last_val = here_val;
  21079. for (;;) {
  21080. here = state.distcode[last_val +
  21081. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  21082. here_bits = here >>> 24;
  21083. here_op = (here >>> 16) & 0xff;
  21084. here_val = here & 0xffff;
  21085. if ((last_bits + here_bits) <= bits) { break; }
  21086. //--- PULLBYTE() ---//
  21087. if (have === 0) { break inf_leave; }
  21088. have--;
  21089. hold += input[next++] << bits;
  21090. bits += 8;
  21091. //---//
  21092. }
  21093. //--- DROPBITS(last.bits) ---//
  21094. hold >>>= last_bits;
  21095. bits -= last_bits;
  21096. //---//
  21097. state.back += last_bits;
  21098. }
  21099. //--- DROPBITS(here.bits) ---//
  21100. hold >>>= here_bits;
  21101. bits -= here_bits;
  21102. //---//
  21103. state.back += here_bits;
  21104. if (here_op & 64) {
  21105. strm.msg = 'invalid distance code';
  21106. state.mode = BAD;
  21107. break;
  21108. }
  21109. state.offset = here_val;
  21110. state.extra = (here_op) & 15;
  21111. state.mode = DISTEXT;
  21112. /* falls through */
  21113. case DISTEXT:
  21114. if (state.extra) {
  21115. //=== NEEDBITS(state.extra);
  21116. n = state.extra;
  21117. while (bits < n) {
  21118. if (have === 0) { break inf_leave; }
  21119. have--;
  21120. hold += input[next++] << bits;
  21121. bits += 8;
  21122. }
  21123. //===//
  21124. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  21125. //--- DROPBITS(state.extra) ---//
  21126. hold >>>= state.extra;
  21127. bits -= state.extra;
  21128. //---//
  21129. state.back += state.extra;
  21130. }
  21131. //#ifdef INFLATE_STRICT
  21132. if (state.offset > state.dmax) {
  21133. strm.msg = 'invalid distance too far back';
  21134. state.mode = BAD;
  21135. break;
  21136. }
  21137. //#endif
  21138. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  21139. state.mode = MATCH;
  21140. /* falls through */
  21141. case MATCH:
  21142. if (left === 0) { break inf_leave; }
  21143. copy = _out - left;
  21144. if (state.offset > copy) { /* copy from window */
  21145. copy = state.offset - copy;
  21146. if (copy > state.whave) {
  21147. if (state.sane) {
  21148. strm.msg = 'invalid distance too far back';
  21149. state.mode = BAD;
  21150. break;
  21151. }
  21152. // (!) This block is disabled in zlib defailts,
  21153. // don't enable it for binary compatibility
  21154. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  21155. // Trace((stderr, "inflate.c too far\n"));
  21156. // copy -= state.whave;
  21157. // if (copy > state.length) { copy = state.length; }
  21158. // if (copy > left) { copy = left; }
  21159. // left -= copy;
  21160. // state.length -= copy;
  21161. // do {
  21162. // output[put++] = 0;
  21163. // } while (--copy);
  21164. // if (state.length === 0) { state.mode = LEN; }
  21165. // break;
  21166. //#endif
  21167. }
  21168. if (copy > state.wnext) {
  21169. copy -= state.wnext;
  21170. from = state.wsize - copy;
  21171. }
  21172. else {
  21173. from = state.wnext - copy;
  21174. }
  21175. if (copy > state.length) { copy = state.length; }
  21176. from_source = state.window;
  21177. }
  21178. else { /* copy from output */
  21179. from_source = output;
  21180. from = put - state.offset;
  21181. copy = state.length;
  21182. }
  21183. if (copy > left) { copy = left; }
  21184. left -= copy;
  21185. state.length -= copy;
  21186. do {
  21187. output[put++] = from_source[from++];
  21188. } while (--copy);
  21189. if (state.length === 0) { state.mode = LEN; }
  21190. break;
  21191. case LIT:
  21192. if (left === 0) { break inf_leave; }
  21193. output[put++] = state.length;
  21194. left--;
  21195. state.mode = LEN;
  21196. break;
  21197. case CHECK:
  21198. if (state.wrap) {
  21199. //=== NEEDBITS(32);
  21200. while (bits < 32) {
  21201. if (have === 0) { break inf_leave; }
  21202. have--;
  21203. // Use '|' insdead of '+' to make sure that result is signed
  21204. hold |= input[next++] << bits;
  21205. bits += 8;
  21206. }
  21207. //===//
  21208. _out -= left;
  21209. strm.total_out += _out;
  21210. state.total += _out;
  21211. if (_out) {
  21212. strm.adler = state.check =
  21213. /*UPDATE(state.check, put - _out, _out);*/
  21214. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  21215. }
  21216. _out = left;
  21217. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  21218. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  21219. strm.msg = 'incorrect data check';
  21220. state.mode = BAD;
  21221. break;
  21222. }
  21223. //=== INITBITS();
  21224. hold = 0;
  21225. bits = 0;
  21226. //===//
  21227. //Tracev((stderr, "inflate: check matches trailer\n"));
  21228. }
  21229. state.mode = LENGTH;
  21230. /* falls through */
  21231. case LENGTH:
  21232. if (state.wrap && state.flags) {
  21233. //=== NEEDBITS(32);
  21234. while (bits < 32) {
  21235. if (have === 0) { break inf_leave; }
  21236. have--;
  21237. hold += input[next++] << bits;
  21238. bits += 8;
  21239. }
  21240. //===//
  21241. if (hold !== (state.total & 0xffffffff)) {
  21242. strm.msg = 'incorrect length check';
  21243. state.mode = BAD;
  21244. break;
  21245. }
  21246. //=== INITBITS();
  21247. hold = 0;
  21248. bits = 0;
  21249. //===//
  21250. //Tracev((stderr, "inflate: length matches trailer\n"));
  21251. }
  21252. state.mode = DONE;
  21253. /* falls through */
  21254. case DONE:
  21255. ret = Z_STREAM_END;
  21256. break inf_leave;
  21257. case BAD:
  21258. ret = Z_DATA_ERROR;
  21259. break inf_leave;
  21260. case MEM:
  21261. return Z_MEM_ERROR;
  21262. case SYNC:
  21263. /* falls through */
  21264. default:
  21265. return Z_STREAM_ERROR;
  21266. }
  21267. }
  21268. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  21269. /*
  21270. Return from inflate(), updating the total counts and the check value.
  21271. If there was no progress during the inflate() call, return a buffer
  21272. error. Call updatewindow() to create and/or update the window state.
  21273. Note: a memory error from inflate() is non-recoverable.
  21274. */
  21275. //--- RESTORE() ---
  21276. strm.next_out = put;
  21277. strm.avail_out = left;
  21278. strm.next_in = next;
  21279. strm.avail_in = have;
  21280. state.hold = hold;
  21281. state.bits = bits;
  21282. //---
  21283. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  21284. (state.mode < CHECK || flush !== Z_FINISH))) {
  21285. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  21286. state.mode = MEM;
  21287. return Z_MEM_ERROR;
  21288. }
  21289. }
  21290. _in -= strm.avail_in;
  21291. _out -= strm.avail_out;
  21292. strm.total_in += _in;
  21293. strm.total_out += _out;
  21294. state.total += _out;
  21295. if (state.wrap && _out) {
  21296. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  21297. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  21298. }
  21299. strm.data_type = state.bits + (state.last ? 64 : 0) +
  21300. (state.mode === TYPE ? 128 : 0) +
  21301. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  21302. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  21303. ret = Z_BUF_ERROR;
  21304. }
  21305. return ret;
  21306. }
  21307. function inflateEnd(strm) {
  21308. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  21309. return Z_STREAM_ERROR;
  21310. }
  21311. var state = strm.state;
  21312. if (state.window) {
  21313. state.window = null;
  21314. }
  21315. strm.state = null;
  21316. return Z_OK;
  21317. }
  21318. function inflateGetHeader(strm, head) {
  21319. var state;
  21320. /* check state */
  21321. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21322. state = strm.state;
  21323. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  21324. /* save header structure */
  21325. state.head = head;
  21326. head.done = false;
  21327. return Z_OK;
  21328. }
  21329. exports.inflateReset = inflateReset;
  21330. exports.inflateReset2 = inflateReset2;
  21331. exports.inflateResetKeep = inflateResetKeep;
  21332. exports.inflateInit = inflateInit;
  21333. exports.inflateInit2 = inflateInit2;
  21334. exports.inflate = inflate;
  21335. exports.inflateEnd = inflateEnd;
  21336. exports.inflateGetHeader = inflateGetHeader;
  21337. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  21338. /* Not implemented
  21339. exports.inflateCopy = inflateCopy;
  21340. exports.inflateGetDictionary = inflateGetDictionary;
  21341. exports.inflateMark = inflateMark;
  21342. exports.inflatePrime = inflatePrime;
  21343. exports.inflateSetDictionary = inflateSetDictionary;
  21344. exports.inflateSync = inflateSync;
  21345. exports.inflateSyncPoint = inflateSyncPoint;
  21346. exports.inflateUndermine = inflateUndermine;
  21347. */
  21348. },{"../utils/common":66,"./adler32":68,"./crc32":70,"./inffast":73,"./inftrees":75}],75:[function(require,module,exports){
  21349. 'use strict';
  21350. var utils = require('../utils/common');
  21351. var MAXBITS = 15;
  21352. var ENOUGH_LENS = 852;
  21353. var ENOUGH_DISTS = 592;
  21354. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  21355. var CODES = 0;
  21356. var LENS = 1;
  21357. var DISTS = 2;
  21358. var lbase = [ /* Length codes 257..285 base */
  21359. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  21360. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  21361. ];
  21362. var lext = [ /* Length codes 257..285 extra */
  21363. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  21364. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  21365. ];
  21366. var dbase = [ /* Distance codes 0..29 base */
  21367. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  21368. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  21369. 8193, 12289, 16385, 24577, 0, 0
  21370. ];
  21371. var dext = [ /* Distance codes 0..29 extra */
  21372. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  21373. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  21374. 28, 28, 29, 29, 64, 64
  21375. ];
  21376. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  21377. {
  21378. var bits = opts.bits;
  21379. //here = opts.here; /* table entry for duplication */
  21380. var len = 0; /* a code's length in bits */
  21381. var sym = 0; /* index of code symbols */
  21382. var min = 0, max = 0; /* minimum and maximum code lengths */
  21383. var root = 0; /* number of index bits for root table */
  21384. var curr = 0; /* number of index bits for current table */
  21385. var drop = 0; /* code bits to drop for sub-table */
  21386. var left = 0; /* number of prefix codes available */
  21387. var used = 0; /* code entries in table used */
  21388. var huff = 0; /* Huffman code */
  21389. var incr; /* for incrementing code, index */
  21390. var fill; /* index for replicating entries */
  21391. var low; /* low bits for current root entry */
  21392. var mask; /* mask for low root bits */
  21393. var next; /* next available space in table */
  21394. var base = null; /* base value table to use */
  21395. var base_index = 0;
  21396. // var shoextra; /* extra bits table to use */
  21397. var end; /* use base and extra for symbol > end */
  21398. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  21399. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  21400. var extra = null;
  21401. var extra_index = 0;
  21402. var here_bits, here_op, here_val;
  21403. /*
  21404. Process a set of code lengths to create a canonical Huffman code. The
  21405. code lengths are lens[0..codes-1]. Each length corresponds to the
  21406. symbols 0..codes-1. The Huffman code is generated by first sorting the
  21407. symbols by length from short to long, and retaining the symbol order
  21408. for codes with equal lengths. Then the code starts with all zero bits
  21409. for the first code of the shortest length, and the codes are integer
  21410. increments for the same length, and zeros are appended as the length
  21411. increases. For the deflate format, these bits are stored backwards
  21412. from their more natural integer increment ordering, and so when the
  21413. decoding tables are built in the large loop below, the integer codes
  21414. are incremented backwards.
  21415. This routine assumes, but does not check, that all of the entries in
  21416. lens[] are in the range 0..MAXBITS. The caller must assure this.
  21417. 1..MAXBITS is interpreted as that code length. zero means that that
  21418. symbol does not occur in this code.
  21419. The codes are sorted by computing a count of codes for each length,
  21420. creating from that a table of starting indices for each length in the
  21421. sorted table, and then entering the symbols in order in the sorted
  21422. table. The sorted table is work[], with that space being provided by
  21423. the caller.
  21424. The length counts are used for other purposes as well, i.e. finding
  21425. the minimum and maximum length codes, determining if there are any
  21426. codes at all, checking for a valid set of lengths, and looking ahead
  21427. at length counts to determine sub-table sizes when building the
  21428. decoding tables.
  21429. */
  21430. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  21431. for (len = 0; len <= MAXBITS; len++) {
  21432. count[len] = 0;
  21433. }
  21434. for (sym = 0; sym < codes; sym++) {
  21435. count[lens[lens_index + sym]]++;
  21436. }
  21437. /* bound code lengths, force root to be within code lengths */
  21438. root = bits;
  21439. for (max = MAXBITS; max >= 1; max--) {
  21440. if (count[max] !== 0) { break; }
  21441. }
  21442. if (root > max) {
  21443. root = max;
  21444. }
  21445. if (max === 0) { /* no symbols to code at all */
  21446. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  21447. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  21448. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  21449. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21450. //table.op[opts.table_index] = 64;
  21451. //table.bits[opts.table_index] = 1;
  21452. //table.val[opts.table_index++] = 0;
  21453. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21454. opts.bits = 1;
  21455. return 0; /* no symbols, but wait for decoding to report error */
  21456. }
  21457. for (min = 1; min < max; min++) {
  21458. if (count[min] !== 0) { break; }
  21459. }
  21460. if (root < min) {
  21461. root = min;
  21462. }
  21463. /* check for an over-subscribed or incomplete set of lengths */
  21464. left = 1;
  21465. for (len = 1; len <= MAXBITS; len++) {
  21466. left <<= 1;
  21467. left -= count[len];
  21468. if (left < 0) {
  21469. return -1;
  21470. } /* over-subscribed */
  21471. }
  21472. if (left > 0 && (type === CODES || max !== 1)) {
  21473. return -1; /* incomplete set */
  21474. }
  21475. /* generate offsets into symbol table for each length for sorting */
  21476. offs[1] = 0;
  21477. for (len = 1; len < MAXBITS; len++) {
  21478. offs[len + 1] = offs[len] + count[len];
  21479. }
  21480. /* sort symbols by length, by symbol order within each length */
  21481. for (sym = 0; sym < codes; sym++) {
  21482. if (lens[lens_index + sym] !== 0) {
  21483. work[offs[lens[lens_index + sym]]++] = sym;
  21484. }
  21485. }
  21486. /*
  21487. Create and fill in decoding tables. In this loop, the table being
  21488. filled is at next and has curr index bits. The code being used is huff
  21489. with length len. That code is converted to an index by dropping drop
  21490. bits off of the bottom. For codes where len is less than drop + curr,
  21491. those top drop + curr - len bits are incremented through all values to
  21492. fill the table with replicated entries.
  21493. root is the number of index bits for the root table. When len exceeds
  21494. root, sub-tables are created pointed to by the root entry with an index
  21495. of the low root bits of huff. This is saved in low to check for when a
  21496. new sub-table should be started. drop is zero when the root table is
  21497. being filled, and drop is root when sub-tables are being filled.
  21498. When a new sub-table is needed, it is necessary to look ahead in the
  21499. code lengths to determine what size sub-table is needed. The length
  21500. counts are used for this, and so count[] is decremented as codes are
  21501. entered in the tables.
  21502. used keeps track of how many table entries have been allocated from the
  21503. provided *table space. It is checked for LENS and DIST tables against
  21504. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  21505. the initial root table size constants. See the comments in inftrees.h
  21506. for more information.
  21507. sym increments through all symbols, and the loop terminates when
  21508. all codes of length max, i.e. all codes, have been processed. This
  21509. routine permits incomplete codes, so another loop after this one fills
  21510. in the rest of the decoding tables with invalid code markers.
  21511. */
  21512. /* set up for code type */
  21513. // poor man optimization - use if-else instead of switch,
  21514. // to avoid deopts in old v8
  21515. if (type === CODES) {
  21516. base = extra = work; /* dummy value--not used */
  21517. end = 19;
  21518. } else if (type === LENS) {
  21519. base = lbase;
  21520. base_index -= 257;
  21521. extra = lext;
  21522. extra_index -= 257;
  21523. end = 256;
  21524. } else { /* DISTS */
  21525. base = dbase;
  21526. extra = dext;
  21527. end = -1;
  21528. }
  21529. /* initialize opts for loop */
  21530. huff = 0; /* starting code */
  21531. sym = 0; /* starting code symbol */
  21532. len = min; /* starting code length */
  21533. next = table_index; /* current table to fill in */
  21534. curr = root; /* current table index bits */
  21535. drop = 0; /* current bits to drop from code for index */
  21536. low = -1; /* trigger new sub-table when len > root */
  21537. used = 1 << root; /* use root table entries */
  21538. mask = used - 1; /* mask for comparing low */
  21539. /* check available table space */
  21540. if ((type === LENS && used > ENOUGH_LENS) ||
  21541. (type === DISTS && used > ENOUGH_DISTS)) {
  21542. return 1;
  21543. }
  21544. var i=0;
  21545. /* process all codes and make table entries */
  21546. for (;;) {
  21547. i++;
  21548. /* create table entry */
  21549. here_bits = len - drop;
  21550. if (work[sym] < end) {
  21551. here_op = 0;
  21552. here_val = work[sym];
  21553. }
  21554. else if (work[sym] > end) {
  21555. here_op = extra[extra_index + work[sym]];
  21556. here_val = base[base_index + work[sym]];
  21557. }
  21558. else {
  21559. here_op = 32 + 64; /* end of block */
  21560. here_val = 0;
  21561. }
  21562. /* replicate for those indices with low len bits equal to huff */
  21563. incr = 1 << (len - drop);
  21564. fill = 1 << curr;
  21565. min = fill; /* save offset to next table */
  21566. do {
  21567. fill -= incr;
  21568. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  21569. } while (fill !== 0);
  21570. /* backwards increment the len-bit code huff */
  21571. incr = 1 << (len - 1);
  21572. while (huff & incr) {
  21573. incr >>= 1;
  21574. }
  21575. if (incr !== 0) {
  21576. huff &= incr - 1;
  21577. huff += incr;
  21578. } else {
  21579. huff = 0;
  21580. }
  21581. /* go to next symbol, update count, len */
  21582. sym++;
  21583. if (--count[len] === 0) {
  21584. if (len === max) { break; }
  21585. len = lens[lens_index + work[sym]];
  21586. }
  21587. /* create new sub-table if needed */
  21588. if (len > root && (huff & mask) !== low) {
  21589. /* if first time, transition to sub-tables */
  21590. if (drop === 0) {
  21591. drop = root;
  21592. }
  21593. /* increment past last table */
  21594. next += min; /* here min is 1 << curr */
  21595. /* determine length of next table */
  21596. curr = len - drop;
  21597. left = 1 << curr;
  21598. while (curr + drop < max) {
  21599. left -= count[curr + drop];
  21600. if (left <= 0) { break; }
  21601. curr++;
  21602. left <<= 1;
  21603. }
  21604. /* check for enough space */
  21605. used += 1 << curr;
  21606. if ((type === LENS && used > ENOUGH_LENS) ||
  21607. (type === DISTS && used > ENOUGH_DISTS)) {
  21608. return 1;
  21609. }
  21610. /* point entry in root table to sub-table */
  21611. low = huff & mask;
  21612. /*table.op[low] = curr;
  21613. table.bits[low] = root;
  21614. table.val[low] = next - opts.table_index;*/
  21615. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  21616. }
  21617. }
  21618. /* fill in remaining table entry if code is incomplete (guaranteed to have
  21619. at most one remaining entry, since if the code is incomplete, the
  21620. maximum code length that was allowed to get this far is one bit) */
  21621. if (huff !== 0) {
  21622. //table.op[next + huff] = 64; /* invalid code marker */
  21623. //table.bits[next + huff] = len - drop;
  21624. //table.val[next + huff] = 0;
  21625. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  21626. }
  21627. /* set return parameters */
  21628. //opts.table_index += used;
  21629. opts.bits = root;
  21630. return 0;
  21631. };
  21632. },{"../utils/common":66}],76:[function(require,module,exports){
  21633. 'use strict';
  21634. module.exports = {
  21635. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  21636. '1': 'stream end', /* Z_STREAM_END 1 */
  21637. '0': '', /* Z_OK 0 */
  21638. '-1': 'file error', /* Z_ERRNO (-1) */
  21639. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  21640. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  21641. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  21642. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  21643. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  21644. };
  21645. },{}],77:[function(require,module,exports){
  21646. 'use strict';
  21647. var utils = require('../utils/common');
  21648. /* Public constants ==========================================================*/
  21649. /* ===========================================================================*/
  21650. //var Z_FILTERED = 1;
  21651. //var Z_HUFFMAN_ONLY = 2;
  21652. //var Z_RLE = 3;
  21653. var Z_FIXED = 4;
  21654. //var Z_DEFAULT_STRATEGY = 0;
  21655. /* Possible values of the data_type field (though see inflate()) */
  21656. var Z_BINARY = 0;
  21657. var Z_TEXT = 1;
  21658. //var Z_ASCII = 1; // = Z_TEXT
  21659. var Z_UNKNOWN = 2;
  21660. /*============================================================================*/
  21661. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  21662. // From zutil.h
  21663. var STORED_BLOCK = 0;
  21664. var STATIC_TREES = 1;
  21665. var DYN_TREES = 2;
  21666. /* The three kinds of block type */
  21667. var MIN_MATCH = 3;
  21668. var MAX_MATCH = 258;
  21669. /* The minimum and maximum match lengths */
  21670. // From deflate.h
  21671. /* ===========================================================================
  21672. * Internal compression state.
  21673. */
  21674. var LENGTH_CODES = 29;
  21675. /* number of length codes, not counting the special END_BLOCK code */
  21676. var LITERALS = 256;
  21677. /* number of literal bytes 0..255 */
  21678. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  21679. /* number of Literal or Length codes, including the END_BLOCK code */
  21680. var D_CODES = 30;
  21681. /* number of distance codes */
  21682. var BL_CODES = 19;
  21683. /* number of codes used to transfer the bit lengths */
  21684. var HEAP_SIZE = 2*L_CODES + 1;
  21685. /* maximum heap size */
  21686. var MAX_BITS = 15;
  21687. /* All codes must not exceed MAX_BITS bits */
  21688. var Buf_size = 16;
  21689. /* size of bit buffer in bi_buf */
  21690. /* ===========================================================================
  21691. * Constants
  21692. */
  21693. var MAX_BL_BITS = 7;
  21694. /* Bit length codes must not exceed MAX_BL_BITS bits */
  21695. var END_BLOCK = 256;
  21696. /* end of block literal code */
  21697. var REP_3_6 = 16;
  21698. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  21699. var REPZ_3_10 = 17;
  21700. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  21701. var REPZ_11_138 = 18;
  21702. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  21703. var extra_lbits = /* extra bits for each length code */
  21704. [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];
  21705. var extra_dbits = /* extra bits for each distance code */
  21706. [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];
  21707. var extra_blbits = /* extra bits for each bit length code */
  21708. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  21709. var bl_order =
  21710. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  21711. /* The lengths of the bit length codes are sent in order of decreasing
  21712. * probability, to avoid transmitting the lengths for unused bit length codes.
  21713. */
  21714. /* ===========================================================================
  21715. * Local data. These are initialized only once.
  21716. */
  21717. // We pre-fill arrays with 0 to avoid uninitialized gaps
  21718. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  21719. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  21720. var static_ltree = new Array((L_CODES+2) * 2);
  21721. zero(static_ltree);
  21722. /* The static literal tree. Since the bit lengths are imposed, there is no
  21723. * need for the L_CODES extra codes used during heap construction. However
  21724. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  21725. * below).
  21726. */
  21727. var static_dtree = new Array(D_CODES * 2);
  21728. zero(static_dtree);
  21729. /* The static distance tree. (Actually a trivial tree since all codes use
  21730. * 5 bits.)
  21731. */
  21732. var _dist_code = new Array(DIST_CODE_LEN);
  21733. zero(_dist_code);
  21734. /* Distance codes. The first 256 values correspond to the distances
  21735. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  21736. * the 15 bit distances.
  21737. */
  21738. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  21739. zero(_length_code);
  21740. /* length code for each normalized match length (0 == MIN_MATCH) */
  21741. var base_length = new Array(LENGTH_CODES);
  21742. zero(base_length);
  21743. /* First normalized length for each code (0 = MIN_MATCH) */
  21744. var base_dist = new Array(D_CODES);
  21745. zero(base_dist);
  21746. /* First normalized distance for each code (0 = distance of 1) */
  21747. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  21748. this.static_tree = static_tree; /* static tree or NULL */
  21749. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  21750. this.extra_base = extra_base; /* base index for extra_bits */
  21751. this.elems = elems; /* max number of elements in the tree */
  21752. this.max_length = max_length; /* max bit length for the codes */
  21753. // show if `static_tree` has data or dummy - needed for monomorphic objects
  21754. this.has_stree = static_tree && static_tree.length;
  21755. };
  21756. var static_l_desc;
  21757. var static_d_desc;
  21758. var static_bl_desc;
  21759. var TreeDesc = function(dyn_tree, stat_desc) {
  21760. this.dyn_tree = dyn_tree; /* the dynamic tree */
  21761. this.max_code = 0; /* largest code with non zero frequency */
  21762. this.stat_desc = stat_desc; /* the corresponding static tree */
  21763. };
  21764. function d_code(dist) {
  21765. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  21766. }
  21767. /* ===========================================================================
  21768. * Output a short LSB first on the stream.
  21769. * IN assertion: there is enough room in pendingBuf.
  21770. */
  21771. function put_short (s, w) {
  21772. // put_byte(s, (uch)((w) & 0xff));
  21773. // put_byte(s, (uch)((ush)(w) >> 8));
  21774. s.pending_buf[s.pending++] = (w) & 0xff;
  21775. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  21776. }
  21777. /* ===========================================================================
  21778. * Send a value on a given number of bits.
  21779. * IN assertion: length <= 16 and value fits in length bits.
  21780. */
  21781. function send_bits(s, value, length) {
  21782. if (s.bi_valid > (Buf_size - length)) {
  21783. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21784. put_short(s, s.bi_buf);
  21785. s.bi_buf = value >> (Buf_size - s.bi_valid);
  21786. s.bi_valid += length - Buf_size;
  21787. } else {
  21788. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21789. s.bi_valid += length;
  21790. }
  21791. }
  21792. function send_code(s, c, tree) {
  21793. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  21794. }
  21795. /* ===========================================================================
  21796. * Reverse the first len bits of a code, using straightforward code (a faster
  21797. * method would use a table)
  21798. * IN assertion: 1 <= len <= 15
  21799. */
  21800. function bi_reverse(code, len) {
  21801. var res = 0;
  21802. do {
  21803. res |= code & 1;
  21804. code >>>= 1;
  21805. res <<= 1;
  21806. } while (--len > 0);
  21807. return res >>> 1;
  21808. }
  21809. /* ===========================================================================
  21810. * Flush the bit buffer, keeping at most 7 bits in it.
  21811. */
  21812. function bi_flush(s) {
  21813. if (s.bi_valid === 16) {
  21814. put_short(s, s.bi_buf);
  21815. s.bi_buf = 0;
  21816. s.bi_valid = 0;
  21817. } else if (s.bi_valid >= 8) {
  21818. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  21819. s.bi_buf >>= 8;
  21820. s.bi_valid -= 8;
  21821. }
  21822. }
  21823. /* ===========================================================================
  21824. * Compute the optimal bit lengths for a tree and update the total bit length
  21825. * for the current block.
  21826. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  21827. * above are the tree nodes sorted by increasing frequency.
  21828. * OUT assertions: the field len is set to the optimal bit length, the
  21829. * array bl_count contains the frequencies for each bit length.
  21830. * The length opt_len is updated; static_len is also updated if stree is
  21831. * not null.
  21832. */
  21833. function gen_bitlen(s, desc)
  21834. // deflate_state *s;
  21835. // tree_desc *desc; /* the tree descriptor */
  21836. {
  21837. var tree = desc.dyn_tree;
  21838. var max_code = desc.max_code;
  21839. var stree = desc.stat_desc.static_tree;
  21840. var has_stree = desc.stat_desc.has_stree;
  21841. var extra = desc.stat_desc.extra_bits;
  21842. var base = desc.stat_desc.extra_base;
  21843. var max_length = desc.stat_desc.max_length;
  21844. var h; /* heap index */
  21845. var n, m; /* iterate over the tree elements */
  21846. var bits; /* bit length */
  21847. var xbits; /* extra bits */
  21848. var f; /* frequency */
  21849. var overflow = 0; /* number of elements with bit length too large */
  21850. for (bits = 0; bits <= MAX_BITS; bits++) {
  21851. s.bl_count[bits] = 0;
  21852. }
  21853. /* In a first pass, compute the optimal bit lengths (which may
  21854. * overflow in the case of the bit length tree).
  21855. */
  21856. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  21857. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  21858. n = s.heap[h];
  21859. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  21860. if (bits > max_length) {
  21861. bits = max_length;
  21862. overflow++;
  21863. }
  21864. tree[n*2 + 1]/*.Len*/ = bits;
  21865. /* We overwrite tree[n].Dad which is no longer needed */
  21866. if (n > max_code) { continue; } /* not a leaf node */
  21867. s.bl_count[bits]++;
  21868. xbits = 0;
  21869. if (n >= base) {
  21870. xbits = extra[n-base];
  21871. }
  21872. f = tree[n * 2]/*.Freq*/;
  21873. s.opt_len += f * (bits + xbits);
  21874. if (has_stree) {
  21875. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  21876. }
  21877. }
  21878. if (overflow === 0) { return; }
  21879. // Trace((stderr,"\nbit length overflow\n"));
  21880. /* This happens for example on obj2 and pic of the Calgary corpus */
  21881. /* Find the first bit length which could increase: */
  21882. do {
  21883. bits = max_length-1;
  21884. while (s.bl_count[bits] === 0) { bits--; }
  21885. s.bl_count[bits]--; /* move one leaf down the tree */
  21886. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  21887. s.bl_count[max_length]--;
  21888. /* The brother of the overflow item also moves one step up,
  21889. * but this does not affect bl_count[max_length]
  21890. */
  21891. overflow -= 2;
  21892. } while (overflow > 0);
  21893. /* Now recompute all bit lengths, scanning in increasing frequency.
  21894. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  21895. * lengths instead of fixing only the wrong ones. This idea is taken
  21896. * from 'ar' written by Haruhiko Okumura.)
  21897. */
  21898. for (bits = max_length; bits !== 0; bits--) {
  21899. n = s.bl_count[bits];
  21900. while (n !== 0) {
  21901. m = s.heap[--h];
  21902. if (m > max_code) { continue; }
  21903. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  21904. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  21905. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  21906. tree[m*2 + 1]/*.Len*/ = bits;
  21907. }
  21908. n--;
  21909. }
  21910. }
  21911. }
  21912. /* ===========================================================================
  21913. * Generate the codes for a given tree and bit counts (which need not be
  21914. * optimal).
  21915. * IN assertion: the array bl_count contains the bit length statistics for
  21916. * the given tree and the field len is set for all tree elements.
  21917. * OUT assertion: the field code is set for all tree elements of non
  21918. * zero code length.
  21919. */
  21920. function gen_codes(tree, max_code, bl_count)
  21921. // ct_data *tree; /* the tree to decorate */
  21922. // int max_code; /* largest code with non zero frequency */
  21923. // ushf *bl_count; /* number of codes at each bit length */
  21924. {
  21925. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  21926. var code = 0; /* running code value */
  21927. var bits; /* bit index */
  21928. var n; /* code index */
  21929. /* The distribution counts are first used to generate the code values
  21930. * without bit reversal.
  21931. */
  21932. for (bits = 1; bits <= MAX_BITS; bits++) {
  21933. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  21934. }
  21935. /* Check that the bit counts in bl_count are consistent. The last code
  21936. * must be all ones.
  21937. */
  21938. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  21939. // "inconsistent bit counts");
  21940. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  21941. for (n = 0; n <= max_code; n++) {
  21942. var len = tree[n*2 + 1]/*.Len*/;
  21943. if (len === 0) { continue; }
  21944. /* Now reverse the bits */
  21945. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  21946. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  21947. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  21948. }
  21949. }
  21950. /* ===========================================================================
  21951. * Initialize the various 'constant' tables.
  21952. */
  21953. function tr_static_init() {
  21954. var n; /* iterates over tree elements */
  21955. var bits; /* bit counter */
  21956. var length; /* length value */
  21957. var code; /* code value */
  21958. var dist; /* distance index */
  21959. var bl_count = new Array(MAX_BITS+1);
  21960. /* number of codes at each bit length for an optimal tree */
  21961. // do check in _tr_init()
  21962. //if (static_init_done) return;
  21963. /* For some embedded targets, global variables are not initialized: */
  21964. /*#ifdef NO_INIT_GLOBAL_POINTERS
  21965. static_l_desc.static_tree = static_ltree;
  21966. static_l_desc.extra_bits = extra_lbits;
  21967. static_d_desc.static_tree = static_dtree;
  21968. static_d_desc.extra_bits = extra_dbits;
  21969. static_bl_desc.extra_bits = extra_blbits;
  21970. #endif*/
  21971. /* Initialize the mapping length (0..255) -> length code (0..28) */
  21972. length = 0;
  21973. for (code = 0; code < LENGTH_CODES-1; code++) {
  21974. base_length[code] = length;
  21975. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  21976. _length_code[length++] = code;
  21977. }
  21978. }
  21979. //Assert (length == 256, "tr_static_init: length != 256");
  21980. /* Note that the length 255 (match length 258) can be represented
  21981. * in two different ways: code 284 + 5 bits or code 285, so we
  21982. * overwrite length_code[255] to use the best encoding:
  21983. */
  21984. _length_code[length-1] = code;
  21985. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  21986. dist = 0;
  21987. for (code = 0 ; code < 16; code++) {
  21988. base_dist[code] = dist;
  21989. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  21990. _dist_code[dist++] = code;
  21991. }
  21992. }
  21993. //Assert (dist == 256, "tr_static_init: dist != 256");
  21994. dist >>= 7; /* from now on, all distances are divided by 128 */
  21995. for ( ; code < D_CODES; code++) {
  21996. base_dist[code] = dist << 7;
  21997. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  21998. _dist_code[256 + dist++] = code;
  21999. }
  22000. }
  22001. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  22002. /* Construct the codes of the static literal tree */
  22003. for (bits = 0; bits <= MAX_BITS; bits++) {
  22004. bl_count[bits] = 0;
  22005. }
  22006. n = 0;
  22007. while (n <= 143) {
  22008. static_ltree[n*2 + 1]/*.Len*/ = 8;
  22009. n++;
  22010. bl_count[8]++;
  22011. }
  22012. while (n <= 255) {
  22013. static_ltree[n*2 + 1]/*.Len*/ = 9;
  22014. n++;
  22015. bl_count[9]++;
  22016. }
  22017. while (n <= 279) {
  22018. static_ltree[n*2 + 1]/*.Len*/ = 7;
  22019. n++;
  22020. bl_count[7]++;
  22021. }
  22022. while (n <= 287) {
  22023. static_ltree[n*2 + 1]/*.Len*/ = 8;
  22024. n++;
  22025. bl_count[8]++;
  22026. }
  22027. /* Codes 286 and 287 do not exist, but we must include them in the
  22028. * tree construction to get a canonical Huffman tree (longest code
  22029. * all ones)
  22030. */
  22031. gen_codes(static_ltree, L_CODES+1, bl_count);
  22032. /* The static distance tree is trivial: */
  22033. for (n = 0; n < D_CODES; n++) {
  22034. static_dtree[n*2 + 1]/*.Len*/ = 5;
  22035. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  22036. }
  22037. // Now data ready and we can init static trees
  22038. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  22039. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  22040. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  22041. //static_init_done = true;
  22042. }
  22043. /* ===========================================================================
  22044. * Initialize a new block.
  22045. */
  22046. function init_block(s) {
  22047. var n; /* iterates over tree elements */
  22048. /* Initialize the trees. */
  22049. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  22050. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  22051. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  22052. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  22053. s.opt_len = s.static_len = 0;
  22054. s.last_lit = s.matches = 0;
  22055. }
  22056. /* ===========================================================================
  22057. * Flush the bit buffer and align the output on a byte boundary
  22058. */
  22059. function bi_windup(s)
  22060. {
  22061. if (s.bi_valid > 8) {
  22062. put_short(s, s.bi_buf);
  22063. } else if (s.bi_valid > 0) {
  22064. //put_byte(s, (Byte)s->bi_buf);
  22065. s.pending_buf[s.pending++] = s.bi_buf;
  22066. }
  22067. s.bi_buf = 0;
  22068. s.bi_valid = 0;
  22069. }
  22070. /* ===========================================================================
  22071. * Copy a stored block, storing first the length and its
  22072. * one's complement if requested.
  22073. */
  22074. function copy_block(s, buf, len, header)
  22075. //DeflateState *s;
  22076. //charf *buf; /* the input data */
  22077. //unsigned len; /* its length */
  22078. //int header; /* true if block header must be written */
  22079. {
  22080. bi_windup(s); /* align on byte boundary */
  22081. if (header) {
  22082. put_short(s, len);
  22083. put_short(s, ~len);
  22084. }
  22085. // while (len--) {
  22086. // put_byte(s, *buf++);
  22087. // }
  22088. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  22089. s.pending += len;
  22090. }
  22091. /* ===========================================================================
  22092. * Compares to subtrees, using the tree depth as tie breaker when
  22093. * the subtrees have equal frequency. This minimizes the worst case length.
  22094. */
  22095. function smaller(tree, n, m, depth) {
  22096. var _n2 = n*2;
  22097. var _m2 = m*2;
  22098. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  22099. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  22100. }
  22101. /* ===========================================================================
  22102. * Restore the heap property by moving down the tree starting at node k,
  22103. * exchanging a node with the smallest of its two sons if necessary, stopping
  22104. * when the heap property is re-established (each father smaller than its
  22105. * two sons).
  22106. */
  22107. function pqdownheap(s, tree, k)
  22108. // deflate_state *s;
  22109. // ct_data *tree; /* the tree to restore */
  22110. // int k; /* node to move down */
  22111. {
  22112. var v = s.heap[k];
  22113. var j = k << 1; /* left son of k */
  22114. while (j <= s.heap_len) {
  22115. /* Set j to the smallest of the two sons: */
  22116. if (j < s.heap_len &&
  22117. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  22118. j++;
  22119. }
  22120. /* Exit if v is smaller than both sons */
  22121. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  22122. /* Exchange v with the smallest son */
  22123. s.heap[k] = s.heap[j];
  22124. k = j;
  22125. /* And continue down the tree, setting j to the left son of k */
  22126. j <<= 1;
  22127. }
  22128. s.heap[k] = v;
  22129. }
  22130. // inlined manually
  22131. // var SMALLEST = 1;
  22132. /* ===========================================================================
  22133. * Send the block data compressed using the given Huffman trees
  22134. */
  22135. function compress_block(s, ltree, dtree)
  22136. // deflate_state *s;
  22137. // const ct_data *ltree; /* literal tree */
  22138. // const ct_data *dtree; /* distance tree */
  22139. {
  22140. var dist; /* distance of matched string */
  22141. var lc; /* match length or unmatched char (if dist == 0) */
  22142. var lx = 0; /* running index in l_buf */
  22143. var code; /* the code to send */
  22144. var extra; /* number of extra bits to send */
  22145. if (s.last_lit !== 0) {
  22146. do {
  22147. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  22148. lc = s.pending_buf[s.l_buf + lx];
  22149. lx++;
  22150. if (dist === 0) {
  22151. send_code(s, lc, ltree); /* send a literal byte */
  22152. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  22153. } else {
  22154. /* Here, lc is the match length - MIN_MATCH */
  22155. code = _length_code[lc];
  22156. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  22157. extra = extra_lbits[code];
  22158. if (extra !== 0) {
  22159. lc -= base_length[code];
  22160. send_bits(s, lc, extra); /* send the extra length bits */
  22161. }
  22162. dist--; /* dist is now the match distance - 1 */
  22163. code = d_code(dist);
  22164. //Assert (code < D_CODES, "bad d_code");
  22165. send_code(s, code, dtree); /* send the distance code */
  22166. extra = extra_dbits[code];
  22167. if (extra !== 0) {
  22168. dist -= base_dist[code];
  22169. send_bits(s, dist, extra); /* send the extra distance bits */
  22170. }
  22171. } /* literal or match pair ? */
  22172. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  22173. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  22174. // "pendingBuf overflow");
  22175. } while (lx < s.last_lit);
  22176. }
  22177. send_code(s, END_BLOCK, ltree);
  22178. }
  22179. /* ===========================================================================
  22180. * Construct one Huffman tree and assigns the code bit strings and lengths.
  22181. * Update the total bit length for the current block.
  22182. * IN assertion: the field freq is set for all tree elements.
  22183. * OUT assertions: the fields len and code are set to the optimal bit length
  22184. * and corresponding code. The length opt_len is updated; static_len is
  22185. * also updated if stree is not null. The field max_code is set.
  22186. */
  22187. function build_tree(s, desc)
  22188. // deflate_state *s;
  22189. // tree_desc *desc; /* the tree descriptor */
  22190. {
  22191. var tree = desc.dyn_tree;
  22192. var stree = desc.stat_desc.static_tree;
  22193. var has_stree = desc.stat_desc.has_stree;
  22194. var elems = desc.stat_desc.elems;
  22195. var n, m; /* iterate over heap elements */
  22196. var max_code = -1; /* largest code with non zero frequency */
  22197. var node; /* new node being created */
  22198. /* Construct the initial heap, with least frequent element in
  22199. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  22200. * heap[0] is not used.
  22201. */
  22202. s.heap_len = 0;
  22203. s.heap_max = HEAP_SIZE;
  22204. for (n = 0; n < elems; n++) {
  22205. if (tree[n * 2]/*.Freq*/ !== 0) {
  22206. s.heap[++s.heap_len] = max_code = n;
  22207. s.depth[n] = 0;
  22208. } else {
  22209. tree[n*2 + 1]/*.Len*/ = 0;
  22210. }
  22211. }
  22212. /* The pkzip format requires that at least one distance code exists,
  22213. * and that at least one bit should be sent even if there is only one
  22214. * possible code. So to avoid special checks later on we force at least
  22215. * two codes of non zero frequency.
  22216. */
  22217. while (s.heap_len < 2) {
  22218. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  22219. tree[node * 2]/*.Freq*/ = 1;
  22220. s.depth[node] = 0;
  22221. s.opt_len--;
  22222. if (has_stree) {
  22223. s.static_len -= stree[node*2 + 1]/*.Len*/;
  22224. }
  22225. /* node is 0 or 1 so it does not have extra bits */
  22226. }
  22227. desc.max_code = max_code;
  22228. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  22229. * establish sub-heaps of increasing lengths:
  22230. */
  22231. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  22232. /* Construct the Huffman tree by repeatedly combining the least two
  22233. * frequent nodes.
  22234. */
  22235. node = elems; /* next internal node of the tree */
  22236. do {
  22237. //pqremove(s, tree, n); /* n = node of least frequency */
  22238. /*** pqremove ***/
  22239. n = s.heap[1/*SMALLEST*/];
  22240. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  22241. pqdownheap(s, tree, 1/*SMALLEST*/);
  22242. /***/
  22243. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  22244. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  22245. s.heap[--s.heap_max] = m;
  22246. /* Create a new node father of n and m */
  22247. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  22248. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  22249. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  22250. /* and insert the new node in the heap */
  22251. s.heap[1/*SMALLEST*/] = node++;
  22252. pqdownheap(s, tree, 1/*SMALLEST*/);
  22253. } while (s.heap_len >= 2);
  22254. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  22255. /* At this point, the fields freq and dad are set. We can now
  22256. * generate the bit lengths.
  22257. */
  22258. gen_bitlen(s, desc);
  22259. /* The field len is now set, we can generate the bit codes */
  22260. gen_codes(tree, max_code, s.bl_count);
  22261. }
  22262. /* ===========================================================================
  22263. * Scan a literal or distance tree to determine the frequencies of the codes
  22264. * in the bit length tree.
  22265. */
  22266. function scan_tree(s, tree, max_code)
  22267. // deflate_state *s;
  22268. // ct_data *tree; /* the tree to be scanned */
  22269. // int max_code; /* and its largest code of non zero frequency */
  22270. {
  22271. var n; /* iterates over all tree elements */
  22272. var prevlen = -1; /* last emitted length */
  22273. var curlen; /* length of current code */
  22274. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  22275. var count = 0; /* repeat count of the current code */
  22276. var max_count = 7; /* max repeat count */
  22277. var min_count = 4; /* min repeat count */
  22278. if (nextlen === 0) {
  22279. max_count = 138;
  22280. min_count = 3;
  22281. }
  22282. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  22283. for (n = 0; n <= max_code; n++) {
  22284. curlen = nextlen;
  22285. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  22286. if (++count < max_count && curlen === nextlen) {
  22287. continue;
  22288. } else if (count < min_count) {
  22289. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  22290. } else if (curlen !== 0) {
  22291. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  22292. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  22293. } else if (count <= 10) {
  22294. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  22295. } else {
  22296. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  22297. }
  22298. count = 0;
  22299. prevlen = curlen;
  22300. if (nextlen === 0) {
  22301. max_count = 138;
  22302. min_count = 3;
  22303. } else if (curlen === nextlen) {
  22304. max_count = 6;
  22305. min_count = 3;
  22306. } else {
  22307. max_count = 7;
  22308. min_count = 4;
  22309. }
  22310. }
  22311. }
  22312. /* ===========================================================================
  22313. * Send a literal or distance tree in compressed form, using the codes in
  22314. * bl_tree.
  22315. */
  22316. function send_tree(s, tree, max_code)
  22317. // deflate_state *s;
  22318. // ct_data *tree; /* the tree to be scanned */
  22319. // int max_code; /* and its largest code of non zero frequency */
  22320. {
  22321. var n; /* iterates over all tree elements */
  22322. var prevlen = -1; /* last emitted length */
  22323. var curlen; /* length of current code */
  22324. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  22325. var count = 0; /* repeat count of the current code */
  22326. var max_count = 7; /* max repeat count */
  22327. var min_count = 4; /* min repeat count */
  22328. /* tree[max_code+1].Len = -1; */ /* guard already set */
  22329. if (nextlen === 0) {
  22330. max_count = 138;
  22331. min_count = 3;
  22332. }
  22333. for (n = 0; n <= max_code; n++) {
  22334. curlen = nextlen;
  22335. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  22336. if (++count < max_count && curlen === nextlen) {
  22337. continue;
  22338. } else if (count < min_count) {
  22339. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  22340. } else if (curlen !== 0) {
  22341. if (curlen !== prevlen) {
  22342. send_code(s, curlen, s.bl_tree);
  22343. count--;
  22344. }
  22345. //Assert(count >= 3 && count <= 6, " 3_6?");
  22346. send_code(s, REP_3_6, s.bl_tree);
  22347. send_bits(s, count-3, 2);
  22348. } else if (count <= 10) {
  22349. send_code(s, REPZ_3_10, s.bl_tree);
  22350. send_bits(s, count-3, 3);
  22351. } else {
  22352. send_code(s, REPZ_11_138, s.bl_tree);
  22353. send_bits(s, count-11, 7);
  22354. }
  22355. count = 0;
  22356. prevlen = curlen;
  22357. if (nextlen === 0) {
  22358. max_count = 138;
  22359. min_count = 3;
  22360. } else if (curlen === nextlen) {
  22361. max_count = 6;
  22362. min_count = 3;
  22363. } else {
  22364. max_count = 7;
  22365. min_count = 4;
  22366. }
  22367. }
  22368. }
  22369. /* ===========================================================================
  22370. * Construct the Huffman tree for the bit lengths and return the index in
  22371. * bl_order of the last bit length code to send.
  22372. */
  22373. function build_bl_tree(s) {
  22374. var max_blindex; /* index of last bit length code of non zero freq */
  22375. /* Determine the bit length frequencies for literal and distance trees */
  22376. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  22377. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  22378. /* Build the bit length tree: */
  22379. build_tree(s, s.bl_desc);
  22380. /* opt_len now includes the length of the tree representations, except
  22381. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  22382. */
  22383. /* Determine the number of bit length codes to send. The pkzip format
  22384. * requires that at least 4 bit length codes be sent. (appnote.txt says
  22385. * 3 but the actual value used is 4.)
  22386. */
  22387. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  22388. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  22389. break;
  22390. }
  22391. }
  22392. /* Update opt_len to include the bit length tree and counts */
  22393. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  22394. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  22395. // s->opt_len, s->static_len));
  22396. return max_blindex;
  22397. }
  22398. /* ===========================================================================
  22399. * Send the header for a block using dynamic Huffman trees: the counts, the
  22400. * lengths of the bit length codes, the literal tree and the distance tree.
  22401. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  22402. */
  22403. function send_all_trees(s, lcodes, dcodes, blcodes)
  22404. // deflate_state *s;
  22405. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  22406. {
  22407. var rank; /* index in bl_order */
  22408. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  22409. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  22410. // "too many codes");
  22411. //Tracev((stderr, "\nbl counts: "));
  22412. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  22413. send_bits(s, dcodes-1, 5);
  22414. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  22415. for (rank = 0; rank < blcodes; rank++) {
  22416. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  22417. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  22418. }
  22419. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  22420. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  22421. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  22422. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  22423. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  22424. }
  22425. /* ===========================================================================
  22426. * Check if the data type is TEXT or BINARY, using the following algorithm:
  22427. * - TEXT if the two conditions below are satisfied:
  22428. * a) There are no non-portable control characters belonging to the
  22429. * "black list" (0..6, 14..25, 28..31).
  22430. * b) There is at least one printable character belonging to the
  22431. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  22432. * - BINARY otherwise.
  22433. * - The following partially-portable control characters form a
  22434. * "gray list" that is ignored in this detection algorithm:
  22435. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  22436. * IN assertion: the fields Freq of dyn_ltree are set.
  22437. */
  22438. function detect_data_type(s) {
  22439. /* black_mask is the bit mask of black-listed bytes
  22440. * set bits 0..6, 14..25, and 28..31
  22441. * 0xf3ffc07f = binary 11110011111111111100000001111111
  22442. */
  22443. var black_mask = 0xf3ffc07f;
  22444. var n;
  22445. /* Check for non-textual ("black-listed") bytes. */
  22446. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  22447. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  22448. return Z_BINARY;
  22449. }
  22450. }
  22451. /* Check for textual ("white-listed") bytes. */
  22452. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  22453. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  22454. return Z_TEXT;
  22455. }
  22456. for (n = 32; n < LITERALS; n++) {
  22457. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  22458. return Z_TEXT;
  22459. }
  22460. }
  22461. /* There are no "black-listed" or "white-listed" bytes:
  22462. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  22463. */
  22464. return Z_BINARY;
  22465. }
  22466. var static_init_done = false;
  22467. /* ===========================================================================
  22468. * Initialize the tree data structures for a new zlib stream.
  22469. */
  22470. function _tr_init(s)
  22471. {
  22472. if (!static_init_done) {
  22473. tr_static_init();
  22474. static_init_done = true;
  22475. }
  22476. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  22477. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  22478. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  22479. s.bi_buf = 0;
  22480. s.bi_valid = 0;
  22481. /* Initialize the first block of the first file: */
  22482. init_block(s);
  22483. }
  22484. /* ===========================================================================
  22485. * Send a stored block
  22486. */
  22487. function _tr_stored_block(s, buf, stored_len, last)
  22488. //DeflateState *s;
  22489. //charf *buf; /* input block */
  22490. //ulg stored_len; /* length of input block */
  22491. //int last; /* one if this is the last block for a file */
  22492. {
  22493. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  22494. copy_block(s, buf, stored_len, true); /* with header */
  22495. }
  22496. /* ===========================================================================
  22497. * Send one empty static block to give enough lookahead for inflate.
  22498. * This takes 10 bits, of which 7 may remain in the bit buffer.
  22499. */
  22500. function _tr_align(s) {
  22501. send_bits(s, STATIC_TREES<<1, 3);
  22502. send_code(s, END_BLOCK, static_ltree);
  22503. bi_flush(s);
  22504. }
  22505. /* ===========================================================================
  22506. * Determine the best encoding for the current block: dynamic trees, static
  22507. * trees or store, and output the encoded block to the zip file.
  22508. */
  22509. function _tr_flush_block(s, buf, stored_len, last)
  22510. //DeflateState *s;
  22511. //charf *buf; /* input block, or NULL if too old */
  22512. //ulg stored_len; /* length of input block */
  22513. //int last; /* one if this is the last block for a file */
  22514. {
  22515. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  22516. var max_blindex = 0; /* index of last bit length code of non zero freq */
  22517. /* Build the Huffman trees unless a stored block is forced */
  22518. if (s.level > 0) {
  22519. /* Check if the file is binary or text */
  22520. if (s.strm.data_type === Z_UNKNOWN) {
  22521. s.strm.data_type = detect_data_type(s);
  22522. }
  22523. /* Construct the literal and distance trees */
  22524. build_tree(s, s.l_desc);
  22525. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  22526. // s->static_len));
  22527. build_tree(s, s.d_desc);
  22528. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  22529. // s->static_len));
  22530. /* At this point, opt_len and static_len are the total bit lengths of
  22531. * the compressed block data, excluding the tree representations.
  22532. */
  22533. /* Build the bit length tree for the above two trees, and get the index
  22534. * in bl_order of the last bit length code to send.
  22535. */
  22536. max_blindex = build_bl_tree(s);
  22537. /* Determine the best encoding. Compute the block lengths in bytes. */
  22538. opt_lenb = (s.opt_len+3+7) >>> 3;
  22539. static_lenb = (s.static_len+3+7) >>> 3;
  22540. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  22541. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  22542. // s->last_lit));
  22543. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  22544. } else {
  22545. // Assert(buf != (char*)0, "lost buf");
  22546. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  22547. }
  22548. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  22549. /* 4: two words for the lengths */
  22550. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  22551. * Otherwise we can't have processed more than WSIZE input bytes since
  22552. * the last block flush, because compression would have been
  22553. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  22554. * transform a block into a stored block.
  22555. */
  22556. _tr_stored_block(s, buf, stored_len, last);
  22557. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  22558. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  22559. compress_block(s, static_ltree, static_dtree);
  22560. } else {
  22561. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  22562. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  22563. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  22564. }
  22565. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  22566. /* The above check is made mod 2^32, for files larger than 512 MB
  22567. * and uLong implemented on 32 bits.
  22568. */
  22569. init_block(s);
  22570. if (last) {
  22571. bi_windup(s);
  22572. }
  22573. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  22574. // s->compressed_len-7*last));
  22575. }
  22576. /* ===========================================================================
  22577. * Save the match info and tally the frequency counts. Return true if
  22578. * the current block must be flushed.
  22579. */
  22580. function _tr_tally(s, dist, lc)
  22581. // deflate_state *s;
  22582. // unsigned dist; /* distance of matched string */
  22583. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  22584. {
  22585. //var out_length, in_length, dcode;
  22586. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  22587. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  22588. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  22589. s.last_lit++;
  22590. if (dist === 0) {
  22591. /* lc is the unmatched char */
  22592. s.dyn_ltree[lc*2]/*.Freq*/++;
  22593. } else {
  22594. s.matches++;
  22595. /* Here, lc is the match length - MIN_MATCH */
  22596. dist--; /* dist = match distance - 1 */
  22597. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  22598. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  22599. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  22600. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  22601. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  22602. }
  22603. // (!) This block is disabled in zlib defailts,
  22604. // don't enable it for binary compatibility
  22605. //#ifdef TRUNCATE_BLOCK
  22606. // /* Try to guess if it is profitable to stop the current block here */
  22607. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  22608. // /* Compute an upper bound for the compressed length */
  22609. // out_length = s.last_lit*8;
  22610. // in_length = s.strstart - s.block_start;
  22611. //
  22612. // for (dcode = 0; dcode < D_CODES; dcode++) {
  22613. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  22614. // }
  22615. // out_length >>>= 3;
  22616. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  22617. // // s->last_lit, in_length, out_length,
  22618. // // 100L - out_length*100L/in_length));
  22619. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  22620. // return true;
  22621. // }
  22622. // }
  22623. //#endif
  22624. return (s.last_lit === s.lit_bufsize-1);
  22625. /* We avoid equality with lit_bufsize because of wraparound at 64K
  22626. * on 16 bit machines and because stored blocks are restricted to
  22627. * 64K-1 bytes.
  22628. */
  22629. }
  22630. exports._tr_init = _tr_init;
  22631. exports._tr_stored_block = _tr_stored_block;
  22632. exports._tr_flush_block = _tr_flush_block;
  22633. exports._tr_tally = _tr_tally;
  22634. exports._tr_align = _tr_align;
  22635. },{"../utils/common":66}],78:[function(require,module,exports){
  22636. 'use strict';
  22637. function ZStream() {
  22638. /* next input byte */
  22639. this.input = null; // JS specific, because we have no pointers
  22640. this.next_in = 0;
  22641. /* number of bytes available at input */
  22642. this.avail_in = 0;
  22643. /* total number of input bytes read so far */
  22644. this.total_in = 0;
  22645. /* next output byte should be put there */
  22646. this.output = null; // JS specific, because we have no pointers
  22647. this.next_out = 0;
  22648. /* remaining free space at output */
  22649. this.avail_out = 0;
  22650. /* total number of bytes output so far */
  22651. this.total_out = 0;
  22652. /* last error message, NULL if no error */
  22653. this.msg = ''/*Z_NULL*/;
  22654. /* not visible by applications */
  22655. this.state = null;
  22656. /* best guess about the data type: binary or text */
  22657. this.data_type = 2/*Z_UNKNOWN*/;
  22658. /* adler32 value of the uncompressed data */
  22659. this.adler = 0;
  22660. }
  22661. module.exports = ZStream;
  22662. },{}],79:[function(require,module,exports){
  22663. module.exports = function arrayEquals(array) {
  22664. // if the other array is a falsy value, return
  22665. if (!array)
  22666. return false;
  22667. // compare lengths - can save a lot of time
  22668. if (this.length != array.length)
  22669. return false;
  22670. for (var i = 0, l = this.length; i < l; i++) {
  22671. // Check if we have nested arrays
  22672. if (this[i] instanceof Array && array[i] instanceof Array) {
  22673. // recurse into the nested arrays
  22674. if (!arrayEquals.apply(this[i], [array[i]]))
  22675. return false;
  22676. } else if (this[i] != array[i]) {
  22677. // Warning - two different object instances will never be equal:
  22678. // {x:20} != {x:20}
  22679. return false;
  22680. }
  22681. }
  22682. return true;
  22683. }
  22684. },{}],80:[function(require,module,exports){
  22685. exports.Interop = require('./interop');
  22686. },{"./interop":81}],81:[function(require,module,exports){
  22687. var transform = require('./transform');
  22688. var arrayEquals = require('./array-equals');
  22689. function Interop() { }
  22690. module.exports = Interop;
  22691. /**
  22692. * This map holds the most recent Plan A offer/answer SDP that was converted
  22693. * to Plan B, with the SDP type ('offer' or 'answer') as keys and the SDP
  22694. * string as values.
  22695. *
  22696. * @type {{}}
  22697. */
  22698. var cache = {};
  22699. /**
  22700. * This method transforms a Plan A SDP to an equivalent Plan B SDP. A
  22701. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  22702. * application.
  22703. *
  22704. * @param desc
  22705. * @returns {*}
  22706. */
  22707. Interop.prototype.toPlanB = function(desc) {
  22708. //#region Preliminary input validation.
  22709. if (typeof desc !== 'object' || desc === null ||
  22710. typeof desc.sdp !== 'string') {
  22711. console.warn('An empty description was passed as an argument.');
  22712. return desc;
  22713. }
  22714. // Objectify the SDP for easier manipulation.
  22715. var session = transform.parse(desc.sdp);
  22716. // If the SDP contains no media, there's nothing to transform.
  22717. if (typeof session.media === 'undefined' ||
  22718. !Array.isArray(session.media) || session.media.length === 0) {
  22719. console.warn('The description has no media.');
  22720. return desc;
  22721. }
  22722. // Try some heuristics to "make sure" this is a Plan A SDP. Plan B SDP has
  22723. // a video, an audio and a data "channel" at most.
  22724. if (session.media.length <= 3 && session.media.every(function(m) {
  22725. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  22726. })) {
  22727. console.warn('This description does not look like Plan A.');
  22728. return desc;
  22729. }
  22730. //#endregion
  22731. // Plan A SDP is our "precious". Cache it for later use in the Plan B ->
  22732. // Plan A transformation.
  22733. cache[desc.type] = desc.sdp;
  22734. //#region Convert from Plan A to Plan B.
  22735. // We rebuild the session.media array.
  22736. var media = session.media;
  22737. session.media = [];
  22738. // Associative array that maps channel types to channel objects for fast
  22739. // access to channel objects by their type, e.g. channels['audio']->channel
  22740. // obj.
  22741. var channels = {};
  22742. // Used to build the group:BUNDLE value after the channels construction
  22743. // loop.
  22744. var types = [];
  22745. // Implode the Plan A m-lines/tracks into Plan B "channels".
  22746. media.forEach(function(mLine) {
  22747. // rtcp-mux is required in the Plan B SDP.
  22748. if (typeof mLine.rtcpMux !== 'string' ||
  22749. mLine.rtcpMux !== 'rtcp-mux') {
  22750. throw new Error('Cannot convert to Plan B because m-lines ' +
  22751. 'without the rtcp-mux attribute were found.');
  22752. }
  22753. // If we don't have a channel for this mLine.type, then use this mLine
  22754. // as the channel basis.
  22755. if (typeof channels[mLine.type] === 'undefined') {
  22756. channels[mLine.type] = mLine;
  22757. }
  22758. // Add sources to the channel and handle a=msid.
  22759. if (typeof mLine.sources === 'object') {
  22760. Object.keys(mLine.sources).forEach(function(ssrc) {
  22761. // Assign the sources to the channel.
  22762. channels[mLine.type].sources[ssrc] = mLine.sources[ssrc];
  22763. // In Plan B the msid is an SSRC attribute. Also, we don't care
  22764. // about the obsolete label and mslabel attributes.
  22765. channels[mLine.type].sources[ssrc].msid = mLine.msid;
  22766. // NOTE ssrcs in ssrc groups will share msids, as
  22767. // draft-uberti-rtcweb-plan-00 mandates.
  22768. });
  22769. }
  22770. // Add ssrc groups to the channel.
  22771. if (typeof mLine.ssrcGroups !== 'undefined' &&
  22772. Array.isArray(mLine.ssrcGroups)) {
  22773. // Create the ssrcGroups array, if it's not defined.
  22774. if (typeof channel.ssrcGroups === 'undefined' ||
  22775. !Array.isArray(channel.ssrcGroups)) {
  22776. channel.ssrcGroups = [];
  22777. }
  22778. channel.ssrcGroups = channel.ssrcGroups.concat(mLine.ssrcGroups);
  22779. }
  22780. if (channels[mLine.type] === mLine) {
  22781. // Copy ICE related stuff from the principal media line.
  22782. mLine.candidates = media[0].candidates;
  22783. mLine.iceUfrag = media[0].iceUfrag;
  22784. mLine.icePwd = media[0].icePwd;
  22785. mLine.fingerprint = media[0].fingerprint;
  22786. // Plan B mids are in ['audio', 'video', 'data']
  22787. mLine.mid = mLine.type;
  22788. // Plan B doesn't support/need the bundle-only attribute.
  22789. delete mLine.bundleOnly;
  22790. // In Plan B the msid is an SSRC attribute.
  22791. delete mLine.msid;
  22792. // Used to build the group:BUNDLE value after this loop.
  22793. types.push(mLine.type);
  22794. // Add the channel to the new media array.
  22795. session.media.push(mLine);
  22796. }
  22797. });
  22798. // We regenerate the BUNDLE group with the new mids.
  22799. session.groups.every(function(group) {
  22800. if (group.type === 'BUNDLE') {
  22801. group.mids = types.join(' ');
  22802. return false;
  22803. } else {
  22804. return true;
  22805. }
  22806. });
  22807. // msid semantic
  22808. session.msidSemantic = {
  22809. semantic: 'WMS',
  22810. token: '*'
  22811. };
  22812. var resStr = transform.write(session);
  22813. return new RTCSessionDescription({
  22814. type: desc.type,
  22815. sdp: resStr
  22816. });
  22817. //#endregion
  22818. };
  22819. /**
  22820. * This method transforms a Plan B SDP to an equivalent Plan A SDP. A
  22821. * PeerConnection wrapper transforms the SDP to Plan A before passing it to FF.
  22822. *
  22823. * @param desc
  22824. * @returns {*}
  22825. */
  22826. Interop.prototype.toPlanA = function(desc) {
  22827. //#region Preliminary input validation.
  22828. if (typeof desc !== 'object' || desc === null ||
  22829. typeof desc.sdp !== 'string') {
  22830. console.warn('An empty description was passed as an argument.');
  22831. return desc;
  22832. }
  22833. var session = transform.parse(desc.sdp);
  22834. // If the SDP contains no media, there's nothing to transform.
  22835. if (typeof session.media === 'undefined' ||
  22836. !Array.isArray(session.media) || session.media.length === 0) {
  22837. console.warn('The description has no media.');
  22838. return desc;
  22839. }
  22840. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  22841. // a video, an audio and a data "channel" at most.
  22842. if (session.media.length > 3 || !session.media.every(function(m) {
  22843. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  22844. })) {
  22845. console.warn('This description does not look like Plan B.');
  22846. return desc;
  22847. }
  22848. // Make sure this Plan B SDP can be converted to a Plan A SDP.
  22849. var mids = [];
  22850. session.media.forEach(function(m) {
  22851. mids.push(m.mid);
  22852. });
  22853. var hasBundle = false;
  22854. if (typeof session.groups !== 'undefined' &&
  22855. Array.isArray(session.groups)) {
  22856. hasBundle = session.groups.every(function(g) {
  22857. return g.type !== 'BUNDLE' ||
  22858. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  22859. });
  22860. }
  22861. if (!hasBundle) {
  22862. throw new Error("Cannot convert to Plan A because m-lines that are " +
  22863. "not bundled were found.");
  22864. }
  22865. //#endregion
  22866. //#region Convert from Plan B to Plan A.
  22867. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  22868. // rebuild an equivalent Plan A offer/answer.
  22869. //
  22870. // For example, if this is a local answer (in Plan A style) that we convert
  22871. // to Plan B prior to handing it over to the application (the
  22872. // PeerConnection wrapper called us, for instance, after a successful
  22873. // createAnswer), we want to remember the m-line at which we've seen the
  22874. // (local) SSRC. That's because when the application wants to do call the
  22875. // SLD method, forcing us to do the inverse transformation (from Plan B to
  22876. // Plan A), we need to know to which m-line to assign the (local) SSRC. We
  22877. // also need to know all the other m-lines that the original answer had and
  22878. // include them in the transformed answer as well.
  22879. //
  22880. // Another example is if this is a remote offer that we convert to Plan B
  22881. // prior to giving it to the application, we want to remember the mid at
  22882. // which we've seen the (remote) SSRC.
  22883. //
  22884. // In the iteration that follows, we use the cached Plan A (if it exists)
  22885. // to assign mids to ssrcs.
  22886. var cached;
  22887. if (typeof cache[desc.type] !== 'undefined') {
  22888. cached = transform.parse(cache[desc.type]);
  22889. }
  22890. // A helper map that sends mids to m-line objects. We use it later to
  22891. // rebuild the Plan A style session.media array.
  22892. var media = {};
  22893. session.media.forEach(function(channel) {
  22894. if (typeof channel.rtcpMux !== 'string' ||
  22895. channel.rtcpMux !== 'rtcp-mux') {
  22896. throw new Error("Cannot convert to Plan A because m-lines " +
  22897. "without the rtcp-mux attribute were found.");
  22898. }
  22899. // With rtcp-mux and bundle all the channels should have the same ICE
  22900. // stuff.
  22901. var sources = channel.sources;
  22902. var ssrcGroups = channel.ssrcGroups;
  22903. var candidates = channel.candidates;
  22904. var iceUfrag = channel.iceUfrag;
  22905. var icePwd = channel.icePwd;
  22906. var fingerprint = channel.fingerprint;
  22907. var port = channel.port;
  22908. // We'll use the "channel" object as a prototype for each new "mLine"
  22909. // that we create, but first we need to clean it up a bit.
  22910. delete channel.sources;
  22911. delete channel.ssrcGroups;
  22912. delete channel.candidates;
  22913. delete channel.iceUfrag;
  22914. delete channel.icePwd;
  22915. delete channel.fingerprint;
  22916. delete channel.port;
  22917. delete channel.mid;
  22918. // inverted ssrc group map
  22919. var invertedGroups = {};
  22920. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  22921. ssrcGroups.forEach(function (ssrcGroup) {
  22922. // TODO(gp) find out how to receive simulcast with FF. For the
  22923. // time being, hide it.
  22924. if (ssrcGroup.semantics === 'SIM') {
  22925. return;
  22926. }
  22927. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  22928. Array.isArray(ssrcGroup.ssrcs)) {
  22929. ssrcGroup.ssrcs.forEach(function (ssrc) {
  22930. if (typeof invertedGroups[ssrc] === 'undefined') {
  22931. invertedGroups[ssrc] = [];
  22932. }
  22933. invertedGroups[ssrc].push(ssrcGroup);
  22934. });
  22935. }
  22936. });
  22937. }
  22938. // ssrc to m-line index.
  22939. var mLines = {};
  22940. if (typeof sources === 'object') {
  22941. // Explode the Plan B channel sources with one m-line per source.
  22942. Object.keys(sources).forEach(function(ssrc) {
  22943. var mLine;
  22944. if (typeof invertedGroups[ssrc] !== 'undefined' &&
  22945. Array.isArray(invertedGroups[ssrc])) {
  22946. invertedGroups[ssrc].every(function (ssrcGroup) {
  22947. // ssrcGroup.ssrcs *is* an Array, no need to check
  22948. // again here.
  22949. return ssrcGroup.ssrcs.every(function (related) {
  22950. if (typeof mLines[related] === 'object') {
  22951. mLine = mLines[related];
  22952. return false;
  22953. } else {
  22954. return true;
  22955. }
  22956. });
  22957. });
  22958. }
  22959. if (typeof mLine === 'object') {
  22960. // the m-line already exists. Just add the source.
  22961. mLine.sources[ssrc] = sources[ssrc];
  22962. delete sources[ssrc].msid;
  22963. } else {
  22964. // Use the "channel" as a prototype for the "mLine".
  22965. mLine = Object.create(channel);
  22966. mLines[ssrc] = mLine;
  22967. // Assign the msid of the source to the m-line.
  22968. mLine.msid = sources[ssrc].msid;
  22969. delete sources[ssrc].msid;
  22970. // We assign one SSRC per media line.
  22971. mLine.sources = {};
  22972. mLine.sources[ssrc] = sources[ssrc];
  22973. mLine.ssrcGroups = invertedGroups[ssrc];
  22974. // Use the cached Plan A SDP (if it exists) to assign SSRCs to
  22975. // mids.
  22976. if (typeof cached !== 'undefined' &&
  22977. typeof cached.media !== 'undefined' &&
  22978. Array.isArray(cached.media)) {
  22979. cached.media.forEach(function(m) {
  22980. if (typeof m.sources === 'object') {
  22981. Object.keys(m.sources).forEach(function(s) {
  22982. if (s === ssrc) {
  22983. mLine.mid = m.mid;
  22984. }
  22985. });
  22986. }
  22987. });
  22988. }
  22989. if (typeof mLine.mid === 'undefined') {
  22990. // If this is an SSRC that we see for the first time assign
  22991. // it a new mid. This is typically the case when this
  22992. // method is called to transform a remote description for
  22993. // the first time or when there is a new SSRC in the remote
  22994. // description because a new peer has joined the
  22995. // conference. Local SSRCs should have already been added
  22996. // to the map in the toPlanB method.
  22997. //
  22998. // Because FF generates answers in Plan A style, we MUST
  22999. // already have a cached answer with all the local SSRCs
  23000. // mapped to some mLine/mid.
  23001. if (desc.type === 'answer') {
  23002. throw new Error("An unmapped SSRC was found.");
  23003. }
  23004. mLine.mid = [channel.type, '-', ssrc].join('');
  23005. }
  23006. // Include the candidates in the 1st media line.
  23007. mLine.candidates = candidates;
  23008. mLine.iceUfrag = iceUfrag;
  23009. mLine.icePwd = icePwd;
  23010. mLine.fingerprint = fingerprint;
  23011. mLine.port = port;
  23012. media[mLine.mid] = mLine;
  23013. }
  23014. });
  23015. }
  23016. });
  23017. // Rebuild the media array in the right order and add the missing mLines
  23018. // (missing from the Plan B SDP).
  23019. session.media = [];
  23020. mids = []; // reuse
  23021. if (desc.type === 'answer') {
  23022. // The media lines in the answer must match the media lines in the
  23023. // offer. The order is important too. Here we use the cached offer to
  23024. // find the m-lines that are missing (from the converted answer), and
  23025. // use the cached answer to complete the converted answer.
  23026. if (typeof cache['offer'] === 'undefined') {
  23027. throw new Error("An answer is being processed but we couldn't " +
  23028. "find a cached offer.");
  23029. }
  23030. var cachedOffer = transform.parse(cache['offer']);
  23031. if (typeof cachedOffer === 'undefined' ||
  23032. typeof cachedOffer.media === 'undefined' ||
  23033. !Array.isArray(cachedOffer.media)) {
  23034. // FIXME(gp) is this really a problem in the general case?
  23035. throw new Error("The cached offer has no media.");
  23036. }
  23037. cachedOffer.media.forEach(function(mo) {
  23038. var mLine;
  23039. if (typeof media[mo.mid] === 'undefined') {
  23040. // This is probably an m-line containing a remote track only.
  23041. // It MUST exist in the cached answer as a remote track only
  23042. // mLine.
  23043. cached.media.every(function(ma) {
  23044. if (mo.mid == ma.mid) {
  23045. mLine = ma;
  23046. return false;
  23047. } else {
  23048. return true;
  23049. }
  23050. });
  23051. } else {
  23052. mLine = media[mo.mid];
  23053. }
  23054. if (typeof mLine === 'undefined') {
  23055. throw new Error("The cached offer contains an m-line that " +
  23056. "doesn't exist neither in the cached answer nor in " +
  23057. "the converted answer.");
  23058. }
  23059. session.media.push(mLine);
  23060. mids.push(mLine.mid);
  23061. });
  23062. } else {
  23063. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  23064. // under any circumstances. If we are no longer interested in sending a
  23065. // track, we just remove the msid and ssrc attributes and set it to
  23066. // either a=recvonly (as the reofferer, we must use recvonly if the
  23067. // other side was previously sending on the m-section, but we can also
  23068. // leave the possibility open if it wasn't previously in use), or
  23069. // a=inacive.
  23070. if (typeof cached !== 'undefined' &&
  23071. typeof cached.media !== 'undefined' &&
  23072. Array.isArray(cached.media)) {
  23073. cached.media.forEach(function(pm) {
  23074. mids.push(pm.mid);
  23075. if (typeof media[pm.mid] !== 'undefined') {
  23076. session.media.push(media[pm.mid]);
  23077. } else {
  23078. delete pm.msid;
  23079. delete pm.sources;
  23080. delete pm.ssrcGroups;
  23081. pm.direction = 'recvonly';
  23082. session.media.push(pm);
  23083. }
  23084. });
  23085. }
  23086. // Add all the remaining (new) m-lines of the transformed SDP.
  23087. Object.keys(media).forEach(function(mid) {
  23088. if (mids.indexOf(mid) === -1) {
  23089. mids.push(mid);
  23090. session.media.push(media[mid]);
  23091. }
  23092. });
  23093. }
  23094. // We regenerate the BUNDLE group (since we regenerated the mids)
  23095. session.groups.every(function(group) {
  23096. if (group.type === 'BUNDLE') {
  23097. group.mids = mids.join(' ');
  23098. return false;
  23099. } else {
  23100. return true;
  23101. }
  23102. });
  23103. // msid semantic
  23104. session.msidSemantic = {
  23105. semantic: 'WMS',
  23106. token: '*'
  23107. };
  23108. var resStr = transform.write(session);
  23109. // Cache the transformed SDP (Plan A) for later re-use in this function.
  23110. cache[desc.type] = resStr;
  23111. return new RTCSessionDescription({
  23112. type: desc.type,
  23113. sdp: resStr
  23114. });
  23115. //#endregion
  23116. };
  23117. },{"./array-equals":79,"./transform":82}],82:[function(require,module,exports){
  23118. var transform = require('sdp-transform');
  23119. exports.write = function(session, opts) {
  23120. if (typeof session !== 'undefined' &&
  23121. typeof session.media !== 'undefined' &&
  23122. Array.isArray(session.media)) {
  23123. session.media.forEach(function (mLine) {
  23124. // expand sources to ssrcs
  23125. if (typeof mLine.sources !== 'undefined' &&
  23126. Object.keys(mLine.sources).length !== 0) {
  23127. mLine.ssrcs = [];
  23128. Object.keys(mLine.sources).forEach(function (ssrc) {
  23129. var source = mLine.sources[ssrc];
  23130. Object.keys(source).forEach(function (attribute) {
  23131. mLine.ssrcs.push({
  23132. id: ssrc,
  23133. attribute: attribute,
  23134. value: source[attribute]
  23135. });
  23136. });
  23137. });
  23138. delete mLine.sources;
  23139. }
  23140. // join ssrcs in ssrc groups
  23141. if (typeof mLine.ssrcGroups !== 'undefined' &&
  23142. Array.isArray(mLine.ssrcGroups)) {
  23143. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  23144. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  23145. Array.isArray(ssrcGroup.ssrcs)) {
  23146. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  23147. }
  23148. });
  23149. }
  23150. });
  23151. }
  23152. // join group mids
  23153. if (typeof session !== 'undefined' &&
  23154. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  23155. session.groups.forEach(function (g) {
  23156. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  23157. g.mids = g.mids.join(' ');
  23158. }
  23159. });
  23160. }
  23161. return transform.write(session, opts);
  23162. };
  23163. exports.parse = function(sdp) {
  23164. var session = transform.parse(sdp);
  23165. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  23166. Array.isArray(session.media)) {
  23167. session.media.forEach(function (mLine) {
  23168. // group sources attributes by ssrc
  23169. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  23170. mLine.sources = {};
  23171. mLine.ssrcs.forEach(function (ssrc) {
  23172. if (!mLine.sources[ssrc.id])
  23173. mLine.sources[ssrc.id] = {};
  23174. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  23175. });
  23176. delete mLine.ssrcs;
  23177. }
  23178. // split ssrcs in ssrc groups
  23179. if (typeof mLine.ssrcGroups !== 'undefined' &&
  23180. Array.isArray(mLine.ssrcGroups)) {
  23181. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  23182. if (typeof ssrcGroup.ssrcs === 'string') {
  23183. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  23184. }
  23185. });
  23186. }
  23187. });
  23188. }
  23189. // split group mids
  23190. if (typeof session !== 'undefined' &&
  23191. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  23192. session.groups.forEach(function (g) {
  23193. if (typeof g.mids === 'string') {
  23194. g.mids = g.mids.split(' ');
  23195. }
  23196. });
  23197. }
  23198. return session;
  23199. };
  23200. },{"sdp-transform":84}],83:[function(require,module,exports){
  23201. var grammar = module.exports = {
  23202. v: [{
  23203. name: 'version',
  23204. reg: /^(\d*)$/
  23205. }],
  23206. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  23207. // NB: sessionId will be a String in most cases because it is huge
  23208. name: 'origin',
  23209. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  23210. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  23211. format: "%s %s %d %s IP%d %s"
  23212. }],
  23213. // default parsing of these only (though some of these feel outdated)
  23214. s: [{ name: 'name' }],
  23215. i: [{ name: 'description' }],
  23216. u: [{ name: 'uri' }],
  23217. e: [{ name: 'email' }],
  23218. p: [{ name: 'phone' }],
  23219. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  23220. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  23221. //k: [{}], // outdated thing ignored
  23222. t: [{ //t=0 0
  23223. name: 'timing',
  23224. reg: /^(\d*) (\d*)/,
  23225. names: ['start', 'stop'],
  23226. format: "%d %d"
  23227. }],
  23228. c: [{ //c=IN IP4 10.47.197.26
  23229. name: 'connection',
  23230. reg: /^IN IP(\d) (\S*)/,
  23231. names: ['version', 'ip'],
  23232. format: "IN IP%d %s"
  23233. }],
  23234. b: [{ //b=AS:4000
  23235. push: 'bandwidth',
  23236. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  23237. names: ['type', 'limit'],
  23238. format: "%s:%s"
  23239. }],
  23240. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  23241. // NB: special - pushes to session
  23242. // TODO: rtp/fmtp should be filtered by the payloads found here?
  23243. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  23244. names: ['type', 'port', 'protocol', 'payloads'],
  23245. format: "%s %d %s %s"
  23246. }],
  23247. a: [
  23248. { //a=rtpmap:110 opus/48000/2
  23249. push: 'rtp',
  23250. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  23251. names: ['payload', 'codec', 'rate', 'encoding'],
  23252. format: function (o) {
  23253. return (o.encoding) ?
  23254. "rtpmap:%d %s/%s/%s":
  23255. "rtpmap:%d %s/%s";
  23256. }
  23257. },
  23258. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  23259. push: 'fmtp',
  23260. reg: /^fmtp:(\d*) (\S*)/,
  23261. names: ['payload', 'config'],
  23262. format: "fmtp:%d %s"
  23263. },
  23264. { //a=control:streamid=0
  23265. name: 'control',
  23266. reg: /^control:(.*)/,
  23267. format: "control:%s"
  23268. },
  23269. { //a=rtcp:65179 IN IP4 193.84.77.194
  23270. name: 'rtcp',
  23271. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  23272. names: ['port', 'netType', 'ipVer', 'address'],
  23273. format: function (o) {
  23274. return (o.address != null) ?
  23275. "rtcp:%d %s IP%d %s":
  23276. "rtcp:%d";
  23277. }
  23278. },
  23279. { //a=rtcp-fb:98 trr-int 100
  23280. push: 'rtcpFbTrrInt',
  23281. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  23282. names: ['payload', 'value'],
  23283. format: "rtcp-fb:%d trr-int %d"
  23284. },
  23285. { //a=rtcp-fb:98 nack rpsi
  23286. push: 'rtcpFb',
  23287. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  23288. names: ['payload', 'type', 'subtype'],
  23289. format: function (o) {
  23290. return (o.subtype != null) ?
  23291. "rtcp-fb:%s %s %s":
  23292. "rtcp-fb:%s %s";
  23293. }
  23294. },
  23295. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  23296. //a=extmap:1/recvonly URI-gps-string
  23297. push: 'ext',
  23298. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  23299. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  23300. format: function (o) {
  23301. return (o.config != null) ?
  23302. "extmap:%s %s %s":
  23303. "extmap:%s %s";
  23304. }
  23305. },
  23306. {
  23307. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  23308. push: 'crypto',
  23309. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  23310. names: ['id', 'suite', 'config', 'sessionConfig'],
  23311. format: function (o) {
  23312. return (o.sessionConfig != null) ?
  23313. "crypto:%d %s %s %s":
  23314. "crypto:%d %s %s";
  23315. }
  23316. },
  23317. { //a=setup:actpass
  23318. name: 'setup',
  23319. reg: /^setup:(\w*)/,
  23320. format: "setup:%s"
  23321. },
  23322. { //a=mid:1
  23323. name: 'mid',
  23324. reg: /^mid:([^\s]*)/,
  23325. format: "mid:%s"
  23326. },
  23327. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  23328. name: 'msid',
  23329. reg: /^msid:(.*)/,
  23330. format: "msid:%s"
  23331. },
  23332. { //a=ptime:20
  23333. name: 'ptime',
  23334. reg: /^ptime:(\d*)/,
  23335. format: "ptime:%d"
  23336. },
  23337. { //a=maxptime:60
  23338. name: 'maxptime',
  23339. reg: /^maxptime:(\d*)/,
  23340. format: "maxptime:%d"
  23341. },
  23342. { //a=sendrecv
  23343. name: 'direction',
  23344. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  23345. },
  23346. { //a=ice-lite
  23347. name: 'icelite',
  23348. reg: /^(ice-lite)/
  23349. },
  23350. { //a=ice-ufrag:F7gI
  23351. name: 'iceUfrag',
  23352. reg: /^ice-ufrag:(\S*)/,
  23353. format: "ice-ufrag:%s"
  23354. },
  23355. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  23356. name: 'icePwd',
  23357. reg: /^ice-pwd:(\S*)/,
  23358. format: "ice-pwd:%s"
  23359. },
  23360. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  23361. name: 'fingerprint',
  23362. reg: /^fingerprint:(\S*) (\S*)/,
  23363. names: ['type', 'hash'],
  23364. format: "fingerprint:%s %s"
  23365. },
  23366. {
  23367. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  23368. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  23369. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  23370. push:'candidates',
  23371. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  23372. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  23373. format: function (o) {
  23374. var str = "candidate:%s %d %s %d %s %d typ %s";
  23375. // NB: candidate has two optional chunks, so %void middle one if it's missing
  23376. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  23377. if (o.generation != null) {
  23378. str += " generation %d";
  23379. }
  23380. return str;
  23381. }
  23382. },
  23383. { //a=end-of-candidates (keep after the candidates line for readability)
  23384. name: 'endOfCandidates',
  23385. reg: /^(end-of-candidates)/
  23386. },
  23387. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  23388. name: 'remoteCandidates',
  23389. reg: /^remote-candidates:(.*)/,
  23390. format: "remote-candidates:%s"
  23391. },
  23392. { //a=ice-options:google-ice
  23393. name: 'iceOptions',
  23394. reg: /^ice-options:(\S*)/,
  23395. format: "ice-options:%s"
  23396. },
  23397. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  23398. push: "ssrcs",
  23399. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  23400. names: ['id', 'attribute', 'value'],
  23401. format: "ssrc:%d %s:%s"
  23402. },
  23403. { //a=ssrc-group:FEC 1 2
  23404. push: "ssrcGroups",
  23405. reg: /^ssrc-group:(\w*) (.*)/,
  23406. names: ['semantics', 'ssrcs'],
  23407. format: "ssrc-group:%s %s"
  23408. },
  23409. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  23410. name: "msidSemantic",
  23411. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  23412. names: ['semantic', 'token'],
  23413. format: "msid-semantic: %s %s" // space after ":" is not accidental
  23414. },
  23415. { //a=group:BUNDLE audio video
  23416. push: 'groups',
  23417. reg: /^group:(\w*) (.*)/,
  23418. names: ['type', 'mids'],
  23419. format: "group:%s %s"
  23420. },
  23421. { //a=rtcp-mux
  23422. name: 'rtcpMux',
  23423. reg: /^(rtcp-mux)/
  23424. },
  23425. { // any a= that we don't understand is kepts verbatim on media.invalid
  23426. push: 'invalid',
  23427. names: ["value"]
  23428. }
  23429. ]
  23430. };
  23431. // set sensible defaults to avoid polluting the grammar with boring details
  23432. Object.keys(grammar).forEach(function (key) {
  23433. var objs = grammar[key];
  23434. objs.forEach(function (obj) {
  23435. if (!obj.reg) {
  23436. obj.reg = /(.*)/;
  23437. }
  23438. if (!obj.format) {
  23439. obj.format = "%s";
  23440. }
  23441. });
  23442. });
  23443. },{}],84:[function(require,module,exports){
  23444. var parser = require('./parser');
  23445. var writer = require('./writer');
  23446. exports.write = writer;
  23447. exports.parse = parser.parse;
  23448. exports.parseFmtpConfig = parser.parseFmtpConfig;
  23449. exports.parsePayloads = parser.parsePayloads;
  23450. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  23451. },{"./parser":85,"./writer":86}],85:[function(require,module,exports){
  23452. var toIntIfInt = function (v) {
  23453. return String(Number(v)) === v ? Number(v) : v;
  23454. };
  23455. var attachProperties = function (match, location, names, rawName) {
  23456. if (rawName && !names) {
  23457. location[rawName] = toIntIfInt(match[1]);
  23458. }
  23459. else {
  23460. for (var i = 0; i < names.length; i += 1) {
  23461. if (match[i+1] != null) {
  23462. location[names[i]] = toIntIfInt(match[i+1]);
  23463. }
  23464. }
  23465. }
  23466. };
  23467. var parseReg = function (obj, location, content) {
  23468. var needsBlank = obj.name && obj.names;
  23469. if (obj.push && !location[obj.push]) {
  23470. location[obj.push] = [];
  23471. }
  23472. else if (needsBlank && !location[obj.name]) {
  23473. location[obj.name] = {};
  23474. }
  23475. var keyLocation = obj.push ?
  23476. {} : // blank object that will be pushed
  23477. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  23478. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  23479. if (obj.push) {
  23480. location[obj.push].push(keyLocation);
  23481. }
  23482. };
  23483. var grammar = require('./grammar');
  23484. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  23485. exports.parse = function (sdp) {
  23486. var session = {}
  23487. , media = []
  23488. , location = session; // points at where properties go under (one of the above)
  23489. // parse lines we understand
  23490. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  23491. var type = l[0];
  23492. var content = l.slice(2);
  23493. if (type === 'm') {
  23494. media.push({rtp: [], fmtp: []});
  23495. location = media[media.length-1]; // point at latest media line
  23496. }
  23497. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  23498. var obj = grammar[type][j];
  23499. if (obj.reg.test(content)) {
  23500. return parseReg(obj, location, content);
  23501. }
  23502. }
  23503. });
  23504. session.media = media; // link it up
  23505. return session;
  23506. };
  23507. var fmtpReducer = function (acc, expr) {
  23508. var s = expr.split('=');
  23509. if (s.length === 2) {
  23510. acc[s[0]] = toIntIfInt(s[1]);
  23511. }
  23512. return acc;
  23513. };
  23514. exports.parseFmtpConfig = function (str) {
  23515. return str.split(';').reduce(fmtpReducer, {});
  23516. };
  23517. exports.parsePayloads = function (str) {
  23518. return str.split(' ').map(Number);
  23519. };
  23520. exports.parseRemoteCandidates = function (str) {
  23521. var candidates = [];
  23522. var parts = str.split(' ').map(toIntIfInt);
  23523. for (var i = 0; i < parts.length; i += 3) {
  23524. candidates.push({
  23525. component: parts[i],
  23526. ip: parts[i + 1],
  23527. port: parts[i + 2]
  23528. });
  23529. }
  23530. return candidates;
  23531. };
  23532. },{"./grammar":83}],86:[function(require,module,exports){
  23533. var grammar = require('./grammar');
  23534. // customized util.format - discards excess arguments and can void middle ones
  23535. var formatRegExp = /%[sdv%]/g;
  23536. var format = function (formatStr) {
  23537. var i = 1;
  23538. var args = arguments;
  23539. var len = args.length;
  23540. return formatStr.replace(formatRegExp, function (x) {
  23541. if (i >= len) {
  23542. return x; // missing argument
  23543. }
  23544. var arg = args[i];
  23545. i += 1;
  23546. switch (x) {
  23547. case '%%':
  23548. return '%';
  23549. case '%s':
  23550. return String(arg);
  23551. case '%d':
  23552. return Number(arg);
  23553. case '%v':
  23554. return '';
  23555. }
  23556. });
  23557. // NB: we discard excess arguments - they are typically undefined from makeLine
  23558. };
  23559. var makeLine = function (type, obj, location) {
  23560. var str = obj.format instanceof Function ?
  23561. (obj.format(obj.push ? location : location[obj.name])) :
  23562. obj.format;
  23563. var args = [type + '=' + str];
  23564. if (obj.names) {
  23565. for (var i = 0; i < obj.names.length; i += 1) {
  23566. var n = obj.names[i];
  23567. if (obj.name) {
  23568. args.push(location[obj.name][n]);
  23569. }
  23570. else { // for mLine and push attributes
  23571. args.push(location[obj.names[i]]);
  23572. }
  23573. }
  23574. }
  23575. else {
  23576. args.push(location[obj.name]);
  23577. }
  23578. return format.apply(null, args);
  23579. };
  23580. // RFC specified order
  23581. // TODO: extend this with all the rest
  23582. var defaultOuterOrder = [
  23583. 'v', 'o', 's', 'i',
  23584. 'u', 'e', 'p', 'c',
  23585. 'b', 't', 'r', 'z', 'a'
  23586. ];
  23587. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  23588. module.exports = function (session, opts) {
  23589. opts = opts || {};
  23590. // ensure certain properties exist
  23591. if (session.version == null) {
  23592. session.version = 0; // "v=0" must be there (only defined version atm)
  23593. }
  23594. if (session.name == null) {
  23595. session.name = " "; // "s= " must be there if no meaningful name set
  23596. }
  23597. session.media.forEach(function (mLine) {
  23598. if (mLine.payloads == null) {
  23599. mLine.payloads = "";
  23600. }
  23601. });
  23602. var outerOrder = opts.outerOrder || defaultOuterOrder;
  23603. var innerOrder = opts.innerOrder || defaultInnerOrder;
  23604. var sdp = [];
  23605. // loop through outerOrder for matching properties on session
  23606. outerOrder.forEach(function (type) {
  23607. grammar[type].forEach(function (obj) {
  23608. if (obj.name in session && session[obj.name] != null) {
  23609. sdp.push(makeLine(type, obj, session));
  23610. }
  23611. else if (obj.push in session && session[obj.push] != null) {
  23612. session[obj.push].forEach(function (el) {
  23613. sdp.push(makeLine(type, obj, el));
  23614. });
  23615. }
  23616. });
  23617. });
  23618. // then for each media line, follow the innerOrder
  23619. session.media.forEach(function (mLine) {
  23620. sdp.push(makeLine('m', grammar.m[0], mLine));
  23621. innerOrder.forEach(function (type) {
  23622. grammar[type].forEach(function (obj) {
  23623. if (obj.name in mLine && mLine[obj.name] != null) {
  23624. sdp.push(makeLine(type, obj, mLine));
  23625. }
  23626. else if (obj.push in mLine && mLine[obj.push] != null) {
  23627. mLine[obj.push].forEach(function (el) {
  23628. sdp.push(makeLine(type, obj, el));
  23629. });
  23630. }
  23631. });
  23632. });
  23633. });
  23634. return sdp.join('\r\n') + '\r\n';
  23635. };
  23636. },{"./grammar":83}],87:[function(require,module,exports){
  23637. var MediaStreamType = {
  23638. VIDEO_TYPE: "Video",
  23639. AUDIO_TYPE: "Audio"
  23640. };
  23641. module.exports = MediaStreamType;
  23642. },{}],88:[function(require,module,exports){
  23643. var RTCBrowserType = {
  23644. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  23645. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  23646. };
  23647. module.exports = RTCBrowserType;
  23648. },{}],89:[function(require,module,exports){
  23649. var RTCEvents = {
  23650. LASTN_CHANGED: "rtc.lastn_changed",
  23651. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  23652. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  23653. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  23654. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  23655. SIMULCAST_START: "rtc.simlcast_start",
  23656. SIMULCAST_STOP: "rtc.simlcast_stop",
  23657. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  23658. };
  23659. module.exports = RTCEvents;
  23660. },{}],90:[function(require,module,exports){
  23661. var Resolutions = {
  23662. "1080": {
  23663. width: 1920,
  23664. height: 1080,
  23665. order: 7
  23666. },
  23667. "fullhd": {
  23668. width: 1920,
  23669. height: 1080,
  23670. order: 7
  23671. },
  23672. "720": {
  23673. width: 1280,
  23674. height: 720,
  23675. order: 6
  23676. },
  23677. "hd": {
  23678. width: 1280,
  23679. height: 720,
  23680. order: 6
  23681. },
  23682. "960": {
  23683. width: 960,
  23684. height: 720,
  23685. order: 5
  23686. },
  23687. "640": {
  23688. width: 640,
  23689. height: 480,
  23690. order: 4
  23691. },
  23692. "vga": {
  23693. width: 640,
  23694. height: 480,
  23695. order: 4
  23696. },
  23697. "360": {
  23698. width: 640,
  23699. height: 360,
  23700. order: 3
  23701. },
  23702. "320": {
  23703. width: 320,
  23704. height: 240,
  23705. order: 2
  23706. },
  23707. "180": {
  23708. width: 320,
  23709. height: 180,
  23710. order: 1
  23711. }
  23712. };
  23713. module.exports = Resolutions;
  23714. },{}],91:[function(require,module,exports){
  23715. var StreamEventTypes = {
  23716. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  23717. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  23718. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  23719. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  23720. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  23721. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  23722. };
  23723. module.exports = StreamEventTypes;
  23724. },{}],92:[function(require,module,exports){
  23725. var UIEvents = {
  23726. NICKNAME_CHANGED: "UI.nickname_changed",
  23727. SELECTED_ENDPOINT: "UI.selected_endpoint",
  23728. PINNED_ENDPOINT: "UI.pinned_endpoint"
  23729. };
  23730. module.exports = UIEvents;
  23731. },{}],93:[function(require,module,exports){
  23732. var AuthenticationEvents = {
  23733. /**
  23734. * Event callback arguments:
  23735. * function(authenticationEnabled, userIdentity)
  23736. * authenticationEnabled - indicates whether authentication has been enabled
  23737. * in this session
  23738. * userIdentity - if user has been logged in then it contains user name. If
  23739. * contains 'null' or 'undefined' then user is not logged in.
  23740. */
  23741. IDENTITY_UPDATED: "authentication.identity_updated"
  23742. };
  23743. module.exports = AuthenticationEvents;
  23744. },{}],94:[function(require,module,exports){
  23745. var CQEvents = {
  23746. LOCALSTATS_UPDATED: "cq.localstats_updated",
  23747. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  23748. STOP: "cq.stop"
  23749. };
  23750. module.exports = CQEvents;
  23751. },{}],95:[function(require,module,exports){
  23752. var DesktopSharingEventTypes = {
  23753. INIT: "ds.init",
  23754. SWITCHING_DONE: "ds.switching_done",
  23755. NEW_STREAM_CREATED: "ds.new_stream_created"
  23756. };
  23757. module.exports = DesktopSharingEventTypes;
  23758. },{}],96:[function(require,module,exports){
  23759. module.exports = {
  23760. getLanguages : function () {
  23761. var languages = [];
  23762. for(var lang in this)
  23763. {
  23764. if(typeof this[lang] === "string")
  23765. languages.push(this[lang]);
  23766. }
  23767. return languages;
  23768. },
  23769. EN: "en",
  23770. BG: "bg",
  23771. DE: "de",
  23772. TR: "tr"
  23773. }
  23774. },{}],97:[function(require,module,exports){
  23775. var XMPPEvents = {
  23776. CONFERENCE_CERATED: "xmpp.conferenceCreated.jingle",
  23777. CALL_TERMINATED: "xmpp.callterminated.jingle",
  23778. CALL_INCOMING: "xmpp.callincoming.jingle",
  23779. DISPOSE_CONFERENCE: "xmpp.dispoce_confernce",
  23780. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  23781. KICKED: "xmpp.kicked",
  23782. BRIDGE_DOWN: "xmpp.bridge_down",
  23783. USER_ID_CHANGED: "xmpp.user_id_changed",
  23784. CHANGED_STREAMS: "xmpp.changed_streams",
  23785. MUC_JOINED: "xmpp.muc_joined",
  23786. MUC_ENTER: "xmpp.muc_enter",
  23787. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  23788. MUC_LEFT: "xmpp.muc_left",
  23789. MUC_DESTROYED: "xmpp.muc_destroyed",
  23790. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  23791. REMOTE_STATS: "xmpp.remote_stats",
  23792. LOCALROLE_CHANGED: "xmpp.localrole_changed",
  23793. PRESENCE_STATUS: "xmpp.presence_status",
  23794. RESERVATION_ERROR: "xmpp.room_reservation_error",
  23795. SUBJECT_CHANGED: "xmpp.subject_changed",
  23796. MESSAGE_RECEIVED: "xmpp.message_received",
  23797. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  23798. PASSWORD_REQUIRED: "xmpp.password_required",
  23799. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  23800. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  23801. ETHERPAD: "xmpp.etherpad",
  23802. DEVICE_AVAILABLE: "xmpp.device_available"
  23803. };
  23804. module.exports = XMPPEvents;
  23805. },{}],98:[function(require,module,exports){
  23806. // Copyright Joyent, Inc. and other Node contributors.
  23807. //
  23808. // Permission is hereby granted, free of charge, to any person obtaining a
  23809. // copy of this software and associated documentation files (the
  23810. // "Software"), to deal in the Software without restriction, including
  23811. // without limitation the rights to use, copy, modify, merge, publish,
  23812. // distribute, sublicense, and/or sell copies of the Software, and to permit
  23813. // persons to whom the Software is furnished to do so, subject to the
  23814. // following conditions:
  23815. //
  23816. // The above copyright notice and this permission notice shall be included
  23817. // in all copies or substantial portions of the Software.
  23818. //
  23819. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  23820. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23821. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  23822. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  23823. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  23824. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  23825. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  23826. function EventEmitter() {
  23827. this._events = this._events || {};
  23828. this._maxListeners = this._maxListeners || undefined;
  23829. }
  23830. module.exports = EventEmitter;
  23831. // Backwards-compat with node 0.10.x
  23832. EventEmitter.EventEmitter = EventEmitter;
  23833. EventEmitter.prototype._events = undefined;
  23834. EventEmitter.prototype._maxListeners = undefined;
  23835. // By default EventEmitters will print a warning if more than 10 listeners are
  23836. // added to it. This is a useful default which helps finding memory leaks.
  23837. EventEmitter.defaultMaxListeners = 10;
  23838. // Obviously not all Emitters should be limited to 10. This function allows
  23839. // that to be increased. Set to zero for unlimited.
  23840. EventEmitter.prototype.setMaxListeners = function(n) {
  23841. if (!isNumber(n) || n < 0 || isNaN(n))
  23842. throw TypeError('n must be a positive number');
  23843. this._maxListeners = n;
  23844. return this;
  23845. };
  23846. EventEmitter.prototype.emit = function(type) {
  23847. var er, handler, len, args, i, listeners;
  23848. if (!this._events)
  23849. this._events = {};
  23850. // If there is no 'error' event listener then throw.
  23851. if (type === 'error') {
  23852. if (!this._events.error ||
  23853. (isObject(this._events.error) && !this._events.error.length)) {
  23854. er = arguments[1];
  23855. if (er instanceof Error) {
  23856. throw er; // Unhandled 'error' event
  23857. }
  23858. throw TypeError('Uncaught, unspecified "error" event.');
  23859. }
  23860. }
  23861. handler = this._events[type];
  23862. if (isUndefined(handler))
  23863. return false;
  23864. if (isFunction(handler)) {
  23865. switch (arguments.length) {
  23866. // fast cases
  23867. case 1:
  23868. handler.call(this);
  23869. break;
  23870. case 2:
  23871. handler.call(this, arguments[1]);
  23872. break;
  23873. case 3:
  23874. handler.call(this, arguments[1], arguments[2]);
  23875. break;
  23876. // slower
  23877. default:
  23878. len = arguments.length;
  23879. args = new Array(len - 1);
  23880. for (i = 1; i < len; i++)
  23881. args[i - 1] = arguments[i];
  23882. handler.apply(this, args);
  23883. }
  23884. } else if (isObject(handler)) {
  23885. len = arguments.length;
  23886. args = new Array(len - 1);
  23887. for (i = 1; i < len; i++)
  23888. args[i - 1] = arguments[i];
  23889. listeners = handler.slice();
  23890. len = listeners.length;
  23891. for (i = 0; i < len; i++)
  23892. listeners[i].apply(this, args);
  23893. }
  23894. return true;
  23895. };
  23896. EventEmitter.prototype.addListener = function(type, listener) {
  23897. var m;
  23898. if (!isFunction(listener))
  23899. throw TypeError('listener must be a function');
  23900. if (!this._events)
  23901. this._events = {};
  23902. // To avoid recursion in the case that type === "newListener"! Before
  23903. // adding it to the listeners, first emit "newListener".
  23904. if (this._events.newListener)
  23905. this.emit('newListener', type,
  23906. isFunction(listener.listener) ?
  23907. listener.listener : listener);
  23908. if (!this._events[type])
  23909. // Optimize the case of one listener. Don't need the extra array object.
  23910. this._events[type] = listener;
  23911. else if (isObject(this._events[type]))
  23912. // If we've already got an array, just append.
  23913. this._events[type].push(listener);
  23914. else
  23915. // Adding the second element, need to change to array.
  23916. this._events[type] = [this._events[type], listener];
  23917. // Check for listener leak
  23918. if (isObject(this._events[type]) && !this._events[type].warned) {
  23919. var m;
  23920. if (!isUndefined(this._maxListeners)) {
  23921. m = this._maxListeners;
  23922. } else {
  23923. m = EventEmitter.defaultMaxListeners;
  23924. }
  23925. if (m && m > 0 && this._events[type].length > m) {
  23926. this._events[type].warned = true;
  23927. console.error('(node) warning: possible EventEmitter memory ' +
  23928. 'leak detected. %d listeners added. ' +
  23929. 'Use emitter.setMaxListeners() to increase limit.',
  23930. this._events[type].length);
  23931. if (typeof console.trace === 'function') {
  23932. // not supported in IE 10
  23933. console.trace();
  23934. }
  23935. }
  23936. }
  23937. return this;
  23938. };
  23939. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  23940. EventEmitter.prototype.once = function(type, listener) {
  23941. if (!isFunction(listener))
  23942. throw TypeError('listener must be a function');
  23943. var fired = false;
  23944. function g() {
  23945. this.removeListener(type, g);
  23946. if (!fired) {
  23947. fired = true;
  23948. listener.apply(this, arguments);
  23949. }
  23950. }
  23951. g.listener = listener;
  23952. this.on(type, g);
  23953. return this;
  23954. };
  23955. // emits a 'removeListener' event iff the listener was removed
  23956. EventEmitter.prototype.removeListener = function(type, listener) {
  23957. var list, position, length, i;
  23958. if (!isFunction(listener))
  23959. throw TypeError('listener must be a function');
  23960. if (!this._events || !this._events[type])
  23961. return this;
  23962. list = this._events[type];
  23963. length = list.length;
  23964. position = -1;
  23965. if (list === listener ||
  23966. (isFunction(list.listener) && list.listener === listener)) {
  23967. delete this._events[type];
  23968. if (this._events.removeListener)
  23969. this.emit('removeListener', type, listener);
  23970. } else if (isObject(list)) {
  23971. for (i = length; i-- > 0;) {
  23972. if (list[i] === listener ||
  23973. (list[i].listener && list[i].listener === listener)) {
  23974. position = i;
  23975. break;
  23976. }
  23977. }
  23978. if (position < 0)
  23979. return this;
  23980. if (list.length === 1) {
  23981. list.length = 0;
  23982. delete this._events[type];
  23983. } else {
  23984. list.splice(position, 1);
  23985. }
  23986. if (this._events.removeListener)
  23987. this.emit('removeListener', type, listener);
  23988. }
  23989. return this;
  23990. };
  23991. EventEmitter.prototype.removeAllListeners = function(type) {
  23992. var key, listeners;
  23993. if (!this._events)
  23994. return this;
  23995. // not listening for removeListener, no need to emit
  23996. if (!this._events.removeListener) {
  23997. if (arguments.length === 0)
  23998. this._events = {};
  23999. else if (this._events[type])
  24000. delete this._events[type];
  24001. return this;
  24002. }
  24003. // emit removeListener for all listeners on all events
  24004. if (arguments.length === 0) {
  24005. for (key in this._events) {
  24006. if (key === 'removeListener') continue;
  24007. this.removeAllListeners(key);
  24008. }
  24009. this.removeAllListeners('removeListener');
  24010. this._events = {};
  24011. return this;
  24012. }
  24013. listeners = this._events[type];
  24014. if (isFunction(listeners)) {
  24015. this.removeListener(type, listeners);
  24016. } else {
  24017. // LIFO order
  24018. while (listeners.length)
  24019. this.removeListener(type, listeners[listeners.length - 1]);
  24020. }
  24021. delete this._events[type];
  24022. return this;
  24023. };
  24024. EventEmitter.prototype.listeners = function(type) {
  24025. var ret;
  24026. if (!this._events || !this._events[type])
  24027. ret = [];
  24028. else if (isFunction(this._events[type]))
  24029. ret = [this._events[type]];
  24030. else
  24031. ret = this._events[type].slice();
  24032. return ret;
  24033. };
  24034. EventEmitter.listenerCount = function(emitter, type) {
  24035. var ret;
  24036. if (!emitter._events || !emitter._events[type])
  24037. ret = 0;
  24038. else if (isFunction(emitter._events[type]))
  24039. ret = 1;
  24040. else
  24041. ret = emitter._events[type].length;
  24042. return ret;
  24043. };
  24044. function isFunction(arg) {
  24045. return typeof arg === 'function';
  24046. }
  24047. function isNumber(arg) {
  24048. return typeof arg === 'number';
  24049. }
  24050. function isObject(arg) {
  24051. return typeof arg === 'object' && arg !== null;
  24052. }
  24053. function isUndefined(arg) {
  24054. return arg === void 0;
  24055. }
  24056. },{}]},{},[1])(1)
  24057. });